dsh-dispatch-board 0.3.3 → 0.5.6

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/index.js CHANGED
@@ -28,8 +28,20 @@
28
28
  */
29
29
 
30
30
  import { Buffer } from 'node:buffer'
31
- import { randomUUID } from 'node:crypto'
32
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
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` 任务在归档满 30 分钟后由宿主自动从看板删除,
97
+ * 归档保留期(§1.2 / §2):`archived` 任务在归档满保留期(默认 30 分钟;v0.3.6 起可通过
98
+ * `config.archiveRetentionMinutes` 配置为 0..10080 分钟,0 = 不自动删除)后由宿主自动从看板删除,
86
99
  * 不需要用户手动点「删除」。判定见 `pruneArchivedTasks()`。
87
100
  */
88
- export const ARCHIVE_RETENTION_MS = 30 * 60 * 1000
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,8 +168,20 @@ 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
155
-
156
- /** 看板四列。顺序即 UI 列顺序。 */
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'])
183
+
184
+ /** 四个状态列(v0.5.4 起「已归档」列默认隐藏、可折叠)。顺序即 UI 列顺序。 */
157
185
  export const STATUSES = ['todo', 'doing', 'done', 'archived']
158
186
 
159
187
  /** 合法状态迁移(含原地更新)。轮询只扫 todo。 */
@@ -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) ? raw.workerRunState : null,
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,689 @@ 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
+ * v0.5.2:把 `git diff` 输出按 `diff --git` 头切成**文件级**补丁(Buffer 粒度,binary / rename /
1406
+ * mode 段原样保留,不会切开单个文件的多个 hunk)。空 diff → `[]`;单文件 → 1 段;
1407
+ * `diff --git` 之前的杂项前导(当前 git 不会产生)直接丢弃。
1408
+ */
1409
+ export function splitGitPatchByFile(diffBuf) {
1410
+ const buf = Buffer.isBuffer(diffBuf) ? diffBuf : Buffer.from(diffBuf == null ? '' : String(diffBuf), 'utf8')
1411
+ if (buf.length === 0) return []
1412
+ const headMarker = Buffer.from('diff --git ')
1413
+ const marker = Buffer.from('\ndiff --git ')
1414
+ let cursor = 0
1415
+ if (!buf.subarray(0, headMarker.length).equals(headMarker)) {
1416
+ const first = buf.indexOf(marker)
1417
+ if (first === -1) return []
1418
+ cursor = first + 1
1419
+ }
1420
+ const chunks = []
1421
+ while (cursor < buf.length) {
1422
+ const next = buf.indexOf(marker, cursor + 1)
1423
+ if (next === -1) {
1424
+ chunks.push(buf.subarray(cursor))
1425
+ break
1426
+ }
1427
+ chunks.push(buf.subarray(cursor, next + 1))
1428
+ cursor = next + 1
1429
+ }
1430
+ return chunks.filter((chunk) => chunk.length > 0)
1431
+ }
1432
+
1433
+ /** 从单文件补丁的 `diff --git` 头取目标路径(b/ 侧),仅用于面向组长的摘要 / 冲突说明。 */
1434
+ function patchTargetPath(patchBuf) {
1435
+ const head = patchBuf.toString('utf8', 0, Math.min(patchBuf.length, 8192))
1436
+ const firstLine = head.split('\n', 1)[0] || ''
1437
+ const rest = firstLine.startsWith('diff --git ') ? firstLine.slice('diff --git '.length).trim() : firstLine.trim()
1438
+ const quoted = /^"a\/(.+)"\s+"b\/(.+)"$/.exec(rest)
1439
+ if (quoted) return quoted[2]
1440
+ const idx = rest.indexOf(' b/')
1441
+ if (idx !== -1) return rest.slice(idx + 3)
1442
+ return rest === '' ? '(未知文件)' : rest
1443
+ }
1444
+
1445
+ /**
1446
+ * 将指定任务的隔离 Git Worktree 改动原子预检并合入主工作区,成功后自动回收 Worktree 与临时分支。
1447
+ *
1448
+ * - 先卸载所有依赖 Junction,再把 Worktree 内未提交文件快照提交至临时分支 `taskboard/<id>`;
1449
+ * - 用 `git diff --binary --full-index -U1 <base>..<wtHead>` 生成补丁,**按文件粒度**在主工作区预检
1450
+ * (v0.5.2,t-209:整份补丁一次性判定会把「前序切片已改过同一文件」误判成整卡冲突):
1451
+ * - 每个文件补丁先跑 `git apply --check --reverse`:通过 = 主工作区已存在该改动 → alreadyApplied,
1452
+ * 跳过、不重复应用;
1453
+ * - 其余文件拼成子集补丁,`git apply --check` 通过 → `git apply` 写入主工作区(兼容主工作区已有
1454
+ * 未提交 WIP 或前序切片改动,不污染主分支 commit 历史),成功后照旧回收 Worktree;
1455
+ * - 子集里仍有文件判定失败 → 真实冲突:主工作区保持 100% 未修改,恢复 Worktree 依赖软链并返回
1456
+ * `{merged:false, conflict:true, conflictFiles}`(摘要里标出哪些文件其实已在主工作区,方便组长核对);
1457
+ * - 全部文件 alreadyApplied → 视为幂等成功(`merged:true`),只回收 Worktree。
1458
+ */
1459
+ export function mergeAndCleanupTaskWorktree(rt, taskId, options = {}) {
1460
+ const task = findTask(rt.state, taskId)
1461
+ const wtPath = asString(task.worktreePath).trim()
1462
+ const branch = asString(task.worktreeBranch).trim()
1463
+ const cleanup = options.cleanup !== false
1464
+ const discardOnly = options.discardOnly === true
1465
+ const shouldCommitBoard = options.commit !== false
1466
+
1467
+ if (wtPath === '' && branch === '') {
1468
+ return {
1469
+ id: task.id,
1470
+ merged: false,
1471
+ noChanges: true,
1472
+ conflict: false,
1473
+ cleaned: true,
1474
+ branch: '',
1475
+ worktreePath: '',
1476
+ conflictFiles: [],
1477
+ summary: '该任务未关联隔离工作树(无需合入)',
1478
+ }
1479
+ }
1480
+
1481
+ const repoInfo = resolveGitRepoInfo(asString(task.cwd), { fresh: true })
1482
+ if (!repoInfo) {
1483
+ if (discardOnly) {
1484
+ cleanupTaskWorktree(task)
1485
+ task.updatedAt = iso(Date.now())
1486
+ if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
1487
+ return {
1488
+ id: task.id,
1489
+ merged: false,
1490
+ noChanges: false,
1491
+ conflict: false,
1492
+ cleaned: true,
1493
+ branch,
1494
+ worktreePath: '',
1495
+ conflictFiles: [],
1496
+ summary: '已清理隔离工作树记录',
1497
+ }
1498
+ }
1499
+ throw new BoardError('conflict', '无法解析任务主工作区 Git 仓库:' + asString(task.cwd))
1500
+ }
1501
+ const { repoRoot } = repoInfo
1502
+
1503
+ if (discardOnly) {
1504
+ cleanupTaskWorktree(task, repoRoot)
1505
+ task.updatedAt = iso(Date.now())
1506
+ if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
1507
+ return {
1508
+ id: task.id,
1509
+ merged: false,
1510
+ noChanges: false,
1511
+ conflict: false,
1512
+ cleaned: true,
1513
+ branch,
1514
+ worktreePath: '',
1515
+ conflictFiles: [],
1516
+ summary: '已丢弃隔离工作树改动并回收临时分支 ' + (branch || wtPath),
1517
+ }
1518
+ }
1519
+
1520
+ if (wtPath === '' || !existsSync(wtPath)) {
1521
+ cleanupTaskWorktree(task, repoRoot)
1522
+ task.updatedAt = iso(Date.now())
1523
+ if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
1524
+ throw new BoardError('not-found', '隔离工作树目录不存在,无法合入:' + (wtPath || branch))
1525
+ }
1526
+
1527
+ // 1) 必须先卸载全部依赖 Junction,防止 git add -A 把主仓 node_modules/.venv 扫进临时分支!
1528
+ unlinkWorktreeJunctions(wtPath, task.worktreeLinks)
1529
+
1530
+ // 2) 将 worker 在隔离工作树内未提交的改动(含新建/删除文件)快照提交到临时分支
1531
+ const statusOut = execFileSync('git', ['-C', wtPath, 'status', '--porcelain'], {
1532
+ encoding: 'utf8',
1533
+ stdio: ['ignore', 'pipe', 'pipe'],
1534
+ windowsHide: true,
1535
+ timeout: 10000,
1536
+ }).trim()
1537
+ if (statusOut !== '') {
1538
+ execFileSync('git', ['-C', wtPath, 'add', '-A'], {
1539
+ stdio: ['ignore', 'pipe', 'pipe'],
1540
+ windowsHide: true,
1541
+ timeout: 10000,
1542
+ })
1543
+ execFileSync(
1544
+ 'git',
1545
+ [
1546
+ '-C',
1547
+ wtPath,
1548
+ '-c',
1549
+ 'user.name=dsh-taskboard',
1550
+ '-c',
1551
+ 'user.email=taskboard@local',
1552
+ 'commit',
1553
+ '-m',
1554
+ 'chore(taskboard): snapshot ' + task.id,
1555
+ '--no-verify',
1556
+ ],
1557
+ {
1558
+ stdio: ['ignore', 'pipe', 'pipe'],
1559
+ windowsHide: true,
1560
+ timeout: 15000,
1561
+ },
1562
+ )
1563
+ }
1564
+
1565
+ // 3) 计算相对基线 commit 的补丁
1566
+ const wtHead = execFileSync('git', ['-C', wtPath, 'rev-parse', 'HEAD'], {
1567
+ encoding: 'utf8',
1568
+ stdio: ['ignore', 'pipe', 'pipe'],
1569
+ windowsHide: true,
1570
+ timeout: 5000,
1571
+ }).trim()
1572
+ let baseCommit = asString(task.worktreeBaseCommit).trim()
1573
+ if (baseCommit === '') {
1574
+ baseCommit = execFileSync('git', ['-C', repoRoot, 'merge-base', 'HEAD', wtHead], {
1575
+ encoding: 'utf8',
1576
+ stdio: ['ignore', 'pipe', 'pipe'],
1577
+ windowsHide: true,
1578
+ timeout: 5000,
1579
+ }).trim()
1580
+ }
1581
+
1582
+ const finishNoChanges = () => {
1583
+ let cleaned = false
1584
+ if (cleanup) {
1585
+ cleanupTaskWorktree(task, repoRoot)
1586
+ cleaned = true
1587
+ } else {
1588
+ task.worktreeLinks = linkWorktreeDependencies(repoRoot, wtPath)
1589
+ }
1590
+ task.updatedAt = iso(Date.now())
1591
+ if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
1592
+ return {
1593
+ id: task.id,
1594
+ merged: false,
1595
+ noChanges: true,
1596
+ conflict: false,
1597
+ cleaned,
1598
+ branch,
1599
+ worktreePath: task.worktreePath || '',
1600
+ conflictFiles: [],
1601
+ summary: '隔离工作树无文件改动' + (cleaned ? ',已回收临时工作树' : ''),
1602
+ }
1603
+ }
1604
+
1605
+ if (wtHead === baseCommit) return finishNoChanges()
1606
+
1607
+ const diffBuf = execFileSync(
1608
+ 'git',
1609
+ ['-C', wtPath, 'diff', '--binary', '--full-index', '-U1', baseCommit + '..' + wtHead],
1610
+ {
1611
+ stdio: ['ignore', 'pipe', 'pipe'],
1612
+ maxBuffer: 64 * 1024 * 1024,
1613
+ windowsHide: true,
1614
+ timeout: 15000,
1615
+ },
1616
+ )
1617
+ if (!diffBuf || diffBuf.length === 0) return finishNoChanges()
1618
+
1619
+ // 4) 主工作区原子预检(不触碰 git index,失败绝不留半截改动或冲突标记)。
1620
+ // v0.5.2(t-209):按**文件**粒度判定——主工作区已经存在某个文件的改动时(前序切片 / 用户手动改过),
1621
+ // 只跳过该文件、继续补入其它文件;不再因为一个文件已合入就把整份补丁判成冲突。
1622
+ const filePatches = splitGitPatchByFile(diffBuf)
1623
+ if (filePatches.length === 0) return finishNoChanges()
1624
+
1625
+ const checkPatch = (patchBuf, extraFlags = []) => {
1626
+ try {
1627
+ execFileSync(
1628
+ 'git',
1629
+ ['-C', repoRoot, 'apply', '--check', ...extraFlags, '--whitespace=nowarn', '-'],
1630
+ {
1631
+ input: patchBuf,
1632
+ stdio: ['pipe', 'pipe', 'pipe'],
1633
+ maxBuffer: 64 * 1024 * 1024,
1634
+ windowsHide: true,
1635
+ timeout: 15000,
1636
+ },
1637
+ )
1638
+ return { ok: true, stderr: '' }
1639
+ } catch (error) {
1640
+ return { ok: false, stderr: String((error && error.stderr) || describeError(error)) }
1641
+ }
1642
+ }
1643
+
1644
+ const alreadyAppliedPatches = []
1645
+ const pendingPatches = []
1646
+ for (const patch of filePatches) {
1647
+ // `--check --reverse` 通过 = 主工作区已存在该文件的这份改动(alreadyApplied),不再重复应用。
1648
+ if (checkPatch(patch, ['--reverse']).ok) alreadyAppliedPatches.push(patch)
1649
+ else pendingPatches.push(patch)
1650
+ }
1651
+ const alreadyAppliedFiles = alreadyAppliedPatches.map((patch) => patchTargetPath(patch))
1652
+ const existingNote =
1653
+ alreadyAppliedFiles.length > 0
1654
+ ? alreadyAppliedFiles.length + ' 个文件已在主工作区存在:' + alreadyAppliedFiles.join(', ')
1655
+ : ''
1656
+
1657
+ const conflictReturn = (stderrText) => {
1658
+ task.worktreeLinks = linkWorktreeDependencies(repoRoot, wtPath)
1659
+ const conflictFiles = extractGitApplyConflictFiles(stderrText)
1660
+ task.updatedAt = iso(Date.now())
1661
+ if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
1662
+ const conflictDesc =
1663
+ conflictFiles.length > 0 ? conflictFiles.join(', ') : flattenResultLine(stderrText, 180)
1664
+ return {
1665
+ id: task.id,
1666
+ merged: false,
1667
+ noChanges: false,
1668
+ conflict: true,
1669
+ cleaned: false,
1670
+ branch,
1671
+ worktreePath: wtPath,
1672
+ conflictFiles,
1673
+ summary:
1674
+ '合入主工作区检测到冲突(主工作区未被修改):' + conflictDesc +
1675
+ (existingNote === '' ? '' : ';' + existingNote) +
1676
+ ';隔离工作树保留在 ' + wtPath,
1677
+ }
1678
+ }
1679
+
1680
+ if (pendingPatches.length > 0) {
1681
+ const pendingBuf = Buffer.concat(pendingPatches)
1682
+ const forward = checkPatch(pendingBuf)
1683
+ // 子集里仍有文件应用失败 → 维持原有冲突语义(主工作区不动、保留工作树),
1684
+ // 摘要里标出哪些文件其实已在主工作区,方便组长核对后手动处理。
1685
+ if (!forward.ok) return conflictReturn(forward.stderr)
1686
+ execFileSync('git', ['-C', repoRoot, 'apply', '--whitespace=nowarn', '-'], {
1687
+ input: pendingBuf,
1688
+ stdio: ['pipe', 'pipe', 'pipe'],
1689
+ maxBuffer: 64 * 1024 * 1024,
1690
+ windowsHide: true,
1691
+ timeout: 15000,
1692
+ })
1693
+ }
1694
+
1695
+ let cleaned = false
1696
+ if (cleanup) {
1697
+ cleanupTaskWorktree(task, repoRoot)
1698
+ cleaned = true
1699
+ } else {
1700
+ task.worktreeLinks = linkWorktreeDependencies(repoRoot, wtPath)
1701
+ }
1702
+ task.updatedAt = iso(Date.now())
1703
+ if (shouldCommitBoard) commitBoard(rt.state, rt.filePath)
1704
+ let summary
1705
+ if (alreadyAppliedPatches.length === 0) {
1706
+ summary = '已将隔离工作树改动合入主工作区' + (cleaned ? '并清理临时分支 ' + branch : '')
1707
+ } else if (pendingPatches.length === 0) {
1708
+ summary =
1709
+ '隔离工作树的 ' + alreadyAppliedPatches.length + ' 个文件已在主工作区存在(无需重复应用)' +
1710
+ (cleaned ? ',已回收临时工作树与分支 ' + branch : '')
1711
+ } else {
1712
+ summary =
1713
+ '已将隔离工作树改动合入主工作区(' +
1714
+ alreadyAppliedPatches.length +
1715
+ ' 个文件已在主工作区存在,仅补入 ' +
1716
+ pendingPatches.length +
1717
+ ' 个)' +
1718
+ (cleaned ? ',已清理临时分支 ' + branch : '')
1719
+ }
1720
+ return {
1721
+ id: task.id,
1722
+ merged: true,
1723
+ noChanges: false,
1724
+ conflict: false,
1725
+ cleaned,
1726
+ branch,
1727
+ worktreePath: task.worktreePath || '',
1728
+ conflictFiles: [],
1729
+ summary,
1730
+ }
1731
+ }
1732
+
847
1733
  /* ------------------------------------------------------------------ *
848
1734
  * 任务操作(纯函数,便于单测)
849
1735
  * ------------------------------------------------------------------ */
@@ -872,6 +1758,11 @@ export function addTask(state, input, now = Date.now()) {
872
1758
  if (needsUser && question === '') {
873
1759
  throw new BoardError('bad-request', 'needsUser=true 时必须提供非空的 question')
874
1760
  }
1761
+ const pendingId = 't-' + state.nextId
1762
+ const dependsOn =
1763
+ input.dependsOn !== undefined && input.dependsOn !== null
1764
+ ? assertValidDependsOnInput(state, pendingId, input.dependsOn)
1765
+ : []
875
1766
  const stamp = iso(now)
876
1767
  const task = {
877
1768
  id: nextTaskId(state),
@@ -885,6 +1776,12 @@ export function addTask(state, input, now = Date.now()) {
885
1776
  dispatchedSessionTitle: '',
886
1777
  reportedAt: null,
887
1778
  autoDispatch: null,
1779
+ parentTaskId: null,
1780
+ dependsOn,
1781
+ worktreePath: null,
1782
+ worktreeBranch: null,
1783
+ worktreeBaseCommit: null,
1784
+ worktreeLinks: [],
888
1785
  needsUser,
889
1786
  question: needsUser ? question : '',
890
1787
  questionOptions: needsUser ? normalizeQuestionOptions(input.questionOptions) : [],
@@ -907,6 +1804,7 @@ export function addTask(state, input, now = Date.now()) {
907
1804
  notificationCount: 0,
908
1805
  lastError: '',
909
1806
  }
1807
+ task.parentTaskId = normalizeParentTaskId(input.parentTaskId, task.id)
910
1808
  state.tasks.push(task)
911
1809
  return task
912
1810
  }
@@ -946,6 +1844,11 @@ export function applyTaskUpdate(state, id, patch, now = Date.now()) {
946
1844
  nextTitle = trimmed(patch.title, MAX_TITLE_CHARS)
947
1845
  if (nextTitle === '') throw new BoardError('bad-request', '标题不能为空')
948
1846
  }
1847
+ let nextDependsOn = null
1848
+ if (patch.dependsOn !== undefined) {
1849
+ nextDependsOn =
1850
+ patch.dependsOn === null ? [] : assertValidDependsOnInput(state, task.id, patch.dependsOn)
1851
+ }
949
1852
  // v0.2.3(§1.9):归档是终态,看板「待你处理」派生明确排除 archived(lib/client.js),
950
1853
  // 在归档任务上提问只会静默石沉大海。这里直接拒绝:本次 patch 没有同时改 status(重开 / 再次归档)
951
1854
  // 却试图设置提问(needsUser:true 或带 question)→ conflict;先于任何字段写入,失败不留部分修改。
@@ -1023,11 +1926,16 @@ export function applyTaskUpdate(state, id, patch, now = Date.now()) {
1023
1926
  task.finishedAt = stamp
1024
1927
  // 新的完成一定还没汇报过;已汇报过的历史结论只在 done→archived 时保留。
1025
1928
  task.reportedAt = null
1929
+ // v0.3.9:轮询任务由组长审核置 done 时,若 workerRunState 仍停在 running,收敛为 ended。
1930
+ if (task.workerRunState === 'running') task.workerRunState = 'ended'
1026
1931
  } else if (patch.status === 'archived') {
1027
1932
  // done→archived 不改 reportedAt:不会重发历史回执。
1028
1933
  task.archivedAt = stamp
1934
+ if (task.workerRunState === 'running') task.workerRunState = 'ended'
1935
+ cleanupTaskWorktree(task)
1029
1936
  } else if (patch.status === 'todo') {
1030
- // 回到待开始:重新排队派发,清掉上一轮的派发记账。
1937
+ // 回到待开始:重新排队派发,清掉上一轮的派发记账与残留隔离工作树。
1938
+ cleanupTaskWorktree(task)
1031
1939
  task.startedAt = null
1032
1940
  task.finishedAt = null
1033
1941
  task.archivedAt = null
@@ -1044,6 +1952,7 @@ export function applyTaskUpdate(state, id, patch, now = Date.now()) {
1044
1952
  }
1045
1953
  }
1046
1954
  if (nextTitle !== null) task.title = nextTitle
1955
+ if (nextDependsOn !== null) task.dependsOn = nextDependsOn
1047
1956
  if (patch.note !== undefined) task.note = truncateNote(patch.note, MAX_NOTE_CHARS)
1048
1957
  if (patch.result !== undefined) task.result = truncateNote(patch.result, MAX_NOTE_CHARS)
1049
1958
  if (patch.assignee !== undefined) task.assignee = trimmed(patch.assignee, 200)
@@ -1073,6 +1982,8 @@ export function archiveDoneTasks(state, now = Date.now()) {
1073
1982
  if (task.status !== 'done') continue
1074
1983
  task.status = 'archived'
1075
1984
  task.archivedAt = iso(now)
1985
+ if (task.workerRunState === 'running') task.workerRunState = 'ended'
1986
+ cleanupTaskWorktree(task)
1076
1987
  // §1.9:归档是终态——flagged 任务归档后不再等用户回答,清问题四字段(回答留档保留)。
1077
1988
  clearNeedsUserFields(task)
1078
1989
  task.updatedAt = iso(now)
@@ -1083,6 +1994,7 @@ export function archiveDoneTasks(state, now = Date.now()) {
1083
1994
 
1084
1995
  export function deleteTask(state, id) {
1085
1996
  const task = findTask(state, id)
1997
+ cleanupTaskWorktree(task)
1086
1998
  const index = state.tasks.indexOf(task)
1087
1999
  if (index >= 0) state.tasks.splice(index, 1)
1088
2000
  return task
@@ -1125,10 +2037,19 @@ export function archiveTimeOf(task) {
1125
2037
  * @param {number} [retentionMs] 保留期(默认 `ARCHIVE_RETENTION_MS`)
1126
2038
  * @returns {{removed:number, ids:string[]}} 删除数量与被删任务 id(board 顺序)
1127
2039
  */
1128
- export function pruneArchivedTasks(state, now = Date.now(), retentionMs = ARCHIVE_RETENTION_MS) {
2040
+ export function pruneArchivedTasks(state, now = Date.now(), retentionMs = undefined) {
1129
2041
  const outcome = { removed: 0, ids: [] }
1130
2042
  if (!isPlainObject(state) || !Array.isArray(state.tasks)) return outcome
1131
- const ttl = Number.isFinite(Number(retentionMs)) && Number(retentionMs) >= 0 ? Number(retentionMs) : ARCHIVE_RETENTION_MS
2043
+ let ttl = ARCHIVE_RETENTION_MS
2044
+ if (retentionMs !== undefined) {
2045
+ const explicit = Number(retentionMs)
2046
+ if (explicit === 0) return outcome
2047
+ if (Number.isFinite(explicit) && explicit > 0) ttl = explicit
2048
+ } else if (isPlainObject(state.config) && state.config.archiveRetentionMinutes !== undefined) {
2049
+ const minutes = normalizeConfig(state.config).archiveRetentionMinutes
2050
+ if (minutes === 0) return outcome
2051
+ ttl = minutes * 60 * 1000
2052
+ }
1132
2053
  const kept = []
1133
2054
  for (const task of state.tasks) {
1134
2055
  if (!isPlainObject(task) || task.status !== 'archived') {
@@ -1141,6 +2062,7 @@ export function pruneArchivedTasks(state, now = Date.now(), retentionMs = ARCHIV
1141
2062
  continue
1142
2063
  }
1143
2064
  if (now - archivedAt >= ttl) {
2065
+ cleanupTaskWorktree(task)
1144
2066
  outcome.ids.push(task.id)
1145
2067
  outcome.removed += 1
1146
2068
  continue
@@ -1180,6 +2102,8 @@ export function selectDispatchCandidates(state, now = Date.now()) {
1180
2102
  .filter((task) => task.status === 'todo')
1181
2103
  // §1.9:等待用户回答的任务不投递(问题没回答前重复派发只会让组长重复提问)。
1182
2104
  .filter((task) => task.needsUser !== true)
2105
+ // v0.4.0:存在未完成前置依赖(todo / doing)的任务不提前派发,防止抢跑(如前置迁移尚在 needsUser 待回复)。
2106
+ .filter((task) => unresolvedDependencies(state, task).length === 0)
1183
2107
  .filter((task) => task.notificationCount < config.maxNotifications)
1184
2108
  .filter((task) => {
1185
2109
  if (!task.notifiedAt) return true
@@ -1294,6 +2218,19 @@ export function requeueTasksOfLead(state, sessionId, now = Date.now(), exceptTas
1294
2218
  if (!task || task.status !== 'doing' || task.dispatchedSessionId !== sessionId) continue
1295
2219
  // v0.3.2:接管新组长时,正在派发的这张卡不属于「旧组长的遗留任务」,不要打回 todo。
1296
2220
  if (keepId !== '' && task.id === keepId) continue
2221
+ // v0.3.5:旧组长自动派出的内部子卡(切片 / 合并 / 验证子卡)不重排为独立 todo 任务——
2222
+ // 否则新组长既重做父任务、又把旧切片当独立任务再派一遍;直接归档留痕,由新组长统一接手父任务。
2223
+ if (task.autoDispatch === LEAD_AUTO_MARK && asString(task.parentTaskId) !== '') {
2224
+ cleanupTaskWorktree(task)
2225
+ task.status = 'archived'
2226
+ task.archivedAt = stamp
2227
+ task.workerRunState = null
2228
+ clearNeedsUserFields(task)
2229
+ task.lastError = '工作区组长会话已归档,旧内部子卡已归档;父任务已重新排队'
2230
+ task.updatedAt = stamp
2231
+ continue
2232
+ }
2233
+ cleanupTaskWorktree(task)
1297
2234
  task.status = 'todo'
1298
2235
  task.startedAt = null
1299
2236
  task.finishedAt = null
@@ -1429,6 +2366,9 @@ export function buildDispatchText(task, now = Date.now()) {
1429
2366
  const lines = ['【任务看板 · 待开始】' + task.id + ' ' + task.title]
1430
2367
  if (task.note) lines.push('备注:' + task.note)
1431
2368
  if (task.cwd) lines.push('工作目录:' + task.cwd)
2369
+ if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
2370
+ lines.push('前置依赖(已满足):' + task.dependsOn.join(', '))
2371
+ }
1432
2372
  // §1.9:todo 任务提问 → 用户回答 → 清标记后再派发时,组长可能在别的会话里,
1433
2373
  // 回答必须随派发文本带过去,不然「用户已经拍板」这件事会丢。
1434
2374
  if (typeof task.lastAnswer === 'string' && task.lastAnswer.trim() !== '') {
@@ -1436,14 +2376,21 @@ export function buildDispatchText(task, now = Date.now()) {
1436
2376
  }
1437
2377
  lines.push('')
1438
2378
  lines.push(
1439
- '请按派单规则处理这条看板任务:先用 taskboard_update 把它置为 doing,' +
1440
- '再派发子 Agent 执行(背景执行,不要自己在对话里等),然后结束本轮。' +
1441
- '如果这条任务可以拆成 ≥2 个写域不相交的独立片,按 persona 的 fan-out 规则一次派多个 worker;' +
1442
- '切片 worker 的 prompt 不要出现父任务 id / 标题,也不要写行首任务 id。' +
1443
- '子 Agent 回报后审核:通过就 taskboard_update 置为 done 并把结论写进 result;' +
2379
+ '请按派单规则处理这条看板任务:先用 taskboard_update 把它置为 doing;' +
2380
+ '若确认是 ≤2 个文件的纯文档 / 配置微调且无需跑任何终端测试/构建(Fast-path 小活直办),可直接用 edit/write 改完复读核验后当轮置 done;' +
2381
+ '凡需跑单测 / 构建 / 脚本验证或改业务代码的任务,派发子 Agent 执行(背景执行,不要自己在对话里等),然后结束本轮。' +
2382
+ '如果这条任务经只读探查确认可以拆成 ≥2 个写域严格不相交的独立片,按 persona 的 fan-out 规则一次派多个 worker:' +
2383
+ '每个切片 worker 的 description 带父任务 id(如「' +
2384
+ task.id +
2385
+ ' 切片 A · …」),prompt 行首显式写「父任务:' +
2386
+ task.id +
2387
+ '」(宿主会自动关联子卡、不吞父卡且不单独打扰主会话),收尾时用 taskboard_list {parentTaskId:"' +
2388
+ task.id +
2389
+ '"} 核对进度;若某张切片子卡 t-K 的 worker 报错或上下文爆满无法续跑、需换新 worker 接手,新 worker 的 prompt 行首写「任务 id:t-K」直接复用该子卡(或先将废卡 archived),不要把失败废卡留在 doing 列。' +
2390
+ '子 Agent 回报后审核:若该任务或子卡带有非空 worktreePath(隔离工作树),审核通过后必须调 taskboard_merge_worktree 将改动合入主工作区并清理临时分支;通过就 taskboard_update 置为 done 并把结论写进 result;' +
1444
2391
  '不通过就 send_message 打回同一个子 Agent 重做,任务保持 doing。' +
1445
- '写 result 时用 Markdown(小标题、- 列表、| 表格 |、`代码`),看板详情浮层会按 Markdown 渲染,' +
1446
- '一段大白话在详情里很难读。子 Agent 的汇报也要求同样的 Markdown 结构。',
2392
+ '写 result 与对话回复必须简短说人话:result 第 1 行直接写一句话人话结论(做成了什么、验证结果如何),下面最多列 3~5 条精炼要点;' +
2393
+ '非必要不画表格,严禁写「我已做的取证」等自证流水账或暴露 W1/W2/assignee=merging 等内部调度黑话;中间派单或波次过渡轮次的对话回复不超过 2 句话。',
1447
2394
  )
1448
2395
  if (task.notificationCount > 0) {
1449
2396
  lines.push('(这是第 ' + (task.notificationCount + 1) + ' 次提醒;任务仍未派发。)')
@@ -1850,7 +2797,7 @@ export function buildReceiptText(tasks, now = Date.now()) {
1850
2797
  lines.push('- ' + task.id + ' ' + task.title + ':' + (summary === '' ? '(无结论)' : summary))
1851
2798
  }
1852
2799
  lines.push('')
1853
- lines.push('请向用户汇总以上结论,不要重复执行任务。')
2800
+ lines.push('请用简洁自然的人话向用户汇总以上结论,不要重复执行任务。')
1854
2801
  lines.push('看板时间:' + localStamp(now))
1855
2802
  return lines.join('\n')
1856
2803
  }
@@ -1864,6 +2811,9 @@ export function selectReceiptTasks(state, limit = MAX_RECEIPT_BATCH) {
1864
2811
  const cap = Number.isFinite(Number(limit)) && Number(limit) > 0 ? Math.round(Number(limit)) : MAX_RECEIPT_BATCH
1865
2812
  return state.tasks
1866
2813
  .filter((task) => task && task.status === 'done' && !task.reportedAt)
2814
+ // v0.3.5(§1.6 / §1.8):带 parentTaskId 的内部自动子卡(fan-out 切片 / 合并 / 验证子卡)
2815
+ // 不单独唤醒主会话推送回执,等父任务最终 done 时向主会话发唯一一次汇总回执。
2816
+ .filter((task) => !(task.autoDispatch === LEAD_AUTO_MARK && asString(task.parentTaskId) !== ''))
1867
2817
  .sort((a, b) => {
1868
2818
  const at = Date.parse(a.updatedAt)
1869
2819
  const bt = Date.parse(b.updatedAt)
@@ -2022,6 +2972,12 @@ async function dispatchRpc(rt, method, payload) {
2022
2972
  const next = normalizeConfig({ ...normalizeConfig(rt.state.config), ...payload })
2023
2973
  const intervalChanged = next.pollIntervalMs !== normalizeConfig(rt.state.config).pollIntervalMs
2024
2974
  rt.state.config = next
2975
+ // v0.3.6:用户在设置里调短归档保留分钟数后,立即按新保留期清理一次已到期归档任务。
2976
+ try {
2977
+ pruneArchivedTasks(rt.state)
2978
+ } catch (error) {
2979
+ console.warn('[taskboard] 配置更新后归档清理失败:' + describeError(error))
2980
+ }
2025
2981
  commitBoard(rt.state, rt.filePath)
2026
2982
  if (intervalChanged) startPolling(rt)
2027
2983
  return { config: next }
@@ -2087,6 +3043,7 @@ const SKIP_TEXT = {
2087
3043
  'agent-busy': '目标会话正在运行,稍后再派',
2088
3044
  // v0.2.0 工作区组长路由(§1.5 跳过原因表;Client 用 poll.skip.<reason> 做 i18n)。
2089
3045
  'lead-busy': '工作区组长正在运行,等它空下来再派',
3046
+ 'lead-worker-busy': '本工作区已有任务正在执行或待组长验收,完成后再自动派发下一条',
2090
3047
  'lead-unavailable': '工作区组长不可用:稍后重试,或在看板点「创建组长」',
2091
3048
  'lead-no-workspace': '无法解析任务的工作区:请从目标工作区的会话里重新加这条任务',
2092
3049
  'creator-busy': '创建这条任务的对话正在运行,等它空下来再派',
@@ -2381,6 +3338,241 @@ function pruneArchivedBoard(rt, now = Date.now()) {
2381
3338
  return outcome.removed
2382
3339
  }
2383
3340
 
3341
+ /**
3342
+ * v0.5.2:卡住自动卡提醒的去重表(进程内 Set,不落盘)。键 = 任务 id + updatedAt——
3343
+ * 同一次「worker 已结束但卡片还停在 doing」只提醒一次;任务再有新的结束事件(updatedAt 变了)
3344
+ * 会重新提醒,不会因为历史去重而永久失声。
3345
+ */
3346
+ function stuckAlertedSet(rt) {
3347
+ if (!(rt.stuckAlerted instanceof Set)) rt.stuckAlerted = new Set()
3348
+ return rt.stuckAlerted
3349
+ }
3350
+
3351
+ function stuckAlertKey(task) {
3352
+ return asString(task && task.id) + '@' + asString(task && task.updatedAt)
3353
+ }
3354
+
3355
+ /**
3356
+ * v0.4.0:巡检并自愈失联的 `doing` 任务(进程重启掉线 / worker 异常退出未发 `subagent/end`)。
3357
+ *
3358
+ * 恢复策略(用户拍板口径):
3359
+ * - **顶层任务**(`parentTaskId` 为空且 `needsUser !== true`):自动回退 `todo` 重新排队接单(保留原 `note` / `result` / `dependsOn`),
3360
+ * `lastError` 写明失联重排原因;
3361
+ * - **内部切片子卡**(`autoDispatch === LEAD_AUTO_MARK` 且 `parentTaskId` 非空):保持 `doing`,标 `workerRunState = 'failed'`
3362
+ * 并写 `lastError`;若所属组长会话在线且 `idle`,合并发送一条「异常恢复」提醒交组长续做或归档。
3363
+ * - **v0.5.2 卡住提醒**:`doing` + `autoDispatch === LEAD_AUTO_MARK` + `workerRunState` 已经是
3364
+ * `'ended'` / `'failed'`(worker 结束事件处理过、但卡片因非 completed / 合入冲突 / 认领失败停在 doing)
3365
+ * + 超过 `ORPHAN_GRACE_MS` 没再更新 → 组长 `idle` 时发一条**一次性**提醒(卡 id / 卡在哪一步 /
3366
+ * lastError 摘要 / 处理提示)。**绝不自动改状态**(收尾与合入必须由组长判断),用 rt 上的内存 Set 去重。
3367
+ */
3368
+ export async function reconcileOrphanedDoingTasks(rt, options = {}) {
3369
+ const outcome = { requeued: 0, markedFailed: 0, reminded: 0, ids: [] }
3370
+ if (!rt || !rt.state || !Array.isArray(rt.state.tasks)) return outcome
3371
+ const startup = options.startup === true
3372
+ const now = Number.isFinite(Number(options.now)) ? Number(options.now) : Date.now()
3373
+ const graceMs = Number.isFinite(Number(options.graceMs)) ? Number(options.graceMs) : ORPHAN_GRACE_MS
3374
+ const agents = serviceOf(rt.ctx, 'agents')
3375
+ const subagents = serviceOf(rt.ctx, 'subagents')
3376
+ if (!startup && !agents && !subagents) return outcome
3377
+
3378
+ const descendantCache = new Map()
3379
+ const loadDescendants = async (parentId) => {
3380
+ if (!parentId || !subagents || typeof subagents.listDescendants !== 'function') return null
3381
+ if (descendantCache.has(parentId)) return descendantCache.get(parentId)
3382
+ try {
3383
+ const rows = await subagents.listDescendants(parentId)
3384
+ const list = Array.isArray(rows) ? rows : []
3385
+ descendantCache.set(parentId, list)
3386
+ return list
3387
+ } catch {
3388
+ descendantCache.set(parentId, null)
3389
+ return null
3390
+ }
3391
+ }
3392
+
3393
+ const stamp = iso(now)
3394
+ const leadAlerts = new Map()
3395
+ // v0.5.2:worker 已结束但卡片仍在 doing 的自动卡(只提醒,不改状态)。
3396
+ const stuckAlerts = new Map()
3397
+ let changed = false
3398
+
3399
+ for (const task of rt.state.tasks) {
3400
+ if (!task || task.status !== 'doing' || task.needsUser === true) continue
3401
+ const lastMs = Date.parse(asString(task.updatedAt) || asString(task.startedAt) || asString(task.createdAt))
3402
+ const ageMs = Number.isFinite(lastMs) ? now - lastMs : 0
3403
+ let orphaned = false
3404
+
3405
+ if (task.workerRunState === 'running') {
3406
+ if (startup) {
3407
+ orphaned = true
3408
+ } else if (ageMs >= graceMs) {
3409
+ const workerId = asString(task.workerSessionId).trim()
3410
+ const parentId = asString(task.dispatchedSessionId || task.sessionId).trim()
3411
+ const liveWorker = workerId !== '' ? liveAgentOf(agents, workerId) : undefined
3412
+ if (liveWorker) {
3413
+ if (liveWorker.status !== 'running') orphaned = true
3414
+ } else if (subagents && typeof subagents.listDescendants === 'function') {
3415
+ if (parentId !== '') {
3416
+ const rows = await loadDescendants(parentId)
3417
+ if (Array.isArray(rows)) {
3418
+ const hit =
3419
+ workerId !== ''
3420
+ ? rows.find((r) => r && asString(r.id).trim() === workerId)
3421
+ : asString(task.assignee) !== ''
3422
+ ? rows.find((r) => r && asString(r.name).trim() === asString(task.assignee).trim())
3423
+ : null
3424
+ const childAgent = hit && asString(hit.id).trim() !== '' ? liveAgentOf(agents, asString(hit.id).trim()) : undefined
3425
+ if (!hit || (agents && typeof agents.get === 'function' && (!childAgent || childAgent.status !== 'running'))) {
3426
+ orphaned = true
3427
+ }
3428
+ }
3429
+ } else if (workerId !== '' && agents && typeof agents.get === 'function') {
3430
+ orphaned = true
3431
+ }
3432
+ }
3433
+ }
3434
+ } else if (
3435
+ startup &&
3436
+ task.workerRunState === null &&
3437
+ asString(task.parentTaskId) === '' &&
3438
+ ageMs > LEAD_IN_FLIGHT_TTL_MS &&
3439
+ !taskHasActiveSubtasks(rt.state, task.id)
3440
+ ) {
3441
+ orphaned = true
3442
+ }
3443
+
3444
+ if (!orphaned) {
3445
+ if (
3446
+ task.autoDispatch === LEAD_AUTO_MARK &&
3447
+ (task.workerRunState === 'ended' || task.workerRunState === 'failed') &&
3448
+ ageMs >= graceMs
3449
+ ) {
3450
+ const leadId = asString(task.dispatchedSessionId || task.sessionId).trim()
3451
+ if (leadId !== '') {
3452
+ const list = stuckAlerts.get(leadId) || []
3453
+ list.push(task)
3454
+ stuckAlerts.set(leadId, list)
3455
+ }
3456
+ }
3457
+ continue
3458
+ }
3459
+ changed = true
3460
+ outcome.ids.push(task.id)
3461
+
3462
+ const isSubtask = task.autoDispatch === LEAD_AUTO_MARK && asString(task.parentTaskId) !== ''
3463
+ if (isSubtask) {
3464
+ task.workerRunState = 'failed'
3465
+ task.lastError = '执行会话已失联(宿主重启或异常退出),等待组长续做或归档'
3466
+ task.updatedAt = stamp
3467
+ outcome.markedFailed += 1
3468
+ const leadId = asString(task.dispatchedSessionId || task.sessionId).trim()
3469
+ if (leadId !== '') {
3470
+ const list = leadAlerts.get(leadId) || []
3471
+ list.push(task)
3472
+ leadAlerts.set(leadId, list)
3473
+ }
3474
+ } else {
3475
+ cleanupTaskWorktree(task)
3476
+ task.status = 'todo'
3477
+ task.startedAt = null
3478
+ task.finishedAt = null
3479
+ task.notifiedAt = null
3480
+ task.notificationCount = 0
3481
+ task.assignee = ''
3482
+ task.workerSessionId = null
3483
+ task.workerRunState = null
3484
+ task.dispatchedSessionId = null
3485
+ task.dispatchedSessionTitle = ''
3486
+ task.autoDispatch = null
3487
+ task.lastError = '上次执行会话已失联(宿主重启或异常退出),已自动回退待开始重新接单'
3488
+ task.updatedAt = stamp
3489
+ outcome.requeued += 1
3490
+ }
3491
+ }
3492
+
3493
+ if (changed) {
3494
+ commitBoard(rt.state, rt.filePath)
3495
+ console.warn(
3496
+ '[taskboard] 失联 doing 任务自愈:回退待开始 ' +
3497
+ outcome.requeued +
3498
+ ' 条,切片标 failed ' +
3499
+ outcome.markedFailed +
3500
+ ' 条(' +
3501
+ outcome.ids.join(', ') +
3502
+ ')',
3503
+ )
3504
+ }
3505
+
3506
+ if (!startup && leadAlerts.size > 0 && agents) {
3507
+ const archived = archivedSessionIdSet(rt)
3508
+ for (const [leadId, failedSlices] of leadAlerts.entries()) {
3509
+ if (archived.has(leadId)) continue
3510
+ const leadAgent = liveAgentOf(agents, leadId)
3511
+ if (!leadAgent || leadAgent.status !== 'idle') continue
3512
+ const lines = ['【任务看板 · 异常恢复】检测到以下并行子卡的执行会话已失联中断(已标为 failed):']
3513
+ for (const item of failedSlices) {
3514
+ lines.push('- ' + item.id + '(父任务:' + item.parentTaskId + ')' + item.title)
3515
+ }
3516
+ lines.push('请检查工作区现有改动后决定:需续做的在新 worker prompt 行首写「任务 id:<子卡id>」复用接管,不再需要的用 taskboard_update 置 archived。')
3517
+ try {
3518
+ leadAgent.followup(createBoardUserMessage(lines.join('\n')))
3519
+ const sessions = serviceOf(rt.ctx, 'sessions')
3520
+ if (sessions && typeof sessions.flush === 'function') await sessions.flush(leadAgent.session)
3521
+ } catch (error) {
3522
+ console.warn('[taskboard] 发送失联子卡恢复提醒失败:' + describeError(error))
3523
+ }
3524
+ }
3525
+ }
3526
+
3527
+ // v0.5.2:worker 已经结束、卡片却还停在 doing(非 completed / 合入冲突 / 认领失败)时,
3528
+ // 组长 idle 就发一条一次性提醒——绝不自动改状态,只把「卡在哪一步 + 原因 + 怎么收尾」说清楚。
3529
+ if (!startup && stuckAlerts.size > 0 && agents) {
3530
+ const archived = archivedSessionIdSet(rt)
3531
+ const reminded = stuckAlertedSet(rt)
3532
+ for (const [leadId, stuckTasks] of stuckAlerts.entries()) {
3533
+ if (archived.has(leadId)) continue
3534
+ const leadAgent = liveAgentOf(agents, leadId)
3535
+ if (!leadAgent || leadAgent.status !== 'idle') continue
3536
+ const pending = stuckTasks.filter((task) => !reminded.has(stuckAlertKey(task)))
3537
+ if (pending.length === 0) continue
3538
+ const lines = [
3539
+ '【任务看板 · 卡住提醒】以下自动卡的任务已经结束,但看板还停在「进行中」(宿主不会自动改状态):',
3540
+ ]
3541
+ for (const item of pending) {
3542
+ const step =
3543
+ (asString(item.parentTaskId) === '' ? '顶层任务' : '切片 · 父任务 ' + item.parentTaskId) +
3544
+ ' · worker 已结束(' +
3545
+ asString(item.workerRunState) +
3546
+ ')'
3547
+ const reason = trimmed(item.lastError, 200)
3548
+ lines.push('- ' + item.id + '(' + step + ')' + item.title + (reason === '' ? '' : ' · ' + reason))
3549
+ if (asString(item.worktreePath) !== '') {
3550
+ lines.push(' 隔离工作树还没合入:' + item.worktreePath + '(先 taskboard_merge_worktree 处理冲突 / 合入)')
3551
+ }
3552
+ }
3553
+ lines.push(
3554
+ '请核对后收尾:直接 taskboard_update {id, status:"done", result:"…"};若挂有隔离工作树,先 taskboard_merge_worktree 合入(或传 discardOnly:true 回收)。宿主不会自动改状态。',
3555
+ )
3556
+ try {
3557
+ leadAgent.followup(createBoardUserMessage(lines.join('\n')))
3558
+ const sessions = serviceOf(rt.ctx, 'sessions')
3559
+ if (sessions && typeof sessions.flush === 'function') await sessions.flush(leadAgent.session)
3560
+ for (const item of pending) {
3561
+ reminded.add(stuckAlertKey(item))
3562
+ outcome.reminded += 1
3563
+ }
3564
+ console.warn(
3565
+ '[taskboard] 已提醒组长处理卡住的自动卡:' + pending.map((item) => item.id).join('、'),
3566
+ )
3567
+ } catch (error) {
3568
+ console.warn('[taskboard] 发送卡住自动卡提醒失败:' + describeError(error))
3569
+ }
3570
+ }
3571
+ }
3572
+
3573
+ return outcome
3574
+ }
3575
+
2384
3576
  /**
2385
3577
  * 轮询派单入口。每次 tick 末尾都会尝试 flush 一次完成回执(§1.6):
2386
3578
  * 回执投递不占用派发名额(未绑定主会话 / 主会话忙或离线时是 no-op)。
@@ -2401,6 +3593,13 @@ async function runTick(rt, options = {}) {
2401
3593
  rt.poll.lastRunAt = iso(now)
2402
3594
  // 归档清理(§1.2)必须在 pollEnabled 判断之前:暂停派发时归档仍要按时删除。
2403
3595
  pruneArchivedBoard(rt, now)
3596
+ if (!options.taskId) {
3597
+ try {
3598
+ await reconcileOrphanedDoingTasks(rt, { startup: false, now })
3599
+ } catch (error) {
3600
+ console.warn('[taskboard] 失联任务巡检失败:' + describeError(error))
3601
+ }
3602
+ }
2404
3603
  const config = normalizeConfig(rt.state.config)
2405
3604
  if (!config.pollEnabled && !options.taskId) {
2406
3605
  rt.poll.lastSkipReason = 'poll-disabled'
@@ -2414,6 +3613,13 @@ async function runTick(rt, options = {}) {
2414
3613
  if (single.needsUser === true) {
2415
3614
  throw new BoardError('conflict', '任务正在等待用户回复(needsUser),回答后才能继续派发')
2416
3615
  }
3616
+ const blockingDeps = unresolvedDependencies(rt.state, single)
3617
+ if (blockingDeps.length > 0) {
3618
+ throw new BoardError(
3619
+ 'conflict',
3620
+ '前置任务尚未完成(' + blockingDeps.join(', ') + '),请先完成前置任务或移除依赖后再派发',
3621
+ )
3622
+ }
2417
3623
  candidates = [single]
2418
3624
  } else {
2419
3625
  candidates = selectDispatchCandidates(rt.state, now)
@@ -2485,12 +3691,14 @@ async function runTick(rt, options = {}) {
2485
3691
  * followup + sessions.flush 成功后置 doing、记通知与 dispatchedSession*、清 lastError。
2486
3692
  */
2487
3693
  async function deliverBoardTask(rt, task, agent, now) {
3694
+ const taskId = task.id
2488
3695
  const sessionId = agentSessionId(agent)
2489
3696
  // 创建时没能解析出工作区(会话还没 live)→ 投递前从目标会话补一次,派发文本就能带上工作目录。
2490
3697
  if (!task.cwd) {
2491
3698
  const cwd = sessionCwd(agent)
2492
3699
  if (cwd) task.cwd = cwd
2493
3700
  }
3701
+ const resolvedCwd = task.cwd
2494
3702
  const message = createBoardUserMessage(buildDispatchText(task, now))
2495
3703
  try {
2496
3704
  agent.followup(message)
@@ -2503,32 +3711,35 @@ async function deliverBoardTask(rt, task, agent, now) {
2503
3711
  console.warn('[taskboard] 会话 flush 失败(消息已入队):' + describeError(flushError))
2504
3712
  }
2505
3713
  } catch (error) {
3714
+ const current = taskById(rt.state, taskId) || task
2506
3715
  rt.poll.lastSkipReason = 'followup-failed'
2507
- task.lastError = skipText('followup-failed') + ':' + describeError(error)
2508
- task.updatedAt = iso(now)
3716
+ current.lastError = skipText('followup-failed') + ':' + describeError(error)
3717
+ current.updatedAt = iso(now)
2509
3718
  commitBoard(rt.state, rt.filePath)
2510
3719
  console.warn('[taskboard] 派发失败:' + describeError(error))
2511
3720
  return { dispatched: false, reason: 'followup-failed', error: describeError(error) }
2512
3721
  }
2513
- task.notifiedAt = iso(now)
2514
- task.notificationCount = (Number(task.notificationCount) || 0) + 1
2515
- task.updatedAt = iso(now)
2516
- task.lastError = ''
3722
+ const target = taskById(rt.state, taskId) || task
3723
+ if (!target.cwd && resolvedCwd) target.cwd = resolvedCwd
3724
+ target.notifiedAt = iso(now)
3725
+ target.notificationCount = (Number(target.notificationCount) || 0) + 1
3726
+ target.updatedAt = iso(now)
3727
+ target.lastError = ''
2517
3728
  // 投递成功即视为「进行中」:看板立刻反映已派发,不再依赖主 Agent 记得调 taskboard_update
2518
3729
  // (它照样可以再调一次 doing,迁移 doing→doing 合法)。
2519
- if (task.status === 'todo') {
2520
- task.status = 'doing'
2521
- if (!task.startedAt) task.startedAt = iso(now)
3730
+ if (target.status === 'todo') {
3731
+ target.status = 'doing'
3732
+ if (!target.startedAt) target.startedAt = iso(now)
2522
3733
  }
2523
3734
  rt.poll.lastDispatchAt = iso(now)
2524
3735
  rt.poll.lastDispatchSessionId = sessionId
2525
3736
  rt.poll.lastDispatchSessionTitle = sessionTitle(agent)
2526
- task.dispatchedSessionId = sessionId
2527
- task.dispatchedSessionTitle = sessionTitle(agent) || ''
2528
- rt.poll.lastDispatchTaskId = task.id
3737
+ target.dispatchedSessionId = sessionId
3738
+ target.dispatchedSessionTitle = sessionTitle(agent) || ''
3739
+ rt.poll.lastDispatchTaskId = target.id
2529
3740
  rt.poll.lastSkipReason = null
2530
3741
  commitBoard(rt.state, rt.filePath)
2531
- return { dispatched: true, sessionId, task: { ...task } }
3742
+ return { dispatched: true, sessionId, task: { ...target } }
2532
3743
  }
2533
3744
 
2534
3745
  /** 「用户回复」followup 文本(§1.9):任务仍在原状态,要求组长接着处理。 */
@@ -2575,8 +3786,13 @@ export async function answerTask(rt, id, answer, now = Date.now()) {
2575
3786
  }
2576
3787
  /** 失败统一收尾:保留 flagged 状态,把原因写进任务 lastError 并落盘,再抛给 RPC。 */
2577
3788
  const fail = (code, message) => {
2578
- task.lastError = message
2579
- task.updatedAt = iso(now)
3789
+ const current = taskById(rt.state, task.id) || task
3790
+ current.lastError = message
3791
+ current.updatedAt = iso(now)
3792
+ if (current !== task) {
3793
+ task.lastError = message
3794
+ task.updatedAt = current.updatedAt
3795
+ }
2580
3796
  commitBoard(rt.state, rt.filePath)
2581
3797
  return new BoardError(code, message)
2582
3798
  }
@@ -2614,13 +3830,16 @@ export async function answerTask(rt, id, answer, now = Date.now()) {
2614
3830
  throw fail('internal', '回复发送失败:' + describeError(error))
2615
3831
  }
2616
3832
  const stamp = iso(now)
2617
- clearNeedsUserFields(task)
2618
- task.lastAnswer = text
2619
- task.answeredAt = stamp
2620
- task.lastError = ''
2621
- task.updatedAt = stamp
3833
+ const target = taskById(rt.state, task.id) || task
3834
+ for (const item of target === task ? [target] : [target, task]) {
3835
+ clearNeedsUserFields(item)
3836
+ item.lastAnswer = text
3837
+ item.answeredAt = stamp
3838
+ item.lastError = ''
3839
+ item.updatedAt = stamp
3840
+ }
2622
3841
  commitBoard(rt.state, rt.filePath)
2623
- return { task: { ...task }, sessionId }
3842
+ return { task: { ...target }, sessionId }
2624
3843
  }
2625
3844
 
2626
3845
  /** RPC `bind-main-session`(§3.1.1):绑定完成回执收件人;不要求会话当前在线。 */
@@ -2814,7 +4033,11 @@ export async function flushReceipts(rt, now = Date.now()) {
2814
4033
  console.warn('[taskboard] 完成回执投递失败:' + describeError(error))
2815
4034
  return { sent: false, reason: 'followup-failed' }
2816
4035
  }
2817
- for (const task of batch) task.reportedAt = stamp
4036
+ for (const task of batch) {
4037
+ task.reportedAt = stamp
4038
+ const current = taskById(rt.state, task.id)
4039
+ if (current && current !== task) current.reportedAt = stamp
4040
+ }
2818
4041
  commitBoard(rt.state, rt.filePath)
2819
4042
  return { sent: true, count: batch.length, sessionId: config.mainSessionId }
2820
4043
  } finally {
@@ -2822,6 +4045,64 @@ export async function flushReceipts(rt, now = Date.now()) {
2822
4045
  }
2823
4046
  }
2824
4047
 
4048
+ /**
4049
+ * v0.3.9 + v0.5.0:该工作区当前是否因在途执行而需要阻塞新任务派发。
4050
+ *
4051
+ * - 当 `config.worktreeIsolation !== false` 且 `cwd` 是有效 Git 仓库(`resolveGitRepoInfo(cwd) !== null`)时:
4052
+ * 支持各任务独占独立 Git Worktree **真并发执行**!仅在以下情况阻塞:
4053
+ * ① 有任务处于主工作区合并/全量验证阶段(`assignee === 'merging'`);
4054
+ * ② 有未挂载 `worktreePath` 的任务直接在主工作区运行 worker(或已完成待主工作区复核);
4055
+ * ③ 该工作区当前同时运行的隔离 Worktree worker 数已达上限 `MAX_CONCURRENT_WORKTREES`(4)。
4056
+ * - 当非 Git 目录或 `config.worktreeIsolation === false` 时:退回单目录严格串行保护(v0.3.9)。
4057
+ */
4058
+ export function hasActiveWorkspaceExecution(state, leadSessionId = '', cwd = '', now = Date.now()) {
4059
+ if (!state || !Array.isArray(state.tasks)) return false
4060
+ const leadId = typeof leadSessionId === 'string' ? leadSessionId.trim() : ''
4061
+ const wantCwd = typeof cwd === 'string' && cwd !== '' ? normalizePathForCompare(cwd) : ''
4062
+ if (leadId === '' && wantCwd === '') return false
4063
+
4064
+ const cfg = normalizeConfig(state.config)
4065
+ const canIsolate =
4066
+ cfg.worktreeIsolation !== false && typeof cwd === 'string' && cwd.trim() !== '' && resolveGitRepoInfo(cwd, { now }) !== null
4067
+
4068
+ let isolatedRunning = 0
4069
+ for (const task of state.tasks) {
4070
+ if (!task || task.status !== 'doing' || task.needsUser === true) continue
4071
+ const sameLead = leadId !== '' && asString(task.dispatchedSessionId) === leadId
4072
+ const sameCwd = wantCwd !== '' && typeof task.cwd === 'string' && normalizePathForCompare(task.cwd) === wantCwd
4073
+ if (!sameLead && !sameCwd) continue
4074
+ const stamp = Date.parse(asString(task.updatedAt) || asString(task.startedAt) || asString(task.createdAt))
4075
+ if (Number.isFinite(stamp) && now - stamp > LEAD_IN_FLIGHT_TTL_MS) continue
4076
+
4077
+ const isMerging = asString(task.assignee).trim() === 'merging'
4078
+ if (isMerging) return true
4079
+
4080
+ const hasWorktree = asString(task.worktreePath).trim() !== ''
4081
+ if (!canIsolate) {
4082
+ if (task.workerRunState === 'running') return true
4083
+ if (task.autoDispatch !== LEAD_AUTO_MARK && task.workerRunState === 'ended') return true
4084
+ continue
4085
+ }
4086
+
4087
+ // Git Worktree 并发模式:主目录裸跑任务仍串行保护;挂载了独立 worktreePath 的任务允许并发至 MAX_CONCURRENT_WORKTREES。
4088
+ if (task.workerRunState === 'running') {
4089
+ if (!hasWorktree) return true
4090
+ isolatedRunning += 1
4091
+ if (isolatedRunning >= MAX_CONCURRENT_WORKTREES) return true
4092
+ continue
4093
+ }
4094
+ if (
4095
+ task.autoDispatch !== LEAD_AUTO_MARK &&
4096
+ task.workerRunState === 'ended' &&
4097
+ !hasWorktree &&
4098
+ !taskHasActiveSubtasks(state, task.id)
4099
+ ) {
4100
+ return true
4101
+ }
4102
+ }
4103
+ return false
4104
+ }
4105
+
2825
4106
  /**
2826
4107
  * 工作区组长路由(§1.5):解析任务 cwd → 工作区 key → 复用/创建常驻组长。
2827
4108
  * 绝不 createDispatchSession(每任务新建),也绝不跨工作区改派。
@@ -2855,6 +4136,9 @@ async function routeWorkspaceLead(rt, task, config, agents, options, now) {
2855
4136
  if (!agent) return { ok: false, reason: 'lead-unavailable' }
2856
4137
  // force(立即派发)时组长忙也把消息排进它的下一轮,与旧模式 creator-busy 的 force 语义一致。
2857
4138
  if (agent.status !== 'idle' && options.force !== true) return { ok: false, reason: 'lead-busy' }
4139
+ if (options.force !== true && hasActiveWorkspaceExecution(rt.state, mapping.sessionId, cwd, now)) {
4140
+ return { ok: false, reason: 'lead-worker-busy' }
4141
+ }
2858
4142
  return { ok: true, agent, key }
2859
4143
  }
2860
4144
  // 没有映射 → 懒创建本工作区的常驻组长(一个工作区一个,不是每任务一个)。
@@ -2867,6 +4151,9 @@ async function routeWorkspaceLead(rt, task, config, agents, options, now) {
2867
4151
  if (created.entry) config.workspaceLeads = putWorkspaceLead(config.workspaceLeads, key, created.entry)
2868
4152
  if (!created.agent) return { ok: false, reason: 'lead-unavailable' }
2869
4153
  if (created.agent.status !== 'idle' && options.force !== true) return { ok: false, reason: 'lead-busy' }
4154
+ if (options.force !== true && hasActiveWorkspaceExecution(rt.state, created.entry && created.entry.sessionId, cwd, now)) {
4155
+ return { ok: false, reason: 'lead-worker-busy' }
4156
+ }
2870
4157
  return { ok: true, agent: created.agent, key }
2871
4158
  }
2872
4159
 
@@ -3185,15 +4472,71 @@ export function looksLikeSessionId(value) {
3185
4472
  return SESSION_ID_PATTERN.test(text)
3186
4473
  }
3187
4474
 
4475
+ /**
4476
+ * v0.3.5:派发 prompt 行首显式声明的「父任务:t-N」/「父卡:t-N」(fan-out 切片 / 合并 / 验证子卡)。
4477
+ * 命中后闸门直接走新建子卡并关联 `parentTaskId`,绝不误吞父卡,彻底替代旧版「prompt 严禁提父卡」的文字禁区。
4478
+ */
4479
+ export function dispatchExplicitParentId(text) {
4480
+ for (const line of normalizeDispatchLines(text)) {
4481
+ const match = /^(?:父任务|父卡) *(?:id *)?: *(t-[0-9]{1,6})(?![0-9])/i.exec(line)
4482
+ if (!match) continue
4483
+ const id = match[1].toLowerCase()
4484
+ const rest = line.slice(match[0].length)
4485
+ if (taskIdsInDispatchLine(rest).some((other) => other.toLowerCase() !== id)) continue
4486
+ return id
4487
+ }
4488
+ return ''
4489
+ }
4490
+
4491
+ /** 某张任务名下是否已经存在未归档子卡(已拆片的父卡不得再被「看板任务:t-N」引用抢占)。 */
4492
+ export function taskHasActiveSubtasks(state, parentId) {
4493
+ const id = normalizeParentTaskId(parentId)
4494
+ if (!id || !state || !Array.isArray(state.tasks)) return false
4495
+ return state.tasks.some(
4496
+ (item) => item && item.status !== 'archived' && normalizeParentTaskId(item.parentTaskId) === id,
4497
+ )
4498
+ }
4499
+
4500
+ /**
4501
+ * v0.3.5:当闸门已确定要新建一张自动卡(未复用已有卡)时,推导它的所属父任务 id:
4502
+ * 优先级:行首 `父任务:t-N` → `description` 中的首个 `t-N`(兼容 v0.3.3 切片写法与 `验证 t-1`)
4503
+ * → 未能复用的 `看板任务:t-N` 引用(如对正在运行或已拆片的 `t-1` 派出的验证 / 合并 worker)。
4504
+ * 只有该 `t-N` 在板内真实存在且未归档时才采用。
4505
+ */
4506
+ export function inferParentTaskIdForAutoCard(args, state) {
4507
+ if (!state || !Array.isArray(state.tasks)) return null
4508
+ const prompt = subagentPromptText(args)
4509
+ const description = isPlainObject(args) ? asString(args.description) : ''
4510
+ const candidates = []
4511
+ const explicitParent = dispatchExplicitParentId(prompt)
4512
+ if (explicitParent !== '') candidates.push(explicitParent)
4513
+ if (description !== '') {
4514
+ const descMatch = /(?:^|[^A-Za-z0-9_-])(t-[0-9]{1,6})(?![0-9])/i.exec(description)
4515
+ if (descMatch) candidates.push(descMatch[1].toLowerCase())
4516
+ }
4517
+ const refId = dispatchReferencedTaskId(prompt)
4518
+ if (refId !== '') candidates.push(refId)
4519
+ for (const candidateId of candidates) {
4520
+ const parent = taskById(state, candidateId)
4521
+ if (parent && parent.status !== 'archived') return parent.id
4522
+ }
4523
+ return null
4524
+ }
4525
+
3188
4526
  /**
3189
4527
  * 「看板任务:t-N」提到的卡片能否被这次派发认领:
3190
4528
  * - 必须在待做 / 进行中(做完 / 归档的任务不抢);
4529
+ * - 名下不能已有未归档子卡(已进入 fan-out 的父卡不能被后续合并 / 验证子 Agent 误抢占);
4530
+ * - 当前没有正在跑的 worker(`workerRunState !== 'running'`:v0.3.1 起 `assignee` 是 worker 名字,
4531
+ * 只看 `looksLikeSessionId(assignee)` 会漏掉正在跑的 worker,导致验证子 Agent 抢占原卡);
3191
4532
  * - 还没挂真实 worker 会话 id(已挂 = 已有 worker 在干,这次多半是验证子 Agent / 另一个 worker,
3192
4533
  * 应该有自己的卡片;自由文本 assignee 如 `taskboard-worker` 不算)。
3193
4534
  */
3194
- export function canReuseMentionedTask(task) {
4535
+ export function canReuseMentionedTask(task, state = null) {
3195
4536
  if (!task) return false
3196
4537
  if (task.status !== 'todo' && task.status !== 'doing') return false
4538
+ if (task.workerRunState === 'running') return false
4539
+ if (state && taskHasActiveSubtasks(state, task.id)) return false
3197
4540
  return !looksLikeSessionId(task.assignee)
3198
4541
  }
3199
4542
 
@@ -3213,8 +4556,8 @@ export function takePreparedDispatch(rt, exec) {
3213
4556
 
3214
4557
  /**
3215
4558
  * §1.8(0.2.4):组长把轮询投递任务置 doing → 记一条「即将为它派 worker」的意图(不落盘)。
3216
- * 只在任务当前 `assignee === ''`(还没挂 worker)时记录:worker 已经挂上后再改 doing 不算新意图,
3217
- * 避免把后续直聊派活错误并进旧任务。
4559
+ * 只在任务当前未挂 worker 且未挂提问(`assignee === ''`、`workerRunState !== 'running'`、`needsUser !== true`)
4560
+ * 时记录:worker 已挂上或正在等用户回复时不算新派发意图,避免把后续直聊派活错误并进旧任务。
3218
4561
  */
3219
4562
  export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
3220
4563
  try {
@@ -3226,7 +4569,7 @@ export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
3226
4569
  if (!task) return false
3227
4570
  if (task.status !== 'doing' || asString(task.notifiedAt) === '') return false
3228
4571
  if (task.dispatchedSessionId !== leadId) return false
3229
- if (task.assignee !== '') return false
4572
+ if (task.assignee !== '' || task.workerRunState === 'running' || task.needsUser === true) return false
3230
4573
  if (!(rt.leadDispatchIntent instanceof Map)) rt.leadDispatchIntent = new Map()
3231
4574
  rt.leadDispatchIntent.set(leadId, { taskId: task.id, at: now })
3232
4575
  return true
@@ -3235,7 +4578,7 @@ export function noteLeadDispatchIntent(rt, agent, taskId, now = Date.now()) {
3235
4578
  }
3236
4579
  }
3237
4580
 
3238
- /** 取走(一次性)该组长的派发意图;过期 / 任务状态不符 → 作废。 */
4581
+ /** 取走(一次性)该组长的派发意图;过期 / 任务状态不符 / 已挂 running worker / 正在等用户回复 → 作废。 */
3239
4582
  function takeLeadDispatchIntent(rt, leadId, now) {
3240
4583
  if (!leadId || !(rt.leadDispatchIntent instanceof Map)) return null
3241
4584
  const entry = rt.leadDispatchIntent.get(leadId)
@@ -3244,12 +4587,15 @@ function takeLeadDispatchIntent(rt, leadId, now) {
3244
4587
  if (!Number.isFinite(entry.at) || now - entry.at > LEAD_DISPATCH_INTENT_MS) return null
3245
4588
  const task = taskById(rt.state, entry.taskId)
3246
4589
  if (!task || task.status !== 'doing' || asString(task.notifiedAt) === '') return null
4590
+ if (task.workerRunState === 'running' || task.needsUser === true) return null
3247
4591
  return task
3248
4592
  }
3249
4593
 
3250
4594
  /**
3251
4595
  * 这次派发的 prompt 是否真的指向这条任务(任务 id 或标题出现在 prompt 里)。
3252
4596
  * 用来防止「组长刚给 t-68 记了派发意图」的**下一条无关直聊派发**把 t-68 认领走(t-69 事故的变体)。
4597
+ * v0.3.3 补充:如果 `description` 显式带了父任务 id(如 `t-107 切片 A`)而 `prompt` 没有带该任务 id,
4598
+ * 这是并行 fan-out 的切片 worker——即使 prompt 碰巧包含父任务短标题,也不能把父卡认领走。
3253
4599
  */
3254
4600
  export function dispatchMentionsTask(args, task) {
3255
4601
  if (!task) return false
@@ -3258,7 +4604,10 @@ export function dispatchMentionsTask(args, task) {
3258
4604
  const id = asString(task.id)
3259
4605
  if (id !== '') {
3260
4606
  const escaped = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
3261
- if (new RegExp('(^|[^A-Za-z0-9_-])' + escaped + '([^A-Za-z0-9_-]|$)').test(prompt)) return true
4607
+ const idPattern = new RegExp('(^|[^A-Za-z0-9_-])' + escaped + '([^A-Za-z0-9_-]|$)')
4608
+ if (idPattern.test(prompt)) return true
4609
+ const description = isPlainObject(args) ? asString(args.description) : ''
4610
+ if (description !== '' && idPattern.test(description)) return false
3262
4611
  }
3263
4612
  const title = asString(task.title).trim()
3264
4613
  return title.length >= 4 && prompt.includes(title)
@@ -3270,7 +4619,14 @@ export function findPendingDispatchCard(state, leadId, title, note, now = Date.n
3270
4619
  for (let i = state.tasks.length - 1; i >= 0; i -= 1) {
3271
4620
  const task = state.tasks[i]
3272
4621
  if (!task || task.autoDispatch !== LEAD_AUTO_MARK) continue
3273
- if (task.status !== 'doing' || task.assignee !== '') continue
4622
+ if (
4623
+ task.status !== 'doing' ||
4624
+ task.assignee !== '' ||
4625
+ task.workerRunState !== null ||
4626
+ asString(task.workerSessionId) !== ''
4627
+ ) {
4628
+ continue
4629
+ }
3274
4630
  if (task.dispatchedSessionId !== leadId) continue
3275
4631
  if (task.title !== title || (task.note || '') !== (note || '')) continue
3276
4632
  const stamp = Date.parse(asString(task.createdAt))
@@ -3355,30 +4711,53 @@ export function prepareLeadDispatch(rt, input, now = Date.now()) {
3355
4711
  // 0) 一次性消费「组长刚置 doing」的意图:即使这次靠显式任务 id 认领,也要把它清掉,
3356
4712
  // 否则陈旧的 t-68 意图会在下一次无关的直聊派发里把旧任务认领走(t-69 事故的变体)。
3357
4713
  const intent = takeLeadDispatchIntent(rt, leadId, now)
3358
- // 1) 显式任务 id(prompt 里的「任务 id:t-N」)优先:轮询任务的 worker / 返工都靠它认领。
3359
- const explicitId = dispatchTaskIdFromPrompt(subagentPromptText(args))
3360
- const explicit = explicitId === '' ? null : taskById(rt.state, explicitId)
3361
- if (explicit && explicit.status !== 'archived') {
3362
- return finishPreparedDispatch(rt, auto, store, exec, explicit, false, 'task-id', now)
3363
- }
3364
- // 1b) 「看板任务:t-N」式引用(0.2.4):组长直聊派活时手动建了卡、prompt 用这种写法也要认领,
3365
- // 否则会为同一件事建两张卡。只认领待做 / 进行中且还没挂真实 worker 的卡片。
3366
- const referencedId = dispatchReferencedTaskId(subagentPromptText(args))
3367
- const referenced = referencedId === '' ? null : taskById(rt.state, referencedId)
3368
- if (referenced && canReuseMentionedTask(referenced)) {
3369
- return finishPreparedDispatch(rt, auto, store, exec, referenced, false, 'task-id-mention', now)
3370
- }
3371
- // 2) 组长刚把某条轮询任务置 doing → 这次派发就是它的 worker(要求 prompt 真的指向那条任务)。
3372
- if (intent && dispatchMentionsTask(args, intent)) {
3373
- return finishPreparedDispatch(rt, auto, store, exec, intent, false, 'lead-intent', now)
4714
+ const promptText = subagentPromptText(args)
4715
+ // 0b) v0.3.5 + v0.3.9:先提取行首显式 `任务 id:t-K` 与 `父任务:t-N`。
4716
+ // - 若明确指定了 `任务 id:t-K` 且不等于 `父任务:t-N`(包括续做接管某张失败子卡时同时写两行的场景),
4717
+ // 直接按 `task-id` 复用 `t-K`(不另建僵尸卡);
4718
+ // - 否则若显式声明 `父任务:t-N` 且父卡存在未归档,则判定为新建子卡派发,跳过父卡认领(1b / 2)。
4719
+ const explicitParentRaw = dispatchExplicitParentId(promptText)
4720
+ const explicitParentTask = explicitParentRaw === '' ? null : taskById(rt.state, explicitParentRaw)
4721
+ const explicitParentId =
4722
+ explicitParentTask && explicitParentTask.status !== 'archived' ? explicitParentTask.id : null
4723
+ const explicitId = dispatchTaskIdFromPrompt(promptText)
4724
+ if (explicitId !== '' && explicitId !== explicitParentId) {
4725
+ const explicit = taskById(rt.state, explicitId)
4726
+ if (explicit && explicit.status !== 'archived') {
4727
+ if (explicitParentId && !explicit.parentTaskId) {
4728
+ explicit.parentTaskId = normalizeParentTaskId(explicitParentId, explicit.id)
4729
+ }
4730
+ return finishPreparedDispatch(rt, auto, store, exec, explicit, false, 'task-id', now)
4731
+ }
4732
+ }
4733
+ if (!explicitParentId) {
4734
+ // 1b) 「看板任务:t-N」式引用(0.2.4):组长直聊派活时手动建了卡、prompt 用这种写法也要认领,
4735
+ // 否则会为同一件事建两张卡。只认领待做 / 进行中、无子卡且还没挂真实 worker 的卡片。
4736
+ const referencedId = dispatchReferencedTaskId(promptText)
4737
+ const referenced = referencedId === '' ? null : taskById(rt.state, referencedId)
4738
+ if (referenced && canReuseMentionedTask(referenced, rt.state)) {
4739
+ return finishPreparedDispatch(rt, auto, store, exec, referenced, false, 'task-id-mention', now)
4740
+ }
4741
+ // 2) 组长刚把某条轮询任务置 doing → 这次派发就是它的 worker(要求 prompt 真的指向那条任务)。
4742
+ if (intent && dispatchMentionsTask(args, intent) && !taskHasActiveSubtasks(rt.state, intent.id)) {
4743
+ return finishPreparedDispatch(rt, auto, store, exec, intent, false, 'lead-intent', now)
4744
+ }
3374
4745
  }
3375
4746
  // 3) 同参数重复调用(模型重试 / PTC 嵌套)→ 复用刚建好还没挂 worker 的卡片。
3376
4747
  const pending = findPendingDispatchCard(rt.state, leadId, title, note, now)
3377
4748
  if (pending) return finishPreparedDispatch(rt, auto, store, exec, pending, false, 'pending-duplicate', now)
3378
- // 4) 新派发:先建卡(doing + autoDispatch),写盘成功才允许启动 worker。
4749
+ // 4) 新派发:先建卡(doing + autoDispatch + 可选 parentTaskId),写盘成功才允许启动 worker。
4750
+ const parentTaskId = explicitParentId || inferParentTaskIdForAutoCard(args, rt.state)
3379
4751
  const task = addTask(
3380
4752
  rt.state,
3381
- { title, note, source: 'agent', sessionId: leadId || null, cwd: leadDispatchCwd(rt, agent, args) },
4753
+ {
4754
+ title,
4755
+ note,
4756
+ source: 'agent',
4757
+ sessionId: leadId || null,
4758
+ cwd: leadDispatchCwd(rt, agent, args),
4759
+ parentTaskId,
4760
+ },
3382
4761
  now,
3383
4762
  )
3384
4763
  applyTaskUpdate(rt.state, task.id, { status: 'doing' }, now)
@@ -3676,16 +5055,30 @@ function backfillWorkerSessionId(rt, input) {
3676
5055
  .then(() => subagents.listDescendants(parentId))
3677
5056
  .then((rows) => {
3678
5057
  if (!Array.isArray(rows)) return
3679
- const entry = rows.find(
5058
+ const matching = rows.filter(
3680
5059
  (row) => row && row.parentId === parentId && row.kind === 'child' && asString(row.name) === workerName,
3681
5060
  )
3682
- const childId = entry ? asString(entry.id).trim() : ''
3683
- if (childId === '') return
5061
+ if (matching.length === 0) return
3684
5062
  reloadBoardIfStale(rt)
3685
5063
  const task = taskById(rt.state, taskId)
3686
5064
  if (!task) return
3687
5065
  // 已经有 id(回填过 / 重派换了 worker)→ 不覆盖。
3688
5066
  if (asString(task.workerSessionId) !== '') return
5067
+ // 长驻组长会话下若复用 worker name,倒序优先认领尚未绑定其它卡片的最新 childId。
5068
+ let childId = ''
5069
+ for (let i = matching.length - 1; i >= 0; i -= 1) {
5070
+ const candidateId = asString(matching[i].id).trim()
5071
+ if (candidateId === '') continue
5072
+ const taken = rt.state.tasks.some(
5073
+ (other) => other && other.id !== taskId && asString(other.workerSessionId) === candidateId,
5074
+ )
5075
+ if (!taken) {
5076
+ childId = candidateId
5077
+ break
5078
+ }
5079
+ if (childId === '') childId = candidateId
5080
+ }
5081
+ if (childId === '') return
3689
5082
  task.workerSessionId = childId
3690
5083
  if ((task.workerRunState === null || task.workerRunState === '') && task.status === 'doing') {
3691
5084
  task.workerRunState = 'running'
@@ -3706,6 +5099,46 @@ function backfillWorkerSessionId(rt, input) {
3706
5099
  return true
3707
5100
  }
3708
5101
 
5102
+ /**
5103
+ * v0.3.9:轮询投递任务 / 人工任务(`autoDispatch !== LEAD_AUTO_MARK`)在 worker 结束时,
5104
+ * 绝不自动置 `done` 或改 `result`(交由组长审核),但必须把宿主独占的 `workerRunState` 从 `'running'`
5105
+ * 收敛为 `'ended'` / `'failed'`(并顺带回填缺失的 `workerSessionId`),避免像 t-111 那样任务已 `done`
5106
+ * 却永久残留 `workerRunState='running'`。
5107
+ */
5108
+ function settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now) {
5109
+ if (!rt || !rt.state || !Array.isArray(rt.state.tasks) || childId === '') return false
5110
+ let matched = null
5111
+ for (let i = rt.state.tasks.length - 1; i >= 0; i -= 1) {
5112
+ const item = rt.state.tasks[i]
5113
+ if (!item || item.workerRunState !== 'running') continue
5114
+ if (asString(item.workerSessionId) === childId) {
5115
+ matched = item
5116
+ break
5117
+ }
5118
+ }
5119
+ if (!matched && parentId !== '') {
5120
+ const candidates = rt.state.tasks.filter(
5121
+ (item) =>
5122
+ item &&
5123
+ item.workerRunState === 'running' &&
5124
+ asString(item.workerSessionId) === '' &&
5125
+ (asString(item.dispatchedSessionId) === parentId || asString(item.sessionId) === parentId),
5126
+ )
5127
+ if (workerName !== '') {
5128
+ const byName = candidates.filter((item) => asString(item.assignee) === workerName)
5129
+ if (byName.length === 1) matched = byName[0]
5130
+ } else if (candidates.length === 1) {
5131
+ matched = candidates[0]
5132
+ }
5133
+ }
5134
+ if (!matched) return false
5135
+ if (asString(matched.workerSessionId) === '') matched.workerSessionId = childId
5136
+ matched.workerRunState = stopReason === 'completed' ? 'ended' : 'failed'
5137
+ matched.updatedAt = iso(now)
5138
+ commitBoard(rt.state, rt.filePath)
5139
+ return true
5140
+ }
5141
+
3709
5142
  /**
3710
5143
  * subagent/end:worker 结束 → **宿主自动建的任务**置 done + result(§1.8),并 flush 完成回执(§1.6)。
3711
5144
  * 只认带 `autoDispatch === 'lead-dispatch'` 标记的任务:轮询投递任务的 assignee 也可能被组长写成 worker
@@ -3723,42 +5156,107 @@ export async function handleSubagentEnd(rt, info, now = Date.now()) {
3723
5156
  return { updated: false, reason: 'skipped' }
3724
5157
  }
3725
5158
  reloadBoardIfStale(rt)
5159
+ const parentId = asString(info && info.parentSessionId).trim()
5160
+ let workerName = trimmed(info && info.name, 200)
3726
5161
  let task = findTaskByWorker(rt.state, childId)
3727
5162
  if (!task) {
3728
5163
  // v0.3.1:workerSessionId 还没回填时(当前 dsh 的 subagent 结果没有 subagentId),
3729
- // 用 end 事件里的 parentSessionId 在「该组长名下、只此一条在跑的自动卡」里兜底认领。
3730
- // 多于一条时无法判断是哪个 worker → 不猜(保持 doing,交给组长审核)。
3731
- const parentId = asString(info && info.parentSessionId).trim()
5164
+ // 先按 worker name(info.name 或 subagents.listDescendants 反查 childId)精确匹配 candidate.assignee
5165
+ // (支持 v0.3.3 并发 fan-out 切片卡);拿不到 workerName 时,仅当该组长名下只此一条在跑的自动卡才兜底认领。
5166
+ if (parentId !== '') {
5167
+ if (workerName === '') {
5168
+ try {
5169
+ const ctx = rt && rt.ctx
5170
+ const subagents = ctx && typeof ctx.get === 'function' ? ctx.get('subagents') : undefined
5171
+ if (subagents && typeof subagents.listDescendants === 'function') {
5172
+ const rows = await subagents.listDescendants(parentId)
5173
+ if (Array.isArray(rows)) {
5174
+ const row = rows.find((item) => item && asString(item.id).trim() === childId)
5175
+ if (row) workerName = trimmed(row.name, 200)
5176
+ }
5177
+ }
5178
+ } catch {
5179
+ /* listDescendants 失败时退回单候选兜底 */
5180
+ }
5181
+ reloadBoardIfStale(rt)
5182
+ task = findTaskByWorker(rt.state, childId)
5183
+ }
5184
+ if (!task) {
5185
+ // v0.5.2:放宽兜底候选——workerSessionId 还没回填时,卡片可能已进入 ended / failed / null
5186
+ // (上一次 aborted 收尾、或宿主重启归一化),不能再要求 workerRunState === 'running',
5187
+ // 否则结束事件永远认领不到卡、卡片停在 doing 又没有任何外部提示。
5188
+ // 只按「该组长名下 + doing 自动卡 + workerSessionId 为空或正是本次 childId」筛,
5189
+ // 再用 info.name / assignee 精确匹配;多候选无法区分时不猜。
5190
+ const candidates = rt.state.tasks.filter(
5191
+ (candidate) =>
5192
+ candidate &&
5193
+ candidate.autoDispatch === LEAD_AUTO_MARK &&
5194
+ candidate.status === 'doing' &&
5195
+ asString(candidate.sessionId) === parentId &&
5196
+ (asString(candidate.workerSessionId) === '' ||
5197
+ asString(candidate.workerSessionId) === childId),
5198
+ )
5199
+ if (workerName !== '') {
5200
+ const byName = candidates.filter((candidate) => asString(candidate.assignee) === workerName)
5201
+ if (byName.length === 1) task = byName[0]
5202
+ // 名字对不上、但只剩一条且 assignee 还没写(tools/result 没走到 / 回填失败):不算猜测。
5203
+ if (!task && byName.length === 0 && candidates.length === 1 && asString(candidates[0].assignee) === '') {
5204
+ task = candidates[0]
5205
+ }
5206
+ }
5207
+ if (!task && workerName === '' && candidates.length === 1) {
5208
+ task = candidates[0]
5209
+ }
5210
+ }
5211
+ }
5212
+ }
5213
+ const rawStopReason = asString(info && info.stopReason).trim()
5214
+ const stopReason = rawStopReason === '' ? 'unknown' : rawStopReason
5215
+ if (!task) {
5216
+ // v0.5.2:认领不到卡片时不再静默——该组长名下若确实还有 doing 的自动卡,说明收尾逻辑漏了,
5217
+ // 必须留下可查的告警(含 childId / name / parentId / stopReason),交给组长人工核对。
3732
5218
  if (parentId !== '') {
3733
- const candidates = rt.state.tasks.filter(
5219
+ const lingering = rt.state.tasks.filter(
3734
5220
  (candidate) =>
3735
5221
  candidate &&
3736
5222
  candidate.autoDispatch === LEAD_AUTO_MARK &&
3737
5223
  candidate.status === 'doing' &&
3738
- asString(candidate.workerRunState) === 'running' &&
3739
- asString(candidate.sessionId) === parentId &&
3740
- asString(candidate.workerSessionId) === '',
5224
+ (asString(candidate.sessionId) === parentId ||
5225
+ asString(candidate.dispatchedSessionId) === parentId),
3741
5226
  )
3742
- if (candidates.length === 1) task = candidates[0]
5227
+ if (lingering.length > 0) {
5228
+ recordLeadAutoError(
5229
+ rt,
5230
+ 'worker 结束但没有匹配到看板自动卡:childId=' +
5231
+ childId +
5232
+ ',name=' +
5233
+ (workerName === '' ? '(未知)' : workerName) +
5234
+ ',parentId=' +
5235
+ parentId +
5236
+ ',stopReason=' +
5237
+ stopReason +
5238
+ ';该组长名下仍有 doing 的自动卡 ' +
5239
+ lingering.map((candidate) => candidate.id).join('、') +
5240
+ ',需要人工核对',
5241
+ now,
5242
+ )
5243
+ }
3743
5244
  }
3744
- }
3745
- if (!task) {
3746
5245
  // 不是宿主建的自动任务(例如组长审核时派去跑命令的验证子 Agent,
3747
- // 或轮询投递任务的 worker——那条任务的 autoDispatch 为 null)。
5246
+ // 或轮询投递任务的 worker——那条任务的 autoDispatch 为 null):仅收敛其 workerRunState。
5247
+ settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now)
3748
5248
  auto.skipped += 1
3749
5249
  auto.updatedAt = iso(now)
3750
5250
  return { updated: false, reason: 'no-task' }
3751
5251
  }
3752
5252
  if (!isLeadAutoTask(task) || asString(task.notifiedAt) !== '') {
3753
5253
  // 兜底:findTaskByWorker 已经过滤过,这里再挡一层,确保轮询任务(notifiedAt 非空)永不被自动 done。
5254
+ settleNonAutoWorkerRunState(rt, childId, parentId, workerName, stopReason, now)
3754
5255
  auto.skipped += 1
3755
5256
  auto.updatedAt = iso(now)
3756
5257
  return { updated: false, reason: 'not-auto', taskId: task.id }
3757
5258
  }
3758
5259
  const result = workerResultText(info)
3759
- // 缺字段 / 空串 / 未知值一律按非 completed 处理(绝不静默置 done):文案里缺省写 unknown。
3760
- const rawStopReason = asString(info && info.stopReason).trim()
3761
- const stopReason = rawStopReason === '' ? 'unknown' : rawStopReason
3762
5260
  const wasDoing = task.status === 'doing'
3763
5261
  if (stopReason !== 'completed') {
3764
5262
  if (!wasDoing) {
@@ -3786,6 +5284,42 @@ export async function handleSubagentEnd(rt, info, now = Date.now()) {
3786
5284
  auto.updatedAt = iso(now)
3787
5285
  return { updated: false, reason: 'status-' + task.status, taskId: task.id }
3788
5286
  }
5287
+ // v0.5.0:直聊顶层自动卡(parentTaskId 为空)由宿主直接收尾置 done——若挂载了隔离 Git Worktree,
5288
+ // 必须在置 done 前自动合入主工作区并清理临时分支;若发生真实冲突,保持 doing + 写 lastError 保留现场!
5289
+ // (fan-out 内部切片子卡 parentTaskId 非空:保留其 worktreePath 供组长按波次调 taskboard_merge_worktree 合入。)
5290
+ if (
5291
+ wasDoing &&
5292
+ asString(task.parentTaskId) === '' &&
5293
+ asString(task.worktreePath) !== ''
5294
+ ) {
5295
+ try {
5296
+ const merged = mergeAndCleanupTaskWorktree(rt, task.id, { cleanup: true, commit: false })
5297
+ if (merged.conflict) {
5298
+ if (result !== '') task.result = result
5299
+ if (asString(task.workerSessionId) === '') task.workerSessionId = childId
5300
+ task.workerRunState = 'ended'
5301
+ task.lastError = trimmed(merged.summary, 500)
5302
+ task.updatedAt = iso(now)
5303
+ commitBoard(rt.state, rt.filePath)
5304
+ auto.lastTaskId = task.id
5305
+ auto.lastWorkerSessionId = childId
5306
+ auto.updatedAt = iso(now)
5307
+ console.warn('[taskboard] 直聊任务自动合入隔离工作树冲突:' + merged.summary)
5308
+ return { updated: false, reason: 'worktree-conflict', taskId: task.id }
5309
+ }
5310
+ } catch (mergeError) {
5311
+ if (result !== '') task.result = result
5312
+ if (asString(task.workerSessionId) === '') task.workerSessionId = childId
5313
+ task.workerRunState = 'ended'
5314
+ task.lastError = trimmed('隔离工作树自动合入失败:' + describeError(mergeError), 500)
5315
+ task.updatedAt = iso(now)
5316
+ commitBoard(rt.state, rt.filePath)
5317
+ auto.lastTaskId = task.id
5318
+ auto.lastWorkerSessionId = childId
5319
+ auto.updatedAt = iso(now)
5320
+ return { updated: false, reason: 'worktree-merge-error', taskId: task.id }
5321
+ }
5322
+ }
3789
5323
  const patch = {}
3790
5324
  if (result !== '') patch.result = result
3791
5325
  // doing → done;已是 done(组长先审完 / 同一 worker 再次结束)就只刷新 result。
@@ -3873,9 +5407,11 @@ export function registerLeadAutoHooks(ctx, rt) {
3873
5407
  ctx.on(
3874
5408
  'subagent/end',
3875
5409
  (info) => {
3876
- Promise.resolve()
3877
- .then(() => handleSubagentEnd(rt, info))
3878
- .catch((error) => recordLeadAutoError(rt, 'worker 完成挂钩失败:' + describeError(error)))
5410
+ // v0.3.5:同步执行 handleSubagentEnd 前半段(findTaskByWorker 命中时无 await,状态 done 与写盘
5411
+ // 在 subagent/end 发射栈内同步完成),防止父会话被唤醒后立即调 taskboard_list 读到旧 doing 状态。
5412
+ Promise.resolve(handleSubagentEnd(rt, info)).catch((error) =>
5413
+ recordLeadAutoError(rt, 'worker 完成挂钩失败:' + describeError(error)),
5414
+ )
3879
5415
  },
3880
5416
  { global: true },
3881
5417
  )
@@ -3885,6 +5421,117 @@ export function registerLeadAutoHooks(ctx, rt) {
3885
5421
  return true
3886
5422
  }
3887
5423
 
5424
+ /**
5425
+ * v0.5.2:`description` / `prompt` 里「用户明确要求留在主工作区」的措辞。
5426
+ *
5427
+ * 否定对象必须正好是「(建 / 用)隔离工作树」本身:像「不要删除隔离工作树里的文件」
5428
+ * 「不要在隔离工作树里装依赖」这类句子,否定的是「删除 / 装依赖」而不是「隔离」,
5429
+ * 绝不能命中——否则会把本该隔离执行的活错误地拉回主工作区并发踩踏。
5430
+ * (正则里 `不要` 与 `隔离` 之间只允许创建 / 使用一类的动词,其它动词会让整个分支失配。)
5431
+ */
5432
+ const EXPLICIT_MAIN_WORKSPACE_RE = new RegExp(
5433
+ [
5434
+ // 不建隔离工作树 / 不要建 / 不要使用 / 无需隔离工作树 / 禁止创建 / 勿开
5435
+ '(?:不要|别|不|无需|禁止|勿)(?:要|用|需|必|许)?(?:创建|建立|建|启用|开启|使用|开)?\\s*隔离(?:的)?(?:git\\s*)?工作树',
5436
+ // 直接改主工作区 / 直接修改主仓库
5437
+ '直接\\s*(?:改|修改|操作|执行|跑|提交)\\s*(?:到|在)?\\s*(?:主工作区|主仓库|主仓)',
5438
+ // 在主工作区执行 / 在主工作区里改
5439
+ '在\\s*(?:主工作区|主仓库|主仓)\\s*(?:里|内|中)?\\s*(?:直接)?\\s*(?:执行|修改|操作|跑|改|提交|干活)',
5440
+ // 主工作区里直接改
5441
+ '(?:主工作区|主仓库|主仓)\\s*(?:里|内|中)\\s*直接\\s*(?:执行|修改|操作|跑|改|提交|干活)',
5442
+ ].join('|'),
5443
+ 'im',
5444
+ )
5445
+
5446
+ /**
5447
+ * v0.5.0:判断本次 `subagent` 派发是否必须留在主工作区执行(跳过 Git Worktree 隔离):
5448
+ * - 任务自身或所属父任务处于 `assignee === 'merging'`(合并与全量验证阶段);
5449
+ * - `description` / `prompt` 明确声明为合并验证、解冲突、只读审查或以 `[主工作区]` 开头;
5450
+ * - v0.5.2:显式主工作区措辞(`不建隔离工作树` / `直接改主工作区` / `在主工作区执行` 等),
5451
+ * 见 `EXPLICIT_MAIN_WORKSPACE_RE`(尊重用户的显式指令,不再一律隔离)。
5452
+ */
5453
+ export function shouldSkipWorktreeForDispatch(state, task, args) {
5454
+ if (!task || task.status === 'archived') return true
5455
+ if (asString(task.assignee).trim() === 'merging') return true
5456
+ const parentId = asString(task.parentTaskId).trim()
5457
+ if (parentId !== '' && state) {
5458
+ const parent = taskById(state, parentId)
5459
+ if (parent && asString(parent.assignee).trim() === 'merging') return true
5460
+ }
5461
+ const desc = isPlainObject(args) ? asString(args.description) : ''
5462
+ const prompt = subagentPromptText(args)
5463
+ if (/合并与全量验证|合并验证|冲突合并|解冲突|全量验证|^\[主工作区\]/i.test(desc)) return true
5464
+ if (/^\[主工作区\]|你是只读审查员/m.test(prompt)) return true
5465
+ // v0.5.2:显式要求主工作区(prompt / description 任一命中即可)。
5466
+ if (EXPLICIT_MAIN_WORKSPACE_RE.test(desc) || EXPLICIT_MAIN_WORKSPACE_RE.test(prompt)) return true
5467
+ return false
5468
+ }
5469
+
5470
+ /**
5471
+ * v0.5.0:在 `tools/pre-execute` 闸门准备卡片后,按需为该任务挂载隔离 Git Worktree,
5472
+ * 并透明重写 `exec.arguments.cwd` 与注入 `[隔离工作树已启用]` 前缀提示。
5473
+ */
5474
+ export function attachDispatchWorktree(rt, agent, taskId, exec) {
5475
+ try {
5476
+ if (!rt || !rt.state || !taskId) return { isolated: false, reason: 'no-task' }
5477
+ const cfg = normalizeConfig(rt.state.config)
5478
+ if (cfg.worktreeIsolation === false) return { isolated: false, reason: 'disabled' }
5479
+ const task = taskById(rt.state, taskId)
5480
+ if (!task) return { isolated: false, reason: 'no-task' }
5481
+ const args = exec && isPlainObject(exec.arguments) ? exec.arguments : {}
5482
+ if (shouldSkipWorktreeForDispatch(rt.state, task, args)) {
5483
+ return { isolated: false, reason: 'main-workspace-role' }
5484
+ }
5485
+ const baseCwd = asString(task.cwd).trim() || leadDispatchCwd(rt, agent, args)
5486
+ if (baseCwd === '') return { isolated: false, reason: 'no-cwd' }
5487
+ if (!task.cwd) task.cwd = baseCwd
5488
+
5489
+ const argCwd = asString(args.cwd).trim()
5490
+ if (
5491
+ argCwd !== '' &&
5492
+ normalizePathForCompare(argCwd) !== normalizePathForCompare(baseCwd) &&
5493
+ normalizePathForCompare(argCwd) !== normalizePathForCompare(asString(task.worktreePath))
5494
+ ) {
5495
+ return { isolated: false, reason: 'explicit-custom-cwd' }
5496
+ }
5497
+
5498
+ const repoInfo = resolveGitRepoInfo(baseCwd, { fresh: true })
5499
+ if (!repoInfo) return { isolated: false, reason: 'not-git-repo' }
5500
+
5501
+ const wt = ensureTaskWorktree(rt, task, repoInfo)
5502
+ if (!wt || !wt.worktreePath) return { isolated: false, reason: 'unavailable' }
5503
+
5504
+ if (exec && typeof exec === 'object') {
5505
+ let nextArgs = isPlainObject(exec.arguments) ? exec.arguments : {}
5506
+ if (Object.isFrozen(nextArgs)) nextArgs = { ...nextArgs }
5507
+ nextArgs.cwd = wt.worktreePath
5508
+ const notice =
5509
+ '[隔离工作树已启用] 当前子任务在独立 Git Worktree 中执行:' +
5510
+ wt.worktreePath +
5511
+ '(分支:' +
5512
+ wt.branch +
5513
+ ',主工作区:' +
5514
+ repoInfo.repoRoot +
5515
+ ')。主仓依赖(node_modules / .venv)已通过软链共享,可直接在当前目录读写文件与运行单测;请勿删除软链依赖目录,也请勿跨目录修改主工作区文件。'
5516
+ if (typeof nextArgs.prompt === 'string') {
5517
+ if (!nextArgs.prompt.includes('[隔离工作树已启用]')) {
5518
+ nextArgs.prompt = notice + '\n\n' + nextArgs.prompt
5519
+ }
5520
+ } else if (Array.isArray(nextArgs.prompt)) {
5521
+ if (!subagentPromptText(nextArgs).includes('[隔离工作树已启用]')) {
5522
+ nextArgs.prompt = [{ type: 'text', text: notice }, ...nextArgs.prompt]
5523
+ }
5524
+ }
5525
+ exec.arguments = nextArgs
5526
+ }
5527
+
5528
+ return { isolated: true, worktreePath: wt.worktreePath, branch: wt.branch, reused: wt.reused }
5529
+ } catch (error) {
5530
+ console.warn('[taskboard] 创建 Git Worktree 失败,退回主工作区执行:' + describeError(error))
5531
+ return { isolated: false, reason: 'error', error: describeError(error) }
5532
+ }
5533
+ }
5534
+
3888
5535
  /**
3889
5536
  * 注册 §1.8(0.2.4)的**派发前强制建卡闸门**(`tools/pre-execute`)。
3890
5537
  *
@@ -3922,6 +5569,8 @@ export function registerLeadDispatchGate(ctx, rt) {
3922
5569
  // v0.3.2:卡片已准备好、worker 即将启动——这是「派发者出现」的时刻。
3923
5570
  // 工作区没有组长 / 组长已归档 → 把当前派单会话登记为组长,避免轮询再新建一个组长窗口。
3924
5571
  adoptWorkspaceLead(rt, agent, exec.arguments, { taskId: outcome.taskId })
5572
+ // v0.5.0:按需挂载独立 Git Worktree,自动重写 worker 的 cwd 与隔离说明(注意在 adoptWorkspaceLead 之后执行,不覆盖组长主工作区路径)。
5573
+ attachDispatchWorktree(rt, agent, outcome.taskId, exec)
3925
5574
  return next()
3926
5575
  } catch (error) {
3927
5576
  const message =
@@ -4044,6 +5693,8 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
4044
5693
  id: { type: 'string' },
4045
5694
  title: { type: 'string' },
4046
5695
  status: { type: 'string', enum: [...STATUSES] },
5696
+ parentTaskId: { type: 'string' },
5697
+ dependsOn: { type: 'array', items: { type: 'string' } },
4047
5698
  note: { type: 'string' },
4048
5699
  assignee: { type: 'string' },
4049
5700
  result: { type: 'string' },
@@ -4051,6 +5702,9 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
4051
5702
  needsUser: { type: 'boolean' },
4052
5703
  question: { type: 'string' },
4053
5704
  questionOptions: { type: 'array', items: { type: 'string' } },
5705
+ worktreePath: { type: 'string' },
5706
+ worktreeBranch: { type: 'string' },
5707
+ lastError: { type: 'string' },
4054
5708
  },
4055
5709
  },
4056
5710
  },
@@ -4058,7 +5712,7 @@ export const TASK_LIST_OUTPUT_SCHEMA = {
4058
5712
  }
4059
5713
 
4060
5714
  /**
4061
- * 三个模型工具共用的任务摘要(taskboard_list 的 tasks[] / taskboard_add / taskboard_update 的 task)。
5715
+ * 面向模型的任务摘要(taskboard_list 的 tasks[] / taskboard_add / taskboard_update 的 task)。
4062
5716
  *
4063
5717
  * 这里的键必须全部在 output.schema 里声明:dsh tools 管线在 execute() 成功返回之后才校验 canonical
4064
5718
  * output,而两个 output.schema 都是 additionalProperties:false 的封闭契约——多带一个未声明字段就会抛
@@ -4072,6 +5726,8 @@ export function taskBrief(task) {
4072
5726
  id: task.id,
4073
5727
  title: task.title,
4074
5728
  status: task.status,
5729
+ parentTaskId: task.parentTaskId || '',
5730
+ dependsOn: Array.isArray(task.dependsOn) ? task.dependsOn.slice() : [],
4075
5731
  note: task.note || '',
4076
5732
  assignee: task.assignee || '',
4077
5733
  result: task.result || '',
@@ -4080,6 +5736,12 @@ export function taskBrief(task) {
4080
5736
  needsUser: task.needsUser === true,
4081
5737
  question: task.question || '',
4082
5738
  questionOptions: Array.isArray(task.questionOptions) ? task.questionOptions.slice() : [],
5739
+ // v0.5.0:隔离工作树路径与分支,供组长判断是否需调 taskboard_merge_worktree 合入主工作区。
5740
+ worktreePath: task.worktreePath || '',
5741
+ worktreeBranch: task.worktreeBranch || '',
5742
+ // v0.5.2:故障原因必须对模型可见——中断(aborted)/ 合入冲突等只写 lastError、状态保持 doing 时,
5743
+ // 组长从 taskboard_list 就能看出「卡片为什么没动」,不再出现「活干完了、状态没变、也没提示」。
5744
+ lastError: task.lastError || '',
4083
5745
  }
4084
5746
  }
4085
5747
 
@@ -4087,20 +5749,40 @@ function renderTaskList(value) {
4087
5749
  if (value.count === 0) return [{ type: 'text', text: '看板没有匹配的任务。' }]
4088
5750
  const lines = ['看板任务(' + value.count + ' 条):']
4089
5751
  for (const task of value.tasks) {
4090
- const bits = ['[' + task.status + ']', task.id, task.title]
5752
+ const bits = ['[' + task.status + ']', task.id]
5753
+ if (task.parentTaskId) bits.push('(父:' + task.parentTaskId + ')')
5754
+ if (Array.isArray(task.dependsOn) && task.dependsOn.length > 0) {
5755
+ bits.push('(依赖:' + task.dependsOn.join(',') + ')')
5756
+ }
5757
+ bits.push(task.title)
4091
5758
  if (task.assignee) bits.push('@' + task.assignee)
4092
5759
  lines.push('- ' + bits.join(' '))
5760
+ if (task.worktreePath) lines.push(' 隔离工作树:' + task.worktreePath + (task.worktreeBranch ? ' (' + task.worktreeBranch + ')' : ''))
4093
5761
  if (task.note) lines.push(' 备注:' + task.note)
4094
5762
  if (task.result) lines.push(' 结论:' + task.result)
5763
+ // v0.5.2:异常(aborted / 合入冲突等)必须出现在模型工具输出里,否则外部只看得到「卡在 doing」。
5764
+ if (task.lastError) lines.push(' 最近异常:' + task.lastError)
4095
5765
  if (task.needsUser) lines.push(' 待用户回答:' + task.question)
4096
5766
  }
4097
5767
  return [{ type: 'text', text: lines.join('\n') }]
4098
5768
  }
4099
5769
 
4100
5770
  function renderTaskOne(prefix, task) {
4101
- const lines = [prefix + task.id + ' [' + task.status + '] ' + task.title]
5771
+ const head =
5772
+ prefix +
5773
+ task.id +
5774
+ ' [' +
5775
+ task.status +
5776
+ ']' +
5777
+ (task.parentTaskId ? ' (父:' + task.parentTaskId + ')' : '') +
5778
+ (Array.isArray(task.dependsOn) && task.dependsOn.length > 0 ? ' (依赖:' + task.dependsOn.join(',') + ')' : '') +
5779
+ ' ' +
5780
+ task.title
5781
+ const lines = [head]
5782
+ if (task.worktreePath) lines.push('隔离工作树:' + task.worktreePath + (task.worktreeBranch ? ' (' + task.worktreeBranch + ')' : ''))
4102
5783
  if (task.note) lines.push('备注:' + task.note)
4103
5784
  if (task.result) lines.push('结论:' + task.result)
5785
+ if (task.lastError) lines.push('最近异常:' + task.lastError)
4104
5786
  if (task.needsUser) lines.push('待用户回答:' + task.question)
4105
5787
  const updatedMs = Date.parse(task.updatedAt)
4106
5788
  lines.push(
@@ -4122,6 +5804,8 @@ export const TASK_ONE_OUTPUT_SCHEMA = {
4122
5804
  id: { type: 'string' },
4123
5805
  title: { type: 'string' },
4124
5806
  status: { type: 'string', enum: [...STATUSES] },
5807
+ parentTaskId: { type: 'string' },
5808
+ dependsOn: { type: 'array', items: { type: 'string' } },
4125
5809
  note: { type: 'string' },
4126
5810
  assignee: { type: 'string' },
4127
5811
  result: { type: 'string' },
@@ -4129,11 +5813,31 @@ export const TASK_ONE_OUTPUT_SCHEMA = {
4129
5813
  needsUser: { type: 'boolean' },
4130
5814
  question: { type: 'string' },
4131
5815
  questionOptions: { type: 'array', items: { type: 'string' } },
5816
+ worktreePath: { type: 'string' },
5817
+ worktreeBranch: { type: 'string' },
5818
+ lastError: { type: 'string' },
4132
5819
  },
4133
5820
  },
4134
5821
  },
4135
5822
  }
4136
5823
 
5824
+ export const TASK_MERGE_WORKTREE_OUTPUT_SCHEMA = {
5825
+ type: 'object',
5826
+ additionalProperties: false,
5827
+ required: ['id', 'merged', 'noChanges', 'conflict', 'cleaned', 'branch', 'worktreePath', 'conflictFiles', 'summary'],
5828
+ properties: {
5829
+ id: { type: 'string' },
5830
+ merged: { type: 'boolean' },
5831
+ noChanges: { type: 'boolean' },
5832
+ conflict: { type: 'boolean' },
5833
+ cleaned: { type: 'boolean' },
5834
+ branch: { type: 'string' },
5835
+ worktreePath: { type: 'string' },
5836
+ conflictFiles: { type: 'array', items: { type: 'string' } },
5837
+ summary: { type: 'string' },
5838
+ },
5839
+ }
5840
+
4137
5841
  /**
4138
5842
  * 注册三个模型工具。宿主级注册 = 全局可见(所有预设的 Agent 都能用),
4139
5843
  * 这也是「非派单模式也能往看板里塞任务」的实现方式。
@@ -4148,7 +5852,7 @@ export function registerTools(toolCtx, rt) {
4148
5852
  name: 'taskboard_list',
4149
5853
  description:
4150
5854
  '列出任务看板上的任务(默认全部状态:todo=待开始 / doing=进行中 / done=已完成 / archived=已归档)。' +
4151
- '派单前用它确认要处理哪条任务,审核后用 taskboard_update 更新状态。',
5855
+ '派单前用它确认要处理哪条任务;并行拆片(fan-out)时传 parentTaskId 只看该父任务名下的全部子卡进度;审核后用 taskboard_update 更新状态。',
4152
5856
  parameters: {
4153
5857
  type: 'object',
4154
5858
  additionalProperties: false,
@@ -4158,6 +5862,10 @@ export function registerTools(toolCtx, rt) {
4158
5862
  enum: [...STATUSES],
4159
5863
  description: '只看某一列;省略则返回全部状态。',
4160
5864
  },
5865
+ parentTaskId: {
5866
+ type: 'string',
5867
+ description: '可选:只看某条父任务(如 t-10)名下的切片 / 合并 / 验证子卡;省略不过滤。',
5868
+ },
4161
5869
  },
4162
5870
  },
4163
5871
  output: {
@@ -4165,10 +5873,16 @@ export function registerTools(toolCtx, rt) {
4165
5873
  render: (_args, value) => renderTaskList(value),
4166
5874
  },
4167
5875
  execute(args) {
5876
+ reloadBoardIfStale(rt)
4168
5877
  const want = args && args.status !== undefined ? args.status : ''
4169
5878
  if (want !== '' && !STATUSES.includes(want)) throw new Error('非法状态:' + String(want))
5879
+ const wantParentRaw = args && typeof args.parentTaskId === 'string' ? args.parentTaskId.trim().toLowerCase() : ''
5880
+ if (wantParentRaw !== '' && !/^t-[0-9]{1,6}$/.test(wantParentRaw)) {
5881
+ throw new Error('非法 parentTaskId:' + String(args.parentTaskId))
5882
+ }
4170
5883
  const tasks = rt.state.tasks
4171
5884
  .filter((task) => (want === '' ? true : task.status === want))
5885
+ .filter((task) => (wantParentRaw === '' ? true : asString(task.parentTaskId).toLowerCase() === wantParentRaw))
4172
5886
  .map(taskBrief)
4173
5887
  return Promise.resolve({ count: tasks.length, tasks })
4174
5888
  },
@@ -4178,7 +5892,8 @@ export function registerTools(toolCtx, rt) {
4178
5892
  description:
4179
5893
  '往任务看板添加一条待开始任务。用户口述的需求、你自己拆出来的后续任务都可以加进看板,' +
4180
5894
  '轮询器会把它派给任务所属工作区的常驻组长。title 必填,note 写验收标准或补充信息;' +
4181
- 'workspace 可选(工作区 id / 名称 / 绝对路径),用于从主会话往其它工作区派任务。',
5895
+ 'workspace 可选(工作区 id / 名称 / 绝对路径),用于从主会话往其它工作区派任务;' +
5896
+ 'parentTaskId 可选(关联所属父任务 id,如 t-10)。',
4182
5897
  parameters: {
4183
5898
  type: 'object',
4184
5899
  additionalProperties: false,
@@ -4190,6 +5905,15 @@ export function registerTools(toolCtx, rt) {
4190
5905
  type: 'string',
4191
5906
  description: '可选:任务所属工作区(工作区 id / 名称 / 绝对路径),省略则用当前会话工作区',
4192
5907
  },
5908
+ parentTaskId: {
5909
+ type: 'string',
5910
+ description: '可选:关联所属父任务 id(例如 t-10)',
5911
+ },
5912
+ dependsOn: {
5913
+ type: 'array',
5914
+ items: { type: 'string' },
5915
+ description: '可选:前置依赖任务 id 列表(如 ["t-1", "t-2"]);前置任务全部完成前本任务不会自动派发',
5916
+ },
4193
5917
  },
4194
5918
  },
4195
5919
  output: {
@@ -4197,9 +5921,14 @@ export function registerTools(toolCtx, rt) {
4197
5921
  render: (_args, value) => renderTaskOne('已添加任务 ', value.task),
4198
5922
  },
4199
5923
  execute(args, exec) {
5924
+ reloadBoardIfStale(rt)
4200
5925
  const title = trimmed(args && args.title, MAX_TITLE_CHARS)
4201
5926
  if (title === '') throw new Error('title 不能为空')
4202
5927
  if (typeof (args && args.note) === 'string') assertNoteAttachments(args.note)
5928
+ const rawParent = args && typeof args.parentTaskId === 'string' ? args.parentTaskId.trim() : ''
5929
+ if (rawParent !== '' && !normalizeParentTaskId(rawParent)) {
5930
+ throw new Error('非法 parentTaskId:' + rawParent)
5931
+ }
4203
5932
  let sessionId = null
4204
5933
  let cwd = null
4205
5934
  try {
@@ -4219,7 +5948,15 @@ export function registerTools(toolCtx, rt) {
4219
5948
  if (resolved === '') throw new Error('未知工作区:' + workspaceArg)
4220
5949
  cwd = resolved
4221
5950
  }
4222
- const task = addTask(rt.state, { title, note: args && args.note, source: 'agent', sessionId, cwd })
5951
+ const task = addTask(rt.state, {
5952
+ title,
5953
+ note: args && args.note,
5954
+ source: 'agent',
5955
+ sessionId,
5956
+ cwd,
5957
+ parentTaskId: rawParent || null,
5958
+ dependsOn: args && args.dependsOn,
5959
+ })
4223
5960
  commitBoard(rt.state, rt.filePath)
4224
5961
  return Promise.resolve({ task: taskBrief(task) })
4225
5962
  },
@@ -4228,7 +5965,8 @@ export function registerTools(toolCtx, rt) {
4228
5965
  name: 'taskboard_update',
4229
5966
  description:
4230
5967
  '更新看板任务:置为 doing(已派发)、done(审核通过)、todo(打回重做)、archived(归档);' +
4231
- '也可以用 result 写审核结论。assignee 只写子 Agent 的 label / 名字(自由文本),**不要写会话 id**——' +
5968
+ '也可以用 result 写审核结论、lastError 写故障或阻塞原因(传空串清空,提问不要写进 lastError)。' +
5969
+ 'assignee 只写子 Agent 的 label / 名字(自由文本),**不要写会话 id**——' +
4232
5970
  '执行会话 id 由宿主记在 workerSessionId,模型写不进去。状态迁移非法时会返回错误。' +
4233
5971
  '需要用户决策时用 needsUser:true + question(可选 questionOptions 选项)在任务上提问,' +
4234
5972
  '看板会把它放进「待你处理」并通知用户回答;needsUser:false 取消提问(问题字段清空,回答留档)。' +
@@ -4243,6 +5981,10 @@ export function registerTools(toolCtx, rt) {
4243
5981
  result: { type: 'string', description: '审核结论 / 子 Agent 汇报摘要' },
4244
5982
  assignee: { type: 'string', description: '子 Agent 的 label / 名字(自由文本;不要写会话 id)' },
4245
5983
  note: { type: 'string', description: '备注(覆盖原备注)' },
5984
+ lastError: {
5985
+ type: 'string',
5986
+ description: '故障或阻塞原因(派发失败 / 缺少工作目录 / worker 异常;传空串可清空,不要写向用户的提问)',
5987
+ },
4246
5988
  needsUser: {
4247
5989
  type: 'boolean',
4248
5990
  description: '是否在等用户回复:true 时必须同时给 question;false 取消提问',
@@ -4253,6 +5995,11 @@ export function registerTools(toolCtx, rt) {
4253
5995
  items: { type: 'string' },
4254
5996
  description: '可选答案(最多 4 个,每个 ≤80 字;用户可以在看板上点选)',
4255
5997
  },
5998
+ dependsOn: {
5999
+ type: 'array',
6000
+ items: { type: 'string' },
6001
+ description: '可选:覆盖设置前置依赖任务 id 列表(传空数组 [] 清空前置依赖)',
6002
+ },
4256
6003
  },
4257
6004
  },
4258
6005
  output: {
@@ -4261,11 +6008,22 @@ export function registerTools(toolCtx, rt) {
4261
6008
  },
4262
6009
  async execute(args, exec) {
4263
6010
  if (!args || !args.id) throw new Error('缺少任务 id')
6011
+ reloadBoardIfStale(rt)
4264
6012
  const patch = {}
4265
6013
  // v0.2.9(§2):`workerSessionId` / `workerRunState` 是宿主独占字段,**不在白名单里**——
4266
6014
  // 模型即使传了也进不了 patch(`parameters.additionalProperties:false` 还会在入参校验阶段拒绝),
4267
6015
  // `applyTaskUpdate` 也不读这两个键,所以任务字段绝不会被模型改写。
4268
- for (const key of ['status', 'result', 'assignee', 'note', 'needsUser', 'question', 'questionOptions']) {
6016
+ for (const key of [
6017
+ 'status',
6018
+ 'result',
6019
+ 'assignee',
6020
+ 'note',
6021
+ 'lastError',
6022
+ 'needsUser',
6023
+ 'question',
6024
+ 'questionOptions',
6025
+ 'dependsOn',
6026
+ ]) {
4269
6027
  if (args[key] !== undefined) patch[key] = args[key]
4270
6028
  }
4271
6029
  // §1.9:提问的会话 id(askedBy)由宿主补,模型不能伪造别的会话。
@@ -4295,7 +6053,43 @@ export function registerTools(toolCtx, rt) {
4295
6053
  return { task: taskBrief(task) }
4296
6054
  },
4297
6055
  })
4298
- console.log('[taskboard] 模型工具已注册:taskboard_list / taskboard_add / taskboard_update')
6056
+ tools.register({
6057
+ name: 'taskboard_merge_worktree',
6058
+ description:
6059
+ '将看板任务(或并行切片子卡)关联的隔离 Git Worktree 改动原子预检并合入主工作区,成功后自动回收临时 Worktree 目录与分支。' +
6060
+ '当 taskboard_list 中卡片 worktreePath 非空时,组长在审核通过置 done 前(或波次合并阶段)必须调用本工具合入主工作区;' +
6061
+ '若返回 conflict:true(主工作区不会被污染),请派合并 worker 手动解冲突后再传 discardOnly:true 清理临时工作树。',
6062
+ parameters: {
6063
+ type: 'object',
6064
+ additionalProperties: false,
6065
+ required: ['id'],
6066
+ properties: {
6067
+ id: { type: 'string', description: '任务或子卡 id,例如 t-12' },
6068
+ cleanup: {
6069
+ type: 'boolean',
6070
+ description: '可选:合入成功后是否立即删除临时 Worktree 与分支(默认 true)',
6071
+ },
6072
+ discardOnly: {
6073
+ type: 'boolean',
6074
+ description: '可选:设为 true 时不合入改动,直接卸载依赖软链并回收该任务的临时 Worktree 与分支(用于手动解冲突后清理或废弃切片)',
6075
+ },
6076
+ },
6077
+ },
6078
+ output: {
6079
+ schema: TASK_MERGE_WORKTREE_OUTPUT_SCHEMA,
6080
+ render: (_args, value) => [{ type: 'text', text: value.summary }],
6081
+ },
6082
+ execute(args) {
6083
+ if (!args || !args.id) throw new Error('缺少任务 id')
6084
+ reloadBoardIfStale(rt)
6085
+ const outcome = mergeAndCleanupTaskWorktree(rt, args.id, {
6086
+ cleanup: args.cleanup !== false,
6087
+ discardOnly: args.discardOnly === true,
6088
+ })
6089
+ return Promise.resolve(outcome)
6090
+ },
6091
+ })
6092
+ console.log('[taskboard] 模型工具已注册:taskboard_list / taskboard_add / taskboard_update / taskboard_merge_worktree')
4299
6093
  }
4300
6094
 
4301
6095
  /* ------------------------------------------------------------------ *
@@ -4346,6 +6140,10 @@ export function apply(ctx) {
4346
6140
  // 启动时清一次过期归档(§1.2):宿主停机期间到期的归档不必等第一个 tick。
4347
6141
  // 只在真的有删除时写盘(pruneArchivedBoard 内部判断),因此没有副作用地复用同一路径。
4348
6142
  pruneArchivedBoard(runtime, Date.now())
6143
+ // v0.4.0:启动时自愈上次进程退出遗留的 doing + running 失联任务(顶层回退 todo,切片标 failed)。
6144
+ reconcileOrphanedDoingTasks(runtime, { startup: true, now: Date.now() }).catch((error) =>
6145
+ console.warn('[taskboard] 启动期失联任务自愈失败:' + describeError(error)),
6146
+ )
4349
6147
 
4350
6148
  // 模式状态:agentPresets 服务就绪后读名单(预设本身由 bundle patch 声明,不在这里安装)。
4351
6149
  // 预设行的激活是异步的,所以前几次读不到不算失败——最多重试 3 次再告警。