dsh-workplan 2.2.6 → 2.2.7

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
@@ -81,6 +81,7 @@ import {
81
81
  parseUpdateMessage,
82
82
  buildUpdateMessage,
83
83
  normaliseHandoffs,
84
+ mergeHandoffEntriesByUpdatedAt,
84
85
  needEntryText,
85
86
  openHandoffs,
86
87
  DEPARTMENTS,
@@ -170,7 +171,26 @@ function liveStatuses(statuses: any) {
170
171
  * `changeRequest.pending`(执行中收到、尚未重规划的变更)与 `reportPending`
171
172
  * (完成结果还没写进会话)只存在于 `record` 而不是 `statuses`,所以必须在
172
173
  * 这一层显式传入;`plan.ts` 的 `deliveryReadiness` 因此仍是纯函数。
174
+ *
175
+ * [2.2.9][T3][M4.1] `reportPending` 不再读 `record.reportPending` 可变标志。
176
+ * 事故实证(wp-215ed52f 症状②):门禁读标志、看板读标志、消息冻结读标志,
177
+ * 而该标志在 finishRound/markReported/自愈/重建多处的写入时机互不同步,
178
+ * 判定结果随读取落在哪个时间窗口而翻转——「可交付↔未放行」来回震荡。
179
+ * 现在门禁、看板、stop-steer、消息冻结、自愈全部读同一个纯派生函数
180
+ * `deriveReportPending(record)`:事实只有 statuses(经 T2 单调闸的终态),
181
+ * 标志降级为审计镜像。blocked/pending 行不是 done,永不触发该阻塞。
173
182
  */
183
+ export function deriveReportPending(record: any): boolean {
184
+ const statuses = Array.isArray(record?.statuses) ? record.statuses : []
185
+ /*
186
+ * [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
187
+ * 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
188
+ * 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
189
+ * 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
190
+ */
191
+ return statuses.some((item: any) => item?.status === 'done' && item?.closure === 'done')
192
+ }
193
+
174
194
  function readinessOf(record: any, snapshot?: any) {
175
195
  const snap = snapshot ?? derivePlanSnapshot(
176
196
  record?.plan ? blockCancelledDependents(record.plan, record?.statuses) : record?.statuses,
@@ -179,7 +199,7 @@ function readinessOf(record: any, snapshot?: any) {
179
199
  return deliveryReadiness(snap, {
180
200
  phase: record?.phase,
181
201
  changePending: record?.changeRequest?.status === 'pending',
182
- reportPending: record?.reportPending === true,
202
+ reportPending: deriveReportPending(record),
183
203
  /*
184
204
  * 计划定义的验收标准是交付门的另一半:状态行只回答「子 Agent 说通过
185
205
  * 了几条」,这里回答「计划要求的几条有没有被逐条回应」。
@@ -219,13 +239,97 @@ export const PLANNER_HARD_MULTIPLIER = 3
219
239
  *
220
240
  * 用户规则(AGENTS.md 第 12 条)只说过「子 Agent 不得继承主 Agent 的等级」,
221
241
  * 规划器同样是主 Agent 派出的子调用:任务里明确授权「规划器停止继承」。规划
222
- * 本身属于「跨多个系统梳理根因并给出方案」——按同一条三档规则属非常复杂 →
223
- * max。`DSH_WORKPLAN_PLANNER_REASONING_EFFORT` 仍可显式覆盖(用户为降本/提速
242
+ * 本身属于「跨多个系统梳理根因并给出方案」——按五档规则(轻度=low/中等=
243
+ * medium或high/非常复杂=xhigh或max)属非常复杂 → 默认取 max(五档内的最高
244
+ * 档;xhigh 留给显式覆盖)。`DSH_WORKPLAN_PLANNER_REASONING_EFFORT` 仍可显式
245
+ * 覆盖(用户为降本/提速
224
246
  * 主动选择低档时有效),未设或非法时才用本默认值;**绝不读取
225
247
  * modelSelection.reasoningEffort**。旧行为(plannerEffort || 主 Agent 档位)会
226
248
  * 让主 Agent 的 low/high 直接决定拆解质量,与「子 Agent 自决档位」同源、同错。
227
249
  */
228
250
  export const DEFAULT_PLANNER_REASONING_EFFORT = 'max'
251
+
252
+ /*
253
+ * [2.2.7] 推理档位兼容性钳制(用户 2026-11-09 报告的 PLANNER_LLM_ERROR 根因修复)。
254
+ *
255
+ * 宿主 dsh-llm 会在发起网络请求之前,把请求的 reasoningEffort 与该模型声明的
256
+ * `reasoning.efforts` 清单逐一比对,不在清单内即抛 UNSUPPORTED_REASONING_EFFORT
257
+ * (本地失败、重试不会自愈)。规划器默认 max、子任务档位允许 low / medium /
258
+ * high / xhigh / max 五档——这些都假设主链路模型支持相应档位。一旦运行在
259
+ * qwen 这类只声明 low/medium/xhigh 的模型上,第一次规划调用就被宿主拒绝,
260
+ * 整个自动分解降级;
261
+ * 同一枚雷也埋在派发侧:计划里的 high/max/xhigh 行派给 qwen 子会话会同样即抛。
262
+ *
263
+ * 治本方案不是按模型名字猜档位(家族无穷、名单过时),而是在发送任何带档位的
264
+ * 请求前,用宿主公开能力面 `llm.resolveModelInfo` 读出目标模型**实际声明**的
265
+ * 档位清单,把请求档位钳制到清单内强度最接近的一档:
266
+ * - 清单包含请求档位 ⇒ 原样发送(模型声明支持五档时,low/medium/high/xhigh/max
267
+ * 全部原样透传,不钳制);
268
+ * - 否则取「不高于请求档」里最高的支持档(max→xhigh、high→medium…);
269
+ * [2.2.7][T4/五档] 五档请求落在三档清单(low/high/max)上的降级序按强度表
270
+ * 逐级下探:max 原样、xhigh→high、high 原样、medium→low、low 原样;落在
271
+ * qwen 型清单(low/medium/xhigh)上:max→xhigh、xhigh 原样、high→medium、
272
+ * medium 原样、low 原样。降级序即 EFFORT_STRENGTH_ORDER 中「不高于请求档」
273
+ * 的最近支持档,任何合法五档值都不会被拒绝或清空;
274
+ * - 全部支持档都强于请求档 ⇒ 取最弱支持档(宁可降质,不可失败);
275
+ * - 模型根本没有 reasoning 元数据(空清单)⇒ 不发送 reasoningEffort 字段,
276
+ * 与宿主 resolveCallWithInfo 的「reasoning===undefined 时任何档位都抛错」对齐;
277
+ * - 能力查询不可用(宿主不暴露 / 查询抛错)⇒ 保持旧行为,绝不因钳制引入新故障。
278
+ */
279
+ const EFFORT_STRENGTH_ORDER: readonly string[] = Object.freeze(
280
+ ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'],
281
+ )
282
+
283
+ /** 请求档位 → 模型支持清单内的等效钳制档;空清单返回 undefined(= 不发送该字段)。 */
284
+ export function clampEffortToSupported(effort: string, supported: readonly string[] | null | undefined): string | undefined {
285
+ if (!Array.isArray(supported) || supported.length === 0) return undefined
286
+ if (supported.includes(effort)) return effort
287
+ const rank = (id: string) => EFFORT_STRENGTH_ORDER.indexOf(id)
288
+ const ranked = [...supported].sort((a, b) => {
289
+ const ra = rank(a)
290
+ const rb = rank(b)
291
+ if (ra === rb) return 0
292
+ if (ra < 0) return 1
293
+ if (rb < 0) return -1
294
+ return ra - rb
295
+ })
296
+ const target = rank(effort)
297
+ if (target < 0) return ranked[ranked.length - 1]
298
+ const atOrBelow = ranked.filter((id) => rank(id) >= 0 && rank(id) <= target)
299
+ if (atOrBelow.length > 0) return atOrBelow[atOrBelow.length - 1]
300
+ return ranked[0]
301
+ }
302
+
303
+ const supportedEffortsCache = new Map<string, string[]>()
304
+
305
+ /**
306
+ * 读取 provider/model 声明的推理档位清单。
307
+ * @returns 档位 id 数组(可为空数组 = 模型不支持任何档位);null = 无从判定,调用方保持旧行为。
308
+ */
309
+ export async function resolveSupportedEfforts(
310
+ llm: any,
311
+ provider?: string,
312
+ model?: string,
313
+ signal?: any,
314
+ ): Promise<string[] | null> {
315
+ if (!llm || typeof llm.resolveModelInfo !== 'function' || !provider || !model) return null
316
+ const key = `${provider}/${model}`
317
+ const hit = supportedEffortsCache.get(key)
318
+ if (hit) return hit
319
+ if (signal?.aborted) return null
320
+ try {
321
+ const info = await llm.resolveModelInfo(provider, model, signal)
322
+ const efforts = info?.reasoning?.efforts
323
+ const list = Array.isArray(efforts)
324
+ ? efforts.map((item: any) => String(item?.id ?? '')).filter((id: string) => id !== '')
325
+ : []
326
+ supportedEffortsCache.set(key, list)
327
+ return list
328
+ } catch {
329
+ // 查询失败 ⇒ 与「宿主不暴露该能力」同等处理:不钳制、不缓存、不阻断。
330
+ return null
331
+ }
332
+ }
229
333
  /**
230
334
  * Absolute ceiling for one child execution.
231
335
  *
@@ -685,12 +789,14 @@ export async function runPlanner(ctx: any, options: any) {
685
789
  * - DSH_WORKPLAN_PLANNER_MAX_TOKENS:给单次生成封顶。无界生成是「流满 900 秒
686
790
  * 撞绝对上限」的放大器——封顶后模型会正常 finish,截断可被抢救/回喂;
687
791
  * - DSH_WORKPLAN_PLANNER_REASONING_EFFORT:规划专用推理档,只接受
688
- * low / high / max 三档。非法值不传给模型,回落默认档(见下)。
792
+ * low / medium / high / xhigh / max 五档。非法值不传给模型,回落默认档(见下)。
689
793
  *
690
794
  * [2.2.0][T13b] 用户 2026-11-08 决策 5「规划器停止继承」:未设该旋钮时,规划器
691
795
  * 不再沿用主 Agent 的推理档,而是取 DEFAULT_PLANNER_REASONING_EFFORT(max)。
692
- * 校验白名单复用 plan.ts 的 REASONING_EFFORTS:把 "ultra"/"medium" 这类非法值
693
- * 原样发给模型,真实宿主会以 400 拒绝整次规划——环境变量写错不应该让整个
796
+ * 校验白名单复用 plan.ts 的 REASONING_EFFORTS(五档:low / medium / high /
797
+ * xhigh / max;[2.2.7][T4] 由三档扩五档,medium/xhigh 现为合法值):把
798
+ * "ultra"/"minimal" 这类非法值原样发给模型,真实宿主会以 400 拒绝整次规划——
799
+ * 环境变量写错不应该让整个
694
800
  * 任务降级,所以非法值按「未设置」处理。
695
801
  */
696
802
  const plannerMaxTokens = normalisePlannerWindow(process.env.DSH_WORKPLAN_PLANNER_MAX_TOKENS, 0)
@@ -698,7 +804,31 @@ export async function runPlanner(ctx: any, options: any) {
698
804
  // 用户的成本预期,所以先归一化再进白名单。
699
805
  const plannerEffortRaw = String(process.env.DSH_WORKPLAN_PLANNER_REASONING_EFFORT ?? '').trim().toLowerCase()
700
806
  const plannerEffort = REASONING_EFFORTS.includes(plannerEffortRaw) ? plannerEffortRaw : ''
701
- const effectivePlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT
807
+ const requestedPlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT
808
+ /*
809
+ * [2.2.7] 发送前按模型能力钳制档位:宿主对不支持的档位会在网络调用前直接
810
+ * 抛 UNSUPPORTED_REASONING_EFFORT,重试不自愈(终态),整次规划因此降级。
811
+ * 查询不可用时保持旧行为;查询到清单后请求档钳制到清单内等效档,空清单
812
+ * (模型无 reasoning 元数据)则不发送档位字段。'' 在这里表示「不发送」。
813
+ */
814
+ const plannerEffortSupport = await resolveSupportedEfforts(
815
+ ctx.llm,
816
+ modelSelection?.provider,
817
+ modelSelection?.model,
818
+ signal,
819
+ )
820
+ const effectivePlannerEffort = plannerEffortSupport === null
821
+ ? requestedPlannerEffort
822
+ : (clampEffortToSupported(requestedPlannerEffort, plannerEffortSupport) ?? '')
823
+ if (plannerEffortSupport !== null && effectivePlannerEffort !== requestedPlannerEffort) {
824
+ console.warn('[dsh-workplan] planner reasoning effort clamped for model compatibility:', JSON.stringify({
825
+ provider: modelSelection?.provider,
826
+ model: modelSelection?.model,
827
+ requested: requestedPlannerEffort,
828
+ effective: effectivePlannerEffort || '(omitted)',
829
+ supported: plannerEffortSupport,
830
+ }))
831
+ }
702
832
  const secs = (ms: number) => Math.max(1, Math.round(ms / 1000))
703
833
  let lastErrors: string[] = []
704
834
  /*
@@ -803,7 +933,8 @@ export async function runPlanner(ctx: any, options: any) {
803
933
  const stream = ctx.llm.stream({
804
934
  provider: modelSelection.provider,
805
935
  model: modelSelection.model,
806
- reasoningEffort: effectivePlannerEffort,
936
+ // [2.2.7] '' = 模型无 reasoning 元数据,不发送档位字段(发送必被宿主拒绝)。
937
+ ...(effectivePlannerEffort ? { reasoningEffort: effectivePlannerEffort } : {}),
807
938
  ...(plannerMaxTokens > 0 ? { maxTokens: plannerMaxTokens } : {}),
808
939
  messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
809
940
  signal: controller.signal,
@@ -974,8 +1105,11 @@ export async function runPlanner(ctx: any, options: any) {
974
1105
  // [2.2.0][T13b] 记录**实际发给模型**的档位:旧值记的是 modelSelection
975
1106
  // (主 Agent 档位),规划器停止继承后它不再等于生效值,照抄会让事后
976
1107
  // 复盘把「主 Agent=high」误读成「规划器=high」。
1108
+ // [2.2.7] 钳制发生时同样记录实际发出值('' = 未发送)。
977
1109
  reasoningEffort: effectivePlannerEffort,
978
- reasoningEffortSource: plannerEffort ? 'env' : 'default-max',
1110
+ reasoningEffortSource: (plannerEffort ? 'env' : 'default-max')
1111
+ + (plannerEffortSupport !== null && effectivePlannerEffort !== requestedPlannerEffort
1112
+ ? `→clamped(${requestedPlannerEffort})` : ''),
979
1113
  attempt,
980
1114
  taskChars: typeof taskText === 'string' ? taskText.length : 0,
981
1115
  promptChars,
@@ -1386,7 +1520,21 @@ export function budgetResetError(item: any, subtask: any, cwd: any, artifactExis
1386
1520
  * the session replay cannot disagree. This wrapper only adds the two things
1387
1521
  * that need the environment: the strict/legacy switch and the file check.
1388
1522
  */
1389
- function settleFromOutput(record: any, subtask: any, output: any, guard: SubtaskGuard, options: any) {
1523
+ function settleFromOutput(
1524
+ record: any,
1525
+ subtask: any,
1526
+ output: any,
1527
+ guard: SubtaskGuard,
1528
+ options: any,
1529
+ /*
1530
+ * [2.2.8][T7] 两个可选入参:`precomputedVerdict` 让调用方把已经裁决过的
1531
+ * 结果直接传入(unparsable 门在结算前判定过一次,纯函数重算是浪费也是
1532
+ * 双源);`extraEvidence` 只在「解析失败重试耗尽、按实受阻」时传入——
1533
+ * 它把 attempt 摘要/声明产物在盘上的事实随 blocked 行留档。
1534
+ */
1535
+ precomputedVerdict?: any,
1536
+ extraEvidence?: { artifacts: any[]; missingArtifacts: string[] } | null,
1537
+ ) {
1390
1538
  /*
1391
1539
  * [1.11.0] 已经升级的请示不能被收尾正文覆盖。
1392
1540
  *
@@ -1397,7 +1545,7 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
1397
1545
  */
1398
1546
  const current = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
1399
1547
  if (current?.closure === 'escalated') return { status: 'blocked', escalated: true }
1400
- const verdict = adjudicateResult({
1548
+ const verdict = precomputedVerdict ?? adjudicateResult({
1401
1549
  output,
1402
1550
  strict: options.strictEvidence !== false,
1403
1551
  /*
@@ -1412,6 +1560,26 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
1412
1560
  const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
1413
1561
  const escalated = verdict.status === 'blocked'
1414
1562
  && typeof verdict.question === 'string' && verdict.question.trim() !== ''
1563
+ /*
1564
+ * [2.2.8][T7] 解析失败重试耗尽后的受阻,不得退化成「零产出失败」。
1565
+ *
1566
+ * T4 实证:子会话工作已完成、交付物已在盘上,只是结果块 JSON 写坏了;
1567
+ * 旧账本只留一句「结果块 JSON 非法」,主 Agent 无从知道产物存在,只能
1568
+ * 级联下游重做。现在把 attempt 摘要/声明产物中**确实在盘上**的清单随
1569
+ * blocked 行留档,并在 error 文案里给出「用 dsh_workplan_update 复核改判」
1570
+ * 的出口。语义不变:非法 JSON 依旧不计 done,这里只是把事实说全。
1571
+ */
1572
+ const landedRefs = (extraEvidence?.artifacts ?? [])
1573
+ .filter((item: any) => item?.exists === true)
1574
+ .map((item: any) => String(item?.ref ?? ''))
1575
+ .filter((ref: string) => ref !== '')
1576
+ const reviewNote = landedRefs.length > 0
1577
+ ? `;本次回报声明的产物清单已随本行留档(已在盘上:${landedRefs.slice(0, 6).join('、')})——产物已在盘上,`
1578
+ + '请先用 dsh_workplan_update 复核改判,勿按零产出处理,也不要级联阻断下游'
1579
+ : ''
1580
+ const settleError = typeof verdict.error === 'string' && verdict.error !== ''
1581
+ ? `${verdict.error}${reviewNote}`
1582
+ : verdict.error
1415
1583
  /*
1416
1584
  * [2.0.0] 自我学习闭环的出口:完成且带复盘证据时,立刻写入永久记忆。
1417
1585
  *
@@ -1445,11 +1613,15 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
1445
1613
  progress: 100,
1446
1614
  finishedAt: Date.now(),
1447
1615
  summary: truncate(lessonNote ? `${output}\n[自我学习] ${lessonNote}` : output, 3000),
1448
- error: verdict.error,
1616
+ error: settleError,
1449
1617
  verification: verdict.verification,
1450
1618
  acceptance: verdict.acceptance,
1451
- artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
1452
- missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
1619
+ artifacts: checked.artifacts.length > 0
1620
+ ? checked.artifacts
1621
+ : (extraEvidence && extraEvidence.artifacts.length > 0 ? extraEvidence.artifacts : undefined),
1622
+ missingArtifacts: checked.missingArtifacts.length > 0
1623
+ ? checked.missingArtifacts
1624
+ : (extraEvidence && extraEvidence.missingArtifacts.length > 0 ? extraEvidence.missingArtifacts : undefined),
1453
1625
  needs: verdict.needs.length > 0 ? verdict.needs : undefined,
1454
1626
  /*
1455
1627
  * [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
@@ -1486,7 +1658,7 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
1486
1658
  }),
1487
1659
  }, guard)
1488
1660
  if (verdict.status === 'blocked') {
1489
- recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (verdict.error ?? '未完成'), guard)
1661
+ recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (settleError ?? '未完成'), guard)
1490
1662
  } else if (checked.missingArtifacts.length > 0) {
1491
1663
  recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
1492
1664
  }
@@ -1552,11 +1724,65 @@ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, i
1552
1724
  if (code === 'CHILD_NOT_COMPLETED') {
1553
1725
  return Number(remainingMs) > Number(idleTimeoutMs)
1554
1726
  }
1727
+ /*
1728
+ * [2.2.8][T7] 结果块解析失败与 CHILD_NOT_COMPLETED 走同一道闸(用户 2026-11-09
1729
+ * 报告 T4 事故:非法 JSON 一次即 blocked,并级联阻断下游;子会话其实已完成
1730
+ * 工作,只差一个合法回报)。回喂重报要有意义,必须还剩超过一个空闲窗口的
1731
+ * 预算;「最多两次」由函数开头的 attempt 上限统一把关,不会无限循环。
1732
+ */
1733
+ if (code === 'EVIDENCE_UNPARSABLE') {
1734
+ return Number(remainingMs) > Number(idleTimeoutMs)
1735
+ }
1736
+ return true
1737
+ }
1738
+
1739
+ /*
1740
+ * [2.2.7] 执行中断即时通知(用户 2026-11-09 报告的第二个缺陷)。
1741
+ *
1742
+ * 缺陷现场:部门专家执行中被中断(子会话报错、重试、no-ack、预算耗尽)时,
1743
+ * 主会话直到整轮结束才随结果消息一并交代——期间用户只看到进度不动,无法区分
1744
+ * 「在慢慢做」与「已经失败」,只能干着急。既有即时通道只覆盖 done
1745
+ * (emitSubtaskDoneNotice)与到点预警;中断类事件全走 record.errors(只有
1746
+ * 主 Agent 下次读记录才可见)。
1747
+ *
1748
+ * 这里补上同构的「中断即报」:中断一发生就往主会话写一条纯文本 user/message,
1749
+ * 文案固定三段——发生什么(含错误码与真因摘录)、系统正在怎么处理(重试/收束/
1750
+ * 待裁决)、对用户意味着什么(不是任务失败终局)。频率纪律:每个子任务整轮
1751
+ * 至多 INTERRUPT_NOTICE_CAP 条,写失败只留档到 record.errors,绝不影响执行。
1752
+ * 消息不带 workplan 标记,回放解析器按未知消息跳过(与完成通知同一纪律)。
1753
+ */
1754
+ const INTERRUPT_NOTICE_CAP = 3
1755
+ export function announceSubtaskInterrupt(
1756
+ record: any,
1757
+ session: any,
1758
+ subtaskId: string,
1759
+ text: string,
1760
+ ): boolean {
1761
+ if (!record || !session || typeof session.append !== 'function') return false
1762
+ const row = Array.isArray(record.statuses)
1763
+ ? record.statuses.find((item: any) => item?.subtaskId === subtaskId)
1764
+ : null
1765
+ const sent = Number(row?.interruptNoticeCount ?? 0)
1766
+ if (sent >= INTERRUPT_NOTICE_CAP) return false
1767
+ const notice = `【dsh-workplan·执行中断】${truncate(String(text ?? '').replace(/\s+/g, ' ').trim(), 400)}`
1768
+ try {
1769
+ appendUserMessage(session, notice)
1770
+ } catch (error: any) {
1771
+ record.errors = [...(record.errors ?? []), `${subtaskId} 中断通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20)
1772
+ return false
1773
+ }
1774
+ if (row) row.interruptNoticeCount = sent + 1
1555
1775
  return true
1556
1776
  }
1557
1777
 
1558
1778
  async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
1559
1779
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
1780
+ /*
1781
+ * [2.2.7] 中断即报的目标会话:与 noticeChannel/finaliseNotice 同一取值链,
1782
+ * 拿不到就安静跳过(通知是观测设施,不是交付物)。
1783
+ */
1784
+ const interruptSession = () => options.session ?? options.agent?.session
1785
+ ?? findSession(ctx, String(record?.plan?.sessionId ?? ''))
1560
1786
  let lastError: any = null
1561
1787
  /*
1562
1788
  * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
@@ -1751,6 +1977,34 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
1751
1977
  } catch {
1752
1978
  lessonsBrief = ''
1753
1979
  }
1980
+ /*
1981
+ * [2.2.7] 子会话档位同样要过模型能力这道闸:计划里的 low / medium /
1982
+ * high / xhigh / max 五档值是规划器按通用五档规则写的([2.2.7][T4];旧
1983
+ * 三档计划中的 low/high/max 属五档子集,回放零迁移),可子会话用的就是
1984
+ * 主链路模型(modelSelection)。
1985
+ * 若该模型不声明这些档(qwen 只声明 low/medium/xhigh),照发必被宿主
1986
+ * 在请求前抛 UNSUPPORTED_REASONING_EFFORT——派发期即中断。查询不可用
1987
+ * 时保持旧行为;查询成功后钳制到等效档,空清单则不发送该字段。
1988
+ */
1989
+ const requestedChildEffort = typeof subtask.reasoningEffort === 'string'
1990
+ && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1991
+ ? subtask.reasoningEffort
1992
+ : DEFAULT_REASONING_EFFORT
1993
+ /*
1994
+ * [2.2.7] 能力不可查询时保持同步路径:派发链上任何多余的 await 微任务都会
1995
+ * 把 awaiting 通道写入推晚一个 tick(notice-channel 运行时集成用例即因此
1996
+ * 断言失败)。只有真要向宿主查询时才引入这一次等待。
1997
+ */
1998
+ const effortQueryable = Boolean(
1999
+ ctx.llm && typeof ctx.llm.resolveModelInfo === 'function'
2000
+ && modelSelection?.provider && modelSelection?.model,
2001
+ )
2002
+ const childEffortSupport = effortQueryable
2003
+ ? await resolveSupportedEfforts(ctx.llm, modelSelection.provider, modelSelection.model, parentSignal)
2004
+ : null
2005
+ const childEffort = childEffortSupport === null
2006
+ ? requestedChildEffort
2007
+ : (clampEffortToSupported(requestedChildEffort, childEffortSupport) ?? '')
1754
2008
  activation = await ctx.subagents.startActivation({
1755
2009
  provider: 'spawn',
1756
2010
  label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
@@ -1816,10 +2070,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
1816
2070
  ...(modelSelection?.provider && modelSelection?.model
1817
2071
  ? { provider: modelSelection.provider, model: modelSelection.model }
1818
2072
  : {}),
1819
- reasoningEffort: typeof subtask.reasoningEffort === 'string'
1820
- && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1821
- ? subtask.reasoningEffort
1822
- : DEFAULT_REASONING_EFFORT,
2073
+ // [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
2074
+ ...(childEffort ? { reasoningEffort: childEffort } : {}),
1823
2075
  },
1824
2076
  maxDepth: 1,
1825
2077
  },
@@ -1911,6 +2163,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
1911
2163
  summary: `未完成:${message}`,
1912
2164
  }, guard)
1913
2165
  recordSubtaskError(record, subtask.id, message, guard)
2166
+ // [2.2.7] 中断即报:no-ack 是「根本没启动」,不是「做失败了」。
2167
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id,
2168
+ `子任务 ${subtask.id}(${subtask.title})${message};性质:子会话疑似根本没启动,不是执行失败;处理:已中止该子会话并把本行置为受阻(blockedKind=no-ack),主会话可决定重新下发指示或放弃该行,其余子任务不受影响。`)
1914
2169
  if (!child.controller.signal.aborted) {
1915
2170
  child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }))
1916
2171
  }
@@ -2058,6 +2313,47 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2058
2313
  )
2059
2314
  }
2060
2315
  if (!output) throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT')
2316
+ /*
2317
+ * [2.2.8][T7] 结果块解析失败 = 与 CHILD_NOT_COMPLETED 同路径的有界回喂重试。
2318
+ *
2319
+ * T4 事故(用户 2026-11-09 报告):子会话工作完成、交付物已在盘上,只是
2320
+ * 结果块 JSON 写坏;旧实现在这里一次即判 blocked,并级联阻断下游——
2321
+ * 侧栏(子会话实时活动态)与账本(结算态)出现十几分钟的可见错位。
2322
+ * 现在结算前先用纯函数裁决一次(不写状态、不留双源):
2323
+ * - unparsable 且还有回喂意义(`shouldRetryAttempt` 与 CHILD_NOT_COMPLETED
2324
+ * 同一道闸;最多两次由 attempt 上限统一把关,不会无限循环)→ 抛
2325
+ * EVIDENCE_UNPARSABLE,由下方 catch 把解析器具体错误回喂同一子会话,
2326
+ * 要求「修正结果块后重新回报,勿重做已完成工作」;
2327
+ * - 重试后仍 unparsable(或预算不再够一次回喂)→ 按实受阻,随行附上
2328
+ * attempt 摘要声明且确核在盘的产物清单,提示主 Agent 用
2329
+ * `dsh_workplan_update` 复核改判。
2330
+ * 结算严格性不变:非法 JSON 依旧绝不计 done——只修恢复路径。
2331
+ */
2332
+ const settleRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
2333
+ const settleVerdict = settleRow?.closure === 'escalated'
2334
+ ? null
2335
+ : adjudicateResult({
2336
+ output,
2337
+ strict: options.strictEvidence !== false,
2338
+ expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
2339
+ })
2340
+ if (settleVerdict && settleVerdict.verification === 'unparsable') {
2341
+ const unparsableLanded = probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists)
2342
+ const unparsableError = new PlanError(
2343
+ `结果块无法解析,本次回报不能结算(工作本身不计失败):${truncate(String(settleVerdict.error ?? ''), 600)}`
2344
+ + (unparsableLanded.length > 0
2345
+ ? `;上一次回报声明且已核到在盘的产物:${unparsableLanded.slice(0, 6).join('、')}——请勿重做已完成的工作,只修正结果块为合法 JSON 后重新完整回报`
2346
+ : ';请修正结果块为合法 JSON(引号、逗号、括号成对,标记成对出现)后重新回报'),
2347
+ 'EVIDENCE_UNPARSABLE',
2348
+ { subtaskId: subtask.id },
2349
+ )
2350
+ if (shouldRetryAttempt(unparsableError, attempt, deadline - Date.now(), idleTimeoutMs)) {
2351
+ throw unparsableError
2352
+ }
2353
+ settleFromOutput(record, subtask, output, guard, options, settleVerdict,
2354
+ probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists))
2355
+ return
2356
+ }
2061
2357
  /*
2062
2358
  * [1.7.0] Evidence decides the verdict.
2063
2359
  *
@@ -2067,7 +2363,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2067
2363
  * is the single deterministic table; `settleFromOutput` adds the
2068
2364
  * environment-dependent artifact check.
2069
2365
  */
2070
- settleFromOutput(record, subtask, output, guard, options)
2366
+ settleFromOutput(record, subtask, output, guard, options, settleVerdict ?? undefined)
2071
2367
  return
2072
2368
  } catch (error: any) {
2073
2369
  lastError = error
@@ -2095,6 +2391,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2095
2391
  `${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
2096
2392
  ].slice(-20)
2097
2393
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
2394
+ // [2.2.7] 中断即报:用户当下就知道「谁被打断、为什么、系统正在怎么处理」。
2395
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id,
2396
+ `子任务 ${subtask.id}(${subtask.title})第 ${attempt} 次执行被打断(${lastFailure.code}:${truncate(lastFailure.message, 140)});处理:插件已把失败原因回喂同一子会话并自动重试(第 ${attempt + 1} 次),任务整体仍在推进,这不是最终失败。`)
2098
2397
  continue
2099
2398
  }
2100
2399
  /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
@@ -2125,7 +2424,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2125
2424
  return interruptedFlag ? { interrupted: true } : undefined
2126
2425
  }
2127
2426
  const message = describeError(lastError ?? new Error('未知失败'))
2128
- writeSubtaskStatus(record, subtask.id, {
2427
+ const finalBlocked = writeSubtaskStatus(record, subtask.id, {
2129
2428
  status: 'blocked',
2130
2429
  closure: 'blocked',
2131
2430
  blockedKind: 'failed',
@@ -2144,6 +2443,15 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2144
2443
  : {}),
2145
2444
  }, guard)
2146
2445
  recordSubtaskError(record, subtask.id, message, guard)
2446
+ // [2.2.7] 中断即报:重试耗尽/不可重试走到终点时立即说清本质原因与后续处置,
2447
+ // 不等整轮结果消息。
2448
+ if (finalBlocked && !guard.timedOut && !parentSignal.aborted) {
2449
+ const landed = interruptedEvidence?.artifacts?.length
2450
+ ? `已核到 ${interruptedEvidence.artifacts.length} 个产物在盘上:${interruptedEvidence.artifacts.slice(0, 3).join('、')}`
2451
+ : '子会话未留下已核实的在盘产物'
2452
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id,
2453
+ `子任务 ${subtask.id}(${subtask.title})已受阻:${truncate(message, 160)};产物线索:${landed};处理:本行不再自动重试,整轮结果会如实列为未完成,由主会话据实决定续跑/改判/向你说明——期间其余子任务继续执行。`)
2454
+ }
2147
2455
  return interruptedFlag ? { interrupted: true } : undefined
2148
2456
  } catch (error) {
2149
2457
  const message = describeError(error)
@@ -2166,6 +2474,9 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
2166
2474
  // The status list itself is unusable; the outer dispatcher records the error.
2167
2475
  }
2168
2476
  recordSubtaskError(record, subtask.id, message, guard)
2477
+ // [2.2.7] 中断即报:执行链路自身出异常同样不能对用户沉默。
2478
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id,
2479
+ `子任务 ${subtask.id}(${subtask.title})执行过程发生未预期异常:${truncate(message, 160)};处理:本行已置为受阻并如实留档,主会话将在结果消息后据实决定续跑/改判,不会伪造完成。`)
2169
2480
  } finally {
2170
2481
  /*
2171
2482
  * [2.2.0][T3/O-2a] 结算点唯一的通道收束入口(成功/受阻/待指示/中断都走这里)。
@@ -2659,7 +2970,15 @@ export function buildRoundResult(record: any, sessionId: any, limits: any) {
2659
2970
  * `deliveryReady` 门禁读同一组输入(否则「结果说完成、present 被拒」)。
2660
2971
  */
2661
2972
  changePending: record.changeRequest?.status === 'pending',
2662
- reportPending: record.reportPending === true,
2973
+ /*
2974
+ * [2.2.9][T3][M5] 冻结值与载荷同源:finishRound 已保证先 markReported
2975
+ * 再 build,这里若仍读 `record.reportPending` 可变标志,标志可能停在
2976
+ * 上一次失败的旧值,导致结果消息文本(plan.ts buildResultSummary 判
2977
+ * 「证据未通过(reportPending)」)与同一消息内 statuses 的门禁判定互相
2978
+ * 矛盾——正是震荡观感在消息侧的残留。改读派生函数后,冻结的 S3 恒等于
2979
+ * 载荷 statuses 的事实,摘要、指令与 present 门禁读到同一结论。
2980
+ */
2981
+ reportPending: deriveReportPending(record),
2663
2982
  })
2664
2983
  }
2665
2984
 
@@ -3285,7 +3604,8 @@ function serialisePlan(record: any, session: any) {
3285
3604
  */
3286
3605
  planRevision: Number(record.planRevision ?? 0),
3287
3606
  changeRequest: record.changeRequest ?? null,
3288
- reportPending: record.reportPending === true,
3607
+ // [2.2.9][T3][M4.1] 看板观测与门禁同源(纯派生),不再读可变标志。
3608
+ reportPending: deriveReportPending(record),
3289
3609
  /*
3290
3610
  * Liveness and resume bookkeeping. Without these the dashboard could not
3291
3611
  * tell a slow-but-alive child from a wedged one, and the model could not
@@ -3592,14 +3912,60 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
3592
3912
  * `dsh_workplan_update` used to live only in the live cache, so a refresh
3593
3913
  * reverted the dashboard to the child's original verdict. The durable
3594
3914
  * `workplan-update` message is small and append-only, so replay is just
3595
- * "apply it when its turn comes"; a lower revision never overwrites a
3596
- * newer one (see `applyResultStatuses`).
3915
+ * "apply it when its turn comes". [2.2.9][T2][mono-gate] used to claim a
3916
+ * protection that only existed on the result-message path
3917
+ * (`applyResultStatuses`): a durable update with a lower revision could
3918
+ * still overwrite a newer settled row. The gate below now enforces it —
3919
+ * a strictly-lower revision never overwrites; equal revision passes
3920
+ * (dedup for the same write lives in `appliedUpdates`).
3597
3921
  */
3598
3922
  const update = parseUpdateMessage(event.data)
3599
3923
  if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
3600
3924
  const snap = snapshots.get(update.planId)
3601
3925
  if (snap) {
3602
3926
  try {
3927
+ /*
3928
+ * [2.2.9][T2][mono-gate] 结算事件写入单调性闸(M1,症状①主闸)。
3929
+ *
3930
+ * 事故形状(wp-215ed52f T5 实证):结算 rev16 已落 durable 结果消息,
3931
+ * 主 Agent 基于落后的 live 快照做 handoff 答复,追加了 rev9/10 的
3932
+ * workplan-update(seq 更晚)。回放按 seq 升序,后到的旧事件无条件
3933
+ * 覆盖先落盘的新结算——「后到即覆盖」与「revision 单调、已结算内容
3934
+ * 不可回退」的业务不变量正面冲突。
3935
+ *
3936
+ * 闸语义(与 plan.ts applyResultStatuses 的 result 族闸对齐):
3937
+ * - evRev < rowRev → 回退事件:拒绝整事件语义(含 3936 一带的直写
3938
+ * 白名单与 extendMs 合成,防止旧事件的状态性字段漏进新行),只有
3939
+ * handoffs 走逐项单调合并(M2:答复是字段级增量,新登记永远合法、
3940
+ * answered/closed 终态永不回退);
3941
+ * - 仍必须 appliedUpdates.set:否则同一次改判的 tool/result 配对
3942
+ * 记录(patch 不带 rev,applyStatus 强算 current+1)会绕过本闸从
3943
+ * 第二通道把旧内容灌回;
3944
+ * - evRev === rowRev → 前向通过(等 rev 补写是合法场景;同一条写入
3945
+ * 的重复应用由既有 appliedUpdates/1.8.11 去重通道拦截);
3946
+ * - evRev 为 null(旧格式无 revision 字段 / 非整数)→ 不猜、放行,
3947
+ * 向后兼容(applyStatus 尾部按 current+1 单调抬号)。
3948
+ */
3949
+ const gateRow = snap.statuses.find((item: any) => item?.subtaskId === update.subtaskId)
3950
+ const rowRev = Number(gateRow?.revision ?? 0)
3951
+ const evRev = Number.isInteger(update.revision) ? Number(update.revision) : null
3952
+ if (gateRow && evRev !== null && evRev < rowRev) {
3953
+ if (Array.isArray(update.handoffs)) {
3954
+ const merged = mergeHandoffEntriesByUpdatedAt(gateRow.handoffs, update.handoffs)
3955
+ if (merged.changed) gateRow.handoffs = merged.value
3956
+ }
3957
+ console.warn(
3958
+ '[dsh-workplan] monotonicity gate skipped a stale replayed update: '
3959
+ + `${String(update.planId)}/${String(update.subtaskId)} `
3960
+ + `(event rev ${evRev} < row rev ${rowRev}); row content kept, `
3961
+ + 'handoff entries merged monotonically',
3962
+ )
3963
+ appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
3964
+ seq: Number(event.seq ?? 0),
3965
+ status: String(update.status ?? ''),
3966
+ })
3967
+ continue
3968
+ }
3603
3969
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
3604
3970
  /*
3605
3971
  * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
@@ -3633,6 +3999,31 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
3633
3999
  timeoutMs: update.timeoutMs,
3634
4000
  updatedBy: 'agent',
3635
4001
  })
4002
+ /*
4003
+ * [2.2.9][T3][M4] 回放侧人工改判的回报闭环——与 live 路径(改判
4004
+ * 工具在 durable 落盘成功后 markReported)配成同一条不变量:
4005
+ * durable 的 workplan-update 携带显式 status:'done' 时,这条消息
4006
+ * 本身就是主 Agent 亲笔写进会话日志的「完成已回报」证据。旧日志
4007
+ * 嵌的是 closure:'done'(2.2.9 之前的口径),回放在此一并升级为
4008
+ * reported;report.ref 指向这条 durable 消息的 seq——引用真实存在、
4009
+ * 可复核。不升 handoffs 快照消息(它们的 status 未被应用,handoff
4010
+ * 记录不是一次回报),子结算行的回报仍须来自结果消息或 pre-step
4011
+ * 自愈(M4.2)。live 与重建由此在同一份日志上逐行同判,
4012
+ * 「可交付↔门禁未放行」的震荡失去立足点。
4013
+ */
4014
+ if (update.status === 'done' && update.handoffs === undefined) {
4015
+ const healedRow = snap.statuses.find((item: any) => item?.subtaskId === update.subtaskId)
4016
+ if (healedRow?.status === 'done' && healedRow?.closure === 'done') {
4017
+ healedRow.closure = 'reported'
4018
+ healedRow.reportedAt = Number(update.at) || Date.now()
4019
+ healedRow.report = {
4020
+ state: 'sent',
4021
+ at: Number(update.at) || Date.now(),
4022
+ ref: `${String(update.planId)}:replay:${String(Number(event.seq ?? 0))}`,
4023
+ turn: null,
4024
+ }
4025
+ }
4026
+ }
3636
4027
  /*
3637
4028
  * [2.2.0][T4/O-3b][E] 柔性时长协商新字段回放(E 项,runtime.ts 2931 一带)。
3638
4029
  *
@@ -3676,7 +4067,13 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
3676
4067
  console.warn(
3677
4068
  '[dsh-workplan] 回放忽略一条不合法的历史改判:'
3678
4069
  + `${String(update?.planId ?? '')}/${String(update?.subtaskId ?? '')}:`
3679
- + `${error instanceof Error ? error.message : String(error)}`,
4070
+ + /*
4071
+ * [2.2.9][T3][M4.3] 可诊断化:旧快照携带的 closure/revision 与被保留
4072
+ * 的行现状一并带出,「改判丢失」不再只有一句 error.message。
4073
+ */
4074
+ `event rev=${String(update?.revision ?? 'none')} closure=${String(update?.closure ?? 'none')} `
4075
+ + `vs row rev=${String(snap.statuses.find((item: any) => item?.subtaskId === update?.subtaskId)?.revision ?? 'none')}:`
4076
+ + `${error instanceof Error ? error.message : String(error)}`,
3680
4077
  )
3681
4078
  }
3682
4079
  }
@@ -3864,13 +4261,19 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
3864
4261
  planRevision: chosen.planRevision,
3865
4262
  changeRequest: chosen.changeRequest,
3866
4263
  /*
3867
- * [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
3868
- * 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
3869
- * 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
3870
- * 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
4264
+ * [2.2.9][T3][M4.2] 重建记录必须带 `resultWritten`。
4265
+ *
4266
+ * 事故实证(wp-215ed52f 症状②第三拍):pre-step 回报自愈的条件是
4267
+ * `reportPending && resultWritten`,而重建对象从不携带该字段(恒
4268
+ * undefined)→ 条件永不成立 → 重启后派生出的「未回报」态永远无法
4269
+ * 自愈,只能靠幂等复核+人工改判收敛——这正是「震荡三次」的机制解释。
4270
+ * durable 会话里存在本轮结果消息(resultSeen)就是「已写入」的事实,
4271
+ * 用它补齐后自愈在重建态可达:重启 → reportPending 派生 true →
4272
+ * pre-step 幂等 markReported → 门禁一次收敛。
3871
4273
  */
3872
- reportPending: statuses.some((item: any) =>
3873
- item?.status === 'done' && item?.closure === 'done'),
4274
+ resultWritten: resultSeen,
4275
+ // [2.2.9][T3][M4.1] 派生口径与门禁/看板/冻结单源(deriveReportPending)。
4276
+ reportPending: deriveReportPending({ statuses }),
3874
4277
  }
3875
4278
  }
3876
4279
 
@@ -4194,14 +4597,20 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
4194
4597
  /*
4195
4598
  * [1.11.0] 回报自愈(契约 §7.3 B4):上一轮结果消息已写入,但回报标记
4196
4599
  * 写失败/进程中断时,下一步 pre-step 幂等补齐,不重复追加上下文。
4600
+ *
4601
+ * [2.2.9][T3][M4.1/M4.2] 判定改读派生谓词 `deriveReportPending`:live
4602
+ * 记录的标志只是审计镜像,自愈若读镜像,镜像过期时该自愈的不自愈、
4603
+ * 不该自愈的白跑一遍。配合重建对象补上的 `resultWritten`(M4.2,
4604
+ * 此前该字段在重建态恒 undefined、条件永不成立,自愈对重启后的会话
4605
+ * 形同虚设——「震荡三次靠人工收敛」的第三拍),重启 → 派生 true →
4606
+ * 首个 pre-step 幂等 markReported → 门禁一次收敛,无需人工改判。
4197
4607
  */
4198
4608
  const session = payload.agent?.session
4199
4609
  const known = session ? state.records.get(session.id) : null
4200
- if (known?.plan && known.reportPending === true && known.resultWritten === true) {
4610
+ if (known?.plan && deriveReportPending(known) && known.resultWritten === true) {
4201
4611
  const changed = markReported(known, session, `${known.plan.planId}:${known.dispatchedAt ?? 0}`)
4202
4612
  if (changed > 0) {
4203
- known.reportPending = (known.statuses ?? []).some((item: any) =>
4204
- item?.status === 'done' && item?.closure === 'done')
4613
+ known.reportPending = deriveReportPending(known)
4205
4614
  }
4206
4615
  }
4207
4616
  return await maybePlan(ctx, state, payload, downstream, { ...options, limits })
@@ -4696,6 +5105,19 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
4696
5105
  instruction: writtenRow?.instruction,
4697
5106
  instructionSeq: writtenRow?.instructionSeq,
4698
5107
  }))
5108
+ /*
5109
+ * [2.2.9][T3][M4] 人工改判的这条 durable update 消息本身就是「完成已
5110
+ * 回报」的会话证据(主 Agent 亲笔写进会话日志),落盘成功后立即闭环
5111
+ * closure done→reported,否则派生闸会把改判行当成未回报而永久拦死
5112
+ * ——改判→present 是主 Agent 的正常工作流(wp-215ed52f T5/R1-1 实证)。
5113
+ * append 失败时不进此支:行留在 closure:'done',门禁 fail-closed,
5114
+ * 绝不留下无证据的已回报(与 finishRound 同一铁律)。回放侧对
5115
+ * status:'done' 的改判消息做同样的升级(见 reconstructFromSession),
5116
+ * live 与重建在同一份日志上逐行同判——W2 分叉就此封死。
5117
+ */
5118
+ if (status === 'done') {
5119
+ markReported(record, session, `${record.plan.planId}:${record.dispatchedAt ?? 0}`, subtaskId)
5120
+ }
4699
5121
  } catch (error) {
4700
5122
  pushRecordError(record, error)
4701
5123
  }
@@ -5354,14 +5776,19 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5354
5776
  * 绝不留下没有证据的 reported。
5355
5777
  */
5356
5778
  const before = (record.statuses ?? []).map((item: any) => ({ ...item }))
5357
- const needReport = before.filter((item: any) => item?.status === 'done' && item?.closure !== 'reported').length
5358
- // ^ 本轮结算:done 且未到 reported 的行(含旧日志的 null)都算待回报。
5359
- const reported = markReported(record, session, ref)
5779
+ markReported(record, session, ref)
5360
5780
  const resultMessage = buildRoundResult(record, session.id, limits)
5361
5781
  try {
5362
5782
  appendUserMessage(session, resultMessage)
5363
5783
  record.resultWritten = true
5364
- record.reportPending = needReport > 0 && reported < needReport
5784
+ /*
5785
+ * [2.2.9][T3][M4] 标志自此只是审计镜像,一律按派生函数回填。
5786
+ * 旧公式 `needReport > 0 && reported < needReport` 自带第三套口径
5787
+ * (把旧日志 closure=null 的行也算待回报),与门禁/重建/自愈使用的
5788
+ * 严格 `closure==='done'` 判据并存——多套判据互不一致正是震荡的
5789
+ * 温床。收敛后镜像与 statuses 事实恒等,任何读取方都对得上。
5790
+ */
5791
+ record.reportPending = deriveReportPending(record)
5365
5792
  } catch (error) {
5366
5793
  // 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
5367
5794
  record.statuses = before
@@ -5373,10 +5800,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5373
5800
  */
5374
5801
  pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
5375
5802
  /*
5376
- * [1.11.0] 写失败时不能假装回报过。保留 reportPending,让下一次
5377
- * pre-step 或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
5803
+ * [1.11.0] 写失败时不能假装回报过。回滚后镜像同步为回滚事实
5804
+ * (done 行回到 closure:'done' ⇒ 派生 true),交下一次 pre-step
5805
+ * 自愈或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
5378
5806
  */
5379
- record.reportPending = true
5807
+ record.reportPending = deriveReportPending(record)
5380
5808
  }
5381
5809
  } else {
5382
5810
  /*
@@ -5386,8 +5814,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5386
5814
  const pending = (record.statuses ?? []).some((item: any) =>
5387
5815
  item?.status === 'done' && item?.closure !== 'reported')
5388
5816
  if (pending) {
5389
- const changed = markReported(record, session, ref)
5390
- if (changed > 0) record.reportPending = false
5817
+ markReported(record, session, ref)
5818
+ // [2.2.9][T3][M4] 镜像按派生回填:部分标记失败时不谎报「已回报」。
5819
+ record.reportPending = deriveReportPending(record)
5391
5820
  }
5392
5821
  }
5393
5822
  /*
@@ -5782,6 +6211,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
5782
6211
  escalationSeq: revision,
5783
6212
  revision,
5784
6213
  }))
6214
+ // [2.2.7] 中断即报:请示同样要让用户当下看到「有人卡在哪、等什么决定」,
6215
+ // 结构化 update 消息是给回放/主 Agent 的,这条纯文本是给用户的。
6216
+ announceSubtaskInterrupt(record, parent, row.subtaskId,
6217
+ `子任务 ${row.subtaskId} 执行中请求指示:${truncate(question, 160)};性质:等待主会话拍板,不是执行失败;处理:主会话答复后用 dsh_workplan_instruct 下发决定,该行将恢复执行。`)
5785
6218
  } catch (error) {
5786
6219
  pushRecordError(record, error)
5787
6220
  }
@@ -6792,7 +7225,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
6792
7225
  statuses: snapshot.statuses,
6793
7226
  attempt: book.count,
6794
7227
  changePending: record.changeRequest?.status === 'pending',
6795
- reportPending: record.reportPending === true,
7228
+ // [2.2.9][T3][M4.1] 强制收尾提示与门禁同源(纯派生)。
7229
+ reportPending: deriveReportPending(record),
6796
7230
  }),
6797
7231
  {
6798
7232
  kind: 'workplan-continue',