dsh-dispatch-board 0.3.3 → 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/lib/client.js +640 -155
- package/lib/index.js +1659 -96
- package/package.json +1 -1
- package/presets/taskboard.patch.yml +104 -56
package/lib/index.js
CHANGED
|
@@ -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
|
|
@@ -1294,6 +2135,19 @@ export function requeueTasksOfLead(state, sessionId, now = Date.now(), exceptTas
|
|
|
1294
2135
|
if (!task || task.status !== 'doing' || task.dispatchedSessionId !== sessionId) continue
|
|
1295
2136
|
// v0.3.2:接管新组长时,正在派发的这张卡不属于「旧组长的遗留任务」,不要打回 todo。
|
|
1296
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)
|
|
1297
2151
|
task.status = 'todo'
|
|
1298
2152
|
task.startedAt = null
|
|
1299
2153
|
task.finishedAt = null
|
|
@@ -1429,6 +2283,9 @@ export function buildDispatchText(task, now = Date.now()) {
|
|
|
1429
2283
|
const lines = ['【任务看板 · 待开始】' + task.id + ' ' + task.title]
|
|
1430
2284
|
if (task.note) lines.push('备注:' + task.note)
|
|
1431
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
|
+
}
|
|
1432
2289
|
// §1.9:todo 任务提问 → 用户回答 → 清标记后再派发时,组长可能在别的会话里,
|
|
1433
2290
|
// 回答必须随派发文本带过去,不然「用户已经拍板」这件事会丢。
|
|
1434
2291
|
if (typeof task.lastAnswer === 'string' && task.lastAnswer.trim() !== '') {
|
|
@@ -1436,14 +2293,21 @@ export function buildDispatchText(task, now = Date.now()) {
|
|
|
1436
2293
|
}
|
|
1437
2294
|
lines.push('')
|
|
1438
2295
|
lines.push(
|
|
1439
|
-
'请按派单规则处理这条看板任务:先用 taskboard_update 把它置为 doing
|
|
1440
|
-
'
|
|
1441
|
-
'
|
|
1442
|
-
'
|
|
1443
|
-
'
|
|
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;' +
|
|
1444
2308
|
'不通过就 send_message 打回同一个子 Agent 重做,任务保持 doing。' +
|
|
1445
|
-
'写 result
|
|
1446
|
-
'
|
|
2309
|
+
'写 result 与对话回复必须简短说人话:result 第 1 行直接写一句话人话结论(做成了什么、验证结果如何),下面最多列 3~5 条精炼要点;' +
|
|
2310
|
+
'非必要不画表格,严禁写「我已做的取证」等自证流水账或暴露 W1/W2/assignee=merging 等内部调度黑话;中间派单或波次过渡轮次的对话回复不超过 2 句话。',
|
|
1447
2311
|
)
|
|
1448
2312
|
if (task.notificationCount > 0) {
|
|
1449
2313
|
lines.push('(这是第 ' + (task.notificationCount + 1) + ' 次提醒;任务仍未派发。)')
|
|
@@ -1850,7 +2714,7 @@ export function buildReceiptText(tasks, now = Date.now()) {
|
|
|
1850
2714
|
lines.push('- ' + task.id + ' ' + task.title + ':' + (summary === '' ? '(无结论)' : summary))
|
|
1851
2715
|
}
|
|
1852
2716
|
lines.push('')
|
|
1853
|
-
lines.push('
|
|
2717
|
+
lines.push('请用简洁自然的人话向用户汇总以上结论,不要重复执行任务。')
|
|
1854
2718
|
lines.push('看板时间:' + localStamp(now))
|
|
1855
2719
|
return lines.join('\n')
|
|
1856
2720
|
}
|
|
@@ -1864,6 +2728,9 @@ export function selectReceiptTasks(state, limit = MAX_RECEIPT_BATCH) {
|
|
|
1864
2728
|
const cap = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.round(Number(limit)) : MAX_RECEIPT_BATCH
|
|
1865
2729
|
return state.tasks
|
|
1866
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) !== ''))
|
|
1867
2734
|
.sort((a, b) => {
|
|
1868
2735
|
const at = Date.parse(a.updatedAt)
|
|
1869
2736
|
const bt = Date.parse(b.updatedAt)
|
|
@@ -2022,6 +2889,12 @@ async function dispatchRpc(rt, method, payload) {
|
|
|
2022
2889
|
const next = normalizeConfig({ ...normalizeConfig(rt.state.config), ...payload })
|
|
2023
2890
|
const intervalChanged = next.pollIntervalMs !== normalizeConfig(rt.state.config).pollIntervalMs
|
|
2024
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
|
+
}
|
|
2025
2898
|
commitBoard(rt.state, rt.filePath)
|
|
2026
2899
|
if (intervalChanged) startPolling(rt)
|
|
2027
2900
|
return { config: next }
|
|
@@ -2087,6 +2960,7 @@ const SKIP_TEXT = {
|
|
|
2087
2960
|
'agent-busy': '目标会话正在运行,稍后再派',
|
|
2088
2961
|
// v0.2.0 工作区组长路由(§1.5 跳过原因表;Client 用 poll.skip.<reason> 做 i18n)。
|
|
2089
2962
|
'lead-busy': '工作区组长正在运行,等它空下来再派',
|
|
2963
|
+
'lead-worker-busy': '本工作区已有任务正在执行或待组长验收,完成后再自动派发下一条',
|
|
2090
2964
|
'lead-unavailable': '工作区组长不可用:稍后重试,或在看板点「创建组长」',
|
|
2091
2965
|
'lead-no-workspace': '无法解析任务的工作区:请从目标工作区的会话里重新加这条任务',
|
|
2092
2966
|
'creator-busy': '创建这条任务的对话正在运行,等它空下来再派',
|
|
@@ -2381,6 +3255,161 @@ function pruneArchivedBoard(rt, now = Date.now()) {
|
|
|
2381
3255
|
return outcome.removed
|
|
2382
3256
|
}
|
|
2383
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
|
+
|
|
2384
3413
|
/**
|
|
2385
3414
|
* 轮询派单入口。每次 tick 末尾都会尝试 flush 一次完成回执(§1.6):
|
|
2386
3415
|
* 回执投递不占用派发名额(未绑定主会话 / 主会话忙或离线时是 no-op)。
|
|
@@ -2401,6 +3430,13 @@ async function runTick(rt, options = {}) {
|
|
|
2401
3430
|
rt.poll.lastRunAt = iso(now)
|
|
2402
3431
|
// 归档清理(§1.2)必须在 pollEnabled 判断之前:暂停派发时归档仍要按时删除。
|
|
2403
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
|
+
}
|
|
2404
3440
|
const config = normalizeConfig(rt.state.config)
|
|
2405
3441
|
if (!config.pollEnabled && !options.taskId) {
|
|
2406
3442
|
rt.poll.lastSkipReason = 'poll-disabled'
|
|
@@ -2414,6 +3450,13 @@ async function runTick(rt, options = {}) {
|
|
|
2414
3450
|
if (single.needsUser === true) {
|
|
2415
3451
|
throw new BoardError('conflict', '任务正在等待用户回复(needsUser),回答后才能继续派发')
|
|
2416
3452
|
}
|
|
3453
|
+
const blockingDeps = unresolvedDependencies(rt.state, single)
|
|
3454
|
+
if (blockingDeps.length > 0) {
|
|
3455
|
+
throw new BoardError(
|
|
3456
|
+
'conflict',
|
|
3457
|
+
'前置任务尚未完成(' + blockingDeps.join(', ') + '),请先完成前置任务或移除依赖后再派发',
|
|
3458
|
+
)
|
|
3459
|
+
}
|
|
2417
3460
|
candidates = [single]
|
|
2418
3461
|
} else {
|
|
2419
3462
|
candidates = selectDispatchCandidates(rt.state, now)
|
|
@@ -2485,12 +3528,14 @@ async function runTick(rt, options = {}) {
|
|
|
2485
3528
|
* followup + sessions.flush 成功后置 doing、记通知与 dispatchedSession*、清 lastError。
|
|
2486
3529
|
*/
|
|
2487
3530
|
async function deliverBoardTask(rt, task, agent, now) {
|
|
3531
|
+
const taskId = task.id
|
|
2488
3532
|
const sessionId = agentSessionId(agent)
|
|
2489
3533
|
// 创建时没能解析出工作区(会话还没 live)→ 投递前从目标会话补一次,派发文本就能带上工作目录。
|
|
2490
3534
|
if (!task.cwd) {
|
|
2491
3535
|
const cwd = sessionCwd(agent)
|
|
2492
3536
|
if (cwd) task.cwd = cwd
|
|
2493
3537
|
}
|
|
3538
|
+
const resolvedCwd = task.cwd
|
|
2494
3539
|
const message = createBoardUserMessage(buildDispatchText(task, now))
|
|
2495
3540
|
try {
|
|
2496
3541
|
agent.followup(message)
|
|
@@ -2503,32 +3548,35 @@ async function deliverBoardTask(rt, task, agent, now) {
|
|
|
2503
3548
|
console.warn('[taskboard] 会话 flush 失败(消息已入队):' + describeError(flushError))
|
|
2504
3549
|
}
|
|
2505
3550
|
} catch (error) {
|
|
3551
|
+
const current = taskById(rt.state, taskId) || task
|
|
2506
3552
|
rt.poll.lastSkipReason = 'followup-failed'
|
|
2507
|
-
|
|
2508
|
-
|
|
3553
|
+
current.lastError = skipText('followup-failed') + ':' + describeError(error)
|
|
3554
|
+
current.updatedAt = iso(now)
|
|
2509
3555
|
commitBoard(rt.state, rt.filePath)
|
|
2510
3556
|
console.warn('[taskboard] 派发失败:' + describeError(error))
|
|
2511
3557
|
return { dispatched: false, reason: 'followup-failed', error: describeError(error) }
|
|
2512
3558
|
}
|
|
2513
|
-
|
|
2514
|
-
|
|
2515
|
-
|
|
2516
|
-
|
|
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 = ''
|
|
2517
3565
|
// 投递成功即视为「进行中」:看板立刻反映已派发,不再依赖主 Agent 记得调 taskboard_update
|
|
2518
3566
|
// (它照样可以再调一次 doing,迁移 doing→doing 合法)。
|
|
2519
|
-
if (
|
|
2520
|
-
|
|
2521
|
-
if (!
|
|
3567
|
+
if (target.status === 'todo') {
|
|
3568
|
+
target.status = 'doing'
|
|
3569
|
+
if (!target.startedAt) target.startedAt = iso(now)
|
|
2522
3570
|
}
|
|
2523
3571
|
rt.poll.lastDispatchAt = iso(now)
|
|
2524
3572
|
rt.poll.lastDispatchSessionId = sessionId
|
|
2525
3573
|
rt.poll.lastDispatchSessionTitle = sessionTitle(agent)
|
|
2526
|
-
|
|
2527
|
-
|
|
2528
|
-
rt.poll.lastDispatchTaskId =
|
|
3574
|
+
target.dispatchedSessionId = sessionId
|
|
3575
|
+
target.dispatchedSessionTitle = sessionTitle(agent) || ''
|
|
3576
|
+
rt.poll.lastDispatchTaskId = target.id
|
|
2529
3577
|
rt.poll.lastSkipReason = null
|
|
2530
3578
|
commitBoard(rt.state, rt.filePath)
|
|
2531
|
-
return { dispatched: true, sessionId, task: { ...
|
|
3579
|
+
return { dispatched: true, sessionId, task: { ...target } }
|
|
2532
3580
|
}
|
|
2533
3581
|
|
|
2534
3582
|
/** 「用户回复」followup 文本(§1.9):任务仍在原状态,要求组长接着处理。 */
|
|
@@ -2575,8 +3623,13 @@ export async function answerTask(rt, id, answer, now = Date.now()) {
|
|
|
2575
3623
|
}
|
|
2576
3624
|
/** 失败统一收尾:保留 flagged 状态,把原因写进任务 lastError 并落盘,再抛给 RPC。 */
|
|
2577
3625
|
const fail = (code, message) => {
|
|
2578
|
-
task.
|
|
2579
|
-
|
|
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
|
+
}
|
|
2580
3633
|
commitBoard(rt.state, rt.filePath)
|
|
2581
3634
|
return new BoardError(code, message)
|
|
2582
3635
|
}
|
|
@@ -2614,13 +3667,16 @@ export async function answerTask(rt, id, answer, now = Date.now()) {
|
|
|
2614
3667
|
throw fail('internal', '回复发送失败:' + describeError(error))
|
|
2615
3668
|
}
|
|
2616
3669
|
const stamp = iso(now)
|
|
2617
|
-
|
|
2618
|
-
task
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
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
|
+
}
|
|
2622
3678
|
commitBoard(rt.state, rt.filePath)
|
|
2623
|
-
return { task: { ...
|
|
3679
|
+
return { task: { ...target }, sessionId }
|
|
2624
3680
|
}
|
|
2625
3681
|
|
|
2626
3682
|
/** RPC `bind-main-session`(§3.1.1):绑定完成回执收件人;不要求会话当前在线。 */
|
|
@@ -2814,7 +3870,11 @@ export async function flushReceipts(rt, now = Date.now()) {
|
|
|
2814
3870
|
console.warn('[taskboard] 完成回执投递失败:' + describeError(error))
|
|
2815
3871
|
return { sent: false, reason: 'followup-failed' }
|
|
2816
3872
|
}
|
|
2817
|
-
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
|
+
}
|
|
2818
3878
|
commitBoard(rt.state, rt.filePath)
|
|
2819
3879
|
return { sent: true, count: batch.length, sessionId: config.mainSessionId }
|
|
2820
3880
|
} finally {
|
|
@@ -2822,6 +3882,64 @@ export async function flushReceipts(rt, now = Date.now()) {
|
|
|
2822
3882
|
}
|
|
2823
3883
|
}
|
|
2824
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
|
+
|
|
2825
3943
|
/**
|
|
2826
3944
|
* 工作区组长路由(§1.5):解析任务 cwd → 工作区 key → 复用/创建常驻组长。
|
|
2827
3945
|
* 绝不 createDispatchSession(每任务新建),也绝不跨工作区改派。
|
|
@@ -2855,6 +3973,9 @@ async function routeWorkspaceLead(rt, task, config, agents, options, now) {
|
|
|
2855
3973
|
if (!agent) return { ok: false, reason: 'lead-unavailable' }
|
|
2856
3974
|
// force(立即派发)时组长忙也把消息排进它的下一轮,与旧模式 creator-busy 的 force 语义一致。
|
|
2857
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
|
+
}
|
|
2858
3979
|
return { ok: true, agent, key }
|
|
2859
3980
|
}
|
|
2860
3981
|
// 没有映射 → 懒创建本工作区的常驻组长(一个工作区一个,不是每任务一个)。
|
|
@@ -2867,6 +3988,9 @@ async function routeWorkspaceLead(rt, task, config, agents, options, now) {
|
|
|
2867
3988
|
if (created.entry) config.workspaceLeads = putWorkspaceLead(config.workspaceLeads, key, created.entry)
|
|
2868
3989
|
if (!created.agent) return { ok: false, reason: 'lead-unavailable' }
|
|
2869
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
|
+
}
|
|
2870
3994
|
return { ok: true, agent: created.agent, key }
|
|
2871
3995
|
}
|
|
2872
3996
|
|
|
@@ -3185,15 +4309,71 @@ export function looksLikeSessionId(value) {
|
|
|
3185
4309
|
return SESSION_ID_PATTERN.test(text)
|
|
3186
4310
|
}
|
|
3187
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
|
+
|
|
3188
4363
|
/**
|
|
3189
4364
|
* 「看板任务:t-N」提到的卡片能否被这次派发认领:
|
|
3190
4365
|
* - 必须在待做 / 进行中(做完 / 归档的任务不抢);
|
|
4366
|
+
* - 名下不能已有未归档子卡(已进入 fan-out 的父卡不能被后续合并 / 验证子 Agent 误抢占);
|
|
4367
|
+
* - 当前没有正在跑的 worker(`workerRunState !== 'running'`:v0.3.1 起 `assignee` 是 worker 名字,
|
|
4368
|
+
* 只看 `looksLikeSessionId(assignee)` 会漏掉正在跑的 worker,导致验证子 Agent 抢占原卡);
|
|
3191
4369
|
* - 还没挂真实 worker 会话 id(已挂 = 已有 worker 在干,这次多半是验证子 Agent / 另一个 worker,
|
|
3192
4370
|
* 应该有自己的卡片;自由文本 assignee 如 `taskboard-worker` 不算)。
|
|
3193
4371
|
*/
|
|
3194
|
-
export function canReuseMentionedTask(task) {
|
|
4372
|
+
export function canReuseMentionedTask(task, state = null) {
|
|
3195
4373
|
if (!task) return false
|
|
3196
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
|
|
3197
4377
|
return !looksLikeSessionId(task.assignee)
|
|
3198
4378
|
}
|
|
3199
4379
|
|
|
@@ -3213,8 +4393,8 @@ export function takePreparedDispatch(rt, exec) {
|
|
|
3213
4393
|
|
|
3214
4394
|
/**
|
|
3215
4395
|
* §1.8(0.2.4):组长把轮询投递任务置 doing → 记一条「即将为它派 worker」的意图(不落盘)。
|
|
3216
|
-
*
|
|
3217
|
-
*
|
|
4396
|
+
* 只在任务当前未挂 worker 且未挂提问(`assignee === ''`、`workerRunState !== 'running'`、`needsUser !== true`)
|
|
4397
|
+
* 时记录:worker 已挂上或正在等用户回复时不算新派发意图,避免把后续直聊派活错误并进旧任务。
|
|
3218
4398
|
*/
|
|
3219
4399
|
export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
|
|
3220
4400
|
try {
|
|
@@ -3226,7 +4406,7 @@ export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
|
|
|
3226
4406
|
if (!task) return false
|
|
3227
4407
|
if (task.status !== 'doing' || asString(task.notifiedAt) === '') return false
|
|
3228
4408
|
if (task.dispatchedSessionId !== leadId) return false
|
|
3229
|
-
if (task.assignee !== '') return false
|
|
4409
|
+
if (task.assignee !== '' || task.workerRunState === 'running' || task.needsUser === true) return false
|
|
3230
4410
|
if (!(rt.leadDispatchIntent instanceof Map)) rt.leadDispatchIntent = new Map()
|
|
3231
4411
|
rt.leadDispatchIntent.set(leadId, { taskId: task.id, at: now })
|
|
3232
4412
|
return true
|
|
@@ -3235,7 +4415,7 @@ export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
|
|
|
3235
4415
|
}
|
|
3236
4416
|
}
|
|
3237
4417
|
|
|
3238
|
-
/** 取走(一次性)该组长的派发意图;过期 / 任务状态不符 → 作废。 */
|
|
4418
|
+
/** 取走(一次性)该组长的派发意图;过期 / 任务状态不符 / 已挂 running worker / 正在等用户回复 → 作废。 */
|
|
3239
4419
|
function takeLeadDispatchIntent(rt, leadId, now) {
|
|
3240
4420
|
if (!leadId || !(rt.leadDispatchIntent instanceof Map)) return null
|
|
3241
4421
|
const entry = rt.leadDispatchIntent.get(leadId)
|
|
@@ -3244,12 +4424,15 @@ function takeLeadDispatchIntent(rt, leadId, now) {
|
|
|
3244
4424
|
if (!Number.isFinite(entry.at) || now - entry.at > LEAD_DISPATCH_INTENT_MS) return null
|
|
3245
4425
|
const task = taskById(rt.state, entry.taskId)
|
|
3246
4426
|
if (!task || task.status !== 'doing' || asString(task.notifiedAt) === '') return null
|
|
4427
|
+
if (task.workerRunState === 'running' || task.needsUser === true) return null
|
|
3247
4428
|
return task
|
|
3248
4429
|
}
|
|
3249
4430
|
|
|
3250
4431
|
/**
|
|
3251
4432
|
* 这次派发的 prompt 是否真的指向这条任务(任务 id 或标题出现在 prompt 里)。
|
|
3252
4433
|
* 用来防止「组长刚给 t-68 记了派发意图」的**下一条无关直聊派发**把 t-68 认领走(t-69 事故的变体)。
|
|
4434
|
+
* v0.3.3 补充:如果 `description` 显式带了父任务 id(如 `t-107 切片 A`)而 `prompt` 没有带该任务 id,
|
|
4435
|
+
* 这是并行 fan-out 的切片 worker——即使 prompt 碰巧包含父任务短标题,也不能把父卡认领走。
|
|
3253
4436
|
*/
|
|
3254
4437
|
export function dispatchMentionsTask(args, task) {
|
|
3255
4438
|
if (!task) return false
|
|
@@ -3258,7 +4441,10 @@ export function dispatchMentionsTask(args, task) {
|
|
|
3258
4441
|
const id = asString(task.id)
|
|
3259
4442
|
if (id !== '') {
|
|
3260
4443
|
const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
3261
|
-
|
|
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
|
|
3262
4448
|
}
|
|
3263
4449
|
const title = asString(task.title).trim()
|
|
3264
4450
|
return title.length >= 4 && prompt.includes(title)
|
|
@@ -3270,7 +4456,14 @@ export function findPendingDispatchCard(state, leadId, title, note, now = Date.n
|
|
|
3270
4456
|
for (let i = state.tasks.length - 1; i >= 0; i -= 1) {
|
|
3271
4457
|
const task = state.tasks[i]
|
|
3272
4458
|
if (!task || task.autoDispatch !== LEAD_AUTO_MARK) continue
|
|
3273
|
-
if (
|
|
4459
|
+
if (
|
|
4460
|
+
task.status !== 'doing' ||
|
|
4461
|
+
task.assignee !== '' ||
|
|
4462
|
+
task.workerRunState !== null ||
|
|
4463
|
+
asString(task.workerSessionId) !== ''
|
|
4464
|
+
) {
|
|
4465
|
+
continue
|
|
4466
|
+
}
|
|
3274
4467
|
if (task.dispatchedSessionId !== leadId) continue
|
|
3275
4468
|
if (task.title !== title || (task.note || '') !== (note || '')) continue
|
|
3276
4469
|
const stamp = Date.parse(asString(task.createdAt))
|
|
@@ -3355,30 +4548,53 @@ export function prepareLeadDispatch(rt, input, now = Date.now()) {
|
|
|
3355
4548
|
// 0) 一次性消费「组长刚置 doing」的意图:即使这次靠显式任务 id 认领,也要把它清掉,
|
|
3356
4549
|
// 否则陈旧的 t-68 意图会在下一次无关的直聊派发里把旧任务认领走(t-69 事故的变体)。
|
|
3357
4550
|
const intent = takeLeadDispatchIntent(rt, leadId, now)
|
|
3358
|
-
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
3362
|
-
|
|
3363
|
-
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
const
|
|
3368
|
-
if (
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
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
|
+
}
|
|
3374
4582
|
}
|
|
3375
4583
|
// 3) 同参数重复调用(模型重试 / PTC 嵌套)→ 复用刚建好还没挂 worker 的卡片。
|
|
3376
4584
|
const pending = findPendingDispatchCard(rt.state, leadId, title, note, now)
|
|
3377
4585
|
if (pending) return finishPreparedDispatch(rt, auto, store, exec, pending, false, 'pending-duplicate', now)
|
|
3378
|
-
// 4) 新派发:先建卡(doing + autoDispatch),写盘成功才允许启动 worker。
|
|
4586
|
+
// 4) 新派发:先建卡(doing + autoDispatch + 可选 parentTaskId),写盘成功才允许启动 worker。
|
|
4587
|
+
const parentTaskId = explicitParentId || inferParentTaskIdForAutoCard(args, rt.state)
|
|
3379
4588
|
const task = addTask(
|
|
3380
4589
|
rt.state,
|
|
3381
|
-
{
|
|
4590
|
+
{
|
|
4591
|
+
title,
|
|
4592
|
+
note,
|
|
4593
|
+
source: 'agent',
|
|
4594
|
+
sessionId: leadId || null,
|
|
4595
|
+
cwd: leadDispatchCwd(rt, agent, args),
|
|
4596
|
+
parentTaskId,
|
|
4597
|
+
},
|
|
3382
4598
|
now,
|
|
3383
4599
|
)
|
|
3384
4600
|
applyTaskUpdate(rt.state, task.id, { status: 'doing' }, now)
|
|
@@ -3676,16 +4892,30 @@ function backfillWorkerSessionId(rt, input) {
|
|
|
3676
4892
|
.then(() => subagents.listDescendants(parentId))
|
|
3677
4893
|
.then((rows) => {
|
|
3678
4894
|
if (!Array.isArray(rows)) return
|
|
3679
|
-
const
|
|
4895
|
+
const matching = rows.filter(
|
|
3680
4896
|
(row) => row && row.parentId === parentId && row.kind === 'child' && asString(row.name) === workerName,
|
|
3681
4897
|
)
|
|
3682
|
-
|
|
3683
|
-
if (childId === '') return
|
|
4898
|
+
if (matching.length === 0) return
|
|
3684
4899
|
reloadBoardIfStale(rt)
|
|
3685
4900
|
const task = taskById(rt.state, taskId)
|
|
3686
4901
|
if (!task) return
|
|
3687
4902
|
// 已经有 id(回填过 / 重派换了 worker)→ 不覆盖。
|
|
3688
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
|
|
3689
4919
|
task.workerSessionId = childId
|
|
3690
4920
|
if ((task.workerRunState === null || task.workerRunState === '') && task.status === 'doing') {
|
|
3691
4921
|
task.workerRunState = 'running'
|
|
@@ -3706,6 +4936,46 @@ function backfillWorkerSessionId(rt, input) {
|
|
|
3706
4936
|
return true
|
|
3707
4937
|
}
|
|
3708
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
|
+
|
|
3709
4979
|
/**
|
|
3710
4980
|
* subagent/end:worker 结束 → **宿主自动建的任务**置 done + result(§1.8),并 flush 完成回执(§1.6)。
|
|
3711
4981
|
* 只认带 `autoDispatch === 'lead-dispatch'` 标记的任务:轮询投递任务的 assignee 也可能被组长写成 worker
|
|
@@ -3723,42 +4993,69 @@ export async function handleSubagentEnd(rt, info, now = Date.now()) {
|
|
|
3723
4993
|
return { updated: false, reason: 'skipped' }
|
|
3724
4994
|
}
|
|
3725
4995
|
reloadBoardIfStale(rt)
|
|
4996
|
+
const parentId = asString(info && info.parentSessionId).trim()
|
|
4997
|
+
let workerName = trimmed(info && info.name, 200)
|
|
3726
4998
|
let task = findTaskByWorker(rt.state, childId)
|
|
3727
4999
|
if (!task) {
|
|
3728
5000
|
// v0.3.1:workerSessionId 还没回填时(当前 dsh 的 subagent 结果没有 subagentId),
|
|
3729
|
-
//
|
|
3730
|
-
//
|
|
3731
|
-
const parentId = asString(info && info.parentSessionId).trim()
|
|
5001
|
+
// 先按 worker name(info.name 或 subagents.listDescendants 反查 childId)精确匹配 candidate.assignee
|
|
5002
|
+
// (支持 v0.3.3 并发 fan-out 切片卡);拿不到 workerName 时,仅当该组长名下只此一条在跑的自动卡才兜底认领。
|
|
3732
5003
|
if (parentId !== '') {
|
|
3733
|
-
|
|
3734
|
-
|
|
3735
|
-
|
|
3736
|
-
|
|
3737
|
-
|
|
3738
|
-
|
|
3739
|
-
|
|
3740
|
-
|
|
3741
|
-
|
|
3742
|
-
|
|
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
|
+
}
|
|
3743
5039
|
}
|
|
3744
5040
|
}
|
|
5041
|
+
const rawStopReason = asString(info && info.stopReason).trim()
|
|
5042
|
+
const stopReason = rawStopReason === '' ? 'unknown' : rawStopReason
|
|
3745
5043
|
if (!task) {
|
|
3746
5044
|
// 不是宿主建的自动任务(例如组长审核时派去跑命令的验证子 Agent,
|
|
3747
|
-
// 或轮询投递任务的 worker——那条任务的 autoDispatch 为 null
|
|
5045
|
+
// 或轮询投递任务的 worker——那条任务的 autoDispatch 为 null):仅收敛其 workerRunState。
|
|
5046
|
+
settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now)
|
|
3748
5047
|
auto.skipped += 1
|
|
3749
5048
|
auto.updatedAt = iso(now)
|
|
3750
5049
|
return { updated: false, reason: 'no-task' }
|
|
3751
5050
|
}
|
|
3752
5051
|
if (!isLeadAutoTask(task) || asString(task.notifiedAt) !== '') {
|
|
3753
5052
|
// 兜底:findTaskByWorker 已经过滤过,这里再挡一层,确保轮询任务(notifiedAt 非空)永不被自动 done。
|
|
5053
|
+
settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now)
|
|
3754
5054
|
auto.skipped += 1
|
|
3755
5055
|
auto.updatedAt = iso(now)
|
|
3756
5056
|
return { updated: false, reason: 'not-auto', taskId: task.id }
|
|
3757
5057
|
}
|
|
3758
5058
|
const result = workerResultText(info)
|
|
3759
|
-
// 缺字段 / 空串 / 未知值一律按非 completed 处理(绝不静默置 done):文案里缺省写 unknown。
|
|
3760
|
-
const rawStopReason = asString(info && info.stopReason).trim()
|
|
3761
|
-
const stopReason = rawStopReason === '' ? 'unknown' : rawStopReason
|
|
3762
5059
|
const wasDoing = task.status === 'doing'
|
|
3763
5060
|
if (stopReason !== 'completed') {
|
|
3764
5061
|
if (!wasDoing) {
|
|
@@ -3786,6 +5083,42 @@ export async function handleSubagentEnd(rt, info, now = Date.now()) {
|
|
|
3786
5083
|
auto.updatedAt = iso(now)
|
|
3787
5084
|
return { updated: false, reason: 'status-' + task.status, taskId: task.id }
|
|
3788
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
|
+
}
|
|
3789
5122
|
const patch = {}
|
|
3790
5123
|
if (result !== '') patch.result = result
|
|
3791
5124
|
// doing → done;已是 done(组长先审完 / 同一 worker 再次结束)就只刷新 result。
|
|
@@ -3873,9 +5206,11 @@ export function registerLeadAutoHooks(ctx, rt) {
|
|
|
3873
5206
|
ctx.on(
|
|
3874
5207
|
'subagent/end',
|
|
3875
5208
|
(info) => {
|
|
3876
|
-
|
|
3877
|
-
|
|
3878
|
-
|
|
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
|
+
)
|
|
3879
5214
|
},
|
|
3880
5215
|
{ global: true },
|
|
3881
5216
|
)
|
|
@@ -3885,6 +5220,91 @@ export function registerLeadAutoHooks(ctx, rt) {
|
|
|
3885
5220
|
return true
|
|
3886
5221
|
}
|
|
3887
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
|
+
|
|
3888
5308
|
/**
|
|
3889
5309
|
* 注册 §1.8(0.2.4)的**派发前强制建卡闸门**(`tools/pre-execute`)。
|
|
3890
5310
|
*
|
|
@@ -3922,6 +5342,8 @@ export function registerLeadDispatchGate(ctx, rt) {
|
|
|
3922
5342
|
// v0.3.2:卡片已准备好、worker 即将启动——这是「派发者出现」的时刻。
|
|
3923
5343
|
// 工作区没有组长 / 组长已归档 → 把当前派单会话登记为组长,避免轮询再新建一个组长窗口。
|
|
3924
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)
|
|
3925
5347
|
return next()
|
|
3926
5348
|
} catch (error) {
|
|
3927
5349
|
const message =
|
|
@@ -4044,6 +5466,8 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
|
|
|
4044
5466
|
id: { type: 'string' },
|
|
4045
5467
|
title: { type: 'string' },
|
|
4046
5468
|
status: { type: 'string', enum: [...STATUSES] },
|
|
5469
|
+
parentTaskId: { type: 'string' },
|
|
5470
|
+
dependsOn: { type: 'array', items: { type: 'string' } },
|
|
4047
5471
|
note: { type: 'string' },
|
|
4048
5472
|
assignee: { type: 'string' },
|
|
4049
5473
|
result: { type: 'string' },
|
|
@@ -4051,6 +5475,8 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
|
|
|
4051
5475
|
needsUser: { type: 'boolean' },
|
|
4052
5476
|
question: { type: 'string' },
|
|
4053
5477
|
questionOptions: { type: 'array', items: { type: 'string' } },
|
|
5478
|
+
worktreePath: { type: 'string' },
|
|
5479
|
+
worktreeBranch: { type: 'string' },
|
|
4054
5480
|
},
|
|
4055
5481
|
},
|
|
4056
5482
|
},
|
|
@@ -4058,7 +5484,7 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
|
|
|
4058
5484
|
}
|
|
4059
5485
|
|
|
4060
5486
|
/**
|
|
4061
|
-
*
|
|
5487
|
+
* 面向模型的任务摘要(taskboard_list 的 tasks[] / taskboard_add / taskboard_update 的 task)。
|
|
4062
5488
|
*
|
|
4063
5489
|
* 这里的键必须全部在 output.schema 里声明:dsh tools 管线在 execute() 成功返回之后才校验 canonical
|
|
4064
5490
|
* output,而两个 output.schema 都是 additionalProperties:false 的封闭契约——多带一个未声明字段就会抛
|
|
@@ -4072,6 +5498,8 @@ export function taskBrief(task) {
|
|
|
4072
5498
|
id: task.id,
|
|
4073
5499
|
title: task.title,
|
|
4074
5500
|
status: task.status,
|
|
5501
|
+
parentTaskId: task.parentTaskId || '',
|
|
5502
|
+
dependsOn: Array.isArray(task.dependsOn) ? task.dependsOn.slice() : [],
|
|
4075
5503
|
note: task.note || '',
|
|
4076
5504
|
assignee: task.assignee || '',
|
|
4077
5505
|
result: task.result || '',
|
|
@@ -4080,6 +5508,9 @@ export function taskBrief(task) {
|
|
|
4080
5508
|
needsUser: task.needsUser === true,
|
|
4081
5509
|
question: task.question || '',
|
|
4082
5510
|
questionOptions: Array.isArray(task.questionOptions) ? task.questionOptions.slice() : [],
|
|
5511
|
+
// v0.5.0:隔离工作树路径与分支,供组长判断是否需调 taskboard_merge_worktree 合入主工作区。
|
|
5512
|
+
worktreePath: task.worktreePath || '',
|
|
5513
|
+
worktreeBranch: task.worktreeBranch || '',
|
|
4083
5514
|
}
|
|
4084
5515
|
}
|
|
4085
5516
|
|
|
@@ -4087,9 +5518,15 @@ function renderTaskList(value) {
|
|
|
4087
5518
|
if (value.count === 0) return [{ type: 'text', text: '看板没有匹配的任务。' }]
|
|
4088
5519
|
const lines = ['看板任务(' + value.count + ' 条):']
|
|
4089
5520
|
for (const task of value.tasks) {
|
|
4090
|
-
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)
|
|
4091
5527
|
if (task.assignee) bits.push('@' + task.assignee)
|
|
4092
5528
|
lines.push('- ' + bits.join(' '))
|
|
5529
|
+
if (task.worktreePath) lines.push(' 隔离工作树:' + task.worktreePath + (task.worktreeBranch ? ' (' + task.worktreeBranch + ')' : ''))
|
|
4093
5530
|
if (task.note) lines.push(' 备注:' + task.note)
|
|
4094
5531
|
if (task.result) lines.push(' 结论:' + task.result)
|
|
4095
5532
|
if (task.needsUser) lines.push(' 待用户回答:' + task.question)
|
|
@@ -4098,7 +5535,18 @@ function renderTaskList(value) {
|
|
|
4098
5535
|
}
|
|
4099
5536
|
|
|
4100
5537
|
function renderTaskOne(prefix, task) {
|
|
4101
|
-
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 + ')' : ''))
|
|
4102
5550
|
if (task.note) lines.push('备注:' + task.note)
|
|
4103
5551
|
if (task.result) lines.push('结论:' + task.result)
|
|
4104
5552
|
if (task.needsUser) lines.push('待用户回答:' + task.question)
|
|
@@ -4122,6 +5570,8 @@ export const TASK_ONE_OUTPUT_SCHEMA = {
|
|
|
4122
5570
|
id: { type: 'string' },
|
|
4123
5571
|
title: { type: 'string' },
|
|
4124
5572
|
status: { type: 'string', enum: [...STATUSES] },
|
|
5573
|
+
parentTaskId: { type: 'string' },
|
|
5574
|
+
dependsOn: { type: 'array', items: { type: 'string' } },
|
|
4125
5575
|
note: { type: 'string' },
|
|
4126
5576
|
assignee: { type: 'string' },
|
|
4127
5577
|
result: { type: 'string' },
|
|
@@ -4129,11 +5579,30 @@ export const TASK_ONE_OUTPUT_SCHEMA = {
|
|
|
4129
5579
|
needsUser: { type: 'boolean' },
|
|
4130
5580
|
question: { type: 'string' },
|
|
4131
5581
|
questionOptions: { type: 'array', items: { type: 'string' } },
|
|
5582
|
+
worktreePath: { type: 'string' },
|
|
5583
|
+
worktreeBranch: { type: 'string' },
|
|
4132
5584
|
},
|
|
4133
5585
|
},
|
|
4134
5586
|
},
|
|
4135
5587
|
}
|
|
4136
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
|
+
|
|
4137
5606
|
/**
|
|
4138
5607
|
* 注册三个模型工具。宿主级注册 = 全局可见(所有预设的 Agent 都能用),
|
|
4139
5608
|
* 这也是「非派单模式也能往看板里塞任务」的实现方式。
|
|
@@ -4148,7 +5617,7 @@ export function registerTools(toolCtx, rt) {
|
|
|
4148
5617
|
name: 'taskboard_list',
|
|
4149
5618
|
description:
|
|
4150
5619
|
'列出任务看板上的任务(默认全部状态:todo=待开始 / doing=进行中 / done=已完成 / archived=已归档)。' +
|
|
4151
|
-
'
|
|
5620
|
+
'派单前用它确认要处理哪条任务;并行拆片(fan-out)时传 parentTaskId 只看该父任务名下的全部子卡进度;审核后用 taskboard_update 更新状态。',
|
|
4152
5621
|
parameters: {
|
|
4153
5622
|
type: 'object',
|
|
4154
5623
|
additionalProperties: false,
|
|
@@ -4158,6 +5627,10 @@ export function registerTools(toolCtx, rt) {
|
|
|
4158
5627
|
enum: [...STATUSES],
|
|
4159
5628
|
description: '只看某一列;省略则返回全部状态。',
|
|
4160
5629
|
},
|
|
5630
|
+
parentTaskId: {
|
|
5631
|
+
type: 'string',
|
|
5632
|
+
description: '可选:只看某条父任务(如 t-10)名下的切片 / 合并 / 验证子卡;省略不过滤。',
|
|
5633
|
+
},
|
|
4161
5634
|
},
|
|
4162
5635
|
},
|
|
4163
5636
|
output: {
|
|
@@ -4165,10 +5638,16 @@ export function registerTools(toolCtx, rt) {
|
|
|
4165
5638
|
render: (_args, value) => renderTaskList(value),
|
|
4166
5639
|
},
|
|
4167
5640
|
execute(args) {
|
|
5641
|
+
reloadBoardIfStale(rt)
|
|
4168
5642
|
const want = args && args.status !== undefined ? args.status : ''
|
|
4169
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
|
+
}
|
|
4170
5648
|
const tasks = rt.state.tasks
|
|
4171
5649
|
.filter((task) => (want === '' ? true : task.status === want))
|
|
5650
|
+
.filter((task) => (wantParentRaw === '' ? true : asString(task.parentTaskId).toLowerCase() === wantParentRaw))
|
|
4172
5651
|
.map(taskBrief)
|
|
4173
5652
|
return Promise.resolve({ count: tasks.length, tasks })
|
|
4174
5653
|
},
|
|
@@ -4178,7 +5657,8 @@ export function registerTools(toolCtx, rt) {
|
|
|
4178
5657
|
description:
|
|
4179
5658
|
'往任务看板添加一条待开始任务。用户口述的需求、你自己拆出来的后续任务都可以加进看板,' +
|
|
4180
5659
|
'轮询器会把它派给任务所属工作区的常驻组长。title 必填,note 写验收标准或补充信息;' +
|
|
4181
|
-
'workspace 可选(工作区 id / 名称 /
|
|
5660
|
+
'workspace 可选(工作区 id / 名称 / 绝对路径),用于从主会话往其它工作区派任务;' +
|
|
5661
|
+
'parentTaskId 可选(关联所属父任务 id,如 t-10)。',
|
|
4182
5662
|
parameters: {
|
|
4183
5663
|
type: 'object',
|
|
4184
5664
|
additionalProperties: false,
|
|
@@ -4190,6 +5670,15 @@ export function registerTools(toolCtx, rt) {
|
|
|
4190
5670
|
type: 'string',
|
|
4191
5671
|
description: '可选:任务所属工作区(工作区 id / 名称 / 绝对路径),省略则用当前会话工作区',
|
|
4192
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
|
+
},
|
|
4193
5682
|
},
|
|
4194
5683
|
},
|
|
4195
5684
|
output: {
|
|
@@ -4197,9 +5686,14 @@ export function registerTools(toolCtx, rt) {
|
|
|
4197
5686
|
render: (_args, value) => renderTaskOne('已添加任务 ', value.task),
|
|
4198
5687
|
},
|
|
4199
5688
|
execute(args, exec) {
|
|
5689
|
+
reloadBoardIfStale(rt)
|
|
4200
5690
|
const title = trimmed(args && args.title, MAX_TITLE_CHARS)
|
|
4201
5691
|
if (title === '') throw new Error('title 不能为空')
|
|
4202
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
|
+
}
|
|
4203
5697
|
let sessionId = null
|
|
4204
5698
|
let cwd = null
|
|
4205
5699
|
try {
|
|
@@ -4219,7 +5713,15 @@ export function registerTools(toolCtx, rt) {
|
|
|
4219
5713
|
if (resolved === '') throw new Error('未知工作区:' + workspaceArg)
|
|
4220
5714
|
cwd = resolved
|
|
4221
5715
|
}
|
|
4222
|
-
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
|
+
})
|
|
4223
5725
|
commitBoard(rt.state, rt.filePath)
|
|
4224
5726
|
return Promise.resolve({ task: taskBrief(task) })
|
|
4225
5727
|
},
|
|
@@ -4228,7 +5730,8 @@ export function registerTools(toolCtx, rt) {
|
|
|
4228
5730
|
name: 'taskboard_update',
|
|
4229
5731
|
description:
|
|
4230
5732
|
'更新看板任务:置为 doing(已派发)、done(审核通过)、todo(打回重做)、archived(归档);' +
|
|
4231
|
-
'也可以用 result
|
|
5733
|
+
'也可以用 result 写审核结论、lastError 写故障或阻塞原因(传空串清空,提问不要写进 lastError)。' +
|
|
5734
|
+
'assignee 只写子 Agent 的 label / 名字(自由文本),**不要写会话 id**——' +
|
|
4232
5735
|
'执行会话 id 由宿主记在 workerSessionId,模型写不进去。状态迁移非法时会返回错误。' +
|
|
4233
5736
|
'需要用户决策时用 needsUser:true + question(可选 questionOptions 选项)在任务上提问,' +
|
|
4234
5737
|
'看板会把它放进「待你处理」并通知用户回答;needsUser:false 取消提问(问题字段清空,回答留档)。' +
|
|
@@ -4243,6 +5746,10 @@ export function registerTools(toolCtx, rt) {
|
|
|
4243
5746
|
result: { type: 'string', description: '审核结论 / 子 Agent 汇报摘要' },
|
|
4244
5747
|
assignee: { type: 'string', description: '子 Agent 的 label / 名字(自由文本;不要写会话 id)' },
|
|
4245
5748
|
note: { type: 'string', description: '备注(覆盖原备注)' },
|
|
5749
|
+
lastError: {
|
|
5750
|
+
type: 'string',
|
|
5751
|
+
description: '故障或阻塞原因(派发失败 / 缺少工作目录 / worker 异常;传空串可清空,不要写向用户的提问)',
|
|
5752
|
+
},
|
|
4246
5753
|
needsUser: {
|
|
4247
5754
|
type: 'boolean',
|
|
4248
5755
|
description: '是否在等用户回复:true 时必须同时给 question;false 取消提问',
|
|
@@ -4253,6 +5760,11 @@ export function registerTools(toolCtx, rt) {
|
|
|
4253
5760
|
items: { type: 'string' },
|
|
4254
5761
|
description: '可选答案(最多 4 个,每个 ≤80 字;用户可以在看板上点选)',
|
|
4255
5762
|
},
|
|
5763
|
+
dependsOn: {
|
|
5764
|
+
type: 'array',
|
|
5765
|
+
items: { type: 'string' },
|
|
5766
|
+
description: '可选:覆盖设置前置依赖任务 id 列表(传空数组 [] 清空前置依赖)',
|
|
5767
|
+
},
|
|
4256
5768
|
},
|
|
4257
5769
|
},
|
|
4258
5770
|
output: {
|
|
@@ -4261,11 +5773,22 @@ export function registerTools(toolCtx, rt) {
|
|
|
4261
5773
|
},
|
|
4262
5774
|
async execute(args, exec) {
|
|
4263
5775
|
if (!args || !args.id) throw new Error('缺少任务 id')
|
|
5776
|
+
reloadBoardIfStale(rt)
|
|
4264
5777
|
const patch = {}
|
|
4265
5778
|
// v0.2.9(§2):`workerSessionId` / `workerRunState` 是宿主独占字段,**不在白名单里**——
|
|
4266
5779
|
// 模型即使传了也进不了 patch(`parameters.additionalProperties:false` 还会在入参校验阶段拒绝),
|
|
4267
5780
|
// `applyTaskUpdate` 也不读这两个键,所以任务字段绝不会被模型改写。
|
|
4268
|
-
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
|
+
]) {
|
|
4269
5792
|
if (args[key] !== undefined) patch[key] = args[key]
|
|
4270
5793
|
}
|
|
4271
5794
|
// §1.9:提问的会话 id(askedBy)由宿主补,模型不能伪造别的会话。
|
|
@@ -4295,7 +5818,43 @@ export function registerTools(toolCtx, rt) {
|
|
|
4295
5818
|
return { task: taskBrief(task) }
|
|
4296
5819
|
},
|
|
4297
5820
|
})
|
|
4298
|
-
|
|
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')
|
|
4299
5858
|
}
|
|
4300
5859
|
|
|
4301
5860
|
/* ------------------------------------------------------------------ *
|
|
@@ -4346,6 +5905,10 @@ export function apply(ctx) {
|
|
|
4346
5905
|
// 启动时清一次过期归档(§1.2):宿主停机期间到期的归档不必等第一个 tick。
|
|
4347
5906
|
// 只在真的有删除时写盘(pruneArchivedBoard 内部判断),因此没有副作用地复用同一路径。
|
|
4348
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
|
+
)
|
|
4349
5912
|
|
|
4350
5913
|
// 模式状态:agentPresets 服务就绪后读名单(预设本身由 bundle patch 声明,不在这里安装)。
|
|
4351
5914
|
// 预设行的激活是异步的,所以前几次读不到不算失败——最多重试 3 次再告警。
|