dsh-team-bots 0.2.395 → 0.2.460

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 (72) hide show
  1. package/package.json +4 -1
  2. package/scripts/doctor.mjs +14 -3
  3. package/src/api.js +30 -3
  4. package/src/config.js +108 -0
  5. package/src/db-migrations.js +24 -0
  6. package/src/db.js +5 -0
  7. package/src/feishu/channel.js +702 -0
  8. package/src/feishu/commands.js +20 -0
  9. package/src/feishu/format.js +56 -0
  10. package/src/feishu/index.js +19 -0
  11. package/src/feishu/store.js +205 -0
  12. package/src/http.js +11 -5
  13. package/src/service.js +7 -0
  14. package/src/services/bots.js +42 -0
  15. package/src/services/chat.js +19 -10
  16. package/src/services/core.js +153 -8
  17. package/src/services/external-trigger-schema.js +61 -0
  18. package/src/services/feishu.js +181 -0
  19. package/src/services/github-source.js +157 -0
  20. package/src/services/memory.js +122 -34
  21. package/src/services/projects.js +2 -0
  22. package/src/services/reason-codes.js +63 -0
  23. package/src/services/review-watchdog.js +30 -8
  24. package/src/services/run-finish.js +33 -9
  25. package/src/services/runs.js +48 -7
  26. package/src/services/runtime/context-window.js +53 -0
  27. package/src/services/runtime/prompt.js +165 -139
  28. package/src/services/runtime/sandbox-policy.js +65 -0
  29. package/src/services/runtime/session-continuity.js +38 -0
  30. package/src/services/runtime/session.js +148 -4
  31. package/src/services/scheduler.js +9 -2
  32. package/src/services/system.js +51 -3
  33. package/src/services/task-dispatch.js +43 -4
  34. package/src/services/task-notify.js +13 -8
  35. package/src/services/tasks.js +12 -4
  36. package/src/services/wechat-trigger-schema.js +62 -0
  37. package/src/services/wechat.js +129 -19
  38. package/src/services/write-scopes.js +38 -0
  39. package/src/tools.js +13 -3
  40. package/src/wechat/channel.js +130 -26
  41. package/src/wechat/commands.js +13 -1
  42. package/src/wechat/store.js +69 -18
  43. package/ui/app.js +8 -3
  44. package/ui/i18n/en/chat.js +1 -0
  45. package/ui/i18n/en/nav.js +5 -0
  46. package/ui/i18n/en/settings.js +25 -5
  47. package/ui/i18n/en/tasks.js +12 -0
  48. package/ui/i18n/en/wechat.js +25 -3
  49. package/ui/i18n/zh/chat.js +1 -0
  50. package/ui/i18n/zh/nav.js +5 -0
  51. package/ui/i18n/zh/settings.js +25 -5
  52. package/ui/i18n/zh/tasks.js +12 -0
  53. package/ui/i18n/zh/wechat.js +25 -3
  54. package/ui/modules/api.js +23 -1
  55. package/ui/modules/cards.js +15 -0
  56. package/ui/modules/chat.js +43 -2
  57. package/ui/modules/dom-morph.js +14 -7
  58. package/ui/modules/events-board.js +73 -23
  59. package/ui/modules/events-click.js +16 -0
  60. package/ui/modules/file-preview.js +89 -0
  61. package/ui/modules/global-pages.js +138 -10
  62. package/ui/modules/modal-forms.js +8 -9
  63. package/ui/modules/modal-layer.js +2 -0
  64. package/ui/modules/settings.js +51 -9
  65. package/ui/modules/state.js +2 -0
  66. package/ui/modules/tasks.js +20 -0
  67. package/ui/modules/util.js +39 -0
  68. package/ui/styles/base.css +13 -13
  69. package/ui/styles/chat-cards.css +28 -0
  70. package/ui/styles/frame.css +27 -3
  71. package/ui/styles/global-config.css +28 -3
  72. package/ui/styles/surfaces.css +2 -0
@@ -9,6 +9,22 @@ import { badRequest, conflict, forbidden, notFound } from '../errors.js'
9
9
  import { maskSecrets } from '../secrets.js'
10
10
  import { id, jsonParse, nowIso, redactSecrets, text, sanitizeFilename } from '../util.js'
11
11
 
12
+ // 记忆上限(DSHBOTS-339):bot/project 作用域 active 记忆硬顶 MEMORY_CAP 条;触顶后新增被拒,
13
+ // 须先整理到 MEMORY_COMPACT_TO 条以内才恢复放行(滞回,避免在阈值附近反复开关)。team 作用域不限。
14
+ export const MEMORY_CAP = 64
15
+ export const MEMORY_COMPACT_TO = 33
16
+ // 单条记忆篇幅上限(owner 补充):content 不得超过 256 字。
17
+ export const MEMORY_MAX_CHARS = 256
18
+
19
+ // 记忆审查专用模型(可选):provider 与 model 都非空才启用,否则 null(沿用 Bot
20
+ // 主模型)。手法同读图代理的 visionProxyTarget——配置对见 config.js 的
21
+ // memoryReviewProvider/memoryReviewModel(DSH_TEAM_MEMORY_REVIEW_PROVIDER/_MODEL)。
22
+ export function memoryReviewModelTarget(config) {
23
+ const provider = String(config?.memoryReviewProvider ?? '').trim()
24
+ const model = String(config?.memoryReviewModel ?? '').trim()
25
+ return provider && model ? { provider, model } : null
26
+ }
27
+
12
28
  // 记忆审查输出:模型返回 JSON 数组,形如 [{scope, topic, content, confidence}]。
13
29
  export function parseMemoryReview(output) {
14
30
  const raw = String(output ?? '').trim()
@@ -90,31 +106,31 @@ export const memoryMethods = {
90
106
  },
91
107
  learnFromTask(project, bot, task, output, runId) {
92
108
  if (!output || output.trim().length < 40) return
93
- const content = maskSecrets(redactSecrets(`${task.title}:${output.trim().slice(0, 900)}`), this.secretEntries())
109
+ // 自动沉淀按篇幅预算截断,保证落库单条 ≤ MEMORY_MAX_CHARS 字。
110
+ const content = maskSecrets(redactSecrets(`${task.title}:${output.trim().slice(0, 900)}`), this.secretEntries()).slice(0, MEMORY_MAX_CHARS)
94
111
  const source = `run:${runId}`
95
112
  const existing = this.store.get("SELECT id FROM memories WHERE source = ? AND scope_type = 'bot' AND scope_id = ?", source, bot.id)
96
113
  if (existing) return
97
- this.createMemory({
98
- scopeType: 'bot',
99
- scopeId: bot.id,
100
- topic: `任务 ${project.key}-${task.number}`,
101
- content,
102
- source,
103
- confidence: 0.7,
104
- createdBy: `bot:${bot.id}`,
105
- actor: { type: 'bot', id: bot.id },
106
- })
114
+ // 自动沉淀是尽力而为:触顶(或任何写入失败)只 warn 丢弃,不得炸任务交付 run。
115
+ const settle = (scopeType, scopeId, topic, confidence) => {
116
+ try {
117
+ this.createMemory({
118
+ scopeType,
119
+ scopeId,
120
+ topic,
121
+ content,
122
+ source,
123
+ confidence,
124
+ createdBy: `bot:${bot.id}`,
125
+ actor: { type: 'bot', id: bot.id },
126
+ })
127
+ } catch (error ) {
128
+ this.logger.warn?.('dsh-team: 任务记忆沉淀被拒(%s/%s):%s', scopeType, scopeId, error?.message ?? error)
129
+ }
130
+ }
131
+ settle('bot', bot.id, `任务 ${project.key}-${task.number}`, 0.7)
107
132
  if (project.owner_bot_id === bot.id) {
108
- this.createMemory({
109
- scopeType: 'project',
110
- scopeId: project.id,
111
- topic: `${project.key}-${task.number} 交付记录`,
112
- content,
113
- source,
114
- confidence: 0.6,
115
- createdBy: `bot:${bot.id}`,
116
- actor: { type: 'bot', id: bot.id },
117
- })
133
+ settle('project', project.id, `${project.key}-${task.number} 交付记录`, 0.6)
118
134
  }
119
135
  },
120
136
 
@@ -135,13 +151,17 @@ export const memoryMethods = {
135
151
  sourceRunId,
136
152
  )
137
153
  if (active) return active.id
154
+ // 审查模型覆盖:配置了专用模型对时随运行下发(runs.model_* 三列既有通道,
155
+ // startRun 的 modelOverrideFor 消费);未配置为 NULL,沿用 Bot 主模型。
156
+ const target = memoryReviewModelTarget(this.config)
138
157
  const reviewRunId = id('run')
139
158
  const createdAt = nowIso()
140
159
  this.store.run(
141
160
  `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
142
- attempt, idempotency_key, queued_at)
143
- VALUES (?, ?, ?, NULL, 'memory_review', 'read', 'memory_review', ?, 'queued', 1, ?, ?)`,
144
- reviewRunId, project.id, bot.id, sourceRunId, `memory_review:${sourceRunId}`, createdAt,
161
+ attempt, idempotency_key, model_provider, model_model, queued_at)
162
+ VALUES (?, ?, ?, NULL, 'memory_review', 'read', 'memory_review', ?, 'queued', 1, ?, ?, ?, ?)`,
163
+ reviewRunId, project.id, bot.id, sourceRunId, `memory_review:${sourceRunId}`,
164
+ target?.provider ?? null, target?.model ?? null, createdAt,
145
165
  )
146
166
  this.store.run(
147
167
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
@@ -178,7 +198,8 @@ export const memoryMethods = {
178
198
  for (const item of items) {
179
199
  const scopeType = ['bot', 'project', 'team'].includes(item.scope) ? item.scope : 'bot'
180
200
  const scopeId = scopeType === 'bot' ? bot.id : scopeType === 'project' ? project.id : 'team'
181
- const content = maskSecrets(redactSecrets(text(item.content, 8000)), this.secretEntries())
201
+ // 审查产出同样按篇幅预算截断,避免超长条目被写入咽喉拒绝而整条丢失。
202
+ const content = maskSecrets(redactSecrets(text(item.content, 8000)), this.secretEntries()).slice(0, MEMORY_MAX_CHARS)
182
203
  if (!content) continue
183
204
  const dedupeKey = `${scopeType}|${scopeId}|${source}|${content}`
184
205
  if (seen.has(dedupeKey)) {
@@ -245,11 +266,55 @@ export const memoryMethods = {
245
266
  const row = this.store.get("SELECT id FROM projects WHERE owner_bot_id = ? LIMIT 1", botId)
246
267
  return Boolean(row)
247
268
  },
269
+
270
+ // ── 记忆上限治理(DSHBOTS-339)──
271
+ // bot/project 作用域 active 行硬顶 MEMORY_CAP;触顶后新增被拒并置滞回标志
272
+ // memory_full:<scope_type>:<scope_id>,整理到 MEMORY_COMPACT_TO 条以内才清标志放行。
273
+ // team 作用域不参与计数。计数走 memories_scope_idx(scope_type, scope_id, status)。
274
+ memoryActiveCount(scopeType, scopeId) {
275
+ return Number(this.store.get(
276
+ 'SELECT COUNT(*) AS count FROM memories WHERE scope_type = ? AND scope_id = ? AND status = ?',
277
+ scopeType, scopeId, 'active',
278
+ )?.count ?? 0)
279
+ },
280
+ memoryCapacityMessage(scopeType, scopeId, count) {
281
+ const label = scopeType === 'bot' ? `Bot(${scopeId})` : `项目(${scopeId})`
282
+ return `${label}记忆已达 ${count}/${MEMORY_CAP} 条上限,新增被拒绝;请先去废弃(team_memory_cleanup 清理已闭环任务或过时主题)、去冗(同主题用 team_memory_write 覆盖写)、融合(合并相近条目),整理到 ≤${MEMORY_COMPACT_TO} 条后再新增。`
283
+ },
284
+ assertMemoryCapacity(scopeType, scopeId) {
285
+ if (scopeType !== 'bot' && scopeType !== 'project') return
286
+ const count = this.memoryActiveCount(scopeType, scopeId)
287
+ const flagKey = `memory_full:${scopeType}:${scopeId}`
288
+ if (count >= MEMORY_CAP) {
289
+ this.store.setSetting(flagKey, '1')
290
+ throw conflict(this.memoryCapacityMessage(scopeType, scopeId, count))
291
+ }
292
+ if (this.store.setting(flagKey) === null) return
293
+ if (count > MEMORY_COMPACT_TO) throw conflict(this.memoryCapacityMessage(scopeType, scopeId, count))
294
+ this.store.run('DELETE FROM settings WHERE key = ?', flagKey)
295
+ },
296
+
297
+ // 项目再开容量闸(DSHBOTS-342):归档把 active+pending 一并冻为 frozen,再开统一解回 active,
298
+ // 冻结条数若已超 MEMORY_CAP,解回即破顶。此时整笔再开拒绝(项目保持归档),
299
+ // 先按 memoryCapacityMessage 指引整理(归档态可逐条 deleteMemory)再重开。
300
+ assertProjectReopenCapacity(scopeId, wouldBeActive) {
301
+ if (wouldBeActive <= MEMORY_CAP) return
302
+ throw conflict(this.memoryCapacityMessage('project', scopeId, wouldBeActive))
303
+ },
304
+
305
+ // 单条记忆篇幅上限:content 超过 MEMORY_MAX_CHARS 字即拒绝,防止单条挤占召回预算。
306
+ assertMemoryLength(content) {
307
+ if (content.length > MEMORY_MAX_CHARS) {
308
+ throw badRequest(`记忆内容不能超过 ${MEMORY_MAX_CHARS} 字(当前 ${content.length} 字),请精简后重试`)
309
+ }
310
+ },
311
+
248
312
  createMemory({ scopeType, scopeId, topic, content, source = '', confidence = 1, createdBy = 'system', actor = null, status = 'active', sourceRefs = [] }) {
249
313
  const cleanScope = ['bot', 'project', 'team'].includes(scopeType) ? scopeType : null
250
314
  if (!cleanScope) throw badRequest('记忆作用域无效')
251
315
  const cleanContent = redactSecrets(text(content, 8000))
252
316
  if (!cleanContent) throw badRequest('记忆内容不能为空')
317
+ this.assertMemoryLength(cleanContent)
253
318
  const writeActor = actor ?? { type: createdBy.split(':')[0] || 'system', id: createdBy.split(':').slice(1).join(':') || 'system' }
254
319
  this.assertMemoryWriteScope(cleanScope, scopeId, writeActor)
255
320
  if (cleanScope === 'bot') {
@@ -260,6 +325,7 @@ export const memoryMethods = {
260
325
  const project = this.projectRow(scopeId)
261
326
  if (project.status !== 'active') throw conflict('项目已归档,记忆已冻结')
262
327
  }
328
+ this.assertMemoryCapacity(cleanScope, scopeId)
263
329
  const memoryId = id('mem')
264
330
  const createdAt = nowIso()
265
331
  const cleanStatus = status === 'pending' ? 'pending' : 'active'
@@ -289,6 +355,8 @@ export const memoryMethods = {
289
355
  const memory = this.store.get('SELECT * FROM memories WHERE id = ?', memoryId)
290
356
  if (!memory) throw notFound('记忆不存在')
291
357
  if (memory.status !== 'pending') throw conflict('只有待审记忆可以批准')
358
+ // 审批会把 pending 提成 active,同样受上限约束:active 已满时拒绝。
359
+ this.assertMemoryCapacity(memory.scope_type, memory.scope_id)
292
360
  const now = nowIso()
293
361
  this.store.run(
294
362
  "UPDATE memories SET status = 'active', approved_by = ?, revision = revision + 1, updated_at = ? WHERE id = ?",
@@ -391,7 +459,10 @@ export const memoryMethods = {
391
459
  async updateMemory(memoryId, patch) {
392
460
  const memory = this.store.get('SELECT * FROM memories WHERE id = ?', memoryId)
393
461
  if (!memory) throw notFound('记忆不存在')
394
- const content = redactSecrets(text(patch.content ?? memory.content, 8000))
462
+ // 篇幅闸只约束本次实际变更的 content:存量超长条目仅改 topic 时不得被误拦(DSHBOTS-342)。
463
+ const contentChanged = patch.content != null
464
+ const content = contentChanged ? redactSecrets(text(patch.content, 8000)) : memory.content
465
+ if (contentChanged) this.assertMemoryLength(content)
395
466
  const topic = text(patch.topic ?? memory.topic, 120)
396
467
  this.store.run(
397
468
  'UPDATE memories SET topic = ?, content = ?, updated_at = ? WHERE id = ?',
@@ -488,6 +559,7 @@ export const memoryMethods = {
488
559
  }
489
560
  const content = redactSecrets(text(input.content, 8000))
490
561
  if (!content) throw badRequest('记忆内容不能为空')
562
+ this.assertMemoryLength(content)
491
563
  const now = nowIso()
492
564
  this.store.run(
493
565
  'UPDATE memories SET content = ?, source = ?, revision = revision + 1, updated_at = ? WHERE id = ?',
@@ -503,7 +575,9 @@ export const memoryMethods = {
503
575
  },
504
576
 
505
577
  // 批量清理:按过期口径把 active 记忆终态化(archived,检索即不再回灌)。
506
- // 口径两选一(可并用):task=已闭环卡(done/canceled)的过程记录主题,topics=点名主题。
578
+ // 口径:task=已闭环卡(done/canceled)的过程记录主题,topics=点名主题,
579
+ // before=updated_at 严格早于该 ISO 时间戳的全部 active 条目(存量收敛的批量判据)。
580
+ // before 与 topics/task 可组合,按 AND 交集收窄;三者全缺即拒绝(不做「全清」缺省)。
507
581
  // 逐条 memory_events 留痕 + 一笔 memory.cleanup 审计列出被清条目。
508
582
  memoryCleanupFromBot(sessionId, input) {
509
583
  const ownerCtx = this.ownerContextFor(sessionId)
@@ -522,12 +596,26 @@ export const memoryMethods = {
522
596
  taskTopics = [`任务 ${taskLabel}`, `${taskLabel} 交付记录`]
523
597
  }
524
598
  const wanted = [...new Set([...topics, ...taskTopics])]
525
- if (!wanted.length) throw badRequest('cleanup 需要 topics 或 task 至少一项')
526
- const placeholders = wanted.map(() => '?').join(', ')
527
- const rows = this.store.all(
528
- `SELECT * FROM memories WHERE scope_type = ? AND scope_id = ? AND status = 'active' AND topic IN (${placeholders})`,
529
- scopeType, scopeId, ...wanted,
530
- )
599
+ let before = null
600
+ if (input.before !== undefined && input.before !== null) {
601
+ before = String(input.before).trim()
602
+ if (!Number.isFinite(Date.parse(before))) {
603
+ throw badRequest('before 必须是有效的 ISO 时间戳(例如 2026-01-01T00:00:00.000Z)')
604
+ }
605
+ }
606
+ if (!wanted.length && !before) throw badRequest('cleanup 需要 topics、task 或 before 至少一项')
607
+ const clauses = ['scope_type = ?', 'scope_id = ?', "status = 'active'"]
608
+ const params = [scopeType, scopeId]
609
+ if (before) {
610
+ // julianday 归一化时间戳格式,避免字符串比较把等值瞬间误判为「早于」。
611
+ clauses.push('julianday(updated_at) < julianday(?)')
612
+ params.push(before)
613
+ }
614
+ if (wanted.length) {
615
+ clauses.push(`topic IN (${wanted.map(() => '?').join(', ')})`)
616
+ params.push(...wanted)
617
+ }
618
+ const rows = this.store.all(`SELECT * FROM memories WHERE ${clauses.join(' AND ')}`, ...params)
531
619
  const now = nowIso()
532
620
  const cleaned = []
533
621
  this.store.transaction(() => {
@@ -539,7 +627,7 @@ export const memoryMethods = {
539
627
  )
540
628
  cleaned.push({ id: row.id, topic: row.topic })
541
629
  }
542
- this.audit(actor, 'memory.cleanup', 'memory', `${scopeType}:${scopeId}`, { scope: scopeType, task: taskLabel, cleaned })
630
+ this.audit(actor, 'memory.cleanup', 'memory', `${scopeType}:${scopeId}`, { scope: scopeType, task: taskLabel, before, cleaned })
543
631
  })
544
632
  return { cleaned, archived: cleaned.length, missed: wanted.filter(topic => !cleaned.some(item => item.topic === topic)) }
545
633
  },
@@ -402,11 +402,13 @@ export const projectsMethods = {
402
402
  }
403
403
  // 再开与归档对称:归档时冻结的项目记忆解回 active,逐条留 memory_events 审计。
404
404
  // 已知不对称(接受):冻结前 active/pending 一并冻为 frozen,再开统一解回 active,pending 记忆直接生效。
405
+ // 容量闸(DSHBOTS-342):解回后 active 不得超 MEMORY_CAP,否则整笔再开拒绝(事务回滚,项目保持归档)。
405
406
  if (updates.status === 'active' && project.status === 'archived') {
406
407
  const frozen = this.store.all(
407
408
  "SELECT id FROM memories WHERE scope_type = 'project' AND scope_id = ? AND status = 'frozen'",
408
409
  projectId,
409
410
  )
411
+ this.assertProjectReopenCapacity(projectId, frozen.length + this.memoryActiveCount('project', projectId))
410
412
  for (const memory of frozen) {
411
413
  this.store.run("UPDATE memories SET status = 'active', updated_at = ? WHERE id = ?", nowIso(), memory.id)
412
414
  this.store.run(
@@ -0,0 +1,63 @@
1
+ // src/services/reason-codes.js —— run_events 事件类型注册表(B10/DSHBOTS-337)。
2
+ // 吸收原型 core/reasons.ts「结构化原因码注册表」的口径,按 team 现实收窄:
3
+ // run_events.type 本就是结构化码(34 类,可过滤、可断言),message 是站点语境的
4
+ // 人类细节(同码不同站点的措辞天然不同,如 queued 有 10 种触发语境)——原型
5
+ // 「码→唯一文案」的第二层在这里会与 type 列形成双真值,不引入。
6
+ // 本注册表的职责:①type 全集的单一登记面(域归属 + 双语规范释义,术语表锚点);
7
+ // ②「新事件必须登记」的守门依据(tests/reason-codes.test.ts 扫描全部 type 字面量
8
+ // ⊆ 本表,新闸门/新事件落码时必须先来登记)。
9
+ //
10
+ // 动态 type(非字面量,如 run.kind 直写)不在静态扫描范围,登记仍需人工核对本表。
11
+
12
+ export const RUN_EVENT_DOMAINS = ['dispatch', 'run', 'review', 'memory', 'notify', 'ops']
13
+
14
+ export const RUN_EVENT_TYPES = {
15
+ queued: { domain: 'dispatch', zh: '运行入队', en: 'Run queued' },
16
+ board_resume: { domain: 'dispatch', zh: '看板拖入执行中', en: 'Resumed via board drag' },
17
+ board_pause: { domain: 'dispatch', zh: '任务移出执行中', en: 'Paused via board' },
18
+ task_blocked_dep: { domain: 'dispatch', zh: '依赖未完结,暂缓领取', en: 'Blocked by unfinished dependencies' },
19
+ task_deadline: { domain: 'dispatch', zh: '整卡死线已到,拒绝启动新施工运行', en: 'Card deadline reached; new build runs refused' },
20
+ task_left_in_progress: { domain: 'dispatch', zh: '任务离开执行中', en: 'Task left in-progress' },
21
+ force_blocked: { domain: 'dispatch', zh: '总监强制受阻,运行中止', en: 'Force-blocked by director' },
22
+ stale_superseded: { domain: 'dispatch', zh: '任务已结束,排队运行被清理', en: 'Stale queued run superseded' },
23
+ canceled: { domain: 'run', zh: '运行已取消', en: 'Run canceled' },
24
+ human_slot: { domain: 'dispatch', zh: '借人的消息保底槽放行', en: 'Admitted via human reserve slot' },
25
+ run_parallel: { domain: 'dispatch', zh: '写范围不重叠,并行放行', en: 'Parallel admission via disjoint write scopes' },
26
+ plan_retry: { domain: 'dispatch', zh: '限流重试到期,派生新运行', en: 'Rate-limit retry due; derived run spawned' },
27
+ quota_wait: { domain: 'dispatch', zh: '额度耗尽,排队等待恢复', en: 'Quota exhausted; waiting for reset' },
28
+ quota_fallback: { domain: 'dispatch', zh: '额度耗尽,走备用模型', en: 'Quota exhausted; switched to fallback model' },
29
+ quota_exhausted: { domain: 'run', zh: '额度耗尽入账', en: 'Quota exhaustion recorded' },
30
+ model_fallback: { domain: 'run', zh: '主模型不可用,切换备用模型', en: 'Primary model unavailable; fallback applied' },
31
+ review_fallback: { domain: 'review', zh: '委派核验未产出可用结论,回退', en: 'Delegated review returned nothing usable; fallback' },
32
+ reviewed: { domain: 'review', zh: '记忆审查完成', en: 'Memory review completed' },
33
+ started: { domain: 'run', zh: '运行启动', en: 'Run started' },
34
+ recovered: { domain: 'run', zh: '宿主重启重排队恢复', en: 'Recovered after host restart' },
35
+ sandbox_mode: { domain: 'run', zh: '文件沙箱档位应用', en: 'File sandbox mode applied' },
36
+ config_snapshot: { domain: 'run', zh: '治理配置版本快照', en: 'Governance config snapshot' },
37
+ steered: { domain: 'run', zh: '评论/提示直通注入运行', en: 'Steered into running session' },
38
+ reply_delivered: { domain: 'run', zh: '回信已注入发送方会话', en: 'Reply steered to sender session' },
39
+ attention_answered: { domain: 'notify', zh: '负责人已回答结构化提问', en: 'Owner answered the structured question' },
40
+ notified: { domain: 'notify', zh: '任务提醒已注入', en: 'Task reminder injected' },
41
+ partner_notice: { domain: 'notify', zh: '伙伴提醒记账', en: 'Partner notice recorded' },
42
+ card_changed: { domain: 'notify', zh: '卡面变更修正提示已注入', en: 'Card amendment injected' },
43
+ scopes_updated: { domain: 'run', zh: '写范围修改同步快照', en: 'Write-scope snapshot refreshed' },
44
+ artifacts_skipped: { domain: 'ops', zh: '产物记录跳过', en: 'Artifact recording skipped' },
45
+ artifacts_ignore_failed: { domain: 'ops', zh: '忽略过滤不可用', en: 'gitignore filter unavailable' },
46
+ read_audit_dup: { domain: 'ops', zh: '工作区指纹与已告警记录相同,不重复点名', en: 'Workspace fingerprint unchanged; no re-alert' },
47
+ read_audit_attributed: { domain: 'ops', zh: '工作区变化已归因到并发写运行', en: 'Workspace change attributed to a concurrent write run' },
48
+ code_hygiene_alert: { domain: 'ops', zh: '代码卫生告警(超行数判定线)', en: 'Code hygiene alert (file over the line limit)' },
49
+ rollover_summary_ready: { domain: 'memory', zh: '交接摘要已就绪', en: 'Handoff summary ready' },
50
+ rollover_summary_failed: { domain: 'memory', zh: '交接摘要未生成', en: 'Handoff summary failed' },
51
+ session_compact_done: { domain: 'memory', zh: '会话总结压缩完成', en: 'Session summary compaction finished' },
52
+ session_compact_failed: { domain: 'memory', zh: '会话总结压缩未生成', en: 'Session summary compaction failed' },
53
+ session_compact_fold: { domain: 'memory', zh: '宿主历史折叠完成', en: 'Host history range folded' },
54
+ session_compact_fold_skipped: { domain: 'memory', zh: '宿主无压缩服务,保持仅总结轮', en: 'Host compaction unavailable; summary turn only' },
55
+ session_compact_fold_failed: { domain: 'memory', zh: '宿主历史折叠未执行', en: 'Host history fold not performed' },
56
+ }
57
+
58
+ // 规范释义(术语表锚点):按域给 zh/en;未知码回退原码展示(不抛错)。
59
+ export function runEventTypeLabel(type, locale = 'zh') {
60
+ const entry = RUN_EVENT_TYPES[type]
61
+ if (!entry) return String(type)
62
+ return locale === 'en' ? entry.en : entry.zh
63
+ }
@@ -13,7 +13,7 @@
13
13
  import { execFileSync } from 'node:child_process'
14
14
  import { existsSync } from 'node:fs'
15
15
  import { join } from 'node:path'
16
- import { bool, effectiveReviewIdleMinutes, REVIEW_AUTO_CLOSE_KEY, REVIEW_ESCALATE_KEY, REVIEW_ESCALATE_RANGE } from '../config.js'
16
+ import { effectiveReviewIdleMinutes, REVIEW_AUTO_CLOSE_KEY, REVIEW_ESCALATE_KEY, REVIEW_ESCALATE_RANGE } from '../config.js'
17
17
  import { messageLocale, systemAlertLabel } from './locale.js'
18
18
 
19
19
  // 单卡去重/判定表(settings 键,JSON map):{ taskId: { tier, verdict, basis, at, action? } }。
@@ -117,9 +117,17 @@ export function effectiveReviewEscalateMultiple(getSetting) {
117
117
  return Number.isFinite(raw) && raw >= min && raw <= max ? raw : min
118
118
  }
119
119
 
120
- // 自动收口总开关:默认开(程序化收口是本卡产品目标),0 = 关闭自动 accept/return 只提醒。
120
+ // 自动收口三态(B3/DSHBOTS-326 observe 干跑档):'0' 关(只提醒,不判定留痕)、
121
+ // 'observe' 干跑(判定 + task_events 留痕,不收口——新自动化的安全上线路径:人回看
122
+ // 观察记录确认无误后再切开)、'1' 开(判定 + 程序化收口)。canary=小范围生效,
123
+ // observe=完全不生效,两档语义不同。
124
+ export function reviewAutoCloseMode(service) {
125
+ const value = String(service.store.setting(REVIEW_AUTO_CLOSE_KEY, '1') ?? '1')
126
+ return value === 'observe' ? 'observe' : value === '0' ? 'off' : 'on'
127
+ }
128
+
121
129
  export function reviewAutoCloseEnabled(service) {
122
- return bool(service.store.setting(REVIEW_AUTO_CLOSE_KEY, '1'), true)
130
+ return reviewAutoCloseMode(service) === 'on'
123
131
  }
124
132
 
125
133
  const alertedTier = (value) => {
@@ -190,6 +198,8 @@ export function runReviewWatchdog(service) {
190
198
  const { minutes } = effectiveReviewIdleMinutes(service.config, key => service.store.setting(key))
191
199
  const escalateMultiple = effectiveReviewEscalateMultiple(key => service.store.setting(key))
192
200
  const autoCloseEnabled = reviewAutoCloseEnabled(service)
201
+ const observeMode = reviewAutoCloseMode(service) === 'observe'
202
+ const observed = []
193
203
  const rows = service.store.all(`
194
204
  SELECT t.id, t.project_id, t.updated_at, t.assignee_bot_id, p.key AS project_key, t.number,
195
205
  t.review_target,
@@ -208,7 +218,7 @@ export function runReviewWatchdog(service) {
208
218
  // 回收即落库(H5):卡离开 in_review 的摘除不依赖后续是否有卡触发提醒。
209
219
  if (recovered.length > 0) persist()
210
220
  if (minutes <= 0) {
211
- return { skipped: 'disabled', alerted: [], escalated: [], recovered }
221
+ return { skipped: 'disabled', alerted: [], escalated: [], recovered, observed: [] }
212
222
  }
213
223
  const alerted = []
214
224
  const escalated = []
@@ -226,17 +236,29 @@ export function runReviewWatchdog(service) {
226
236
  // 的卡先按一档提醒,跨档升级由下一轮扫描完成,避免一口气连发两档消息。
227
237
  const fireTier = prevTier === 0 ? 1 : tier
228
238
  const judgment = judgeCard(service, row)
229
- const actionable = autoCloseEnabled
230
- && (judgment.verdict === 'A' || (judgment.verdict === 'B' && row.assignee_bot_id))
239
+ const closeEligible = judgment.verdict === 'A' || (judgment.verdict === 'B' && row.assignee_bot_id)
240
+ const actionable = autoCloseEnabled && closeEligible
241
+ // observe 干跑(B3/DSHBOTS-326):本会收口的判定只留痕不执行——task_events 记
242
+ // would 动作与依据,任务详情时间线可回看;卡状态不变、applyReview 不调用。
243
+ const observable = observeMode && closeEligible
231
244
  const entry = { tier: fireTier, verdict: judgment.verdict, basis: judgment.basis, at: new Date().toISOString() }
232
- if (actionable) entry.action = judgment.verdict === 'A' ? 'accept' : 'return'
245
+ if (actionable || observable) entry.action = judgment.verdict === 'A' ? 'accept' : 'return'
233
246
  map[row.id] = entry
234
247
  persist()
235
248
  const label = `${row.project_key}-${row.number}`
236
249
  const idleMinutes = Math.floor(idleMs / 60_000)
250
+ if (observable) {
251
+ const would = judgment.verdict === 'A' ? 'accept' : 'return'
252
+ service.addTaskEvent(row.id, 'review_watchdog_observe', SYSTEM_ACTOR, {
253
+ verdict: judgment.verdict, would, basis: judgment.basis, tier: fireTier,
254
+ })
255
+ observed.push({ id: row.id, label, verdict: judgment.verdict, would })
256
+ }
237
257
  if (actionable) {
238
258
  autoClose(service, row, judgment, fireTier)
239
259
  } else {
260
+ // C(或开关关闭/observe 干跑):仅提醒;滞留达阈值×倍数升级语气二次催办(H2)。
261
+ // observe 模式的 A/B 卡同样走提醒(干跑不能把催办也干掉),另加判定留痕事件。
240
262
  // C(或开关关闭):仅提醒;滞留达阈值×倍数升级语气二次催办(H2)。
241
263
  // 前缀按 locale 落库(DSHBOTS-228):缺省英文 [SYSTEM ALERT],中文环境【系统指令】。
242
264
  const alertPrefix = systemAlertLabel(messageLocale(service.config, key => service.store.setting(key), service.runtime?.ctx?.get?.('loader')))
@@ -262,7 +284,7 @@ export function runReviewWatchdog(service) {
262
284
  service.logger?.warn?.('review watchdog card %s failed: %s', row.id, cardError?.message ?? cardError)
263
285
  }
264
286
  }
265
- return { alerted, escalated, recovered }
287
+ return { alerted, escalated, recovered, observed }
266
288
  } catch (error ) {
267
289
  service.logger?.warn?.('review watchdog failed: %s', error?.message ?? error)
268
290
  return { alerted: [], escalated: [], recovered: [], error: String(error?.message ?? error) }
@@ -250,6 +250,30 @@ export const runFinishMethods = {
250
250
  status === 'succeeded' && cleanOutput ? 'session_compact_done' : 'session_compact_failed',
251
251
  status === 'succeeded' && cleanOutput ? '会话总结压缩完成,留原会话继续' : `会话总结压缩未生成:${error?.message ?? '模型未返回文本'}`,
252
252
  )
253
+ // 宿主历史折叠(单轮上下文治理 P1):总结轮入史后把旧区间真正折叠掉(compactNow),
254
+ // 会话前缀才实际缩小;不await收尾(折叠自带幂等锁与忙碌让路),结果按事件留痕。
255
+ // 降级路径:宿主无 compaction 缝隙时保持仅总结轮(skipped 留痕可见,不静默);
256
+ // 可选调用兼容测试 StubRuntime(无该方法时静默跳过折叠)。
257
+ void Promise.resolve(this.runtime?.compactHostSessionHistory?.(run.session_id))
258
+ .then(outcome => {
259
+ if (!outcome) return
260
+ if (outcome.unavailable) {
261
+ this.insertRunEvent(runId, 'session_compact_fold_skipped', '宿主未提供 compaction 服务,本窗口保持仅总结轮')
262
+ } else if (outcome.folded) {
263
+ this.insertRunEvent(
264
+ runId,
265
+ 'session_compact_fold',
266
+ `宿主历史折叠完成:收拢 ${outcome.shadowedItems ?? '?'} 条区间、约 ${outcome.shadowedTokens ?? '?'} token`,
267
+ )
268
+ } else {
269
+ this.insertRunEvent(
270
+ runId,
271
+ 'session_compact_fold_failed',
272
+ `宿主历史折叠未执行(${outcome.reason}${outcome.message ? `:${outcome.message}` : ''})`,
273
+ )
274
+ }
275
+ })
276
+ .catch(err => this.logger?.warn?.('session_compact 折叠收尾异常: %s', err?.message ?? err))
253
277
  if (this.rate[run.project_id]) delete this.rate[run.project_id]
254
278
  return
255
279
  }
@@ -522,17 +546,17 @@ export const runFinishMethods = {
522
546
  if (run.project_id && this.rate[run.project_id]) delete this.rate[run.project_id]
523
547
  },
524
548
 
525
- // 微信直达对话回程(DSHBOTS-208/258):trigger_type='wechat' 的运行(项目群聊直达、
526
- // 项目外 director 专属工作区 solo 直达)结束时,把 bot 回复(或失败提示)推回微信管理员,出站走通道既有合批/重试治理;
527
- // 只推微信触发的运行,工作台群聊回复不受影响。推送失败不阻塞收尾主流程。
549
+ // 通道直达对话回程(DSHBOTS-208/258/329):trigger_type='wechat'/'feishu' 的运行
550
+ // (项目群聊直达、项目外 director 专属工作区 solo 直达)结束时,把 bot 回复(或失败提示)
551
+ // 推回来源通道管理员,出站走通道既有合批/重试治理;只推通道触发的运行,工作台群聊回复不受影响。
528
552
  // 排版(头部标记/分隔线)集中在 wechat/format.js 的 chatReply(DSHBOTS-211)。
553
+ // DSHBOTS-326:出站经 channelNotify 扇出到各已启用通道(微信/飞书),单通道失败只留痕不阻断另一通道。
554
+ // DSHBOTS-329:飞书触发运行同款回程——推回飞书管理员,目标会话由飞书通道的
555
+ // store.reply_message_id 锚点决定(卡②入站时落锚,见 src/feishu/channel.ts 的 saveReplyMessageId)。
529
556
  notifyWechatChat(bot, run, body, failed = false) {
530
- if (run?.trigger_type !== 'wechat' || !this.wechat) return
531
- try {
532
- this.wechat.notify(chatReply(bot?.name ?? 'Bot', body, failed))
533
- } catch (error ) {
534
- this.logger.warn?.('dsh-team: 微信直达回复推送失败: %s', error?.message ?? error)
535
- }
557
+ const trigger = run?.trigger_type
558
+ if (trigger !== 'wechat' && trigger !== 'feishu') return
559
+ this.channelNotify?.(chatReply(bot?.name ?? 'Bot', body, failed))
536
560
  },
537
561
 
538
562
  // ── Bot 群聊回复 mention 唤醒(DSHBOTS-252)────────────────────────────
@@ -13,7 +13,7 @@ import { deliveryPlan, replyDeliveryPrompt } from '../botmsg.js'
13
13
  import { id, jsonParse, nowIso, sha256, text } from '../util.js'
14
14
  import { readWriteScopes, writeScopePathsOverlap } from './write-scopes.js'
15
15
  import { isProviderUnavailableCode } from './model-fallback.js'
16
- import { effectiveSandbox } from './runtime/prompt.js'
16
+ import { effectiveSandbox, PROMPT_SEGMENT_DEFAULTS, parsePromptOverrides } from './runtime/prompt.js'
17
17
  import { ensureAttentionSchema, parseAttention } from './attention-schema.js'
18
18
 
19
19
  // 合批窗口与上限默认值(DSHBOTS-231/287,DSHBOTS-290 随语义回补从 scheduler.ts 迁来):
@@ -22,6 +22,15 @@ import { ensureAttentionSchema, parseAttention } from './attention-schema.js'
22
22
  const COALESCE_MAX_MESSAGES_DEFAULT = 5
23
23
  const COALESCE_WINDOW_MS_DEFAULT = 30_000
24
24
 
25
+ /**
26
+ * origin→trigger_type 映射(DSHBOTS-329):通道来源的直达运行打来源通道标记
27
+ * ('wechat' 微信 / 'feishu' 飞书),运行收尾据此把回复推回该通道管理员;
28
+ * 普通 UI 消息(origin 空)与未映射的值都落 'mention',不推任何通道。
29
+ */
30
+ export function originTriggerType(origin) {
31
+ return origin === 'wechat' || origin === 'feishu' ? origin : 'mention'
32
+ }
33
+
25
34
  // ── 只读运行工作区审计归因(DSHBOTS-94)─────────────────────────────────
26
35
  // 指纹行形如 " M dir/file"(前两字符状态位 + 空格 + 路径);重命名 "R old -> new"
27
36
  // 的新旧路径都算被触碰。带引号的 quoted 路径不解析(与产物清单同一口径,跳过)。
@@ -200,9 +209,9 @@ export const runsMethods = {
200
209
  return runId
201
210
  }
202
211
  const spec = item.kind === 'chat'
203
- ? { projectId: item.projectId, mode: 'read', trigger: item.origin === 'wechat' ? 'wechat' : 'mention', idem: `chat:${item.messageId}:${bot.id}` }
212
+ ? { projectId: item.projectId, mode: 'read', trigger: originTriggerType(item.origin), idem: `chat:${item.messageId}:${bot.id}` }
204
213
  : item.kind === 'solo_chat'
205
- ? { projectId: null, mode: 'write', trigger: item.triggerType === 'wechat' ? 'wechat' : 'mention', idem: `solo_chat:${item.messageId}` }
214
+ ? { projectId: null, mode: 'write', trigger: originTriggerType(item.triggerType), idem: `solo_chat:${item.messageId}` }
206
215
  : item.kind === 'dm'
207
216
  ? { projectId: item.projectId, mode: 'read', trigger: 'dm', idem: `dm:${item.messageId}` }
208
217
  : { projectId: item.projectId, mode: 'read', trigger: 'dm_reply', idem: `dm_reply:${item.messageId}` }
@@ -481,7 +490,11 @@ export const runsMethods = {
481
490
  this.store.run(
482
491
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
483
492
  id('evt'), runId, 'queued',
484
- triggerType === 'wechat' ? '微信消息触发(项目外单聊直达)' : '单聊消息触发',
493
+ triggerType === 'wechat'
494
+ ? '微信消息触发(项目外单聊直达)'
495
+ : triggerType === 'feishu'
496
+ ? '飞书消息触发(项目外单聊直达)'
497
+ : '单聊消息触发',
485
498
  createdAt,
486
499
  )
487
500
  return runId
@@ -502,8 +515,9 @@ export const runsMethods = {
502
515
  }
503
516
  const runId = id('run')
504
517
  const createdAt = nowIso()
505
- // 微信直达(DSHBOTS-208):trigger_type 记 'wechat',运行收尾据此把 bot 回复推回微信管理员。
506
- const triggerType = origin === 'wechat' ? 'wechat' : 'mention'
518
+ // 通道直达(DSHBOTS-208/329):trigger_type 记来源通道('wechat'/'feishu'),
519
+ // 运行收尾据此把 bot 回复推回该通道管理员;普通群聊消息保持 'mention' 不推。
520
+ const triggerType = originTriggerType(origin)
507
521
  try {
508
522
  this.store.run(
509
523
  `INSERT INTO runs(id, project_id, bot_id, kind, mode, trigger_type, trigger_ref, status,
@@ -522,7 +536,13 @@ export const runsMethods = {
522
536
  }
523
537
  this.store.run(
524
538
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
525
- id('evt'), runId, 'queued', triggerType === 'wechat' ? '微信群聊消息触发(直达)' : '群聊消息触发', createdAt,
539
+ id('evt'), runId, 'queued',
540
+ triggerType === 'wechat'
541
+ ? '微信群聊消息触发(直达)'
542
+ : triggerType === 'feishu'
543
+ ? '飞书群聊消息触发(直达)'
544
+ : '群聊消息触发',
545
+ createdAt,
526
546
  )
527
547
  return runId
528
548
  },
@@ -628,6 +648,27 @@ export const runsMethods = {
628
648
  const run = this.runRow(runId)
629
649
  const bot = this.store.get('SELECT * FROM bots WHERE id = ?', run.bot_id)
630
650
  const project = run.project_id ? this.store.get('SELECT * FROM projects WHERE id = ?', run.project_id) : null
651
+ // 配置版本快照(C2/DSHBOTS-334):任务运行独占会话(D-308),本运行的治理配置即
652
+ // 派发时刻的生效值——bot 角色版本(bots.current_revision)+ 可编辑提示词段覆盖正文
653
+ // (缺省段记 null,默认文本随发版可追溯)+ 实际下发模型(runs 行三列,D-25)。
654
+ // 回答「这张卡按哪版规则跑的」;只记账不闸门(ADR §3:变更不撤销在途,恢复前复核
655
+ // 由派发链闸门承担)。只对 kind='task' 记:消息族运行共用控制面冻结会话(D-91),
656
+ // 生效文本是冻结时的旧值,快照「当时 settings」反而误导。
657
+ if (run.kind === 'task') {
658
+ const overrides = parsePromptOverrides(this.store.setting('prompt_overrides', ''))
659
+ const segments = Object.fromEntries(
660
+ Object.keys(PROMPT_SEGMENT_DEFAULTS).map(key => [key, overrides?.[key]?.text ?? null]),
661
+ )
662
+ const model = run.model_provider
663
+ ? { provider: run.model_provider, model: run.model_model, effort: run.model_effort ?? null }
664
+ : { provider: bot.provider, model: bot.model, effort: bot.effort ?? null }
665
+ this.store.run(
666
+ 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
667
+ id('evt'), run.id, 'config_snapshot',
668
+ JSON.stringify({ bot_revision: Number(bot.current_revision) || 0, model, prompt_segment_overrides: segments }),
669
+ nowIso(),
670
+ )
671
+ }
631
672
  try {
632
673
  const task = run.task_id ? this.taskRow(run.task_id) : null
633
674
  // DSHBOTS-112:vision 派生运行按 project_id 归位原消息(群聊 messages / 单聊
@@ -0,0 +1,53 @@
1
+ // src/services/runtime/context-window.js —— 语境窗域
2
+ // 增量尾窗常量、无信息量系统通知过滤与水位推进。
3
+ // 本文件只放方法体,方法挂到 DshRuntime 原型上(见 src/runtime.js 的 defineMethods 调用),
4
+ // 因此方法体内的 this 与拆分前完全一致。
5
+
6
+ // 增量尾窗(DSHBOTS-96 P1-1):无水位(新会话或进程重启)回退尾 12 条全量窗给足上下文;
7
+ // 有水位只注入其后的新消息;上限 24 条兜住多运行并发共用会话时的积压。
8
+ export const RECENT_FALLBACK_LIMIT = 12
9
+ export const RECENT_INCREMENTAL_LIMIT = 24
10
+
11
+ // 无信息量的系统短状态通知(DSHBOTS-96 P3-1):状态已由 Open tasks 与任务评论通道覆盖,
12
+ // 不再重复进尾窗(命中即整条跳过,不占窗位)。
13
+ export const NOISE_SYSTEM_BODY = /^(已写入.+记忆。|任务 \S+ 验收通过。|密钥 \S+ 的请求被拒绝。)$/
14
+
15
+ // 记忆快照召回量(单轮上下文治理 P4):memoryContextFor 由宿主渲染成历史尾部的用户
16
+ // 快照,文本一变就追加一条——live 实测条均 ~400 字符,16 条恰好顶满 7k 截断,等于每次
17
+ // 记忆写入都往活跃会话追加约 3.5k token 的近似快照。降为 8 条 + 3.5k 封顶(按更新时间
18
+ // 取最近 8 条完整条目,不做条内截断),单次追加体积减半;历史侧增长由 P1 折叠兜底。
19
+ export const MEMORY_CONTEXT_LIMIT = 8
20
+ export const MEMORY_CONTEXT_MAX_CHARS = 3_500
21
+
22
+ export const contextMethods = {
23
+ // 增量水位尾窗(DSHBOTS-96 P1-1):每会话维护已注入的 rowid 水位,此后每轮只注入
24
+ // 水位之后的新消息,替代旧的「尾 12 条×240 摘录每轮重烧」。语义:
25
+ // - 无水位(新会话或进程重启)→ 回退尾 RECENT_FALLBACK_LIMIT 条全量窗;
26
+ // - 有水位 → 取 rowid > 水位的新消息(rowid 单调递增,与 created_at 排序一致);
27
+ // - 水位推进到取窗时刻该表 scope 内最大 rowid,只进不退;空窗也推进(越过触发消息);
28
+ // - 多运行并发共用同一会话:先取窗者带走积压并前移水位,后取窗者窗口为空——
29
+ // 两条提示词进同一宿主会话历史,消息不丢不重;
30
+ // - excludeId 排除本轮触发消息(正文已在 # Group message / # Solo message 完整呈现,不再双份)。
31
+ // 无会话上下文时不读不写水位,等价旧的固定尾窗。
32
+ watermarkWindow({ sessionId, table, columns, where, params, excludeId }) {
33
+ const advance = this.store.get(`SELECT MAX(rowid) AS m FROM ${table} WHERE ${where}`, ...params)?.m ?? null
34
+ const watermark = sessionId ? this.messageWatermarks.get(sessionId) : undefined
35
+ const rows = watermark === undefined
36
+ ? this.store.all(
37
+ `SELECT ${columns} FROM ${table} WHERE ${where} ORDER BY rowid DESC LIMIT ?`,
38
+ ...params, RECENT_FALLBACK_LIMIT,
39
+ ).reverse()
40
+ : this.store.all(
41
+ `SELECT ${columns} FROM ${table} WHERE ${where} AND rowid > ? ORDER BY rowid DESC LIMIT ?`,
42
+ ...params, watermark, RECENT_INCREMENTAL_LIMIT,
43
+ ).reverse()
44
+ if (sessionId && advance !== null) {
45
+ const current = this.messageWatermarks.get(sessionId)
46
+ if (current === undefined || advance > current) this.messageWatermarks.set(sessionId, advance)
47
+ }
48
+ return {
49
+ rows: excludeId ? rows.filter(row => row.id !== excludeId) : rows,
50
+ incremental: watermark !== undefined,
51
+ }
52
+ },
53
+ }