dsh-team-bots 0.2.338 → 0.2.347
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 +81 -19
- package/docs/README.zh.md +83 -21
- package/package.json +1 -1
- package/src/service.js +4 -0
- package/src/services/backoff.js +34 -0
- package/src/services/notify.js +70 -0
- package/src/services/run-finish.js +72 -15
- package/src/services/scheduler.js +7 -6
- package/src/services/task-dispatch.js +315 -0
- package/src/services/task-notify.js +6 -4
- package/src/services/task-runs.js +179 -0
- package/src/services/tasks.js +8 -465
- package/ui/app.js +1 -1
- package/ui/i18n/en/chat.js +1 -1
- package/ui/i18n/en/common.js +0 -2
- package/ui/i18n/en/nav.js +0 -1
- package/ui/i18n/en/settings.js +2 -4
- package/ui/i18n/en/tasks.js +1 -4
- package/ui/i18n/en/wechat.js +1 -2
- package/ui/i18n/zh/chat.js +1 -1
- package/ui/i18n/zh/common.js +0 -2
- package/ui/i18n/zh/nav.js +0 -1
- package/ui/i18n/zh/settings.js +2 -4
- package/ui/i18n/zh/tasks.js +1 -4
- package/ui/i18n/zh/wechat.js +1 -2
- package/ui/modules/cards.js +1 -1
- package/ui/modules/global-pages.js +2 -4
- package/ui/modules/modal-forms.js +3 -3
- package/ui/modules/tasks.js +2 -3
- package/ui/styles/global-config.css +0 -3
|
@@ -7,7 +7,7 @@ import { effectiveRunLimits } from '../config.js'
|
|
|
7
7
|
import { badRequest } from '../errors.js'
|
|
8
8
|
import { applyRetention, reconcileUsage } from '../usage-reconcile.js'
|
|
9
9
|
import { id, jsonParse, nowIso, text } from '../util.js'
|
|
10
|
-
import { MAX_RATE_LIMIT_RETRIES,
|
|
10
|
+
import { MAX_RATE_LIMIT_RETRIES, isQuotaExhausted, isRetryChainError } from './backoff.js'
|
|
11
11
|
import { ensureTaskRelationsSchema, unsatisfiedBlockedDeps } from './task-relations.js'
|
|
12
12
|
import { effectiveWriteScopes, writeScopesOverlap } from './write-scopes.js'
|
|
13
13
|
import { runReviewWatchdog } from './review-watchdog.js'
|
|
@@ -398,9 +398,10 @@ export const schedulerMethods = {
|
|
|
398
398
|
}
|
|
399
399
|
},
|
|
400
400
|
// 限流失败的自动重试(DSHBOTS-24;DSHBOTS-38 放开到 3 次并支持合成退避):
|
|
401
|
-
// 失败 run 带 retry_after_ms(provider 真发过 Retry-After
|
|
402
|
-
//
|
|
403
|
-
//
|
|
401
|
+
// 失败 run 带 retry_after_ms(provider 真发过 Retry-After,或限流/瞬态无头时 finishRun 合成的指数退避),
|
|
402
|
+
// 到期派生一次新运行。重试链最多跑到 attempt=3(1→2→3),之后转常规失败处置;
|
|
403
|
+
// DSHBOTS-266:链内错误判定移到下方 JS——限流码集合之外,网络瞬态失败(ECONNRESET/5xx/408
|
|
404
|
+
// 等,错误码/正文双匹配,见 backoff.ts 的 isRetryChainError)同样进本路径;SQL 表达不了该正则。
|
|
404
405
|
// 只针对任务运行——solo/私信运行显示 plan_wait 状态但不自动派生,避免对同一个对话者重复发信。
|
|
405
406
|
// 过期超过 24h 视为时过境迁不派生(服务停摆/长期搁置后不补跑旧任务)。
|
|
406
407
|
// 幂等闸:task_id 非空 + 原 run 无 plan_retry 事件;idempotency_key UNIQUE 兜底并发 tick。
|
|
@@ -410,15 +411,15 @@ export const schedulerMethods = {
|
|
|
410
411
|
`SELECT r.* FROM runs r
|
|
411
412
|
WHERE r.status = 'failed' AND r.retry_after_ms IS NOT NULL
|
|
412
413
|
AND r.task_id IS NOT NULL AND r.attempt < ${MAX_RATE_LIMIT_RETRIES}
|
|
413
|
-
AND r.error_code IN (${[...RATE_LIMIT_CODES].map(() => '?').join(', ')})
|
|
414
414
|
AND CAST(strftime('%s', COALESCE(r.ended_at, r.queued_at)) AS REAL) + r.retry_after_ms / 1000.0
|
|
415
415
|
<= CAST(strftime('%s', 'now') AS REAL)
|
|
416
416
|
AND CAST(strftime('%s', COALESCE(r.ended_at, r.queued_at)) AS REAL) + r.retry_after_ms / 1000.0
|
|
417
417
|
> CAST(strftime('%s', 'now') AS REAL) - ${PLAN_RETRY_MAX_LATE_SECONDS}
|
|
418
418
|
AND NOT EXISTS(SELECT 1 FROM run_events e WHERE e.run_id = r.id AND e.type = 'plan_retry')`,
|
|
419
|
-
...RATE_LIMIT_CODES,
|
|
420
419
|
)
|
|
421
420
|
for (const run of expired) {
|
|
421
|
+
// DSHBOTS-266:重试链判定(限流码 ∪ 网络瞬态)在 JS 做;非链内错误码不派生(现状不变)。
|
|
422
|
+
if (!isRetryChainError({ code: run.error_code, message: run.error_message })) continue
|
|
422
423
|
// DSHBOTS-99:额度耗尽(已达到限额)的运行不再自动派生重试——额度窗口用尽时重打主模型
|
|
423
424
|
// 只会再撞一次额度,任务已经转受阻,不能让它自己空转。
|
|
424
425
|
// 备用链上的运行同理:每条链只切一次备用,plan_retry 派生出来的是主模型运行,等于绕开限额口径。
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
// src/services/task-dispatch.js —— 任务派单与改派域
|
|
2
|
+
// 覆盖:派发门禁(assertDispatchTarget)、派单/重派(assignTask / assignFromBot)、
|
|
3
|
+
// 看板拖拽联动(transitionTask / applyBoardDragDirective)、总监强制受阻(forceBlockTask)、
|
|
4
|
+
// Bot 会话入口(forceBlockFromBot)与派单辅助(写范围清洗/重复卡检测/任务号解析/owner 上下文)。
|
|
5
|
+
// 任务建档、状态流转与视图见 ./tasks.js。
|
|
6
|
+
// 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.js 的 defineMethods 调用)。
|
|
7
|
+
|
|
8
|
+
import { badRequest, conflict, forbidden, notFound } from '../errors.js'
|
|
9
|
+
import { nowIso } from '../util.js'
|
|
10
|
+
import { filterIgnoredWriteScopes, parseWriteScopes, parseWriteScopesFromDescription, readWriteScopes } from './write-scopes.js'
|
|
11
|
+
import { resolveSandboxOverride } from './file-policy.js'
|
|
12
|
+
import { ensureTaskSandboxSchema } from './task-sandbox-schema.js'
|
|
13
|
+
|
|
14
|
+
export const taskDispatchMethods = {
|
|
15
|
+
// 派发门禁(DSHBOTS-262):暂停中的 Bot 不接新卡——新建派单、改派、重派一律拒绝,
|
|
16
|
+
// 先恢复(bot status → active)再派;归档/移除等其余不可用态沿用 assertMember 既有口径。
|
|
17
|
+
assertDispatchTarget(projectId, botId) {
|
|
18
|
+
const bot = this.store.get('SELECT name, status FROM bots WHERE id = ?', botId)
|
|
19
|
+
if (bot?.status === 'paused') throw badRequest(`Bot ${bot.name} 已暂停,先恢复再派卡`)
|
|
20
|
+
this.assertMember(projectId, botId)
|
|
21
|
+
},
|
|
22
|
+
// sandboxOverride 选项(DSHBOTS-156):undefined=不动(重派未传 sandbox 时保留旧覆盖);
|
|
23
|
+
// null=显式清掉回落 bot 配置档(重派传 sandbox='inherit');字符串=收紧档(派发入口已校验)。
|
|
24
|
+
async assignTask(taskId, botId, actor = this.actor(), { autoStart = true, sandboxOverride } = {} ) {
|
|
25
|
+
const task = this.taskRow(taskId)
|
|
26
|
+
const project = this.projectRow(task.project_id)
|
|
27
|
+
this.assertDispatchTarget(project.id, botId)
|
|
28
|
+
const active = this.store.get(
|
|
29
|
+
"SELECT id, kind FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
|
|
30
|
+
taskId,
|
|
31
|
+
)
|
|
32
|
+
// 换负责人闸门(DSHBOTS-169):queued 占位运行(死队列,永远不会被领取)不是执行中,
|
|
33
|
+
// 不再阻断改派——事务内按 SUPERSEDED 口径清掉后放行;只有 running 的任务运行照旧阻断
|
|
34
|
+
// (文案不变)。同负责人重派不走此闸,行为不变。
|
|
35
|
+
const reassigning = task.assignee_bot_id !== botId
|
|
36
|
+
if (reassigning && this.store.get(
|
|
37
|
+
"SELECT id FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'running' LIMIT 1",
|
|
38
|
+
taskId,
|
|
39
|
+
)) throw conflict('任务有正在执行的运行,不能更换负责人')
|
|
40
|
+
const supersedeQueued = reassigning && !!this.store.get(
|
|
41
|
+
"SELECT id FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'queued' LIMIT 1",
|
|
42
|
+
taskId,
|
|
43
|
+
)
|
|
44
|
+
ensureTaskSandboxSchema(this.store)
|
|
45
|
+
const sandboxTouched = sandboxOverride !== undefined
|
|
46
|
+
// 存量 NULL 预算卡补挂(DSHBOTS-198):COALESCE 只补空,显式已设的卡不覆盖。
|
|
47
|
+
const defaultTimeBudget = this.defaultTaskTimeBudget()
|
|
48
|
+
this.store.transaction(() => {
|
|
49
|
+
// queued 占位清理与改派同事务(DSHBOTS-169):SUPERSEDED 不进任务执行历史,run 事件可审计。
|
|
50
|
+
// 助手是同步函数(体内无 await),抛错会让整个事务回滚,不会留下「改派已生效但占位还在」的半成品。
|
|
51
|
+
if (supersedeQueued) this.cancelSupersededQueuedRuns(taskId)
|
|
52
|
+
this.store.run(
|
|
53
|
+
`UPDATE tasks SET assignee_bot_id = ?, review_target = ?,
|
|
54
|
+
status = CASE WHEN status IN ('backlog', 'blocked') THEN 'todo' ELSE status END,
|
|
55
|
+
time_budget_minutes = COALESCE(time_budget_minutes, ?),
|
|
56
|
+
version = version + 1, updated_at = ?${sandboxTouched ? ', sandbox_override = ?' : ''} WHERE id = ?`,
|
|
57
|
+
...(sandboxTouched
|
|
58
|
+
? [botId, actor.type === 'bot' ? 'owner_bot' : 'user', defaultTimeBudget, nowIso(), sandboxOverride ?? null, taskId]
|
|
59
|
+
: [botId, actor.type === 'bot' ? 'owner_bot' : 'user', defaultTimeBudget, nowIso(), taskId]),
|
|
60
|
+
)
|
|
61
|
+
this.addTaskEvent(taskId, 'assigned', actor, {
|
|
62
|
+
botId,
|
|
63
|
+
...(sandboxTouched && { sandbox: sandboxOverride ?? 'inherit' }),
|
|
64
|
+
})
|
|
65
|
+
this.audit(actor, 'task.assign', 'task', taskId, { botId, ...(sandboxTouched && { sandbox: sandboxOverride ?? 'inherit' }) })
|
|
66
|
+
})
|
|
67
|
+
// 总监bot的验收/受阻处理运行本身占用任务的唯一活动运行名额,
|
|
68
|
+
// 此时由 finishRun 的收尾逻辑负责重新排队执行,这里跳过。
|
|
69
|
+
// 换负责人清掉 queued 占位后名额已空:重算判定才会按新负责人重排 task_run(DSHBOTS-169)。
|
|
70
|
+
// 幂等键:task_run 是先写者赢闸(ON CONFLICT DO NOTHING 且撞键不再 applyOutboxRow),
|
|
71
|
+
// 稳定键 task:<id>:assigned 会在再次改派时撞上历史 delivered 行而被静默吞掉、排不出新运行
|
|
72
|
+
// (不限清 queued 占位场景,无活跃运行的改派同样会写键)。凡换负责人一律带事务内单调自增
|
|
73
|
+
// 的 task.version 后缀(确定性、跨改派不碰撞);同负责人重派保持稳定键,slotHeld 已提供幂等。
|
|
74
|
+
const slotHeld = supersedeQueued
|
|
75
|
+
? this.store.get(
|
|
76
|
+
"SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
|
|
77
|
+
taskId,
|
|
78
|
+
)
|
|
79
|
+
: active
|
|
80
|
+
if (!slotHeld) {
|
|
81
|
+
const assignedVersion = reassigning ? this.taskRow(taskId).version : null
|
|
82
|
+
this.enqueueOutbox({
|
|
83
|
+
kind: 'task_run',
|
|
84
|
+
payload: { taskId, triggerType: 'assigned' },
|
|
85
|
+
projectId: task.project_id,
|
|
86
|
+
taskId,
|
|
87
|
+
idempotencyKey: `task:${taskId}:assigned${assignedVersion === null ? '' : `:v${assignedVersion}`}`,
|
|
88
|
+
})
|
|
89
|
+
}
|
|
90
|
+
if (autoStart) void this.tick()
|
|
91
|
+
return this.taskView(this.taskRow(taskId))
|
|
92
|
+
},
|
|
93
|
+
async transitionTask(taskId, status, actor = this.actor()) {
|
|
94
|
+
const before = this.taskRow(taskId)
|
|
95
|
+
// 离开「进行中」前的活跃运行数:运行中止已由 updateTask 内的写占用释放统一完成,
|
|
96
|
+
// 这里只按中止条数决定要不要发看板暂停的系统指令消息,避免同一处中止被算两遍。
|
|
97
|
+
const activeRuns = Number(this.store.get(
|
|
98
|
+
"SELECT COUNT(*) AS n FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
|
|
99
|
+
taskId,
|
|
100
|
+
)?.n ?? 0)
|
|
101
|
+
// 看板拖拽沿用 D-54 的运行触发类型(board_resume):拖入「执行中」的通知与开工由
|
|
102
|
+
// updateTask 内的统一触发点完成(同一任务只发一条消息、只入队一次运行)。
|
|
103
|
+
await this.updateTask(taskId, { status }, actor, { startTriggerType: 'board_resume' })
|
|
104
|
+
await this.applyBoardDragDirective(before, status, { activeRuns })
|
|
105
|
+
// 重新取数:拖拽联动可能刚入队或暂停了运行,沿用 updateTask 的返回会带过期的 latestRun。
|
|
106
|
+
return this.taskView(this.taskRow(taskId))
|
|
107
|
+
},
|
|
108
|
+
// 看板拖拽联动(DSHBOTS-54):拖出到 todo/blocked 自动暂停。
|
|
109
|
+
// 拖入「执行中」一侧的通知与开工已收进 updateTask 内的统一触发点(DSHBOTS-100):
|
|
110
|
+
// blocked/in_review → in_progress 与编辑表单改状态同样要通知并开工,逻辑只有那一处,
|
|
111
|
+
// 这里不再重复发消息、重复入队(同一任务只发一条)。
|
|
112
|
+
// 指令消息由系统直接发(sender_type='system',不触发 bot 运行);
|
|
113
|
+
// 出向 in_review/done/canceled 的写运行中止由 updateTask 内的写占用释放统一处理(DSHBOTS-73)。
|
|
114
|
+
async applyBoardDragDirective(before, afterStatus, { activeRuns = 0 } = {}) {
|
|
115
|
+
if (before.status === afterStatus) return
|
|
116
|
+
if (before.status === 'in_progress' && (afterStatus === 'todo' || afterStatus === 'blocked')) {
|
|
117
|
+
// 运行中止已由 updateTask 内的写占用释放统一完成(同一处处理),这里只按中止条数发系统指令消息。
|
|
118
|
+
if (activeRuns > 0) {
|
|
119
|
+
const project = this.projectRow(before.project_id)
|
|
120
|
+
this.insertMessage({
|
|
121
|
+
projectId: before.project_id,
|
|
122
|
+
senderType: 'system',
|
|
123
|
+
senderId: 'system',
|
|
124
|
+
taskId: before.id,
|
|
125
|
+
body: `任务 ${project.key}-${before.number} 已移出执行中,运行已暂停。`,
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
// 总监强制受阻(DSHBOTS-232 ②):把「进行中」任务强制移「受阻」并中止其名下全部
|
|
131
|
+
// 排队/执行中运行。运行中止走既有 abort 链路(cancelRunInternal → runtime.cancelRun),
|
|
132
|
+
// 与看板暂停(PAUSED_BY_BOARD,可续跑的暂停语义)区分:强制受阻是中止语义,
|
|
133
|
+
// 稳定码 TASK_FORCE_BLOCKED + run 事件 force_blocked + 审计 task.force_blocked 留痕。
|
|
134
|
+
// 先停运行再改状态:状态变更经 updateTask 单一触发点,此时活跃运行已清空,
|
|
135
|
+
// 不会落进看板暂停分支造成双重口径。
|
|
136
|
+
async forceBlockTask(taskId, actor = this.actor()) {
|
|
137
|
+
const task = this.taskRow(taskId)
|
|
138
|
+
if (task.status !== 'in_progress') throw conflict(`任务不在进行中,不能强制受阻(当前 ${task.status})`)
|
|
139
|
+
const runs = this.store.all(
|
|
140
|
+
"SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
|
|
141
|
+
taskId,
|
|
142
|
+
)
|
|
143
|
+
const stoppedRuns = []
|
|
144
|
+
for (const run of runs) {
|
|
145
|
+
await this.cancelRunInternal(run.id, false)
|
|
146
|
+
this.store.run(
|
|
147
|
+
'UPDATE runs SET error_code = ?, error_message = ? WHERE id = ?',
|
|
148
|
+
'TASK_FORCE_BLOCKED', '总监强制移为受阻,运行中止', run.id,
|
|
149
|
+
)
|
|
150
|
+
this.insertRunEvent(run.id, 'force_blocked', '总监强制受阻,运行中止')
|
|
151
|
+
stoppedRuns.push(run.id)
|
|
152
|
+
}
|
|
153
|
+
await this.updateTask(taskId, { status: 'blocked' }, actor)
|
|
154
|
+
this.audit(actor, 'task.force_blocked', 'task', taskId, { stoppedRuns })
|
|
155
|
+
const project = this.projectRow(task.project_id)
|
|
156
|
+
this.insertMessage({
|
|
157
|
+
projectId: task.project_id,
|
|
158
|
+
senderType: 'system',
|
|
159
|
+
senderId: 'system',
|
|
160
|
+
taskId,
|
|
161
|
+
body: `任务 ${project.key}-${task.number} 被总监强制移为受阻,运行已中止。`,
|
|
162
|
+
})
|
|
163
|
+
return this.taskView(this.taskRow(taskId))
|
|
164
|
+
},
|
|
165
|
+
// 总监会话入口(team_block_task 工具):与 reviewFromBot 同款 owner 校验。
|
|
166
|
+
async forceBlockFromBot(sessionId, input) {
|
|
167
|
+
const { project, actor } = this.ownerContextFor(sessionId)
|
|
168
|
+
const task = this.resolveBotTask(project, input.task)
|
|
169
|
+
return this.forceBlockTask(task.id, actor)
|
|
170
|
+
},
|
|
171
|
+
resolveBotTask(project, ref) {
|
|
172
|
+
const raw = String(ref ?? '').trim()
|
|
173
|
+
if (!raw) throw badRequest('缺少任务编号')
|
|
174
|
+
let task
|
|
175
|
+
if (raw.startsWith('task_')) {
|
|
176
|
+
task = this.store.get('SELECT * FROM tasks WHERE id = ? AND project_id = ?', raw, project.id)
|
|
177
|
+
} else {
|
|
178
|
+
const match = raw.match(/^(?:([A-Za-z][A-Za-z0-9]*)-)?(\d+)$/)
|
|
179
|
+
if (match && (!match[1] || match[1].toLowerCase() === project.key.toLowerCase())) {
|
|
180
|
+
task = this.store.get('SELECT * FROM tasks WHERE project_id = ? AND number = ?', project.id, Number(match[2]))
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (!task) throw notFound(`找不到任务 ${raw}`)
|
|
184
|
+
return task
|
|
185
|
+
},
|
|
186
|
+
ownerContextFor(sessionId) {
|
|
187
|
+
const binding = this.store.get('SELECT * FROM session_bindings WHERE session_id = ?', sessionId)
|
|
188
|
+
if (!binding) throw forbidden('只有项目群中的 Bot 可以执行该操作')
|
|
189
|
+
if (!binding.project_id) throw forbidden('单聊会话不在项目中,无法管理任务')
|
|
190
|
+
const project = this.projectRow(binding.project_id)
|
|
191
|
+
if (project.owner_bot_id !== binding.bot_id) throw forbidden('只有项目总监 Bot 可以执行该操作')
|
|
192
|
+
return { binding, project, actor: { type: 'bot', id: binding.bot_id } }
|
|
193
|
+
},
|
|
194
|
+
// 派单侧同写范围重复检测(DSHBOTS-82):同一文件上叠 N 张小卡时,各卡各立各排,
|
|
195
|
+
// 后面的卡只能等前一张跑完,形成排队空转。这里在派单入口找「写范围完全一致」的同项目在办卡。
|
|
196
|
+
// 只比完全一致(集合相等,顺序无关);相交但不同的放行——那属于正常的串行依赖,
|
|
197
|
+
// 正确性由调度器写范围闸门保证,不在派单入口拦截。
|
|
198
|
+
findDuplicateScopeTask(projectId, scopes) {
|
|
199
|
+
const target = new Set(scopes)
|
|
200
|
+
if (!target.size) return null
|
|
201
|
+
const candidates = this.store.all(
|
|
202
|
+
`SELECT id, number, title, write_scopes FROM tasks
|
|
203
|
+
WHERE project_id = ? AND status IN ('todo', 'in_progress', 'blocked')`,
|
|
204
|
+
projectId,
|
|
205
|
+
)
|
|
206
|
+
for (const row of candidates) {
|
|
207
|
+
const other = readWriteScopes(row.write_scopes)
|
|
208
|
+
if (other.length !== target.size) continue
|
|
209
|
+
if ([...target].every(scope => other.includes(scope))) return row
|
|
210
|
+
}
|
|
211
|
+
return null
|
|
212
|
+
},
|
|
213
|
+
// 派单清洗(DSHBOTS-168):写范围声明的程序化质量闸门,三入口共用——
|
|
214
|
+
// createTask(owner 派单路径权威清洗)、assignFromBot(经 createTask 同一清洗)、
|
|
215
|
+
// taskUpdateScopes(改卡入口)。两步:
|
|
216
|
+
// ① ignored 机械移除——命中项目 .gitignore 的条目没有写保护价值,剔除并落审计
|
|
217
|
+
// task.scopes_normalize(removed=[...]);全部被移除后调用方各自的「必须声明写
|
|
218
|
+
// 范围」闸门自然接管(清单为空)。非 git 目录 / git 不可用时保守放行不清洗。
|
|
219
|
+
// ② 一级目录驳回——清洗后仍不含 / 的条目(src、tests 这类整目录声明)直接拒绝:
|
|
220
|
+
// 整目录会把同项目全部写运行判为冲突锁死并发,这不是清洗能救的,必须改卡。
|
|
221
|
+
normalizeDispatchScopes(project, scopes, { actor, taskId }) {
|
|
222
|
+
const { kept, removed } = filterIgnoredWriteScopes(scopes, this.projectWorkDir(project))
|
|
223
|
+
if (removed.length) this.audit(actor, 'task.scopes_normalize', 'task', taskId, { removed })
|
|
224
|
+
const bare = kept.filter(scope => !scope.includes('/'))
|
|
225
|
+
if (bare.length) {
|
|
226
|
+
throw badRequest(
|
|
227
|
+
`写范围不能声明整目录:${bare.join('、')} —— 写范围必须声明到二级路径或具体文件,`
|
|
228
|
+
+ '整目录声明会锁死同项目全部写运行。',
|
|
229
|
+
)
|
|
230
|
+
}
|
|
231
|
+
return kept
|
|
232
|
+
},
|
|
233
|
+
async assignFromBot(sessionId, input) {
|
|
234
|
+
const { project, actor } = this.ownerContextFor(sessionId)
|
|
235
|
+
const member = this.membersOf(project.id).find(bot => bot.name.toLowerCase() === String(input.assignee ?? '').toLowerCase())
|
|
236
|
+
if (!member) throw badRequest(`项目中没有 Bot ${input.assignee}`)
|
|
237
|
+
// 派发沙箱覆盖(DSHBOTS-156):可选 sandbox 只收紧不放大,校验对准承接 bot 的配置档;
|
|
238
|
+
// 缺省 = 跟随 bot 配置(新卡 NULL/重派保留旧值),'inherit' 显式回落 bot 配置(重派清覆盖)。
|
|
239
|
+
const sandboxOverride = input.sandbox === undefined
|
|
240
|
+
? undefined
|
|
241
|
+
: resolveSandboxOverride(this.botRow(member.id), input.sandbox)
|
|
242
|
+
if (input.taskId || input.task) {
|
|
243
|
+
const task = this.resolveBotTask(project, input.taskId ?? input.task)
|
|
244
|
+
if (['done', 'canceled'].includes(task.status)) throw conflict(`任务 ${project.key}-${task.number} 已结束,不能重派`)
|
|
245
|
+
// 任务卡修正闭环(DSHBOTS-232 ①):重派可同时改卡面(标题/描述/优先级)——先经
|
|
246
|
+
// updateTask 落卡,卡面变化由其统一触发点通知负责人修正,再走原重派链路。
|
|
247
|
+
// 写范围不在此口改:入队运行快照与调度闸门消费的不是同一份数据,
|
|
248
|
+
// 改范围走工作台 taskUpdateScopes(含排队运行快照同步),不在这里开第二入口。
|
|
249
|
+
const patch = {}
|
|
250
|
+
if (input.title !== undefined) patch.title = input.title
|
|
251
|
+
if (input.description !== undefined) patch.description = input.description
|
|
252
|
+
if (input.priority !== undefined) patch.priority = input.priority
|
|
253
|
+
if (Object.keys(patch).length) await this.updateTask(task.id, patch, actor)
|
|
254
|
+
const updated = await this.assignTask(task.id, member.id, actor, { autoStart: false, sandboxOverride })
|
|
255
|
+
void this.tick()
|
|
256
|
+
return updated
|
|
257
|
+
}
|
|
258
|
+
// 派单必须声明写范围(程序化闸门,不靠派单方自觉):未声明写范围的任务其写运行会与
|
|
259
|
+
// 同项目所有写运行判为冲突并保守串行,一条空范围任务就能把整队堵死。这里直接拒绝,
|
|
260
|
+
// 而不是留到调度器里把并发能力悄悄吃掉。
|
|
261
|
+
const parsedScopes = input.write_scopes === undefined || input.write_scopes === null
|
|
262
|
+
? parseWriteScopesFromDescription(input.description)
|
|
263
|
+
: parseWriteScopes(input.write_scopes)
|
|
264
|
+
// 闸门按清洗后清单预判(DSHBOTS-168):全部命中忽略规则 = 实际未声明,落上面的
|
|
265
|
+
// 拒绝。原清单透传 createTask 做权威清洗+审计(审计需真实 taskId),此处只预览不落账。
|
|
266
|
+
const scopes = filterIgnoredWriteScopes(parsedScopes, this.projectWorkDir(project)).kept
|
|
267
|
+
if (!scopes.length) {
|
|
268
|
+
throw badRequest(
|
|
269
|
+
'派单必须声明写范围:传 write_scopes 路径数组,或在描述里写一行「写范围:a, b」。'
|
|
270
|
+
+ '未声明会让该任务的写运行与同项目其他写运行全部串行,一条任务即可堵死队列。',
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
// 同写范围重复卡拦截(DSHBOTS-82):同项目已有「写范围完全一致」的在办卡时直接拒绝,
|
|
274
|
+
// 避免同一文件上叠 N 张排队卡空转。force_duplicate 是逃生口:跳过检测,但留审计痕迹。
|
|
275
|
+
// 紧急豁免(DSHBOTS-126):priority='urgent' 的新卡放行——紧急任务无视排队立即施工,
|
|
276
|
+
// 但创建消息报备与哪张在办卡共用车道,不静默并行。
|
|
277
|
+
const duplicate = this.findDuplicateScopeTask(project.id, scopes)
|
|
278
|
+
const forceDuplicate = input.force_duplicate === true
|
|
279
|
+
const urgentExempt = input.priority === 'urgent'
|
|
280
|
+
if (duplicate && !forceDuplicate && !urgentExempt) {
|
|
281
|
+
throw conflict(
|
|
282
|
+
`已存在同写范围任务 ${project.key}-${duplicate.number} ${duplicate.title},请勿重复派单;`
|
|
283
|
+
+ '若需合并多张小卡,请在原任务描述追加清单后重派原任务。'
|
|
284
|
+
+ '紧急任务(priority=urgent)豁免此拦截,可立即派单施工。',
|
|
285
|
+
)
|
|
286
|
+
}
|
|
287
|
+
const task = await this.createTask({
|
|
288
|
+
projectId: project.id,
|
|
289
|
+
title: input.title,
|
|
290
|
+
description: input.description,
|
|
291
|
+
assigneeBotId: member.id,
|
|
292
|
+
priority: input.priority,
|
|
293
|
+
// 透传原始清单(DSHBOTS-168):清洗+审计由 createTask 统一做(审计挂真实 taskId)。
|
|
294
|
+
writeScopes: parsedScopes,
|
|
295
|
+
// 总监派单可带父子/依赖关系(snake_case 透传,createTask 内统一校验与落库)。
|
|
296
|
+
parentTaskId: input.parent_task_id,
|
|
297
|
+
blockedBy: input.blocked_by,
|
|
298
|
+
// 时效要求(新任务 only):重派已有任务(上面 input.taskId/input.task 分支)不更新该字段。
|
|
299
|
+
timeBudgetMinutes: input.time_budget_minutes ?? input.timeBudgetMinutes,
|
|
300
|
+
// 紧急豁免共用车道报备(DSHBOTS-126):urgent 放行同写范围派单时,创建消息注明与哪张在办卡共用车道。
|
|
301
|
+
laneShareTask: urgentExempt && duplicate ? `${project.key}-${duplicate.number}` : null,
|
|
302
|
+
sandboxOverride,
|
|
303
|
+
autoStart: true,
|
|
304
|
+
postCard: true,
|
|
305
|
+
}, actor)
|
|
306
|
+
if (forceDuplicate) {
|
|
307
|
+
this.audit(actor, 'dispatch_force_duplicate', 'task', task.id, {
|
|
308
|
+
writeScopes: scopes,
|
|
309
|
+
duplicateTaskId: duplicate?.id ?? null,
|
|
310
|
+
duplicateIdentifier: duplicate ? `${project.key}-${duplicate.number}` : null,
|
|
311
|
+
})
|
|
312
|
+
}
|
|
313
|
+
return task
|
|
314
|
+
},
|
|
315
|
+
}
|
|
@@ -23,10 +23,12 @@ export const taskNotifyMethods = {
|
|
|
23
23
|
task.id,
|
|
24
24
|
)
|
|
25
25
|
if (active) return null
|
|
26
|
-
// 负责人 bot
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
26
|
+
// 负责人 bot 行缺失(数据异常)或已暂停/归档(DSHBOTS-262)时整体跳过:通知与开工
|
|
27
|
+
// 都指不到人——看板拖拽/表单改状态是派发链路的隐形入口,暂停中不该被唤醒
|
|
28
|
+
// (enqueueTaskRun 对 pending task_run 补投兜底同口径);也不能让通知失败反过来
|
|
29
|
+
// 把已经落库的状态变更顶掉。
|
|
30
|
+
const bot = this.store.get('SELECT name, status FROM bots WHERE id = ?', assigneeId)
|
|
31
|
+
if (!bot || bot.status !== 'active') return null
|
|
30
32
|
const project = this.projectRow(task.project_id)
|
|
31
33
|
const identifier = `${project.key}-${task.number}`
|
|
32
34
|
try {
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
// src/services/task-runs.js —— 任务运行入队、写占用与评论交互域
|
|
2
|
+
// 覆盖:任务运行入队(enqueueTaskRun / enqueueOwnerTaskRun)、写占用释放(releaseTaskWriteLocks)、
|
|
3
|
+
// 终态排队运行清理(cancelSupersededQueuedRuns)、任务评论与运行中继(addComment / steerRunningTaskRun)。
|
|
4
|
+
// 任务建档、状态流转与视图见 ./tasks.js;派单/改派见 ./task-dispatch.js。
|
|
5
|
+
// 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.js 的 defineMethods 调用)。
|
|
6
|
+
|
|
7
|
+
import { badRequest, conflict } from '../errors.js'
|
|
8
|
+
import { id, nowIso, text } from '../util.js'
|
|
9
|
+
import { readWriteScopes } from './write-scopes.js'
|
|
10
|
+
|
|
11
|
+
export const taskRunMethods = {
|
|
12
|
+
// 写占用释放(DSHBOTS-73,用户口径):写范围占用只看「进行中」的任务,
|
|
13
|
+
// 任务一旦离开「进行中」就立刻解除占用/锁定——中止它名下仍在跑/排队的写运行,
|
|
14
|
+
// 写槽让给同项目其他写运行(调度器侧另有 write-lock-scope 闸门兜底)。
|
|
15
|
+
// 只停写运行:只读运行(验收/受阻处理/记忆复盘)不停,否则会打断验收流程。
|
|
16
|
+
// 看板拖出到 todo/blocked 沿用既有暂停口径(PAUSED_BY_BOARD + board_pause 事件),其余目的地用稳定码。
|
|
17
|
+
async releaseTaskWriteLocks(taskId, { fromStatus = null, toStatus = null } = {}) {
|
|
18
|
+
if (fromStatus === 'in_progress' && (toStatus === 'todo' || toStatus === 'blocked')) {
|
|
19
|
+
// 看板暂停路径:取消该任务全部在跑/排队运行并写 PAUSED_BY_BOARD(DSHBOTS-54 既有口径)。
|
|
20
|
+
return await this.pauseRunsForBoard(taskId)
|
|
21
|
+
}
|
|
22
|
+
const runs = this.store.all(
|
|
23
|
+
"SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running') AND mode = 'write'",
|
|
24
|
+
taskId,
|
|
25
|
+
)
|
|
26
|
+
const errorMessage = `任务离开「进行中」(${fromStatus ?? '-'} → ${toStatus ?? '-'}),写运行中止,写占用已释放`
|
|
27
|
+
for (const run of runs) {
|
|
28
|
+
await this.cancelRunInternal(run.id, false)
|
|
29
|
+
this.store.run(
|
|
30
|
+
'UPDATE runs SET error_code = ?, error_message = ? WHERE id = ?',
|
|
31
|
+
'TASK_LEFT_IN_PROGRESS', errorMessage, run.id,
|
|
32
|
+
)
|
|
33
|
+
this.insertRunEvent(run.id, 'task_left_in_progress', errorMessage)
|
|
34
|
+
}
|
|
35
|
+
return runs.length
|
|
36
|
+
},
|
|
37
|
+
// 终态清理(DSHBOTS-110):任务流转到 done/canceled 时,把该任务残留的 queued 运行全部置
|
|
38
|
+
// canceled(SUPERSEDED + stale_superseded 事件),防止调度窗口内漏网的排队运行被起跑执行。
|
|
39
|
+
// 只清 queued:running 的写运行由 releaseTaskWriteLocks 按 TASK_LEFT_IN_PROGRESS 口径处理。
|
|
40
|
+
// 清理任务名下的排队运行(SUPERSEDED 口径)。体内纯同步 store 调用、无 await,
|
|
41
|
+
// 因此是同步函数:调用点可直接放进事务,抛错即回滚,不会出现「事务已提交但清理失败」的静默态。
|
|
42
|
+
cancelSupersededQueuedRuns(taskId) {
|
|
43
|
+
const rows = this.store.all(
|
|
44
|
+
"SELECT id FROM runs WHERE task_id = ? AND status = 'queued'",
|
|
45
|
+
taskId,
|
|
46
|
+
)
|
|
47
|
+
let canceled = 0
|
|
48
|
+
for (const row of rows) {
|
|
49
|
+
if (this.cancelQueuedRunAsSuperseded(row.id)) canceled += 1
|
|
50
|
+
}
|
|
51
|
+
return canceled
|
|
52
|
+
},
|
|
53
|
+
async addComment(taskId, bodyInput, actor = this.actor()) {
|
|
54
|
+
const task = this.taskRow(taskId)
|
|
55
|
+
const body = text(bodyInput, 20_000)
|
|
56
|
+
if (!body) throw badRequest('评论不能为空')
|
|
57
|
+
const commentId = id('cmt')
|
|
58
|
+
this.store.transaction(() => {
|
|
59
|
+
this.store.run(
|
|
60
|
+
'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
|
|
61
|
+
commentId, taskId, actor.type, actor.id, body, nowIso(),
|
|
62
|
+
)
|
|
63
|
+
this.addTaskEvent(taskId, 'commented', actor, { commentId })
|
|
64
|
+
this.audit(actor, 'task.comment', 'task', taskId, { commentId })
|
|
65
|
+
})
|
|
66
|
+
const comment = this.store.get('SELECT * FROM task_comments WHERE id = ?', commentId)
|
|
67
|
+
const steered = await this.steerRunningTaskRun(task, comment, actor)
|
|
68
|
+
return { ...comment, steered }
|
|
69
|
+
},
|
|
70
|
+
// 任务运行期间的评论直接投递给正在执行的会话,避免只能等下一次运行才被读到。
|
|
71
|
+
async steerRunningTaskRun(task, comment, actor) {
|
|
72
|
+
if (!this.runtime?.steer || actor.type === 'bot') return false
|
|
73
|
+
const run = this.store.get(
|
|
74
|
+
"SELECT * FROM runs WHERE task_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1",
|
|
75
|
+
task.id,
|
|
76
|
+
)
|
|
77
|
+
if (!run?.session_id) return false
|
|
78
|
+
const project = this.store.get('SELECT key FROM projects WHERE id = ?', task.project_id)
|
|
79
|
+
const author = this.actorName(actor)
|
|
80
|
+
try {
|
|
81
|
+
await this.runtime.steer(
|
|
82
|
+
run.session_id,
|
|
83
|
+
`New comment on ${project?.key ?? 'TASK'}-${task.number} from ${author}:\n${comment.body}\n\nIf this changes the plan, adjust the work in progress; otherwise keep going and mention it in the delivery report.`,
|
|
84
|
+
)
|
|
85
|
+
this.store.run(
|
|
86
|
+
'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
|
|
87
|
+
id('evt'), run.id, 'steered', `评论直通(${author})`, nowIso(),
|
|
88
|
+
)
|
|
89
|
+
return true
|
|
90
|
+
} catch (error) {
|
|
91
|
+
this.logger.warn?.('dsh-team: steer run %s failed: %s', run.id, error)
|
|
92
|
+
return false
|
|
93
|
+
}
|
|
94
|
+
},
|
|
95
|
+
enqueueTaskRun(task, triggerType, actor) {
|
|
96
|
+
if (!task.assignee_bot_id) throw badRequest('任务没有负责人')
|
|
97
|
+
if (task.status === 'done' || task.status === 'canceled') throw conflict('已完成或取消的任务不能运行')
|
|
98
|
+
const active = this.store.get(
|
|
99
|
+
"SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
|
|
100
|
+
task.id,
|
|
101
|
+
)
|
|
102
|
+
if (active) return active.id
|
|
103
|
+
const runId = id('run')
|
|
104
|
+
const createdAt = nowIso()
|
|
105
|
+
// 写范围在入队时快照:任务后续改声明不影响已排队的运行。
|
|
106
|
+
const writeScopes = JSON.stringify(readWriteScopes(task.write_scopes))
|
|
107
|
+
// DSHBOTS-241:额度耗尽期内派发不撞墙——主 provider 耗尽时直接走备用模型;
|
|
108
|
+
// 未配备用或备用同样耗尽则留 queued 等恢复(调度器按额度状态放行,恢复后自动回主模型)。
|
|
109
|
+
const bot = this.store.get(
|
|
110
|
+
'SELECT id, status, provider, fallback_provider, fallback_model, fallback_effort FROM bots WHERE id = ?',
|
|
111
|
+
task.assignee_bot_id,
|
|
112
|
+
)
|
|
113
|
+
// 暂停/归档的负责人不创建任务运行(DSHBOTS-262):派发入口已拒绝,这里兜住
|
|
114
|
+
// 「入队后负责人被暂停」的 pending task_run 补投——静默丢弃,口径同 chat_run 的 apply 闸门。
|
|
115
|
+
if (!bot || bot.status !== 'active') return null
|
|
116
|
+
const routing = this.quotaRoutingForBot(bot)
|
|
117
|
+
const fallbackProvider = routing.mode === 'fallback' ? routing.provider : null
|
|
118
|
+
const fallbackModel = routing.mode === 'fallback' ? routing.model : null
|
|
119
|
+
const fallbackEffort = routing.mode === 'fallback' ? routing.effort : null
|
|
120
|
+
this.store.run(
|
|
121
|
+
`INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
|
|
122
|
+
attempt, idempotency_key, write_scopes, model_provider, model_model, model_effort, queued_at)
|
|
123
|
+
VALUES (?, ?, ?, ?, 'task', 'write', ?, ?, 'queued', 1, ?, ?, ?, ?, ?, ?)`,
|
|
124
|
+
runId, task.project_id, task.assignee_bot_id, task.id, triggerType, task.id,
|
|
125
|
+
`task:${task.id}:${Date.now()}:${runId}`, writeScopes, fallbackProvider, fallbackModel, fallbackEffort, createdAt,
|
|
126
|
+
)
|
|
127
|
+
this.store.run(
|
|
128
|
+
'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
|
|
129
|
+
id('evt'), runId, 'queued', `由 ${actor.type}:${actor.id} 触发`, createdAt,
|
|
130
|
+
)
|
|
131
|
+
if (routing.mode === 'fallback') {
|
|
132
|
+
this.insertRunEvent(
|
|
133
|
+
runId,
|
|
134
|
+
'quota_fallback',
|
|
135
|
+
`主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}(预计 ${this.botQuotaState(bot.id, bot.provider)?.resetAt ?? '未知'} 恢复)`,
|
|
136
|
+
)
|
|
137
|
+
} else if (routing.mode === 'wait') {
|
|
138
|
+
this.insertRunEvent(
|
|
139
|
+
runId,
|
|
140
|
+
'quota_wait',
|
|
141
|
+
`主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`,
|
|
142
|
+
)
|
|
143
|
+
}
|
|
144
|
+
if (triggerType === 'board_resume') {
|
|
145
|
+
this.insertRunEvent(runId, 'board_resume', '看板拖入执行中,系统指令自动开工')
|
|
146
|
+
}
|
|
147
|
+
return runId
|
|
148
|
+
},
|
|
149
|
+
enqueueOwnerTaskRun(task, kind) {
|
|
150
|
+
const project = this.projectRow(task.project_id)
|
|
151
|
+
const owner = project.owner_bot_id
|
|
152
|
+
? this.store.get("SELECT * FROM bots WHERE id = ? AND status = 'active'", project.owner_bot_id)
|
|
153
|
+
: null
|
|
154
|
+
if (!owner) return null
|
|
155
|
+
const active = this.store.get(
|
|
156
|
+
"SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
|
|
157
|
+
task.id,
|
|
158
|
+
)
|
|
159
|
+
if (active) return active.id
|
|
160
|
+
const runId = id('run')
|
|
161
|
+
const createdAt = nowIso()
|
|
162
|
+
const triggerType = kind === 'review' ? 'review_requested' : 'blocked_handoff'
|
|
163
|
+
this.store.run(
|
|
164
|
+
`INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
|
|
165
|
+
attempt, idempotency_key, queued_at)
|
|
166
|
+
VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
|
|
167
|
+
runId, project.id, owner.id, task.id, kind, triggerType, task.id,
|
|
168
|
+
`${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
|
|
169
|
+
)
|
|
170
|
+
this.store.run(
|
|
171
|
+
'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
|
|
172
|
+
id('evt'), runId, 'queued',
|
|
173
|
+
kind === 'review' ? '任务交付,转总监验收' : '任务受阻,转总监处理',
|
|
174
|
+
createdAt,
|
|
175
|
+
)
|
|
176
|
+
void this.tick()
|
|
177
|
+
return runId
|
|
178
|
+
},
|
|
179
|
+
}
|