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.
@@ -1,13 +1,14 @@
1
- // src/services/tasks.js —— 任务与审批域
2
- // 任务建档、状态流转、派单与评论;交付验收/退回与核验委派见 ./task-review.js。
1
+ // src/services/tasks.js —— 任务核心域(建档、状态流转与视图)
2
+ // 派单/改派/看板联动见 ./task-dispatch.js;运行入队、写占用释放与评论见 ./task-runs.js;
3
+ // 交付验收/退回与核验委派见 ./task-review.js。
3
4
  // 本文件只放方法体,方法挂到 TeamService 原型上(见 src/service.js 的 defineMethods 调用),
4
5
  // 因此方法体内的 this 与拆分前完全一致。
5
6
 
6
- import { badRequest, conflict, forbidden, notFound } from '../errors.js'
7
+ import { badRequest, conflict, notFound } from '../errors.js'
7
8
  import { clampNumber, id, nowIso, projectKey, TASK_ID_PATTERN, text } from '../util.js'
8
- import { filterIgnoredWriteScopes, parseWriteScopes, parseWriteScopesFromDescription, readWriteScopes } from './write-scopes.js'
9
+ import { parseWriteScopes, parseWriteScopesFromDescription, readWriteScopes } from './write-scopes.js'
9
10
  import { ensureAttentionSchema, parseAttention } from './attention-schema.js'
10
- import { resolveSandboxOverride, SANDBOX_OVERRIDES } from './file-policy.js'
11
+ import { SANDBOX_OVERRIDES } from './file-policy.js'
11
12
  import { ensureTaskSandboxSchema } from './task-sandbox-schema.js'
12
13
  import {
13
14
  ensureTaskRelationsSchema, normalizeBlockedByInput, taskDepsView, validateTaskRelations,
@@ -74,7 +75,7 @@ export const tasksMethods = {
74
75
  const title = text(input.title, 240)
75
76
  if (!title) throw badRequest('任务标题不能为空')
76
77
  const assigneeId = input.assigneeBotId || null
77
- if (assigneeId) this.assertMember(project.id, assigneeId)
78
+ if (assigneeId) this.assertDispatchTarget(project.id, assigneeId)
78
79
  const status = input.status && TASK_STATUSES.has(input.status) ? input.status : (assigneeId ? 'todo' : 'backlog')
79
80
  const priority = TASK_PRIORITIES.has(input.priority) ? input.priority : 'medium'
80
81
  // 写范围:显式传参优先(含空数组 = 明确不声明);未传时从描述的「写范围:」行兜底解析。
@@ -271,7 +272,7 @@ export const tasksMethods = {
271
272
  updates.priority = patch.priority
272
273
  }
273
274
  if (patch.assigneeBotId !== undefined) {
274
- if (patch.assigneeBotId) this.assertMember(task.project_id, patch.assigneeBotId)
275
+ if (patch.assigneeBotId) this.assertDispatchTarget(task.project_id, patch.assigneeBotId)
275
276
  updates.assignee_bot_id = patch.assigneeBotId || null
276
277
  }
277
278
  if (patch.position !== undefined) updates.position = Number(patch.position) || 0
@@ -353,469 +354,11 @@ export const tasksMethods = {
353
354
  }
354
355
  return this.taskView(this.taskRow(taskId))
355
356
  },
356
- // 写占用释放(DSHBOTS-73,用户口径):写范围占用只看「进行中」的任务,
357
- // 任务一旦离开「进行中」就立刻解除占用/锁定——中止它名下仍在跑/排队的写运行,
358
- // 写槽让给同项目其他写运行(调度器侧另有 write-lock-scope 闸门兜底)。
359
- // 只停写运行:只读运行(验收/受阻处理/记忆复盘)不停,否则会打断验收流程。
360
- // 看板拖出到 todo/blocked 沿用既有暂停口径(PAUSED_BY_BOARD + board_pause 事件),其余目的地用稳定码。
361
- async releaseTaskWriteLocks(taskId, { fromStatus = null, toStatus = null } = {}) {
362
- if (fromStatus === 'in_progress' && (toStatus === 'todo' || toStatus === 'blocked')) {
363
- // 看板暂停路径:取消该任务全部在跑/排队运行并写 PAUSED_BY_BOARD(DSHBOTS-54 既有口径)。
364
- return await this.pauseRunsForBoard(taskId)
365
- }
366
- const runs = this.store.all(
367
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running') AND mode = 'write'",
368
- taskId,
369
- )
370
- const errorMessage = `任务离开「进行中」(${fromStatus ?? '-'} → ${toStatus ?? '-'}),写运行中止,写占用已释放`
371
- for (const run of runs) {
372
- await this.cancelRunInternal(run.id, false)
373
- this.store.run(
374
- 'UPDATE runs SET error_code = ?, error_message = ? WHERE id = ?',
375
- 'TASK_LEFT_IN_PROGRESS', errorMessage, run.id,
376
- )
377
- this.insertRunEvent(run.id, 'task_left_in_progress', errorMessage)
378
- }
379
- return runs.length
380
- },
381
- // 终态清理(DSHBOTS-110):任务流转到 done/canceled 时,把该任务残留的 queued 运行全部置
382
- // canceled(SUPERSEDED + stale_superseded 事件),防止调度窗口内漏网的排队运行被起跑执行。
383
- // 只清 queued:running 的写运行由 releaseTaskWriteLocks 按 TASK_LEFT_IN_PROGRESS 口径处理。
384
- // 清理任务名下的排队运行(SUPERSEDED 口径)。体内纯同步 store 调用、无 await,
385
- // 因此是同步函数:调用点可直接放进事务,抛错即回滚,不会出现「事务已提交但清理失败」的静默态。
386
- cancelSupersededQueuedRuns(taskId) {
387
- const rows = this.store.all(
388
- "SELECT id FROM runs WHERE task_id = ? AND status = 'queued'",
389
- taskId,
390
- )
391
- let canceled = 0
392
- for (const row of rows) {
393
- if (this.cancelQueuedRunAsSuperseded(row.id)) canceled += 1
394
- }
395
- return canceled
396
- },
397
357
  assertTransition(from, to) {
398
358
  if (from === to) return
399
359
  if (!TRANSITIONS[from]?.has(to)) throw conflict(`任务不能从 ${from} 变为 ${to}`)
400
360
  },
401
- // sandboxOverride 选项(DSHBOTS-156):undefined=不动(重派未传 sandbox 时保留旧覆盖);
402
- // null=显式清掉回落 bot 配置档(重派传 sandbox='inherit');字符串=收紧档(派发入口已校验)。
403
- async assignTask(taskId, botId, actor = this.actor(), { autoStart = true, sandboxOverride } = {} ) {
404
- const task = this.taskRow(taskId)
405
- const project = this.projectRow(task.project_id)
406
- this.assertMember(project.id, botId)
407
- const active = this.store.get(
408
- "SELECT id, kind FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
409
- taskId,
410
- )
411
- // 换负责人闸门(DSHBOTS-169):queued 占位运行(死队列,永远不会被领取)不是执行中,
412
- // 不再阻断改派——事务内按 SUPERSEDED 口径清掉后放行;只有 running 的任务运行照旧阻断
413
- // (文案不变)。同负责人重派不走此闸,行为不变。
414
- const reassigning = task.assignee_bot_id !== botId
415
- if (reassigning && this.store.get(
416
- "SELECT id FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'running' LIMIT 1",
417
- taskId,
418
- )) throw conflict('任务有正在执行的运行,不能更换负责人')
419
- const supersedeQueued = reassigning && !!this.store.get(
420
- "SELECT id FROM runs WHERE task_id = ? AND kind = 'task' AND status = 'queued' LIMIT 1",
421
- taskId,
422
- )
423
- ensureTaskSandboxSchema(this.store)
424
- const sandboxTouched = sandboxOverride !== undefined
425
- // 存量 NULL 预算卡补挂(DSHBOTS-198):COALESCE 只补空,显式已设的卡不覆盖。
426
- const defaultTimeBudget = this.defaultTaskTimeBudget()
427
- this.store.transaction(() => {
428
- // queued 占位清理与改派同事务(DSHBOTS-169):SUPERSEDED 不进任务执行历史,run 事件可审计。
429
- // 助手是同步函数(体内无 await),抛错会让整个事务回滚,不会留下「改派已生效但占位还在」的半成品。
430
- if (supersedeQueued) this.cancelSupersededQueuedRuns(taskId)
431
- this.store.run(
432
- `UPDATE tasks SET assignee_bot_id = ?, review_target = ?,
433
- status = CASE WHEN status IN ('backlog', 'blocked') THEN 'todo' ELSE status END,
434
- time_budget_minutes = COALESCE(time_budget_minutes, ?),
435
- version = version + 1, updated_at = ?${sandboxTouched ? ', sandbox_override = ?' : ''} WHERE id = ?`,
436
- ...(sandboxTouched
437
- ? [botId, actor.type === 'bot' ? 'owner_bot' : 'user', defaultTimeBudget, nowIso(), sandboxOverride ?? null, taskId]
438
- : [botId, actor.type === 'bot' ? 'owner_bot' : 'user', defaultTimeBudget, nowIso(), taskId]),
439
- )
440
- this.addTaskEvent(taskId, 'assigned', actor, {
441
- botId,
442
- ...(sandboxTouched && { sandbox: sandboxOverride ?? 'inherit' }),
443
- })
444
- this.audit(actor, 'task.assign', 'task', taskId, { botId, ...(sandboxTouched && { sandbox: sandboxOverride ?? 'inherit' }) })
445
- })
446
- // 总监bot的验收/受阻处理运行本身占用任务的唯一活动运行名额,
447
- // 此时由 finishRun 的收尾逻辑负责重新排队执行,这里跳过。
448
- // 换负责人清掉 queued 占位后名额已空:重算判定才会按新负责人重排 task_run(DSHBOTS-169)。
449
- // 幂等键:task_run 是先写者赢闸(ON CONFLICT DO NOTHING 且撞键不再 applyOutboxRow),
450
- // 稳定键 task:<id>:assigned 会在再次改派时撞上历史 delivered 行而被静默吞掉、排不出新运行
451
- // (不限清 queued 占位场景,无活跃运行的改派同样会写键)。凡换负责人一律带事务内单调自增
452
- // 的 task.version 后缀(确定性、跨改派不碰撞);同负责人重派保持稳定键,slotHeld 已提供幂等。
453
- const slotHeld = supersedeQueued
454
- ? this.store.get(
455
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
456
- taskId,
457
- )
458
- : active
459
- if (!slotHeld) {
460
- const assignedVersion = reassigning ? this.taskRow(taskId).version : null
461
- this.enqueueOutbox({
462
- kind: 'task_run',
463
- payload: { taskId, triggerType: 'assigned' },
464
- projectId: task.project_id,
465
- taskId,
466
- idempotencyKey: `task:${taskId}:assigned${assignedVersion === null ? '' : `:v${assignedVersion}`}`,
467
- })
468
- }
469
- if (autoStart) void this.tick()
470
- return this.taskView(this.taskRow(taskId))
471
- },
472
- async transitionTask(taskId, status, actor = this.actor()) {
473
- const before = this.taskRow(taskId)
474
- // 离开「进行中」前的活跃运行数:运行中止已由 updateTask 内的写占用释放统一完成,
475
- // 这里只按中止条数决定要不要发看板暂停的系统指令消息,避免同一处中止被算两遍。
476
- const activeRuns = Number(this.store.get(
477
- "SELECT COUNT(*) AS n FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
478
- taskId,
479
- )?.n ?? 0)
480
- // 看板拖拽沿用 D-54 的运行触发类型(board_resume):拖入「执行中」的通知与开工由
481
- // updateTask 内的统一触发点完成(同一任务只发一条消息、只入队一次运行)。
482
- await this.updateTask(taskId, { status }, actor, { startTriggerType: 'board_resume' })
483
- await this.applyBoardDragDirective(before, status, { activeRuns })
484
- // 重新取数:拖拽联动可能刚入队或暂停了运行,沿用 updateTask 的返回会带过期的 latestRun。
485
- return this.taskView(this.taskRow(taskId))
486
- },
487
-
488
- // 看板拖拽联动(DSHBOTS-54):拖出到 todo/blocked 自动暂停。
489
- // 拖入「执行中」一侧的通知与开工已收进 updateTask 内的统一触发点(DSHBOTS-100):
490
- // blocked/in_review → in_progress 与编辑表单改状态同样要通知并开工,逻辑只有那一处,
491
- // 这里不再重复发消息、重复入队(同一任务只发一条)。
492
- // 指令消息由系统直接发(sender_type='system',不触发 bot 运行);
493
- // 出向 in_review/done/canceled 的写运行中止由 updateTask 内的写占用释放统一处理(DSHBOTS-73)。
494
- async applyBoardDragDirective(before, afterStatus, { activeRuns = 0 } = {}) {
495
- if (before.status === afterStatus) return
496
- if (before.status === 'in_progress' && (afterStatus === 'todo' || afterStatus === 'blocked')) {
497
- // 运行中止已由 updateTask 内的写占用释放统一完成(同一处处理),这里只按中止条数发系统指令消息。
498
- if (activeRuns > 0) {
499
- const project = this.projectRow(before.project_id)
500
- this.insertMessage({
501
- projectId: before.project_id,
502
- senderType: 'system',
503
- senderId: 'system',
504
- taskId: before.id,
505
- body: `任务 ${project.key}-${before.number} 已移出执行中,运行已暂停。`,
506
- })
507
- }
508
- }
509
- },
510
- // 总监强制受阻(DSHBOTS-232 ②):把「进行中」任务强制移「受阻」并中止其名下全部
511
- // 排队/执行中运行。运行中止走既有 abort 链路(cancelRunInternal → runtime.cancelRun),
512
- // 与看板暂停(PAUSED_BY_BOARD,可续跑的暂停语义)区分:强制受阻是中止语义,
513
- // 稳定码 TASK_FORCE_BLOCKED + run 事件 force_blocked + 审计 task.force_blocked 留痕。
514
- // 先停运行再改状态:状态变更经 updateTask 单一触发点,此时活跃运行已清空,
515
- // 不会落进看板暂停分支造成双重口径。
516
- async forceBlockTask(taskId, actor = this.actor()) {
517
- const task = this.taskRow(taskId)
518
- if (task.status !== 'in_progress') throw conflict(`任务不在进行中,不能强制受阻(当前 ${task.status})`)
519
- const runs = this.store.all(
520
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
521
- taskId,
522
- )
523
- const stoppedRuns = []
524
- for (const run of runs) {
525
- await this.cancelRunInternal(run.id, false)
526
- this.store.run(
527
- 'UPDATE runs SET error_code = ?, error_message = ? WHERE id = ?',
528
- 'TASK_FORCE_BLOCKED', '总监强制移为受阻,运行中止', run.id,
529
- )
530
- this.insertRunEvent(run.id, 'force_blocked', '总监强制受阻,运行中止')
531
- stoppedRuns.push(run.id)
532
- }
533
- await this.updateTask(taskId, { status: 'blocked' }, actor)
534
- this.audit(actor, 'task.force_blocked', 'task', taskId, { stoppedRuns })
535
- const project = this.projectRow(task.project_id)
536
- this.insertMessage({
537
- projectId: task.project_id,
538
- senderType: 'system',
539
- senderId: 'system',
540
- taskId,
541
- body: `任务 ${project.key}-${task.number} 被总监强制移为受阻,运行已中止。`,
542
- })
543
- return this.taskView(this.taskRow(taskId))
544
- },
545
- // 总监会话入口(team_block_task 工具):与 reviewFromBot 同款 owner 校验。
546
- async forceBlockFromBot(sessionId, input) {
547
- const { project, actor } = this.ownerContextFor(sessionId)
548
- const task = this.resolveBotTask(project, input.task)
549
- return this.forceBlockTask(task.id, actor)
550
- },
551
- async addComment(taskId, bodyInput, actor = this.actor()) {
552
- const task = this.taskRow(taskId)
553
- const body = text(bodyInput, 20_000)
554
- if (!body) throw badRequest('评论不能为空')
555
- const commentId = id('cmt')
556
- this.store.transaction(() => {
557
- this.store.run(
558
- 'INSERT INTO task_comments(id, task_id, author_type, author_id, body, created_at) VALUES (?, ?, ?, ?, ?, ?)',
559
- commentId, taskId, actor.type, actor.id, body, nowIso(),
560
- )
561
- this.addTaskEvent(taskId, 'commented', actor, { commentId })
562
- this.audit(actor, 'task.comment', 'task', taskId, { commentId })
563
- })
564
- const comment = this.store.get('SELECT * FROM task_comments WHERE id = ?', commentId)
565
- const steered = await this.steerRunningTaskRun(task, comment, actor)
566
- return { ...comment, steered }
567
- },
568
361
 
569
- // 任务运行期间的评论直接投递给正在执行的会话,避免只能等下一次运行才被读到。
570
- async steerRunningTaskRun(task, comment, actor) {
571
- if (!this.runtime?.steer || actor.type === 'bot') return false
572
- const run = this.store.get(
573
- "SELECT * FROM runs WHERE task_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1",
574
- task.id,
575
- )
576
- if (!run?.session_id) return false
577
- const project = this.store.get('SELECT key FROM projects WHERE id = ?', task.project_id)
578
- const author = this.actorName(actor)
579
- try {
580
- await this.runtime.steer(
581
- run.session_id,
582
- `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.`,
583
- )
584
- this.store.run(
585
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
586
- id('evt'), run.id, 'steered', `评论直通(${author})`, nowIso(),
587
- )
588
- return true
589
- } catch (error) {
590
- this.logger.warn?.('dsh-team: steer run %s failed: %s', run.id, error)
591
- return false
592
- }
593
- },
594
- enqueueTaskRun(task, triggerType, actor) {
595
- if (!task.assignee_bot_id) throw badRequest('任务没有负责人')
596
- if (task.status === 'done' || task.status === 'canceled') throw conflict('已完成或取消的任务不能运行')
597
- const active = this.store.get(
598
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
599
- task.id,
600
- )
601
- if (active) return active.id
602
- const runId = id('run')
603
- const createdAt = nowIso()
604
- // 写范围在入队时快照:任务后续改声明不影响已排队的运行。
605
- const writeScopes = JSON.stringify(readWriteScopes(task.write_scopes))
606
- // DSHBOTS-241:额度耗尽期内派发不撞墙——主 provider 耗尽时直接走备用模型;
607
- // 未配备用或备用同样耗尽则留 queued 等恢复(调度器按额度状态放行,恢复后自动回主模型)。
608
- const bot = this.store.get(
609
- 'SELECT id, provider, fallback_provider, fallback_model, fallback_effort FROM bots WHERE id = ?',
610
- task.assignee_bot_id,
611
- )
612
- const routing = this.quotaRoutingForBot(bot)
613
- const fallbackProvider = routing.mode === 'fallback' ? routing.provider : null
614
- const fallbackModel = routing.mode === 'fallback' ? routing.model : null
615
- const fallbackEffort = routing.mode === 'fallback' ? routing.effort : null
616
- this.store.run(
617
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
618
- attempt, idempotency_key, write_scopes, model_provider, model_model, model_effort, queued_at)
619
- VALUES (?, ?, ?, ?, 'task', 'write', ?, ?, 'queued', 1, ?, ?, ?, ?, ?, ?)`,
620
- runId, task.project_id, task.assignee_bot_id, task.id, triggerType, task.id,
621
- `task:${task.id}:${Date.now()}:${runId}`, writeScopes, fallbackProvider, fallbackModel, fallbackEffort, createdAt,
622
- )
623
- this.store.run(
624
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
625
- id('evt'), runId, 'queued', `由 ${actor.type}:${actor.id} 触发`, createdAt,
626
- )
627
- if (routing.mode === 'fallback') {
628
- this.insertRunEvent(
629
- runId,
630
- 'quota_fallback',
631
- `主 provider 额度耗尽,本次直接走备用模型 ${routing.ref}(预计 ${this.botQuotaState(bot.id, bot.provider)?.resetAt ?? '未知'} 恢复)`,
632
- )
633
- } else if (routing.mode === 'wait') {
634
- this.insertRunEvent(
635
- runId,
636
- 'quota_wait',
637
- `主 provider 额度耗尽且无可用备用模型,排队等待至 ${routing.resetAt ?? '恢复'}`,
638
- )
639
- }
640
- if (triggerType === 'board_resume') {
641
- this.insertRunEvent(runId, 'board_resume', '看板拖入执行中,系统指令自动开工')
642
- }
643
- return runId
644
- },
645
- enqueueOwnerTaskRun(task, kind) {
646
- const project = this.projectRow(task.project_id)
647
- const owner = project.owner_bot_id
648
- ? this.store.get("SELECT * FROM bots WHERE id = ? AND status = 'active'", project.owner_bot_id)
649
- : null
650
- if (!owner) return null
651
- const active = this.store.get(
652
- "SELECT id FROM runs WHERE task_id = ? AND status IN ('queued', 'running')",
653
- task.id,
654
- )
655
- if (active) return active.id
656
- const runId = id('run')
657
- const createdAt = nowIso()
658
- const triggerType = kind === 'review' ? 'review_requested' : 'blocked_handoff'
659
- this.store.run(
660
- `INSERT INTO runs(id, project_id, bot_id, task_id, kind, mode, trigger_type, trigger_ref, status,
661
- attempt, idempotency_key, queued_at)
662
- VALUES (?, ?, ?, ?, ?, 'read', ?, ?, 'queued', 1, ?, ?)`,
663
- runId, project.id, owner.id, task.id, kind, triggerType, task.id,
664
- `${kind}:${task.id}:${Date.now()}:${runId}`, createdAt,
665
- )
666
- this.store.run(
667
- 'INSERT INTO run_events(id, run_id, type, message, created_at) VALUES (?, ?, ?, ?, ?)',
668
- id('evt'), runId, 'queued',
669
- kind === 'review' ? '任务交付,转总监验收' : '任务受阻,转总监处理',
670
- createdAt,
671
- )
672
- void this.tick()
673
- return runId
674
- },
675
- resolveBotTask(project, ref) {
676
- const raw = String(ref ?? '').trim()
677
- if (!raw) throw badRequest('缺少任务编号')
678
- let task
679
- if (raw.startsWith('task_')) {
680
- task = this.store.get('SELECT * FROM tasks WHERE id = ? AND project_id = ?', raw, project.id)
681
- } else {
682
- const match = raw.match(/^(?:([A-Za-z][A-Za-z0-9]*)-)?(\d+)$/)
683
- if (match && (!match[1] || match[1].toLowerCase() === project.key.toLowerCase())) {
684
- task = this.store.get('SELECT * FROM tasks WHERE project_id = ? AND number = ?', project.id, Number(match[2]))
685
- }
686
- }
687
- if (!task) throw notFound(`找不到任务 ${raw}`)
688
- return task
689
- },
690
- ownerContextFor(sessionId) {
691
- const binding = this.store.get('SELECT * FROM session_bindings WHERE session_id = ?', sessionId)
692
- if (!binding) throw forbidden('只有项目群中的 Bot 可以执行该操作')
693
- if (!binding.project_id) throw forbidden('单聊会话不在项目中,无法管理任务')
694
- const project = this.projectRow(binding.project_id)
695
- if (project.owner_bot_id !== binding.bot_id) throw forbidden('只有项目总监 Bot 可以执行该操作')
696
- return { binding, project, actor: { type: 'bot', id: binding.bot_id } }
697
- },
698
- // 派单侧同写范围重复检测(DSHBOTS-82):同一文件上叠 N 张小卡时,各卡各立各排,
699
- // 后面的卡只能等前一张跑完,形成排队空转。这里在派单入口找「写范围完全一致」的同项目在办卡。
700
- // 只比完全一致(集合相等,顺序无关);相交但不同的放行——那属于正常的串行依赖,
701
- // 正确性由调度器写范围闸门保证,不在派单入口拦截。
702
- findDuplicateScopeTask(projectId, scopes) {
703
- const target = new Set(scopes)
704
- if (!target.size) return null
705
- const candidates = this.store.all(
706
- `SELECT id, number, title, write_scopes FROM tasks
707
- WHERE project_id = ? AND status IN ('todo', 'in_progress', 'blocked')`,
708
- projectId,
709
- )
710
- for (const row of candidates) {
711
- const other = readWriteScopes(row.write_scopes)
712
- if (other.length !== target.size) continue
713
- if ([...target].every(scope => other.includes(scope))) return row
714
- }
715
- return null
716
- },
717
- // 派单清洗(DSHBOTS-168):写范围声明的程序化质量闸门,三入口共用——
718
- // createTask(owner 派单路径权威清洗)、assignFromBot(经 createTask 同一清洗)、
719
- // taskUpdateScopes(改卡入口)。两步:
720
- // ① ignored 机械移除——命中项目 .gitignore 的条目没有写保护价值,剔除并落审计
721
- // task.scopes_normalize(removed=[...]);全部被移除后调用方各自的「必须声明写
722
- // 范围」闸门自然接管(清单为空)。非 git 目录 / git 不可用时保守放行不清洗。
723
- // ② 一级目录驳回——清洗后仍不含 / 的条目(src、tests 这类整目录声明)直接拒绝:
724
- // 整目录会把同项目全部写运行判为冲突锁死并发,这不是清洗能救的,必须改卡。
725
- normalizeDispatchScopes(project, scopes, { actor, taskId }) {
726
- const { kept, removed } = filterIgnoredWriteScopes(scopes, this.projectWorkDir(project))
727
- if (removed.length) this.audit(actor, 'task.scopes_normalize', 'task', taskId, { removed })
728
- const bare = kept.filter(scope => !scope.includes('/'))
729
- if (bare.length) {
730
- throw badRequest(
731
- `写范围不能声明整目录:${bare.join('、')} —— 写范围必须声明到二级路径或具体文件,`
732
- + '整目录声明会锁死同项目全部写运行。',
733
- )
734
- }
735
- return kept
736
- },
737
- async assignFromBot(sessionId, input) {
738
- const { project, actor } = this.ownerContextFor(sessionId)
739
- const member = this.membersOf(project.id).find(bot => bot.name.toLowerCase() === String(input.assignee ?? '').toLowerCase())
740
- if (!member) throw badRequest(`项目中没有 Bot ${input.assignee}`)
741
- // 派发沙箱覆盖(DSHBOTS-156):可选 sandbox 只收紧不放大,校验对准承接 bot 的配置档;
742
- // 缺省 = 跟随 bot 配置(新卡 NULL/重派保留旧值),'inherit' 显式回落 bot 配置(重派清覆盖)。
743
- const sandboxOverride = input.sandbox === undefined
744
- ? undefined
745
- : resolveSandboxOverride(this.botRow(member.id), input.sandbox)
746
- if (input.taskId || input.task) {
747
- const task = this.resolveBotTask(project, input.taskId ?? input.task)
748
- if (['done', 'canceled'].includes(task.status)) throw conflict(`任务 ${project.key}-${task.number} 已结束,不能重派`)
749
- // 任务卡修正闭环(DSHBOTS-232 ①):重派可同时改卡面(标题/描述/优先级)——先经
750
- // updateTask 落卡,卡面变化由其统一触发点通知负责人修正,再走原重派链路。
751
- // 写范围不在此口改:入队运行快照与调度闸门消费的不是同一份数据,
752
- // 改范围走工作台 taskUpdateScopes(含排队运行快照同步),不在这里开第二入口。
753
- const patch = {}
754
- if (input.title !== undefined) patch.title = input.title
755
- if (input.description !== undefined) patch.description = input.description
756
- if (input.priority !== undefined) patch.priority = input.priority
757
- if (Object.keys(patch).length) await this.updateTask(task.id, patch, actor)
758
- const updated = await this.assignTask(task.id, member.id, actor, { autoStart: false, sandboxOverride })
759
- void this.tick()
760
- return updated
761
- }
762
- // 派单必须声明写范围(程序化闸门,不靠派单方自觉):未声明写范围的任务其写运行会与
763
- // 同项目所有写运行判为冲突并保守串行,一条空范围任务就能把整队堵死。这里直接拒绝,
764
- // 而不是留到调度器里把并发能力悄悄吃掉。
765
- const parsedScopes = input.write_scopes === undefined || input.write_scopes === null
766
- ? parseWriteScopesFromDescription(input.description)
767
- : parseWriteScopes(input.write_scopes)
768
- // 闸门按清洗后清单预判(DSHBOTS-168):全部命中忽略规则 = 实际未声明,落上面的
769
- // 拒绝。原清单透传 createTask 做权威清洗+审计(审计需真实 taskId),此处只预览不落账。
770
- const scopes = filterIgnoredWriteScopes(parsedScopes, this.projectWorkDir(project)).kept
771
- if (!scopes.length) {
772
- throw badRequest(
773
- '派单必须声明写范围:传 write_scopes 路径数组,或在描述里写一行「写范围:a, b」。'
774
- + '未声明会让该任务的写运行与同项目其他写运行全部串行,一条任务即可堵死队列。',
775
- )
776
- }
777
- // 同写范围重复卡拦截(DSHBOTS-82):同项目已有「写范围完全一致」的在办卡时直接拒绝,
778
- // 避免同一文件上叠 N 张排队卡空转。force_duplicate 是逃生口:跳过检测,但留审计痕迹。
779
- // 紧急豁免(DSHBOTS-126):priority='urgent' 的新卡放行——紧急任务无视排队立即施工,
780
- // 但创建消息报备与哪张在办卡共用车道,不静默并行。
781
- const duplicate = this.findDuplicateScopeTask(project.id, scopes)
782
- const forceDuplicate = input.force_duplicate === true
783
- const urgentExempt = input.priority === 'urgent'
784
- if (duplicate && !forceDuplicate && !urgentExempt) {
785
- throw conflict(
786
- `已存在同写范围任务 ${project.key}-${duplicate.number} ${duplicate.title},请勿重复派单;`
787
- + '若需合并多张小卡,请在原任务描述追加清单后重派原任务。'
788
- + '紧急任务(priority=urgent)豁免此拦截,可立即派单施工。',
789
- )
790
- }
791
- const task = await this.createTask({
792
- projectId: project.id,
793
- title: input.title,
794
- description: input.description,
795
- assigneeBotId: member.id,
796
- priority: input.priority,
797
- // 透传原始清单(DSHBOTS-168):清洗+审计由 createTask 统一做(审计挂真实 taskId)。
798
- writeScopes: parsedScopes,
799
- // 总监派单可带父子/依赖关系(snake_case 透传,createTask 内统一校验与落库)。
800
- parentTaskId: input.parent_task_id,
801
- blockedBy: input.blocked_by,
802
- // 时效要求(新任务 only):重派已有任务(上面 input.taskId/input.task 分支)不更新该字段。
803
- timeBudgetMinutes: input.time_budget_minutes ?? input.timeBudgetMinutes,
804
- // 紧急豁免共用车道报备(DSHBOTS-126):urgent 放行同写范围派单时,创建消息注明与哪张在办卡共用车道。
805
- laneShareTask: urgentExempt && duplicate ? `${project.key}-${duplicate.number}` : null,
806
- sandboxOverride,
807
- autoStart: true,
808
- postCard: true,
809
- }, actor)
810
- if (forceDuplicate) {
811
- this.audit(actor, 'dispatch_force_duplicate', 'task', task.id, {
812
- writeScopes: scopes,
813
- duplicateTaskId: duplicate?.id ?? null,
814
- duplicateIdentifier: duplicate ? `${project.key}-${duplicate.number}` : null,
815
- })
816
- }
817
- return task
818
- },
819
362
  resolveTaskByIdentifier(identifier) {
820
363
  const match = TASK_ID_PATTERN.exec(String(identifier ?? '').trim())
821
364
  if (!match) throw badRequest('任务号格式应为 <项目key>-<序号>,如 web-3')
package/ui/app.js CHANGED
@@ -328,7 +328,7 @@ function renderShell() {
328
328
  </div>
329
329
  ${state.tree.archived ? `<div class="tree-list">
330
330
  ${archivedChats.length === 0 ? `<div class="side-empty">${t('tree.archivedEmpty')}</div>` : archivedChats.map(item => `
331
- <button class="tree-item chat-item archived ${item.id === project?.id && !isGlobal && state.chatMode !== 'solo' ? 'active' : ''}" data-action="select-project" data-project-id="${attr(item.id)}" title="${esc(item.name)} · ${t('tree.archivedHint')}">
331
+ <button class="tree-item chat-item archived ${item.id === project?.id && !isGlobal && state.chatMode !== 'solo' ? 'active' : ''}" data-action="select-project" data-project-id="${attr(item.id)}" title="${esc(item.name)}">
332
332
  <span class="chat-hash">#</span>
333
333
  <span class="tree-item-name">${esc(item.name)}</span>
334
334
  <span class="tree-flag">${t('common.archived')}</span>
@@ -63,7 +63,7 @@ export default {
63
63
  "solo.dispatching": "Dispatching",
64
64
  "solo.noDispatching": "Nothing is dispatching right now.",
65
65
  "solo.subagents": "Subagents",
66
- "solo.subagentsBody": "Bot sessions ship with subagent / subagent_fork / workflow tools and can spawn subagents on the fly to parallelize; no extra orchestration is needed here.",
66
+ "solo.subagentsBody": "Built in: subagent / subagent_fork / workflow — spawn parallel subagents mid-run.",
67
67
  "solo.recentRuns": "Recent dispatch runs",
68
68
  "solo.noRuns": "No dispatch runs yet.",
69
69
  "solo.workspace": "Dedicated workspace",
@@ -84,7 +84,6 @@ export default {
84
84
  "questionStatus.expired": "Cancelled",
85
85
  "questionStatus.timeout": "Timed out",
86
86
  // DSHBOTS-220: ui/modules copy
87
- "<span class=\\\"faint\\\" title=\\\"项目共 ${totalCount} 个任务;当前筛选、时间窗或列表上限隐藏了 ${hiddenCount} 个\\\">项目共 ${totalCount} 个 · 隐藏 ${hiddenCount} 个</span>": "<span class=\\\"faint\\\" title=\\\"Project has ${totalCount} tasks; the current filter, time window, or list limit hides ${hiddenCount}\\\">${totalCount} total · ${hiddenCount} hidden</span>",
88
87
  "<span class=\\\"pill amber\\\">${pending} 条待审</span>": "${pending} pending",
89
88
  "Bot 已归档": "Bot archived",
90
89
  "」关闭": "\\\", disabled",
@@ -171,7 +170,6 @@ export default {
171
170
  "主目录": "Home",
172
171
  "选定此目录": "Choose this folder",
173
172
  "项目共 ${totalCount} 个 · 隐藏 ${hiddenCount} 个": "${totalCount} tasks in this project · ${hiddenCount} hidden",
174
- "项目共 ${totalCount} 个任务;当前筛选、时间窗或列表上限隐藏了 ${hiddenCount} 个": "${totalCount} tasks in this project; the current filter, time window or list limit hides ${hiddenCount}",
175
173
  // DSHBOTS-241:bot 额度墙状态与手动解除
176
174
  "额度状态": "Quota status",
177
175
  "额度": "Quota",
package/ui/i18n/en/nav.js CHANGED
@@ -65,7 +65,6 @@ export default {
65
65
  "tree.archivedTitle": "Archived group chats",
66
66
  "tree.archived": "Archived",
67
67
  "tree.archivedEmpty": "No archived projects.",
68
- "tree.archivedHint": "Reopen & remove under Project settings · status",
69
68
  // Sidebar bottom
70
69
  "sidebar.botsOverview": "Bots overview",
71
70
  "sidebar.pendingProposals": "Proposals awaiting approval",
@@ -87,7 +87,7 @@ export default {
87
87
  "已被浏览器拒绝": "Blocked by the browser",
88
88
  "在浏览器站点设置中允许通知后刷新页面。": "Allow notifications in the browser site settings and reload the page.",
89
89
  "已开启": "On",
90
- "新审批到达且页面不可见或失焦时弹系统通知,需保持本页开启。": "System notifications appear when a new approval arrives while the page is hidden or unfocused; keep this page open.",
90
+ "页面不可见或失焦时弹系统通知,需保持本页开启。": "System notifications appear while the page is hidden or unfocused; keep this page open.",
91
91
  "已关闭": "Off",
92
92
  "未开启": "Off",
93
93
  "开启后新审批到达时弹系统桌面通知。": "Once enabled, system desktop notifications appear when a new approval arrives.",
@@ -269,7 +269,6 @@ export default {
269
269
  "状态": "Status",
270
270
  "生产目录": "Production directory",
271
271
  "用途说明": "Purpose",
272
- "的工作目录,可指向既有代码库等本机目录;留空则用默认管理目录。": "working directory, which can point to an existing codebase or other local directory; leave blank to use the default management directory.",
273
272
  "的工作目录,可指向既有代码库;留空则用默认管理目录,切换后已有密钥会自动迁移并清理旧目录。": "working directory, which can point to an existing codebase; leave blank to use the default management directory. After switching, existing keys are migrated automatically and the old directory is cleaned up.",
274
273
  "目标": "Target",
275
274
  "确认移除追踪": "Confirm tracking removal",
@@ -289,7 +288,7 @@ export default {
289
288
  "群聊回复模式": "Group reply mode",
290
289
  "背景、范围、约束、验收标准": "Background, scope, constraints, acceptance criteria",
291
290
  "至少 8 个字符,保存后不再回显": "At least 8 characters; never shown again after saving",
292
- "至少 8 个字符;同作用域同名会覆盖旧值。": "At least 8 characters; a key with the same name in the same scope overwrites the old value.",
291
+ "同作用域同名会覆盖旧值。": "A key with the same name in the same scope overwrites the old value.",
293
292
  "补充说明、验收意见或阻塞原因": "Additional notes, acceptance comments, or blocking reasons",
294
293
  "被": "Blocked by ",
295
294
  "角色指令": "Role instructions",
@@ -319,7 +318,6 @@ export default {
319
318
  "还没有密钥。": "No keys yet.",
320
319
  "还没有评论。": "No comments yet.",
321
320
  "还没有运行。": "No runs yet.",
322
- "这是软移除:数据只在数据库中停止展示,不清理任何文件。": "This is a soft removal: data is only hidden from the database; no files are deleted.",
323
321
  "这次运行没有可展示的轨迹。": "This run has no trajectory to display.",
324
322
  "进入项目后才能邀请成员。": "Open a project before inviting members.",
325
323
  "连接中": "Connecting",
@@ -32,8 +32,7 @@ export default {
32
32
  "dm.failed": "Failed",
33
33
  "dm.repliedAt": "Replied at ${time}",
34
34
  // Task time budget (DSHBOTS-129)
35
- "taskForm.timeBudgetLabel": "Time budget (minutes)",
36
- "taskForm.timeBudgetPlaceholder": "Optional; leave blank for none",
35
+ "taskForm.timeBudgetLabel": "Time budget (minutes, optional)",
37
36
  "task.timeBudgetValue": "${minutes} min",
38
37
  "task.timeBudgetNote": "Hard limit: the run is aborted on expiry; the shorter of this budget and the global run timeout applies",
39
38
  // Task rejection (DSHBOTS-141): terminal tasks back to backlog
@@ -42,7 +41,6 @@ export default {
42
41
  "task.rejectConfirm": "Move \"${title}\" back to the backlog?",
43
42
  "task.rejectDone": "Rejected; task moved back to the backlog",
44
43
  // Task board
45
- "task.dragHint": "Drag a task row to change its status; click a group header to collapse it.",
46
44
  "task.searchPlaceholder": "Search tasks, IDs, or labels",
47
45
  "task.filterAllStatus": "All statuses",
48
46
  "task.filterAllMembers": "All members",
@@ -52,7 +50,6 @@ export default {
52
50
  "task.time30d": "Last 30 days",
53
51
  "task.timeAll": "All time",
54
52
  "task.sortLabel": "Task sort",
55
- "task.sortTitle": "Sorts within a group only; does not affect grouping or hierarchy",
56
53
  "task.sortCreatedDesc": "Created new → old",
57
54
  "task.sortCreatedAsc": "Created old → new",
58
55
  "task.sortCompletedDesc": "Completed new → old",
@@ -11,11 +11,10 @@ export default {
11
11
  "已退出微信绑定": "WeChat binding removed",
12
12
  "待扫码": "Waiting to scan",
13
13
  "待输验证码": "Waiting for verification code",
14
- "微信扫码授权 ClawBot;手机上确认后此处会自动变为已连接。": "Scan the QR code with WeChat to authorize ClawBot; after confirming on your phone, this will automatically show as connected.",
15
14
  "微信通道未启用": "WeChat channel not enabled",
16
15
  "微信验证码": "WeChat verification code",
17
16
  "扫码后手机上的验证码": "The verification code shown on your phone after scanning",
18
- "扫码授权成功后自动把授权者绑定为管理员;任务完成会主动推送。": "After successful QR authorization, the authorizer is automatically bound as an administrator; task completion is pushed proactively.",
17
+ "微信扫码授权 ClawBot;确认后自动绑定授权者为管理员,任务完成主动推送。": "Scan with WeChat to authorize ClawBot; the authorizer is bound as administrator and task completion is pushed proactively.",
19
18
  "扫码绑定": "Scan to bind",
20
19
  "提交验证码": "Submit code",
21
20
  "请输入微信验证码": "Enter the WeChat verification code",
@@ -63,7 +63,7 @@ export default {
63
63
  "solo.dispatching": "正在调度",
64
64
  "solo.noDispatching": "当前没有运行中的调度。",
65
65
  "solo.subagents": "子智能体",
66
- "solo.subagentsBody": "bot 会话已内置 subagent / subagent_fork / workflow 工具,可在执行中自行派生子智能体并行加速;无需工作台额外编排。",
66
+ "solo.subagentsBody": "内置 subagent / subagent_fork / workflow,可在执行中派生并行子智能体。",
67
67
  "solo.recentRuns": "最近调度运行",
68
68
  "solo.noRuns": "还没有调度运行。",
69
69
  "solo.workspace": "专属工作区",