dsh-workplan 2.2.8 → 2.3.0

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/src/runtime.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { randomUUID } from 'node:crypto'
16
- import { existsSync, realpathSync, statSync } from 'node:fs'
16
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs'
17
17
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
18
18
 
19
19
  import {
@@ -1198,7 +1198,8 @@ async function disposeActivation(activation: any, record: any, subtaskId: string
1198
1198
  activation.dispose(),
1199
1199
  new Promise((_: any, reject: any) => {
1200
1200
  timer = setTimeout(() => reject(new Error('dispose timeout')), DISPOSE_TIMEOUT_MS)
1201
- timer.unref?.()
1201
+ // [2.2.9][handle-policy] 收束类(T1 报告 R6):dispose 超时臂必须真实触发,
1202
+ // unref 时裸事件循环下进程先排空、race 永不 settle 也不报错。下方 finally 照常 clearTimeout。
1202
1203
  }),
1203
1204
  ])
1204
1205
  } catch (error: any) {
@@ -1733,6 +1734,16 @@ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, i
1733
1734
  if (code === 'EVIDENCE_UNPARSABLE') {
1734
1735
  return Number(remainingMs) > Number(idleTimeoutMs)
1735
1736
  }
1737
+ /*
1738
+ * [2.2.9] 结果块缺失与 unparsable 同闸(用户 2026-11-10 红字复发族):
1739
+ * 结算的唯一载体是收尾消息块,任何异常收尾(error/截断/超时)都会丢;
1740
+ * 旧实现 missing 一次即 blocked 并级联冻结下游(看板红字「待裁决/需处理」
1741
+ * 反复出现的结构根因之一)。回喂补报(勿重做已完成工作)同样要求剩余
1742
+ * 预算大于一个空闲窗口;「最多两次」由函数开头 attempt 上限统一把关。
1743
+ */
1744
+ if (code === 'EVIDENCE_MISSING') {
1745
+ return Number(remainingMs) > Number(idleTimeoutMs)
1746
+ }
1736
1747
  return true
1737
1748
  }
1738
1749
 
@@ -2137,6 +2148,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2137
2148
  if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
2138
2149
  writeSubtaskStatus(record, subtask.id, { ackOverdue: true }, guard)
2139
2150
  }, ASSIGN_ACK_NOTICE_MS)
2151
+ // [2.2.9][handle-policy] 卫生类(T1 报告 R7):只丢一次「已下发未响应」提示,保留 unref。
2140
2152
  noticeTimer.unref?.()
2141
2153
  ackTimers.push(noticeTimer)
2142
2154
  /*
@@ -2170,7 +2182,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2170
2182
  child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }))
2171
2183
  }
2172
2184
  }, ASSIGN_ACK_DEADLINE_MS)
2173
- deadlineTimer.unref?.()
2185
+ // [2.2.9][handle-policy] 收束类(T1 报告 R2):180s no-ack 判定必须真实触发;unref 时
2186
+ // 裸循环在判定前排空、行悬死(CI cancelled 红叉根因族)。ack 与收束路径均有 clearAckTimers 清理。
2174
2187
  ackTimers.push(deadlineTimer)
2175
2188
  const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
2176
2189
  // [2.2.0][T4/O-3b][O-4d] 双计时同源(方案 §2.5):看门狗 hardMs 与本次尝试的
@@ -2354,6 +2367,59 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2354
2367
  probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists))
2355
2368
  return
2356
2369
  }
2370
+ /*
2371
+ * [2.2.9] 结果块**缺失**(子会话收尾异常:error/截断/超时)= 与 unparsable
2372
+ * 同族的有界回喂重试,且优先采纳盘上结算备份。
2373
+ *
2374
+ * 红字复发族根因(用户 2026-11-10 截图:T1 超时/缺失结算→blocked→级联
2375
+ * 冻结→「已结束·需处理」):结算唯一载体是收尾消息块,单点、原子、无
2376
+ * 盘上备份;丢块后旧实现一次即 blocked。现在两层恢复:
2377
+ * ① 盘上备份优先:子会话按提示词约定在收尾前把结果块 JSON 写入
2378
+ * reports/wp-settlement-<subtaskId>.json(见 plan.ts 子提示词);
2379
+ * 消息块缺失时读该文件重裁决,合法即照常结算(来源留档);
2380
+ * ② 无备份且预算够一个空闲窗口 → 抛 EVIDENCE_MISSING 回喂同一子会话,
2381
+ * 附在盘产物清单与「只补交结果块、勿重做已完成工作」;重试耗尽才
2382
+ * 按实 blocked(既有 settleFromOutput 路径,严格性不变:缺失永不计 done)。
2383
+ */
2384
+ if (settleVerdict && settleVerdict.verification === 'unverified'
2385
+ && /结果块缺失/.test(String(settleVerdict.error ?? ''))) {
2386
+ const settleBackup = join(options.cwd ?? process.cwd(), 'reports', `wp-settlement-${subtask.id}.json`)
2387
+ let backupVerdict: any = null
2388
+ let backupText = ''
2389
+ try {
2390
+ backupText = readFileSync(settleBackup, 'utf8')
2391
+ backupVerdict = adjudicateResult({
2392
+ output: backupText,
2393
+ strict: true,
2394
+ expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
2395
+ })
2396
+ if (!backupVerdict || /结果块缺失|无法解析/.test(String(backupVerdict.error ?? ''))) backupVerdict = null
2397
+ } catch {
2398
+ backupVerdict = null
2399
+ }
2400
+ if (backupVerdict) {
2401
+ settleFromOutput(record, subtask, backupText, guard, options, backupVerdict,
2402
+ probeInterruptedEvidence(backupText, subtask, options.cwd, options.artifactExists))
2403
+ record.errors = [
2404
+ ...(record.errors ?? []),
2405
+ `${subtask.id}: 消息结果块缺失,已采纳盘上结算备份 ${settleBackup}([2.2.9] 恢复路径)`,
2406
+ ].slice(-20)
2407
+ return
2408
+ }
2409
+ const missingLanded = probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists)
2410
+ const missingError = new PlanError(
2411
+ '结果块缺失,本次回报不能结算(工作本身不计失败)'
2412
+ + (missingLanded.length > 0
2413
+ ? `;已核到在盘产物:${missingLanded.slice(0, 6).join('、')}`
2414
+ : '')
2415
+ + '——请勿重做已完成的工作,只补交完整结构化结果块(WORKPLAN_EVIDENCE 标记成对、JSON 合法)后重新回报',
2416
+ 'EVIDENCE_MISSING',
2417
+ { subtaskId: subtask.id },
2418
+ )
2419
+ if (shouldRetryAttempt(missingError, attempt, deadline - Date.now(), idleTimeoutMs)) {
2420
+ throw missingError
2421
+ }
2422
+ }
2357
2423
  /*
2358
2424
  * [1.7.0] Evidence decides the verdict.
2359
2425
  *
@@ -2597,6 +2663,107 @@ export function extendDeadline(record: any, subtaskId: any, extendMs: any, meta:
2597
2663
  return { ok: true, deadlineAt, timerRearmed: true, watchdogRearmed: Boolean(handle.watchdog) }
2598
2664
  }
2599
2665
 
2666
+ /*
2667
+ * [2.3.0][T1] 专家执行时间机制 v2.3.0(用户 2026-11-10 四项要求,全链路):
2668
+ * (a) 预估上报 → 告知用户:recordTimeNotice 落档后向主会话推送「请把预期用时
2669
+ * 转告用户」的即时通知;
2670
+ * (b) 超时 → 放宽 → 告知专家:延期事务成功后把最新执行时限推送给执行中的专家
2671
+ * 子会话,并附「必须在保证工作质量的前提下高效率执行」硬要求;
2672
+ * (c) 二次超时 → 主 Agent 接手:runSubtaskAttempt 的到点收束对每行计数
2673
+ * (timeoutCount),第二次超时置 takeoverRequired,并用 buildTakeoverBrief
2674
+ * 登记专家已完成产物、mergePreservedArtifacts 做「禁止丢弃已完成部分」的
2675
+ * 只读保护合并。
2676
+ * 向后兼容:全部走 StatusEntry 未知字段直写通道(与 deadlineAt/timeJournal
2677
+ * 同族),回放白名单同步透传;不改任何既有判定与既有字段语义。
2678
+ */
2679
+ export const TAKEOVER_AFTER_TIMEOUTS = 2
2680
+
2681
+ /**
2682
+ * [2.3.0][T1] 组装「主 Agent 接手包」:已完成部分(专家已落盘产物 + 已登记
2683
+ * artifacts)逐条快照,未完成部分按 outputs 反推。instruction 是硬约束文案:
2684
+ * 禁止丢弃已完成部分——接手只补缺口,不整步重跑、不删除或覆盖专家产物。
2685
+ */
2686
+ export function buildTakeoverBrief(subtask: any, row: any, landedRefs: any, timeoutCount: any) {
2687
+ const refs = (Array.isArray(landedRefs) ? landedRefs : [])
2688
+ .map((item: any) => String(item ?? ''))
2689
+ .filter(Boolean)
2690
+ .slice(0, 20)
2691
+ const completedArtifacts = (Array.isArray(row?.artifacts) ? row.artifacts : [])
2692
+ .filter((item: any) => item?.kind === 'file' && typeof item?.ref === 'string' && item.ref)
2693
+ .map((item: any) => ({ kind: 'file', ref: item.ref, exists: item.exists !== false }))
2694
+ .slice(0, 20)
2695
+ const outputs = (Array.isArray(subtask?.outputs) ? subtask.outputs : [])
2696
+ .map((item: any) => String(item ?? ''))
2697
+ .filter(Boolean)
2698
+ const remainingOutputs = outputs.filter((ref: string) => !refs.includes(ref))
2699
+ return {
2700
+ at: Date.now(),
2701
+ timeoutCount: Number(timeoutCount) || 0,
2702
+ landedRefs: refs,
2703
+ completedArtifacts,
2704
+ remainingOutputs,
2705
+ instruction: '主 Agent 只接手未完成部分:landedRefs/completedArtifacts 是专家已'
2706
+ + '完成并登记保护的产物,只读、禁止丢弃、禁止删除或覆盖、禁止整步重跑;'
2707
+ + '仅继续 remainingOutputs 与未满足的验收标准。',
2708
+ }
2709
+ }
2710
+
2711
+ /**
2712
+ * [2.3.0][T1] 「禁止丢弃已完成部分」的只读保护合并(A4 硬编码点):
2713
+ * 接手登记的保护清单(takeoverBrief.landedRefs)与行上 artifacts 取并集,
2714
+ * 只增不减——任何后续对 artifacts 的写入都不可能丢掉已完成部分。
2715
+ * 纯函数,可脱离宿主回归。
2716
+ */
2717
+ export function mergePreservedArtifacts(artifacts: any, preservedRefs: any) {
2718
+ const list = (Array.isArray(artifacts) ? artifacts : [])
2719
+ .filter((item: any) => item && typeof item === 'object' && typeof item.ref === 'string')
2720
+ .map((item: any) => ({ ...item }))
2721
+ const seen = new Set(list.map((item: any) => String(item.ref)))
2722
+ for (const rawRef of Array.isArray(preservedRefs) ? preservedRefs : []) {
2723
+ const ref = String(rawRef ?? '')
2724
+ if (!ref || seen.has(ref)) continue
2725
+ // 保护条目固定 kind:'file'/exists:true:登记发生在产物确认在盘的时刻。
2726
+ list.push({ kind: 'file', ref, exists: true, preservedByTakeover: true })
2727
+ seen.add(ref)
2728
+ }
2729
+ return list.slice(-40)
2730
+ }
2731
+
2732
+ /**
2733
+ * [2.3.0][T1] 放宽成功后告知执行中的专家最新时限(A2 的「告知」半边)。
2734
+ * 走 ctx.subagents.sendMessage 与 follow-up 同一投递通道:运行中的子会话在下一
2735
+ * 步收到。投递失败不阻断延期事务(时限已经推移),只留档 record.errors。
2736
+ */
2737
+ async function notifyExpertOfExtension(ctx: any, agent: any, record: any, subtaskId: string, deadlineAt: number) {
2738
+ const row = Array.isArray(record?.statuses)
2739
+ ? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
2740
+ : null
2741
+ const childId = String(row?.childId ?? '')
2742
+ const service: any = ctx?.subagents
2743
+ if (!childId) {
2744
+ return { ok: false, error: '该行没有活跃子会话(childId 缺失),专家续跑时可从状态行 deadlineAt 读取最新时限' }
2745
+ }
2746
+ if (!service || typeof service.sendMessage !== 'function') {
2747
+ return { ok: false, error: '当前部署没有可用的 subagent 服务,无法投递延期告知' }
2748
+ }
2749
+ const remainingMin = Math.max(1, Math.ceil((Number(deadlineAt) - Date.now()) / 60000))
2750
+ const text = `【dsh-workplan·延期告知】子任务 ${subtaskId} 的执行时限已由主 Agent 放宽:`
2751
+ + `最新执行时间为 ${new Date(Number(deadlineAt)).toISOString()}(约剩 ${remainingMin} 分钟)。`
2752
+ + '你必须在保证工作质量的前提下高效率执行:优先推进高价值步骤,已完成内容及时落盘,'
2753
+ + '并在回报中明确区分「已完成 / 未完成」。收到本通知后请继续当前工作,不要重新开始。'
2754
+ try {
2755
+ await service.sendMessage(agent, childId, [{ type: 'text', text }], {})
2756
+ if (row) {
2757
+ const journal = Array.isArray(row.timeJournal) ? row.timeJournal : []
2758
+ journal.push({ at: Date.now(), action: 'notify-expert', deadlineAt: Number(deadlineAt), by: 'system' })
2759
+ row.timeJournal = journal.slice(-20)
2760
+ }
2761
+ return { ok: true }
2762
+ } catch (error: any) {
2763
+ return { ok: false, error: truncate(error instanceof Error ? error.message : String(error), 300) }
2764
+ }
2765
+ }
2766
+
2600
2767
  /*
2601
2768
  * One attempt under a deadline that belongs to that attempt alone.
2602
2769
  *
@@ -2674,7 +2841,15 @@ async function runSubtaskAttempt(
2674
2841
  // 续跑、人工裁决)。Reached only when the child ignored both its idle window
2675
2842
  // and its abort signal; the message says so, otherwise the cause looks like
2676
2843
  // a plain "too slow" and the next investigation goes down the wrong path.
2677
- const message = `子任务 ${subtask.id} 达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 决定延期 / 重试 / 接受,或转新轮续跑、人工裁决)`
2844
+ // [2.3.0][T1] 计数在组装文案前预读:第 1 次超时的文案要求「必须放宽并
2845
+ // 告知专家」;第 2 次及以后的文案要求「主 Agent 接手、已完成部分只读
2846
+ // 保护、禁止丢弃」。错误文本是结果消息/看板/续跑判定的共同来源,所以
2847
+ // 接手语义必须在这里就落进 message,而不是只进即时通知。
2848
+ const preRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
2849
+ const timeoutCountAtFire = Number(preRow?.timeoutCount ?? 0) + 1
2850
+ const message = timeoutCountAtFire >= TAKEOVER_AFTER_TIMEOUTS
2851
+ ? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑)`
2852
+ : `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 立即放宽(extendMs,放宽后插件自动告知专家最新时限与保证质量高效率要求)/ 重试 / 接受,或转新轮续跑、人工裁决)`
2678
2853
  try {
2679
2854
  // [1.8.19] Keep the evidence of what already landed on disk.
2680
2855
  const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
@@ -2705,6 +2880,40 @@ async function runSubtaskAttempt(
2705
2880
  */
2706
2881
  const settleRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
2707
2882
  if (settleRow) settleRow.pendingAdjudication = true
2883
+ /*
2884
+ * [2.3.0][T1] 超时计数与二次超时接手(用户要求 1/2 的机读落点):
2885
+ * 每次到点收束给状态行 timeoutCount +1 并记入 timeJournal(action:'timeout')。
2886
+ * 第 1 次超时 → 即时通知主 Agent「必须放宽(extendMs)并告知专家最新时限」,
2887
+ * 告知专家由延期事务自动投递(notifyExpertOfExtension);
2888
+ * 第 2 次超时 → takeoverRequired=true + buildTakeoverBrief 登记已完成部分,
2889
+ * mergePreservedArtifacts 把已落盘产物并入行 artifacts(只读保护、只增不减),
2890
+ * 主 Agent 接手只继续 remainingOutputs 与未满足验收,禁止丢弃已完成部分。
2891
+ * 计数走 StatusEntry 未知字段直写通道,回放白名单同步透传。
2892
+ */
2893
+ if (settleRow) {
2894
+ const timeoutCount = timeoutCountAtFire
2895
+ settleRow.timeoutCount = timeoutCount
2896
+ const timeoutJournal = Array.isArray(settleRow.timeJournal) ? settleRow.timeJournal : []
2897
+ timeoutJournal.push({ at: Date.now(), action: 'timeout', timeoutCount, by: 'system' })
2898
+ settleRow.timeJournal = timeoutJournal.slice(-20)
2899
+ if (timeoutCount >= TAKEOVER_AFTER_TIMEOUTS) {
2900
+ // 禁止丢弃已完成部分:接手包 + artifacts 只增不减的并集合并。
2901
+ settleRow.takeoverRequired = true
2902
+ settleRow.takeoverBrief = buildTakeoverBrief(subtask, settleRow, ceilingLanded, timeoutCount)
2903
+ settleRow.artifacts = mergePreservedArtifacts(settleRow.artifacts, settleRow.takeoverBrief.landedRefs)
2904
+ }
2905
+ try {
2906
+ const takeoverText = timeoutCount >= TAKEOVER_AFTER_TIMEOUTS
2907
+ ? `子任务 ${subtask.id} 已第 ${timeoutCount} 次达到协商时限(二次超时):按 2.3.0 机制本行已置「主 Agent 接手」(takeoverRequired)。`
2908
+ + `专家已完成并登记保护的部分(只读、禁止丢弃):${(ceilingLanded as string[]).slice(0, 8).join('、') || '(见 takeoverBrief)'};`
2909
+ + '请主 Agent 直接接手继续未完成部分,不要整步重跑、不要删除或覆盖已登记产物。'
2910
+ : `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
2911
+ + '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。'
2912
+ announceSubtaskInterrupt(record, options.session ?? options.agent?.session, subtask.id, takeoverText)
2913
+ } catch {
2914
+ // 通知失败不影响结算(与预警同一纪律)。
2915
+ }
2916
+ }
2708
2917
  record.updatedAt = Date.now()
2709
2918
  } catch (error: any) {
2710
2919
  record.errors = [
@@ -2941,6 +3150,23 @@ export function modelStatusLines(statuses: any) {
2941
3150
  timeWarning: item.timeWarning ?? null,
2942
3151
  timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
2943
3152
  pendingAdjudication: item.pendingAdjudication === true,
3153
+ // [2.3.0][T1] 预估上报(A1)也要进模型可读面:主 Agent 告知用户前先读这里。
3154
+ timeNotice: item.timeNotice ?? null,
3155
+ /*
3156
+ * [2.3.0][T1] 超时计数 / 二次超时接手进入模型可读面:主 Agent 一眼能看出
3157
+ * 该行第几次超时、是否必须接手、接手包里哪些是只读保护的已完成产物。
3158
+ */
3159
+ timeoutCount: Number(item.timeoutCount ?? 0),
3160
+ takeoverRequired: item.takeoverRequired === true,
3161
+ takeoverBrief: item.takeoverBrief ?? null,
3162
+ /*
3163
+ * [2.3.0][T1] 已完成产物的只读保护登记必须进模型可读面:statusTool 的行
3164
+ * 来自本函数,此前不序列化 artifacts,导致 takeoverRequired 的「禁止丢弃
3165
+ * 已完成部分」清单对主 Agent 不可见。只透出对象形条目,照录不改写。
3166
+ */
3167
+ artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
3168
+ .filter((entry: any) => entry && typeof entry === 'object' && typeof entry.ref === 'string')
3169
+ .map((entry: any) => ({ ...entry })),
2944
3170
  /*
2945
3171
  * [2.2.0][T3/O-2a] 子→主预告通道的结论必须进入模型可读面。
2946
3172
  *
@@ -3112,7 +3338,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
3112
3338
  // [2.2.5][热修] 双重保险:即使哨兵值/配置未来被改成超限值,也把延时钳在
3113
3339
  // Node setTimeout 上限之内,杜绝“1ms 触发”的整轮秒杀。
3114
3340
  }, Math.min(Math.max(1000, deadline - Date.now()), ROUND_TIMER_MAX_MS))
3115
- totalTimer.unref?.()
3341
+ // [2.2.9][handle-policy] 收束类(T1 报告 R1,P0):轮次总预算计时器必须真实触发(与 2.2.8
3342
+ // 已修的 attempt 上限计时器同构);unref 时裸循环在 TOTAL_TIMEOUT 前排空 → node:test 判
3343
+ // cancelledByParent → CI 红叉。收束路径 finally 有 clearTimeout(totalTimer),不会悬挂宿主。
3116
3344
  record.dispatchedAt = Date.now()
3117
3345
  record.phase = 'executing'
3118
3346
  record.updatedAt = record.dispatchedAt
@@ -3871,7 +4099,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
3871
4099
  for (const entry of (Array.isArray(result.statuses) ? result.statuses : [])) {
3872
4100
  const rebuiltRow = snap.statuses.find((item: any) => item?.subtaskId === entry?.subtaskId)
3873
4101
  if (!rebuiltRow || !isRecord(entry)) continue
3874
- for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
4102
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
3875
4103
  if (entry[field] !== undefined) rebuiltRow[field] = entry[field]
3876
4104
  }
3877
4105
  /*
@@ -4038,7 +4266,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
4038
4266
  */
4039
4267
  const replayRow = snap.statuses.find((item: any) => item?.subtaskId === update.subtaskId)
4040
4268
  if (replayRow) {
4041
- for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
4269
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
4042
4270
  if (update[field] !== undefined) replayRow[field] = update[field]
4043
4271
  }
4044
4272
  const replayExtend = Number(update.extendMs)
@@ -4738,7 +4966,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
4738
4966
  * 路由分支,按 T4 直写通道写行(StatusEntry 保留未知字段;回放白名单已透传
4739
4967
  * timeNotice,刷新后不丢)。
4740
4968
  */
4741
- function recordTimeNotice(record: any, subtaskId: string, notice: any) {
4969
+ function recordTimeNotice(record: any, subtaskId: string, notice: any, session?: any) {
4742
4970
  const row = Array.isArray(record?.statuses)
4743
4971
  ? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
4744
4972
  : null
@@ -4761,6 +4989,23 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
4761
4989
  })
4762
4990
  row.timeJournal = journal.slice(-20)
4763
4991
  record.updatedAt = at
4992
+ /*
4993
+ * [2.3.0][T1] 预估上报 → 告知用户(用户要求 1 的前半段闭环):专家的开工
4994
+ * 预告落档后,插件立即向主会话推送一条即时通知,明确「请把此预期执行
4995
+ * 时间告知用户」;新预告覆盖旧预告(每条新预告各通知一次,与「开工预告」
4996
+ * 协议一致)。通知是观测设施:写失败只留档 errors,绝不影响记录与执行。
4997
+ */
4998
+ if (session) {
4999
+ try {
5000
+ appendUserMessage(session, `【dsh-workplan·专家预估上报】子任务 ${subtaskId} 的执行专家`
5001
+ + `预估执行时间 ${Number(notice?.declaredMinutes)} 分钟`
5002
+ + (reason ? `(${reason})` : '')
5003
+ + `;请把此预期执行时间告知用户。若执行中超时,请主 Agent 放宽(extendMs)`
5004
+ + '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。')
5005
+ } catch (error: any) {
5006
+ record.errors = [...(record.errors ?? []), `${subtaskId} 预估上报通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20)
5007
+ }
5008
+ }
4764
5009
  }
4765
5010
 
4766
5011
  async function updateStatus(agent: any, args: any): Promise<any> {
@@ -4935,7 +5180,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
4935
5180
  * [2.2.0][T5/O-4c] 预告与指示同一次到达时,指示成功落行后再记预告:
4936
5181
  * 指示失败不该留下一笔「专家已预告」的记录。
4937
5182
  */
4938
- if (hasTimeNotice && instructed?.ok !== false) recordTimeNotice(record, subtaskId, timeNoticeArg)
5183
+ if (hasTimeNotice && instructed?.ok !== false) recordTimeNotice(record, subtaskId, timeNoticeArg, session)
4939
5184
  return instructed
4940
5185
  }
4941
5186
  if (current?.closure === 'escalated') {
@@ -5002,9 +5247,17 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5002
5247
  }
5003
5248
  }
5004
5249
  extension = extended
5250
+ /*
5251
+ * [2.3.0][T1] 用户要求 1 后半段:放宽成功后必须把「最新执行时间」告知
5252
+ * 专家,同时附「必须在保证工作质量的前提下高效率执行」硬要求,让专家
5253
+ * 有准备(收到通知继续当前工作,不重新开始)。投递失败不回滚延期——
5254
+ * 时限已经推移,只是告知通道未达:留档 errors,回执带 childNotified
5255
+ * 供主 Agent 决定是否用 dsh_workplan_followup 补发。
5256
+ */
5257
+ extension.childNotified = (await notifyExpertOfExtension(ctx, agent, record, subtaskId, extension.deadlineAt)).ok
5005
5258
  }
5006
5259
  if (!statusRequested) {
5007
- if (hasTimeNotice) recordTimeNotice(record, subtaskId, timeNoticeArg)
5260
+ if (hasTimeNotice) recordTimeNotice(record, subtaskId, timeNoticeArg, session)
5008
5261
  /*
5009
5262
  * 纯时限事务到此结束。方案 §2.2 效果 3:状态行 revision +1(延期/预告也是
5010
5263
  * 行变更,同样受 STALE_WRITE 乐观锁保护);状态与判定一个字段都不改。
@@ -5030,6 +5283,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5030
5283
  deadlineAt: extension.deadlineAt,
5031
5284
  timerRearmed: extension.timerRearmed,
5032
5285
  watchdogRearmed: extension.watchdogRearmed,
5286
+ childNotified: extension.childNotified === true,
5033
5287
  }
5034
5288
  : {}),
5035
5289
  ...(hasTimeNotice ? { timeNotice: written?.timeNotice ?? null } : {}),
@@ -5073,11 +5327,24 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5073
5327
  revision,
5074
5328
  updatedBy: 'agent',
5075
5329
  })
5330
+ /*
5331
+ * [2.3.0][T1] 禁止丢弃已完成部分(A4 的第二个硬编码保护点):接手行
5332
+ * (takeoverRequired)后续任何一次 artifacts 写入,都把 takeoverBrief 登记
5333
+ * 的保护产物并集合并回来——只增不减,主 Agent 改判时不可能删掉专家已完成
5334
+ * 的产物清单,只能在其基础上补缺口。
5335
+ */
5336
+ if (args?.artifacts !== undefined) {
5337
+ const protectedRow = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
5338
+ if (protectedRow?.takeoverRequired === true && Array.isArray(protectedRow?.takeoverBrief?.landedRefs)
5339
+ && protectedRow.takeoverBrief.landedRefs.length > 0) {
5340
+ protectedRow.artifacts = mergePreservedArtifacts(protectedRow.artifacts, protectedRow.takeoverBrief.landedRefs)
5341
+ }
5342
+ }
5076
5343
  /*
5077
5344
  * [2.2.0][T5/O-4c] 带 status 的调用同时带 timeNotice 时,预告记录在改判落行
5078
5345
  * 之后写入:applyStatus 抛错(如非法 verification)时不会留下半写的预告。
5079
5346
  */
5080
- if (hasTimeNotice) recordTimeNotice(record, subtaskId, timeNoticeArg)
5347
+ if (hasTimeNotice) recordTimeNotice(record, subtaskId, timeNoticeArg, session)
5081
5348
  if (status === 'blocked') {
5082
5349
  record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' })
5083
5350
  }
@@ -5675,7 +5942,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5675
5942
  ctx.logger?.warn?.(`dsh-workplan: 自动续跑失败:${error instanceof Error ? error.message : String(error)}`)
5676
5943
  }
5677
5944
  }, decision.delayMs)
5678
- timer.unref?.()
5945
+ // [2.2.9][handle-policy] 收束类(T1 报告 R3):自动续跑计时器是计划走向下一轮的唯一驱动,
5946
+ // unref 时裸循环下续跑永不发生、计划静默停摆。clearAutoResumeTimer 在人工派发/状态写入/
5947
+ // 取消/指示/dispose/rearm 各路径统一撤销;延时自身有界,不会悬挂宿主。
5679
5948
  book.timer = timer
5680
5949
  return decision
5681
5950
  }
@@ -6298,6 +6567,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
6298
6567
  }
6299
6568
  stop()
6300
6569
  }, INSTRUCTION_POLL_MS)
6570
+ // [2.2.9][handle-policy] 卫生类(T1 报告 R8):回执轮询只提供提前确认,deadline 判定兜底,保留 unref。
6301
6571
  poll.unref?.()
6302
6572
  timers.push(poll)
6303
6573
  const notice = setTimeout(() => {
@@ -6308,6 +6578,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
6308
6578
  // The row moved on between the read and the write; nothing to report.
6309
6579
  }
6310
6580
  }, INSTRUCTION_ACK_NOTICE_MS)
6581
+ // [2.2.9][handle-policy] 卫生类(T1 报告 R9):只丢一次「指示未回执」提示,保留 unref。
6311
6582
  notice.unref?.()
6312
6583
  timers.push(notice)
6313
6584
  const deadline = setTimeout(() => {
@@ -6331,7 +6602,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
6331
6602
  }
6332
6603
  stop()
6333
6604
  }, INSTRUCTION_ACK_DEADLINE_MS)
6334
- deadline.unref?.()
6605
+ // [2.2.9][handle-policy] 收束类(T1 报告 R5):指示 no-ack 判定必须真实触发;触发/回执即 stop()
6606
+ // 清掉整组计时器,延时有界(INSTRUCTION_ACK_DEADLINE_MS),不会悬挂宿主。
6335
6607
  timers.push(deadline)
6336
6608
  }
6337
6609
 
package/src/watchdog.ts CHANGED
@@ -262,7 +262,8 @@ export function createProgressWatchdog(input: {
262
262
  }
263
263
 
264
264
  timer = setInterval(poll, pollMs)
265
- timer.unref?.()
265
+ // [2.2.9][handle-policy] 收束类(T1 报告 R4):看门狗是卡死子任务的最后收束保证,unref 时
266
+ // 裸循环下看门狗失效。finish()/stop() 均 clearInterval,生命周期与子任务尝试绑定,不会悬挂宿主。
266
267
 
267
268
  return {
268
269
  fired,