dsh-team-bots 0.2.465 → 0.3.64

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 (84) hide show
  1. package/NOTICE +5 -0
  2. package/README.md +8 -2
  3. package/docs/README.zh.md +8 -2
  4. package/docs/assets/global-config.png +0 -0
  5. package/docs/assets/global-config.zh.png +0 -0
  6. package/docs/assets/tasks.png +0 -0
  7. package/docs/assets/tasks.zh.png +0 -0
  8. package/docs/assets/usage.png +0 -0
  9. package/docs/assets/usage.zh.png +0 -0
  10. package/package.json +8 -2
  11. package/src/api.js +16 -2
  12. package/src/config.js +193 -8
  13. package/src/db-migrations.js +53 -4
  14. package/src/db.js +37 -3
  15. package/src/http.js +20 -1
  16. package/src/runtime.js +16 -1
  17. package/src/seed-bots.js +4 -0
  18. package/src/service.js +21 -2
  19. package/src/services/approvals.js +276 -8
  20. package/src/services/bot-quota.js +54 -0
  21. package/src/services/bots.js +8 -0
  22. package/src/services/chat.js +54 -5
  23. package/src/services/core.js +31 -2
  24. package/src/services/memory.js +112 -25
  25. package/src/services/model-fallback.js +55 -15
  26. package/src/services/projects.js +13 -2
  27. package/src/services/run-finish.js +44 -11
  28. package/src/services/runs.js +15 -7
  29. package/src/services/runtime/prompt.js +31 -6
  30. package/src/services/runtime/session.js +87 -25
  31. package/src/services/scheduler.js +26 -5
  32. package/src/services/system.js +162 -10
  33. package/src/services/task-dispatch.js +24 -0
  34. package/src/services/task-notify.js +18 -0
  35. package/src/services/task-review.js +102 -23
  36. package/src/services/task-runs.js +31 -3
  37. package/src/services/tasks.js +91 -3
  38. package/src/tools.js +20 -14
  39. package/ui/app.js +7 -10
  40. package/ui/i18n/en/chat.js +2 -0
  41. package/ui/i18n/en/common.js +10 -0
  42. package/ui/i18n/en/settings.js +76 -1
  43. package/ui/i18n/en/tasks.js +3 -0
  44. package/ui/i18n/zh/chat.js +2 -0
  45. package/ui/i18n/zh/common.js +10 -0
  46. package/ui/i18n/zh/settings.js +76 -1
  47. package/ui/i18n/zh/tasks.js +3 -0
  48. package/ui/modules/api.js +9 -1
  49. package/ui/modules/cards.js +6 -3
  50. package/ui/modules/chat.js +1 -1
  51. package/ui/modules/composer.js +6 -1
  52. package/ui/modules/events-board.js +48 -0
  53. package/ui/modules/events-misc.js +43 -0
  54. package/ui/modules/events-submit.js +20 -0
  55. package/ui/modules/form-validation.js +204 -0
  56. package/ui/modules/global-pages.js +8 -5
  57. package/ui/modules/modal-forms.js +4 -4
  58. package/ui/modules/modal-layer.js +4 -1
  59. package/ui/modules/page-shell.js +10 -7
  60. package/ui/modules/permissions.js +99 -0
  61. package/ui/modules/settings.js +108 -26
  62. package/ui/modules/state.js +10 -0
  63. package/ui/modules/task-menu.js +147 -0
  64. package/ui/modules/tasks.js +11 -10
  65. package/ui/modules/util.js +43 -6
  66. package/ui/styles/a11y.css +13 -0
  67. package/ui/styles/base.css +57 -11
  68. package/ui/styles/buttons.css +46 -6
  69. package/ui/styles/cards.css +90 -0
  70. package/ui/styles/chat.css +23 -2
  71. package/ui/styles/global-config.css +7 -4
  72. package/ui/styles/modal.css +28 -0
  73. package/ui/styles/settings.css +23 -1
  74. package/ui/styles/tasks.css +51 -1
  75. package/ui/styles/toast.css +18 -11
  76. package/ui/styles/usage.css +2 -0
  77. package/ui/styles/wide.css +5 -0
  78. package/docs/assets/channel-redesign.png +0 -0
  79. package/docs/assets/global-config-dark.png +0 -0
  80. package/docs/assets/global-config-light.png +0 -0
  81. package/docs/assets/global-config-light.zh.png +0 -0
  82. package/docs/assets/global-config-redesign.png +0 -0
  83. package/docs/assets/secrets-redesign.png +0 -0
  84. package/docs/assets/usage-redesign-global.png +0 -0
@@ -343,6 +343,13 @@ export const taskDispatchMethods = {
343
343
  if (input.taskId || input.task) {
344
344
  const task = this.resolveBotTask(project, input.taskId ?? input.task)
345
345
  if (['done', 'canceled'].includes(task.status)) throw conflict(`任务 ${project.key}-${task.number} 已结束,不能重派`)
346
+ // 变更栅栏(吸收 dsh-agent-team mutation-fence 理念):改卡可选带 expected_version
347
+ // (bot 最后看到的卡 version)。不匹配即拒,拒绝附最近变更事实,写者可就地重新
348
+ // 裁决;不带该参数保持既有 last-write-wins 行为(看板 UI 有自己的刷新闭环)。
349
+ if (input.expected_version !== undefined
350
+ && Number(input.expected_version) !== Number(task.version)) {
351
+ throw this.staleTaskConflict(task, input.expected_version)
352
+ }
346
353
  // 核验纪律派单闸(DSHBOTS-303):重派/改卡按生效卡面(本次传入优先,缺省回落原卡)。
347
354
  this.assertNotVerificationDispatch(project, member.id, input.title ?? task.title, input.description ?? task.description)
348
355
  // 派单策略闸(DSHBOTS-314):重派按原卡声明写范围同闸(重派不改写范围,D-232 口径)。
@@ -352,6 +359,9 @@ export const taskDispatchMethods = {
352
359
  // 写范围不在此口改:入队运行快照与调度闸门消费的不是同一份数据,
353
360
  // 改范围走工作台 taskUpdateScopes(含排队运行快照同步),不在这里开第二入口。
354
361
  const patch = {}
362
+ // 栅栏双保险:上面的预检与 updateTask 的 CAS 之间卡仍可能被并发更新,改卡补丁
363
+ // 一并携带 expected_version,由 updateTask 的 CAS 兜底拦截。
364
+ if (input.expected_version !== undefined) patch.version = input.expected_version
355
365
  if (input.title !== undefined) patch.title = input.title
356
366
  if (input.description !== undefined) patch.description = input.description
357
367
  if (input.priority !== undefined) patch.priority = input.priority
@@ -384,6 +394,20 @@ export const taskDispatchMethods = {
384
394
  + '未声明会让该任务的写运行与同项目其他写运行全部串行,一条任务即可堵死队列。',
385
395
  )
386
396
  }
397
+ // 大卡拆分闸(产品化派单纪律):写范围条目超过 maxWriteScopesPerTask 时拒绝整卡
398
+ // 派发——超大范围卡与同项目一切写运行按保守串行互斥,一条卡即可吃掉整队并行能力
399
+ // (2026-11-13 生产实测 run_parallel 触发率仅 26%,主因即大范围声明)。拒绝文案
400
+ // 按 D-269 口径 = 原因 + 替代命令(parent_task_id 拆子卡,子卡范围不相交即并行)。
401
+ const maxScopes = Number(this.config.maxWriteScopesPerTask)
402
+ if (scopes.length > maxScopes) {
403
+ throw badRequest(
404
+ `写范围 ${scopes.length} 条超过单卡上限 ${maxScopes}(maxWriteScopesPerTask),大卡必须拆分:`
405
+ + '先建一张主卡(或复用既有卡)拿任务号,再按独立部分拆子卡——每张子卡一次 '
406
+ + 'team_assign_task,传 parent_task_id=主卡任务号,write_scopes 只覆盖该部分且互不相交;'
407
+ + `范围有依赖顺序时用 blocked_by 串联。拆完后子卡可并行施工。`
408
+ + '确需单卡大范围时调大 DSH_TEAM_MAX_WRITE_SCOPES / maxWriteScopesPerTask。',
409
+ )
410
+ }
387
411
  // 同写范围重复卡拦截(DSHBOTS-82):同项目已有「写范围完全一致」的在办卡时直接拒绝,
388
412
  // 避免同一文件上叠 N 张排队卡空转。force_duplicate 是逃生口:跳过检测,但留审计痕迹。
389
413
  // 紧急豁免(DSHBOTS-126):priority='urgent' 的新卡放行——紧急任务无视排队立即施工,
@@ -10,6 +10,7 @@
10
10
  // 微信推送文案排版集中在 src/wechat/format.js(DSHBOTS-211)。
11
11
 
12
12
  import { taskCreated, taskDone } from '../wechat/format.js'
13
+ import { jsonParse, nowIso } from '../util.js'
13
14
 
14
15
  export const taskNotifyMethods = {
15
16
  // 「任务进入进行中」的唯一落点。
@@ -123,4 +124,21 @@ export const taskNotifyMethods = {
123
124
  this.logger.warn?.('dsh-team: 任务创建通知失败 %s: %s', identifier, error?.message ?? error)
124
125
  }
125
126
  },
127
+ // 验收边界沉淀提醒(吸收 dsh-agent-team acceptance-boundary 理念,搭车投递形态):
128
+ // 验收通过只落一个 per-(bot, project) 待提醒标记(上限 3 条),负责人在该项目的下一次
129
+ // 运行提示词里渲染一次性提醒块(见 prompt.ts acceptReminderBlock)并清标记——零额外
130
+ // 轮次、不往会话日志注入外来消息、不依赖会话存续(steer 形态的三个毛病都没有)。
131
+ noteTaskAccepted(task) {
132
+ const project = this.projectRow(task.project_id)
133
+ const identifier = `${project.key}-${task.number}`
134
+ if (!task.assignee_bot_id) return false
135
+ const key = `accept_remind:${task.assignee_bot_id}:${project.id}`
136
+ const list = jsonParse(this.store.setting(key), [])
137
+ const safe = Array.isArray(list) ? list : []
138
+ const next = [...safe.filter(item => item?.identifier !== identifier), {
139
+ identifier, title: task.title ?? '', at: nowIso(),
140
+ }].slice(-3)
141
+ this.store.setSetting(key, JSON.stringify(next))
142
+ return true
143
+ },
126
144
  }
@@ -7,8 +7,10 @@
7
7
 
8
8
  import { badRequest, conflict, forbidden } from '../errors.js'
9
9
  import { bool } from '../config.js'
10
+ import { REVIEWER_BOT_NAME } from '../seed-bots.js'
10
11
  import { id, nowIso, text } from '../util.js'
11
12
  import { parseWriteScopes, readWriteScopes } from './write-scopes.js'
13
+ import { effectiveSandbox } from './runtime/sandbox-policy.js'
12
14
 
13
15
  export const taskReviewMethods = {
14
16
  async reviewFromBot(sessionId, input) {
@@ -21,14 +23,34 @@ export const taskReviewMethods = {
21
23
  return this.applyReview(task, project, input.decision, input.comment, actor)
22
24
  },
23
25
 
26
+ // 验收核验分档开关:默认开,DSH_TEAM_REVIEW_READ_ONLY_SKIP=0 关闭回到全量强制核验。
27
+ reviewReadOnlySkipEnabled() {
28
+ return bool(this.config.reviewReadOnlySkip, true)
29
+ },
30
+
31
+ // 只读档交付判定(核验分档的单一口径):交付运行的生效沙箱为 read-only(非写运行被
32
+ // run_type 收紧,或任务覆盖/负责人配置档为只读)即视为只读交付——物理上写不了工作区,
33
+ // 核验子代理重读一遍的边际价值最低。queueAutoReviewDelegate 跳过、验收闸门放宽、
34
+ // taskReviewStatus 标记 skipped 三处共用本判定。
35
+ readOnlyDelivery(run, taskRow) {
36
+ if (!run || !this.reviewReadOnlySkipEnabled()) return false
37
+ // 保守卫:mode 缺失的坏数据不豁免(DB 列 NOT NULL DEFAULT 'write',正常不会缺),
38
+ // 只有显式 read 运行或写运行被覆盖/配置收紧到只读才豁免。
39
+ if (run.mode !== 'write' && run.mode !== 'read') return false
40
+ const bot = this.store.get('SELECT id, file_policy FROM bots WHERE id = ?', run.bot_id)
41
+ const task = taskRow ?? (run.task_id ? this.store.get('SELECT id, sandbox_override FROM tasks WHERE id = ?', run.task_id) : null)
42
+ return effectiveSandbox(run, bot, task).mode === 'read-only'
43
+ },
44
+
24
45
  // 验收机械闸(DSHBOTS-318/353):把「验收必须经由子代理」从提示约束升级为机械约束——
25
46
  // owner bot 的 team_review_task 前置校验本评审周期内的子代理账目(run_events 的
26
47
  // subagent_spawned)。周期起点 T=最近一次交付(run_succeeded)或看板流转
27
- // (status→in_review)事件的 created_at 取 MAX;账目归属两条认领线:
28
- // 本任务的 owner 运行(task_id+bot_id)或调用方会话的任意运行——两跳正规流程
29
- // (review_delegate 派子代理 → 新运行只裁决)的账目挂在上一跳已结束运行上,
30
- // 按「当运行有账」查必漏,故按周期查。comment 显式注明「兜底验收」放行
31
- // (对应 router 硬流程第 4 条:子代理失败重试一次仍失败时 director 兜底)。
48
+ // (status→in_review)事件的 created_at 取 MAX;账目归属三条认领线:
49
+ // 本任务的 owner 运行(task_id+bot_id)、调用方会话的任意运行、或本任务上的委派核验
50
+ // 运行(task_id+trigger_type,DSHBOTS-365:核验承接人可能是成员 reviewer 而非总监,
51
+ // 其子代理账目挂在自己名下)。两跳正规流程(review_delegate 派子代理 → 新运行只裁决)
52
+ // 的账目挂在上一跳已结束运行上,按当运行有账查必漏,故按周期查。comment 显式注明
53
+ // 「兜底验收」放行(对应 router 硬流程第 4 条:子代理失败重试一次仍失败时 director 兜底)。
32
54
  // 仅机器人路径:微信管理员/看板 owner 走 applyReview,不经过本闸。
33
55
  assertReviewSubagentVerified(sessionId, project, task, comment) {
34
56
  if (comment?.includes('兜底验收')) return
@@ -38,13 +60,23 @@ export const taskReviewMethods = {
38
60
  AND (type = 'run_succeeded' OR (type = 'status' AND json_extract(data_json, '$.to') = 'in_review'))`,
39
61
  task.id,
40
62
  )?.t ?? ''
63
+ // 核验分档:本评审周期的交付运行为只读档(事件载荷 runId 指回交付运行)时免子代理
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`,
69
+ task.id, windowStart,
70
+ )
71
+ if (delivered && this.readOnlyDelivery(delivered, task)) return
41
72
  const ledger = this.store.get(
42
73
  `SELECT 1 AS hit FROM runs r
43
- WHERE ((r.task_id = ? AND r.bot_id = ?) OR r.session_id = ?)
74
+ WHERE ((r.task_id = ? AND r.bot_id = ?) OR r.session_id = ?
75
+ OR (r.task_id = ? AND r.trigger_type = 'review_delegate'))
44
76
  AND EXISTS (SELECT 1 FROM run_events e
45
77
  WHERE e.run_id = r.id AND e.type = 'subagent_spawned' AND e.created_at >= ?)
46
78
  LIMIT 1`,
47
- task.id, project.owner_bot_id, sessionId, windowStart,
79
+ task.id, project.owner_bot_id, sessionId, task.id, windowStart,
48
80
  )
49
81
  if (ledger) return
50
82
  // DSHBOTS-269 失败语义引导:拒绝文案 = 原因 + 正确下一步。
@@ -77,6 +109,8 @@ export const taskReviewMethods = {
77
109
  body: `任务 ${identifier} 验收通过。`,
78
110
  taskId: task.id,
79
111
  })
112
+ // 验收边界沉淀提醒:落待提醒标记,负责人下次在该项目运行时搭车渲染(零额外轮次)。
113
+ this.noteTaskAccepted(this.taskRow(task.id))
80
114
  } else {
81
115
  const reason = text(comment, 20_000)
82
116
  if (!reason) throw badRequest('退回任务必须说明原因')
@@ -98,10 +132,12 @@ export const taskReviewMethods = {
98
132
  return this.taskView(this.taskRow(task.id))
99
133
  },
100
134
 
101
- // 验收核验委派(DSHBOTS-107):待验收任务上,owner 一键把核验工作派给总监 Bot,
102
- // 由其会话内的 subagent/subagent_fork 并行完成(提示词见 runtime/prompt.js 的
103
- // review-verification 模板)。核验结论以任务评论写回(finishRun 复用 addComment 通道),
104
- // 裁决权不变:accept/return 仍由 owner 经 team_review_task 或看板执行,本方法不碰任务状态。
135
+ // 验收核验委派(DSHBOTS-107;DSHBOTS-365 承接人默认 reviewer):待验收任务上,owner
136
+ // 一键委派子代理核验——承接人优先项目内种子 reviewer(reviewDelegateBotFor),无则
137
+ // 总监 Bot 兜底,由其会话内的 subagent/subagent_fork 并行完成(提示词见
138
+ // runtime/prompt.js 的 review-verification 模板)。核验结论以任务评论写回(finishRun
139
+ // 复用 addComment 通道),不改任务状态、不代负责人裁决:accept/return 仍由 owner 经
140
+ // team_review_task 或看板执行,本方法不碰任务状态。
105
141
  async taskReviewDelegate(taskId, actor = this.actor()) {
106
142
  if (actor.type !== 'user') throw forbidden('只有工作台 owner 可以委派子代理核验')
107
143
  const task = this.taskRow(taskId)
@@ -147,6 +183,19 @@ export const taskReviewMethods = {
147
183
  return this.taskView(this.taskRow(taskId))
148
184
  },
149
185
 
186
+ // 核验承接人(DSHBOTS-365 产品默认):项目成员里的种子 reviewer 优先(固定名识别,
187
+ // 改名/移除/不可用即失效),回落总监自行核验(兜底)。裁决权不变:仍归 owner。
188
+ reviewDelegateBotFor(project) {
189
+ if (!project.owner_bot_id) return null
190
+ return this.store.get(
191
+ `SELECT b.* FROM bots b
192
+ JOIN project_members m ON m.member_type = 'bot' AND m.member_id = b.id
193
+ WHERE m.project_id = ? AND b.name = ? AND b.status = 'active' AND b.id <> ?
194
+ LIMIT 1`,
195
+ project.id, REVIEWER_BOT_NAME, project.owner_bot_id,
196
+ )
197
+ },
198
+
150
199
  // 核验委派共享入口(DSHBOTS-113):手动按钮(taskReviewDelegate)与交付后自动委派
151
200
  // (review_delegate_auto outbox)走同一实现,守卫(待验收状态 / 可用总监 / one_active
152
201
  // 幂等复看)与运行形态(kind='review', mode='read', trigger='review_delegate')完全一致。
@@ -159,6 +208,8 @@ export const taskReviewMethods = {
159
208
  ? this.store.get("SELECT * FROM bots WHERE id = ? AND status = 'active'", project.owner_bot_id)
160
209
  : null
161
210
  if (!owner) throw conflict(`项目 ${project.name} 没有可用的总监 Bot,无法委派核验`)
211
+ // 核验承接人:优先成员 reviewer(DSHBOTS-365),无则总监兜底。
212
+ const verifier = this.reviewDelegateBotFor(project) ?? owner
162
213
  const active = this.store.get(
163
214
  "SELECT id, trigger_type FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
164
215
  task.id,
@@ -169,29 +220,57 @@ export const taskReviewMethods = {
169
220
  if (active.trigger_type === 'review_delegate') return { runId: active.id, reused: true }
170
221
  throw conflict(`任务 ${identifier} 已有运行在排队或执行,请先停止再委派核验`)
171
222
  }
172
- // busy 闸(DSHBOTS-290):总监忙时不落 runs 行(撞 one_active_run_per_bot),挂待
223
+ // DSHBOTS-358:额度路由(与任务运行同口径)——主 provider 耗尽时走备用模型,
224
+ // 无可用备用则留 queued 等恢复;路由快照写进运行行的 model_* 三列。
225
+ const routing = this.quotaRoutingForBot(verifier)
226
+ const routeProvider = routing.mode === 'fallback' ? routing.provider : null
227
+ const routeModel = routing.mode === 'fallback' ? routing.model : null
228
+ const routeEffort = routing.mode === 'fallback' ? routing.effort : null
229
+ // busy 闸(DSHBOTS-290):承接人忙时不落 runs 行(撞 one_active_run_per_bot),挂待
173
230
  // 处理队列空闲建回(insertHeldMessageRun 的 owner_task 分支);返回 deferred 让
174
231
  // 手动入口与 outbox 自动入口都能感知「已挂起」而非失败。
175
- if (this.botBusy(owner.id, project.id)) {
176
- this.holdPendingMessage(owner.id, project.id, {
177
- kind: 'owner_task', messageId: `owner_task:${task.id}:review_delegate`, taskId: task.id,
178
- projectId: project.id, runKind: 'review', triggerType: 'review_delegate', queuedAt: nowIso(),
179
- })
232
+ const hold = () => this.holdPendingMessage(verifier.id, project.id, {
233
+ kind: 'owner_task', messageId: `owner_task:${task.id}:review_delegate`, taskId: task.id,
234
+ projectId: project.id, runKind: 'review', triggerType: 'review_delegate', queuedAt: nowIso(),
235
+ routing: routing.mode === 'fallback'
236
+ ? { mode: 'fallback', provider: routing.provider, model: routing.model, effort: routing.effort, ref: routing.ref }
237
+ : routing.mode === 'wait'
238
+ ? { mode: 'wait', resetAt: routing.resetAt }
239
+ : { mode: 'primary' },
240
+ })
241
+ if (this.botBusy(verifier.id, project.id)) {
242
+ hold()
180
243
  return { runId: null, deferred: true }
181
244
  }
182
245
  const runId = id('run')
183
246
  const createdAt = nowIso()
184
- this.store.run(
185
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
186
- attempt, idempotency_key, queued_at)
187
- VALUES (?, ?, ?, ?, 'review', 'read', 'review_delegate', ?, 'queued', 1, ?, ?)`,
188
- runId, project.id, owner.id, task.id, task.id, `review_delegate:${task.id}:${Date.now()}:${runId}`, createdAt,
189
- )
247
+ try {
248
+ this.store.run(
249
+ `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
250
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
251
+ VALUES (?, ?, ?, ?, 'review', 'read', 'review_delegate', ?, 'queued', 1, ?, ?, ?, ?, ?)`,
252
+ runId, project.id, verifier.id, task.id, task.id, `review_delegate:${task.id}:${Date.now()}:${runId}`,
253
+ routeProvider, routeModel, routeEffort, createdAt,
254
+ )
255
+ } catch (error) {
256
+ // 查后插竞态(DSHBOTS-300 同款):busy 检查与 INSERT 之间承接人被占用,撞
257
+ // one_active_run_per_bot——挂待处理队列空闲建回,同 busy 闸返回 deferred,不向上抛。
258
+ if (this.isRunBotUniqueViolation(error)) {
259
+ hold()
260
+ return { runId: null, deferred: true }
261
+ }
262
+ throw error
263
+ }
190
264
  this.store.run(
191
265
  'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
192
266
  id('evt'), runId, 'queued',
193
267
  `${origin === 'auto' ? '交付后自动' : 'owner'}委派子代理核验(${actor.type}:${actor.id})`, createdAt,
194
268
  )
269
+ if (routing.mode === 'fallback') {
270
+ this.insertRunEvent(runId, 'quota_fallback', `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}`)
271
+ } else if (routing.mode === 'wait') {
272
+ this.insertRunEvent(runId, 'quota_wait', `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`)
273
+ }
195
274
  this.audit(actor, origin === 'auto' ? 'review.auto_delegate' : 'task.review_delegate', 'task', task.id, { runId })
196
275
  void this.tick()
197
276
  return { runId, reused: false }
@@ -179,9 +179,21 @@ export const taskRunMethods = {
179
179
  // busy 闸(DSHBOTS-290):owner 忙时 review/handle 运行同样不落 runs 行(撞
180
180
  // one_active_run_per_bot),挂待处理队列空闲建回——与 enqueueTaskRun 同口径。
181
181
  // DSHBOTS-300:挂起项提为 hold 闭包,busy 分支与查后插竞态兜底共用。
182
+ // DSHBOTS-358:额度路由(与任务运行同口径)——主 provider 耗尽时走备用模型,
183
+ // 无可用备用则留 queued 等恢复;路由快照写进运行行的 model_* 三列。
184
+ // 路由在 busy 闸之前算好:挂起项要带同一份快照,空闲建回时列面与直插一致。
185
+ const routing = this.quotaRoutingForBot(owner)
186
+ const routeProvider = routing.mode === 'fallback' ? routing.provider : null
187
+ const routeModel = routing.mode === 'fallback' ? routing.model : null
188
+ const routeEffort = routing.mode === 'fallback' ? routing.effort : null
182
189
  const hold = () => this.holdPendingMessage(owner.id, project.id, {
183
190
  kind: 'owner_task', messageId: `owner_task:${current.id}:${kind}`, taskId: current.id,
184
191
  projectId: project.id, runKind: kind, triggerType, queuedAt: createdAt,
192
+ routing: routing.mode === 'fallback'
193
+ ? { mode: 'fallback', provider: routing.provider, model: routing.model, effort: routing.effort, ref: routing.ref }
194
+ : routing.mode === 'wait'
195
+ ? { mode: 'wait', resetAt: routing.resetAt }
196
+ : { mode: 'primary' },
185
197
  })
186
198
  if (this.botBusy(owner.id, project.id)) {
187
199
  hold()
@@ -190,10 +202,11 @@ export const taskRunMethods = {
190
202
  try {
191
203
  this.store.run(
192
204
  `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
193
- attempt, idempotency_key, queued_at)
194
- VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
205
+ attempt, idempotency_key, model_provider, model_model, model_effort, queued_at)
206
+ VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?, ?, ?, ?)`,
195
207
  runId, project.id, owner.id, task.id, kind, triggerType, task.id,
196
- `${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
208
+ `${kind}:${task.id}:${Date.now()}:${runId}`,
209
+ routeProvider, routeModel, routeEffort, createdAt,
197
210
  )
198
211
  } catch (error ) {
199
212
  // DSHBOTS-304:双投胜利方同任务 active 运行已在→合并返回其 id 消算(同 enqueueTaskRun)。
@@ -211,6 +224,21 @@ export const taskRunMethods = {
211
224
  kind === 'review' ? '任务交付,转总监验收' : '任务受阻,转总监处理',
212
225
  createdAt,
213
226
  )
227
+ // DSHBOTS-358:内部运行同样接额度路由——主 provider 耗尽时直接走备用模型;
228
+ // 无可用备用则留 queued 等恢复(调度器额度闸门兜底),不再照常下发撞墙。
229
+ if (routing.mode === 'fallback') {
230
+ this.insertRunEvent(
231
+ runId,
232
+ 'quota_fallback',
233
+ `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}(预计 ${this.botQuotaState(owner.id, owner.provider)?.resetAt ?? '未知'} 恢复)`,
234
+ )
235
+ } else if (routing.mode === 'wait') {
236
+ this.insertRunEvent(
237
+ runId,
238
+ 'quota_wait',
239
+ `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`,
240
+ )
241
+ }
214
242
  void this.tick()
215
243
  return runId
216
244
  },
@@ -238,6 +238,91 @@ export const tasksMethods = {
238
238
  id('tevt'), taskId, type, actor.type, actor.id, JSON.stringify(data), nowIso(),
239
239
  )
240
240
  },
241
+ // 统一状态迁移落点(吸收 dsh-agent-team「账本为权威、投影可重放」理念):所有直接改
242
+ // tasks.status 的路径都经此走——同一事务内 UPDATE + 权威 'status' 事件(from/to),
243
+ // 事件流因此能完整重放任务状态机(见 taskProjectionDrift)。守卫防终态覆盖/非法源态;
244
+ // 返回是否实际迁移(未命中守卫为 no-op,调用方保持原语义)。
245
+ setTaskStatus(taskId, to, actor, guard = {}) {
246
+ const task = this.taskRow(taskId)
247
+ if (task.status === to) return false
248
+ const guardSql = guard.ifIs
249
+ ? 'status = ?'
250
+ : `status NOT IN (${(guard.notIn ?? ['done', 'canceled']).map(() => '?').join(',')})`
251
+ const guardParams = guard.ifIs ? [guard.ifIs] : (guard.notIn ?? ['done', 'canceled'])
252
+ let applied = false
253
+ this.store.transaction(() => {
254
+ const result = this.store.run(
255
+ `UPDATE tasks SET status = ?, version = version + 1, updated_at = ? WHERE id = ? AND ${guardSql}`,
256
+ to, nowIso(), taskId, ...guardParams,
257
+ )
258
+ applied = Number(result?.changes ?? 0) > 0
259
+ if (applied) this.addTaskEvent(taskId, 'status', actor, { field: 'status', from: task.status, to })
260
+ })
261
+ return applied
262
+ },
263
+ // 投影漂移巡检:按权威事件流(created 初始态 + 'status' 事件序列)重放每个任务的状态,
264
+ // 与 tasks 表对照。漂移即投影与账本脱节(崩溃半事务/手工改库),报告不修复。
265
+ taskProjectionDrift() {
266
+ const drifted = []
267
+ for (const task of this.store.all('SELECT id, number, project_id, status FROM tasks')) {
268
+ const events = this.store.all(
269
+ `SELECT type, data_json FROM task_events WHERE task_id = ?
270
+ AND (type = 'created' OR (type = 'status' AND json_extract(data_json, '$.field') = 'status'))
271
+ ORDER BY created_at, rowid`,
272
+ task.id,
273
+ )
274
+ if (!events.length) continue
275
+ let replayed = null
276
+ for (const event of events) {
277
+ const data = JSON.parse(event.data_json ?? '{}')
278
+ if (event.type === 'created') replayed = data.status ?? 'backlog'
279
+ else if (data.to) replayed = data.to
280
+ }
281
+ if (replayed !== null && replayed !== task.status) {
282
+ const project = this.store.get('SELECT key FROM projects WHERE id = ?', task.project_id)
283
+ drifted.push({ taskId: task.id, identifier: `${project?.key ?? 'T'}-${task.number}`, recorded: task.status, replayed })
284
+ }
285
+ }
286
+ return drifted
287
+ },
288
+ // 变更栅栏的事实面(吸收 dsh-agent-team mutation-fence 理念):版本冲突的拒绝不只说
289
+ // 「请刷新」,还附最近变更事实,让写者就地重新裁决,不必整卡重读。事件与 version
290
+ // 增量非一一对应(交付是一事件一增量,updateTask 是一增量多事件),故按时间取最近
291
+ // N 条而非按版本切割。
292
+ taskChangesSince(taskId, limit = 5) {
293
+ const rows = this.store.all(
294
+ '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
+ taskId, limit,
296
+ )
297
+ return rows.reverse().map(row => {
298
+ let data = {}
299
+ try { data = JSON.parse(row.data_json ?? '{}') } catch { /* 旧格式事件按原始类型渲染 */ }
300
+ const who = row.actor_type === 'bot'
301
+ ? (this.store.get('SELECT name FROM bots WHERE id = ?', row.actor_id)?.name ?? row.actor_id)
302
+ : row.actor_type
303
+ if (data.field !== undefined) {
304
+ return `${who} 改 ${data.field}:${JSON.stringify(data.from ?? null)}→${JSON.stringify(data.to ?? null)}`
305
+ }
306
+ if (row.type === 'assigned') {
307
+ const name = this.store.get('SELECT name FROM bots WHERE id = ?', data.botId)?.name ?? data.botId
308
+ return `${who} 派单给 ${name ?? '?'}`
309
+ }
310
+ if (row.type === 'run_succeeded') return `${who} 交付(${data.identifier ?? row.task_id ?? ''})`
311
+ if (row.type === 'created') return `${who} 建卡`
312
+ return `${who} ${row.type}`
313
+ })
314
+ },
315
+ // 版本冲突拒绝(原因 + 错过的事实 + 正确下一步):updateTask 的 CAS 与
316
+ // team_assign_task 改卡的 expected_version 共用同一文案面。
317
+ staleTaskConflict(task, seenVersion) {
318
+ const project = this.store.get('SELECT key FROM projects WHERE id = ?', task.project_id)
319
+ const changes = this.taskChangesSince(task.id)
320
+ return conflict(
321
+ `任务 ${project?.key ?? 'T'}-${task.number} 已被更新(你基于 version ${Number(seenVersion)},当前 version ${task.version})。`
322
+ + `自那之后的最近变更:${changes.join(';') || '(无事件记录,以卡面为准'})。`
323
+ + '可基于以上事实重新裁决后带 expected_version 重试,或先 team_recall 刷新卡面再改。',
324
+ )
325
+ },
241
326
  taskView(task) {
242
327
  // attention_json 列由 attention 域自管迁移(db.js 不加行),读视图前懒迁移一次。
243
328
  // parent_task_id/blocked_by 同款:task-relations 域自管迁移 + 依赖派生字段。
@@ -280,15 +365,18 @@ export const tasksMethods = {
280
365
  },
281
366
 
282
367
  // 核验状态(DSHBOTS-113):none=未核验 / pending=核验中(委派运行在跑或自动委派待投递)/
283
- // done=本次交付已有核验结论 / failed=核验失败(运行失败或自动委派重试耗尽)。
368
+ // done=本次交付已有核验结论 / failed=核验失败(运行失败或自动委派重试耗尽)/
369
+ // skipped=只读档交付按策略跳过核验(readOnlyDelivery 豁免)。
284
370
  // 以「最近一次成功的执行运行」(本次交付)为基准,只认其后发起的核验,避免上一轮
285
371
  // 交付的旧结论被误读为本轮已核验。自动流程失败必须在 UI 可见(防静默漏审)。
286
372
  taskReviewStatus(task) {
287
373
  const delivery = this.store.get(
288
- "SELECT queued_at FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'succeeded' AND COALESCE(error_code, '') <> 'SUPERSEDED' ORDER BY ended_at DESC LIMIT 1",
374
+ "SELECT queued_at, bot_id, task_id, mode FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'succeeded' AND COALESCE(error_code, '') <> 'SUPERSEDED' ORDER BY ended_at DESC LIMIT 1",
289
375
  task.id,
290
376
  )
291
377
  if (!delivery) return 'none'
378
+ // 核验分档:只读档交付按策略跳过核验,标 skipped(UI 呈现「只读免核验」而非误报未核验)。
379
+ if (this.readOnlyDelivery(delivery, task)) return 'skipped'
292
380
  const activeRun = this.store.get(
293
381
  "SELECT id FROM runs WHERE task_id = ? AND trigger_type = 'review_delegate' AND status IN ('queued', 'running') AND queued_at >= ?",
294
382
  task.id, delivery.queued_at,
@@ -320,7 +408,7 @@ export const tasksMethods = {
320
408
  async updateTask(taskId, patch, actor = this.actor(), options = {} ) {
321
409
  const task = this.taskRow(taskId)
322
410
  if (patch.version !== undefined && Number(patch.version) !== Number(task.version)) {
323
- throw conflict('任务已被其他人更新,请刷新后重试')
411
+ throw this.staleTaskConflict(task, patch.version)
324
412
  }
325
413
  const updates = {}
326
414
  if (patch.title !== undefined) {
package/src/tools.js CHANGED
@@ -35,8 +35,9 @@ export const SUBAGENT_GENERATION_TOOLS = [
35
35
  // team_block_task(DSHBOTS-232)与派单/验收同款总监专属:强制受阻停运行是不可逆控制面操作。
36
36
  // team_list_bots / team_add_member / team_create_bot(DSHBOTS-229)是团队编制入口:
37
37
  // 池查询含未入群 bot,加人与建 bot 会改动项目成员或全局 bot 档案。
38
- // team_memory_list / team_memory_write / team_memory_cleanup(DSHBOTS-239)是记忆巡检面:
39
- // 枚举、同名覆盖写与批量终态化清理都只归总监。
38
+ // team_memory_list / team_memory_write / team_memory_cleanup(DSHBOTS-239)是记忆管理面:
39
+ // bot 域记忆由 Bot 自己管理(成员触顶后的合法自救通道),项目/团队域归项目总监,
40
+ // 总监可经 bot 点名代管任意 Bot——权限判定在服务层 resolveMemoryScopeFor。
40
41
  export const DIRECTOR_ONLY_TOOLS = [
41
42
  'team_assign_task',
42
43
  'team_review_task',
@@ -44,9 +45,6 @@ export const DIRECTOR_ONLY_TOOLS = [
44
45
  'team_list_bots',
45
46
  'team_add_member',
46
47
  'team_create_bot',
47
- 'team_memory_list',
48
- 'team_memory_write',
49
- 'team_memory_cleanup',
50
48
  'team_release_bot_quota',
51
49
  ]
52
50
 
@@ -59,14 +57,18 @@ export function subagentCapabilityEnabledFor(bot, config) {
59
57
  // 子代理生成工具由 preset 全局注册,成员 bot 默认可见,无需额外放行。
60
58
  // DSHBOTS-247:调用点形状不一——session.ts 的结转/复用路径传 resolveAgent 的
61
59
  // `{ agent }` 包装,新建会话路径传裸 agent。这里归一为句柄后取 restrict,两种形状都生效;
62
- // 旧实现只认包装形状时,裸形状会静默跳过(策略从未生效)或旧构建抛 "reading 'ctx'"。
60
+ // 旧实现只认包装形状时,裸形状会静默跳过(策略从未生效)。
61
+ // DSHBOTS-359:restrict 必须以方法调用发出——宿主 ToolsService.restrict 首行读 this.ctx,
62
+ // 摘下函数裸调用会让 this===undefined,抛 "reading 'ctx'" 被吞成 warn,策略自 DSHBOTS-238
63
+ // 起从未真正生效(成员 bot 一直可见总监专权工具)。
63
64
  export function applyBotToolPolicy(resolved, { isOwner, logger } ) {
64
65
  if (isOwner) return
65
66
  const handle = resolved?.agent ?? resolved
66
- const restrict = handle?.ctx?.tools?.restrict
67
- if (typeof restrict !== 'function') return
67
+ const tools = handle?.ctx?.tools
68
+ if (typeof tools?.restrict !== 'function') return
68
69
  try {
69
- restrict({ deny: [...DIRECTOR_ONLY_TOOLS] })
70
+ // 方法调用保留接收者(this === tools),与宿主 dsh-subagent 的 childCtx.tools.restrict 同形。
71
+ tools.restrict({ deny: [...DIRECTOR_ONLY_TOOLS] })
70
72
  } catch (error ) {
71
73
  // 工具层兜底失败不阻断会话:服务层 ownerContextFor 仍是权威闸门。
72
74
  logger?.warn?.(`dsh-team: 应用成员 bot 工具策略失败:${error?.message ?? error}`)
@@ -86,12 +88,13 @@ export function installTeamTools(ctx, service) {
86
88
  title: { type: 'string', description: 'Short actionable task title (new tasks; on re-dispatch it amends the card)' },
87
89
  description: { type: 'string', description: 'Self-contained instructions, constraints and acceptance criteria (new tasks; on re-dispatch it amends the card and the assignee is notified to correct course). Name the expected deliverable file paths inside the write scopes, and never instruct the bot to paste file contents into its delivery report — the report references paths, reviewers read the files' },
88
90
  priority: { type: 'string', enum: ['urgent', 'high', 'medium', 'low', 'none'], description: 'Task priority (new tasks and card amendment on re-dispatch)' },
89
- write_scopes: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative paths this task will modify (new tasks only); the scheduler runs tasks with disjoint scopes in parallel. Omit to parse a `写范围:`/`write_scopes:` line from the description instead' },
91
+ write_scopes: { type: 'array', items: { type: 'string' }, description: 'Workspace-relative paths this task will modify (new tasks only); the scheduler runs tasks with disjoint scopes in parallel. Keep it small: a task declaring more than maxWriteScopesPerTask (default 8) paths is rejected — split into subtask cards with parent_task_id and disjoint scopes instead. Omit to parse a `写范围:`/`write_scopes:` line from the description instead' },
90
92
  deliverables: { type: 'array', items: { type: 'string' }, description: 'Expected deliverable file paths, workspace-relative and inside the write scopes (new tasks; on re-dispatch it amends the card). The assignee references these paths in its delivery report instead of pasting file contents; reviewers read the files at these paths' },
91
93
  force_duplicate: { type: 'boolean', description: 'Escape hatch (new tasks only): skip the same-write-scope duplicate check when an unfinished task in this project already declares identical write scopes. Use only when a second task on the same paths is intentional; every use is audited as dispatch_force_duplicate' },
92
- time_budget_minutes: { type: 'integer', description: 'Required delivery time limit in minutes (new tasks only, 1-10080): injected into the task prompt, and the run is aborted when the budget expires. The effective timeout is the smaller of this budget and the global run timeout. Omit to take the priority-tier budget (urgent/high 45, medium 30, low/none 15 minutes); non-dispatch task creation falls back to env DSH_TEAM_TASK_TIME_BUDGET_MINUTES > stall-watchdog minutes > 20 minutes' },
94
+ time_budget_minutes: { type: 'integer', description: 'Required delivery time limit in minutes (new tasks only, 1-10080): injected into the task prompt, and the run is aborted when the budget expires. The effective timeout is the smaller of this budget and the global run timeout. Omit to take the priority-tier budget (urgent/high 90, medium 60, low/none 30 minutes); non-dispatch task creation falls back to env DSH_TEAM_TASK_TIME_BUDGET_MINUTES > stall-watchdog minutes > 40 minutes' },
93
95
  parent_task_id: { type: 'string', description: 'Nest the new task as a subtask under this main task id (new tasks only): pass it when the main item cannot be finished in this run or a new closing condition emerged, so follow-up work lands as a product-grade card instead of a verbal note; also pass it to split a large task into parallel subtask cards for speed (independent parts, disjoint write_scopes, so the cards run concurrently). Must reference an existing task in the same project; self-reference is rejected. The backend validates' },
94
96
  task: { type: 'string', description: 'Existing task to re-dispatch, as KEY-N (for example DEMO-3). Omit to create a new task' },
97
+ expected_version: { type: 'integer', description: 'Mutation fence (re-dispatch/amend only): the task card version you last saw (the `version` field of any card view). When the card has changed since (delivery, status transition, another edit), the write is refused and the refusal lists the most recent changes so you can re-decide in place; retry with the new expected_version, or omit to keep last-write-wins behavior' },
95
98
  sandbox: { type: 'string', enum: ['inherit', 'workspace-write', 'read-only'], default: 'inherit', description: 'Sandbox tier for this task\'s runs (new tasks and re-dispatch); default inherit = follow the assignee bot\'s configured file policy, so a development task is never tightened to read-only unless the card says so. inherit also clears any stored override on re-dispatch. workspace-write/read-only must not be wider than that configuration (tighten-only; every run of the task starts under the effective tier, recorded as a sandbox_mode run event). Use read-only to run a development task in review mode' },
96
99
  },
97
100
  required: ['assignee'],
@@ -266,11 +269,12 @@ export function installTeamTools(ctx, service) {
266
269
 
267
270
  ctx.tools.register({
268
271
  name: 'team_memory_list',
269
- description: 'List existing long-term memories in one scope (bot / project / team) for hygiene inspection: entries with short id, topic, updated time and a content preview, optionally filtered by topic substring. Director-only.',
272
+ description: 'List existing long-term memories in one scope (bot / project / team) for hygiene inspection: entries with short id, topic, updated time and a content preview, optionally filtered by topic substring. Every bot manages its own bot scope; project and team scopes are director-only.',
270
273
  parameters: {
271
274
  type: 'object',
272
275
  properties: {
273
276
  scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'Which memory scope to enumerate: bot = your own memories, project = this project, team = whole team. Default project' },
277
+ bot: { type: 'string', description: 'With scope=bot, target that bot (exact bot name or id) instead of yourself — use it to inspect a member bot\'s memories when its scope hits the cap' },
274
278
  topic: { type: 'string', description: 'Optional substring filter on the topic label' },
275
279
  limit: { type: 'integer', description: 'Max entries to return (1-200, default 50)' },
276
280
  },
@@ -289,11 +293,12 @@ export function installTeamTools(ctx, service) {
289
293
 
290
294
  ctx.tools.register({
291
295
  name: 'team_memory_write',
292
- description: 'Write a durable memory with same-name overwrite: an active memory with the same scope+topic is updated in place (revision bumps, event trail kept) instead of appending a duplicate entry; otherwise a new memory is created. Use it to refresh a wording to the latest final state instead of piling up near-duplicates. Scope rules: bot = your own, project = this project, team = whole team. Never store secrets or credentials. Director-only.',
296
+ description: 'Write a durable memory with same-name overwrite: an active memory with the same scope+topic is updated in place (revision bumps, event trail kept) instead of appending a duplicate entry; otherwise a new memory is created. Use it to refresh a wording to the latest final state instead of piling up near-duplicates. Scope rules: bot = your own (every bot), project = this project (director), team = whole team (director). Never store secrets or credentials.',
293
297
  parameters: {
294
298
  type: 'object',
295
299
  properties: {
296
300
  scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'bot: only you remember it; project: every project bot can use it; team: shared by the whole team (owner bots only)' },
301
+ bot: { type: 'string', description: 'With scope=bot, write into that bot\'s memories (exact bot name or id) instead of your own — use it for same-name-overwrite dedupe in a member bot\'s scope' },
297
302
  topic: { type: 'string', description: 'Short topic label; same topic in the same scope is overwritten in place' },
298
303
  content: { type: 'string', description: 'The durable memory, with enough context to be useful later' },
299
304
  },
@@ -310,11 +315,12 @@ export function installTeamTools(ctx, service) {
310
315
 
311
316
  ctx.tools.register({
312
317
  name: 'team_memory_cleanup',
313
- description: 'Batch-deprecate stale memories in one scope: matched entries are archived (terminal — excluded from recall), each keeps its memory_events trail, and the batch is audited as memory.cleanup with the cleaned entries listed. Criteria (at least one required): `task` archives a closed card\'s process records (its 任务 KEY-N / KEY-N 交付记录 topics; the task must already be done or canceled); `topics` archives the explicitly listed topics — use it for older wordings that conflict with a newer final decision; `before` archives every active entry whose updated_at is strictly older than the given ISO timestamp — the one-shot bulk criterion for legacy backlog convergence. `before` combines with `topics`/`task` as an AND filter. Do not archive entries recording the user\'s explicit decisions. Director-only.',
318
+ description: 'Batch-deprecate stale memories in one scope: matched entries are archived (terminal — excluded from recall), each keeps its memory_events trail, and the batch is audited as memory.cleanup with the cleaned entries listed. Criteria (at least one required): `task` archives a closed card\'s process records (its 任务 KEY-N / KEY-N 交付记录 topics; the task must already be done or canceled); `topics` archives the explicitly listed topics — use it for older wordings that conflict with a newer final decision; `before` archives every active entry whose updated_at is strictly older than the given ISO timestamp — the one-shot bulk criterion for legacy backlog convergence. `before` combines with `topics`/`task` as an AND filter. Do not archive entries recording the user\'s explicit decisions. Every bot manages its own bot scope; project and team scopes are director-only.',
314
319
  parameters: {
315
320
  type: 'object',
316
321
  properties: {
317
322
  scope: { type: 'string', enum: ['bot', 'project', 'team'], description: 'Which memory scope to clean: bot = your own, project = this project, team = whole team' },
323
+ bot: { type: 'string', description: 'With scope=bot, clean that bot\'s memories (exact bot name or id) instead of your own — the sanctioned path when a member bot\'s scope hits the cap and it cannot clean itself' },
318
324
  topics: { type: 'array', items: { type: 'string' }, description: 'Exact topic labels to archive in this scope' },
319
325
  task: { type: 'string', description: 'Closed card (KEY-N) whose process-record memories should be archived; rejected unless the task is done or canceled' },
320
326
  before: { type: 'string', description: 'ISO timestamp cutoff (e.g. 2026-01-01T00:00:00.000Z): archive every active entry in this scope with updated_at strictly before it. Required when neither topics nor task is given; combining with topics/task intersects the criteria' },
package/ui/app.js CHANGED
@@ -1,4 +1,4 @@
1
- import { state, STATUS, STATUS_ORDER, PRIORITY, PROPOSAL_STATUS, COLORS, COLOR_NAMES, BOT_STATUS, RUN_STATUS, RUN_KIND, CHAT_PAGE_SIZE, CHAT_ACTIVE_TASK_LIMIT, SKILL_STATUS, MEMORY_STATUS, PROPOSAL_KIND, TERMINAL_STATUS, CREATOR_TYPE, EFFORT, FILE_POLICY, DEFAULT_FILE_POLICY, VIEW_ACTION, NAV, SOLO_NAV } from './modules/state.js'
1
+ import { state, STATUS, STATUS_ORDER, PRIORITY, PROPOSAL_STATUS, COLORS, COLOR_NAMES, BOT_STATUS, RUN_STATUS, RUN_KIND, CHAT_PAGE_SIZE, CHAT_ACTIVE_TASK_LIMIT, SKILL_STATUS, MEMORY_STATUS, PROPOSAL_KIND, TERMINAL_STATUS, CREATOR_TYPE, EFFORT, FILE_POLICY, DEFAULT_FILE_POLICY, VIEW_ACTION, NAV, SOLO_NAV, runStatusLabel, runKindLabel } from './modules/state.js'
2
2
  import { icon } from './modules/icons.js'
3
3
  import { applyUiScale, applyUiTheme, initColorScheme, esc, attr, pathCode, costValue, clamp, botById, shortRefId, actorLabel, taskById, activeProject, inSoloContext, pageProject, activeBots, formatNumber, CURRENCY_SYMBOL, formatCost, timeAgo, formatTime, duration, avatar, statusPill, runDot, memberRunDot, runDotHtml, memorySource, toast, filePolicyOptions } from './modules/util.js'
4
4
  import { richText, mdPlainSummary, mdChatScope, mdImageChipTitle } from './modules/markdown.js'
@@ -199,7 +199,8 @@ function tabDot(view) {
199
199
  return false
200
200
  }
201
201
 
202
- // STATUS/RUN_STATUS/RUN_KIND 的渲染标签:表内有键走 t(),表外原样回落(保持旧 ?? 兜底语义)。
202
+ // STATUS 的渲染标签:表内有键走 t(),表外原样回落(保持旧 ?? 兜底语义;
203
+ // runStatus/runKind 同口径的 runStatusLabel/runKindLabel 已下沉 modules/state.js)。
203
204
  function statusLabel(status) {
204
205
  return STATUS[status] ? t('status.' + status) : status
205
206
  }
@@ -213,14 +214,6 @@ function sideRowStatusHtml(status) {
213
214
  return `<span class="side-row-status${live}">${esc(statusLabel(status))}</span>`
214
215
  }
215
216
 
216
- function runStatusLabel(status) {
217
- return RUN_STATUS[status] ? t('runStatus.' + status) : status
218
- }
219
-
220
- function runKindLabel(kind) {
221
- return RUN_KIND[kind] ? t('runKind.' + kind) : kind
222
- }
223
-
224
217
  function renderShell() {
225
218
  const data = state.data
226
219
  const inSolo = inSoloContext()
@@ -642,7 +635,11 @@ async function poll() {
642
635
  notifyNewApprovals(data?.approvals ?? [])
643
636
  return
644
637
  }
638
+ // 版本短路:loadState 在服务端版本未变时原引用返回,数据零变化——跳过整页重渲染
639
+ // 与通知重算(2.8s 空闲轮询从「全量取数+渲染」降为一次版本比对)。
640
+ const previousData = state.data
645
641
  await loadState(state.projectId, { quiet: true })
642
+ if (state.data === previousData) return
646
643
  // 渲染闸门(DSHBOTS-123):composer 静默窗内有输入或 IME 组词中才挡整页重建,
647
644
  // 其余输入控件维持原「焦点即挡」;被挡周期的取数已生效,下一周期自动补渲染。
648
645
  if (!pollRenderBlockedByFocus(document.activeElement, { composing: state.composerComposing, composerInputAt: state.composerInputAt })) render()
@@ -77,6 +77,8 @@ export default {
77
77
  // DSHBOTS-220: ui/modules copy
78
78
  "等待审批": "Waiting for approval",
79
79
  "已允许一次": "Allowed once",
80
+ // DSHBOTS-365: distinct pill text for rule-based auto-allow (decided_by=auto:rule:*)
81
+ "规则自动放行": "Auto-allowed by rule",
80
82
  "已拒绝": "Rejected",
81
83
  "已超时": "Timed out",
82
84
  "已取消": "Canceled",