dsh-dispatch-board 0.3.0 → 0.5.1
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 +13 -9
- package/lib/client.js +640 -155
- package/lib/index.js +1861 -100
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +2 -2
- package/presets/taskboard.patch.yml +106 -36
package/lib/index.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* set-config / archive-done / install-preset / bind-main-session / clear-main-session /
|
|
9
9
|
* set-workspace-filter / set-workspace-draft / ensure-workspace-lead / upload-attachment / attachment 等端点;
|
|
10
10
|
* 2. 持久化任务看板到 $DSH_HOME/storages/dsh-taskboard/board.json(原子写);
|
|
11
|
-
* 3.
|
|
11
|
+
* 3. 轮询「待开始」列(默认 workspace-lead 模式):按任务工作区复用/懒创建常驻工作区组长
|
|
12
12
|
* (taskboard-dispatch 预设),用 agent.followup() 推一条【任务看板 · 待开始】消息;
|
|
13
13
|
* 组长据此派 taskboard-worker 子 Agent 干活并审核写回(本插件不直接起子 Agent);
|
|
14
14
|
* 4. 任务 done 且未汇报时,把完成回执合并成【任务看板 · 汇报】推给主会话(config.mainSessionId);
|
|
@@ -28,8 +28,20 @@
|
|
|
28
28
|
*/
|
|
29
29
|
|
|
30
30
|
import { Buffer } from 'node:buffer'
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
31
|
+
import { execFileSync } from 'node:child_process'
|
|
32
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
33
|
+
import {
|
|
34
|
+
existsSync,
|
|
35
|
+
lstatSync,
|
|
36
|
+
mkdirSync,
|
|
37
|
+
readdirSync,
|
|
38
|
+
readFileSync,
|
|
39
|
+
renameSync,
|
|
40
|
+
rmSync,
|
|
41
|
+
symlinkSync,
|
|
42
|
+
unlinkSync,
|
|
43
|
+
writeFileSync,
|
|
44
|
+
} from 'node:fs'
|
|
33
45
|
import { homedir } from 'node:os'
|
|
34
46
|
import { dirname, join, resolve, sep } from 'node:path'
|
|
35
47
|
import { fileURLToPath } from 'node:url'
|
|
@@ -82,10 +94,14 @@ const MAX_RECEIPT_BATCH = 10
|
|
|
82
94
|
/** 完成回执里每条任务结论压成单行后的最大字符数(§1.6)。 */
|
|
83
95
|
const RECEIPT_RESULT_CHARS = 200
|
|
84
96
|
/**
|
|
85
|
-
* 归档保留期(§1.2 / §2):`archived`
|
|
97
|
+
* 归档保留期(§1.2 / §2):`archived` 任务在归档满保留期(默认 30 分钟;v0.3.6 起可通过
|
|
98
|
+
* `config.archiveRetentionMinutes` 配置为 0..10080 分钟,0 = 不自动删除)后由宿主自动从看板删除,
|
|
86
99
|
* 不需要用户手动点「删除」。判定见 `pruneArchivedTasks()`。
|
|
87
100
|
*/
|
|
88
|
-
export const
|
|
101
|
+
export const DEFAULT_ARCHIVE_RETENTION_MINUTES = 30
|
|
102
|
+
export const MIN_ARCHIVE_RETENTION_MINUTES = 0
|
|
103
|
+
export const MAX_ARCHIVE_RETENTION_MINUTES = 10080
|
|
104
|
+
export const ARCHIVE_RETENTION_MS = DEFAULT_ARCHIVE_RETENTION_MINUTES * 60 * 1000
|
|
89
105
|
|
|
90
106
|
/* ------------------------------------------------------------------ *
|
|
91
107
|
* 粘贴图片附件(v0.2.0,§2.1)
|
|
@@ -152,6 +168,18 @@ export const LEAD_DISPATCH_INTENT_MS = 10 * 60 * 1000
|
|
|
152
168
|
* 的预建卡片的时间窗;窗口内标题 + note 完全相同 → 复用,不再建第二张。
|
|
153
169
|
*/
|
|
154
170
|
export const LEAD_DISPATCH_DEDUPE_MS = 2 * 60 * 1000
|
|
171
|
+
/** v0.4.0:单条任务最多声明多少个前置依赖任务 id(`dependsOn`)。 */
|
|
172
|
+
export const MAX_DEPENDS_ON = 16
|
|
173
|
+
/** v0.4.0:轮询巡检 `doing + running` 失联卡的启动宽限时间(避开刚派发异步回填窗口)。 */
|
|
174
|
+
export const ORPHAN_GRACE_MS = 60 * 1000
|
|
175
|
+
/** v0.5.0:Git Worktree 物理隔离目录名(默认位于 $DSH_HOME/storages/dsh-taskboard/worktrees/)。 */
|
|
176
|
+
const WORKTREE_DIRNAME = 'worktrees'
|
|
177
|
+
/** v0.5.0:单 Git 工作区允许同时并发运行的隔离 Worktree worker 上限。 */
|
|
178
|
+
export const MAX_CONCURRENT_WORKTREES = 4
|
|
179
|
+
/** v0.5.0:Git 仓库根探测缓存时长(避免轮询对同一路径频繁拉起 git 子进程)。 */
|
|
180
|
+
const GIT_INFO_CACHE_MS = 15 * 1000
|
|
181
|
+
const WORKTREE_DEP_DIRS = Object.freeze(['node_modules', '.venv', 'venv'])
|
|
182
|
+
const WORKTREE_SCAN_SKIP_DIRS = new Set(['.git', 'node_modules', '.venv', 'venv', 'dist', 'build', 'out', 'target'])
|
|
155
183
|
|
|
156
184
|
/** 看板四列。顺序即 UI 列顺序。 */
|
|
157
185
|
export const STATUSES = ['todo', 'doing', 'done', 'archived']
|
|
@@ -313,6 +341,10 @@ export function createEmptyBoard() {
|
|
|
313
341
|
// v0.2.3:平台看板新建行「任务所属工作区」选择('' = 未选择,提交禁用)。
|
|
314
342
|
// 与 workspaceFilter 各自独立记忆、互不串值。
|
|
315
343
|
workspaceDraft: '',
|
|
344
|
+
// v0.3.6:归档任务保留分钟数(默认 30 分钟)。
|
|
345
|
+
archiveRetentionMinutes: DEFAULT_ARCHIVE_RETENTION_MINUTES,
|
|
346
|
+
// v0.5.0:Git Worktree 物理并发隔离(默认开启)。
|
|
347
|
+
worktreeIsolation: true,
|
|
316
348
|
},
|
|
317
349
|
tasks: [],
|
|
318
350
|
}
|
|
@@ -394,6 +426,7 @@ export function normalizeConfig(raw) {
|
|
|
394
426
|
const config = isPlainObject(raw) ? raw : {}
|
|
395
427
|
const interval = Number(config.pollIntervalMs)
|
|
396
428
|
const maxNotifications = Number(config.maxNotifications)
|
|
429
|
+
const archiveMinutes = Number(config.archiveRetentionMinutes)
|
|
397
430
|
return {
|
|
398
431
|
pollEnabled: config.pollEnabled !== false,
|
|
399
432
|
dispatchMode: DISPATCH_MODES.includes(config.dispatchMode) ? config.dispatchMode : DEFAULT_DISPATCH_MODE,
|
|
@@ -405,6 +438,16 @@ export function normalizeConfig(raw) {
|
|
|
405
438
|
Number.isFinite(maxNotifications) && maxNotifications >= 1 && maxNotifications <= 50
|
|
406
439
|
? Math.round(maxNotifications)
|
|
407
440
|
: DEFAULT_MAX_NOTIFICATIONS,
|
|
441
|
+
// v0.3.6:归档任务保留分钟数(0..10080;0 = 不自动删除,默认 30 分钟)。
|
|
442
|
+
archiveRetentionMinutes:
|
|
443
|
+
config.archiveRetentionMinutes !== undefined &&
|
|
444
|
+
config.archiveRetentionMinutes !== null &&
|
|
445
|
+
config.archiveRetentionMinutes !== '' &&
|
|
446
|
+
Number.isFinite(archiveMinutes) &&
|
|
447
|
+
archiveMinutes >= MIN_ARCHIVE_RETENTION_MINUTES &&
|
|
448
|
+
archiveMinutes <= MAX_ARCHIVE_RETENTION_MINUTES
|
|
449
|
+
? Math.round(archiveMinutes)
|
|
450
|
+
: DEFAULT_ARCHIVE_RETENTION_MINUTES,
|
|
408
451
|
// v0.2.0 完成回执收件人:未绑定 / 空白 = null。
|
|
409
452
|
mainSessionId: (() => {
|
|
410
453
|
const id = typeof config.mainSessionId === 'string' ? config.mainSessionId.trim() : ''
|
|
@@ -416,6 +459,8 @@ export function normalizeConfig(raw) {
|
|
|
416
459
|
workspaceFilter: normalizeWorkspaceSelection(config.workspaceFilter),
|
|
417
460
|
// v0.2.3:新建行「任务所属工作区」选择(UI 偏好,'' = 未选择;坏值回退默认)。
|
|
418
461
|
workspaceDraft: normalizeWorkspaceSelection(config.workspaceDraft),
|
|
462
|
+
// v0.5.0:Git Worktree 物理并发隔离开关(默认 true,显式传 false 关闭)。
|
|
463
|
+
worktreeIsolation: config.worktreeIsolation !== false,
|
|
419
464
|
}
|
|
420
465
|
}
|
|
421
466
|
|
|
@@ -436,6 +481,150 @@ export function normalizeQuestionOptions(raw) {
|
|
|
436
481
|
return options
|
|
437
482
|
}
|
|
438
483
|
|
|
484
|
+
/** 规范化父任务 id(v0.3.5):只接受合法 `t-<数字>` 且禁止自引用,否则返回 null。 */
|
|
485
|
+
export function normalizeParentTaskId(value, selfId = '') {
|
|
486
|
+
const raw = typeof value === 'string' ? value.trim().toLowerCase() : ''
|
|
487
|
+
if (!/^t-[0-9]{1,6}$/.test(raw)) return null
|
|
488
|
+
const self = typeof selfId === 'string' ? selfId.trim().toLowerCase() : ''
|
|
489
|
+
if (self !== '' && raw === self) return null
|
|
490
|
+
return raw
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* v0.4.0:规范化前置依赖任务列表(`dependsOn: string[]`)。
|
|
495
|
+
* 支持传入 `string[]` 或逗号/分号/空白分隔字符串(如 `"t-1, t-2"`);只保留合法 `t-<数字>`,
|
|
496
|
+
* 去重并排除自身 `selfId`,上限 `MAX_DEPENDS_ON`(16)。
|
|
497
|
+
*/
|
|
498
|
+
export function normalizeDependsOn(raw, selfId = '') {
|
|
499
|
+
const self = typeof selfId === 'string' ? selfId.trim().toLowerCase() : ''
|
|
500
|
+
const parts = Array.isArray(raw)
|
|
501
|
+
? raw
|
|
502
|
+
: typeof raw === 'string'
|
|
503
|
+
? raw.split(/[\s,,;;]+/)
|
|
504
|
+
: []
|
|
505
|
+
const out = []
|
|
506
|
+
for (const item of parts) {
|
|
507
|
+
if (typeof item !== 'string') continue
|
|
508
|
+
const id = item.trim().toLowerCase()
|
|
509
|
+
if (!/^t-[0-9]{1,6}$/.test(id)) continue
|
|
510
|
+
if (self !== '' && id === self) continue
|
|
511
|
+
if (out.includes(id)) continue
|
|
512
|
+
out.push(id)
|
|
513
|
+
if (out.length >= MAX_DEPENDS_ON) break
|
|
514
|
+
}
|
|
515
|
+
return out
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* v0.4.0:检测把 `taskId` 的依赖设为 `nextDependsOn` 是否会在板内形成有向环(含自环与传递环)。
|
|
520
|
+
* @returns {string[]|null} 若成环则返回环路径数组(如 `['t-1','t-2','t-1']`),无环返回 `null`。
|
|
521
|
+
*/
|
|
522
|
+
export function findDependencyCycle(state, taskId, nextDependsOn) {
|
|
523
|
+
const start = typeof taskId === 'string' ? taskId.trim().toLowerCase() : ''
|
|
524
|
+
const deps = normalizeDependsOn(nextDependsOn)
|
|
525
|
+
if (start === '' || deps.length === 0) return null
|
|
526
|
+
if (deps.includes(start)) return [start, start]
|
|
527
|
+
const tasks = state && Array.isArray(state.tasks) ? state.tasks : []
|
|
528
|
+
const map = new Map()
|
|
529
|
+
for (const t of tasks) {
|
|
530
|
+
if (t && typeof t.id === 'string') {
|
|
531
|
+
map.set(t.id.toLowerCase(), Array.isArray(t.dependsOn) ? t.dependsOn : [])
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
map.set(start, deps)
|
|
535
|
+
const visiting = new Set([start])
|
|
536
|
+
const visited = new Set()
|
|
537
|
+
const dfs = (current, path) => {
|
|
538
|
+
const children = map.get(current) || []
|
|
539
|
+
for (const next of children) {
|
|
540
|
+
const id = String(next).toLowerCase()
|
|
541
|
+
if (id === start) return [...path, start]
|
|
542
|
+
if (visiting.has(id) || visited.has(id)) continue
|
|
543
|
+
visiting.add(id)
|
|
544
|
+
const hit = dfs(id, [...path, id])
|
|
545
|
+
if (hit) return hit
|
|
546
|
+
visiting.delete(id)
|
|
547
|
+
visited.add(id)
|
|
548
|
+
}
|
|
549
|
+
return null
|
|
550
|
+
}
|
|
551
|
+
return dfs(start, [start])
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* v0.4.0:校验用户 / 模型显式提交的 `dependsOn` 列表(建任务 / 更新任务时调用):
|
|
556
|
+
* - 格式非法或自依赖直接报错(`bad-request` / `conflict`);
|
|
557
|
+
* - 引用的前置任务当前必须在看板中真实存在(防止手误写错不存在的 `t-999`);
|
|
558
|
+
* - 不得构成循环依赖(`conflict`)。
|
|
559
|
+
*/
|
|
560
|
+
function assertValidDependsOnInput(state, selfId, rawDependsOn) {
|
|
561
|
+
const self = typeof selfId === 'string' ? selfId.trim().toLowerCase() : ''
|
|
562
|
+
const rawItems = Array.isArray(rawDependsOn)
|
|
563
|
+
? rawDependsOn
|
|
564
|
+
: typeof rawDependsOn === 'string'
|
|
565
|
+
? rawDependsOn.split(/[\s,,;;]+/).filter((s) => s.trim() !== '')
|
|
566
|
+
: null
|
|
567
|
+
if (rawItems === null) {
|
|
568
|
+
throw new BoardError('bad-request', 'dependsOn 必须是任务 id 数组或逗号分隔字符串')
|
|
569
|
+
}
|
|
570
|
+
const normalized = []
|
|
571
|
+
for (const item of rawItems) {
|
|
572
|
+
if (typeof item !== 'string' || !/^t-[0-9]{1,6}$/i.test(item.trim())) {
|
|
573
|
+
throw new BoardError('bad-request', '非法的前置依赖任务 id:' + String(item))
|
|
574
|
+
}
|
|
575
|
+
const id = item.trim().toLowerCase()
|
|
576
|
+
if (self !== '' && id === self) {
|
|
577
|
+
throw new BoardError('conflict', '任务不能依赖自身:' + id)
|
|
578
|
+
}
|
|
579
|
+
const target = state && Array.isArray(state.tasks) ? state.tasks.find((t) => t && t.id.toLowerCase() === id) : null
|
|
580
|
+
if (!target) {
|
|
581
|
+
throw new BoardError('bad-request', '前置依赖任务不存在:' + id)
|
|
582
|
+
}
|
|
583
|
+
if (!normalized.includes(id)) normalized.push(id)
|
|
584
|
+
if (normalized.length > MAX_DEPENDS_ON) {
|
|
585
|
+
throw new BoardError('bad-request', '单条任务最多设置 ' + MAX_DEPENDS_ON + ' 个前置依赖')
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
if (self !== '' && normalized.length > 0) {
|
|
589
|
+
const cycle = findDependencyCycle(state, self, normalized)
|
|
590
|
+
if (cycle) {
|
|
591
|
+
throw new BoardError('conflict', '任务依赖存在循环引用:' + cycle.join(' → '))
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return normalized
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* v0.4.0:返回当前仍在阻塞 `task` 的未完成前置任务 id 列表。
|
|
599
|
+
* - 前置卡存在且 `status === 'todo' || status === 'doing'` → 仍在阻塞;
|
|
600
|
+
* - 前置卡已 `done` / `archived`,或归档满保留期后已被 `pruneArchivedTasks` 自动淘汰 → 视为已满足,不死锁后置任务。
|
|
601
|
+
*/
|
|
602
|
+
export function unresolvedDependencies(state, task) {
|
|
603
|
+
if (!task || !Array.isArray(task.dependsOn) || task.dependsOn.length === 0) return []
|
|
604
|
+
const tasks = state && Array.isArray(state.tasks) ? state.tasks : []
|
|
605
|
+
const blocking = []
|
|
606
|
+
for (const depId of task.dependsOn) {
|
|
607
|
+
const dep = tasks.find((item) => item && item.id.toLowerCase() === String(depId).toLowerCase())
|
|
608
|
+
if (dep && dep.status !== 'done' && dep.status !== 'archived') {
|
|
609
|
+
blocking.push(dep.id)
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
return blocking
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
function normalizeWorktreeLinks(raw) {
|
|
616
|
+
if (!Array.isArray(raw)) return []
|
|
617
|
+
const out = []
|
|
618
|
+
for (const item of raw) {
|
|
619
|
+
if (typeof item !== 'string') continue
|
|
620
|
+
const rel = item.trim()
|
|
621
|
+
if (rel === '' || out.includes(rel)) continue
|
|
622
|
+
out.push(rel)
|
|
623
|
+
if (out.length >= 32) break
|
|
624
|
+
}
|
|
625
|
+
return out
|
|
626
|
+
}
|
|
627
|
+
|
|
439
628
|
function normalizeTask(raw, index) {
|
|
440
629
|
if (!isPlainObject(raw)) return null
|
|
441
630
|
const status = STATUSES.includes(raw.status) ? raw.status : 'todo'
|
|
@@ -460,6 +649,15 @@ function normalizeTask(raw, index) {
|
|
|
460
649
|
reportedAt: asString(raw.reportedAt) || null,
|
|
461
650
|
// v0.2.0 自动建任务标记(§1.8):只有 'lead-dispatch' 合法,其它一律 null(= 普通任务)。
|
|
462
651
|
autoDispatch: raw.autoDispatch === LEAD_AUTO_MARK ? LEAD_AUTO_MARK : null,
|
|
652
|
+
// v0.3.5 子卡所属父任务 id(fan-out 切片 / 合并 / 验证子卡);顶层任务为 null。
|
|
653
|
+
parentTaskId: normalizeParentTaskId(raw.parentTaskId, id),
|
|
654
|
+
// v0.4.0 前置依赖任务列表(无前置依赖为空数组 [])。
|
|
655
|
+
dependsOn: normalizeDependsOn(raw.dependsOn, id),
|
|
656
|
+
// v0.5.0 Git Worktree 物理隔离记录(无隔离时为 null / [])。
|
|
657
|
+
worktreePath: trimmed(raw.worktreePath, 1024) || null,
|
|
658
|
+
worktreeBranch: trimmed(raw.worktreeBranch, 200) || null,
|
|
659
|
+
worktreeBaseCommit: trimmed(raw.worktreeBaseCommit, 80) || null,
|
|
660
|
+
worktreeLinks: normalizeWorktreeLinks(raw.worktreeLinks),
|
|
463
661
|
// v0.2.2「待你处理」(§1.9):不新增 status,只在任务上打标记 + 问题 / 选项 / 提问者。
|
|
464
662
|
needsUser,
|
|
465
663
|
question: needsUser ? question : '',
|
|
@@ -471,9 +669,14 @@ function normalizeTask(raw, index) {
|
|
|
471
669
|
cwd: typeof raw.cwd === 'string' && raw.cwd !== '' ? raw.cwd : null,
|
|
472
670
|
assignee: trimmed(raw.assignee, 200),
|
|
473
671
|
// v0.2.9(§2):宿主独占的「执行会话 id / 执行状态」。模型不可写(不在 taskboard_update 白名单、
|
|
474
|
-
// applyTaskUpdate 也不读这两个键),老 board.json 缺字段一律 null
|
|
672
|
+
// applyTaskUpdate 也不读这两个键),老 board.json 缺字段一律 null;v0.3.9:终态(done/archived)下
|
|
673
|
+
// 历史残留的 'running' 读盘自动收敛为 'ended'。
|
|
475
674
|
workerSessionId: trimmed(raw.workerSessionId, 200) || null,
|
|
476
|
-
workerRunState: WORKER_RUN_STATES.includes(raw.workerRunState)
|
|
675
|
+
workerRunState: WORKER_RUN_STATES.includes(raw.workerRunState)
|
|
676
|
+
? raw.workerRunState === 'running' && (status === 'done' || status === 'archived')
|
|
677
|
+
? 'ended'
|
|
678
|
+
: raw.workerRunState
|
|
679
|
+
: null,
|
|
477
680
|
result: truncateNote(raw.result, MAX_NOTE_CHARS),
|
|
478
681
|
createdAt: asString(raw.createdAt) || iso(Date.now()),
|
|
479
682
|
updatedAt: asString(raw.updatedAt) || asString(raw.createdAt) || iso(Date.now()),
|
|
@@ -844,6 +1047,606 @@ export async function readAttachment(id, options = {}) {
|
|
|
844
1047
|
}
|
|
845
1048
|
}
|
|
846
1049
|
|
|
1050
|
+
/* ------------------------------------------------------------------ *
|
|
1051
|
+
* Git Worktree 物理隔离与依赖软链引擎(v0.5.0)
|
|
1052
|
+
* ------------------------------------------------------------------ */
|
|
1053
|
+
|
|
1054
|
+
/** Worktree 根目录:默认与 board.json 同级的 worktrees/(即 $DSH_HOME/storages/dsh-taskboard/worktrees)。 */
|
|
1055
|
+
export function worktreesDir(boardFilePath = boardPath()) {
|
|
1056
|
+
const target = typeof boardFilePath === 'string' && boardFilePath.trim() !== '' ? boardFilePath.trim() : boardPath()
|
|
1057
|
+
return join(dirname(target), WORKTREE_DIRNAME)
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/**
|
|
1061
|
+
* 快速向上查找包含 `.git` 的目录(纯 fs 检测,零子进程开销)。
|
|
1062
|
+
* 对单测假路径(`C:\work\a`)或非 Git 目录在 <0.1ms 内返回 `null`。
|
|
1063
|
+
*/
|
|
1064
|
+
export function findDotGitUpwards(startDir) {
|
|
1065
|
+
const raw = typeof startDir === 'string' ? startDir.trim() : ''
|
|
1066
|
+
if (raw === '' || !existsSync(raw)) return null
|
|
1067
|
+
let cur = resolve(raw)
|
|
1068
|
+
for (let depth = 0; depth < 64; depth += 1) {
|
|
1069
|
+
try {
|
|
1070
|
+
if (existsSync(join(cur, '.git'))) return cur
|
|
1071
|
+
} catch {
|
|
1072
|
+
return null
|
|
1073
|
+
}
|
|
1074
|
+
const parent = dirname(cur)
|
|
1075
|
+
if (!parent || parent === cur) break
|
|
1076
|
+
cur = parent
|
|
1077
|
+
}
|
|
1078
|
+
return null
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
const gitRepoInfoCache = new Map()
|
|
1082
|
+
|
|
1083
|
+
export function clearGitRepoInfoCache() {
|
|
1084
|
+
gitRepoInfoCache.clear()
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
/**
|
|
1088
|
+
* 解析目标目录所属的 Git 主仓库根目录与当前 `HEAD` 提交。
|
|
1089
|
+
* 若不是 Git 仓库或尚无任何 commit(无 `HEAD`),返回 `null`(自动退回单目录串行模式)。
|
|
1090
|
+
* @param {string} startDir
|
|
1091
|
+
* @param {{fresh?:boolean, now?:number}} [options]
|
|
1092
|
+
* @returns {{repoRoot:string, headCommit:string}|null}
|
|
1093
|
+
*/
|
|
1094
|
+
export function resolveGitRepoInfo(startDir, options = {}) {
|
|
1095
|
+
const dotGitHolder = findDotGitUpwards(startDir)
|
|
1096
|
+
if (!dotGitHolder) return null
|
|
1097
|
+
const cacheKey = normalizePathForCompare(dotGitHolder)
|
|
1098
|
+
const now = typeof options.now === 'number' ? options.now : Date.now()
|
|
1099
|
+
if (options.fresh !== true && cacheKey !== '') {
|
|
1100
|
+
const cached = gitRepoInfoCache.get(cacheKey)
|
|
1101
|
+
if (cached && now - cached.at < GIT_INFO_CACHE_MS) {
|
|
1102
|
+
return cached.value
|
|
1103
|
+
}
|
|
1104
|
+
}
|
|
1105
|
+
try {
|
|
1106
|
+
const topRaw = execFileSync('git', ['-C', dotGitHolder, 'rev-parse', '--show-toplevel'], {
|
|
1107
|
+
encoding: 'utf8',
|
|
1108
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1109
|
+
windowsHide: true,
|
|
1110
|
+
timeout: 5000,
|
|
1111
|
+
}).trim()
|
|
1112
|
+
if (topRaw === '') return null
|
|
1113
|
+
const repoRoot = resolve(topRaw)
|
|
1114
|
+
const headCommit = execFileSync('git', ['-C', repoRoot, 'rev-parse', '--verify', 'HEAD'], {
|
|
1115
|
+
encoding: 'utf8',
|
|
1116
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1117
|
+
windowsHide: true,
|
|
1118
|
+
timeout: 5000,
|
|
1119
|
+
}).trim()
|
|
1120
|
+
if (!/^[0-9a-f]{40}$/i.test(headCommit)) {
|
|
1121
|
+
if (cacheKey !== '') gitRepoInfoCache.set(cacheKey, { value: null, at: now })
|
|
1122
|
+
return null
|
|
1123
|
+
}
|
|
1124
|
+
const value = { repoRoot, headCommit }
|
|
1125
|
+
if (cacheKey !== '') gitRepoInfoCache.set(cacheKey, { value, at: now })
|
|
1126
|
+
return value
|
|
1127
|
+
} catch {
|
|
1128
|
+
if (cacheKey !== '') gitRepoInfoCache.set(cacheKey, { value: null, at: now })
|
|
1129
|
+
return null
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
function isSymlinkPath(targetPath) {
|
|
1134
|
+
try {
|
|
1135
|
+
return lstatSync(targetPath).isSymbolicLink()
|
|
1136
|
+
} catch {
|
|
1137
|
+
return false
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
/**
|
|
1142
|
+
* 将主工作区已有的依赖目录(`node_modules` / `.venv` / `venv`,含一级子项目)通过目录 Junction
|
|
1143
|
+
* 软链进隔离 Worktree,使 worker 无需重新 `npm install` 即可直接跑单测或类型检查。
|
|
1144
|
+
*/
|
|
1145
|
+
export function linkWorktreeDependencies(repoRoot, wtPath) {
|
|
1146
|
+
const linked = []
|
|
1147
|
+
if (typeof repoRoot !== 'string' || repoRoot === '' || typeof wtPath !== 'string' || wtPath === '') return linked
|
|
1148
|
+
if (!existsSync(repoRoot) || !existsSync(wtPath)) return linked
|
|
1149
|
+
|
|
1150
|
+
const candidates = [...WORKTREE_DEP_DIRS]
|
|
1151
|
+
try {
|
|
1152
|
+
const entries = readdirSync(repoRoot, { withFileTypes: true })
|
|
1153
|
+
for (const entry of entries) {
|
|
1154
|
+
if (!entry || !entry.isDirectory()) continue
|
|
1155
|
+
const sub = entry.name
|
|
1156
|
+
if (!sub || sub.startsWith('.') || WORKTREE_SCAN_SKIP_DIRS.has(sub)) continue
|
|
1157
|
+
if (!existsSync(join(wtPath, sub))) continue
|
|
1158
|
+
for (const dep of WORKTREE_DEP_DIRS) {
|
|
1159
|
+
candidates.push(join(sub, dep))
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
} catch {
|
|
1163
|
+
/* ignore subdir scan errors */
|
|
1164
|
+
}
|
|
1165
|
+
|
|
1166
|
+
const linkType = process.platform === 'win32' ? 'junction' : 'dir'
|
|
1167
|
+
for (const rel of candidates) {
|
|
1168
|
+
if (linked.length >= 32) break
|
|
1169
|
+
const src = join(repoRoot, rel)
|
|
1170
|
+
const dst = join(wtPath, rel)
|
|
1171
|
+
try {
|
|
1172
|
+
if (!existsSync(src)) continue
|
|
1173
|
+
const srcStat = lstatSync(src)
|
|
1174
|
+
if (!srcStat.isDirectory() && !srcStat.isSymbolicLink()) continue
|
|
1175
|
+
if (existsSync(dst) || isSymlinkPath(dst)) continue
|
|
1176
|
+
symlinkSync(src, dst, linkType)
|
|
1177
|
+
linked.push(rel)
|
|
1178
|
+
} catch {
|
|
1179
|
+
/* best-effort per dependency dir */
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
return linked
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
/**
|
|
1186
|
+
* 安全卸载 Worktree 内的所有依赖软链(Junction / symlink)。
|
|
1187
|
+
* 必须在任何 `git add -A`、`git worktree remove` 或 `rmSync` 之前调用,确保主仓 `node_modules` 毫发无损。
|
|
1188
|
+
*/
|
|
1189
|
+
export function unlinkWorktreeJunctions(wtPath, recordedLinks = []) {
|
|
1190
|
+
if (typeof wtPath !== 'string' || wtPath.trim() === '' || !existsSync(wtPath)) return 0
|
|
1191
|
+
const candidates = new Set(normalizeWorktreeLinks(recordedLinks))
|
|
1192
|
+
for (const dep of WORKTREE_DEP_DIRS) candidates.add(dep)
|
|
1193
|
+
try {
|
|
1194
|
+
const entries = readdirSync(wtPath, { withFileTypes: true })
|
|
1195
|
+
for (const entry of entries) {
|
|
1196
|
+
if (!entry || !entry.isDirectory()) continue
|
|
1197
|
+
const sub = entry.name
|
|
1198
|
+
if (!sub || sub === '.git' || WORKTREE_DEP_DIRS.includes(sub)) continue
|
|
1199
|
+
for (const dep of WORKTREE_DEP_DIRS) candidates.add(join(sub, dep))
|
|
1200
|
+
}
|
|
1201
|
+
} catch {
|
|
1202
|
+
/* ignore */
|
|
1203
|
+
}
|
|
1204
|
+
let removed = 0
|
|
1205
|
+
for (const rel of candidates) {
|
|
1206
|
+
const full = join(wtPath, rel)
|
|
1207
|
+
try {
|
|
1208
|
+
if (lstatSync(full).isSymbolicLink()) {
|
|
1209
|
+
unlinkSync(full)
|
|
1210
|
+
removed += 1
|
|
1211
|
+
}
|
|
1212
|
+
} catch {
|
|
1213
|
+
/* already unlinked or missing */
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
return removed
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
function repoWorktreeSlug(repoRoot) {
|
|
1220
|
+
const tail = (baseName(repoRoot) || 'repo').replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 32) || 'repo'
|
|
1221
|
+
const hash = createHash('sha1').update(normalizePathForCompare(repoRoot)).digest('hex').slice(0, 8)
|
|
1222
|
+
return tail + '-' + hash
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
function inferRepoRootFromWorktreeDotGit(wtPath) {
|
|
1226
|
+
try {
|
|
1227
|
+
const dotGitFile = join(wtPath, '.git')
|
|
1228
|
+
if (!existsSync(dotGitFile) || lstatSync(dotGitFile).isDirectory()) return ''
|
|
1229
|
+
const text = readFileSync(dotGitFile, 'utf8').trim()
|
|
1230
|
+
const match = /^gitdir:\s*(.+)$/i.exec(text)
|
|
1231
|
+
if (!match) return ''
|
|
1232
|
+
const gitWorktreeAdmin = resolve(wtPath, match[1].trim())
|
|
1233
|
+
const worktreesParent = dirname(gitWorktreeAdmin)
|
|
1234
|
+
if (baseName(worktreesParent).toLowerCase() !== 'worktrees') return ''
|
|
1235
|
+
const dotGitDir = dirname(worktreesParent)
|
|
1236
|
+
if (baseName(dotGitDir).toLowerCase() === '.git') return dirname(dotGitDir)
|
|
1237
|
+
} catch {
|
|
1238
|
+
/* ignore */
|
|
1239
|
+
}
|
|
1240
|
+
return ''
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* 为指定看板任务创建(或复用)隔离的 Git Worktree 与临时分支 `taskboard/<taskId>`。
|
|
1245
|
+
*/
|
|
1246
|
+
export function ensureTaskWorktree(rt, task, repoInfo = null) {
|
|
1247
|
+
if (!isPlainObject(task)) return null
|
|
1248
|
+
const cwd = asString(task.cwd).trim()
|
|
1249
|
+
if (cwd === '') return null
|
|
1250
|
+
const info = repoInfo || resolveGitRepoInfo(cwd, { fresh: true })
|
|
1251
|
+
if (!info) return null
|
|
1252
|
+
const { repoRoot, headCommit } = info
|
|
1253
|
+
const safeTaskId = asString(task.id).trim().replace(/[^A-Za-z0-9._-]/g, '_')
|
|
1254
|
+
if (safeTaskId === '') return null
|
|
1255
|
+
const branch = 'taskboard/' + safeTaskId
|
|
1256
|
+
|
|
1257
|
+
// 失败子卡换新 worker 接手重派时:若原 Worktree 目录仍在盘上,直接复用并补齐依赖软链(保留前序半成品进度)。
|
|
1258
|
+
const existingPath = asString(task.worktreePath).trim()
|
|
1259
|
+
if (existingPath !== '' && existsSync(existingPath)) {
|
|
1260
|
+
const newLinks = linkWorktreeDependencies(repoRoot, existingPath)
|
|
1261
|
+
task.worktreeLinks = normalizeWorktreeLinks([...(Array.isArray(task.worktreeLinks) ? task.worktreeLinks : []), ...newLinks])
|
|
1262
|
+
if (!task.worktreeBranch) task.worktreeBranch = branch
|
|
1263
|
+
if (!task.worktreeBaseCommit) task.worktreeBaseCommit = headCommit
|
|
1264
|
+
if (rt && rt.state) commitBoard(rt.state, rt.filePath)
|
|
1265
|
+
return {
|
|
1266
|
+
worktreePath: existingPath,
|
|
1267
|
+
branch: task.worktreeBranch,
|
|
1268
|
+
baseCommit: task.worktreeBaseCommit,
|
|
1269
|
+
links: task.worktreeLinks,
|
|
1270
|
+
reused: true,
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
const wtParent = join(worktreesDir(rt && rt.filePath), repoWorktreeSlug(repoRoot))
|
|
1275
|
+
const wtPath = join(wtParent, safeTaskId)
|
|
1276
|
+
mkdirSync(wtParent, { recursive: true })
|
|
1277
|
+
|
|
1278
|
+
if (existsSync(wtPath)) {
|
|
1279
|
+
unlinkWorktreeJunctions(wtPath, task.worktreeLinks)
|
|
1280
|
+
try {
|
|
1281
|
+
execFileSync('git', ['-C', repoRoot, 'worktree', 'remove', '--force', wtPath], {
|
|
1282
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1283
|
+
windowsHide: true,
|
|
1284
|
+
timeout: 10000,
|
|
1285
|
+
})
|
|
1286
|
+
} catch {
|
|
1287
|
+
rmSync(wtPath, { recursive: true, force: true })
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
try {
|
|
1291
|
+
execFileSync('git', ['-C', repoRoot, 'worktree', 'prune'], {
|
|
1292
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1293
|
+
windowsHide: true,
|
|
1294
|
+
timeout: 5000,
|
|
1295
|
+
})
|
|
1296
|
+
} catch {
|
|
1297
|
+
/* ignore */
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
execFileSync('git', ['-C', repoRoot, 'worktree', 'add', '-B', branch, wtPath, headCommit], {
|
|
1301
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1302
|
+
windowsHide: true,
|
|
1303
|
+
timeout: 15000,
|
|
1304
|
+
})
|
|
1305
|
+
const links = linkWorktreeDependencies(repoRoot, wtPath)
|
|
1306
|
+
task.worktreePath = wtPath
|
|
1307
|
+
task.worktreeBranch = branch
|
|
1308
|
+
task.worktreeBaseCommit = headCommit
|
|
1309
|
+
task.worktreeLinks = links
|
|
1310
|
+
task.updatedAt = iso(Date.now())
|
|
1311
|
+
if (rt && rt.state) commitBoard(rt.state, rt.filePath)
|
|
1312
|
+
return { worktreePath: wtPath, branch, baseCommit: headCommit, links, reused: false }
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/**
|
|
1316
|
+
* 清理任务关联的隔离 Git Worktree 目录与 `taskboard/<id>` 临时分支(幂等、best-effort,永不抛错)。
|
|
1317
|
+
*/
|
|
1318
|
+
export function cleanupTaskWorktree(task, repoRootHint = '') {
|
|
1319
|
+
if (!isPlainObject(task)) return { cleaned: false }
|
|
1320
|
+
const wtPath = asString(task.worktreePath).trim()
|
|
1321
|
+
const branch = asString(task.worktreeBranch).trim()
|
|
1322
|
+
if (wtPath === '' && branch === '') return { cleaned: false }
|
|
1323
|
+
|
|
1324
|
+
if (wtPath !== '') {
|
|
1325
|
+
unlinkWorktreeJunctions(wtPath, task.worktreeLinks)
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
const repoRoot =
|
|
1329
|
+
(typeof repoRootHint === 'string' && repoRootHint.trim() !== '' ? repoRootHint.trim() : '') ||
|
|
1330
|
+
findDotGitUpwards(asString(task.cwd)) ||
|
|
1331
|
+
(wtPath !== '' ? inferRepoRootFromWorktreeDotGit(wtPath) : '')
|
|
1332
|
+
|
|
1333
|
+
if (repoRoot && wtPath !== '') {
|
|
1334
|
+
try {
|
|
1335
|
+
execFileSync('git', ['-C', repoRoot, 'worktree', 'remove', '--force', wtPath], {
|
|
1336
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1337
|
+
windowsHide: true,
|
|
1338
|
+
timeout: 10000,
|
|
1339
|
+
})
|
|
1340
|
+
} catch {
|
|
1341
|
+
/* fallback rmSync below */
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
if (wtPath !== '' && existsSync(wtPath)) {
|
|
1345
|
+
unlinkWorktreeJunctions(wtPath, task.worktreeLinks)
|
|
1346
|
+
try {
|
|
1347
|
+
rmSync(wtPath, { recursive: true, force: true })
|
|
1348
|
+
} catch {
|
|
1349
|
+
/* ignore */
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
if (repoRoot) {
|
|
1353
|
+
try {
|
|
1354
|
+
execFileSync('git', ['-C', repoRoot, 'worktree', 'prune'], {
|
|
1355
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1356
|
+
windowsHide: true,
|
|
1357
|
+
timeout: 5000,
|
|
1358
|
+
})
|
|
1359
|
+
} catch {
|
|
1360
|
+
/* ignore */
|
|
1361
|
+
}
|
|
1362
|
+
if (branch !== '' && branch.startsWith('taskboard/')) {
|
|
1363
|
+
try {
|
|
1364
|
+
execFileSync('git', ['-C', repoRoot, 'branch', '-D', branch], {
|
|
1365
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1366
|
+
windowsHide: true,
|
|
1367
|
+
timeout: 5000,
|
|
1368
|
+
})
|
|
1369
|
+
} catch {
|
|
1370
|
+
/* branch may already be deleted */
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
task.worktreePath = null
|
|
1376
|
+
task.worktreeBranch = null
|
|
1377
|
+
task.worktreeBaseCommit = null
|
|
1378
|
+
task.worktreeLinks = []
|
|
1379
|
+
return { cleaned: true }
|
|
1380
|
+
}
|
|
1381
|
+
|
|
1382
|
+
/** 从 `git apply --check` 的 stderr 提取冲突文件列表。 */
|
|
1383
|
+
export function extractGitApplyConflictFiles(stderrText) {
|
|
1384
|
+
const files = []
|
|
1385
|
+
const push = (raw) => {
|
|
1386
|
+
const clean = typeof raw === 'string' ? raw.trim() : ''
|
|
1387
|
+
if (clean !== '' && !files.includes(clean)) files.push(clean)
|
|
1388
|
+
}
|
|
1389
|
+
for (const line of String(stderrText || '').split(/\r?\n/)) {
|
|
1390
|
+
let m = /^error:\s+patch failed:\s+(.+?):\d+\s*$/i.exec(line)
|
|
1391
|
+
if (m) {
|
|
1392
|
+
push(m[1])
|
|
1393
|
+
continue
|
|
1394
|
+
}
|
|
1395
|
+
m =
|
|
1396
|
+
/^error:\s+(.+?):\s+(?:patch does not apply|already exists in working directory|does not exist in working tree|typechange|cannot read)/i.exec(
|
|
1397
|
+
line,
|
|
1398
|
+
)
|
|
1399
|
+
if (m) push(m[1])
|
|
1400
|
+
}
|
|
1401
|
+
return files
|
|
1402
|
+
}
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* 将指定任务的隔离 Git Worktree 改动原子预检并合入主工作区,成功后自动回收 Worktree 与临时分支。
|
|
1406
|
+
*
|
|
1407
|
+
* - 先卸载所有依赖 Junction,再把 Worktree 内未提交文件快照提交至临时分支 `taskboard/<id>`;
|
|
1408
|
+
* - 用 `git diff --binary --full-index -U1 <base>..<wtHead>` 生成补丁,先在主工作区跑 `git apply --check`:
|
|
1409
|
+
* - 通过 → `git apply` 写入主工作区(兼容主工作区已有未提交 WIP 或前序切片改动,不污染主分支 commit 历史);
|
|
1410
|
+
* - 若 `--check` 失败但 `--check --reverse` 通过 → 说明完全相同的补丁已合入过,按幂等成功处理;
|
|
1411
|
+
* - 真实冲突 → 主工作区保持 100% 未修改,恢复 Worktree 依赖软链并返回 `{merged:false, conflict:true, conflictFiles}`。
|
|
1412
|
+
*/
|
|
1413
|
+
export function mergeAndCleanupTaskWorktree(rt, taskId, options = {}) {
|
|
1414
|
+
const task = findTask(rt.state, taskId)
|
|
1415
|
+
const wtPath = asString(task.worktreePath).trim()
|
|
1416
|
+
const branch = asString(task.worktreeBranch).trim()
|
|
1417
|
+
const cleanup = options.cleanup !== false
|
|
1418
|
+
const discardOnly = options.discardOnly === true
|
|
1419
|
+
const shouldCommitBoard = options.commit !== false
|
|
1420
|
+
|
|
1421
|
+
if (wtPath === '' && branch === '') {
|
|
1422
|
+
return {
|
|
1423
|
+
id: task.id,
|
|
1424
|
+
merged: false,
|
|
1425
|
+
noChanges: true,
|
|
1426
|
+
conflict: false,
|
|
1427
|
+
cleaned: true,
|
|
1428
|
+
branch: '',
|
|
1429
|
+
worktreePath: '',
|
|
1430
|
+
conflictFiles: [],
|
|
1431
|
+
summary: '该任务未关联隔离工作树(无需合入)',
|
|
1432
|
+
}
|
|
1433
|
+
}
|
|
1434
|
+
|
|
1435
|
+
const repoInfo = resolveGitRepoInfo(asString(task.cwd), { fresh: true })
|
|
1436
|
+
if (!repoInfo) {
|
|
1437
|
+
if (discardOnly) {
|
|
1438
|
+
cleanupTaskWorktree(task)
|
|
1439
|
+
task.updatedAt = iso(Date.now())
|
|
1440
|
+
if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
|
|
1441
|
+
return {
|
|
1442
|
+
id: task.id,
|
|
1443
|
+
merged: false,
|
|
1444
|
+
noChanges: false,
|
|
1445
|
+
conflict: false,
|
|
1446
|
+
cleaned: true,
|
|
1447
|
+
branch,
|
|
1448
|
+
worktreePath: '',
|
|
1449
|
+
conflictFiles: [],
|
|
1450
|
+
summary: '已清理隔离工作树记录',
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
throw new BoardError('conflict', '无法解析任务主工作区 Git 仓库:' + asString(task.cwd))
|
|
1454
|
+
}
|
|
1455
|
+
const { repoRoot } = repoInfo
|
|
1456
|
+
|
|
1457
|
+
if (discardOnly) {
|
|
1458
|
+
cleanupTaskWorktree(task, repoRoot)
|
|
1459
|
+
task.updatedAt = iso(Date.now())
|
|
1460
|
+
if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
|
|
1461
|
+
return {
|
|
1462
|
+
id: task.id,
|
|
1463
|
+
merged: false,
|
|
1464
|
+
noChanges: false,
|
|
1465
|
+
conflict: false,
|
|
1466
|
+
cleaned: true,
|
|
1467
|
+
branch,
|
|
1468
|
+
worktreePath: '',
|
|
1469
|
+
conflictFiles: [],
|
|
1470
|
+
summary: '已丢弃隔离工作树改动并回收临时分支 ' + (branch || wtPath),
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
if (wtPath === '' || !existsSync(wtPath)) {
|
|
1475
|
+
cleanupTaskWorktree(task, repoRoot)
|
|
1476
|
+
task.updatedAt = iso(Date.now())
|
|
1477
|
+
if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
|
|
1478
|
+
throw new BoardError('not-found', '隔离工作树目录不存在,无法合入:' + (wtPath || branch))
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
// 1) 必须先卸载全部依赖 Junction,防止 git add -A 把主仓 node_modules/.venv 扫进临时分支!
|
|
1482
|
+
unlinkWorktreeJunctions(wtPath, task.worktreeLinks)
|
|
1483
|
+
|
|
1484
|
+
// 2) 将 worker 在隔离工作树内未提交的改动(含新建/删除文件)快照提交到临时分支
|
|
1485
|
+
const statusOut = execFileSync('git', ['-C', wtPath, 'status', '--porcelain'], {
|
|
1486
|
+
encoding: 'utf8',
|
|
1487
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1488
|
+
windowsHide: true,
|
|
1489
|
+
timeout: 10000,
|
|
1490
|
+
}).trim()
|
|
1491
|
+
if (statusOut !== '') {
|
|
1492
|
+
execFileSync('git', ['-C', wtPath, 'add', '-A'], {
|
|
1493
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1494
|
+
windowsHide: true,
|
|
1495
|
+
timeout: 10000,
|
|
1496
|
+
})
|
|
1497
|
+
execFileSync(
|
|
1498
|
+
'git',
|
|
1499
|
+
[
|
|
1500
|
+
'-C',
|
|
1501
|
+
wtPath,
|
|
1502
|
+
'-c',
|
|
1503
|
+
'user.name=dsh-taskboard',
|
|
1504
|
+
'-c',
|
|
1505
|
+
'user.email=taskboard@local',
|
|
1506
|
+
'commit',
|
|
1507
|
+
'-m',
|
|
1508
|
+
'chore(taskboard): snapshot ' + task.id,
|
|
1509
|
+
'--no-verify',
|
|
1510
|
+
],
|
|
1511
|
+
{
|
|
1512
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1513
|
+
windowsHide: true,
|
|
1514
|
+
timeout: 15000,
|
|
1515
|
+
},
|
|
1516
|
+
)
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// 3) 计算相对基线 commit 的补丁
|
|
1520
|
+
const wtHead = execFileSync('git', ['-C', wtPath, 'rev-parse', 'HEAD'], {
|
|
1521
|
+
encoding: 'utf8',
|
|
1522
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1523
|
+
windowsHide: true,
|
|
1524
|
+
timeout: 5000,
|
|
1525
|
+
}).trim()
|
|
1526
|
+
let baseCommit = asString(task.worktreeBaseCommit).trim()
|
|
1527
|
+
if (baseCommit === '') {
|
|
1528
|
+
baseCommit = execFileSync('git', ['-C', repoRoot, 'merge-base', 'HEAD', wtHead], {
|
|
1529
|
+
encoding: 'utf8',
|
|
1530
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1531
|
+
windowsHide: true,
|
|
1532
|
+
timeout: 5000,
|
|
1533
|
+
}).trim()
|
|
1534
|
+
}
|
|
1535
|
+
|
|
1536
|
+
const finishNoChanges = () => {
|
|
1537
|
+
let cleaned = false
|
|
1538
|
+
if (cleanup) {
|
|
1539
|
+
cleanupTaskWorktree(task, repoRoot)
|
|
1540
|
+
cleaned = true
|
|
1541
|
+
} else {
|
|
1542
|
+
task.worktreeLinks = linkWorktreeDependencies(repoRoot, wtPath)
|
|
1543
|
+
}
|
|
1544
|
+
task.updatedAt = iso(Date.now())
|
|
1545
|
+
if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
|
|
1546
|
+
return {
|
|
1547
|
+
id: task.id,
|
|
1548
|
+
merged: false,
|
|
1549
|
+
noChanges: true,
|
|
1550
|
+
conflict: false,
|
|
1551
|
+
cleaned,
|
|
1552
|
+
branch,
|
|
1553
|
+
worktreePath: task.worktreePath || '',
|
|
1554
|
+
conflictFiles: [],
|
|
1555
|
+
summary: '隔离工作树无文件改动' + (cleaned ? ',已回收临时工作树' : ''),
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
if (wtHead === baseCommit) return finishNoChanges()
|
|
1560
|
+
|
|
1561
|
+
const diffBuf = execFileSync(
|
|
1562
|
+
'git',
|
|
1563
|
+
['-C', wtPath, 'diff', '--binary', '--full-index', '-U1', baseCommit + '..' + wtHead],
|
|
1564
|
+
{
|
|
1565
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
1566
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
1567
|
+
windowsHide: true,
|
|
1568
|
+
timeout: 15000,
|
|
1569
|
+
},
|
|
1570
|
+
)
|
|
1571
|
+
if (!diffBuf || diffBuf.length === 0) return finishNoChanges()
|
|
1572
|
+
|
|
1573
|
+
// 4) 主工作区原子预检(不触碰 git index,失败绝不留半截改动或冲突标记)
|
|
1574
|
+
let alreadyApplied = false
|
|
1575
|
+
try {
|
|
1576
|
+
execFileSync('git', ['-C', repoRoot, 'apply', '--check', '--whitespace=nowarn', '-'], {
|
|
1577
|
+
input: diffBuf,
|
|
1578
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1579
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
1580
|
+
windowsHide: true,
|
|
1581
|
+
timeout: 15000,
|
|
1582
|
+
})
|
|
1583
|
+
} catch (checkError) {
|
|
1584
|
+
try {
|
|
1585
|
+
execFileSync('git', ['-C', repoRoot, 'apply', '--check', '--reverse', '--whitespace=nowarn', '-'], {
|
|
1586
|
+
input: diffBuf,
|
|
1587
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1588
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
1589
|
+
windowsHide: true,
|
|
1590
|
+
timeout: 10000,
|
|
1591
|
+
})
|
|
1592
|
+
alreadyApplied = true
|
|
1593
|
+
} catch {
|
|
1594
|
+
alreadyApplied = false
|
|
1595
|
+
}
|
|
1596
|
+
if (!alreadyApplied) {
|
|
1597
|
+
task.worktreeLinks = linkWorktreeDependencies(repoRoot, wtPath)
|
|
1598
|
+
const stderrText = String((checkError && checkError.stderr) || describeError(checkError))
|
|
1599
|
+
const conflictFiles = extractGitApplyConflictFiles(stderrText)
|
|
1600
|
+
task.updatedAt = iso(Date.now())
|
|
1601
|
+
if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
|
|
1602
|
+
const conflictDesc =
|
|
1603
|
+
conflictFiles.length > 0 ? conflictFiles.join(', ') : flattenResultLine(stderrText, 180)
|
|
1604
|
+
return {
|
|
1605
|
+
id: task.id,
|
|
1606
|
+
merged: false,
|
|
1607
|
+
noChanges: false,
|
|
1608
|
+
conflict: true,
|
|
1609
|
+
cleaned: false,
|
|
1610
|
+
branch,
|
|
1611
|
+
worktreePath: wtPath,
|
|
1612
|
+
conflictFiles,
|
|
1613
|
+
summary: '合入主工作区检测到冲突(主工作区未被修改):' + conflictDesc + ';隔离工作树保留在 ' + wtPath,
|
|
1614
|
+
}
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
if (!alreadyApplied) {
|
|
1619
|
+
execFileSync('git', ['-C', repoRoot, 'apply', '--whitespace=nowarn', '-'], {
|
|
1620
|
+
input: diffBuf,
|
|
1621
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
1622
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
1623
|
+
windowsHide: true,
|
|
1624
|
+
timeout: 15000,
|
|
1625
|
+
})
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
let cleaned = false
|
|
1629
|
+
if (cleanup) {
|
|
1630
|
+
cleanupTaskWorktree(task, repoRoot)
|
|
1631
|
+
cleaned = true
|
|
1632
|
+
} else {
|
|
1633
|
+
task.worktreeLinks = linkWorktreeDependencies(repoRoot, wtPath)
|
|
1634
|
+
}
|
|
1635
|
+
task.updatedAt = iso(Date.now())
|
|
1636
|
+
if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
|
|
1637
|
+
return {
|
|
1638
|
+
id: task.id,
|
|
1639
|
+
merged: true,
|
|
1640
|
+
noChanges: false,
|
|
1641
|
+
conflict: false,
|
|
1642
|
+
cleaned,
|
|
1643
|
+
branch,
|
|
1644
|
+
worktreePath: task.worktreePath || '',
|
|
1645
|
+
conflictFiles: [],
|
|
1646
|
+
summary: '已将隔离工作树改动合入主工作区' + (cleaned ? '并清理临时分支 ' + branch : ''),
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
|
|
847
1650
|
/* ------------------------------------------------------------------ *
|
|
848
1651
|
* 任务操作(纯函数,便于单测)
|
|
849
1652
|
* ------------------------------------------------------------------ */
|
|
@@ -872,6 +1675,11 @@ export function addTask(state, input, now = Date.now()) {
|
|
|
872
1675
|
if (needsUser && question === '') {
|
|
873
1676
|
throw new BoardError('bad-request', 'needsUser=true 时必须提供非空的 question')
|
|
874
1677
|
}
|
|
1678
|
+
const pendingId = 't-' + state.nextId
|
|
1679
|
+
const dependsOn =
|
|
1680
|
+
input.dependsOn !== undefined && input.dependsOn !== null
|
|
1681
|
+
? assertValidDependsOnInput(state, pendingId, input.dependsOn)
|
|
1682
|
+
: []
|
|
875
1683
|
const stamp = iso(now)
|
|
876
1684
|
const task = {
|
|
877
1685
|
id: nextTaskId(state),
|
|
@@ -885,6 +1693,12 @@ export function addTask(state, input, now = Date.now()) {
|
|
|
885
1693
|
dispatchedSessionTitle: '',
|
|
886
1694
|
reportedAt: null,
|
|
887
1695
|
autoDispatch: null,
|
|
1696
|
+
parentTaskId: null,
|
|
1697
|
+
dependsOn,
|
|
1698
|
+
worktreePath: null,
|
|
1699
|
+
worktreeBranch: null,
|
|
1700
|
+
worktreeBaseCommit: null,
|
|
1701
|
+
worktreeLinks: [],
|
|
888
1702
|
needsUser,
|
|
889
1703
|
question: needsUser ? question : '',
|
|
890
1704
|
questionOptions: needsUser ? normalizeQuestionOptions(input.questionOptions) : [],
|
|
@@ -907,6 +1721,7 @@ export function addTask(state, input, now = Date.now()) {
|
|
|
907
1721
|
notificationCount: 0,
|
|
908
1722
|
lastError: '',
|
|
909
1723
|
}
|
|
1724
|
+
task.parentTaskId = normalizeParentTaskId(input.parentTaskId, task.id)
|
|
910
1725
|
state.tasks.push(task)
|
|
911
1726
|
return task
|
|
912
1727
|
}
|
|
@@ -946,6 +1761,11 @@ export function applyTaskUpdate(state, id, patch, now = Date.now()) {
|
|
|
946
1761
|
nextTitle = trimmed(patch.title, MAX_TITLE_CHARS)
|
|
947
1762
|
if (nextTitle === '') throw new BoardError('bad-request', '标题不能为空')
|
|
948
1763
|
}
|
|
1764
|
+
let nextDependsOn = null
|
|
1765
|
+
if (patch.dependsOn !== undefined) {
|
|
1766
|
+
nextDependsOn =
|
|
1767
|
+
patch.dependsOn === null ? [] : assertValidDependsOnInput(state, task.id, patch.dependsOn)
|
|
1768
|
+
}
|
|
949
1769
|
// v0.2.3(§1.9):归档是终态,看板「待你处理」派生明确排除 archived(lib/client.js),
|
|
950
1770
|
// 在归档任务上提问只会静默石沉大海。这里直接拒绝:本次 patch 没有同时改 status(重开 / 再次归档)
|
|
951
1771
|
// 却试图设置提问(needsUser:true 或带 question)→ conflict;先于任何字段写入,失败不留部分修改。
|
|
@@ -1023,11 +1843,16 @@ export function applyTaskUpdate(state, id, patch, now = Date.now()) {
|
|
|
1023
1843
|
task.finishedAt = stamp
|
|
1024
1844
|
// 新的完成一定还没汇报过;已汇报过的历史结论只在 done→archived 时保留。
|
|
1025
1845
|
task.reportedAt = null
|
|
1846
|
+
// v0.3.9:轮询任务由组长审核置 done 时,若 workerRunState 仍停在 running,收敛为 ended。
|
|
1847
|
+
if (task.workerRunState === 'running') task.workerRunState = 'ended'
|
|
1026
1848
|
} else if (patch.status === 'archived') {
|
|
1027
1849
|
// done→archived 不改 reportedAt:不会重发历史回执。
|
|
1028
1850
|
task.archivedAt = stamp
|
|
1851
|
+
if (task.workerRunState === 'running') task.workerRunState = 'ended'
|
|
1852
|
+
cleanupTaskWorktree(task)
|
|
1029
1853
|
} else if (patch.status === 'todo') {
|
|
1030
|
-
//
|
|
1854
|
+
// 回到待开始:重新排队派发,清掉上一轮的派发记账与残留隔离工作树。
|
|
1855
|
+
cleanupTaskWorktree(task)
|
|
1031
1856
|
task.startedAt = null
|
|
1032
1857
|
task.finishedAt = null
|
|
1033
1858
|
task.archivedAt = null
|
|
@@ -1044,6 +1869,7 @@ export function applyTaskUpdate(state, id, patch, now = Date.now()) {
|
|
|
1044
1869
|
}
|
|
1045
1870
|
}
|
|
1046
1871
|
if (nextTitle !== null) task.title = nextTitle
|
|
1872
|
+
if (nextDependsOn !== null) task.dependsOn = nextDependsOn
|
|
1047
1873
|
if (patch.note !== undefined) task.note = truncateNote(patch.note, MAX_NOTE_CHARS)
|
|
1048
1874
|
if (patch.result !== undefined) task.result = truncateNote(patch.result, MAX_NOTE_CHARS)
|
|
1049
1875
|
if (patch.assignee !== undefined) task.assignee = trimmed(patch.assignee, 200)
|
|
@@ -1073,6 +1899,8 @@ export function archiveDoneTasks(state, now = Date.now()) {
|
|
|
1073
1899
|
if (task.status !== 'done') continue
|
|
1074
1900
|
task.status = 'archived'
|
|
1075
1901
|
task.archivedAt = iso(now)
|
|
1902
|
+
if (task.workerRunState === 'running') task.workerRunState = 'ended'
|
|
1903
|
+
cleanupTaskWorktree(task)
|
|
1076
1904
|
// §1.9:归档是终态——flagged 任务归档后不再等用户回答,清问题四字段(回答留档保留)。
|
|
1077
1905
|
clearNeedsUserFields(task)
|
|
1078
1906
|
task.updatedAt = iso(now)
|
|
@@ -1083,6 +1911,7 @@ export function archiveDoneTasks(state, now = Date.now()) {
|
|
|
1083
1911
|
|
|
1084
1912
|
export function deleteTask(state, id) {
|
|
1085
1913
|
const task = findTask(state, id)
|
|
1914
|
+
cleanupTaskWorktree(task)
|
|
1086
1915
|
const index = state.tasks.indexOf(task)
|
|
1087
1916
|
if (index >= 0) state.tasks.splice(index, 1)
|
|
1088
1917
|
return task
|
|
@@ -1125,10 +1954,19 @@ export function archiveTimeOf(task) {
|
|
|
1125
1954
|
* @param {number} [retentionMs] 保留期(默认 `ARCHIVE_RETENTION_MS`)
|
|
1126
1955
|
* @returns {{removed:number, ids:string[]}} 删除数量与被删任务 id(board 顺序)
|
|
1127
1956
|
*/
|
|
1128
|
-
export function pruneArchivedTasks(state, now = Date.now(), retentionMs =
|
|
1957
|
+
export function pruneArchivedTasks(state, now = Date.now(), retentionMs = undefined) {
|
|
1129
1958
|
const outcome = { removed: 0, ids: [] }
|
|
1130
1959
|
if (!isPlainObject(state) || !Array.isArray(state.tasks)) return outcome
|
|
1131
|
-
|
|
1960
|
+
let ttl = ARCHIVE_RETENTION_MS
|
|
1961
|
+
if (retentionMs !== undefined) {
|
|
1962
|
+
const explicit = Number(retentionMs)
|
|
1963
|
+
if (explicit === 0) return outcome
|
|
1964
|
+
if (Number.isFinite(explicit) && explicit > 0) ttl = explicit
|
|
1965
|
+
} else if (isPlainObject(state.config) && state.config.archiveRetentionMinutes !== undefined) {
|
|
1966
|
+
const minutes = normalizeConfig(state.config).archiveRetentionMinutes
|
|
1967
|
+
if (minutes === 0) return outcome
|
|
1968
|
+
ttl = minutes * 60 * 1000
|
|
1969
|
+
}
|
|
1132
1970
|
const kept = []
|
|
1133
1971
|
for (const task of state.tasks) {
|
|
1134
1972
|
if (!isPlainObject(task) || task.status !== 'archived') {
|
|
@@ -1141,6 +1979,7 @@ export function pruneArchivedTasks(state, now = Date.now(), retentionMs = ARCHIV
|
|
|
1141
1979
|
continue
|
|
1142
1980
|
}
|
|
1143
1981
|
if (now - archivedAt >= ttl) {
|
|
1982
|
+
cleanupTaskWorktree(task)
|
|
1144
1983
|
outcome.ids.push(task.id)
|
|
1145
1984
|
outcome.removed += 1
|
|
1146
1985
|
continue
|
|
@@ -1180,6 +2019,8 @@ export function selectDispatchCandidates(state, now = Date.now()) {
|
|
|
1180
2019
|
.filter((task) => task.status === 'todo')
|
|
1181
2020
|
// §1.9:等待用户回答的任务不投递(问题没回答前重复派发只会让组长重复提问)。
|
|
1182
2021
|
.filter((task) => task.needsUser !== true)
|
|
2022
|
+
// v0.4.0:存在未完成前置依赖(todo / doing)的任务不提前派发,防止抢跑(如前置迁移尚在 needsUser 待回复)。
|
|
2023
|
+
.filter((task) => unresolvedDependencies(state, task).length === 0)
|
|
1183
2024
|
.filter((task) => task.notificationCount < config.maxNotifications)
|
|
1184
2025
|
.filter((task) => {
|
|
1185
2026
|
if (!task.notifiedAt) return true
|
|
@@ -1281,15 +2122,32 @@ export function archivedSessionIdSet(rt) {
|
|
|
1281
2122
|
/**
|
|
1282
2123
|
* 工作区组长会话失效(被归档)时,把它名下「进行中」的任务重排回待开始,
|
|
1283
2124
|
* 交给新组长重新接单;done / archived 任务不动。
|
|
2125
|
+
* @param {string} [exceptTaskId] 不重排的任务 id(接管新组长时正在派发的卡)
|
|
1284
2126
|
* @returns {number} 重排的任务数
|
|
1285
2127
|
*/
|
|
1286
|
-
export function requeueTasksOfLead(state, sessionId, now = Date.now()) {
|
|
2128
|
+
export function requeueTasksOfLead(state, sessionId, now = Date.now(), exceptTaskId = '') {
|
|
1287
2129
|
if (!state || !Array.isArray(state.tasks)) return 0
|
|
1288
2130
|
if (typeof sessionId !== 'string' || sessionId === '') return 0
|
|
1289
2131
|
const stamp = iso(now)
|
|
2132
|
+
const keepId = typeof exceptTaskId === 'string' ? exceptTaskId.trim() : ''
|
|
1290
2133
|
let requeued = 0
|
|
1291
2134
|
for (const task of state.tasks) {
|
|
1292
2135
|
if (!task || task.status !== 'doing' || task.dispatchedSessionId !== sessionId) continue
|
|
2136
|
+
// v0.3.2:接管新组长时,正在派发的这张卡不属于「旧组长的遗留任务」,不要打回 todo。
|
|
2137
|
+
if (keepId !== '' && task.id === keepId) continue
|
|
2138
|
+
// v0.3.5:旧组长自动派出的内部子卡(切片 / 合并 / 验证子卡)不重排为独立 todo 任务——
|
|
2139
|
+
// 否则新组长既重做父任务、又把旧切片当独立任务再派一遍;直接归档留痕,由新组长统一接手父任务。
|
|
2140
|
+
if (task.autoDispatch === LEAD_AUTO_MARK && asString(task.parentTaskId) !== '') {
|
|
2141
|
+
cleanupTaskWorktree(task)
|
|
2142
|
+
task.status = 'archived'
|
|
2143
|
+
task.archivedAt = stamp
|
|
2144
|
+
task.workerRunState = null
|
|
2145
|
+
clearNeedsUserFields(task)
|
|
2146
|
+
task.lastError = '工作区组长会话已归档,旧内部子卡已归档;父任务已重新排队'
|
|
2147
|
+
task.updatedAt = stamp
|
|
2148
|
+
continue
|
|
2149
|
+
}
|
|
2150
|
+
cleanupTaskWorktree(task)
|
|
1293
2151
|
task.status = 'todo'
|
|
1294
2152
|
task.startedAt = null
|
|
1295
2153
|
task.finishedAt = null
|
|
@@ -1425,6 +2283,9 @@ export function buildDispatchText(task, now = Date.now()) {
|
|
|
1425
2283
|
const lines = ['【任务看板 · 待开始】' + task.id + ' ' + task.title]
|
|
1426
2284
|
if (task.note) lines.push('备注:' + task.note)
|
|
1427
2285
|
if (task.cwd) lines.push('工作目录:' + task.cwd)
|
|
2286
|
+
if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
|
|
2287
|
+
lines.push('前置依赖(已满足):' + task.dependsOn.join(', '))
|
|
2288
|
+
}
|
|
1428
2289
|
// §1.9:todo 任务提问 → 用户回答 → 清标记后再派发时,组长可能在别的会话里,
|
|
1429
2290
|
// 回答必须随派发文本带过去,不然「用户已经拍板」这件事会丢。
|
|
1430
2291
|
if (typeof task.lastAnswer === 'string' && task.lastAnswer.trim() !== '') {
|
|
@@ -1432,12 +2293,21 @@ export function buildDispatchText(task, now = Date.now()) {
|
|
|
1432
2293
|
}
|
|
1433
2294
|
lines.push('')
|
|
1434
2295
|
lines.push(
|
|
1435
|
-
'请按派单规则处理这条看板任务:先用 taskboard_update 把它置为 doing
|
|
1436
|
-
'
|
|
1437
|
-
'
|
|
2296
|
+
'请按派单规则处理这条看板任务:先用 taskboard_update 把它置为 doing;' +
|
|
2297
|
+
'若确认是 ≤2 个文件的纯文档 / 配置微调且无需跑任何终端测试/构建(Fast-path 小活直办),可直接用 edit/write 改完复读核验后当轮置 done;' +
|
|
2298
|
+
'凡需跑单测 / 构建 / 脚本验证或改业务代码的任务,派发子 Agent 执行(背景执行,不要自己在对话里等),然后结束本轮。' +
|
|
2299
|
+
'如果这条任务经只读探查确认可以拆成 ≥2 个写域严格不相交的独立片,按 persona 的 fan-out 规则一次派多个 worker:' +
|
|
2300
|
+
'每个切片 worker 的 description 带父任务 id(如「' +
|
|
2301
|
+
task.id +
|
|
2302
|
+
' 切片 A · …」),prompt 行首显式写「父任务:' +
|
|
2303
|
+
task.id +
|
|
2304
|
+
'」(宿主会自动关联子卡、不吞父卡且不单独打扰主会话),收尾时用 taskboard_list {parentTaskId:"' +
|
|
2305
|
+
task.id +
|
|
2306
|
+
'"} 核对进度;若某张切片子卡 t-K 的 worker 报错或上下文爆满无法续跑、需换新 worker 接手,新 worker 的 prompt 行首写「任务 id:t-K」直接复用该子卡(或先将废卡 archived),不要把失败废卡留在 doing 列。' +
|
|
2307
|
+
'子 Agent 回报后审核:若该任务或子卡带有非空 worktreePath(隔离工作树),审核通过后必须调 taskboard_merge_worktree 将改动合入主工作区并清理临时分支;通过就 taskboard_update 置为 done 并把结论写进 result;' +
|
|
1438
2308
|
'不通过就 send_message 打回同一个子 Agent 重做,任务保持 doing。' +
|
|
1439
|
-
'写 result
|
|
1440
|
-
'
|
|
2309
|
+
'写 result 与对话回复必须简短说人话:result 第 1 行直接写一句话人话结论(做成了什么、验证结果如何),下面最多列 3~5 条精炼要点;' +
|
|
2310
|
+
'非必要不画表格,严禁写「我已做的取证」等自证流水账或暴露 W1/W2/assignee=merging 等内部调度黑话;中间派单或波次过渡轮次的对话回复不超过 2 句话。',
|
|
1441
2311
|
)
|
|
1442
2312
|
if (task.notificationCount > 0) {
|
|
1443
2313
|
lines.push('(这是第 ' + (task.notificationCount + 1) + ' 次提醒;任务仍未派发。)')
|
|
@@ -1844,7 +2714,7 @@ export function buildReceiptText(tasks, now = Date.now()) {
|
|
|
1844
2714
|
lines.push('- ' + task.id + ' ' + task.title + ':' + (summary === '' ? '(无结论)' : summary))
|
|
1845
2715
|
}
|
|
1846
2716
|
lines.push('')
|
|
1847
|
-
lines.push('
|
|
2717
|
+
lines.push('请用简洁自然的人话向用户汇总以上结论,不要重复执行任务。')
|
|
1848
2718
|
lines.push('看板时间:' + localStamp(now))
|
|
1849
2719
|
return lines.join('\n')
|
|
1850
2720
|
}
|
|
@@ -1858,6 +2728,9 @@ export function selectReceiptTasks(state, limit = MAX_RECEIPT_BATCH) {
|
|
|
1858
2728
|
const cap = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.round(Number(limit)) : MAX_RECEIPT_BATCH
|
|
1859
2729
|
return state.tasks
|
|
1860
2730
|
.filter((task) => task && task.status === 'done' && !task.reportedAt)
|
|
2731
|
+
// v0.3.5(§1.6 / §1.8):带 parentTaskId 的内部自动子卡(fan-out 切片 / 合并 / 验证子卡)
|
|
2732
|
+
// 不单独唤醒主会话推送回执,等父任务最终 done 时向主会话发唯一一次汇总回执。
|
|
2733
|
+
.filter((task) => !(task.autoDispatch === LEAD_AUTO_MARK && asString(task.parentTaskId) !== ''))
|
|
1861
2734
|
.sort((a, b) => {
|
|
1862
2735
|
const at = Date.parse(a.updatedAt)
|
|
1863
2736
|
const bt = Date.parse(b.updatedAt)
|
|
@@ -2016,6 +2889,12 @@ async function dispatchRpc(rt, method, payload) {
|
|
|
2016
2889
|
const next = normalizeConfig({ ...normalizeConfig(rt.state.config), ...payload })
|
|
2017
2890
|
const intervalChanged = next.pollIntervalMs !== normalizeConfig(rt.state.config).pollIntervalMs
|
|
2018
2891
|
rt.state.config = next
|
|
2892
|
+
// v0.3.6:用户在设置里调短归档保留分钟数后,立即按新保留期清理一次已到期归档任务。
|
|
2893
|
+
try {
|
|
2894
|
+
pruneArchivedTasks(rt.state)
|
|
2895
|
+
} catch (error) {
|
|
2896
|
+
console.warn('[taskboard] 配置更新后归档清理失败:' + describeError(error))
|
|
2897
|
+
}
|
|
2019
2898
|
commitBoard(rt.state, rt.filePath)
|
|
2020
2899
|
if (intervalChanged) startPolling(rt)
|
|
2021
2900
|
return { config: next }
|
|
@@ -2081,6 +2960,7 @@ const SKIP_TEXT = {
|
|
|
2081
2960
|
'agent-busy': '目标会话正在运行,稍后再派',
|
|
2082
2961
|
// v0.2.0 工作区组长路由(§1.5 跳过原因表;Client 用 poll.skip.<reason> 做 i18n)。
|
|
2083
2962
|
'lead-busy': '工作区组长正在运行,等它空下来再派',
|
|
2963
|
+
'lead-worker-busy': '本工作区已有任务正在执行或待组长验收,完成后再自动派发下一条',
|
|
2084
2964
|
'lead-unavailable': '工作区组长不可用:稍后重试,或在看板点「创建组长」',
|
|
2085
2965
|
'lead-no-workspace': '无法解析任务的工作区:请从目标工作区的会话里重新加这条任务',
|
|
2086
2966
|
'creator-busy': '创建这条任务的对话正在运行,等它空下来再派',
|
|
@@ -2245,6 +3125,93 @@ function repairWorkspaceLeadMapping(rt, mapping, key, cwd, agent) {
|
|
|
2245
3125
|
commitBoard(rt.state, rt.filePath)
|
|
2246
3126
|
}
|
|
2247
3127
|
|
|
3128
|
+
/**
|
|
3129
|
+
* v0.3.2:派单会话「接管」工作区组长(§1.5)。
|
|
3130
|
+
*
|
|
3131
|
+
* 触发:一个 `taskboard-dispatch` 会话在 `tools/pre-execute` 闸门成功准备卡片、即将启动 worker。
|
|
3132
|
+
* 规则(只有这两种情况才改写映射,绝不抢已有可用组长):
|
|
3133
|
+
* - 该工作区还没有组长映射;
|
|
3134
|
+
* - 已有映射的组长会话已被归档(视为失效:删映射、重排它名下 doing 任务)。
|
|
3135
|
+
* 接管后把当前会话写进 `config.workspaceLeads`——轮询下一轮就投给它,不再新建一个组长窗口。
|
|
3136
|
+
* 只让 root 会话当组长:dispatch 预设的子 Agent(罕见)不接管工作区。
|
|
3137
|
+
* @param {{taskId?:string}} [options] `taskId` = 正在派发的卡,从旧组长重排里排除并改绑到当前会话
|
|
3138
|
+
* @returns {{adopted:boolean, key?:string, reason?:string}}
|
|
3139
|
+
*/
|
|
3140
|
+
function adoptWorkspaceLead(rt, agent, args, options = {}, now = Date.now()) {
|
|
3141
|
+
try {
|
|
3142
|
+
const sessionId = agentSessionId(agent) || ''
|
|
3143
|
+
if (sessionId === '') return { adopted: false, reason: 'no-session' }
|
|
3144
|
+
// 子 Agent(delegationDepth > 0)不是 root:它可能带着 dispatch 预设,但不应成为工作区组长。
|
|
3145
|
+
try {
|
|
3146
|
+
const agents = serviceOf(rt.ctx, 'agents')
|
|
3147
|
+
const roots = agents && typeof agents.roots === 'function' ? agents.roots() : null
|
|
3148
|
+
if (Array.isArray(roots) && roots.length > 0) {
|
|
3149
|
+
// 按 session id 比较,避免 roots() 返回的对象与 exec.agent 不是同一个引用。
|
|
3150
|
+
const rootIds = new Set(
|
|
3151
|
+
roots.map((root) => agentSessionId(root)).filter((id) => typeof id === 'string' && id !== ''),
|
|
3152
|
+
)
|
|
3153
|
+
if (rootIds.size > 0 && !rootIds.has(sessionId)) return { adopted: false, reason: 'not-root' }
|
|
3154
|
+
}
|
|
3155
|
+
} catch {
|
|
3156
|
+
/* roots 不可用时放行(best-effort,不阻断派发) */
|
|
3157
|
+
}
|
|
3158
|
+
const rawCwd =
|
|
3159
|
+
sessionCwd(agent) || resolveSessionCwd(rt.ctx, sessionId) || (isPlainObject(args) ? asString(args.cwd) : '')
|
|
3160
|
+
if (rawCwd === '') return { adopted: false, reason: 'no-workspace' }
|
|
3161
|
+
const cwd = workspacePathForCwd(rt.ctx, rawCwd) || rawCwd
|
|
3162
|
+
const key = workspaceKeyForCwd(rt.ctx, cwd)
|
|
3163
|
+
if (key === '') return { adopted: false, reason: 'no-workspace' }
|
|
3164
|
+
reloadBoardIfStale(rt)
|
|
3165
|
+
const archived = archivedSessionIdSet(rt)
|
|
3166
|
+
// 当前会话自己已归档:不该接管(归档门通常会先拒绝它跑模型步进,这里再兜一层)。
|
|
3167
|
+
if (archived.has(sessionId)) return { adopted: false, reason: 'self-archived' }
|
|
3168
|
+
let config = normalizeConfig(rt.state.config)
|
|
3169
|
+
const mapping = selectWorkspaceLead(config, key)
|
|
3170
|
+
if (mapping && mapping.sessionId === sessionId) {
|
|
3171
|
+
// 已经是组长:顺手修掉空的 title / cwd,不改 sessionId。
|
|
3172
|
+
repairWorkspaceLeadMapping(rt, mapping, key, cwd, agent)
|
|
3173
|
+
return { adopted: false, reason: 'already-lead' }
|
|
3174
|
+
}
|
|
3175
|
+
if (mapping) {
|
|
3176
|
+
// 已有别的组长:只有它已归档(失效)才接管;活着的组长不抢。
|
|
3177
|
+
if (!archived.has(mapping.sessionId)) {
|
|
3178
|
+
return { adopted: false, reason: 'other-lead' }
|
|
3179
|
+
}
|
|
3180
|
+
dropWorkspaceLeadMapping(rt, key)
|
|
3181
|
+
requeueTasksOfLead(rt.state, mapping.sessionId, now, options.taskId || '')
|
|
3182
|
+
config = normalizeConfig(rt.state.config)
|
|
3183
|
+
console.warn('[taskboard] 工作区组长已归档,由派发会话接管:' + key + ' → ' + sessionId)
|
|
3184
|
+
}
|
|
3185
|
+
const entry = {
|
|
3186
|
+
sessionId,
|
|
3187
|
+
title: sessionTitle(agent),
|
|
3188
|
+
cwd,
|
|
3189
|
+
createdAt: iso(now),
|
|
3190
|
+
}
|
|
3191
|
+
config.workspaceLeads = putWorkspaceLead(config.workspaceLeads, key, entry)
|
|
3192
|
+
rt.state.config = config
|
|
3193
|
+
// 正在派发的卡:把「组长对话」改到当前会话(旧组长可能正是被归档的那个)。
|
|
3194
|
+
if (typeof options.taskId === 'string' && options.taskId !== '') {
|
|
3195
|
+
const task = taskById(rt.state, options.taskId)
|
|
3196
|
+
if (task) {
|
|
3197
|
+
task.dispatchedSessionId = sessionId
|
|
3198
|
+
task.dispatchedSessionTitle = sessionTitle(agent)
|
|
3199
|
+
task.updatedAt = iso(now)
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
const saved = commitBoard(rt.state, rt.filePath)
|
|
3203
|
+
if (saved && saved.saved === false) {
|
|
3204
|
+
console.warn('[taskboard] 工作区组长接管写盘失败:' + (saved.error || ''))
|
|
3205
|
+
}
|
|
3206
|
+
console.log('[taskboard] 工作区组长由派发会话接管:' + key + ' → ' + sessionId)
|
|
3207
|
+
return { adopted: true, key }
|
|
3208
|
+
} catch (error) {
|
|
3209
|
+
// 接管是 best-effort:失败不影响这次派发,下一次派发 / ensure-workspace-lead 还会再试。
|
|
3210
|
+
console.warn('[taskboard] 工作区组长接管失败:' + describeError(error))
|
|
3211
|
+
return { adopted: false, reason: 'error' }
|
|
3212
|
+
}
|
|
3213
|
+
}
|
|
3214
|
+
|
|
2248
3215
|
/** 组装 LeadRef(§3.1.1):live/busy 来自 live Agent,title 优先 live 标题、其次持久化映射。 */
|
|
2249
3216
|
function leadRefFrom(key, mapping, agent, archived = false) {
|
|
2250
3217
|
const live = !!agent
|
|
@@ -2288,6 +3255,161 @@ function pruneArchivedBoard(rt, now = Date.now()) {
|
|
|
2288
3255
|
return outcome.removed
|
|
2289
3256
|
}
|
|
2290
3257
|
|
|
3258
|
+
/**
|
|
3259
|
+
* v0.4.0:巡检并自愈失联的 `doing` 任务(进程重启掉线 / worker 异常退出未发 `subagent/end`)。
|
|
3260
|
+
*
|
|
3261
|
+
* 恢复策略(用户拍板口径):
|
|
3262
|
+
* - **顶层任务**(`parentTaskId` 为空且 `needsUser !== true`):自动回退 `todo` 重新排队接单(保留原 `note` / `result` / `dependsOn`),
|
|
3263
|
+
* `lastError` 写明失联重排原因;
|
|
3264
|
+
* - **内部切片子卡**(`autoDispatch === LEAD_AUTO_MARK` 且 `parentTaskId` 非空):保持 `doing`,标 `workerRunState = 'failed'`
|
|
3265
|
+
* 并写 `lastError`;若所属组长会话在线且 `idle`,合并发送一条「异常恢复」提醒交组长续做或归档。
|
|
3266
|
+
*/
|
|
3267
|
+
export async function reconcileOrphanedDoingTasks(rt, options = {}) {
|
|
3268
|
+
const outcome = { requeued: 0, markedFailed: 0, ids: [] }
|
|
3269
|
+
if (!rt || !rt.state || !Array.isArray(rt.state.tasks)) return outcome
|
|
3270
|
+
const startup = options.startup === true
|
|
3271
|
+
const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now()
|
|
3272
|
+
const graceMs = Number.isFinite(Number(options.graceMs)) ? Number(options.graceMs) : ORPHAN_GRACE_MS
|
|
3273
|
+
const agents = serviceOf(rt.ctx, 'agents')
|
|
3274
|
+
const subagents = serviceOf(rt.ctx, 'subagents')
|
|
3275
|
+
if (!startup && !agents && !subagents) return outcome
|
|
3276
|
+
|
|
3277
|
+
const descendantCache = new Map()
|
|
3278
|
+
const loadDescendants = async (parentId) => {
|
|
3279
|
+
if (!parentId || !subagents || typeof subagents.listDescendants !== 'function') return null
|
|
3280
|
+
if (descendantCache.has(parentId)) return descendantCache.get(parentId)
|
|
3281
|
+
try {
|
|
3282
|
+
const rows = await subagents.listDescendants(parentId)
|
|
3283
|
+
const list = Array.isArray(rows) ? rows : []
|
|
3284
|
+
descendantCache.set(parentId, list)
|
|
3285
|
+
return list
|
|
3286
|
+
} catch {
|
|
3287
|
+
descendantCache.set(parentId, null)
|
|
3288
|
+
return null
|
|
3289
|
+
}
|
|
3290
|
+
}
|
|
3291
|
+
|
|
3292
|
+
const stamp = iso(now)
|
|
3293
|
+
const leadAlerts = new Map()
|
|
3294
|
+
let changed = false
|
|
3295
|
+
|
|
3296
|
+
for (const task of rt.state.tasks) {
|
|
3297
|
+
if (!task || task.status !== 'doing' || task.needsUser === true) continue
|
|
3298
|
+
const lastMs = Date.parse(asString(task.updatedAt) || asString(task.startedAt) || asString(task.createdAt))
|
|
3299
|
+
const ageMs = Number.isFinite(lastMs) ? now - lastMs : 0
|
|
3300
|
+
let orphaned = false
|
|
3301
|
+
|
|
3302
|
+
if (task.workerRunState === 'running') {
|
|
3303
|
+
if (startup) {
|
|
3304
|
+
orphaned = true
|
|
3305
|
+
} else if (ageMs >= graceMs) {
|
|
3306
|
+
const workerId = asString(task.workerSessionId).trim()
|
|
3307
|
+
const parentId = asString(task.dispatchedSessionId || task.sessionId).trim()
|
|
3308
|
+
const liveWorker = workerId !== '' ? liveAgentOf(agents, workerId) : undefined
|
|
3309
|
+
if (liveWorker) {
|
|
3310
|
+
if (liveWorker.status !== 'running') orphaned = true
|
|
3311
|
+
} else if (subagents && typeof subagents.listDescendants === 'function') {
|
|
3312
|
+
if (parentId !== '') {
|
|
3313
|
+
const rows = await loadDescendants(parentId)
|
|
3314
|
+
if (Array.isArray(rows)) {
|
|
3315
|
+
const hit =
|
|
3316
|
+
workerId !== ''
|
|
3317
|
+
? rows.find((r) => r && asString(r.id).trim() === workerId)
|
|
3318
|
+
: asString(task.assignee) !== ''
|
|
3319
|
+
? rows.find((r) => r && asString(r.name).trim() === asString(task.assignee).trim())
|
|
3320
|
+
: null
|
|
3321
|
+
const childAgent = hit && asString(hit.id).trim() !== '' ? liveAgentOf(agents, asString(hit.id).trim()) : undefined
|
|
3322
|
+
if (!hit || (agents && typeof agents.get === 'function' && (!childAgent || childAgent.status !== 'running'))) {
|
|
3323
|
+
orphaned = true
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
} else if (workerId !== '' && agents && typeof agents.get === 'function') {
|
|
3327
|
+
orphaned = true
|
|
3328
|
+
}
|
|
3329
|
+
}
|
|
3330
|
+
}
|
|
3331
|
+
} else if (
|
|
3332
|
+
startup &&
|
|
3333
|
+
task.workerRunState === null &&
|
|
3334
|
+
asString(task.parentTaskId) === '' &&
|
|
3335
|
+
ageMs > LEAD_IN_FLIGHT_TTL_MS &&
|
|
3336
|
+
!taskHasActiveSubtasks(rt.state, task.id)
|
|
3337
|
+
) {
|
|
3338
|
+
orphaned = true
|
|
3339
|
+
}
|
|
3340
|
+
|
|
3341
|
+
if (!orphaned) continue
|
|
3342
|
+
changed = true
|
|
3343
|
+
outcome.ids.push(task.id)
|
|
3344
|
+
|
|
3345
|
+
const isSubtask = task.autoDispatch === LEAD_AUTO_MARK && asString(task.parentTaskId) !== ''
|
|
3346
|
+
if (isSubtask) {
|
|
3347
|
+
task.workerRunState = 'failed'
|
|
3348
|
+
task.lastError = '执行会话已失联(宿主重启或异常退出),等待组长续做或归档'
|
|
3349
|
+
task.updatedAt = stamp
|
|
3350
|
+
outcome.markedFailed += 1
|
|
3351
|
+
const leadId = asString(task.dispatchedSessionId || task.sessionId).trim()
|
|
3352
|
+
if (leadId !== '') {
|
|
3353
|
+
const list = leadAlerts.get(leadId) || []
|
|
3354
|
+
list.push(task)
|
|
3355
|
+
leadAlerts.set(leadId, list)
|
|
3356
|
+
}
|
|
3357
|
+
} else {
|
|
3358
|
+
cleanupTaskWorktree(task)
|
|
3359
|
+
task.status = 'todo'
|
|
3360
|
+
task.startedAt = null
|
|
3361
|
+
task.finishedAt = null
|
|
3362
|
+
task.notifiedAt = null
|
|
3363
|
+
task.notificationCount = 0
|
|
3364
|
+
task.assignee = ''
|
|
3365
|
+
task.workerSessionId = null
|
|
3366
|
+
task.workerRunState = null
|
|
3367
|
+
task.dispatchedSessionId = null
|
|
3368
|
+
task.dispatchedSessionTitle = ''
|
|
3369
|
+
task.autoDispatch = null
|
|
3370
|
+
task.lastError = '上次执行会话已失联(宿主重启或异常退出),已自动回退待开始重新接单'
|
|
3371
|
+
task.updatedAt = stamp
|
|
3372
|
+
outcome.requeued += 1
|
|
3373
|
+
}
|
|
3374
|
+
}
|
|
3375
|
+
|
|
3376
|
+
if (changed) {
|
|
3377
|
+
commitBoard(rt.state, rt.filePath)
|
|
3378
|
+
console.warn(
|
|
3379
|
+
'[taskboard] 失联 doing 任务自愈:回退待开始 ' +
|
|
3380
|
+
outcome.requeued +
|
|
3381
|
+
' 条,切片标 failed ' +
|
|
3382
|
+
outcome.markedFailed +
|
|
3383
|
+
' 条(' +
|
|
3384
|
+
outcome.ids.join(', ') +
|
|
3385
|
+
')',
|
|
3386
|
+
)
|
|
3387
|
+
}
|
|
3388
|
+
|
|
3389
|
+
if (!startup && leadAlerts.size > 0 && agents) {
|
|
3390
|
+
const archived = archivedSessionIdSet(rt)
|
|
3391
|
+
for (const [leadId, failedSlices] of leadAlerts.entries()) {
|
|
3392
|
+
if (archived.has(leadId)) continue
|
|
3393
|
+
const leadAgent = liveAgentOf(agents, leadId)
|
|
3394
|
+
if (!leadAgent || leadAgent.status !== 'idle') continue
|
|
3395
|
+
const lines = ['【任务看板 · 异常恢复】检测到以下并行子卡的执行会话已失联中断(已标为 failed):']
|
|
3396
|
+
for (const item of failedSlices) {
|
|
3397
|
+
lines.push('- ' + item.id + '(父任务:' + item.parentTaskId + ')' + item.title)
|
|
3398
|
+
}
|
|
3399
|
+
lines.push('请检查工作区现有改动后决定:需续做的在新 worker prompt 行首写「任务 id:<子卡id>」复用接管,不再需要的用 taskboard_update 置 archived。')
|
|
3400
|
+
try {
|
|
3401
|
+
leadAgent.followup(createBoardUserMessage(lines.join('\n')))
|
|
3402
|
+
const sessions = serviceOf(rt.ctx, 'sessions')
|
|
3403
|
+
if (sessions && typeof sessions.flush === 'function') await sessions.flush(leadAgent.session)
|
|
3404
|
+
} catch (error) {
|
|
3405
|
+
console.warn('[taskboard] 发送失联子卡恢复提醒失败:' + describeError(error))
|
|
3406
|
+
}
|
|
3407
|
+
}
|
|
3408
|
+
}
|
|
3409
|
+
|
|
3410
|
+
return outcome
|
|
3411
|
+
}
|
|
3412
|
+
|
|
2291
3413
|
/**
|
|
2292
3414
|
* 轮询派单入口。每次 tick 末尾都会尝试 flush 一次完成回执(§1.6):
|
|
2293
3415
|
* 回执投递不占用派发名额(未绑定主会话 / 主会话忙或离线时是 no-op)。
|
|
@@ -2308,6 +3430,13 @@ async function runTick(rt, options = {}) {
|
|
|
2308
3430
|
rt.poll.lastRunAt = iso(now)
|
|
2309
3431
|
// 归档清理(§1.2)必须在 pollEnabled 判断之前:暂停派发时归档仍要按时删除。
|
|
2310
3432
|
pruneArchivedBoard(rt, now)
|
|
3433
|
+
if (!options.taskId) {
|
|
3434
|
+
try {
|
|
3435
|
+
await reconcileOrphanedDoingTasks(rt, { startup: false, now })
|
|
3436
|
+
} catch (error) {
|
|
3437
|
+
console.warn('[taskboard] 失联任务巡检失败:' + describeError(error))
|
|
3438
|
+
}
|
|
3439
|
+
}
|
|
2311
3440
|
const config = normalizeConfig(rt.state.config)
|
|
2312
3441
|
if (!config.pollEnabled && !options.taskId) {
|
|
2313
3442
|
rt.poll.lastSkipReason = 'poll-disabled'
|
|
@@ -2321,6 +3450,13 @@ async function runTick(rt, options = {}) {
|
|
|
2321
3450
|
if (single.needsUser === true) {
|
|
2322
3451
|
throw new BoardError('conflict', '任务正在等待用户回复(needsUser),回答后才能继续派发')
|
|
2323
3452
|
}
|
|
3453
|
+
const blockingDeps = unresolvedDependencies(rt.state, single)
|
|
3454
|
+
if (blockingDeps.length > 0) {
|
|
3455
|
+
throw new BoardError(
|
|
3456
|
+
'conflict',
|
|
3457
|
+
'前置任务尚未完成(' + blockingDeps.join(', ') + '),请先完成前置任务或移除依赖后再派发',
|
|
3458
|
+
)
|
|
3459
|
+
}
|
|
2324
3460
|
candidates = [single]
|
|
2325
3461
|
} else {
|
|
2326
3462
|
candidates = selectDispatchCandidates(rt.state, now)
|
|
@@ -2331,7 +3467,7 @@ async function runTick(rt, options = {}) {
|
|
|
2331
3467
|
}
|
|
2332
3468
|
const agents = serviceOf(rt.ctx, 'agents')
|
|
2333
3469
|
|
|
2334
|
-
//
|
|
3470
|
+
// 默认:按任务工作区投给该工作区的常驻组长(§1.5)。绝不每任务新建会话。
|
|
2335
3471
|
if (config.dispatchMode === 'workspace-lead') {
|
|
2336
3472
|
const picked = await pickWorkspaceLeadTarget(rt, candidates, config, agents, options, now)
|
|
2337
3473
|
if (!picked) return { dispatched: false, reason: rt.poll.lastSkipReason || 'lead-unavailable' }
|
|
@@ -2392,12 +3528,14 @@ async function runTick(rt, options = {}) {
|
|
|
2392
3528
|
* followup + sessions.flush 成功后置 doing、记通知与 dispatchedSession*、清 lastError。
|
|
2393
3529
|
*/
|
|
2394
3530
|
async function deliverBoardTask(rt, task, agent, now) {
|
|
3531
|
+
const taskId = task.id
|
|
2395
3532
|
const sessionId = agentSessionId(agent)
|
|
2396
3533
|
// 创建时没能解析出工作区(会话还没 live)→ 投递前从目标会话补一次,派发文本就能带上工作目录。
|
|
2397
3534
|
if (!task.cwd) {
|
|
2398
3535
|
const cwd = sessionCwd(agent)
|
|
2399
3536
|
if (cwd) task.cwd = cwd
|
|
2400
3537
|
}
|
|
3538
|
+
const resolvedCwd = task.cwd
|
|
2401
3539
|
const message = createBoardUserMessage(buildDispatchText(task, now))
|
|
2402
3540
|
try {
|
|
2403
3541
|
agent.followup(message)
|
|
@@ -2410,32 +3548,35 @@ async function deliverBoardTask(rt, task, agent, now) {
|
|
|
2410
3548
|
console.warn('[taskboard] 会话 flush 失败(消息已入队):' + describeError(flushError))
|
|
2411
3549
|
}
|
|
2412
3550
|
} catch (error) {
|
|
3551
|
+
const current = taskById(rt.state, taskId) || task
|
|
2413
3552
|
rt.poll.lastSkipReason = 'followup-failed'
|
|
2414
|
-
|
|
2415
|
-
|
|
3553
|
+
current.lastError = skipText('followup-failed') + ':' + describeError(error)
|
|
3554
|
+
current.updatedAt = iso(now)
|
|
2416
3555
|
commitBoard(rt.state, rt.filePath)
|
|
2417
3556
|
console.warn('[taskboard] 派发失败:' + describeError(error))
|
|
2418
3557
|
return { dispatched: false, reason: 'followup-failed', error: describeError(error) }
|
|
2419
3558
|
}
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
3559
|
+
const target = taskById(rt.state, taskId) || task
|
|
3560
|
+
if (!target.cwd && resolvedCwd) target.cwd = resolvedCwd
|
|
3561
|
+
target.notifiedAt = iso(now)
|
|
3562
|
+
target.notificationCount = (Number(target.notificationCount) || 0) + 1
|
|
3563
|
+
target.updatedAt = iso(now)
|
|
3564
|
+
target.lastError = ''
|
|
2424
3565
|
// 投递成功即视为「进行中」:看板立刻反映已派发,不再依赖主 Agent 记得调 taskboard_update
|
|
2425
3566
|
// (它照样可以再调一次 doing,迁移 doing→doing 合法)。
|
|
2426
|
-
if (
|
|
2427
|
-
|
|
2428
|
-
if (!
|
|
3567
|
+
if (target.status === 'todo') {
|
|
3568
|
+
target.status = 'doing'
|
|
3569
|
+
if (!target.startedAt) target.startedAt = iso(now)
|
|
2429
3570
|
}
|
|
2430
3571
|
rt.poll.lastDispatchAt = iso(now)
|
|
2431
3572
|
rt.poll.lastDispatchSessionId = sessionId
|
|
2432
3573
|
rt.poll.lastDispatchSessionTitle = sessionTitle(agent)
|
|
2433
|
-
|
|
2434
|
-
|
|
2435
|
-
rt.poll.lastDispatchTaskId =
|
|
3574
|
+
target.dispatchedSessionId = sessionId
|
|
3575
|
+
target.dispatchedSessionTitle = sessionTitle(agent) || ''
|
|
3576
|
+
rt.poll.lastDispatchTaskId = target.id
|
|
2436
3577
|
rt.poll.lastSkipReason = null
|
|
2437
3578
|
commitBoard(rt.state, rt.filePath)
|
|
2438
|
-
return { dispatched: true, sessionId, task: { ...
|
|
3579
|
+
return { dispatched: true, sessionId, task: { ...target } }
|
|
2439
3580
|
}
|
|
2440
3581
|
|
|
2441
3582
|
/** 「用户回复」followup 文本(§1.9):任务仍在原状态,要求组长接着处理。 */
|
|
@@ -2482,8 +3623,13 @@ export async function answerTask(rt, id, answer, now = Date.now()) {
|
|
|
2482
3623
|
}
|
|
2483
3624
|
/** 失败统一收尾:保留 flagged 状态,把原因写进任务 lastError 并落盘,再抛给 RPC。 */
|
|
2484
3625
|
const fail = (code, message) => {
|
|
2485
|
-
task.
|
|
2486
|
-
|
|
3626
|
+
const current = taskById(rt.state, task.id) || task
|
|
3627
|
+
current.lastError = message
|
|
3628
|
+
current.updatedAt = iso(now)
|
|
3629
|
+
if (current !== task) {
|
|
3630
|
+
task.lastError = message
|
|
3631
|
+
task.updatedAt = current.updatedAt
|
|
3632
|
+
}
|
|
2487
3633
|
commitBoard(rt.state, rt.filePath)
|
|
2488
3634
|
return new BoardError(code, message)
|
|
2489
3635
|
}
|
|
@@ -2521,13 +3667,16 @@ export async function answerTask(rt, id, answer, now = Date.now()) {
|
|
|
2521
3667
|
throw fail('internal', '回复发送失败:' + describeError(error))
|
|
2522
3668
|
}
|
|
2523
3669
|
const stamp = iso(now)
|
|
2524
|
-
|
|
2525
|
-
task
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
|
|
3670
|
+
const target = taskById(rt.state, task.id) || task
|
|
3671
|
+
for (const item of target === task ? [target] : [target, task]) {
|
|
3672
|
+
clearNeedsUserFields(item)
|
|
3673
|
+
item.lastAnswer = text
|
|
3674
|
+
item.answeredAt = stamp
|
|
3675
|
+
item.lastError = ''
|
|
3676
|
+
item.updatedAt = stamp
|
|
3677
|
+
}
|
|
2529
3678
|
commitBoard(rt.state, rt.filePath)
|
|
2530
|
-
return { task: { ...
|
|
3679
|
+
return { task: { ...target }, sessionId }
|
|
2531
3680
|
}
|
|
2532
3681
|
|
|
2533
3682
|
/** RPC `bind-main-session`(§3.1.1):绑定完成回执收件人;不要求会话当前在线。 */
|
|
@@ -2721,7 +3870,11 @@ export async function flushReceipts(rt, now = Date.now()) {
|
|
|
2721
3870
|
console.warn('[taskboard] 完成回执投递失败:' + describeError(error))
|
|
2722
3871
|
return { sent: false, reason: 'followup-failed' }
|
|
2723
3872
|
}
|
|
2724
|
-
for (const task of batch)
|
|
3873
|
+
for (const task of batch) {
|
|
3874
|
+
task.reportedAt = stamp
|
|
3875
|
+
const current = taskById(rt.state, task.id)
|
|
3876
|
+
if (current && current !== task) current.reportedAt = stamp
|
|
3877
|
+
}
|
|
2725
3878
|
commitBoard(rt.state, rt.filePath)
|
|
2726
3879
|
return { sent: true, count: batch.length, sessionId: config.mainSessionId }
|
|
2727
3880
|
} finally {
|
|
@@ -2729,6 +3882,64 @@ export async function flushReceipts(rt, now = Date.now()) {
|
|
|
2729
3882
|
}
|
|
2730
3883
|
}
|
|
2731
3884
|
|
|
3885
|
+
/**
|
|
3886
|
+
* v0.3.9 + v0.5.0:该工作区当前是否因在途执行而需要阻塞新任务派发。
|
|
3887
|
+
*
|
|
3888
|
+
* - 当 `config.worktreeIsolation !== false` 且 `cwd` 是有效 Git 仓库(`resolveGitRepoInfo(cwd) !== null`)时:
|
|
3889
|
+
* 支持各任务独占独立 Git Worktree **真并发执行**!仅在以下情况阻塞:
|
|
3890
|
+
* ① 有任务处于主工作区合并/全量验证阶段(`assignee === 'merging'`);
|
|
3891
|
+
* ② 有未挂载 `worktreePath` 的任务直接在主工作区运行 worker(或已完成待主工作区复核);
|
|
3892
|
+
* ③ 该工作区当前同时运行的隔离 Worktree worker 数已达上限 `MAX_CONCURRENT_WORKTREES`(4)。
|
|
3893
|
+
* - 当非 Git 目录或 `config.worktreeIsolation === false` 时:退回单目录严格串行保护(v0.3.9)。
|
|
3894
|
+
*/
|
|
3895
|
+
export function hasActiveWorkspaceExecution(state, leadSessionId = '', cwd = '', now = Date.now()) {
|
|
3896
|
+
if (!state || !Array.isArray(state.tasks)) return false
|
|
3897
|
+
const leadId = typeof leadSessionId === 'string' ? leadSessionId.trim() : ''
|
|
3898
|
+
const wantCwd = typeof cwd === 'string' && cwd !== '' ? normalizePathForCompare(cwd) : ''
|
|
3899
|
+
if (leadId === '' && wantCwd === '') return false
|
|
3900
|
+
|
|
3901
|
+
const cfg = normalizeConfig(state.config)
|
|
3902
|
+
const canIsolate =
|
|
3903
|
+
cfg.worktreeIsolation !== false && typeof cwd === 'string' && cwd.trim() !== '' && resolveGitRepoInfo(cwd, { now }) !== null
|
|
3904
|
+
|
|
3905
|
+
let isolatedRunning = 0
|
|
3906
|
+
for (const task of state.tasks) {
|
|
3907
|
+
if (!task || task.status !== 'doing' || task.needsUser === true) continue
|
|
3908
|
+
const sameLead = leadId !== '' && asString(task.dispatchedSessionId) === leadId
|
|
3909
|
+
const sameCwd = wantCwd !== '' && typeof task.cwd === 'string' && normalizePathForCompare(task.cwd) === wantCwd
|
|
3910
|
+
if (!sameLead && !sameCwd) continue
|
|
3911
|
+
const stamp = Date.parse(asString(task.updatedAt) || asString(task.startedAt) || asString(task.createdAt))
|
|
3912
|
+
if (Number.isFinite(stamp) && now - stamp > LEAD_IN_FLIGHT_TTL_MS) continue
|
|
3913
|
+
|
|
3914
|
+
const isMerging = asString(task.assignee).trim() === 'merging'
|
|
3915
|
+
if (isMerging) return true
|
|
3916
|
+
|
|
3917
|
+
const hasWorktree = asString(task.worktreePath).trim() !== ''
|
|
3918
|
+
if (!canIsolate) {
|
|
3919
|
+
if (task.workerRunState === 'running') return true
|
|
3920
|
+
if (task.autoDispatch !== LEAD_AUTO_MARK && task.workerRunState === 'ended') return true
|
|
3921
|
+
continue
|
|
3922
|
+
}
|
|
3923
|
+
|
|
3924
|
+
// Git Worktree 并发模式:主目录裸跑任务仍串行保护;挂载了独立 worktreePath 的任务允许并发至 MAX_CONCURRENT_WORKTREES。
|
|
3925
|
+
if (task.workerRunState === 'running') {
|
|
3926
|
+
if (!hasWorktree) return true
|
|
3927
|
+
isolatedRunning += 1
|
|
3928
|
+
if (isolatedRunning >= MAX_CONCURRENT_WORKTREES) return true
|
|
3929
|
+
continue
|
|
3930
|
+
}
|
|
3931
|
+
if (
|
|
3932
|
+
task.autoDispatch !== LEAD_AUTO_MARK &&
|
|
3933
|
+
task.workerRunState === 'ended' &&
|
|
3934
|
+
!hasWorktree &&
|
|
3935
|
+
!taskHasActiveSubtasks(state, task.id)
|
|
3936
|
+
) {
|
|
3937
|
+
return true
|
|
3938
|
+
}
|
|
3939
|
+
}
|
|
3940
|
+
return false
|
|
3941
|
+
}
|
|
3942
|
+
|
|
2732
3943
|
/**
|
|
2733
3944
|
* 工作区组长路由(§1.5):解析任务 cwd → 工作区 key → 复用/创建常驻组长。
|
|
2734
3945
|
* 绝不 createDispatchSession(每任务新建),也绝不跨工作区改派。
|
|
@@ -2762,6 +3973,9 @@ async function routeWorkspaceLead(rt, task, config, agents, options, now) {
|
|
|
2762
3973
|
if (!agent) return { ok: false, reason: 'lead-unavailable' }
|
|
2763
3974
|
// force(立即派发)时组长忙也把消息排进它的下一轮,与旧模式 creator-busy 的 force 语义一致。
|
|
2764
3975
|
if (agent.status !== 'idle' && options.force !== true) return { ok: false, reason: 'lead-busy' }
|
|
3976
|
+
if (options.force !== true && hasActiveWorkspaceExecution(rt.state, mapping.sessionId, cwd, now)) {
|
|
3977
|
+
return { ok: false, reason: 'lead-worker-busy' }
|
|
3978
|
+
}
|
|
2765
3979
|
return { ok: true, agent, key }
|
|
2766
3980
|
}
|
|
2767
3981
|
// 没有映射 → 懒创建本工作区的常驻组长(一个工作区一个,不是每任务一个)。
|
|
@@ -2774,6 +3988,9 @@ async function routeWorkspaceLead(rt, task, config, agents, options, now) {
|
|
|
2774
3988
|
if (created.entry) config.workspaceLeads = putWorkspaceLead(config.workspaceLeads, key, created.entry)
|
|
2775
3989
|
if (!created.agent) return { ok: false, reason: 'lead-unavailable' }
|
|
2776
3990
|
if (created.agent.status !== 'idle' && options.force !== true) return { ok: false, reason: 'lead-busy' }
|
|
3991
|
+
if (options.force !== true && hasActiveWorkspaceExecution(rt.state, created.entry && created.entry.sessionId, cwd, now)) {
|
|
3992
|
+
return { ok: false, reason: 'lead-worker-busy' }
|
|
3993
|
+
}
|
|
2777
3994
|
return { ok: true, agent: created.agent, key }
|
|
2778
3995
|
}
|
|
2779
3996
|
|
|
@@ -2869,17 +4086,27 @@ function recordLeadAutoError(rt, message, now = Date.now()) {
|
|
|
2869
4086
|
console.warn('[taskboard] ' + auto.lastError)
|
|
2870
4087
|
}
|
|
2871
4088
|
|
|
2872
|
-
/**
|
|
4089
|
+
/**
|
|
4090
|
+
* worker 会话 id 对应的**宿主自动建**任务:同一 worker 只建一条(§1.8 去重 / 完成回写)。
|
|
4091
|
+
* v0.3.1:优先认宿主独占的 `workerSessionId`(真实执行会话 id),老 board / 旧 Host 没有这个字段时
|
|
4092
|
+
* 才回退到 `assignee`(v0.2.9 之前的语义:assignee 直接写 subagentId)——当前 dsh 的 `subagent`
|
|
4093
|
+
* 结果没有 subagentId,assignee 可能是名字,不能只靠它认任务。
|
|
4094
|
+
* 只认带标记的任务:轮询投递任务的 workerSessionId / assignee 也可能被写成 worker 会话 id,
|
|
4095
|
+
* 那是组长审核的对象,绝不能被宿主自动收尾(§1.8 完成回写)。
|
|
4096
|
+
*/
|
|
2873
4097
|
export function findTaskByWorker(state, workerSessionId) {
|
|
2874
4098
|
const id = trimmed(workerSessionId, 200)
|
|
2875
4099
|
if (!state || !Array.isArray(state.tasks) || id === '') return null
|
|
2876
4100
|
for (let i = state.tasks.length - 1; i >= 0; i--) {
|
|
2877
4101
|
const task = state.tasks[i]
|
|
2878
|
-
if (!task || task.
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
4102
|
+
if (!task || task.autoDispatch !== LEAD_AUTO_MARK) continue
|
|
4103
|
+
const storedWorker = asString(task.workerSessionId)
|
|
4104
|
+
if (storedWorker !== '') {
|
|
4105
|
+
if (storedWorker === id) return task
|
|
4106
|
+
continue
|
|
4107
|
+
}
|
|
4108
|
+
// 老 board / v0.2.9 之前没有 workerSessionId 字段:只能回退 assignee。
|
|
4109
|
+
if (task.assignee === id) return task
|
|
2883
4110
|
}
|
|
2884
4111
|
return null
|
|
2885
4112
|
}
|
|
@@ -3082,15 +4309,71 @@ export function looksLikeSessionId(value) {
|
|
|
3082
4309
|
return SESSION_ID_PATTERN.test(text)
|
|
3083
4310
|
}
|
|
3084
4311
|
|
|
4312
|
+
/**
|
|
4313
|
+
* v0.3.5:派发 prompt 行首显式声明的「父任务:t-N」/「父卡:t-N」(fan-out 切片 / 合并 / 验证子卡)。
|
|
4314
|
+
* 命中后闸门直接走新建子卡并关联 `parentTaskId`,绝不误吞父卡,彻底替代旧版「prompt 严禁提父卡」的文字禁区。
|
|
4315
|
+
*/
|
|
4316
|
+
export function dispatchExplicitParentId(text) {
|
|
4317
|
+
for (const line of normalizeDispatchLines(text)) {
|
|
4318
|
+
const match = /^(?:父任务|父卡) *(?:id *)?: *(t-[0-9]{1,6})(?![0-9])/i.exec(line)
|
|
4319
|
+
if (!match) continue
|
|
4320
|
+
const id = match[1].toLowerCase()
|
|
4321
|
+
const rest = line.slice(match[0].length)
|
|
4322
|
+
if (taskIdsInDispatchLine(rest).some((other) => other.toLowerCase() !== id)) continue
|
|
4323
|
+
return id
|
|
4324
|
+
}
|
|
4325
|
+
return ''
|
|
4326
|
+
}
|
|
4327
|
+
|
|
4328
|
+
/** 某张任务名下是否已经存在未归档子卡(已拆片的父卡不得再被「看板任务:t-N」引用抢占)。 */
|
|
4329
|
+
export function taskHasActiveSubtasks(state, parentId) {
|
|
4330
|
+
const id = normalizeParentTaskId(parentId)
|
|
4331
|
+
if (!id || !state || !Array.isArray(state.tasks)) return false
|
|
4332
|
+
return state.tasks.some(
|
|
4333
|
+
(item) => item && item.status !== 'archived' && normalizeParentTaskId(item.parentTaskId) === id,
|
|
4334
|
+
)
|
|
4335
|
+
}
|
|
4336
|
+
|
|
4337
|
+
/**
|
|
4338
|
+
* v0.3.5:当闸门已确定要新建一张自动卡(未复用已有卡)时,推导它的所属父任务 id:
|
|
4339
|
+
* 优先级:行首 `父任务:t-N` → `description` 中的首个 `t-N`(兼容 v0.3.3 切片写法与 `验证 t-1`)
|
|
4340
|
+
* → 未能复用的 `看板任务:t-N` 引用(如对正在运行或已拆片的 `t-1` 派出的验证 / 合并 worker)。
|
|
4341
|
+
* 只有该 `t-N` 在板内真实存在且未归档时才采用。
|
|
4342
|
+
*/
|
|
4343
|
+
export function inferParentTaskIdForAutoCard(args, state) {
|
|
4344
|
+
if (!state || !Array.isArray(state.tasks)) return null
|
|
4345
|
+
const prompt = subagentPromptText(args)
|
|
4346
|
+
const description = isPlainObject(args) ? asString(args.description) : ''
|
|
4347
|
+
const candidates = []
|
|
4348
|
+
const explicitParent = dispatchExplicitParentId(prompt)
|
|
4349
|
+
if (explicitParent !== '') candidates.push(explicitParent)
|
|
4350
|
+
if (description !== '') {
|
|
4351
|
+
const descMatch = /(?:^|[^A-Za-z0-9_-])(t-[0-9]{1,6})(?![0-9])/i.exec(description)
|
|
4352
|
+
if (descMatch) candidates.push(descMatch[1].toLowerCase())
|
|
4353
|
+
}
|
|
4354
|
+
const refId = dispatchReferencedTaskId(prompt)
|
|
4355
|
+
if (refId !== '') candidates.push(refId)
|
|
4356
|
+
for (const candidateId of candidates) {
|
|
4357
|
+
const parent = taskById(state, candidateId)
|
|
4358
|
+
if (parent && parent.status !== 'archived') return parent.id
|
|
4359
|
+
}
|
|
4360
|
+
return null
|
|
4361
|
+
}
|
|
4362
|
+
|
|
3085
4363
|
/**
|
|
3086
4364
|
* 「看板任务:t-N」提到的卡片能否被这次派发认领:
|
|
3087
4365
|
* - 必须在待做 / 进行中(做完 / 归档的任务不抢);
|
|
4366
|
+
* - 名下不能已有未归档子卡(已进入 fan-out 的父卡不能被后续合并 / 验证子 Agent 误抢占);
|
|
4367
|
+
* - 当前没有正在跑的 worker(`workerRunState !== 'running'`:v0.3.1 起 `assignee` 是 worker 名字,
|
|
4368
|
+
* 只看 `looksLikeSessionId(assignee)` 会漏掉正在跑的 worker,导致验证子 Agent 抢占原卡);
|
|
3088
4369
|
* - 还没挂真实 worker 会话 id(已挂 = 已有 worker 在干,这次多半是验证子 Agent / 另一个 worker,
|
|
3089
4370
|
* 应该有自己的卡片;自由文本 assignee 如 `taskboard-worker` 不算)。
|
|
3090
4371
|
*/
|
|
3091
|
-
export function canReuseMentionedTask(task) {
|
|
4372
|
+
export function canReuseMentionedTask(task, state = null) {
|
|
3092
4373
|
if (!task) return false
|
|
3093
4374
|
if (task.status !== 'todo' && task.status !== 'doing') return false
|
|
4375
|
+
if (task.workerRunState === 'running') return false
|
|
4376
|
+
if (state && taskHasActiveSubtasks(state, task.id)) return false
|
|
3094
4377
|
return !looksLikeSessionId(task.assignee)
|
|
3095
4378
|
}
|
|
3096
4379
|
|
|
@@ -3110,8 +4393,8 @@ export function takePreparedDispatch(rt, exec) {
|
|
|
3110
4393
|
|
|
3111
4394
|
/**
|
|
3112
4395
|
* §1.8(0.2.4):组长把轮询投递任务置 doing → 记一条「即将为它派 worker」的意图(不落盘)。
|
|
3113
|
-
*
|
|
3114
|
-
*
|
|
4396
|
+
* 只在任务当前未挂 worker 且未挂提问(`assignee === ''`、`workerRunState !== 'running'`、`needsUser !== true`)
|
|
4397
|
+
* 时记录:worker 已挂上或正在等用户回复时不算新派发意图,避免把后续直聊派活错误并进旧任务。
|
|
3115
4398
|
*/
|
|
3116
4399
|
export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
|
|
3117
4400
|
try {
|
|
@@ -3123,7 +4406,7 @@ export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
|
|
|
3123
4406
|
if (!task) return false
|
|
3124
4407
|
if (task.status !== 'doing' || asString(task.notifiedAt) === '') return false
|
|
3125
4408
|
if (task.dispatchedSessionId !== leadId) return false
|
|
3126
|
-
if (task.assignee !== '') return false
|
|
4409
|
+
if (task.assignee !== '' || task.workerRunState === 'running' || task.needsUser === true) return false
|
|
3127
4410
|
if (!(rt.leadDispatchIntent instanceof Map)) rt.leadDispatchIntent = new Map()
|
|
3128
4411
|
rt.leadDispatchIntent.set(leadId, { taskId: task.id, at: now })
|
|
3129
4412
|
return true
|
|
@@ -3132,7 +4415,7 @@ export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
|
|
|
3132
4415
|
}
|
|
3133
4416
|
}
|
|
3134
4417
|
|
|
3135
|
-
/** 取走(一次性)该组长的派发意图;过期 / 任务状态不符 → 作废。 */
|
|
4418
|
+
/** 取走(一次性)该组长的派发意图;过期 / 任务状态不符 / 已挂 running worker / 正在等用户回复 → 作废。 */
|
|
3136
4419
|
function takeLeadDispatchIntent(rt, leadId, now) {
|
|
3137
4420
|
if (!leadId || !(rt.leadDispatchIntent instanceof Map)) return null
|
|
3138
4421
|
const entry = rt.leadDispatchIntent.get(leadId)
|
|
@@ -3141,12 +4424,15 @@ function takeLeadDispatchIntent(rt, leadId, now) {
|
|
|
3141
4424
|
if (!Number.isFinite(entry.at) || now - entry.at > LEAD_DISPATCH_INTENT_MS) return null
|
|
3142
4425
|
const task = taskById(rt.state, entry.taskId)
|
|
3143
4426
|
if (!task || task.status !== 'doing' || asString(task.notifiedAt) === '') return null
|
|
4427
|
+
if (task.workerRunState === 'running' || task.needsUser === true) return null
|
|
3144
4428
|
return task
|
|
3145
4429
|
}
|
|
3146
4430
|
|
|
3147
4431
|
/**
|
|
3148
4432
|
* 这次派发的 prompt 是否真的指向这条任务(任务 id 或标题出现在 prompt 里)。
|
|
3149
4433
|
* 用来防止「组长刚给 t-68 记了派发意图」的**下一条无关直聊派发**把 t-68 认领走(t-69 事故的变体)。
|
|
4434
|
+
* v0.3.3 补充:如果 `description` 显式带了父任务 id(如 `t-107 切片 A`)而 `prompt` 没有带该任务 id,
|
|
4435
|
+
* 这是并行 fan-out 的切片 worker——即使 prompt 碰巧包含父任务短标题,也不能把父卡认领走。
|
|
3150
4436
|
*/
|
|
3151
4437
|
export function dispatchMentionsTask(args, task) {
|
|
3152
4438
|
if (!task) return false
|
|
@@ -3155,7 +4441,10 @@ export function dispatchMentionsTask(args, task) {
|
|
|
3155
4441
|
const id = asString(task.id)
|
|
3156
4442
|
if (id !== '') {
|
|
3157
4443
|
const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
3158
|
-
|
|
4444
|
+
const idPattern = new RegExp('(^|[^A-Za-z0-9_-])' + escaped + '([^A-Za-z0-9_-]|$)')
|
|
4445
|
+
if (idPattern.test(prompt)) return true
|
|
4446
|
+
const description = isPlainObject(args) ? asString(args.description) : ''
|
|
4447
|
+
if (description !== '' && idPattern.test(description)) return false
|
|
3159
4448
|
}
|
|
3160
4449
|
const title = asString(task.title).trim()
|
|
3161
4450
|
return title.length >= 4 && prompt.includes(title)
|
|
@@ -3167,7 +4456,14 @@ export function findPendingDispatchCard(state, leadId, title, note, now = Date.n
|
|
|
3167
4456
|
for (let i = state.tasks.length - 1; i >= 0; i -= 1) {
|
|
3168
4457
|
const task = state.tasks[i]
|
|
3169
4458
|
if (!task || task.autoDispatch !== LEAD_AUTO_MARK) continue
|
|
3170
|
-
if (
|
|
4459
|
+
if (
|
|
4460
|
+
task.status !== 'doing' ||
|
|
4461
|
+
task.assignee !== '' ||
|
|
4462
|
+
task.workerRunState !== null ||
|
|
4463
|
+
asString(task.workerSessionId) !== ''
|
|
4464
|
+
) {
|
|
4465
|
+
continue
|
|
4466
|
+
}
|
|
3171
4467
|
if (task.dispatchedSessionId !== leadId) continue
|
|
3172
4468
|
if (task.title !== title || (task.note || '') !== (note || '')) continue
|
|
3173
4469
|
const stamp = Date.parse(asString(task.createdAt))
|
|
@@ -3252,30 +4548,53 @@ export function prepareLeadDispatch(rt, input, now = Date.now()) {
|
|
|
3252
4548
|
// 0) 一次性消费「组长刚置 doing」的意图:即使这次靠显式任务 id 认领,也要把它清掉,
|
|
3253
4549
|
// 否则陈旧的 t-68 意图会在下一次无关的直聊派发里把旧任务认领走(t-69 事故的变体)。
|
|
3254
4550
|
const intent = takeLeadDispatchIntent(rt, leadId, now)
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
const
|
|
3265
|
-
if (
|
|
3266
|
-
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
4551
|
+
const promptText = subagentPromptText(args)
|
|
4552
|
+
// 0b) v0.3.5 + v0.3.9:先提取行首显式 `任务 id:t-K` 与 `父任务:t-N`。
|
|
4553
|
+
// - 若明确指定了 `任务 id:t-K` 且不等于 `父任务:t-N`(包括续做接管某张失败子卡时同时写两行的场景),
|
|
4554
|
+
// 直接按 `task-id` 复用 `t-K`(不另建僵尸卡);
|
|
4555
|
+
// - 否则若显式声明 `父任务:t-N` 且父卡存在未归档,则判定为新建子卡派发,跳过父卡认领(1b / 2)。
|
|
4556
|
+
const explicitParentRaw = dispatchExplicitParentId(promptText)
|
|
4557
|
+
const explicitParentTask = explicitParentRaw === '' ? null : taskById(rt.state, explicitParentRaw)
|
|
4558
|
+
const explicitParentId =
|
|
4559
|
+
explicitParentTask && explicitParentTask.status !== 'archived' ? explicitParentTask.id : null
|
|
4560
|
+
const explicitId = dispatchTaskIdFromPrompt(promptText)
|
|
4561
|
+
if (explicitId !== '' && explicitId !== explicitParentId) {
|
|
4562
|
+
const explicit = taskById(rt.state, explicitId)
|
|
4563
|
+
if (explicit && explicit.status !== 'archived') {
|
|
4564
|
+
if (explicitParentId && !explicit.parentTaskId) {
|
|
4565
|
+
explicit.parentTaskId = normalizeParentTaskId(explicitParentId, explicit.id)
|
|
4566
|
+
}
|
|
4567
|
+
return finishPreparedDispatch(rt, auto, store, exec, explicit, false, 'task-id', now)
|
|
4568
|
+
}
|
|
4569
|
+
}
|
|
4570
|
+
if (!explicitParentId) {
|
|
4571
|
+
// 1b) 「看板任务:t-N」式引用(0.2.4):组长直聊派活时手动建了卡、prompt 用这种写法也要认领,
|
|
4572
|
+
// 否则会为同一件事建两张卡。只认领待做 / 进行中、无子卡且还没挂真实 worker 的卡片。
|
|
4573
|
+
const referencedId = dispatchReferencedTaskId(promptText)
|
|
4574
|
+
const referenced = referencedId === '' ? null : taskById(rt.state, referencedId)
|
|
4575
|
+
if (referenced && canReuseMentionedTask(referenced, rt.state)) {
|
|
4576
|
+
return finishPreparedDispatch(rt, auto, store, exec, referenced, false, 'task-id-mention', now)
|
|
4577
|
+
}
|
|
4578
|
+
// 2) 组长刚把某条轮询任务置 doing → 这次派发就是它的 worker(要求 prompt 真的指向那条任务)。
|
|
4579
|
+
if (intent && dispatchMentionsTask(args, intent) && !taskHasActiveSubtasks(rt.state, intent.id)) {
|
|
4580
|
+
return finishPreparedDispatch(rt, auto, store, exec, intent, false, 'lead-intent', now)
|
|
4581
|
+
}
|
|
3271
4582
|
}
|
|
3272
4583
|
// 3) 同参数重复调用(模型重试 / PTC 嵌套)→ 复用刚建好还没挂 worker 的卡片。
|
|
3273
4584
|
const pending = findPendingDispatchCard(rt.state, leadId, title, note, now)
|
|
3274
4585
|
if (pending) return finishPreparedDispatch(rt, auto, store, exec, pending, false, 'pending-duplicate', now)
|
|
3275
|
-
// 4) 新派发:先建卡(doing + autoDispatch),写盘成功才允许启动 worker。
|
|
4586
|
+
// 4) 新派发:先建卡(doing + autoDispatch + 可选 parentTaskId),写盘成功才允许启动 worker。
|
|
4587
|
+
const parentTaskId = explicitParentId || inferParentTaskIdForAutoCard(args, rt.state)
|
|
3276
4588
|
const task = addTask(
|
|
3277
4589
|
rt.state,
|
|
3278
|
-
{
|
|
4590
|
+
{
|
|
4591
|
+
title,
|
|
4592
|
+
note,
|
|
4593
|
+
source: 'agent',
|
|
4594
|
+
sessionId: leadId || null,
|
|
4595
|
+
cwd: leadDispatchCwd(rt, agent, args),
|
|
4596
|
+
parentTaskId,
|
|
4597
|
+
},
|
|
3279
4598
|
now,
|
|
3280
4599
|
)
|
|
3281
4600
|
applyTaskUpdate(rt.state, task.id, { status: 'doing' }, now)
|
|
@@ -3423,13 +4742,16 @@ export function releasePreparedDispatch(rt, exec, abortReason = '', now = Date.n
|
|
|
3423
4742
|
export const discardPreparedDispatch = releasePreparedDispatch
|
|
3424
4743
|
|
|
3425
4744
|
/**
|
|
3426
|
-
* tools/result 命中「工作区组长成功派出 worker」时把 worker
|
|
4745
|
+
* tools/result 命中「工作区组长成功派出 worker」时把 worker 信息挂到卡片上(§1.8)。
|
|
3427
4746
|
*
|
|
3428
4747
|
* 0.2.4 起卡片由 `tools/pre-execute` 的派发闸门(`prepareLeadDispatch`)在 worker 启动**之前**
|
|
3429
4748
|
* 建好 / 认领好;这里优先消费闸门留下的 `exec → 卡片` 句柄(`prepared` 分支),只补 worker 字段。
|
|
3430
4749
|
* 闸门没留下句柄(老宿主 / 单测直接调用)时退回旧的「观察后补建」路径,保证兜底也有记录。
|
|
4750
|
+
* v0.3.1:当前 dsh 的 `subagent` 成功结果只有 `{kind:'activation', name}`(没有 subagentId),
|
|
4751
|
+
* `childId` 可能为空——这时用 name 先占位,`workerSessionId` 由 `backfillWorkerSessionId()`
|
|
4752
|
+
* 从子 Agent 目录按 name 异步回填;**不能**因为缺 id 就丢掉「worker 已启动」事实。
|
|
3431
4753
|
* 只做副作用:永不抛出(失败只记 leadAuto.lastError),不阻断派发。
|
|
3432
|
-
* @param {{agent:object, childId
|
|
4754
|
+
* @param {{agent:object, childId?:string, workerName?:string, args?:object, exec?:object}} input
|
|
3433
4755
|
* @returns {{created:boolean, reason?:string, taskId?:string, task?:object}}
|
|
3434
4756
|
*/
|
|
3435
4757
|
export function handleSubagentDispatch(rt, input, now = Date.now()) {
|
|
@@ -3437,7 +4759,8 @@ export function handleSubagentDispatch(rt, input, now = Date.now()) {
|
|
|
3437
4759
|
try {
|
|
3438
4760
|
const agent = input && input.agent
|
|
3439
4761
|
const childId = trimmed(input && input.childId, 200)
|
|
3440
|
-
|
|
4762
|
+
const workerName = trimmed(input && input.workerName, 200)
|
|
4763
|
+
if (!agent) {
|
|
3441
4764
|
auto.skipped += 1
|
|
3442
4765
|
auto.updatedAt = iso(now)
|
|
3443
4766
|
return { created: false, reason: 'skipped' }
|
|
@@ -3463,11 +4786,16 @@ export function handleSubagentDispatch(rt, input, now = Date.now()) {
|
|
|
3463
4786
|
}
|
|
3464
4787
|
}
|
|
3465
4788
|
// 自动建的卡片归当前 worker;轮询任务只在还没挂 worker 时补——组长审核的对象不被覆盖。
|
|
3466
|
-
|
|
3467
|
-
|
|
4789
|
+
const workerLabel = childId !== '' ? childId : workerName
|
|
4790
|
+
if (workerLabel !== '' && (task.autoDispatch === LEAD_AUTO_MARK || task.assignee === '')) {
|
|
4791
|
+
task.assignee = workerLabel
|
|
4792
|
+
}
|
|
4793
|
+
// v0.2.9(§2):执行会话 id 由宿主独占,**总是**覆盖为本次 worker 会话——不看 `autoDispatch`、
|
|
3468
4794
|
// 不看已有 `assignee`。组长把 assignee 写成 subagent 名字(实测 `session-jump-bug`)时,
|
|
3469
4795
|
// 看板「对话」仍指向真正在跑的那个会话;重派后也不会继续指向旧 worker。
|
|
3470
|
-
|
|
4796
|
+
// v0.3.1:当前 dsh 的 `subagent` 结果没有 subagentId,先置 null(清掉旧 worker),
|
|
4797
|
+
// 再由 `backfillWorkerSessionId()` 从子 Agent 目录按 name 回填。
|
|
4798
|
+
task.workerSessionId = childId !== '' ? childId : null
|
|
3471
4799
|
task.workerRunState = 'running'
|
|
3472
4800
|
if (sessionId !== '' && asString(task.dispatchedSessionId) === '') task.dispatchedSessionId = sessionId
|
|
3473
4801
|
if (asString(task.dispatchedSessionTitle) === '') task.dispatchedSessionTitle = sessionTitle(agent)
|
|
@@ -3475,7 +4803,7 @@ export function handleSubagentDispatch(rt, input, now = Date.now()) {
|
|
|
3475
4803
|
task.updatedAt = iso(now)
|
|
3476
4804
|
const saved = commitBoard(rt.state, rt.filePath)
|
|
3477
4805
|
auto.lastTaskId = task.id
|
|
3478
|
-
auto.lastWorkerSessionId = childId
|
|
4806
|
+
if (childId !== '') auto.lastWorkerSessionId = childId
|
|
3479
4807
|
auto.updatedAt = iso(now)
|
|
3480
4808
|
if (saved && saved.saved === false) {
|
|
3481
4809
|
// worker 已经跑起来了(无法回退),但卡片在启动前已落盘:只记错误,让排障知道 worker 会话 id 没落盘。
|
|
@@ -3485,6 +4813,13 @@ export function handleSubagentDispatch(rt, input, now = Date.now()) {
|
|
|
3485
4813
|
}
|
|
3486
4814
|
// 卡片在闸门之后被删掉了:继续走下面的兜底建卡,绝不出现「worker 在跑、看板没记录」。
|
|
3487
4815
|
}
|
|
4816
|
+
if (childId === '') {
|
|
4817
|
+
// 没有 prepared 卡片、也拿不到 worker 会话 id:没有可追踪的对象,不建卡也不降级。
|
|
4818
|
+
// 计一次 skipped:handler 走到了但没有动作(§3.2 口径)。
|
|
4819
|
+
auto.skipped += 1
|
|
4820
|
+
auto.updatedAt = iso(now)
|
|
4821
|
+
return { created: false, reason: 'no-child-id' }
|
|
4822
|
+
}
|
|
3488
4823
|
const existing = findTaskByWorker(rt.state, childId)
|
|
3489
4824
|
if (existing) {
|
|
3490
4825
|
auto.deduped += 1
|
|
@@ -3536,6 +4871,111 @@ export function handleSubagentDispatch(rt, input, now = Date.now()) {
|
|
|
3536
4871
|
}
|
|
3537
4872
|
}
|
|
3538
4873
|
|
|
4874
|
+
/**
|
|
4875
|
+
* v0.3.1:当前 dsh 的 `subagent` 成功结果只有 `{kind:'activation', name}`,没有 subagentId。
|
|
4876
|
+
* worker 会话 id 从子 Agent 目录(`subagents.listDescendants(parentSessionId)`)按 name 回填——
|
|
4877
|
+
* 同一个父级下 name 唯一(dsh 的 catalog 约束)。best-effort:目录不可用 / 子 Agent 还没出现时
|
|
4878
|
+
* 保持 `workerSessionId=null`,卡片仍是 doing;**绝不**因此回退 todo 再被轮询重复派发。
|
|
4879
|
+
* @param {{agent:object, taskId:string, workerName:string}} input
|
|
4880
|
+
* @returns {boolean} 是否已发起异步回填
|
|
4881
|
+
*/
|
|
4882
|
+
function backfillWorkerSessionId(rt, input) {
|
|
4883
|
+
const agent = input && input.agent
|
|
4884
|
+
const taskId = trimmed(input && input.taskId, 200)
|
|
4885
|
+
const workerName = trimmed(input && input.workerName, 200)
|
|
4886
|
+
const parentId = agentSessionId(agent) || ''
|
|
4887
|
+
if (taskId === '' || workerName === '' || parentId === '') return false
|
|
4888
|
+
const ctx = rt && rt.ctx
|
|
4889
|
+
const subagents = ctx && typeof ctx.get === 'function' ? ctx.get('subagents') : undefined
|
|
4890
|
+
if (!subagents || typeof subagents.listDescendants !== 'function') return false
|
|
4891
|
+
Promise.resolve()
|
|
4892
|
+
.then(() => subagents.listDescendants(parentId))
|
|
4893
|
+
.then((rows) => {
|
|
4894
|
+
if (!Array.isArray(rows)) return
|
|
4895
|
+
const matching = rows.filter(
|
|
4896
|
+
(row) => row && row.parentId === parentId && row.kind === 'child' && asString(row.name) === workerName,
|
|
4897
|
+
)
|
|
4898
|
+
if (matching.length === 0) return
|
|
4899
|
+
reloadBoardIfStale(rt)
|
|
4900
|
+
const task = taskById(rt.state, taskId)
|
|
4901
|
+
if (!task) return
|
|
4902
|
+
// 已经有 id(回填过 / 重派换了 worker)→ 不覆盖。
|
|
4903
|
+
if (asString(task.workerSessionId) !== '') return
|
|
4904
|
+
// 长驻组长会话下若复用 worker name,倒序优先认领尚未绑定其它卡片的最新 childId。
|
|
4905
|
+
let childId = ''
|
|
4906
|
+
for (let i = matching.length - 1; i >= 0; i -= 1) {
|
|
4907
|
+
const candidateId = asString(matching[i].id).trim()
|
|
4908
|
+
if (candidateId === '') continue
|
|
4909
|
+
const taken = rt.state.tasks.some(
|
|
4910
|
+
(other) => other && other.id !== taskId && asString(other.workerSessionId) === candidateId,
|
|
4911
|
+
)
|
|
4912
|
+
if (!taken) {
|
|
4913
|
+
childId = candidateId
|
|
4914
|
+
break
|
|
4915
|
+
}
|
|
4916
|
+
if (childId === '') childId = candidateId
|
|
4917
|
+
}
|
|
4918
|
+
if (childId === '') return
|
|
4919
|
+
task.workerSessionId = childId
|
|
4920
|
+
if ((task.workerRunState === null || task.workerRunState === '') && task.status === 'doing') {
|
|
4921
|
+
task.workerRunState = 'running'
|
|
4922
|
+
}
|
|
4923
|
+
task.updatedAt = iso(Date.now())
|
|
4924
|
+
const saved = commitBoard(rt.state, rt.filePath)
|
|
4925
|
+
if (saved && saved.saved === false) {
|
|
4926
|
+
console.warn('[taskboard] worker 会话 id 回填写盘失败:' + (saved.error || ''))
|
|
4927
|
+
}
|
|
4928
|
+
const auto = ensureLeadAuto(rt)
|
|
4929
|
+
auto.lastWorkerSessionId = childId
|
|
4930
|
+
auto.updatedAt = iso(Date.now())
|
|
4931
|
+
})
|
|
4932
|
+
.catch((error) => {
|
|
4933
|
+
// 回填是 best-effort,不是派发失败:只告警,不污染 leadAuto.lastError。
|
|
4934
|
+
console.warn('[taskboard] worker 会话 id 回填失败:' + describeError(error))
|
|
4935
|
+
})
|
|
4936
|
+
return true
|
|
4937
|
+
}
|
|
4938
|
+
|
|
4939
|
+
/**
|
|
4940
|
+
* v0.3.9:轮询投递任务 / 人工任务(`autoDispatch !== LEAD_AUTO_MARK`)在 worker 结束时,
|
|
4941
|
+
* 绝不自动置 `done` 或改 `result`(交由组长审核),但必须把宿主独占的 `workerRunState` 从 `'running'`
|
|
4942
|
+
* 收敛为 `'ended'` / `'failed'`(并顺带回填缺失的 `workerSessionId`),避免像 t-111 那样任务已 `done`
|
|
4943
|
+
* 却永久残留 `workerRunState='running'`。
|
|
4944
|
+
*/
|
|
4945
|
+
function settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now) {
|
|
4946
|
+
if (!rt || !rt.state || !Array.isArray(rt.state.tasks) || childId === '') return false
|
|
4947
|
+
let matched = null
|
|
4948
|
+
for (let i = rt.state.tasks.length - 1; i >= 0; i -= 1) {
|
|
4949
|
+
const item = rt.state.tasks[i]
|
|
4950
|
+
if (!item || item.workerRunState !== 'running') continue
|
|
4951
|
+
if (asString(item.workerSessionId) === childId) {
|
|
4952
|
+
matched = item
|
|
4953
|
+
break
|
|
4954
|
+
}
|
|
4955
|
+
}
|
|
4956
|
+
if (!matched && parentId !== '') {
|
|
4957
|
+
const candidates = rt.state.tasks.filter(
|
|
4958
|
+
(item) =>
|
|
4959
|
+
item &&
|
|
4960
|
+
item.workerRunState === 'running' &&
|
|
4961
|
+
asString(item.workerSessionId) === '' &&
|
|
4962
|
+
(asString(item.dispatchedSessionId) === parentId || asString(item.sessionId) === parentId),
|
|
4963
|
+
)
|
|
4964
|
+
if (workerName !== '') {
|
|
4965
|
+
const byName = candidates.filter((item) => asString(item.assignee) === workerName)
|
|
4966
|
+
if (byName.length === 1) matched = byName[0]
|
|
4967
|
+
} else if (candidates.length === 1) {
|
|
4968
|
+
matched = candidates[0]
|
|
4969
|
+
}
|
|
4970
|
+
}
|
|
4971
|
+
if (!matched) return false
|
|
4972
|
+
if (asString(matched.workerSessionId) === '') matched.workerSessionId = childId
|
|
4973
|
+
matched.workerRunState = stopReason === 'completed' ? 'ended' : 'failed'
|
|
4974
|
+
matched.updatedAt = iso(now)
|
|
4975
|
+
commitBoard(rt.state, rt.filePath)
|
|
4976
|
+
return true
|
|
4977
|
+
}
|
|
4978
|
+
|
|
3539
4979
|
/**
|
|
3540
4980
|
* subagent/end:worker 结束 → **宿主自动建的任务**置 done + result(§1.8),并 flush 完成回执(§1.6)。
|
|
3541
4981
|
* 只认带 `autoDispatch === 'lead-dispatch'` 标记的任务:轮询投递任务的 assignee 也可能被组长写成 worker
|
|
@@ -3553,24 +4993,69 @@ export async function handleSubagentEnd(rt, info, now = Date.now()) {
|
|
|
3553
4993
|
return { updated: false, reason: 'skipped' }
|
|
3554
4994
|
}
|
|
3555
4995
|
reloadBoardIfStale(rt)
|
|
3556
|
-
const
|
|
4996
|
+
const parentId = asString(info && info.parentSessionId).trim()
|
|
4997
|
+
let workerName = trimmed(info && info.name, 200)
|
|
4998
|
+
let task = findTaskByWorker(rt.state, childId)
|
|
4999
|
+
if (!task) {
|
|
5000
|
+
// v0.3.1:workerSessionId 还没回填时(当前 dsh 的 subagent 结果没有 subagentId),
|
|
5001
|
+
// 先按 worker name(info.name 或 subagents.listDescendants 反查 childId)精确匹配 candidate.assignee
|
|
5002
|
+
// (支持 v0.3.3 并发 fan-out 切片卡);拿不到 workerName 时,仅当该组长名下只此一条在跑的自动卡才兜底认领。
|
|
5003
|
+
if (parentId !== '') {
|
|
5004
|
+
if (workerName === '') {
|
|
5005
|
+
try {
|
|
5006
|
+
const ctx = rt && rt.ctx
|
|
5007
|
+
const subagents = ctx && typeof ctx.get === 'function' ? ctx.get('subagents') : undefined
|
|
5008
|
+
if (subagents && typeof subagents.listDescendants === 'function') {
|
|
5009
|
+
const rows = await subagents.listDescendants(parentId)
|
|
5010
|
+
if (Array.isArray(rows)) {
|
|
5011
|
+
const row = rows.find((item) => item && asString(item.id).trim() === childId)
|
|
5012
|
+
if (row) workerName = trimmed(row.name, 200)
|
|
5013
|
+
}
|
|
5014
|
+
}
|
|
5015
|
+
} catch {
|
|
5016
|
+
/* listDescendants 失败时退回单候选兜底 */
|
|
5017
|
+
}
|
|
5018
|
+
reloadBoardIfStale(rt)
|
|
5019
|
+
task = findTaskByWorker(rt.state, childId)
|
|
5020
|
+
}
|
|
5021
|
+
if (!task) {
|
|
5022
|
+
const candidates = rt.state.tasks.filter(
|
|
5023
|
+
(candidate) =>
|
|
5024
|
+
candidate &&
|
|
5025
|
+
candidate.autoDispatch === LEAD_AUTO_MARK &&
|
|
5026
|
+
candidate.status === 'doing' &&
|
|
5027
|
+
asString(candidate.workerRunState) === 'running' &&
|
|
5028
|
+
asString(candidate.sessionId) === parentId &&
|
|
5029
|
+
asString(candidate.workerSessionId) === '',
|
|
5030
|
+
)
|
|
5031
|
+
if (workerName !== '') {
|
|
5032
|
+
const byName = candidates.filter((candidate) => asString(candidate.assignee) === workerName)
|
|
5033
|
+
if (byName.length === 1) task = byName[0]
|
|
5034
|
+
}
|
|
5035
|
+
if (!task && workerName === '' && candidates.length === 1) {
|
|
5036
|
+
task = candidates[0]
|
|
5037
|
+
}
|
|
5038
|
+
}
|
|
5039
|
+
}
|
|
5040
|
+
}
|
|
5041
|
+
const rawStopReason = asString(info && info.stopReason).trim()
|
|
5042
|
+
const stopReason = rawStopReason === '' ? 'unknown' : rawStopReason
|
|
3557
5043
|
if (!task) {
|
|
3558
5044
|
// 不是宿主建的自动任务(例如组长审核时派去跑命令的验证子 Agent,
|
|
3559
|
-
// 或轮询投递任务的 worker——那条任务的 autoDispatch 为 null
|
|
5045
|
+
// 或轮询投递任务的 worker——那条任务的 autoDispatch 为 null):仅收敛其 workerRunState。
|
|
5046
|
+
settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now)
|
|
3560
5047
|
auto.skipped += 1
|
|
3561
5048
|
auto.updatedAt = iso(now)
|
|
3562
5049
|
return { updated: false, reason: 'no-task' }
|
|
3563
5050
|
}
|
|
3564
5051
|
if (!isLeadAutoTask(task) || asString(task.notifiedAt) !== '') {
|
|
3565
5052
|
// 兜底:findTaskByWorker 已经过滤过,这里再挡一层,确保轮询任务(notifiedAt 非空)永不被自动 done。
|
|
5053
|
+
settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now)
|
|
3566
5054
|
auto.skipped += 1
|
|
3567
5055
|
auto.updatedAt = iso(now)
|
|
3568
5056
|
return { updated: false, reason: 'not-auto', taskId: task.id }
|
|
3569
5057
|
}
|
|
3570
5058
|
const result = workerResultText(info)
|
|
3571
|
-
// 缺字段 / 空串 / 未知值一律按非 completed 处理(绝不静默置 done):文案里缺省写 unknown。
|
|
3572
|
-
const rawStopReason = asString(info && info.stopReason).trim()
|
|
3573
|
-
const stopReason = rawStopReason === '' ? 'unknown' : rawStopReason
|
|
3574
5059
|
const wasDoing = task.status === 'doing'
|
|
3575
5060
|
if (stopReason !== 'completed') {
|
|
3576
5061
|
if (!wasDoing) {
|
|
@@ -3598,6 +5083,42 @@ export async function handleSubagentEnd(rt, info, now = Date.now()) {
|
|
|
3598
5083
|
auto.updatedAt = iso(now)
|
|
3599
5084
|
return { updated: false, reason: 'status-' + task.status, taskId: task.id }
|
|
3600
5085
|
}
|
|
5086
|
+
// v0.5.0:直聊顶层自动卡(parentTaskId 为空)由宿主直接收尾置 done——若挂载了隔离 Git Worktree,
|
|
5087
|
+
// 必须在置 done 前自动合入主工作区并清理临时分支;若发生真实冲突,保持 doing + 写 lastError 保留现场!
|
|
5088
|
+
// (fan-out 内部切片子卡 parentTaskId 非空:保留其 worktreePath 供组长按波次调 taskboard_merge_worktree 合入。)
|
|
5089
|
+
if (
|
|
5090
|
+
wasDoing &&
|
|
5091
|
+
asString(task.parentTaskId) === '' &&
|
|
5092
|
+
asString(task.worktreePath) !== ''
|
|
5093
|
+
) {
|
|
5094
|
+
try {
|
|
5095
|
+
const merged = mergeAndCleanupTaskWorktree(rt, task.id, { cleanup: true, commit: false })
|
|
5096
|
+
if (merged.conflict) {
|
|
5097
|
+
if (result !== '') task.result = result
|
|
5098
|
+
if (asString(task.workerSessionId) === '') task.workerSessionId = childId
|
|
5099
|
+
task.workerRunState = 'ended'
|
|
5100
|
+
task.lastError = trimmed(merged.summary, 500)
|
|
5101
|
+
task.updatedAt = iso(now)
|
|
5102
|
+
commitBoard(rt.state, rt.filePath)
|
|
5103
|
+
auto.lastTaskId = task.id
|
|
5104
|
+
auto.lastWorkerSessionId = childId
|
|
5105
|
+
auto.updatedAt = iso(now)
|
|
5106
|
+
console.warn('[taskboard] 直聊任务自动合入隔离工作树冲突:' + merged.summary)
|
|
5107
|
+
return { updated: false, reason: 'worktree-conflict', taskId: task.id }
|
|
5108
|
+
}
|
|
5109
|
+
} catch (mergeError) {
|
|
5110
|
+
if (result !== '') task.result = result
|
|
5111
|
+
if (asString(task.workerSessionId) === '') task.workerSessionId = childId
|
|
5112
|
+
task.workerRunState = 'ended'
|
|
5113
|
+
task.lastError = trimmed('隔离工作树自动合入失败:' + describeError(mergeError), 500)
|
|
5114
|
+
task.updatedAt = iso(now)
|
|
5115
|
+
commitBoard(rt.state, rt.filePath)
|
|
5116
|
+
auto.lastTaskId = task.id
|
|
5117
|
+
auto.lastWorkerSessionId = childId
|
|
5118
|
+
auto.updatedAt = iso(now)
|
|
5119
|
+
return { updated: false, reason: 'worktree-merge-error', taskId: task.id }
|
|
5120
|
+
}
|
|
5121
|
+
}
|
|
3601
5122
|
const patch = {}
|
|
3602
5123
|
if (result !== '') patch.result = result
|
|
3603
5124
|
// doing → done;已是 done(组长先审完 / 同一 worker 再次结束)就只刷新 result。
|
|
@@ -3653,13 +5174,12 @@ export function registerLeadAutoHooks(ctx, rt) {
|
|
|
3653
5174
|
(exec, result) => {
|
|
3654
5175
|
try {
|
|
3655
5176
|
if (!exec || exec.name !== 'subagent') return
|
|
3656
|
-
// §1.8
|
|
3657
|
-
// exec.name === 'subagent' + 非错误结果 + value 是 {kind:'activation'
|
|
5177
|
+
// §1.8 命中条件(缺一不可,避免别的工具输出里恰好带 subagentId 就误建任务):
|
|
5178
|
+
// exec.name === 'subagent' + 非错误结果 + value 是 {kind:'activation'}。
|
|
3658
5179
|
const failed = !result || result.isError === true
|
|
3659
5180
|
const value = result && result.value
|
|
3660
5181
|
const activation = !failed && isPlainObject(value) && value.kind === 'activation'
|
|
3661
|
-
|
|
3662
|
-
if (!activation || childId === '') {
|
|
5182
|
+
if (!activation) {
|
|
3663
5183
|
// §1.8(0.2.4,t-70 加固):无法确认 worker 已启动(被其它策略拒绝 / post-execute block /
|
|
3664
5184
|
// 启动失败 / 取消 / 返回形状变化)→ **绝不删卡**,只把闸门预建的卡片降级为可见的待开始
|
|
3665
5185
|
// 记录(status=todo + lastError)。删掉一张 worker 可能正在使用的卡 = 重新制造「有活没卡」。
|
|
@@ -3668,7 +5188,15 @@ export function registerLeadAutoHooks(ctx, rt) {
|
|
|
3668
5188
|
}
|
|
3669
5189
|
const agent = exec.agent
|
|
3670
5190
|
if (!agent) return
|
|
3671
|
-
|
|
5191
|
+
// v0.3.1:当前 dsh 的 `subagent` 成功结果是 `{kind:'activation', name}`,没有 subagentId。
|
|
5192
|
+
// activation 本身就证明 worker 已启动:先按 name 占位 / 保持 doing,再从子 Agent 目录回填
|
|
5193
|
+
// workerSessionId。只有「不是 activation」才走上面的降级分支。
|
|
5194
|
+
const childId = typeof value.subagentId === 'string' ? value.subagentId.trim() : ''
|
|
5195
|
+
const workerName = asString(value.name).trim()
|
|
5196
|
+
const dispatched = handleSubagentDispatch(rt, { agent, childId, workerName, args: exec.arguments, exec })
|
|
5197
|
+
if (childId === '' && workerName !== '' && dispatched && dispatched.taskId) {
|
|
5198
|
+
backfillWorkerSessionId(rt, { agent, taskId: dispatched.taskId, workerName })
|
|
5199
|
+
}
|
|
3672
5200
|
} catch (error) {
|
|
3673
5201
|
recordLeadAutoError(rt, '组长直聊派活挂钩失败:' + describeError(error))
|
|
3674
5202
|
}
|
|
@@ -3678,9 +5206,11 @@ export function registerLeadAutoHooks(ctx, rt) {
|
|
|
3678
5206
|
ctx.on(
|
|
3679
5207
|
'subagent/end',
|
|
3680
5208
|
(info) => {
|
|
3681
|
-
|
|
3682
|
-
|
|
3683
|
-
|
|
5209
|
+
// v0.3.5:同步执行 handleSubagentEnd 前半段(findTaskByWorker 命中时无 await,状态 done 与写盘
|
|
5210
|
+
// 在 subagent/end 发射栈内同步完成),防止父会话被唤醒后立即调 taskboard_list 读到旧 doing 状态。
|
|
5211
|
+
Promise.resolve(handleSubagentEnd(rt, info)).catch((error) =>
|
|
5212
|
+
recordLeadAutoError(rt, 'worker 完成挂钩失败:' + describeError(error)),
|
|
5213
|
+
)
|
|
3684
5214
|
},
|
|
3685
5215
|
{ global: true },
|
|
3686
5216
|
)
|
|
@@ -3690,6 +5220,91 @@ export function registerLeadAutoHooks(ctx, rt) {
|
|
|
3690
5220
|
return true
|
|
3691
5221
|
}
|
|
3692
5222
|
|
|
5223
|
+
/**
|
|
5224
|
+
* v0.5.0:判断本次 `subagent` 派发是否必须留在主工作区执行(跳过 Git Worktree 隔离):
|
|
5225
|
+
* - 任务自身或所属父任务处于 `assignee === 'merging'`(合并与全量验证阶段);
|
|
5226
|
+
* - `description` / `prompt` 明确声明为合并验证、解冲突、只读审查或以 `[主工作区]` 开头。
|
|
5227
|
+
*/
|
|
5228
|
+
export function shouldSkipWorktreeForDispatch(state, task, args) {
|
|
5229
|
+
if (!task || task.status === 'archived') return true
|
|
5230
|
+
if (asString(task.assignee).trim() === 'merging') return true
|
|
5231
|
+
const parentId = asString(task.parentTaskId).trim()
|
|
5232
|
+
if (parentId !== '' && state) {
|
|
5233
|
+
const parent = taskById(state, parentId)
|
|
5234
|
+
if (parent && asString(parent.assignee).trim() === 'merging') return true
|
|
5235
|
+
}
|
|
5236
|
+
const desc = isPlainObject(args) ? asString(args.description) : ''
|
|
5237
|
+
const prompt = subagentPromptText(args)
|
|
5238
|
+
if (/合并与全量验证|合并验证|冲突合并|解冲突|全量验证|^\[主工作区\]/i.test(desc)) return true
|
|
5239
|
+
if (/^\[主工作区\]|你是只读审查员/m.test(prompt)) return true
|
|
5240
|
+
return false
|
|
5241
|
+
}
|
|
5242
|
+
|
|
5243
|
+
/**
|
|
5244
|
+
* v0.5.0:在 `tools/pre-execute` 闸门准备卡片后,按需为该任务挂载隔离 Git Worktree,
|
|
5245
|
+
* 并透明重写 `exec.arguments.cwd` 与注入 `[隔离工作树已启用]` 前缀提示。
|
|
5246
|
+
*/
|
|
5247
|
+
export function attachDispatchWorktree(rt, agent, taskId, exec) {
|
|
5248
|
+
try {
|
|
5249
|
+
if (!rt || !rt.state || !taskId) return { isolated: false, reason: 'no-task' }
|
|
5250
|
+
const cfg = normalizeConfig(rt.state.config)
|
|
5251
|
+
if (cfg.worktreeIsolation === false) return { isolated: false, reason: 'disabled' }
|
|
5252
|
+
const task = taskById(rt.state, taskId)
|
|
5253
|
+
if (!task) return { isolated: false, reason: 'no-task' }
|
|
5254
|
+
const args = exec && isPlainObject(exec.arguments) ? exec.arguments : {}
|
|
5255
|
+
if (shouldSkipWorktreeForDispatch(rt.state, task, args)) {
|
|
5256
|
+
return { isolated: false, reason: 'main-workspace-role' }
|
|
5257
|
+
}
|
|
5258
|
+
const baseCwd = asString(task.cwd).trim() || leadDispatchCwd(rt, agent, args)
|
|
5259
|
+
if (baseCwd === '') return { isolated: false, reason: 'no-cwd' }
|
|
5260
|
+
if (!task.cwd) task.cwd = baseCwd
|
|
5261
|
+
|
|
5262
|
+
const argCwd = asString(args.cwd).trim()
|
|
5263
|
+
if (
|
|
5264
|
+
argCwd !== '' &&
|
|
5265
|
+
normalizePathForCompare(argCwd) !== normalizePathForCompare(baseCwd) &&
|
|
5266
|
+
normalizePathForCompare(argCwd) !== normalizePathForCompare(asString(task.worktreePath))
|
|
5267
|
+
) {
|
|
5268
|
+
return { isolated: false, reason: 'explicit-custom-cwd' }
|
|
5269
|
+
}
|
|
5270
|
+
|
|
5271
|
+
const repoInfo = resolveGitRepoInfo(baseCwd, { fresh: true })
|
|
5272
|
+
if (!repoInfo) return { isolated: false, reason: 'not-git-repo' }
|
|
5273
|
+
|
|
5274
|
+
const wt = ensureTaskWorktree(rt, task, repoInfo)
|
|
5275
|
+
if (!wt || !wt.worktreePath) return { isolated: false, reason: 'unavailable' }
|
|
5276
|
+
|
|
5277
|
+
if (exec && typeof exec === 'object') {
|
|
5278
|
+
let nextArgs = isPlainObject(exec.arguments) ? exec.arguments : {}
|
|
5279
|
+
if (Object.isFrozen(nextArgs)) nextArgs = { ...nextArgs }
|
|
5280
|
+
nextArgs.cwd = wt.worktreePath
|
|
5281
|
+
const notice =
|
|
5282
|
+
'[隔离工作树已启用] 当前子任务在独立 Git Worktree 中执行:' +
|
|
5283
|
+
wt.worktreePath +
|
|
5284
|
+
'(分支:' +
|
|
5285
|
+
wt.branch +
|
|
5286
|
+
',主工作区:' +
|
|
5287
|
+
repoInfo.repoRoot +
|
|
5288
|
+
')。主仓依赖(node_modules / .venv)已通过软链共享,可直接在当前目录读写文件与运行单测;请勿删除软链依赖目录,也请勿跨目录修改主工作区文件。'
|
|
5289
|
+
if (typeof nextArgs.prompt === 'string') {
|
|
5290
|
+
if (!nextArgs.prompt.includes('[隔离工作树已启用]')) {
|
|
5291
|
+
nextArgs.prompt = notice + '\n\n' + nextArgs.prompt
|
|
5292
|
+
}
|
|
5293
|
+
} else if (Array.isArray(nextArgs.prompt)) {
|
|
5294
|
+
if (!subagentPromptText(nextArgs).includes('[隔离工作树已启用]')) {
|
|
5295
|
+
nextArgs.prompt = [{ type: 'text', text: notice }, ...nextArgs.prompt]
|
|
5296
|
+
}
|
|
5297
|
+
}
|
|
5298
|
+
exec.arguments = nextArgs
|
|
5299
|
+
}
|
|
5300
|
+
|
|
5301
|
+
return { isolated: true, worktreePath: wt.worktreePath, branch: wt.branch, reused: wt.reused }
|
|
5302
|
+
} catch (error) {
|
|
5303
|
+
console.warn('[taskboard] 创建 Git Worktree 失败,退回主工作区执行:' + describeError(error))
|
|
5304
|
+
return { isolated: false, reason: 'error', error: describeError(error) }
|
|
5305
|
+
}
|
|
5306
|
+
}
|
|
5307
|
+
|
|
3693
5308
|
/**
|
|
3694
5309
|
* 注册 §1.8(0.2.4)的**派发前强制建卡闸门**(`tools/pre-execute`)。
|
|
3695
5310
|
*
|
|
@@ -3724,6 +5339,11 @@ export function registerLeadDispatchGate(ctx, rt) {
|
|
|
3724
5339
|
info: { name: 'TaskboardDispatchError', code: outcome.reason === 'write-failed' ? 'internal' : 'bad-request' },
|
|
3725
5340
|
}
|
|
3726
5341
|
}
|
|
5342
|
+
// v0.3.2:卡片已准备好、worker 即将启动——这是「派发者出现」的时刻。
|
|
5343
|
+
// 工作区没有组长 / 组长已归档 → 把当前派单会话登记为组长,避免轮询再新建一个组长窗口。
|
|
5344
|
+
adoptWorkspaceLead(rt, agent, exec.arguments, { taskId: outcome.taskId })
|
|
5345
|
+
// v0.5.0:按需挂载独立 Git Worktree,自动重写 worker 的 cwd 与隔离说明(注意在 adoptWorkspaceLead 之后执行,不覆盖组长主工作区路径)。
|
|
5346
|
+
attachDispatchWorktree(rt, agent, outcome.taskId, exec)
|
|
3727
5347
|
return next()
|
|
3728
5348
|
} catch (error) {
|
|
3729
5349
|
const message =
|
|
@@ -3846,6 +5466,8 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
|
|
|
3846
5466
|
id: { type: 'string' },
|
|
3847
5467
|
title: { type: 'string' },
|
|
3848
5468
|
status: { type: 'string', enum: [...STATUSES] },
|
|
5469
|
+
parentTaskId: { type: 'string' },
|
|
5470
|
+
dependsOn: { type: 'array', items: { type: 'string' } },
|
|
3849
5471
|
note: { type: 'string' },
|
|
3850
5472
|
assignee: { type: 'string' },
|
|
3851
5473
|
result: { type: 'string' },
|
|
@@ -3853,6 +5475,8 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
|
|
|
3853
5475
|
needsUser: { type: 'boolean' },
|
|
3854
5476
|
question: { type: 'string' },
|
|
3855
5477
|
questionOptions: { type: 'array', items: { type: 'string' } },
|
|
5478
|
+
worktreePath: { type: 'string' },
|
|
5479
|
+
worktreeBranch: { type: 'string' },
|
|
3856
5480
|
},
|
|
3857
5481
|
},
|
|
3858
5482
|
},
|
|
@@ -3860,7 +5484,7 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
|
|
|
3860
5484
|
}
|
|
3861
5485
|
|
|
3862
5486
|
/**
|
|
3863
|
-
*
|
|
5487
|
+
* 面向模型的任务摘要(taskboard_list 的 tasks[] / taskboard_add / taskboard_update 的 task)。
|
|
3864
5488
|
*
|
|
3865
5489
|
* 这里的键必须全部在 output.schema 里声明:dsh tools 管线在 execute() 成功返回之后才校验 canonical
|
|
3866
5490
|
* output,而两个 output.schema 都是 additionalProperties:false 的封闭契约——多带一个未声明字段就会抛
|
|
@@ -3874,6 +5498,8 @@ export function taskBrief(task) {
|
|
|
3874
5498
|
id: task.id,
|
|
3875
5499
|
title: task.title,
|
|
3876
5500
|
status: task.status,
|
|
5501
|
+
parentTaskId: task.parentTaskId || '',
|
|
5502
|
+
dependsOn: Array.isArray(task.dependsOn) ? task.dependsOn.slice() : [],
|
|
3877
5503
|
note: task.note || '',
|
|
3878
5504
|
assignee: task.assignee || '',
|
|
3879
5505
|
result: task.result || '',
|
|
@@ -3882,6 +5508,9 @@ export function taskBrief(task) {
|
|
|
3882
5508
|
needsUser: task.needsUser === true,
|
|
3883
5509
|
question: task.question || '',
|
|
3884
5510
|
questionOptions: Array.isArray(task.questionOptions) ? task.questionOptions.slice() : [],
|
|
5511
|
+
// v0.5.0:隔离工作树路径与分支,供组长判断是否需调 taskboard_merge_worktree 合入主工作区。
|
|
5512
|
+
worktreePath: task.worktreePath || '',
|
|
5513
|
+
worktreeBranch: task.worktreeBranch || '',
|
|
3885
5514
|
}
|
|
3886
5515
|
}
|
|
3887
5516
|
|
|
@@ -3889,9 +5518,15 @@ function renderTaskList(value) {
|
|
|
3889
5518
|
if (value.count === 0) return [{ type: 'text', text: '看板没有匹配的任务。' }]
|
|
3890
5519
|
const lines = ['看板任务(' + value.count + ' 条):']
|
|
3891
5520
|
for (const task of value.tasks) {
|
|
3892
|
-
const bits = ['[' + task.status + ']', task.id
|
|
5521
|
+
const bits = ['[' + task.status + ']', task.id]
|
|
5522
|
+
if (task.parentTaskId) bits.push('(父:' + task.parentTaskId + ')')
|
|
5523
|
+
if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
|
|
5524
|
+
bits.push('(依赖:' + task.dependsOn.join(',') + ')')
|
|
5525
|
+
}
|
|
5526
|
+
bits.push(task.title)
|
|
3893
5527
|
if (task.assignee) bits.push('@' + task.assignee)
|
|
3894
5528
|
lines.push('- ' + bits.join(' '))
|
|
5529
|
+
if (task.worktreePath) lines.push(' 隔离工作树:' + task.worktreePath + (task.worktreeBranch ? ' (' + task.worktreeBranch + ')' : ''))
|
|
3895
5530
|
if (task.note) lines.push(' 备注:' + task.note)
|
|
3896
5531
|
if (task.result) lines.push(' 结论:' + task.result)
|
|
3897
5532
|
if (task.needsUser) lines.push(' 待用户回答:' + task.question)
|
|
@@ -3900,7 +5535,18 @@ function renderTaskList(value) {
|
|
|
3900
5535
|
}
|
|
3901
5536
|
|
|
3902
5537
|
function renderTaskOne(prefix, task) {
|
|
3903
|
-
const
|
|
5538
|
+
const head =
|
|
5539
|
+
prefix +
|
|
5540
|
+
task.id +
|
|
5541
|
+
' [' +
|
|
5542
|
+
task.status +
|
|
5543
|
+
']' +
|
|
5544
|
+
(task.parentTaskId ? ' (父:' + task.parentTaskId + ')' : '') +
|
|
5545
|
+
(Array.isArray(task.dependsOn) && task.dependsOn.length > 0 ? ' (依赖:' + task.dependsOn.join(',') + ')' : '') +
|
|
5546
|
+
' ' +
|
|
5547
|
+
task.title
|
|
5548
|
+
const lines = [head]
|
|
5549
|
+
if (task.worktreePath) lines.push('隔离工作树:' + task.worktreePath + (task.worktreeBranch ? ' (' + task.worktreeBranch + ')' : ''))
|
|
3904
5550
|
if (task.note) lines.push('备注:' + task.note)
|
|
3905
5551
|
if (task.result) lines.push('结论:' + task.result)
|
|
3906
5552
|
if (task.needsUser) lines.push('待用户回答:' + task.question)
|
|
@@ -3924,6 +5570,8 @@ export const TASK_ONE_OUTPUT_SCHEMA = {
|
|
|
3924
5570
|
id: { type: 'string' },
|
|
3925
5571
|
title: { type: 'string' },
|
|
3926
5572
|
status: { type: 'string', enum: [...STATUSES] },
|
|
5573
|
+
parentTaskId: { type: 'string' },
|
|
5574
|
+
dependsOn: { type: 'array', items: { type: 'string' } },
|
|
3927
5575
|
note: { type: 'string' },
|
|
3928
5576
|
assignee: { type: 'string' },
|
|
3929
5577
|
result: { type: 'string' },
|
|
@@ -3931,11 +5579,30 @@ export const TASK_ONE_OUTPUT_SCHEMA = {
|
|
|
3931
5579
|
needsUser: { type: 'boolean' },
|
|
3932
5580
|
question: { type: 'string' },
|
|
3933
5581
|
questionOptions: { type: 'array', items: { type: 'string' } },
|
|
5582
|
+
worktreePath: { type: 'string' },
|
|
5583
|
+
worktreeBranch: { type: 'string' },
|
|
3934
5584
|
},
|
|
3935
5585
|
},
|
|
3936
5586
|
},
|
|
3937
5587
|
}
|
|
3938
5588
|
|
|
5589
|
+
export const TASK_MERGE_WORKTREE_OUTPUT_SCHEMA = {
|
|
5590
|
+
type: 'object',
|
|
5591
|
+
additionalProperties: false,
|
|
5592
|
+
required: ['id', 'merged', 'noChanges', 'conflict', 'cleaned', 'branch', 'worktreePath', 'conflictFiles', 'summary'],
|
|
5593
|
+
properties: {
|
|
5594
|
+
id: { type: 'string' },
|
|
5595
|
+
merged: { type: 'boolean' },
|
|
5596
|
+
noChanges: { type: 'boolean' },
|
|
5597
|
+
conflict: { type: 'boolean' },
|
|
5598
|
+
cleaned: { type: 'boolean' },
|
|
5599
|
+
branch: { type: 'string' },
|
|
5600
|
+
worktreePath: { type: 'string' },
|
|
5601
|
+
conflictFiles: { type: 'array', items: { type: 'string' } },
|
|
5602
|
+
summary: { type: 'string' },
|
|
5603
|
+
},
|
|
5604
|
+
}
|
|
5605
|
+
|
|
3939
5606
|
/**
|
|
3940
5607
|
* 注册三个模型工具。宿主级注册 = 全局可见(所有预设的 Agent 都能用),
|
|
3941
5608
|
* 这也是「非派单模式也能往看板里塞任务」的实现方式。
|
|
@@ -3950,7 +5617,7 @@ export function registerTools(toolCtx, rt) {
|
|
|
3950
5617
|
name: 'taskboard_list',
|
|
3951
5618
|
description:
|
|
3952
5619
|
'列出任务看板上的任务(默认全部状态:todo=待开始 / doing=进行中 / done=已完成 / archived=已归档)。' +
|
|
3953
|
-
'
|
|
5620
|
+
'派单前用它确认要处理哪条任务;并行拆片(fan-out)时传 parentTaskId 只看该父任务名下的全部子卡进度;审核后用 taskboard_update 更新状态。',
|
|
3954
5621
|
parameters: {
|
|
3955
5622
|
type: 'object',
|
|
3956
5623
|
additionalProperties: false,
|
|
@@ -3960,6 +5627,10 @@ export function registerTools(toolCtx, rt) {
|
|
|
3960
5627
|
enum: [...STATUSES],
|
|
3961
5628
|
description: '只看某一列;省略则返回全部状态。',
|
|
3962
5629
|
},
|
|
5630
|
+
parentTaskId: {
|
|
5631
|
+
type: 'string',
|
|
5632
|
+
description: '可选:只看某条父任务(如 t-10)名下的切片 / 合并 / 验证子卡;省略不过滤。',
|
|
5633
|
+
},
|
|
3963
5634
|
},
|
|
3964
5635
|
},
|
|
3965
5636
|
output: {
|
|
@@ -3967,10 +5638,16 @@ export function registerTools(toolCtx, rt) {
|
|
|
3967
5638
|
render: (_args, value) => renderTaskList(value),
|
|
3968
5639
|
},
|
|
3969
5640
|
execute(args) {
|
|
5641
|
+
reloadBoardIfStale(rt)
|
|
3970
5642
|
const want = args && args.status !== undefined ? args.status : ''
|
|
3971
5643
|
if (want !== '' && !STATUSES.includes(want)) throw new Error('非法状态:' + String(want))
|
|
5644
|
+
const wantParentRaw = args && typeof args.parentTaskId === 'string' ? args.parentTaskId.trim().toLowerCase() : ''
|
|
5645
|
+
if (wantParentRaw !== '' && !/^t-[0-9]{1,6}$/.test(wantParentRaw)) {
|
|
5646
|
+
throw new Error('非法 parentTaskId:' + String(args.parentTaskId))
|
|
5647
|
+
}
|
|
3972
5648
|
const tasks = rt.state.tasks
|
|
3973
5649
|
.filter((task) => (want === '' ? true : task.status === want))
|
|
5650
|
+
.filter((task) => (wantParentRaw === '' ? true : asString(task.parentTaskId).toLowerCase() === wantParentRaw))
|
|
3974
5651
|
.map(taskBrief)
|
|
3975
5652
|
return Promise.resolve({ count: tasks.length, tasks })
|
|
3976
5653
|
},
|
|
@@ -3980,7 +5657,8 @@ export function registerTools(toolCtx, rt) {
|
|
|
3980
5657
|
description:
|
|
3981
5658
|
'往任务看板添加一条待开始任务。用户口述的需求、你自己拆出来的后续任务都可以加进看板,' +
|
|
3982
5659
|
'轮询器会把它派给任务所属工作区的常驻组长。title 必填,note 写验收标准或补充信息;' +
|
|
3983
|
-
'workspace 可选(工作区 id / 名称 /
|
|
5660
|
+
'workspace 可选(工作区 id / 名称 / 绝对路径),用于从主会话往其它工作区派任务;' +
|
|
5661
|
+
'parentTaskId 可选(关联所属父任务 id,如 t-10)。',
|
|
3984
5662
|
parameters: {
|
|
3985
5663
|
type: 'object',
|
|
3986
5664
|
additionalProperties: false,
|
|
@@ -3992,6 +5670,15 @@ export function registerTools(toolCtx, rt) {
|
|
|
3992
5670
|
type: 'string',
|
|
3993
5671
|
description: '可选:任务所属工作区(工作区 id / 名称 / 绝对路径),省略则用当前会话工作区',
|
|
3994
5672
|
},
|
|
5673
|
+
parentTaskId: {
|
|
5674
|
+
type: 'string',
|
|
5675
|
+
description: '可选:关联所属父任务 id(例如 t-10)',
|
|
5676
|
+
},
|
|
5677
|
+
dependsOn: {
|
|
5678
|
+
type: 'array',
|
|
5679
|
+
items: { type: 'string' },
|
|
5680
|
+
description: '可选:前置依赖任务 id 列表(如 ["t-1", "t-2"]);前置任务全部完成前本任务不会自动派发',
|
|
5681
|
+
},
|
|
3995
5682
|
},
|
|
3996
5683
|
},
|
|
3997
5684
|
output: {
|
|
@@ -3999,9 +5686,14 @@ export function registerTools(toolCtx, rt) {
|
|
|
3999
5686
|
render: (_args, value) => renderTaskOne('已添加任务 ', value.task),
|
|
4000
5687
|
},
|
|
4001
5688
|
execute(args, exec) {
|
|
5689
|
+
reloadBoardIfStale(rt)
|
|
4002
5690
|
const title = trimmed(args && args.title, MAX_TITLE_CHARS)
|
|
4003
5691
|
if (title === '') throw new Error('title 不能为空')
|
|
4004
5692
|
if (typeof (args && args.note) === 'string') assertNoteAttachments(args.note)
|
|
5693
|
+
const rawParent = args && typeof args.parentTaskId === 'string' ? args.parentTaskId.trim() : ''
|
|
5694
|
+
if (rawParent !== '' && !normalizeParentTaskId(rawParent)) {
|
|
5695
|
+
throw new Error('非法 parentTaskId:' + rawParent)
|
|
5696
|
+
}
|
|
4005
5697
|
let sessionId = null
|
|
4006
5698
|
let cwd = null
|
|
4007
5699
|
try {
|
|
@@ -4021,7 +5713,15 @@ export function registerTools(toolCtx, rt) {
|
|
|
4021
5713
|
if (resolved === '') throw new Error('未知工作区:' + workspaceArg)
|
|
4022
5714
|
cwd = resolved
|
|
4023
5715
|
}
|
|
4024
|
-
const task = addTask(rt.state, {
|
|
5716
|
+
const task = addTask(rt.state, {
|
|
5717
|
+
title,
|
|
5718
|
+
note: args && args.note,
|
|
5719
|
+
source: 'agent',
|
|
5720
|
+
sessionId,
|
|
5721
|
+
cwd,
|
|
5722
|
+
parentTaskId: rawParent || null,
|
|
5723
|
+
dependsOn: args && args.dependsOn,
|
|
5724
|
+
})
|
|
4025
5725
|
commitBoard(rt.state, rt.filePath)
|
|
4026
5726
|
return Promise.resolve({ task: taskBrief(task) })
|
|
4027
5727
|
},
|
|
@@ -4030,7 +5730,8 @@ export function registerTools(toolCtx, rt) {
|
|
|
4030
5730
|
name: 'taskboard_update',
|
|
4031
5731
|
description:
|
|
4032
5732
|
'更新看板任务:置为 doing(已派发)、done(审核通过)、todo(打回重做)、archived(归档);' +
|
|
4033
|
-
'也可以用 result
|
|
5733
|
+
'也可以用 result 写审核结论、lastError 写故障或阻塞原因(传空串清空,提问不要写进 lastError)。' +
|
|
5734
|
+
'assignee 只写子 Agent 的 label / 名字(自由文本),**不要写会话 id**——' +
|
|
4034
5735
|
'执行会话 id 由宿主记在 workerSessionId,模型写不进去。状态迁移非法时会返回错误。' +
|
|
4035
5736
|
'需要用户决策时用 needsUser:true + question(可选 questionOptions 选项)在任务上提问,' +
|
|
4036
5737
|
'看板会把它放进「待你处理」并通知用户回答;needsUser:false 取消提问(问题字段清空,回答留档)。' +
|
|
@@ -4045,6 +5746,10 @@ export function registerTools(toolCtx, rt) {
|
|
|
4045
5746
|
result: { type: 'string', description: '审核结论 / 子 Agent 汇报摘要' },
|
|
4046
5747
|
assignee: { type: 'string', description: '子 Agent 的 label / 名字(自由文本;不要写会话 id)' },
|
|
4047
5748
|
note: { type: 'string', description: '备注(覆盖原备注)' },
|
|
5749
|
+
lastError: {
|
|
5750
|
+
type: 'string',
|
|
5751
|
+
description: '故障或阻塞原因(派发失败 / 缺少工作目录 / worker 异常;传空串可清空,不要写向用户的提问)',
|
|
5752
|
+
},
|
|
4048
5753
|
needsUser: {
|
|
4049
5754
|
type: 'boolean',
|
|
4050
5755
|
description: '是否在等用户回复:true 时必须同时给 question;false 取消提问',
|
|
@@ -4055,6 +5760,11 @@ export function registerTools(toolCtx, rt) {
|
|
|
4055
5760
|
items: { type: 'string' },
|
|
4056
5761
|
description: '可选答案(最多 4 个,每个 ≤80 字;用户可以在看板上点选)',
|
|
4057
5762
|
},
|
|
5763
|
+
dependsOn: {
|
|
5764
|
+
type: 'array',
|
|
5765
|
+
items: { type: 'string' },
|
|
5766
|
+
description: '可选:覆盖设置前置依赖任务 id 列表(传空数组 [] 清空前置依赖)',
|
|
5767
|
+
},
|
|
4058
5768
|
},
|
|
4059
5769
|
},
|
|
4060
5770
|
output: {
|
|
@@ -4063,11 +5773,22 @@ export function registerTools(toolCtx, rt) {
|
|
|
4063
5773
|
},
|
|
4064
5774
|
async execute(args, exec) {
|
|
4065
5775
|
if (!args || !args.id) throw new Error('缺少任务 id')
|
|
5776
|
+
reloadBoardIfStale(rt)
|
|
4066
5777
|
const patch = {}
|
|
4067
5778
|
// v0.2.9(§2):`workerSessionId` / `workerRunState` 是宿主独占字段,**不在白名单里**——
|
|
4068
5779
|
// 模型即使传了也进不了 patch(`parameters.additionalProperties:false` 还会在入参校验阶段拒绝),
|
|
4069
5780
|
// `applyTaskUpdate` 也不读这两个键,所以任务字段绝不会被模型改写。
|
|
4070
|
-
for (const key of [
|
|
5781
|
+
for (const key of [
|
|
5782
|
+
'status',
|
|
5783
|
+
'result',
|
|
5784
|
+
'assignee',
|
|
5785
|
+
'note',
|
|
5786
|
+
'lastError',
|
|
5787
|
+
'needsUser',
|
|
5788
|
+
'question',
|
|
5789
|
+
'questionOptions',
|
|
5790
|
+
'dependsOn',
|
|
5791
|
+
]) {
|
|
4071
5792
|
if (args[key] !== undefined) patch[key] = args[key]
|
|
4072
5793
|
}
|
|
4073
5794
|
// §1.9:提问的会话 id(askedBy)由宿主补,模型不能伪造别的会话。
|
|
@@ -4097,7 +5818,43 @@ export function registerTools(toolCtx, rt) {
|
|
|
4097
5818
|
return { task: taskBrief(task) }
|
|
4098
5819
|
},
|
|
4099
5820
|
})
|
|
4100
|
-
|
|
5821
|
+
tools.register({
|
|
5822
|
+
name: 'taskboard_merge_worktree',
|
|
5823
|
+
description:
|
|
5824
|
+
'将看板任务(或并行切片子卡)关联的隔离 Git Worktree 改动原子预检并合入主工作区,成功后自动回收临时 Worktree 目录与分支。' +
|
|
5825
|
+
'当 taskboard_list 中卡片 worktreePath 非空时,组长在审核通过置 done 前(或波次合并阶段)必须调用本工具合入主工作区;' +
|
|
5826
|
+
'若返回 conflict:true(主工作区不会被污染),请派合并 worker 手动解冲突后再传 discardOnly:true 清理临时工作树。',
|
|
5827
|
+
parameters: {
|
|
5828
|
+
type: 'object',
|
|
5829
|
+
additionalProperties: false,
|
|
5830
|
+
required: ['id'],
|
|
5831
|
+
properties: {
|
|
5832
|
+
id: { type: 'string', description: '任务或子卡 id,例如 t-12' },
|
|
5833
|
+
cleanup: {
|
|
5834
|
+
type: 'boolean',
|
|
5835
|
+
description: '可选:合入成功后是否立即删除临时 Worktree 与分支(默认 true)',
|
|
5836
|
+
},
|
|
5837
|
+
discardOnly: {
|
|
5838
|
+
type: 'boolean',
|
|
5839
|
+
description: '可选:设为 true 时不合入改动,直接卸载依赖软链并回收该任务的临时 Worktree 与分支(用于手动解冲突后清理或废弃切片)',
|
|
5840
|
+
},
|
|
5841
|
+
},
|
|
5842
|
+
},
|
|
5843
|
+
output: {
|
|
5844
|
+
schema: TASK_MERGE_WORKTREE_OUTPUT_SCHEMA,
|
|
5845
|
+
render: (_args, value) => [{ type: 'text', text: value.summary }],
|
|
5846
|
+
},
|
|
5847
|
+
execute(args) {
|
|
5848
|
+
if (!args || !args.id) throw new Error('缺少任务 id')
|
|
5849
|
+
reloadBoardIfStale(rt)
|
|
5850
|
+
const outcome = mergeAndCleanupTaskWorktree(rt, args.id, {
|
|
5851
|
+
cleanup: args.cleanup !== false,
|
|
5852
|
+
discardOnly: args.discardOnly === true,
|
|
5853
|
+
})
|
|
5854
|
+
return Promise.resolve(outcome)
|
|
5855
|
+
},
|
|
5856
|
+
})
|
|
5857
|
+
console.log('[taskboard] 模型工具已注册:taskboard_list / taskboard_add / taskboard_update / taskboard_merge_worktree')
|
|
4101
5858
|
}
|
|
4102
5859
|
|
|
4103
5860
|
/* ------------------------------------------------------------------ *
|
|
@@ -4148,6 +5905,10 @@ export function apply(ctx) {
|
|
|
4148
5905
|
// 启动时清一次过期归档(§1.2):宿主停机期间到期的归档不必等第一个 tick。
|
|
4149
5906
|
// 只在真的有删除时写盘(pruneArchivedBoard 内部判断),因此没有副作用地复用同一路径。
|
|
4150
5907
|
pruneArchivedBoard(runtime, Date.now())
|
|
5908
|
+
// v0.4.0:启动时自愈上次进程退出遗留的 doing + running 失联任务(顶层回退 todo,切片标 failed)。
|
|
5909
|
+
reconcileOrphanedDoingTasks(runtime, { startup: true, now: Date.now() }).catch((error) =>
|
|
5910
|
+
console.warn('[taskboard] 启动期失联任务自愈失败:' + describeError(error)),
|
|
5911
|
+
)
|
|
4151
5912
|
|
|
4152
5913
|
// 模式状态:agentPresets 服务就绪后读名单(预设本身由 bundle patch 声明,不在这里安装)。
|
|
4153
5914
|
// 预设行的激活是异步的,所以前几次读不到不算失败——最多重试 3 次再告警。
|