dsh-team-bots 0.2.338 → 0.2.364

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.
package/README.md CHANGED
@@ -2,48 +2,110 @@
2
2
 
3
3
  [中文](docs/README.zh.md)
4
4
 
5
- DSH Team Bots is the npm package `dsh-team-bots`, a DSH (DeepSeek Harness) plugin that packs a collaborating crew of bots into one workspace: project group chats, a task board, write-scope parallel scheduling, memory and skills, usage and cost, plus a personal WeChat channel. Every run keeps a trajectory, duration, token count and cost.
5
+ `dsh-team-bots` is a DSH plugin that turns one workspace into a team: project group chats, a task board, write-scope parallel scheduling, shared memory and skills, approval cards, usage and cost, and a personal WeChat channel. Every run keeps its trajectory, duration, token count and cost.
6
6
 
7
- ![DSH Team Bots workspace](docs/assets/tasks.png)
7
+ ## Requirements
8
8
 
9
- ## Install
9
+ - Node.js ≥ 22.19
10
+ - the DSH CLI (`dsh`)
11
+
12
+ The plugin runs inside the DSH Web process. It has no standalone service and no port of its own.
10
13
 
11
- Node.js ≥ 22.19 and the DSH CLI are required; the plugin runs inside the DSH Web process — no standalone service or port.
14
+ ## Install
12
15
 
13
16
  ```sh
14
17
  dsh plugin --profile <name> add dsh-team-bots
15
- dsh --profile <name> # read the tokenised dsh web entry from the startup log
16
18
  ```
17
19
 
18
- The package resolves from the npm registry, so no `npm pack` or local tarball is needed; `npm run profile:install -- --profile <name>` does the same from a checkout.
20
+ From a checkout (packs the working tree and installs it into the profile):
21
+
22
+ ```sh
23
+ npm run profile:install -- --profile <name>
24
+ ```
25
+
26
+ Plugin files inside a profile are a snapshot. After changing code, reinstall — otherwise the page keeps serving the old build.
19
27
 
20
- ## Start
28
+ ## Open the workspace
21
29
 
22
30
  ```text
23
- http://<host>:<port>/ auto-login, straight into the team workspace
24
- http://<host>:<port>/api/dsh-team/ui the DSH Team Bots workspace (direct)
25
- http://<host>:<port>/index.html the native DSH web UI
31
+ http://<host>:<port>/ DSH web, auto-login into the team workspace
32
+ http://<host>:<port>/api/dsh-team/ui the team workspace itself
26
33
  ```
27
34
 
28
- The first visit to the home page exchanges the current startup token for a 30-day login cookie. Auto-login means **anyone who can reach the port becomes owner**, so listen on the local machine or a trusted network; public exposure needs an HTTPS reverse proxy that forwards Host and WebSocket correctly.
35
+ The first visit exchanges the current startup token for a 30-day login cookie. Auto-login means anyone who can reach the port becomes owner, so listen on the local machine or a trusted network; for public use put an HTTPS reverse proxy in front that forwards Host and WebSocket correctly.
36
+
37
+ ## What the workspace does
38
+
39
+ ### Group chats and dispatch
40
+
41
+ Every project is a group chat. A bot can also be addressed one-to-one in a dispatch view. Session bindings run in four lanes — task, solo, dm, project — so a group chat, a task run and a direct message never block each other.
42
+
43
+ ### Task board
44
+
45
+ States: backlog, todo, in progress, blocked, in review, done, canceled. A card carries assignee, priority, parent/child links, tags, write scopes, an optional time budget (a hard limit that aborts the run), comments, and its own usage. Rows are grouped by state and can be dragged onto another group to change status.
46
+
47
+ ### Write scopes and parallel scheduling
48
+
49
+ A card declares the paths it will write, relative to the project working directory. Two runs of the same project run in parallel only when both declare scopes and the path prefixes do not overlap; a card with no declared scope is treated as serial. An urgent card may be exempted from the queue — the exemption is written into the card's creation message rather than applied silently.
50
+
51
+ ### Memory, skills, evolution proposals
52
+
53
+ Memory entries are written, reviewed, frozen and archived by the owner, and are readable by every bot in the project. Skills come from a shared skill root plus per-project skills; changing them goes through a proposal, an approval and an apply, with a canary stage before promotion to full effect. The same path can change a bot's role instructions.
54
+
55
+ ### Approval and question cards
56
+
57
+ When a bot asks for a tool approval, a secret, or an answer, the workspace shows a card in the chat. The owner approves, denies or answers in place, and the decision is recorded on the card.
58
+
59
+ ### Usage and cost
60
+
61
+ The usage page breaks the numbers down by model, bot and project, exports CSV, and reads model prices from configuration. Run limits (timeout abort, no-progress watchdog, review idle threshold) and budgets are set per workspace.
62
+
63
+ ### Terminal, channels, secrets
64
+
65
+ A per-project terminal runs commands in the project directory. The WeChat channel binds by QR code and pushes task activity to the owner's WeChat. Secrets are scoped to the team or to one project; values are only ever shown as a fingerprint and are handed out as one-time runtime copies that expire.
29
66
 
30
67
  ## Configuration
31
68
 
32
- The two paths that matter are `DSH_TEAM_WORKSPACE` (team workspace root, default `~/.dsh/workspace/team-bots`) and `DSH_TEAM_DATA` (team database and run records, default `<workspace>/.data`); every other variable, its default and its resolution order (explicit env > value saved on the page > code default) live in `src/config.ts`.
69
+ | Variable | Default | Meaning |
70
+ | --- | --- | --- |
71
+ | `DSH_TEAM_WORKSPACE` | `~/.dsh/workspace/team-bots` | team workspace root |
72
+ | `DSH_TEAM_DATA` | `<workspace>/.data` | database and run records |
33
73
 
34
- Data under `DSH_TEAM_DATA` includes `team.sqlite`, `wechat-channel.sqlite`, `secret.key`, `memory/`, `messages/` and `secrets-runtime/` (burned on TTL expiry). Back up `secret.key` together with the data — without it the existing ciphertext cannot be decrypted.
74
+ Every other variable, its default, and its resolution order (explicit env > value saved in the workspace > code default) live in `src/config.ts`; `.env.example` lists the common ones. Do not put a `.env` file in the repository root — it would leak `DSH_*` into `npm test` and `npm run dev`.
35
75
 
36
- A template for the common variables lives in `.env.example`; **do not put a `.env` file in the repository root**, because that would leak `DSH_*` into `npm test` and `npm run dev`. Plugin files inside a profile are a snapshot: after changing code, reinstall or the page sticks at "connecting to the team space".
76
+ `DSH_TEAM_DATA` holds `team.sqlite`, `wechat-channel.sqlite`, `secret.key`, `memory/`, `messages/` and `secrets-runtime/`. Back up `secret.key` together with the data: without it the stored ciphertext cannot be decrypted.
37
77
 
38
- ## Screenshots
78
+ ## Develop
39
79
 
40
- Usage stats carry the summary window, the last 14 days of detail, a per-model / per-bot / per-project breakdown and a CSV export:
80
+ ```sh
81
+ npm install
82
+ npm run build # compile TypeScript into the shipped .js files
83
+ npm run typecheck
84
+ npm test # build, then node --test over tests/ and scripts/
85
+ npm run dev # local dev server on http://127.0.0.1:4317
86
+ npm run doctor # check node, dsh, paths and profile references
87
+ ```
41
88
 
42
- ![Usage stats](docs/assets/usage.png)
89
+ Additional harnesses: `npm run backup` / `npm run restore-check` for data, `npm run verify:agent-team` for the agent-team capability, `npm run load-test` and `npm run fault-test` for the runtime.
43
90
 
44
- The global configuration page keeps only the core groups; channels, secrets, version status and pricing rules live on their own top-level pages:
91
+ Repository layout:
92
+
93
+ ```text
94
+ ui/ the browser workspace (modules, styles, zh/en copy)
95
+ src/ HTTP API, database, runtime and domain services
96
+ src/services/ domain logic: chat, tasks, scheduler, memory, skills, approvals, usage
97
+ src/tools.ts the tool surface bots see (team_* tools)
98
+ scripts/ build, dev server, doctor, release, backup, test harnesses
99
+ tests/ node:test suites
100
+ ```
101
+
102
+ ## Release
103
+
104
+ ```sh
105
+ npm run release # add --dry-run to print the plan without touching anything
106
+ ```
45
107
 
46
- ![Global configuration](docs/assets/global-config-light.png)
108
+ The tool pushes `dev`, lands it on `main` (fast-forward when possible, otherwise a content snapshot), pushes `main` and the tag, then syncs `dev` back. Publishing uses npm OIDC trusted publishing — no `NPM_TOKEN` — and the workflow installs npm ≥ 11.5.1 before publishing.
47
109
 
48
110
  ## License
49
111
 
package/docs/README.zh.md CHANGED
@@ -2,49 +2,111 @@
2
2
 
3
3
  [English](../README.md)
4
4
 
5
- DSH Team Bots 是 npm 包 `dsh-team-bots`,一个 DSH(DeepSeek Harness)插件,把一整个协作的 bot 团队装进同一个工作区:项目群聊、任务板、按写范围并行调度、记忆与技能、用量与成本,外加一条个人微信通道。每个 run 都保留轨迹、时长、token 数和成本。
5
+ `dsh-team-bots` 是一个 DSH 插件,把一个工作区变成一支团队:项目群聊、任务板、写范围并行调度、共享记忆与技能、审批卡、用量与成本,以及个人微信通道。每次运行都留下轨迹、时长、token 数与成本。
6
6
 
7
- ![DSH Team Bots 工作区](assets/tasks.zh.png)
7
+ ## 运行前提
8
8
 
9
- ## 安装
9
+ - Node.js ≥ 22.19
10
+ - DSH 命令行(`dsh`)
11
+
12
+ 插件运行在 DSH Web 进程内,没有独立服务,也不单独占端口。
10
13
 
11
- 需要 Node.js ≥ 22.19 与 DSH CLI;插件跑在 DSH Web 进程里 —— 没有独立服务与端口。
14
+ ## 安装
12
15
 
13
16
  ```sh
14
17
  dsh plugin --profile <name> add dsh-team-bots
15
- dsh --profile <name> # 从启动日志里读带 token 的 dsh web 入口
16
18
  ```
17
19
 
18
- 包从 npm registry 解析,不需要 `npm pack` 或本地 tarball;在仓库里用 `npm run profile:install -- --profile <name>` 等价。
20
+ 从源码装(打包当前工作树并装进指定 profile):
21
+
22
+ ```sh
23
+ npm run profile:install -- --profile <name>
24
+ ```
25
+
26
+ profile 里的插件文件是一份快照。改完代码要重新安装,否则页面一直跑旧版本。
19
27
 
20
- ## 启动
28
+ ## 打开工作台
21
29
 
22
30
  ```text
23
- http://<host>:<port>/ 自动登录,直接进入团队工作区
24
- http://<host>:<port>/api/dsh-team/ui DSH Team Bots 工作区(直达)
25
- http://<host>:<port>/index.html DSH 原生 Web UI
31
+ http://<host>:<port>/ DSH Web 首页,自动登录进团队工作台
32
+ http://<host>:<port>/api/dsh-team/ui 团队工作台本身
26
33
  ```
27
34
 
28
- 首次访问首页会用当前启动 token 换一张 30 天登录 cookie。自动登录意味着**任何能访问到端口的人都是 owner**,所以请只监听本机或可信网络;要公网暴露,需要一个正确转发 Host 与 WebSocket 的 HTTPS 反向代理。
35
+ 首次访问会把当前启动 token 换成 30 天登录 cookie。自动登录意味着能访问该端口的人就是 owner,请只监听本机或可信网络;要对外暴露,前面放一层转发 Host 与 WebSocket 的 HTTPS 反向代理。
36
+
37
+ ## 工作台能做什么
38
+
39
+ ### 群聊与调度
40
+
41
+ 每个项目是一个群聊;单个 Bot 也可以被单独一对一调度。会话绑定分四道车道——task、solo、dm、project——群聊、任务运行和私信互不阻塞。
42
+
43
+ ### 任务板
44
+
45
+ 状态:待规划、待执行、进行中、受阻、待验收、已完成、已取消。一张卡带负责人、优先级、父子任务、标签、写范围、可选的时效要求(硬性时限,到期中止运行)、评论,以及本卡自己的用量。任务行按状态分组,可拖到别的分组直接改状态。
46
+
47
+ ### 写范围与并行调度
48
+
49
+ 每张卡声明自己会写哪些路径(相对项目工作目录)。同一项目下两个运行只有在双方都声明了写范围、且路径前缀互不重叠时才并行;没声明写范围的卡按串行处理。紧急卡可以豁免排队,但豁免会写进建卡消息,不做静默处理。
50
+
51
+ ### 记忆、技能与进化提案
52
+
53
+ 记忆由 owner 写入、复核、冻结与归档,项目内所有 Bot 都能读到。技能来自共享技能根目录加项目级技能;改动走提案 → 审批 → 落地,先灰度再转全量。同一条路径也能改 Bot 的角色指令。
29
54
 
30
- ## 配置要点
55
+ ### 审批卡与提问卡
31
56
 
32
- 真正要紧的两个路径是 `DSH_TEAM_WORKSPACE`(团队工作区根目录,缺省 `~/.dsh/workspace/team-bots`)和 `DSH_TEAM_DATA`(团队数据库与 run 记录,缺省 `<workspace>/.data`);其余变量、缺省值和解析顺序(显式 env > 页面保存值 > 代码缺省)都在 `src/config.ts`。
57
+ Bot 要工具审批、要密钥或要人回答时,工作台在聊天里出一张卡。owner 就地批准、拒绝或回答,结论记在卡上。
33
58
 
34
- `DSH_TEAM_DATA` 下的数据包括 `team.sqlite`、`wechat-channel.sqlite`、`secret.key`、`memory/`、`messages/` 和 `secrets-runtime/`(TTL 到期即焚)。备份时请把 `secret.key` 一起带走 —— 没有它,已有的密文永远解不开。
59
+ ### 用量与成本
35
60
 
36
- 常用变量的模板在 `.env.example`;**不要把 `.env` 放在仓库根目录**,否则 `DSH_*` 会漏进 `npm test` 和 `npm run dev`。profile 里的插件文件是快照:改了代码必须重装,否则页面会卡在「connecting to the team space」。
61
+ 用量页按模型、按 Bot、按项目拆分,可导出 CSV,模型价格来自配置。运行限制(超时中止、无进展看门狗、验收滞留阈值)与预算按工作区设置。
37
62
 
38
- ## 截图
63
+ ### 终端、通道与密钥
39
64
 
40
- 用量统计带汇总窗口、最近 14 天明细、按模型 / 按 bot / 按项目拆分和 CSV 导出:
65
+ 每个项目有终端,在项目目录里执行命令。微信通道扫码绑定后,把任务动态推给 owner 的微信。密钥分团队级与项目级,界面上只显示指纹,取值以一次性运行时副本下发,到期即失效。
41
66
 
42
- ![用量统计](assets/usage.zh.png)
67
+ ## 配置
43
68
 
44
- 全局配置页只保留核心分组;通道、密钥、版本状态与价格规则在各自的一级页:
69
+ | 变量 | 默认值 | 含义 |
70
+ | --- | --- | --- |
71
+ | `DSH_TEAM_WORKSPACE` | `~/.dsh/workspace/team-bots` | 团队工作区根目录 |
72
+ | `DSH_TEAM_DATA` | `<workspace>/.data` | 数据库与运行记录 |
73
+
74
+ 其余变量的默认值与解析顺序(显式环境变量 > 页面上保存的值 > 代码默认值)都写在 `src/config.ts`,常用项见 `.env.example`。不要在仓库根目录放 `.env`,否则 `DSH_*` 会泄进 `npm test` 和 `npm run dev`。
75
+
76
+ `DSH_TEAM_DATA` 下有 `team.sqlite`、`wechat-channel.sqlite`、`secret.key`、`memory/`、`messages/` 与 `secrets-runtime/`。备份时把 `secret.key` 和数据一起带走——没有它,已存的密文解不开。
77
+
78
+ ## 开发
79
+
80
+ ```sh
81
+ npm install
82
+ npm run build # 把 TypeScript 编译成发布的 .js
83
+ npm run typecheck
84
+ npm test # 先 build,再对 tests/ 与 scripts/ 跑 node --test
85
+ npm run dev # 本地开发服务器:http://127.0.0.1:4317
86
+ npm run doctor # 检查 node、dsh、路径与 profile 引用
87
+ ```
88
+
89
+ 另有几套工具:`npm run backup` / `npm run restore-check` 备份与校验数据,`npm run verify:agent-team` 验证 agent team 能力,`npm run load-test` 与 `npm run fault-test` 压运行时。
90
+
91
+ 仓库结构:
92
+
93
+ ```text
94
+ ui/ 浏览器端工作台(modules、styles、中英文案)
95
+ src/ HTTP 接口、数据库、运行时与领域服务
96
+ src/services/ 领域逻辑:chat、tasks、scheduler、memory、skills、approvals、usage
97
+ src/tools.ts Bot 看到的工具面(team_* 系列)
98
+ scripts/ 构建、开发服务器、doctor、发版、备份与测试工具
99
+ tests/ node:test 用例
100
+ ```
101
+
102
+ ## 发版
103
+
104
+ ```sh
105
+ npm run release # 加 --dry-run 可只打印计划,不做任何改动
106
+ ```
45
107
 
46
- ![全局配置](assets/global-config-light.zh.png)
108
+ 工具先把 `dev` 推上去,再把 dev 落到 `main`(能快进就快进,否则落一份内容快照),推 `main` 与 tag,最后把 `dev` 同步回来。发布走 npm OIDC trusted publishing,不用 `NPM_TOKEN`,工作流在发布前会把 npm 升到 ≥ 11.5.1。
47
109
 
48
- ## License
110
+ ## 许可
49
111
 
50
112
  Apache-2.0,见 `LICENSE` 与 `NOTICE`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-team-bots",
3
- "version": "0.2.338",
3
+ "version": "0.2.364",
4
4
  "description": "Project spaces, group chats, task boards, memory and usage for teams of DSH bots",
5
5
  "repository": {
6
6
  "type": "git",
@@ -41,6 +41,7 @@
41
41
  "pretest": "npm run build",
42
42
  "test": "node --test \"tests/*.test.js\" \"scripts/*.test.js\"",
43
43
  "release": "node scripts/release.mjs",
44
+ "finalize": "node scripts/finalize.mjs",
44
45
  "predev": "npm run build",
45
46
  "dev": "node scripts/dev-server.mjs",
46
47
  "prestart": "npm run build",
package/src/service.js CHANGED
@@ -23,6 +23,8 @@ import { botsMethods } from './services/bots.js'
23
23
  import { projectsMethods } from './services/projects.js'
24
24
  import { chatMethods } from './services/chat.js'
25
25
  import { tasksMethods } from './services/tasks.js'
26
+ import { taskDispatchMethods } from './services/task-dispatch.js'
27
+ import { taskRunMethods } from './services/task-runs.js'
26
28
  import { taskNotifyMethods } from './services/task-notify.js'
27
29
  import { notifyMethods } from './services/notify.js'
28
30
  import { taskReviewMethods } from './services/task-review.js'
@@ -88,6 +90,8 @@ defineMethods(TeamService.prototype, [
88
90
  projectsMethods,
89
91
  chatMethods,
90
92
  tasksMethods,
93
+ taskDispatchMethods,
94
+ taskRunMethods,
91
95
  taskNotifyMethods,
92
96
  notifyMethods,
93
97
  taskReviewMethods,
@@ -90,3 +90,37 @@ export function needsSynthesizedBackoff(error) {
90
90
  if (isQuotaExhausted(error)) return false
91
91
  return isRateLimitError(error) && !(Number(error?.retryAfterMs) > 0)
92
92
  }
93
+
94
+ // ── 网络瞬态失败(DSHBOTS-266)──────────────────────────────────────────────
95
+ // provider 网络抖动(连接重置/超时/5xx 等)是过性失败:退避后重打大概率自愈,
96
+ // 直接常规失败转 blocked 等 owner 手动重试是误伤。判定只接住限流/额度分类漏掉的
97
+ // 过性错误——优先级:额度耗尽 > 限流码 > 瞬态(429 仍走限流路径吃服务端 retry_after)。
98
+ // 正则参考 dsh-superagent-prototype executor/dsh.ts 的 PASSING(去掉 429 与 rate limit:
99
+ // 那两个信号归限流分类,瞬态不抢)。错误码与错误正文双重匹配,任一命中即可。
100
+ // 数字锚点只对数字设界:HTTP_503 / status 502 命中,1408 / 75038 之类的长数字不误伤。
101
+ export const TRANSIENT_PATTERN = /(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|EPIPE|UND_ERR|socket hang up|fetch failed|overloaded|(?<!\d)408(?!\d)|(?<!\d)50[0-4](?!\d))/i
102
+
103
+ // 瞬态退避时长:15s / 30s / 60s(15s × 2^(n-1),attempt 缺失或非法按 1 计)。
104
+ // 比限流链(1min 起步)短——网络抖动通常秒级自愈;重试上限复用 MAX_RATE_LIMIT_RETRIES=3。
105
+ export function transientBackoffMs(attempt) {
106
+ const n = Math.max(1, Number(attempt) || 1)
107
+ return 15_000 * 2 ** (n - 1)
108
+ }
109
+
110
+ // 这次失败是不是网络瞬态。限流码与额度耗尽先排除(各自走既有路径)。
111
+ export function isTransientNetworkError(error) {
112
+ if (isRateLimitError(error)) return false
113
+ if (isQuotaExhausted(error)) return false
114
+ return TRANSIENT_PATTERN.test(`${String(error?.code ?? '')} ${String(error?.message ?? '')}`)
115
+ }
116
+
117
+ // 瞬态失败且 provider 没给可用的 Retry-After → 需要合成指数退避(真 Retry-After 优先)。
118
+ export function needsTransientBackoff(error) {
119
+ return isTransientNetworkError(error) && !(Number(error?.retryAfterMs) > 0)
120
+ }
121
+
122
+ // 这次失败是否进「退避等待 → plan_retry 到期派生」既有重试链(限流或网络瞬态)。
123
+ export function isRetryChainError(error) {
124
+ if (isQuotaExhausted(error)) return false
125
+ return isRateLimitError(error) || isTransientNetworkError(error)
126
+ }
@@ -9,7 +9,99 @@
9
9
  import { badRequest, notFound } from '../errors.js'
10
10
  import { text } from '../util.js'
11
11
 
12
+ // ── 防循环三上限(DSHBOTS-267,配置默认值写死常量,KISS)──────────────────
13
+ // 真实事故背书:伙伴回执淹没主对话、委派续跑近百轮重发已推翻目标。
14
+ // ① 单 run 内经 notify/chat 产生的伙伴提醒(按去重目标计条数)上限:超出静默丢弃并记日志;
15
+ // ② 同类提醒事件(同 run + 同目标 bot)每日次数上限:超出静默丢弃并记日志。
16
+ // 每条放行的提醒在 run_events 记 type='partner_notice',message 存 partner_notice:<目标bot>,
17
+ // 两条上限都从这张事件流计数,不新建并行状态表。
18
+ export const RUN_PARTNER_NOTICE_CAP = 3
19
+ export const PARTNER_NOTICE_DAILY_CAP = 5
20
+
21
+ // ── 滞留阈值兜底(DSHBOTS-280):in_review/blocked 非施工状态的超时提醒 ─────────
22
+ // 只提醒不自动处置:不自动关单、不自动转状态、不重派,验收与解阻由项目总监闭环(DSHBOTS-281 口径)。
23
+ export const STALE_REVIEW_HOURS = 24
24
+ export const STALE_BLOCKED_HOURS = 48
25
+ export const STALE_CARD_NOTICE_PREFIX = '【滞留提醒】'
26
+
27
+ // 滞留判定(纯函数,供 scheduler 扫描与守门测试共用;阈值内/外两向可测)。
28
+ // 基准时间 = tasks.updated_at:blocked 无专门「进入 blocked」时间戳列,用 updated_at 近似
29
+ // ——转 blocked 走 updateTask 必刷 updated_at,其后任何卡面更新同样只推迟提醒,不会漏报。
30
+ export function staleCardHit({ status, updated_at, now = Date.now() } = {} ) {
31
+ if (status !== 'in_review' && status !== 'blocked') return null
32
+ const baseMs = updated_at ? new Date(updated_at).getTime() : NaN
33
+ if (!Number.isFinite(baseMs)) return null
34
+ const hours = (now - baseMs) / 3_600_000
35
+ const threshold = status === 'in_review' ? STALE_REVIEW_HOURS : STALE_BLOCKED_HOURS
36
+ return hours > threshold ? { status, hours, threshold } : null
37
+ }
38
+
39
+ // D-269 口径文案 = 原因(滞留时长+阈值)+ 点名总监的处置方向(DSHBOTS-281:处置归项目
40
+ // 总监自行闭环,不写「owner 可改/可用」转接话术;blocked 侧重派即自动重置死线窗口)。
41
+ export function staleCardNoticeBody({ identifier, status, hours } = {} ) {
42
+ const idle = Math.floor(hours)
43
+ return status === 'in_review'
44
+ ? `${STALE_CARD_NOTICE_PREFIX}${identifier} 待验收已滞留 ${idle} 小时(阈值 ${STALE_REVIEW_HOURS}h):待总监验收收口(accept/return)。`
45
+ : `${STALE_CARD_NOTICE_PREFIX}${identifier} 受阻已滞留 ${idle} 小时(阈值 ${STALE_BLOCKED_HOURS}h):待总监解阻/收口(重派即自动重置死线窗口)。`
46
+ }
47
+
12
48
  export const notifyMethods = {
49
+ // 伙伴提醒配额闸(DSHBOTS-267):放行返回 true;超限静默丢弃(warn 留痕)返回 false。
50
+ // run 归属不到(发起方无活跃运行)时不设限——空闲/人工会话的零星通知无循环风险。
51
+ allowPartnerNotice(runId, targetId) {
52
+ if (!runId || !targetId) return true
53
+ const distinctTargets = this.store.get(
54
+ "SELECT COUNT(DISTINCT message) AS n FROM run_events WHERE run_id = ? AND type = 'partner_notice'",
55
+ runId,
56
+ ).n
57
+ if (distinctTargets >= RUN_PARTNER_NOTICE_CAP) {
58
+ this.logger.warn?.('dsh-team: 伙伴提醒超单 run 上限(%s 个目标),静默丢弃:run=%s target=%s', RUN_PARTNER_NOTICE_CAP, runId, targetId)
59
+ return false
60
+ }
61
+ const todayCount = this.store.get(
62
+ "SELECT COUNT(*) AS n FROM run_events WHERE run_id = ? AND type = 'partner_notice' AND message = ? AND date(created_at) = date('now')",
63
+ runId, `partner_notice:${targetId}`,
64
+ ).n
65
+ if (todayCount >= PARTNER_NOTICE_DAILY_CAP) {
66
+ this.logger.warn?.('dsh-team: 伙伴提醒超每日上限(%s 次/日),静默丢弃:run=%s target=%s', PARTNER_NOTICE_DAILY_CAP, runId, targetId)
67
+ return false
68
+ }
69
+ return true
70
+ },
71
+
72
+ // 记一条放行的伙伴提醒事件(配额闸通过后调用;chat 唤醒路径共用同一事件流)。
73
+ recordPartnerNotice(runId, targetId) {
74
+ if (!runId || !targetId) return
75
+ this.insertRunEvent(runId, 'partner_notice', `partner_notice:${targetId}`)
76
+ },
77
+
78
+ // 滞留提醒投递(DSHBOTS-280):等价 owner 通知通道——与 D-274 死线升级同款
79
+ // (insertMessage 系统留痕进任务线程 + mentions 点名项目 owner)。
80
+ // 防重=同卡每日 ≤1 条,以当日已有同前缀系统留痕为准,超限静默(只 warn 不投递)。
81
+ // 口径说明:D-267 配额闸(allowPartnerNotice)按 run_events type='partner_notice'
82
+ // 的 run 维度计数,run_id 非空挂不上无 run 的 scheduler 扫描;带 run 上下文的
83
+ // notifyMemberFromBot 路径照旧走同一配额流,本扫描路径的防重落点即消息留痕流。
84
+ notifyStaleCardOwner({ project, task, hit }) {
85
+ const identifier = `${project.key}-${task.number}`
86
+ const already = this.store.get(
87
+ "SELECT id FROM messages WHERE task_id = ? AND sender_type = 'system' AND body LIKE ? AND date(created_at) = date('now') LIMIT 1",
88
+ task.id, `${STALE_CARD_NOTICE_PREFIX}%`,
89
+ )
90
+ if (already) {
91
+ this.logger.warn?.('dsh-team: 滞留提醒同卡每日上限(1 条),静默跳过:%s', identifier)
92
+ return false
93
+ }
94
+ this.insertMessage({
95
+ projectId: project.id,
96
+ senderType: 'system',
97
+ senderId: 'system',
98
+ taskId: task.id,
99
+ body: staleCardNoticeBody({ identifier, status: hit.status, hours: hit.hours }),
100
+ mentions: project.owner_bot_id ? [project.owner_bot_id] : [],
101
+ })
102
+ return true
103
+ },
104
+
13
105
  // 工具入口:target=member 通知本项目另一成员;target=task 提醒本项目执行中任务。
14
106
  // 鉴权:调用者必须是本项目成员(memberContextFor),目标成员/任务都锁在本项目内,
15
107
  // 跨项目 ref 一律解析不到(notFound),不泄露他项目是否存在同名目标。
@@ -32,6 +124,18 @@ export const notifyMethods = {
32
124
  .find(member => member.name.toLowerCase() === name.toLowerCase())
33
125
  if (!target) throw notFound(`项目 ${project.name} 里没有叫 ${memberName} 的成员 Bot`)
34
126
  if (target.id === from.id) throw badRequest('不能给自己发通知')
127
+ // 暂停/不可用目标不投递(DSHBOTS-262):通知即唤醒信号,暂停中先恢复再通知。
128
+ if (target.status === 'paused') throw badRequest(`Bot ${target.name} 已暂停,先恢复再通知`)
129
+ if (target.status !== 'active') throw badRequest(`Bot ${target.name} 当前不可用(${target.status})`)
130
+ // DSHBOTS-267 防循环上限:归属发起方当前活跃运行,配额闸不通过即静默丢弃(不落留痕不投递)。
131
+ const activeRun = this.store.get(
132
+ "SELECT id FROM runs WHERE bot_id = ? AND project_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1",
133
+ from.id, project.id,
134
+ )
135
+ if (!this.allowPartnerNotice(activeRun?.id, target.id)) {
136
+ return `伙伴提醒已达防循环上限,本次已静默丢弃(详见运行日志)。`
137
+ }
138
+ this.recordPartnerNotice(activeRun?.id, target.id)
35
139
  const notice = `【通知】${from.name}:${body}`
36
140
  const messageId = this.insertMessage({
37
141
  projectId: project.id,
@@ -72,6 +176,26 @@ export const notifyMethods = {
72
176
  async notifyTaskFromBot({ project, from, ref, body }) {
73
177
  const task = this.resolveBotTask(project, ref)
74
178
  const identifier = `${project.key}-${task.number}`
179
+ // 负责人暂停/不可用时提醒不投递(DSHBOTS-262):提醒即唤醒信号,暂停中先恢复再提醒。
180
+ if (task.assignee_bot_id) {
181
+ const assignee = this.store.get('SELECT name, status FROM bots WHERE id = ?', task.assignee_bot_id)
182
+ if (assignee?.status === 'paused') throw badRequest(`任务 ${identifier} 负责人 ${assignee.name} 已暂停,先恢复再提醒`)
183
+ if (!assignee || assignee.status !== 'active') throw badRequest(`任务 ${identifier} 负责人当前不可用`)
184
+ }
185
+ // DSHBOTS-267 单跟进者在途幂等:每张任务同时只允许一个跟进提醒在途。
186
+ // 在途判定=最近一条任务提醒落库后,该任务没有启动过新运行(提醒尚未被任何运行消费);
187
+ // 重复提醒静默吸收(不落新留痕、不注入、不计新),warn 留痕。
188
+ const lastNotice = this.store.get(
189
+ "SELECT created_at FROM messages WHERE task_id = ? AND sender_type = 'bot' AND body LIKE '【任务提醒】%' ORDER BY created_at DESC, rowid DESC LIMIT 1",
190
+ task.id,
191
+ )
192
+ if (lastNotice && !this.store.get(
193
+ 'SELECT id FROM runs WHERE task_id = ? AND started_at > ? LIMIT 1',
194
+ task.id, lastNotice.created_at,
195
+ )) {
196
+ this.logger.warn?.('dsh-team: 任务 %s 已有在途跟进提醒,重复提醒静默吸收', identifier)
197
+ return `任务 ${identifier} 已有在途跟进提醒,本次重复未投递(幂等去重,不计数)。`
198
+ }
75
199
  const notice = `【任务提醒】${from.name}:${body}`
76
200
  const messageId = this.insertMessage({
77
201
  projectId: project.id,
@@ -10,6 +10,29 @@ import { publishSkill, rollbackSkill, skillSnapshot, stageSkill, syncSkills } fr
10
10
  import { scanProjectSkills } from '../project-skills.js'
11
11
  import { id, jsonParse, nowIso, parseDisabledSkills, sha256, slugify, text } from '../util.js'
12
12
 
13
+ // DSHBOTS-271 融合稿闸门:进化 bot_update 的 instructions 必须是「原指令+新增内容」的融合稿,
14
+ // 纯替换稿会把原提示词整体顶掉。保留率 = 原 instructions 的非空行(trim 后)在提案稿
15
+ // 行集合中的保留占比;低于阈值即拒绝(原因+替代指引,D-269 口径)。
16
+ // 原 instructions 为空(首次立指令)没有可保留内容,保留率恒为 1,直接放行并在 diff 留痕。
17
+ export const MERGE_KEEP_RATIO = 0.6
18
+ export const MERGE_DRAFT_GUIDANCE = '进化指令必须是原指令+新增内容的融合稿:保留原有指令全文再写改动,不是全新替换稿也不是增量补丁'
19
+
20
+ export function mergeKeepRatio(original , proposed ) {
21
+ const originLines = String(original ?? '').split('\n').map(line => line.trim()).filter(Boolean)
22
+ if (!originLines.length) return 1
23
+ const proposedLines = new Set(String(proposed ?? '').split('\n').map(line => line.trim()).filter(Boolean))
24
+ const kept = originLines.filter(line => proposedLines.has(line)).length
25
+ return kept / originLines.length
26
+ }
27
+
28
+ // 创建侧与应用侧(applyProposal 审批落地前)共用同一闸门函数,防创建后 bots.instructions
29
+ // 已被 updateBot 直改通道改写、或绕过创建路径提交的纯替换稿落地。
30
+ export function assertMergeDraft(original , proposed ) {
31
+ const ratio = mergeKeepRatio(original, proposed)
32
+ if (ratio >= MERGE_KEEP_RATIO) return ratio
33
+ throw badRequest(`原指令保留率 ${(ratio * 100).toFixed(0)}%,低于 ${MERGE_KEEP_RATIO * 100}%:${MERGE_DRAFT_GUIDANCE}`)
34
+ }
35
+
13
36
 
14
37
 
15
38
  export const proposalsMethods = {
@@ -24,6 +47,10 @@ export const proposalsMethods = {
24
47
  }
25
48
  if (kind === 'skill' && !input.payload?.content) throw badRequest('技能提案必须包含内容')
26
49
  const payload = input.payload ?? {}
50
+ // 融合稿闸门(DSHBOTS-271):bot_update 带 instructions 时按当前原稿校验保留率;skill 提案不经过此闸门。
51
+ if (kind === 'bot_update' && payload.instructions !== undefined) {
52
+ assertMergeDraft(this.botRow(input.botId).instructions, payload.instructions)
53
+ }
27
54
  const canary = this.proposalCanary(input, kind)
28
55
  const diff = kind === 'bot_update' ? this.botProposalDiff(input.botId, payload) : this.skillProposalDiff(payload)
29
56
  const proposalId = id('prop')
@@ -51,7 +78,10 @@ export const proposalsMethods = {
51
78
  if (payload[field] === undefined) continue
52
79
  const before = bot[field] ?? null
53
80
  if (String(before ?? '') === String(payload[field] ?? '')) continue
54
- diff[field] = { from: before, to: payload[field] }
81
+ const entry = { from: before, to: payload[field] }
82
+ // 首次立指令留痕(DSHBOTS-271):原 instructions 为空时融合闸门放行,diff 标记首立。
83
+ if (field === 'instructions' && !String(before ?? '').trim()) entry.firstInstructions = true
84
+ diff[field] = entry
55
85
  }
56
86
  return diff
57
87
  },
@@ -135,6 +165,11 @@ export const proposalsMethods = {
135
165
  },
136
166
  async applyProposal(proposal, payload, canary, actor) {
137
167
  if (proposal.kind === 'bot_update') {
168
+ // 应用侧复核(DSHBOTS-271):审批落地前按 bots.instructions 当前值重跑同一闸门——
169
+ // 创建提案后原指令可能已被 updateBot 直改通道改写,此处防过期的融合稿或绕过创建路径的纯替换稿落地。
170
+ if (payload.instructions !== undefined) {
171
+ assertMergeDraft(this.botRow(proposal.bot_id).instructions, payload.instructions)
172
+ }
138
173
  await this.updateBot(proposal.bot_id, {
139
174
  ...(payload.role !== undefined ? { role: payload.role } : {}),
140
175
  ...(payload.instructions !== undefined ? { instructions: payload.instructions } : {}),