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/lib/runtime.js CHANGED
@@ -17,7 +17,7 @@ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
17
17
  import { createNoticeChannel, finaliseNoticeChannel, formatNoticeChannelLog, observeRelayedNotice, readLeadAgentId, resolveLeadAgentId, validateNoticeChannel, } from './notice-channel.js';
18
18
  import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, appendUserMessage, applyStatus, attachPlanMeta, blockCancelledDependents, buildChildPrompt, buildCancelMessage, buildClarifyMessage, createPlannerProgressReporter, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, DEFAULT_REASONING_EFFORT, deliveryReadiness, derivePlanSnapshot,
19
19
  // [2.2.0][T4/O-3b] O-3b 消费接线:缺省协商上限由预估派生(plan.ts 纯函数,T3 已定稿)。
20
- deriveSubtaskTimeoutMs, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, REASONING_EFFORTS, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, needEntryText, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, } from './plan.js';
20
+ deriveSubtaskTimeoutMs, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, REASONING_EFFORTS, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, mergeHandoffEntriesByUpdatedAt, needEntryText, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, } from './plan.js';
21
21
  import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js';
22
22
  import { phaseGateFromErrors, phaseSummaryLine, validatePhaseEvidence } from './three-phase.js';
23
23
  import { lessonStats, rankLessons, readLessons, recordLesson, renderLessonsBrief, resolveLessonsFile, } from './lessons.js';
@@ -83,13 +83,31 @@ function liveStatuses(statuses) {
83
83
  * `changeRequest.pending`(执行中收到、尚未重规划的变更)与 `reportPending`
84
84
  * (完成结果还没写进会话)只存在于 `record` 而不是 `statuses`,所以必须在
85
85
  * 这一层显式传入;`plan.ts` 的 `deliveryReadiness` 因此仍是纯函数。
86
+ *
87
+ * [2.2.9][T3][M4.1] `reportPending` 不再读 `record.reportPending` 可变标志。
88
+ * 事故实证(wp-215ed52f 症状②):门禁读标志、看板读标志、消息冻结读标志,
89
+ * 而该标志在 finishRound/markReported/自愈/重建多处的写入时机互不同步,
90
+ * 判定结果随读取落在哪个时间窗口而翻转——「可交付↔未放行」来回震荡。
91
+ * 现在门禁、看板、stop-steer、消息冻结、自愈全部读同一个纯派生函数
92
+ * `deriveReportPending(record)`:事实只有 statuses(经 T2 单调闸的终态),
93
+ * 标志降级为审计镜像。blocked/pending 行不是 done,永不触发该阻塞。
86
94
  */
95
+ export function deriveReportPending(record) {
96
+ const statuses = Array.isArray(record?.statuses) ? record.statuses : [];
97
+ /*
98
+ * [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
99
+ * 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
100
+ * 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
101
+ * 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
102
+ */
103
+ return statuses.some((item) => item?.status === 'done' && item?.closure === 'done');
104
+ }
87
105
  function readinessOf(record, snapshot) {
88
106
  const snap = snapshot ?? derivePlanSnapshot(record?.plan ? blockCancelledDependents(record.plan, record?.statuses) : record?.statuses, record?.plan ? definedSubtaskCount(record.plan) : undefined);
89
107
  return deliveryReadiness(snap, {
90
108
  phase: record?.phase,
91
109
  changePending: record?.changeRequest?.status === 'pending',
92
- reportPending: record?.reportPending === true,
110
+ reportPending: deriveReportPending(record),
93
111
  /*
94
112
  * 计划定义的验收标准是交付门的另一半:状态行只回答「子 Agent 说通过
95
113
  * 了几条」,这里回答「计划要求的几条有没有被逐条回应」。
@@ -128,13 +146,97 @@ export const PLANNER_HARD_MULTIPLIER = 3;
128
146
  *
129
147
  * 用户规则(AGENTS.md 第 12 条)只说过「子 Agent 不得继承主 Agent 的等级」,
130
148
  * 规划器同样是主 Agent 派出的子调用:任务里明确授权「规划器停止继承」。规划
131
- * 本身属于「跨多个系统梳理根因并给出方案」——按同一条三档规则属非常复杂 →
132
- * max。`DSH_WORKPLAN_PLANNER_REASONING_EFFORT` 仍可显式覆盖(用户为降本/提速
149
+ * 本身属于「跨多个系统梳理根因并给出方案」——按五档规则(轻度=low/中等=
150
+ * medium或high/非常复杂=xhigh或max)属非常复杂 → 默认取 max(五档内的最高
151
+ * 档;xhigh 留给显式覆盖)。`DSH_WORKPLAN_PLANNER_REASONING_EFFORT` 仍可显式
152
+ * 覆盖(用户为降本/提速
133
153
  * 主动选择低档时有效),未设或非法时才用本默认值;**绝不读取
134
154
  * modelSelection.reasoningEffort**。旧行为(plannerEffort || 主 Agent 档位)会
135
155
  * 让主 Agent 的 low/high 直接决定拆解质量,与「子 Agent 自决档位」同源、同错。
136
156
  */
137
157
  export const DEFAULT_PLANNER_REASONING_EFFORT = 'max';
158
+ /*
159
+ * [2.2.7] 推理档位兼容性钳制(用户 2026-11-09 报告的 PLANNER_LLM_ERROR 根因修复)。
160
+ *
161
+ * 宿主 dsh-llm 会在发起网络请求之前,把请求的 reasoningEffort 与该模型声明的
162
+ * `reasoning.efforts` 清单逐一比对,不在清单内即抛 UNSUPPORTED_REASONING_EFFORT
163
+ * (本地失败、重试不会自愈)。规划器默认 max、子任务档位允许 low / medium /
164
+ * high / xhigh / max 五档——这些都假设主链路模型支持相应档位。一旦运行在
165
+ * qwen 这类只声明 low/medium/xhigh 的模型上,第一次规划调用就被宿主拒绝,
166
+ * 整个自动分解降级;
167
+ * 同一枚雷也埋在派发侧:计划里的 high/max/xhigh 行派给 qwen 子会话会同样即抛。
168
+ *
169
+ * 治本方案不是按模型名字猜档位(家族无穷、名单过时),而是在发送任何带档位的
170
+ * 请求前,用宿主公开能力面 `llm.resolveModelInfo` 读出目标模型**实际声明**的
171
+ * 档位清单,把请求档位钳制到清单内强度最接近的一档:
172
+ * - 清单包含请求档位 ⇒ 原样发送(模型声明支持五档时,low/medium/high/xhigh/max
173
+ * 全部原样透传,不钳制);
174
+ * - 否则取「不高于请求档」里最高的支持档(max→xhigh、high→medium…);
175
+ * [2.2.7][T4/五档] 五档请求落在三档清单(low/high/max)上的降级序按强度表
176
+ * 逐级下探:max 原样、xhigh→high、high 原样、medium→low、low 原样;落在
177
+ * qwen 型清单(low/medium/xhigh)上:max→xhigh、xhigh 原样、high→medium、
178
+ * medium 原样、low 原样。降级序即 EFFORT_STRENGTH_ORDER 中「不高于请求档」
179
+ * 的最近支持档,任何合法五档值都不会被拒绝或清空;
180
+ * - 全部支持档都强于请求档 ⇒ 取最弱支持档(宁可降质,不可失败);
181
+ * - 模型根本没有 reasoning 元数据(空清单)⇒ 不发送 reasoningEffort 字段,
182
+ * 与宿主 resolveCallWithInfo 的「reasoning===undefined 时任何档位都抛错」对齐;
183
+ * - 能力查询不可用(宿主不暴露 / 查询抛错)⇒ 保持旧行为,绝不因钳制引入新故障。
184
+ */
185
+ const EFFORT_STRENGTH_ORDER = Object.freeze(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
186
+ /** 请求档位 → 模型支持清单内的等效钳制档;空清单返回 undefined(= 不发送该字段)。 */
187
+ export function clampEffortToSupported(effort, supported) {
188
+ if (!Array.isArray(supported) || supported.length === 0)
189
+ return undefined;
190
+ if (supported.includes(effort))
191
+ return effort;
192
+ const rank = (id) => EFFORT_STRENGTH_ORDER.indexOf(id);
193
+ const ranked = [...supported].sort((a, b) => {
194
+ const ra = rank(a);
195
+ const rb = rank(b);
196
+ if (ra === rb)
197
+ return 0;
198
+ if (ra < 0)
199
+ return 1;
200
+ if (rb < 0)
201
+ return -1;
202
+ return ra - rb;
203
+ });
204
+ const target = rank(effort);
205
+ if (target < 0)
206
+ return ranked[ranked.length - 1];
207
+ const atOrBelow = ranked.filter((id) => rank(id) >= 0 && rank(id) <= target);
208
+ if (atOrBelow.length > 0)
209
+ return atOrBelow[atOrBelow.length - 1];
210
+ return ranked[0];
211
+ }
212
+ const supportedEffortsCache = new Map();
213
+ /**
214
+ * 读取 provider/model 声明的推理档位清单。
215
+ * @returns 档位 id 数组(可为空数组 = 模型不支持任何档位);null = 无从判定,调用方保持旧行为。
216
+ */
217
+ export async function resolveSupportedEfforts(llm, provider, model, signal) {
218
+ if (!llm || typeof llm.resolveModelInfo !== 'function' || !provider || !model)
219
+ return null;
220
+ const key = `${provider}/${model}`;
221
+ const hit = supportedEffortsCache.get(key);
222
+ if (hit)
223
+ return hit;
224
+ if (signal?.aborted)
225
+ return null;
226
+ try {
227
+ const info = await llm.resolveModelInfo(provider, model, signal);
228
+ const efforts = info?.reasoning?.efforts;
229
+ const list = Array.isArray(efforts)
230
+ ? efforts.map((item) => String(item?.id ?? '')).filter((id) => id !== '')
231
+ : [];
232
+ supportedEffortsCache.set(key, list);
233
+ return list;
234
+ }
235
+ catch {
236
+ // 查询失败 ⇒ 与「宿主不暴露该能力」同等处理:不钳制、不缓存、不阻断。
237
+ return null;
238
+ }
239
+ }
138
240
  /**
139
241
  * Absolute ceiling for one child execution.
140
242
  *
@@ -604,12 +706,14 @@ export async function runPlanner(ctx, options) {
604
706
  * - DSH_WORKPLAN_PLANNER_MAX_TOKENS:给单次生成封顶。无界生成是「流满 900 秒
605
707
  * 撞绝对上限」的放大器——封顶后模型会正常 finish,截断可被抢救/回喂;
606
708
  * - DSH_WORKPLAN_PLANNER_REASONING_EFFORT:规划专用推理档,只接受
607
- * low / high / max 三档。非法值不传给模型,回落默认档(见下)。
709
+ * low / medium / high / xhigh / max 五档。非法值不传给模型,回落默认档(见下)。
608
710
  *
609
711
  * [2.2.0][T13b] 用户 2026-11-08 决策 5「规划器停止继承」:未设该旋钮时,规划器
610
712
  * 不再沿用主 Agent 的推理档,而是取 DEFAULT_PLANNER_REASONING_EFFORT(max)。
611
- * 校验白名单复用 plan.ts 的 REASONING_EFFORTS:把 "ultra"/"medium" 这类非法值
612
- * 原样发给模型,真实宿主会以 400 拒绝整次规划——环境变量写错不应该让整个
713
+ * 校验白名单复用 plan.ts 的 REASONING_EFFORTS(五档:low / medium / high /
714
+ * xhigh / max;[2.2.7][T4] 由三档扩五档,medium/xhigh 现为合法值):把
715
+ * "ultra"/"minimal" 这类非法值原样发给模型,真实宿主会以 400 拒绝整次规划——
716
+ * 环境变量写错不应该让整个
613
717
  * 任务降级,所以非法值按「未设置」处理。
614
718
  */
615
719
  const plannerMaxTokens = normalisePlannerWindow(process.env.DSH_WORKPLAN_PLANNER_MAX_TOKENS, 0);
@@ -617,7 +721,26 @@ export async function runPlanner(ctx, options) {
617
721
  // 用户的成本预期,所以先归一化再进白名单。
618
722
  const plannerEffortRaw = String(process.env.DSH_WORKPLAN_PLANNER_REASONING_EFFORT ?? '').trim().toLowerCase();
619
723
  const plannerEffort = REASONING_EFFORTS.includes(plannerEffortRaw) ? plannerEffortRaw : '';
620
- const effectivePlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT;
724
+ const requestedPlannerEffort = plannerEffort || DEFAULT_PLANNER_REASONING_EFFORT;
725
+ /*
726
+ * [2.2.7] 发送前按模型能力钳制档位:宿主对不支持的档位会在网络调用前直接
727
+ * 抛 UNSUPPORTED_REASONING_EFFORT,重试不自愈(终态),整次规划因此降级。
728
+ * 查询不可用时保持旧行为;查询到清单后请求档钳制到清单内等效档,空清单
729
+ * (模型无 reasoning 元数据)则不发送档位字段。'' 在这里表示「不发送」。
730
+ */
731
+ const plannerEffortSupport = await resolveSupportedEfforts(ctx.llm, modelSelection?.provider, modelSelection?.model, signal);
732
+ const effectivePlannerEffort = plannerEffortSupport === null
733
+ ? requestedPlannerEffort
734
+ : (clampEffortToSupported(requestedPlannerEffort, plannerEffortSupport) ?? '');
735
+ if (plannerEffortSupport !== null && effectivePlannerEffort !== requestedPlannerEffort) {
736
+ console.warn('[dsh-workplan] planner reasoning effort clamped for model compatibility:', JSON.stringify({
737
+ provider: modelSelection?.provider,
738
+ model: modelSelection?.model,
739
+ requested: requestedPlannerEffort,
740
+ effective: effectivePlannerEffort || '(omitted)',
741
+ supported: plannerEffortSupport,
742
+ }));
743
+ }
621
744
  const secs = (ms) => Math.max(1, Math.round(ms / 1000));
622
745
  let lastErrors = [];
623
746
  /*
@@ -713,7 +836,8 @@ export async function runPlanner(ctx, options) {
713
836
  const stream = ctx.llm.stream({
714
837
  provider: modelSelection.provider,
715
838
  model: modelSelection.model,
716
- reasoningEffort: effectivePlannerEffort,
839
+ // [2.2.7] '' = 模型无 reasoning 元数据,不发送档位字段(发送必被宿主拒绝)。
840
+ ...(effectivePlannerEffort ? { reasoningEffort: effectivePlannerEffort } : {}),
717
841
  ...(plannerMaxTokens > 0 ? { maxTokens: plannerMaxTokens } : {}),
718
842
  messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }],
719
843
  signal: controller.signal,
@@ -885,8 +1009,11 @@ export async function runPlanner(ctx, options) {
885
1009
  // [2.2.0][T13b] 记录**实际发给模型**的档位:旧值记的是 modelSelection
886
1010
  // (主 Agent 档位),规划器停止继承后它不再等于生效值,照抄会让事后
887
1011
  // 复盘把「主 Agent=high」误读成「规划器=high」。
1012
+ // [2.2.7] 钳制发生时同样记录实际发出值('' = 未发送)。
888
1013
  reasoningEffort: effectivePlannerEffort,
889
- reasoningEffortSource: plannerEffort ? 'env' : 'default-max',
1014
+ reasoningEffortSource: (plannerEffort ? 'env' : 'default-max')
1015
+ + (plannerEffortSupport !== null && effectivePlannerEffort !== requestedPlannerEffort
1016
+ ? `→clamped(${requestedPlannerEffort})` : ''),
890
1017
  attempt,
891
1018
  taskChars: typeof taskText === 'string' ? taskText.length : 0,
892
1019
  promptChars,
@@ -1304,7 +1431,14 @@ export function budgetResetError(item, subtask, cwd, artifactExists = existsSync
1304
1431
  * the session replay cannot disagree. This wrapper only adds the two things
1305
1432
  * that need the environment: the strict/legacy switch and the file check.
1306
1433
  */
1307
- function settleFromOutput(record, subtask, output, guard, options) {
1434
+ function settleFromOutput(record, subtask, output, guard, options,
1435
+ /*
1436
+ * [2.2.8][T7] 两个可选入参:`precomputedVerdict` 让调用方把已经裁决过的
1437
+ * 结果直接传入(unparsable 门在结算前判定过一次,纯函数重算是浪费也是
1438
+ * 双源);`extraEvidence` 只在「解析失败重试耗尽、按实受阻」时传入——
1439
+ * 它把 attempt 摘要/声明产物在盘上的事实随 blocked 行留档。
1440
+ */
1441
+ precomputedVerdict, extraEvidence) {
1308
1442
  /*
1309
1443
  * [1.11.0] 已经升级的请示不能被收尾正文覆盖。
1310
1444
  *
@@ -1316,7 +1450,7 @@ function settleFromOutput(record, subtask, output, guard, options) {
1316
1450
  const current = record.statuses.find((item) => item?.subtaskId === subtask.id);
1317
1451
  if (current?.closure === 'escalated')
1318
1452
  return { status: 'blocked', escalated: true };
1319
- const verdict = adjudicateResult({
1453
+ const verdict = precomputedVerdict ?? adjudicateResult({
1320
1454
  output,
1321
1455
  strict: options.strictEvidence !== false,
1322
1456
  /*
@@ -1331,6 +1465,26 @@ function settleFromOutput(record, subtask, output, guard, options) {
1331
1465
  const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists);
1332
1466
  const escalated = verdict.status === 'blocked'
1333
1467
  && typeof verdict.question === 'string' && verdict.question.trim() !== '';
1468
+ /*
1469
+ * [2.2.8][T7] 解析失败重试耗尽后的受阻,不得退化成「零产出失败」。
1470
+ *
1471
+ * T4 实证:子会话工作已完成、交付物已在盘上,只是结果块 JSON 写坏了;
1472
+ * 旧账本只留一句「结果块 JSON 非法」,主 Agent 无从知道产物存在,只能
1473
+ * 级联下游重做。现在把 attempt 摘要/声明产物中**确实在盘上**的清单随
1474
+ * blocked 行留档,并在 error 文案里给出「用 dsh_workplan_update 复核改判」
1475
+ * 的出口。语义不变:非法 JSON 依旧不计 done,这里只是把事实说全。
1476
+ */
1477
+ const landedRefs = (extraEvidence?.artifacts ?? [])
1478
+ .filter((item) => item?.exists === true)
1479
+ .map((item) => String(item?.ref ?? ''))
1480
+ .filter((ref) => ref !== '');
1481
+ const reviewNote = landedRefs.length > 0
1482
+ ? `;本次回报声明的产物清单已随本行留档(已在盘上:${landedRefs.slice(0, 6).join('、')})——产物已在盘上,`
1483
+ + '请先用 dsh_workplan_update 复核改判,勿按零产出处理,也不要级联阻断下游'
1484
+ : '';
1485
+ const settleError = typeof verdict.error === 'string' && verdict.error !== ''
1486
+ ? `${verdict.error}${reviewNote}`
1487
+ : verdict.error;
1334
1488
  /*
1335
1489
  * [2.0.0] 自我学习闭环的出口:完成且带复盘证据时,立刻写入永久记忆。
1336
1490
  *
@@ -1365,11 +1519,15 @@ function settleFromOutput(record, subtask, output, guard, options) {
1365
1519
  progress: 100,
1366
1520
  finishedAt: Date.now(),
1367
1521
  summary: truncate(lessonNote ? `${output}\n[自我学习] ${lessonNote}` : output, 3000),
1368
- error: verdict.error,
1522
+ error: settleError,
1369
1523
  verification: verdict.verification,
1370
1524
  acceptance: verdict.acceptance,
1371
- artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
1372
- missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
1525
+ artifacts: checked.artifacts.length > 0
1526
+ ? checked.artifacts
1527
+ : (extraEvidence && extraEvidence.artifacts.length > 0 ? extraEvidence.artifacts : undefined),
1528
+ missingArtifacts: checked.missingArtifacts.length > 0
1529
+ ? checked.missingArtifacts
1530
+ : (extraEvidence && extraEvidence.missingArtifacts.length > 0 ? extraEvidence.missingArtifacts : undefined),
1373
1531
  needs: verdict.needs.length > 0 ? verdict.needs : undefined,
1374
1532
  /*
1375
1533
  * [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
@@ -1406,7 +1564,7 @@ function settleFromOutput(record, subtask, output, guard, options) {
1406
1564
  }),
1407
1565
  }, guard);
1408
1566
  if (verdict.status === 'blocked') {
1409
- recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (verdict.error ?? '未完成'), guard);
1567
+ recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (settleError ?? '未完成'), guard);
1410
1568
  }
1411
1569
  else if (checked.missingArtifacts.length > 0) {
1412
1570
  recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
@@ -1477,10 +1635,62 @@ export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
1477
1635
  if (code === 'CHILD_NOT_COMPLETED') {
1478
1636
  return Number(remainingMs) > Number(idleTimeoutMs);
1479
1637
  }
1638
+ /*
1639
+ * [2.2.8][T7] 结果块解析失败与 CHILD_NOT_COMPLETED 走同一道闸(用户 2026-11-09
1640
+ * 报告 T4 事故:非法 JSON 一次即 blocked,并级联阻断下游;子会话其实已完成
1641
+ * 工作,只差一个合法回报)。回喂重报要有意义,必须还剩超过一个空闲窗口的
1642
+ * 预算;「最多两次」由函数开头的 attempt 上限统一把关,不会无限循环。
1643
+ */
1644
+ if (code === 'EVIDENCE_UNPARSABLE') {
1645
+ return Number(remainingMs) > Number(idleTimeoutMs);
1646
+ }
1647
+ return true;
1648
+ }
1649
+ /*
1650
+ * [2.2.7] 执行中断即时通知(用户 2026-11-09 报告的第二个缺陷)。
1651
+ *
1652
+ * 缺陷现场:部门专家执行中被中断(子会话报错、重试、no-ack、预算耗尽)时,
1653
+ * 主会话直到整轮结束才随结果消息一并交代——期间用户只看到进度不动,无法区分
1654
+ * 「在慢慢做」与「已经失败」,只能干着急。既有即时通道只覆盖 done
1655
+ * (emitSubtaskDoneNotice)与到点预警;中断类事件全走 record.errors(只有
1656
+ * 主 Agent 下次读记录才可见)。
1657
+ *
1658
+ * 这里补上同构的「中断即报」:中断一发生就往主会话写一条纯文本 user/message,
1659
+ * 文案固定三段——发生什么(含错误码与真因摘录)、系统正在怎么处理(重试/收束/
1660
+ * 待裁决)、对用户意味着什么(不是任务失败终局)。频率纪律:每个子任务整轮
1661
+ * 至多 INTERRUPT_NOTICE_CAP 条,写失败只留档到 record.errors,绝不影响执行。
1662
+ * 消息不带 workplan 标记,回放解析器按未知消息跳过(与完成通知同一纪律)。
1663
+ */
1664
+ const INTERRUPT_NOTICE_CAP = 3;
1665
+ export function announceSubtaskInterrupt(record, session, subtaskId, text) {
1666
+ if (!record || !session || typeof session.append !== 'function')
1667
+ return false;
1668
+ const row = Array.isArray(record.statuses)
1669
+ ? record.statuses.find((item) => item?.subtaskId === subtaskId)
1670
+ : null;
1671
+ const sent = Number(row?.interruptNoticeCount ?? 0);
1672
+ if (sent >= INTERRUPT_NOTICE_CAP)
1673
+ return false;
1674
+ const notice = `【dsh-workplan·执行中断】${truncate(String(text ?? '').replace(/\s+/g, ' ').trim(), 400)}`;
1675
+ try {
1676
+ appendUserMessage(session, notice);
1677
+ }
1678
+ catch (error) {
1679
+ record.errors = [...(record.errors ?? []), `${subtaskId} 中断通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20);
1680
+ return false;
1681
+ }
1682
+ if (row)
1683
+ row.interruptNoticeCount = sent + 1;
1480
1684
  return true;
1481
1685
  }
1482
1686
  async function executeSubtask(ctx, record, stage, subtask, options) {
1483
1687
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
1688
+ /*
1689
+ * [2.2.7] 中断即报的目标会话:与 noticeChannel/finaliseNotice 同一取值链,
1690
+ * 拿不到就安静跳过(通知是观测设施,不是交付物)。
1691
+ */
1692
+ const interruptSession = () => options.session ?? options.agent?.session
1693
+ ?? findSession(ctx, String(record?.plan?.sessionId ?? ''));
1484
1694
  let lastError = null;
1485
1695
  /*
1486
1696
  * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
@@ -1683,6 +1893,32 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1683
1893
  catch {
1684
1894
  lessonsBrief = '';
1685
1895
  }
1896
+ /*
1897
+ * [2.2.7] 子会话档位同样要过模型能力这道闸:计划里的 low / medium /
1898
+ * high / xhigh / max 五档值是规划器按通用五档规则写的([2.2.7][T4];旧
1899
+ * 三档计划中的 low/high/max 属五档子集,回放零迁移),可子会话用的就是
1900
+ * 主链路模型(modelSelection)。
1901
+ * 若该模型不声明这些档(qwen 只声明 low/medium/xhigh),照发必被宿主
1902
+ * 在请求前抛 UNSUPPORTED_REASONING_EFFORT——派发期即中断。查询不可用
1903
+ * 时保持旧行为;查询成功后钳制到等效档,空清单则不发送该字段。
1904
+ */
1905
+ const requestedChildEffort = typeof subtask.reasoningEffort === 'string'
1906
+ && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1907
+ ? subtask.reasoningEffort
1908
+ : DEFAULT_REASONING_EFFORT;
1909
+ /*
1910
+ * [2.2.7] 能力不可查询时保持同步路径:派发链上任何多余的 await 微任务都会
1911
+ * 把 awaiting 通道写入推晚一个 tick(notice-channel 运行时集成用例即因此
1912
+ * 断言失败)。只有真要向宿主查询时才引入这一次等待。
1913
+ */
1914
+ const effortQueryable = Boolean(ctx.llm && typeof ctx.llm.resolveModelInfo === 'function'
1915
+ && modelSelection?.provider && modelSelection?.model);
1916
+ const childEffortSupport = effortQueryable
1917
+ ? await resolveSupportedEfforts(ctx.llm, modelSelection.provider, modelSelection.model, parentSignal)
1918
+ : null;
1919
+ const childEffort = childEffortSupport === null
1920
+ ? requestedChildEffort
1921
+ : (clampEffortToSupported(requestedChildEffort, childEffortSupport) ?? '');
1686
1922
  activation = await ctx.subagents.startActivation({
1687
1923
  provider: 'spawn',
1688
1924
  label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
@@ -1748,10 +1984,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1748
1984
  ...(modelSelection?.provider && modelSelection?.model
1749
1985
  ? { provider: modelSelection.provider, model: modelSelection.model }
1750
1986
  : {}),
1751
- reasoningEffort: typeof subtask.reasoningEffort === 'string'
1752
- && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1753
- ? subtask.reasoningEffort
1754
- : DEFAULT_REASONING_EFFORT,
1987
+ // [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
1988
+ ...(childEffort ? { reasoningEffort: childEffort } : {}),
1755
1989
  },
1756
1990
  maxDepth: 1,
1757
1991
  },
@@ -1850,6 +2084,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1850
2084
  summary: `未完成:${message}`,
1851
2085
  }, guard);
1852
2086
  recordSubtaskError(record, subtask.id, message, guard);
2087
+ // [2.2.7] 中断即报:no-ack 是「根本没启动」,不是「做失败了」。
2088
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id, `子任务 ${subtask.id}(${subtask.title})${message};性质:子会话疑似根本没启动,不是执行失败;处理:已中止该子会话并把本行置为受阻(blockedKind=no-ack),主会话可决定重新下发指示或放弃该行,其余子任务不受影响。`);
1853
2089
  if (!child.controller.signal.aborted) {
1854
2090
  child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }));
1855
2091
  }
@@ -1995,6 +2231,42 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1995
2231
  }
1996
2232
  if (!output)
1997
2233
  throw new PlanError('子 Agent 没有返回文本结果', 'EMPTY_CHILD_OUTPUT');
2234
+ /*
2235
+ * [2.2.8][T7] 结果块解析失败 = 与 CHILD_NOT_COMPLETED 同路径的有界回喂重试。
2236
+ *
2237
+ * T4 事故(用户 2026-11-09 报告):子会话工作完成、交付物已在盘上,只是
2238
+ * 结果块 JSON 写坏;旧实现在这里一次即判 blocked,并级联阻断下游——
2239
+ * 侧栏(子会话实时活动态)与账本(结算态)出现十几分钟的可见错位。
2240
+ * 现在结算前先用纯函数裁决一次(不写状态、不留双源):
2241
+ * - unparsable 且还有回喂意义(`shouldRetryAttempt` 与 CHILD_NOT_COMPLETED
2242
+ * 同一道闸;最多两次由 attempt 上限统一把关,不会无限循环)→ 抛
2243
+ * EVIDENCE_UNPARSABLE,由下方 catch 把解析器具体错误回喂同一子会话,
2244
+ * 要求「修正结果块后重新回报,勿重做已完成工作」;
2245
+ * - 重试后仍 unparsable(或预算不再够一次回喂)→ 按实受阻,随行附上
2246
+ * attempt 摘要声明且确核在盘的产物清单,提示主 Agent 用
2247
+ * `dsh_workplan_update` 复核改判。
2248
+ * 结算严格性不变:非法 JSON 依旧绝不计 done——只修恢复路径。
2249
+ */
2250
+ const settleRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2251
+ const settleVerdict = settleRow?.closure === 'escalated'
2252
+ ? null
2253
+ : adjudicateResult({
2254
+ output,
2255
+ strict: options.strictEvidence !== false,
2256
+ expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
2257
+ });
2258
+ if (settleVerdict && settleVerdict.verification === 'unparsable') {
2259
+ const unparsableLanded = probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists);
2260
+ const unparsableError = new PlanError(`结果块无法解析,本次回报不能结算(工作本身不计失败):${truncate(String(settleVerdict.error ?? ''), 600)}`
2261
+ + (unparsableLanded.length > 0
2262
+ ? `;上一次回报声明且已核到在盘的产物:${unparsableLanded.slice(0, 6).join('、')}——请勿重做已完成的工作,只修正结果块为合法 JSON 后重新完整回报`
2263
+ : ';请修正结果块为合法 JSON(引号、逗号、括号成对,标记成对出现)后重新回报'), 'EVIDENCE_UNPARSABLE', { subtaskId: subtask.id });
2264
+ if (shouldRetryAttempt(unparsableError, attempt, deadline - Date.now(), idleTimeoutMs)) {
2265
+ throw unparsableError;
2266
+ }
2267
+ settleFromOutput(record, subtask, output, guard, options, settleVerdict, probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists));
2268
+ return;
2269
+ }
1998
2270
  /*
1999
2271
  * [1.7.0] Evidence decides the verdict.
2000
2272
  *
@@ -2004,7 +2276,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2004
2276
  * is the single deterministic table; `settleFromOutput` adds the
2005
2277
  * environment-dependent artifact check.
2006
2278
  */
2007
- settleFromOutput(record, subtask, output, guard, options);
2279
+ settleFromOutput(record, subtask, output, guard, options, settleVerdict ?? undefined);
2008
2280
  return;
2009
2281
  }
2010
2282
  catch (error) {
@@ -2034,6 +2306,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2034
2306
  `${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
2035
2307
  ].slice(-20);
2036
2308
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
2309
+ // [2.2.7] 中断即报:用户当下就知道「谁被打断、为什么、系统正在怎么处理」。
2310
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id, `子任务 ${subtask.id}(${subtask.title})第 ${attempt} 次执行被打断(${lastFailure.code}:${truncate(lastFailure.message, 140)});处理:插件已把失败原因回喂同一子会话并自动重试(第 ${attempt + 1} 次),任务整体仍在推进,这不是最终失败。`);
2037
2311
  continue;
2038
2312
  }
2039
2313
  /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
@@ -2064,7 +2338,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2064
2338
  return interruptedFlag ? { interrupted: true } : undefined;
2065
2339
  }
2066
2340
  const message = describeError(lastError ?? new Error('未知失败'));
2067
- writeSubtaskStatus(record, subtask.id, {
2341
+ const finalBlocked = writeSubtaskStatus(record, subtask.id, {
2068
2342
  status: 'blocked',
2069
2343
  closure: 'blocked',
2070
2344
  blockedKind: 'failed',
@@ -2083,6 +2357,14 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2083
2357
  : {}),
2084
2358
  }, guard);
2085
2359
  recordSubtaskError(record, subtask.id, message, guard);
2360
+ // [2.2.7] 中断即报:重试耗尽/不可重试走到终点时立即说清本质原因与后续处置,
2361
+ // 不等整轮结果消息。
2362
+ if (finalBlocked && !guard.timedOut && !parentSignal.aborted) {
2363
+ const landed = interruptedEvidence?.artifacts?.length
2364
+ ? `已核到 ${interruptedEvidence.artifacts.length} 个产物在盘上:${interruptedEvidence.artifacts.slice(0, 3).join('、')}`
2365
+ : '子会话未留下已核实的在盘产物';
2366
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id, `子任务 ${subtask.id}(${subtask.title})已受阻:${truncate(message, 160)};产物线索:${landed};处理:本行不再自动重试,整轮结果会如实列为未完成,由主会话据实决定续跑/改判/向你说明——期间其余子任务继续执行。`);
2367
+ }
2086
2368
  return interruptedFlag ? { interrupted: true } : undefined;
2087
2369
  }
2088
2370
  catch (error) {
@@ -2107,6 +2389,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2107
2389
  // The status list itself is unusable; the outer dispatcher records the error.
2108
2390
  }
2109
2391
  recordSubtaskError(record, subtask.id, message, guard);
2392
+ // [2.2.7] 中断即报:执行链路自身出异常同样不能对用户沉默。
2393
+ announceSubtaskInterrupt(record, interruptSession(), subtask.id, `子任务 ${subtask.id}(${subtask.title})执行过程发生未预期异常:${truncate(message, 160)};处理:本行已置为受阻并如实留档,主会话将在结果消息后据实决定续跑/改判,不会伪造完成。`);
2110
2394
  }
2111
2395
  finally {
2112
2396
  /*
@@ -2601,7 +2885,15 @@ export function buildRoundResult(record, sessionId, limits) {
2601
2885
  * `deliveryReady` 门禁读同一组输入(否则「结果说完成、present 被拒」)。
2602
2886
  */
2603
2887
  changePending: record.changeRequest?.status === 'pending',
2604
- reportPending: record.reportPending === true,
2888
+ /*
2889
+ * [2.2.9][T3][M5] 冻结值与载荷同源:finishRound 已保证先 markReported
2890
+ * 再 build,这里若仍读 `record.reportPending` 可变标志,标志可能停在
2891
+ * 上一次失败的旧值,导致结果消息文本(plan.ts buildResultSummary 判
2892
+ * 「证据未通过(reportPending)」)与同一消息内 statuses 的门禁判定互相
2893
+ * 矛盾——正是震荡观感在消息侧的残留。改读派生函数后,冻结的 S3 恒等于
2894
+ * 载荷 statuses 的事实,摘要、指令与 present 门禁读到同一结论。
2895
+ */
2896
+ reportPending: deriveReportPending(record),
2605
2897
  });
2606
2898
  }
2607
2899
  /**
@@ -3243,7 +3535,8 @@ function serialisePlan(record, session) {
3243
3535
  */
3244
3536
  planRevision: Number(record.planRevision ?? 0),
3245
3537
  changeRequest: record.changeRequest ?? null,
3246
- reportPending: record.reportPending === true,
3538
+ // [2.2.9][T3][M4.1] 看板观测与门禁同源(纯派生),不再读可变标志。
3539
+ reportPending: deriveReportPending(record),
3247
3540
  /*
3248
3541
  * Liveness and resume bookkeeping. Without these the dashboard could not
3249
3542
  * tell a slow-but-alive child from a wedged one, and the model could not
@@ -3541,14 +3834,59 @@ export function reconstructFromSession(session, targetPlanId) {
3541
3834
  * `dsh_workplan_update` used to live only in the live cache, so a refresh
3542
3835
  * reverted the dashboard to the child's original verdict. The durable
3543
3836
  * `workplan-update` message is small and append-only, so replay is just
3544
- * "apply it when its turn comes"; a lower revision never overwrites a
3545
- * newer one (see `applyResultStatuses`).
3837
+ * "apply it when its turn comes". [2.2.9][T2][mono-gate] used to claim a
3838
+ * protection that only existed on the result-message path
3839
+ * (`applyResultStatuses`): a durable update with a lower revision could
3840
+ * still overwrite a newer settled row. The gate below now enforces it —
3841
+ * a strictly-lower revision never overwrites; equal revision passes
3842
+ * (dedup for the same write lives in `appliedUpdates`).
3546
3843
  */
3547
3844
  const update = parseUpdateMessage(event.data);
3548
3845
  if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
3549
3846
  const snap = snapshots.get(update.planId);
3550
3847
  if (snap) {
3551
3848
  try {
3849
+ /*
3850
+ * [2.2.9][T2][mono-gate] 结算事件写入单调性闸(M1,症状①主闸)。
3851
+ *
3852
+ * 事故形状(wp-215ed52f T5 实证):结算 rev16 已落 durable 结果消息,
3853
+ * 主 Agent 基于落后的 live 快照做 handoff 答复,追加了 rev9/10 的
3854
+ * workplan-update(seq 更晚)。回放按 seq 升序,后到的旧事件无条件
3855
+ * 覆盖先落盘的新结算——「后到即覆盖」与「revision 单调、已结算内容
3856
+ * 不可回退」的业务不变量正面冲突。
3857
+ *
3858
+ * 闸语义(与 plan.ts applyResultStatuses 的 result 族闸对齐):
3859
+ * - evRev < rowRev → 回退事件:拒绝整事件语义(含 3936 一带的直写
3860
+ * 白名单与 extendMs 合成,防止旧事件的状态性字段漏进新行),只有
3861
+ * handoffs 走逐项单调合并(M2:答复是字段级增量,新登记永远合法、
3862
+ * answered/closed 终态永不回退);
3863
+ * - 仍必须 appliedUpdates.set:否则同一次改判的 tool/result 配对
3864
+ * 记录(patch 不带 rev,applyStatus 强算 current+1)会绕过本闸从
3865
+ * 第二通道把旧内容灌回;
3866
+ * - evRev === rowRev → 前向通过(等 rev 补写是合法场景;同一条写入
3867
+ * 的重复应用由既有 appliedUpdates/1.8.11 去重通道拦截);
3868
+ * - evRev 为 null(旧格式无 revision 字段 / 非整数)→ 不猜、放行,
3869
+ * 向后兼容(applyStatus 尾部按 current+1 单调抬号)。
3870
+ */
3871
+ const gateRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
3872
+ const rowRev = Number(gateRow?.revision ?? 0);
3873
+ const evRev = Number.isInteger(update.revision) ? Number(update.revision) : null;
3874
+ if (gateRow && evRev !== null && evRev < rowRev) {
3875
+ if (Array.isArray(update.handoffs)) {
3876
+ const merged = mergeHandoffEntriesByUpdatedAt(gateRow.handoffs, update.handoffs);
3877
+ if (merged.changed)
3878
+ gateRow.handoffs = merged.value;
3879
+ }
3880
+ console.warn('[dsh-workplan] monotonicity gate skipped a stale replayed update: '
3881
+ + `${String(update.planId)}/${String(update.subtaskId)} `
3882
+ + `(event rev ${evRev} < row rev ${rowRev}); row content kept, `
3883
+ + 'handoff entries merged monotonically');
3884
+ appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
3885
+ seq: Number(event.seq ?? 0),
3886
+ status: String(update.status ?? ''),
3887
+ });
3888
+ continue;
3889
+ }
3552
3890
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
3553
3891
  /*
3554
3892
  * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
@@ -3582,6 +3920,31 @@ export function reconstructFromSession(session, targetPlanId) {
3582
3920
  timeoutMs: update.timeoutMs,
3583
3921
  updatedBy: 'agent',
3584
3922
  });
3923
+ /*
3924
+ * [2.2.9][T3][M4] 回放侧人工改判的回报闭环——与 live 路径(改判
3925
+ * 工具在 durable 落盘成功后 markReported)配成同一条不变量:
3926
+ * durable 的 workplan-update 携带显式 status:'done' 时,这条消息
3927
+ * 本身就是主 Agent 亲笔写进会话日志的「完成已回报」证据。旧日志
3928
+ * 嵌的是 closure:'done'(2.2.9 之前的口径),回放在此一并升级为
3929
+ * reported;report.ref 指向这条 durable 消息的 seq——引用真实存在、
3930
+ * 可复核。不升 handoffs 快照消息(它们的 status 未被应用,handoff
3931
+ * 记录不是一次回报),子结算行的回报仍须来自结果消息或 pre-step
3932
+ * 自愈(M4.2)。live 与重建由此在同一份日志上逐行同判,
3933
+ * 「可交付↔门禁未放行」的震荡失去立足点。
3934
+ */
3935
+ if (update.status === 'done' && update.handoffs === undefined) {
3936
+ const healedRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
3937
+ if (healedRow?.status === 'done' && healedRow?.closure === 'done') {
3938
+ healedRow.closure = 'reported';
3939
+ healedRow.reportedAt = Number(update.at) || Date.now();
3940
+ healedRow.report = {
3941
+ state: 'sent',
3942
+ at: Number(update.at) || Date.now(),
3943
+ ref: `${String(update.planId)}:replay:${String(Number(event.seq ?? 0))}`,
3944
+ turn: null,
3945
+ };
3946
+ }
3947
+ }
3585
3948
  /*
3586
3949
  * [2.2.0][T4/O-3b][E] 柔性时长协商新字段回放(E 项,runtime.ts 2931 一带)。
3587
3950
  *
@@ -3626,6 +3989,12 @@ export function reconstructFromSession(session, targetPlanId) {
3626
3989
  */
3627
3990
  console.warn('[dsh-workplan] 回放忽略一条不合法的历史改判:'
3628
3991
  + `${String(update?.planId ?? '')}/${String(update?.subtaskId ?? '')}:`
3992
+ + /*
3993
+ * [2.2.9][T3][M4.3] 可诊断化:旧快照携带的 closure/revision 与被保留
3994
+ * 的行现状一并带出,「改判丢失」不再只有一句 error.message。
3995
+ */
3996
+ `event rev=${String(update?.revision ?? 'none')} closure=${String(update?.closure ?? 'none')} `
3997
+ + `vs row rev=${String(snap.statuses.find((item) => item?.subtaskId === update?.subtaskId)?.revision ?? 'none')}:`
3629
3998
  + `${error instanceof Error ? error.message : String(error)}`);
3630
3999
  }
3631
4000
  }
@@ -3826,12 +4195,19 @@ export function reconstructFromSession(session, targetPlanId) {
3826
4195
  planRevision: chosen.planRevision,
3827
4196
  changeRequest: chosen.changeRequest,
3828
4197
  /*
3829
- * [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
3830
- * 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
3831
- * 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
3832
- * 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
4198
+ * [2.2.9][T3][M4.2] 重建记录必须带 `resultWritten`。
4199
+ *
4200
+ * 事故实证(wp-215ed52f 症状②第三拍):pre-step 回报自愈的条件是
4201
+ * `reportPending && resultWritten`,而重建对象从不携带该字段(恒
4202
+ * undefined)→ 条件永不成立 → 重启后派生出的「未回报」态永远无法
4203
+ * 自愈,只能靠幂等复核+人工改判收敛——这正是「震荡三次」的机制解释。
4204
+ * durable 会话里存在本轮结果消息(resultSeen)就是「已写入」的事实,
4205
+ * 用它补齐后自愈在重建态可达:重启 → reportPending 派生 true →
4206
+ * pre-step 幂等 markReported → 门禁一次收敛。
3833
4207
  */
3834
- reportPending: statuses.some((item) => item?.status === 'done' && item?.closure === 'done'),
4208
+ resultWritten: resultSeen,
4209
+ // [2.2.9][T3][M4.1] 派生口径与门禁/看板/冻结单源(deriveReportPending)。
4210
+ reportPending: deriveReportPending({ statuses }),
3835
4211
  };
3836
4212
  }
3837
4213
  function liveSessions(ctx) {
@@ -4053,13 +4429,20 @@ export function createWorkplanRuntime(ctx, options = {}) {
4053
4429
  /*
4054
4430
  * [1.11.0] 回报自愈(契约 §7.3 B4):上一轮结果消息已写入,但回报标记
4055
4431
  * 写失败/进程中断时,下一步 pre-step 幂等补齐,不重复追加上下文。
4432
+ *
4433
+ * [2.2.9][T3][M4.1/M4.2] 判定改读派生谓词 `deriveReportPending`:live
4434
+ * 记录的标志只是审计镜像,自愈若读镜像,镜像过期时该自愈的不自愈、
4435
+ * 不该自愈的白跑一遍。配合重建对象补上的 `resultWritten`(M4.2,
4436
+ * 此前该字段在重建态恒 undefined、条件永不成立,自愈对重启后的会话
4437
+ * 形同虚设——「震荡三次靠人工收敛」的第三拍),重启 → 派生 true →
4438
+ * 首个 pre-step 幂等 markReported → 门禁一次收敛,无需人工改判。
4056
4439
  */
4057
4440
  const session = payload.agent?.session;
4058
4441
  const known = session ? state.records.get(session.id) : null;
4059
- if (known?.plan && known.reportPending === true && known.resultWritten === true) {
4442
+ if (known?.plan && deriveReportPending(known) && known.resultWritten === true) {
4060
4443
  const changed = markReported(known, session, `${known.plan.planId}:${known.dispatchedAt ?? 0}`);
4061
4444
  if (changed > 0) {
4062
- known.reportPending = (known.statuses ?? []).some((item) => item?.status === 'done' && item?.closure === 'done');
4445
+ known.reportPending = deriveReportPending(known);
4063
4446
  }
4064
4447
  }
4065
4448
  return await maybePlan(ctx, state, payload, downstream, { ...options, limits });
@@ -4557,6 +4940,19 @@ export function createWorkplanRuntime(ctx, options = {}) {
4557
4940
  instruction: writtenRow?.instruction,
4558
4941
  instructionSeq: writtenRow?.instructionSeq,
4559
4942
  }));
4943
+ /*
4944
+ * [2.2.9][T3][M4] 人工改判的这条 durable update 消息本身就是「完成已
4945
+ * 回报」的会话证据(主 Agent 亲笔写进会话日志),落盘成功后立即闭环
4946
+ * closure done→reported,否则派生闸会把改判行当成未回报而永久拦死
4947
+ * ——改判→present 是主 Agent 的正常工作流(wp-215ed52f T5/R1-1 实证)。
4948
+ * append 失败时不进此支:行留在 closure:'done',门禁 fail-closed,
4949
+ * 绝不留下无证据的已回报(与 finishRound 同一铁律)。回放侧对
4950
+ * status:'done' 的改判消息做同样的升级(见 reconstructFromSession),
4951
+ * live 与重建在同一份日志上逐行同判——W2 分叉就此封死。
4952
+ */
4953
+ if (status === 'done') {
4954
+ markReported(record, session, `${record.plan.planId}:${record.dispatchedAt ?? 0}`, subtaskId);
4955
+ }
4560
4956
  }
4561
4957
  catch (error) {
4562
4958
  pushRecordError(record, error);
@@ -5232,14 +5628,19 @@ export function createWorkplanRuntime(ctx, options = {}) {
5232
5628
  * 绝不留下没有证据的 reported。
5233
5629
  */
5234
5630
  const before = (record.statuses ?? []).map((item) => ({ ...item }));
5235
- const needReport = before.filter((item) => item?.status === 'done' && item?.closure !== 'reported').length;
5236
- // ^ 本轮结算:done 且未到 reported 的行(含旧日志的 null)都算待回报。
5237
- const reported = markReported(record, session, ref);
5631
+ markReported(record, session, ref);
5238
5632
  const resultMessage = buildRoundResult(record, session.id, limits);
5239
5633
  try {
5240
5634
  appendUserMessage(session, resultMessage);
5241
5635
  record.resultWritten = true;
5242
- record.reportPending = needReport > 0 && reported < needReport;
5636
+ /*
5637
+ * [2.2.9][T3][M4] 标志自此只是审计镜像,一律按派生函数回填。
5638
+ * 旧公式 `needReport > 0 && reported < needReport` 自带第三套口径
5639
+ * (把旧日志 closure=null 的行也算待回报),与门禁/重建/自愈使用的
5640
+ * 严格 `closure==='done'` 判据并存——多套判据互不一致正是震荡的
5641
+ * 温床。收敛后镜像与 statuses 事实恒等,任何读取方都对得上。
5642
+ */
5643
+ record.reportPending = deriveReportPending(record);
5243
5644
  }
5244
5645
  catch (error) {
5245
5646
  // 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
@@ -5252,10 +5653,11 @@ export function createWorkplanRuntime(ctx, options = {}) {
5252
5653
  */
5253
5654
  pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
5254
5655
  /*
5255
- * [1.11.0] 写失败时不能假装回报过。保留 reportPending,让下一次
5256
- * pre-step 或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
5656
+ * [1.11.0] 写失败时不能假装回报过。回滚后镜像同步为回滚事实
5657
+ * (done 行回到 closure:'done' ⇒ 派生 true),交下一次 pre-step
5658
+ * 自愈或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
5257
5659
  */
5258
- record.reportPending = true;
5660
+ record.reportPending = deriveReportPending(record);
5259
5661
  }
5260
5662
  }
5261
5663
  else {
@@ -5265,9 +5667,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
5265
5667
  */
5266
5668
  const pending = (record.statuses ?? []).some((item) => item?.status === 'done' && item?.closure !== 'reported');
5267
5669
  if (pending) {
5268
- const changed = markReported(record, session, ref);
5269
- if (changed > 0)
5270
- record.reportPending = false;
5670
+ markReported(record, session, ref);
5671
+ // [2.2.9][T3][M4] 镜像按派生回填:部分标记失败时不谎报「已回报」。
5672
+ record.reportPending = deriveReportPending(record);
5271
5673
  }
5272
5674
  }
5273
5675
  /*
@@ -5656,6 +6058,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
5656
6058
  escalationSeq: revision,
5657
6059
  revision,
5658
6060
  }));
6061
+ // [2.2.7] 中断即报:请示同样要让用户当下看到「有人卡在哪、等什么决定」,
6062
+ // 结构化 update 消息是给回放/主 Agent 的,这条纯文本是给用户的。
6063
+ announceSubtaskInterrupt(record, parent, row.subtaskId, `子任务 ${row.subtaskId} 执行中请求指示:${truncate(question, 160)};性质:等待主会话拍板,不是执行失败;处理:主会话答复后用 dsh_workplan_instruct 下发决定,该行将恢复执行。`);
5659
6064
  }
5660
6065
  catch (error) {
5661
6066
  pushRecordError(record, error);
@@ -6713,7 +7118,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
6713
7118
  statuses: snapshot.statuses,
6714
7119
  attempt: book.count,
6715
7120
  changePending: record.changeRequest?.status === 'pending',
6716
- reportPending: record.reportPending === true,
7121
+ // [2.2.9][T3][M4.1] 强制收尾提示与门禁同源(纯派生)。
7122
+ reportPending: deriveReportPending(record),
6717
7123
  }), {
6718
7124
  kind: 'workplan-continue',
6719
7125
  form: 'notice',