dsh-workplan 2.3.9 → 3.0.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/lib/runtime.js CHANGED
@@ -12,19 +12,43 @@
12
12
  * in this file is allowed to escape as an unhandled rejection from a listener.
13
13
  */
14
14
  import { randomUUID } from 'node:crypto';
15
- import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
15
+ import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
16
16
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
17
17
  import { createNoticeChannel, finaliseNoticeChannel, formatNoticeChannelLog, observeRelayedNotice, readLeadAgentId, resolveLeadAgentId, validateNoticeChannel, } from './notice-channel.js';
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,
18
+ // [T5-channel][契约v1 §2] 部门消息留痕:冻结 API,只 import 不改(journal-member 实现)。
19
+ import { appendDeptMessage, makeDeptMessageId, readDeptMessages } from './dept-journal.js';
20
+ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, appendUserMessage, enterPreHeadWindow, applyStatus, attachPlanMeta, blockCancelledDependents, buildChildPrompt, buildCancelMessage, buildClarifyMessage, createPlannerProgressReporter,
21
+ // [2.5.2] 规划期间心跳(治整段静默以为死机):plan.ts 纯函数 + 注入工厂。
22
+ createPlanningHeartbeat, planningHeartbeatIntervalMs,
23
+ // [2.5.2][stall-fix] 派发执行期进度心跳文案(同一工厂,buildMessage 注入)。
24
+ buildDispatchHeartbeat, buildDegradedMessage, buildPlanMessage,
25
+ // [2.3.10][T2] 用户要求1:规划前/派发前会话内耗时预告文案(plan.ts 纯函数)。
26
+ buildPhaseZeroLeaderPrompt, buildPhaseZeroContinuationHint, buildPlanningPreAnnouncement, buildDispatchPreAnnouncement, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness,
27
+ // [T7][lead-decisions J2/G2] 负责人时长聚合纯函数:模型可读面与 delegate status
28
+ // 挂同一函数(看板载荷经 plan.ts normaliseStatusEntry 同源),读时派生不持久化。
29
+ deriveLeaderEstimate, leaderEstimateRoster, derivePlanSnapshot,
19
30
  // [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, mergeHandoffEntriesByUpdatedAt, needEntryText, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, } from './plan.js';
31
+ deriveSubtaskTimeoutMs, extractJson, flattenSubtasks,
32
+ // [T7] 关键进度收敛:单条 500 上限裁剪器+轮预算重置(C3)。
33
+ capKeyProgressText, resetRoundInjectionBudget, 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,
34
+ // [3.0.0] F10 专家汇报核验(adjudicateExpertReport)复用同一解析器。
35
+ parseEvidenceBlock,
36
+ // [2.5.2][T4b][D2] 备份归属校验需要从标记块内提取 JSON(裸 JSON 之外的第二入口)。
37
+ EVIDENCE_MARKER_BEGIN, EVIDENCE_MARKER_END, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS,
38
+ // [2.5.5][T10] 合并闸:回放按批展开,结算前把缓冲台账合并落盘。
39
+ parseUpdateMessages, flushPendingWorkplanUpdates, buildUpdateMessage, normaliseHandoffs, mergeHandoffEntriesByUpdatedAt, needEntryText, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, findSubtask, EFFORT_STRENGTH_ORDER, } from './plan.js';
40
+ // [3.0.0] 用户 2026-11-14 第 2、4 条:两条逐字冻结的会话固定文案。
41
+ import { STATUS_ASSIGNED_TEXT, STATUS_ASSIGNING_TEXT, checkExpertReport, checkSubtaskQualityRequirements, isQualityGatePlan } from './v3-contract.js';
42
+ // [SCv2-T4] 判据层单一真源(用户 2026-11-13 裁决 B/B/B/B/A/A/B):生效边界 D-1、
43
+ // 例外批准 Q1-B、结算三选一 §3.5、单次墙钟 Q6-A、事前聚合 Q4-B。运行层常量不改。
44
+ import { CRITERION_TARGET_MINUTES, appendCriterionViolation, attemptWallClockMsOf, criterionExAnte, criterionV2Active, evaluateCriterion, sanitizeCriterionException, } from './criterion.js';
21
45
  import { auditClarifyNeed, compactUnderstandingAudit, validatePlanContext } from './understanding.js';
22
46
  // [2.3.9][T3] LLM 家族检测 + 推理等级静态约束(用户强制要求 1/2;详见 llm-rules.ts 头注释)。
23
47
  // [2.3.9][T4b] 追加第三层派发纯逻辑核:buildLlmRulesBrief(要求 1/2 全文告知注入,
24
48
  // 部门层与专家/组员层共用同一事实源)、planDelegations(负责人「先全面梳理再分配」
25
49
  // 硬门禁 + 分工表校验 + 等级钳制)、buildDelegateePrompt(第三层任务书)。
26
- import { allowedEffortsForModel, buildDelegateePrompt, buildLlmRulesBrief, classifyModelFamily, correctEffortForModel, highestEffortOf, planDelegations, } from './llm-rules.js';
27
- import { phaseGateFromErrors, phaseSummaryLine, validatePhaseEvidence } from './three-phase.js';
50
+ import { allowedEffortsForModel, buildDelegateePrompt, buildLlmRulesBrief, classifyModelFamily, correctEffortForModel, highestEffortOf, planDelegations, buildPhaseZeroDelegateePrompt, resolveTaskEffort, } from './llm-rules.js';
51
+ import { phaseGateFromErrors, phaseSummaryLine, sanitizeMainDeepThink, validateMainDeepThink, validatePhaseEvidence } from './three-phase.js';
28
52
  import { lessonStats, rankLessons, readLessons, recordLesson, renderLessonsBrief, resolveLessonsFile, } from './lessons.js';
29
53
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
30
54
  import { supersedePlanRecord } from './supersede.js';
@@ -120,7 +144,13 @@ function readinessOf(record, snapshot) {
120
144
  expectedAcceptance: record?.plan ? expectedAcceptanceOf(record.plan) : undefined,
121
145
  });
122
146
  }
123
- export const PLANNER_TIMEOUT_MS = 300000;
147
+ /**
148
+ * [2.5.2] 规划期间心跳间隔(默认 45s,DSH_WORKPLAN_PLANNING_HEARTBEAT_MS,
149
+ * 毫秒 ≥5000):runPlanner 仍在跑时按此间隔在会话里发一条可见进度通知,
150
+ * 治「持续流式但很慢的尝试整段静默、用户以为死机」(本会话 turn 1 实测
151
+ * 12.5 分钟零输出)。与失败重试通知正交,不改重试/超时语义。
152
+ */
153
+ export const PLANNING_HEARTBEAT_MS = 45000;
124
154
  /**
125
155
  * 无进展窗口(默认 300s,DSH_WORKPLAN_PLANNER_TIMEOUT_MS,毫秒 >0)。
126
156
  *
@@ -133,19 +163,20 @@ export const PLANNER_TIMEOUT_MS = 300000;
133
163
  * 300.06s)规划器仍在工作却被 abort,自动分解直接降级——提高默认值或开放
134
164
  * 配置都没有解决「按墙钟掐断一个正在产出的调用」这个结构问题。
135
165
  */
136
- export const PLANNER_IDLE_TIMEOUT_MS = 90000;
166
+ export const PLANNER_TIMEOUT_MS = 300000;
137
167
  /**
138
168
  * 首个 chunk 之后的「完全静默」窗口(默认 90s,DSH_WORKPLAN_PLANNER_IDLE_
139
169
  * TIMEOUT_MS,毫秒 >0):文本、推理、usage 一个 chunk 都没有这么久,判定为
140
170
  * 连接卡死而不是模型还在思考。这个常量在 2.1.6 之前只声明、从未接线(死
141
171
  * 代码),现在真正参与计时;设为不小于无进展窗口即等价于关闭。
142
172
  */
143
- export const PLANNER_HARD_MULTIPLIER = 3;
173
+ export const PLANNER_IDLE_TIMEOUT_MS = 90000;
144
174
  /**
145
175
  * 绝对上限 = 无进展窗口 × 该倍数(默认 900s)。慢可以,慢到没边不行:它给
146
176
  * 单次规划器尝试一个终点,保证规划失败永远是「有限时间后给出可执行建议」,
147
177
  * 而不是无限占用本轮预算。
148
178
  */
179
+ export const PLANNER_HARD_MULTIPLIER = 3;
149
180
  /**
150
181
  * [2.2.0][T13b/推理等级] 规划器默认推理档 = max(用户 2026-11-08 决策 5)。
151
182
  *
@@ -187,7 +218,7 @@ export const DEFAULT_PLANNER_REASONING_EFFORT = 'max';
187
218
  * 与宿主 resolveCallWithInfo 的「reasoning===undefined 时任何档位都抛错」对齐;
188
219
  * - 能力查询不可用(宿主不暴露 / 查询抛错)⇒ 保持旧行为,绝不因钳制引入新故障。
189
220
  */
190
- const EFFORT_STRENGTH_ORDER = Object.freeze(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']);
221
+ // [3.0.0] 去副本:强度序单一真源为 plan.ts 导出的 EFFORT_STRENGTH_ORDER(上方已导入,本文件直接引用)。
191
222
  /** 请求档位 → 模型支持清单内的等效钳制档;空清单返回 undefined(= 不发送该字段)。 */
192
223
  export function clampEffortToSupported(effort, supported) {
193
224
  if (!Array.isArray(supported) || supported.length === 0)
@@ -258,6 +289,12 @@ export async function resolveSupportedEfforts(llm, provider, model, signal) {
258
289
  * 2.0×60000, MIN, MAX)),本常量只在无预估、无显式值时兜底(③C2 零回归)。
259
290
  * 时间是协商出来的安全兜底,不是固定交付期限:到点走 L4 安全兜底结算+
260
291
  * 「待裁决」标记(延期 / 重试 / 接受),不表述为「强制结束」式固定期限误杀。
292
+ *
293
+ * [2.6.0][Q1-B/Q7-B] 分层:判据层完成目标 ≤10 分钟(默认必须达成,超出须用户
294
+ * 明确批准并留痕);本条协商上限属运行层安全兜底,数值与公式一律不变,且不构成
295
+ * 「允许慢」的许可。「延期(extendMs)」不再是主 Agent 单方可为——须先取得用户
296
+ * 批准留痕(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=
297
+ * 未批准),未批准时按判据层未达标处理(不 done、转接替子任务)。
261
298
  */
262
299
  export const CHILD_TIMEOUT_MS = 900000;
263
300
  /** No-progress window: the child's own session log stopped growing. */
@@ -275,6 +312,9 @@ export const MIN_CHILD_TIMEOUT_MS = 1000;
275
312
  * 单次绝对上限)(方案 §1③),2h 让「预告 60 分钟的子任务,其单次执行上限
276
313
  * ≥ 60 分钟」(方案 C1)成立;tests/time-estimate-negotiation.test.ts 的
277
314
  * expected 公式直接引用本常量,数值不同步会红灯。
315
+ *
316
+ * [2.6.0][Q7-B] 分层声明:120 分钟是运行层安全兜底(防失控),不是时长许可;
317
+ * 判据层完成目标为 ≤10 分钟(Q1/Q4),两层互不取代,数值与公式零改动。
278
318
  */
279
319
  export const MAX_CHILD_TIMEOUT_MS = 7200000;
280
320
  export const MIN_CHILD_IDLE_MS = 1000;
@@ -407,15 +447,16 @@ export function goalRoundPlanningTask(ctx, payload, existing) {
407
447
  /**
408
448
  * Whether an existing plan record still owns work in this session.
409
449
  *
410
- * `isTerminalPhase()` 只覆盖 cancelled/superseded(present 门禁的语义);
411
- * 对 goal 轮次的入口判定,done/ended/degraded/clarify 同样是「这一轮可以
412
- * 开始新计划」的历史记录,不能把 `/goal` 任务永久挡在自动分解之外。
450
+ * 终态(cancelled/superseded)判定复用 plan.ts 的同一真源 `isTerminalPhase()`
451
+ * (TERMINAL_PHASES),不再本地硬编码;goal 轮次入口在终态之外,done/ended/
452
+ * degraded/clarify 同样是「这一轮可以开始新计划」的历史记录,不能把 `/goal`
453
+ * 任务永久挡在自动分解之外。
413
454
  */
414
455
  function planRecordIsLive(existing) {
415
456
  if (!existing?.plan)
416
457
  return false;
417
458
  const phase = String(existing.phase ?? '');
418
- return !['done', 'ended', 'cancelled', 'superseded', 'clarify', 'degraded'].includes(phase);
459
+ return !isTerminalPhase(phase) && !['done', 'ended', 'clarify', 'degraded'].includes(phase);
419
460
  }
420
461
  /** Read the structured objective of the current goal view, when the service exists. */
421
462
  function goalObjectiveOf(ctx, agent) {
@@ -729,13 +770,23 @@ export async function runPlanner(ctx, options) {
729
770
  /*
730
771
  * [2.3.9][T3/llm-rules] 用户强制要求 1/2(分配前先检测模型家族):qwen 开头
731
772
  * 模型只允许 low / medium / xhigh,其余模型只允许 low / high / max。
732
- * 默认档随家族取「合法集内最高档」(qwen⇒xhigh、非 qwen⇒max);env 显式
733
- * 覆盖仍优先,覆盖值同样过静态收窄。静态约束先于宿主能力钳制执行(两道闸:
734
- * 静态表权威,能力面在其上继续交集钳制,均留痕,与 U7 裁决一致)。模型名
735
- * 缺失⇒不施加静态约束并用原默认档,保持 [2.2.7]「无从判定⇒不阻断」旧行为。
773
+ * env 显式覆盖仍优先,覆盖值同样过静态收窄。静态约束先于宿主能力钳制执行
774
+ * (两道闸:静态表权威,能力面在其上继续交集钳制,均留痕,与 U7 裁决一致)。
775
+ * 模型名缺失⇒不施加静态约束并用原默认档,保持 [2.2.7]「无从判定⇒不阻断」旧行为。
776
+ *
777
+ * [2.5.2][stall-fix] 根因修复(用户报告「提交任务后长时间无反应/以为死机」):
778
+ * 旧默认档取家族最高档(qwen⇒xhigh、非 qwen⇒max),规划器要在最高推理档
779
+ * 生成整份大 JSON,实测单次规划 12-13 分钟——预告之后长时间只有心跳、没有
780
+ * 结果,用户体验即「死机」。规划是结构化分解(中等复杂度),默认档改为
781
+ * 家族中等档(qwen⇒medium、非 qwen⇒high),显著缩短首屏等待;需要最高档
782
+ * 的会话仍可用 DSH_WORKPLAN_PLANNER_REASONING_EFFORT 显式覆盖。中等档不在
783
+ * 合法集时回落最高档(不改变家族白名单语义)。
736
784
  */
737
785
  const plannerStaticAllowed = allowedEffortsForModel(modelSelection?.model);
738
- const plannerFamilyDefault = highestEffortOf(plannerStaticAllowed) ?? DEFAULT_PLANNER_REASONING_EFFORT;
786
+ const plannerModerateDefault = classifyModelFamily(modelSelection?.model) === 'qwen' ? 'medium' : 'high';
787
+ const plannerFamilyDefault = (plannerStaticAllowed && plannerStaticAllowed.includes(plannerModerateDefault)
788
+ ? plannerModerateDefault
789
+ : highestEffortOf(plannerStaticAllowed)) ?? DEFAULT_PLANNER_REASONING_EFFORT;
739
790
  const requestedPlannerEffort = plannerEffort || plannerFamilyDefault;
740
791
  const plannerEffortOriginLabel = plannerEffort ? 'env' : `default-${plannerFamilyDefault}`;
741
792
  const plannerStaticCorrection = plannerStaticAllowed && !plannerStaticAllowed.includes(requestedPlannerEffort)
@@ -900,10 +951,33 @@ export async function runPlanner(ctx, options) {
900
951
  const plan = validated.plan;
901
952
  plan.taskAnchor = guard.audit.anchor;
902
953
  plan.understandingAudit = compactUnderstandingAudit(guard.audit);
954
+ // [2.5.5] 归一化留痕随计划持久化,status/回放可见(治本不静默)。
955
+ if (Array.isArray(validated.notes) && validated.notes.length > 0) {
956
+ plan.normalizations = validated.notes;
957
+ }
903
958
  return plan;
904
959
  }
905
960
  outcome = 'CONTEXT_GUARD';
906
961
  lastErrors = guard.errors.length > 0 ? guard.errors : guard.warnings;
962
+ /*
963
+ * [3.0.1][治本] 只有用户本人能答复的校验错误(CLARIFY=要求自相矛盾、
964
+ * CONTEXT=指代找不到先行词)禁止交回规划器重试:重试的所谓「修复」只能是
965
+ * 模型替用户瞎猜,猜过守卫后计划照常自动派发——用户还没来得及答复,
966
+ * 部门 Agent 已经对着猜出来的目标开工(本次用户报告的正是这一行为)。
967
+ * 这类错误立即中止规划,由入口转成「先澄清」卡片等用户明确答复;
968
+ * 只有 DEVIATION 这类规划器自己能改写的才继续重试。
969
+ */
970
+ const askUser = lastErrors.filter((entry) => /^(?:CLARIFY|CONTEXT):/.test(String(entry)));
971
+ if (askUser.length > 0) {
972
+ const reason = askUser.map((entry) => String(entry).replace(/^(?:CLARIFY|CONTEXT):\s*/, '')).join(';');
973
+ const hasClarify = askUser.some((entry) => String(entry).startsWith('CLARIFY'));
974
+ const hasContext = askUser.some((entry) => String(entry).startsWith('CONTEXT'));
975
+ const question = [
976
+ hasClarify ? '上述互相矛盾/缺失的信息以哪个为准?请用户明确取舍' : '',
977
+ hasContext ? '任务里的指代具体指哪个对象?请用户给出名称、路径或原内容' : '',
978
+ ].filter(Boolean).join(';');
979
+ throw new PlanError(reason, 'CLARIFY_NEEDED', question);
980
+ }
907
981
  continue;
908
982
  }
909
983
  outcome = 'INVALID_PLAN';
@@ -915,6 +989,14 @@ export async function runPlanner(ctx, options) {
915
989
  * 真实原因。这里优先读我们自己写进 controller.signal.reason 的判定码,
916
990
  * 再区分「用户/宿主主动取消」,最后才当作可重试的偶发错误。
917
991
  */
992
+ /*
993
+ * [3.0.1] CLARIFY_NEEDED 是终态,不是可重试错误:原样上抛给入口转澄清卡片。
994
+ * 必须最先判定——否则会被下面的泛化处理标成 outcome 并进入下一次重试。
995
+ */
996
+ if (error instanceof PlanError && error.code === 'CLARIFY_NEEDED') {
997
+ outcome = 'CLARIFY_NEEDED';
998
+ throw error;
999
+ }
918
1000
  const reason = controller.signal.aborted ? controller.signal.reason : undefined;
919
1001
  if (reason && PLANNER_ABORT_CODES.includes(String(reason.code))) {
920
1002
  /*
@@ -1130,6 +1212,37 @@ function resultText(result) {
1130
1212
  const text = messageText({ content: result?.output ?? [] }).trim();
1131
1213
  return text;
1132
1214
  }
1215
+ /*
1216
+ * [3.0.0] F10 专家汇报门禁接线(用户 2026-11-14 要求 7;契约同一事实源
1217
+ * src/comm-format.ts 的 F10 条目 / src/v3-contract.ts 的 checkExpertReport)。
1218
+ *
1219
+ * 第三层叶子(专家)的产出有两处结算回调消费(delegateTool dispatch /
1220
+ * selfEffort 接续),此前只看 stopReason:专家即使不写精简 report 对象也会被
1221
+ * 记成 done,F10 形同虚设。现在在两处回调的汇报入口统一过这道核验:
1222
+ * 只对「子会话正常结束且结果块声明 done」的汇报校验 report 对象
1223
+ * (keyResults/keyInfo/importantInfo/leadRequirements 四字段齐全、非空、
1224
+ * 不重复);缺失或重复即退回(该成员记 failed 并附 F10 拒因),绝不记 done。
1225
+ *
1226
+ * 最小侵入、只拦 done 路径:结果块无法解析 / 声明 blocked/partial 时维持原
1227
+ * 语义(受阻诊断归 escalate/instruct 通道),F1–F9 与三阶段既有判定不在此
1228
+ * 重复;replay/读档路径不经这两个回调,行为零变化。
1229
+ */
1230
+ function adjudicateExpertReport(outcome) {
1231
+ const text = resultText(outcome);
1232
+ const parsed = parseEvidenceBlock(text);
1233
+ const payload = parsed && typeof parsed === 'object' ? parsed.payload : null;
1234
+ if (!payload || typeof payload !== 'object')
1235
+ return { ok: true };
1236
+ if (String(payload.status ?? '') !== 'done')
1237
+ return { ok: true };
1238
+ const report = checkExpertReport(payload.report);
1239
+ if (!Array.isArray(report.violations) || report.violations.length === 0)
1240
+ return { ok: true };
1241
+ return {
1242
+ ok: false,
1243
+ rejection: `专家汇报未通过 F10 精简汇报契约核验,结果退回重交:${report.violations.slice(0, 4).join(';')}`,
1244
+ };
1245
+ }
1133
1246
  async function disposeActivation(activation, record, subtaskId, guard) {
1134
1247
  let timer = null;
1135
1248
  try {
@@ -1425,7 +1538,8 @@ export function timeoutBlockedPatch(subtask, cwd, message, artifactExists = exis
1425
1538
  /**
1426
1539
  * [1.8.19] The round budget reset used to erase every trace of the attempt.
1427
1540
  *
1428
- * The 20-minute `TOTAL_TIMEOUT` branch resets unfinished rows to `pending`, and
1541
+ * The `TOTAL_TIMEOUT` branch(整轮预算到点;现行默认 TOTAL_TIMEOUT_MS=0 即不设
1542
+ * 整轮硬预算,仅显式配置正数时启用)resets unfinished rows to `pending`, and
1429
1543
  * `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
1430
1544
  * 2026-10-31 incident T10 had run for ~19 minutes and had already written its
1431
1545
  * coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
@@ -1501,6 +1615,23 @@ precomputedVerdict, extraEvidence) {
1501
1615
  * 交付才被用户发现。
1502
1616
  */
1503
1617
  expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
1618
+ /*
1619
+ * [3.0.0][用户要求 7/10/11] 格式层级:计划行=部门负责人,结果必须带
1620
+ * departmentSummary(F11);专家结果必须带 report(F10)。结算时按行上
1621
+ * 已派发的专家名单做覆盖度核对。缺省(无层级/旧回放)不查新条目。
1622
+ */
1623
+ formatTier: (Array.isArray(record?.statuses)
1624
+ ? record.statuses
1625
+ .find((item) => item?.subtaskId === subtask?.id)?.delegates
1626
+ ?.map((item) => String(item?.member ?? ''))
1627
+ .filter((name) => name !== '') ?? []
1628
+ : []).length > 0 ? 'leader' : undefined,
1629
+ expectedExperts: Array.isArray(record?.statuses)
1630
+ ? record.statuses
1631
+ .find((item) => item?.subtaskId === subtask?.id)?.delegates
1632
+ ?.map((item) => String(item?.member ?? ''))
1633
+ .filter((name) => name !== '') ?? []
1634
+ : [],
1504
1635
  });
1505
1636
  const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists);
1506
1637
  const escalated = verdict.status === 'blocked'
@@ -1554,12 +1685,65 @@ precomputedVerdict, extraEvidence) {
1554
1685
  lessonNote = `复盘记忆写入失败:${truncate(error instanceof Error ? error.message : String(error), 120)}`;
1555
1686
  }
1556
1687
  }
1688
+ /*
1689
+ * [SCv2-T4][Q1-B/S-Q1-3/Q3-B/Q6-A] 判据层结算闸(spec §3.5 第 4 步):
1690
+ * 仅对判据 v2 已生效的计划(D-1 三重门后新创建)判定;未生效计划行为逐字不变。
1691
+ * 运行层先安全结算(不丢成果,L4/产物探测照旧),再判判据层:done 且
1692
+ * 事前预估之和 ≤10 且事后单次墙钟 ≤10 ⇒ met;有用户批准留痕 ⇒ exception-approved;
1693
+ * 否则 unmet ⇒ 不得 done,改判 blocked(criterion-overrun)、记违规(append-only)、
1694
+ * 文案指向 replan(replace) 接替行只补缺口。判定顺序=运行层→判据层(S-Q7-5)。
1695
+ */
1696
+ let effectiveStatus = verdict.status;
1697
+ let effectiveError = settleError;
1698
+ let criterionResultValue = null;
1699
+ let criterionDirectWrite = null;
1700
+ if (verdict.status === 'done' && criterionV2Active(record.plan?.createdAt)) {
1701
+ const criterionRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
1702
+ const settledAt = Date.now();
1703
+ let leaderForCriterion = null;
1704
+ try {
1705
+ leaderForCriterion = deriveLeaderEstimate(criterionRow);
1706
+ }
1707
+ catch {
1708
+ leaderForCriterion = null;
1709
+ }
1710
+ const exAnte = criterionExAnte(criterionRow, leaderForCriterion);
1711
+ const wallClockMs = attemptWallClockMsOf({ startedAt: criterionRow?.startedAt, finishedAt: settledAt });
1712
+ const evaluation = evaluateCriterion({
1713
+ exAnteMinutes: exAnte.minutes,
1714
+ exAnteComplete: exAnte.complete,
1715
+ wallClockMs,
1716
+ exception: sanitizeCriterionException(criterionRow?.criterionException),
1717
+ settledAt,
1718
+ });
1719
+ criterionResultValue = evaluation.criterionResult;
1720
+ criterionDirectWrite = { criterionResult: evaluation.criterionResult };
1721
+ if (evaluation.criterionResult === 'unmet') {
1722
+ effectiveStatus = 'blocked';
1723
+ criterionDirectWrite = {
1724
+ criterionResult: 'unmet',
1725
+ closure: 'blocked',
1726
+ blockedKind: 'criterion-overrun',
1727
+ criterionViolations: appendCriterionViolation(criterionRow?.criterionViolations, {
1728
+ at: settledAt,
1729
+ attempt: Number(criterionRow?.timeoutCount ?? 0) + 1,
1730
+ wallClockMs,
1731
+ exAnteMinutes: exAnte.minutes,
1732
+ reasons: evaluation.reasons,
1733
+ }),
1734
+ };
1735
+ effectiveError = `${typeof settleError === 'string' && settleError !== '' ? `${settleError};` : ''}`
1736
+ + `判据违规(criterion-overrun):${evaluation.reasons.join(';')}。`
1737
+ + '未获用户批准不得以 done 收尾(Q1-B);已完成产物只读保留,请用 dsh_workplan_replan(replace) 生成接替子任务只补缺口,'
1738
+ + '或先向用户申请例外批准并留痕(criterionApproval)后复核改判。';
1739
+ }
1740
+ }
1557
1741
  writeSubtaskStatus(record, subtask.id, {
1558
- status: verdict.status,
1742
+ status: effectiveStatus,
1559
1743
  progress: 100,
1560
1744
  finishedAt: Date.now(),
1561
1745
  summary: truncate(lessonNote ? `${output}\n[自我学习] ${lessonNote}` : output, 3000),
1562
- error: settleError,
1746
+ error: effectiveError,
1563
1747
  verification: verdict.verification,
1564
1748
  acceptance: verdict.acceptance,
1565
1749
  artifacts: checked.artifacts.length > 0
@@ -1569,6 +1753,13 @@ precomputedVerdict, extraEvidence) {
1569
1753
  ? checked.missingArtifacts
1570
1754
  : (extraEvidence && extraEvidence.missingArtifacts.length > 0 ? extraEvidence.missingArtifacts : undefined),
1571
1755
  needs: verdict.needs.length > 0 ? verdict.needs : undefined,
1756
+ /*
1757
+ * [3.0.0][用户要求 7/8/10/11] 两级精简 JSON 落行:专家汇报 report 与
1758
+ * 部门汇总 departmentSummary。它们已通过 F10/F11 格式门禁,这里原样
1759
+ * 持久化,供完成通知与看板按需读取(不裁剪内容)。
1760
+ */
1761
+ ...(verdict.departmentSummary ? { departmentSummary: verdict.departmentSummary } : {}),
1762
+ ...(verdict.report ? { report: verdict.report } : {}),
1572
1763
  /*
1573
1764
  * [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
1574
1765
  * `question` 就是同一条请示。它仍然写成 blocked 投影,但 closure 是
@@ -1583,7 +1774,7 @@ precomputedVerdict, extraEvidence) {
1583
1774
  escalatedAt: Date.now(),
1584
1775
  escalationSeq: Number(current?.revision ?? 0) + 1,
1585
1776
  }
1586
- : verdict.status === 'done'
1777
+ : effectiveStatus === 'done'
1587
1778
  /*
1588
1779
  * [1.11.0] 完成必须落到 `closure:'done'`,不是 `blocked`。
1589
1780
  *
@@ -1603,8 +1794,18 @@ precomputedVerdict, extraEvidence) {
1603
1794
  blockedKind: verdict.blockedKind === 'comm-format' ? 'comm-format' : 'failed',
1604
1795
  }),
1605
1796
  }, guard);
1606
- if (verdict.status === 'blocked') {
1607
- recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (settleError ?? '未完成'), guard);
1797
+ /*
1798
+ * [SCv2-T4][C08] 判据字段走 StatusEntry 未知字段直写通道(applyStatus 白名单
1799
+ * 不路由新字段,与 pendingAdjudication/timeoutCount 同一纪律);回放白名单
1800
+ * 已追加 criterionResult/criterionException/criterionViolations,刷新不丢。
1801
+ */
1802
+ if (criterionDirectWrite) {
1803
+ const criterionRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
1804
+ if (criterionRow)
1805
+ Object.assign(criterionRow, criterionDirectWrite);
1806
+ }
1807
+ if (effectiveStatus === 'blocked') {
1808
+ recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (effectiveError ?? '未完成'), guard);
1608
1809
  }
1609
1810
  else if (checked.missingArtifacts.length > 0) {
1610
1811
  recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
@@ -1617,7 +1818,7 @@ precomputedVerdict, extraEvidence) {
1617
1818
  * 措辞,A4)。投递与幂等标记由 `onSubtaskDone` 处理器负责:先写通知、
1618
1819
  * 写成功才记 report.state='sent',绝不留无证据的已回报。
1619
1820
  */
1620
- if (verdict.status === 'done' && options.notifyCompletion === true
1821
+ if (effectiveStatus === 'done' && options.notifyCompletion === true
1621
1822
  && typeof options.onSubtaskDone === 'function') {
1622
1823
  try {
1623
1824
  options.onSubtaskDone(record, subtask, verdict);
@@ -1629,7 +1830,7 @@ precomputedVerdict, extraEvidence) {
1629
1830
  */
1630
1831
  }
1631
1832
  }
1632
- return { ...verdict, escalated };
1833
+ return { ...verdict, status: effectiveStatus, escalated, ...(criterionResultValue ? { criterionResult: criterionResultValue } : {}) };
1633
1834
  }
1634
1835
  /**
1635
1836
  * Retry policy for one child attempt.
@@ -1657,7 +1858,8 @@ export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
1657
1858
  * 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
1658
1859
  *
1659
1860
  * [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
1660
- * 出厂配置是 ceiling=900s / idle=300s / round=1200s,撞上限后剩下约
1861
+ * 现行默认是 ceiling=CHILD_TIMEOUT_MS(900s) / idle=CHILD_IDLE_TIMEOUT_MS
1862
+ * (300s) / round=TOTAL_TIMEOUT_MS(0=不设整轮硬预算),撞上限后剩下约
1661
1863
  * 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
1662
1864
  * 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
1663
1865
  * 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
@@ -1733,6 +1935,25 @@ export function announceSubtaskInterrupt(record, session, subtaskId, text) {
1733
1935
  row.interruptNoticeCount = sent + 1;
1734
1936
  return true;
1735
1937
  }
1938
+ /*
1939
+ * [2.5.5][T6] 活体 agent 解析兜底:工具路径(exec.agent)与自动派发路径
1940
+ * (payload.agent)都可能因宿主契约差异拿不到 agent,旧实现把 undefined 直传
1941
+ * 宿主 startActivation,在 spec.parent.id 处毫秒级抛 TypeError(session-1513
1942
+ * 与当前会话实测,childId=null)。这里用宿主同款安全访问器按 session.id 解析;
1943
+ * 解析不到由调用方 fail-closed,绝不裸抛 TypeError。
1944
+ */
1945
+ function resolveLiveAgent(ctx, sessionId) {
1946
+ const id = typeof sessionId === 'string' && sessionId.trim() !== '' ? sessionId.trim() : '';
1947
+ if (!id)
1948
+ return null;
1949
+ try {
1950
+ const agentsService = typeof ctx?.get === 'function' ? ctx.get('agents') : ctx?.agents;
1951
+ return agentsService?.get?.(id) ?? null;
1952
+ }
1953
+ catch {
1954
+ return null;
1955
+ }
1956
+ }
1736
1957
  async function executeSubtask(ctx, record, stage, subtask, options) {
1737
1958
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
1738
1959
  /*
@@ -1886,6 +2107,9 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1886
2107
  * task's dependents); `interruptedEvidence` is what gets written into the
1887
2108
  * blocked status so the main Agent can re-adjudicate on facts.
1888
2109
  */
2110
+ // [2.5.0][自配档] phase-0→phase-1 接续状态(本次尝试链内)。
2111
+ let phaseZeroCompleted = false;
2112
+ let phaseZeroOutput = '';
1889
2113
  let interruptedFlag = false;
1890
2114
  let interruptedEvidence = null;
1891
2115
  try {
@@ -1952,10 +2176,24 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1952
2176
  * 在请求前抛 UNSUPPORTED_REASONING_EFFORT——派发期即中断。查询不可用
1953
2177
  * 时保持旧行为;查询成功后钳制到等效档,空清单则不发送该字段。
1954
2178
  */
1955
- const requestedChildEffort = typeof subtask.reasoningEffort === 'string'
1956
- && REASONING_EFFORTS.includes(subtask.reasoningEffort)
1957
- ? subtask.reasoningEffort
1958
- : DEFAULT_REASONING_EFFORT;
2179
+ /*
2180
+ * [2.5.0] 用户要求 2「全程应用」的执行点:每次激活(首发/重试/续跑)
2181
+ * 都经 resolveTaskEffort 单一判据读档——负责人通过 delegate review
2182
+ * 配置的整体等级(状态行 effortOverride,durable 回放不丢)优先于
2183
+ * 规划器写死的 subtask.reasoningEffort;两者缺失才回落默认档。
2184
+ */
2185
+ const effortRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2186
+ /*
2187
+ * [2.5.0][自配档] 先配置后开工(平台强制):未登记自配整体档 ⇒ phase-0
2188
+ * 以 low 启动(唯一职责=评估复杂度+经 review 提交自配);已登记(含
2189
+ * 重试/续跑/回放读回)⇒ phase-1 经 resolveTaskEffort 单一判据全程用自配档。
2190
+ */
2191
+ const selfEffortConfigured = typeof effortRow?.effortOverride === 'string' && effortRow.effortOverride.length > 0;
2192
+ const phaseZeroActivation = !phaseZeroCompleted && !selfEffortConfigured;
2193
+ const requestedChildEffort = phaseZeroActivation ? 'low' : resolveTaskEffort({
2194
+ override: effortRow?.effortOverride,
2195
+ planned: subtask.reasoningEffort,
2196
+ });
1959
2197
  /*
1960
2198
  * [2.3.9][T3/llm-rules] 用户强制要求 1/2 的执行点:派发前对每个子任务的
1961
2199
  * reasoningEffort 做模型家族等级集合校验。越界档不中断派发(A3 修正轨),
@@ -1993,100 +2231,118 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
1993
2231
  const childEffort = childEffortSupport === null
1994
2232
  ? staticRuleChildEffort
1995
2233
  : (clampEffortToSupported(staticRuleChildEffort, childEffortSupport) ?? '');
2234
+ /*
2235
+ * [2.5.5][治本] 宿主 SubagentActivationSpec 契约:prompt/parent/cwd/
2236
+ * agentOptions/maxDepth 必须在 spec **顶层**(dsh-subagent types.d.ts
2237
+ * SubagentStartRequest)。旧实现把它们嵌套在 request:{} 里(旧宿主形状),
2238
+ * 现宿主读 spec.parent 得 undefined → 派发期即抛
2239
+ * 「Cannot read properties of undefined (reading 'id')」,全部子任务
2240
+ * 级联受阻(本会话重启后 0/6 现场)。单点拍平,两处 spawn 同口径。
2241
+ */
2242
+ // [2.5.5][T6] agent 兜底 + fail-closed(见 resolveLiveAgent 注释)。
2243
+ const liveAgent = options.agent ?? resolveLiveAgent(ctx, options.session?.id ?? record?.plan?.sessionId);
2244
+ if (!liveAgent) {
2245
+ throw new PlanError('派发失败:无法解析活体父 Agent(agent 缺失且 agents 服务兜底失败),fail-closed 不创建子会话', 'AGENT_RESOLUTION_FAILED', { subtaskId: subtask.id });
2246
+ }
1996
2247
  activation = await ctx.subagents.startActivation({
1997
2248
  provider: 'spawn',
1998
2249
  label: `${subtask.department}:${subtask.id} ${subtask.title}`.slice(0, 120),
1999
- request: {
2000
- prompt: [{
2001
- type: 'text',
2002
- text: buildChildPrompt({
2003
- plan: record.plan,
2004
- subtask,
2005
- stage,
2006
- dependencyResults: record.statuses
2007
- .filter((item) => subtask.dependsOn.includes(item.subtaskId))
2008
- .map((item) => ({
2009
- id: item.subtaskId,
2010
- title: item.title,
2011
- status: item.status,
2012
- summary: item.summary,
2013
- /*
2014
- * [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
2015
- *
2016
- * 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
2017
- * 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
2018
- * 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
2019
- */
2020
- artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
2021
- .filter((artifact) => artifact?.exists === true && typeof artifact?.ref === 'string')
2022
- .map((artifact) => String(artifact.ref)),
2023
- })),
2024
- cwd: options.cwd,
2025
- conversationContext,
2026
- statuses: record.statuses,
2250
+ prompt: [{
2251
+ type: 'text',
2252
+ text: phaseZeroActivation ? buildPhaseZeroLeaderPrompt({
2253
+ subtaskId: subtask.id,
2254
+ title: subtask.title,
2255
+ objective: subtask.objective,
2256
+ departmentLabel: DEPARTMENTS[subtask.department]?.zh ?? String(subtask.department ?? '部门'),
2257
+ }) : buildChildPrompt({
2258
+ plan: record.plan,
2259
+ subtask,
2260
+ stage,
2261
+ dependencyResults: record.statuses
2262
+ .filter((item) => subtask.dependsOn.includes(item.subtaskId))
2263
+ .map((item) => ({
2264
+ id: item.subtaskId,
2265
+ title: item.title,
2266
+ status: item.status,
2267
+ summary: item.summary,
2027
2268
  /*
2028
- * [2.2.0][T3/O-2a] 子→主预告通道的目标(真实父会话 id)。
2269
+ * [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
2029
2270
  *
2030
- * 宿主只在非 caller 投递时注入父会话 id,本插件用 caller 投递,
2031
- * 所以这里必须自己给值;空值走「禁止猜测」分支,绝不编造 id。
2032
- */
2033
- leadAgentId: noticeLead.id,
2034
- leadAgentIdSource: noticeLead.source,
2035
- /*
2036
- * [2.1.0] 不再用 attempt>1 做门槛:被格式退回的行复位后第 1 次
2037
- * 激活也必须带上退回通知,否则「退回」只是写了一行状态。
2038
- */
2039
- previousFailure: lastFailure ?? null,
2040
- lessonsBrief,
2041
- /*
2042
- * [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 的
2043
- * **全部内容**告知相关部门。注入文本由 llm-rules.ts 的
2044
- * buildLlmRulesBrief 单一事实源生成(tier='department'):
2045
- * 要求 1/2 原文 + 本会话模型与家族判定 + 本子任务已配置/钳制后
2046
- * 的推理等级 + 部门负责人「先全面梳理、再用 dsh_workplan_delegate
2047
- * 分配给顶尖专家与组员」的强制流程告知。
2271
+ * 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
2272
+ * 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
2273
+ * 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
2048
2274
  */
2049
- llmRulesBrief: buildLlmRulesBrief({
2050
- model: modelSelection?.model ?? null,
2051
- effort: staticRuleChildEffort || null,
2052
- requested: childStaticCorrection ? requestedChildEffort : null,
2053
- correctionReason: childStaticCorrection?.reason ?? null,
2054
- tier: 'department',
2055
- }),
2275
+ artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
2276
+ .filter((artifact) => artifact?.exists === true && typeof artifact?.ref === 'string')
2277
+ .map((artifact) => String(artifact.ref)),
2278
+ })),
2279
+ cwd: options.cwd,
2280
+ conversationContext,
2281
+ statuses: record.statuses,
2282
+ /*
2283
+ * [2.2.0][T3/O-2a] 子→主预告通道的目标(真实父会话 id)。
2284
+ *
2285
+ * 宿主只在非 caller 投递时注入父会话 id,本插件用 caller 投递,
2286
+ * 所以这里必须自己给值;空值走「禁止猜测」分支,绝不编造 id。
2287
+ */
2288
+ leadAgentId: noticeLead.id,
2289
+ leadAgentIdSource: noticeLead.source,
2290
+ /*
2291
+ * [2.1.0] 不再用 attempt>1 做门槛:被格式退回的行复位后第 1 次
2292
+ * 激活也必须带上退回通知,否则「退回」只是写了一行状态。
2293
+ */
2294
+ previousFailure: lastFailure ?? null,
2295
+ lessonsBrief,
2296
+ /*
2297
+ * [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 的
2298
+ * **全部内容**告知相关部门。注入文本由 llm-rules.ts 的
2299
+ * buildLlmRulesBrief 单一事实源生成(tier='department'):
2300
+ * 要求 1/2 原文 + 本会话模型与家族判定 + 本子任务已配置/钳制后
2301
+ * 的推理等级 + 部门负责人「先全面梳理、再用 dsh_workplan_delegate
2302
+ * 分配给顶尖专家与组员」的强制流程告知。
2303
+ */
2304
+ phaseZeroContinuation: phaseZeroCompleted ? buildPhaseZeroContinuationHint(String(effortRow?.effortOverride ?? ''), phaseZeroOutput, effortRow?.effortOverride === 'low' && (effortRow?.consolidation?.assignments ?? []).length === 0) : '',
2305
+ llmRulesBrief: buildLlmRulesBrief({
2306
+ model: modelSelection?.model ?? null,
2307
+ effort: staticRuleChildEffort || null,
2308
+ requested: childStaticCorrection ? requestedChildEffort : null,
2309
+ correctionReason: childStaticCorrection?.reason ?? null,
2310
+ tier: 'department',
2311
+ taskEffort: typeof effortRow?.effortOverride === 'string' ? effortRow.effortOverride : null,
2056
2312
  }),
2057
- }],
2058
- parent: options.agent,
2059
- cwd: typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined,
2060
- /*
2061
- * [2.2.0][T13/推理等级] 子 Agent 不得继承主 Agent 的推理等级。
2062
- *
2063
- * 用户规则原文:「禁止子agent继承主agent的推理等级,子agent必须根据
2064
- * 自身任务的复杂度,自己使用推理等级为low、high或者是Max,其中,轻度
2065
- * 复杂的任务使用low,中等复杂的任务使用high,非常复杂的任务使用Max。」
2066
- * 宿主 resolveChildAgentOptions 在请求未点名 reasoningEffort 时会继承
2067
- * 父 Agent 的等级(dsh-subagent child-agent.d.ts:40-50),旧实现在这里
2068
- * 只传 provider/model,于是主 Agent 的等级被原样带进每个部门子会话。
2069
- * 现在显式覆盖为子任务自己的档位;缺失(旧计划/回放)回落 high,绝不
2070
- * 读取 modelSelection.reasoningEffort。
2071
- */
2072
- agentOptions: {
2073
- ...(modelSelection?.provider && modelSelection?.model
2074
- ? { provider: modelSelection.provider, model: modelSelection.model }
2075
- : {}),
2076
- // [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
2077
- ...(childEffort ? { reasoningEffort: childEffort } : {}),
2078
- },
2079
- /*
2080
- * [2.3.9][T4b] 三层派发深度(用户强制要求 4/5):主 Agent(0) →
2081
- * 部门负责人子会话(1) → 顶尖专家/组员子会话(2)。maxDepth 是宿主
2082
- * resolveChildDepth 的**绝对深度上限**(child-agent.d.ts:24-29),
2083
- * 部门层放行到 2 才能让负责人经 dsh_workplan_delegate 派生第三层;
2084
- * 第三层成员派生时同样传 2 ⇒ 任何第四层(深度 3)被宿主抛
2085
- * SubagentDepthError 硬拒,delegateTool 服务端另有一道「只有部门
2086
- * 负责人行可调用」的校验——提示词说服模型,代码守住边界。
2087
- */
2088
- maxDepth: 2,
2313
+ }),
2314
+ }],
2315
+ parent: liveAgent,
2316
+ cwd: typeof options.cwd === 'string' && options.cwd ? options.cwd : undefined,
2317
+ /*
2318
+ * [2.2.0][T13/推理等级] 子 Agent 不得继承主 Agent 的推理等级。
2319
+ *
2320
+ * 用户规则原文:「禁止子agent继承主agent的推理等级,子agent必须根据
2321
+ * 自身任务的复杂度,自己使用推理等级为low、high或者是Max,其中,轻度
2322
+ * 复杂的任务使用low,中等复杂的任务使用high,非常复杂的任务使用Max。」
2323
+ * 宿主 resolveChildAgentOptions 在请求未点名 reasoningEffort 时会继承
2324
+ * 父 Agent 的等级(dsh-subagent child-agent.d.ts:40-50),旧实现在这里
2325
+ * 只传 provider/model,于是主 Agent 的等级被原样带进每个部门子会话。
2326
+ * 现在显式覆盖为子任务自己的档位;缺失(旧计划/回放)回落 high,绝不
2327
+ * 读取 modelSelection.reasoningEffort。
2328
+ */
2329
+ agentOptions: {
2330
+ ...(modelSelection?.provider && modelSelection?.model
2331
+ ? { provider: modelSelection.provider, model: modelSelection.model }
2332
+ : {}),
2333
+ // [2.2.7] '' = 模型无 reasoning 元数据 ⇒ 不发送,避免派发期即中断。
2334
+ ...(childEffort ? { reasoningEffort: childEffort } : {}),
2089
2335
  },
2336
+ /*
2337
+ * [2.3.9][T4b] 三层派发深度(用户强制要求 4/5):主 Agent(0) →
2338
+ * 部门负责人子会话(1) → 顶尖专家/组员子会话(2)。maxDepth 是宿主
2339
+ * resolveChildDepth 的**绝对深度上限**(child-agent.d.ts:24-29),
2340
+ * 部门层放行到 2 才能让负责人经 dsh_workplan_delegate 派生第三层;
2341
+ * 第三层成员派生时同样传 2 ⇒ 任何第四层(深度 3)被宿主抛
2342
+ * SubagentDepthError 硬拒,delegateTool 服务端另有一道「只有部门
2343
+ * 负责人行可调用」的校验——提示词说服模型,代码守住边界。
2344
+ */
2345
+ maxDepth: 2,
2090
2346
  signal: child.controller.signal,
2091
2347
  delivery: 'caller',
2092
2348
  });
@@ -2307,6 +2563,22 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2307
2563
  }
2308
2564
  if (guard.timedOut)
2309
2565
  return;
2566
+ /*
2567
+ * [2.5.0][自配档] phase-0 结算分支:已登记自配 ⇒ 平台立即以自配档接续
2568
+ * phase-1(不计失败、不耗重试预算);未登记 ⇒ 明确 SELF_EFFORT_MISSING
2569
+ * 回喂(有界重试),禁止静默以 low 档继续正式任务。
2570
+ */
2571
+ if (phaseZeroActivation) {
2572
+ const configuredRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2573
+ const configured = typeof configuredRow?.effortOverride === 'string' && configuredRow.effortOverride.length > 0;
2574
+ if (configured) {
2575
+ phaseZeroCompleted = true;
2576
+ phaseZeroOutput = resultText(result);
2577
+ attempt -= 1; // phase-0→phase-1 是接续不是重试:不消耗 attempt 预算
2578
+ continue;
2579
+ }
2580
+ throw new PlanError('phase-0 结束但未提交自配推理等级:先配置后开工是平台硬规则——请评估任务复杂度并经 dsh_workplan_delegate(action="review") 配置 consolidation.taskReasoningEffort,平台将以自配档接续;low(轻度)任务请改经 action="direct" 登记两轮思考产物(负责人亲自执行,禁止下派)', 'SELF_EFFORT_MISSING', { subtaskId: subtask.id });
2581
+ }
2310
2582
  const output = resultText(result);
2311
2583
  if (result.stopReason !== 'completed') {
2312
2584
  /*
@@ -2386,19 +2658,76 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
2386
2658
  const settleBackup = join(options.cwd ?? process.cwd(), 'reports', `wp-settlement-${subtask.id}.json`);
2387
2659
  let backupVerdict = null;
2388
2660
  let backupText = '';
2661
+ /*
2662
+ * [2.5.2][T4b][D2] 备份采纳前的新鲜度+归属闸。根因
2663
+ * (reports/D1-D2-root-cause-diagnosis.md §2):固定文件名跨计划跨会话
2664
+ * 复用,旧实现读到合法 JSON 即采纳、不做任何校验——本次误采纳 T1 的
2665
+ * 陈旧截图任务结算(假完成)与 T2 的陈旧基金基线结算(误 blocked),
2666
+ * 级联冻结 T3/T4/T5。现在:
2667
+ * ① 新鲜度:备份 mtime 必须 >= 本次尝试 startedAt(只认本次尝试内
2668
+ * 新写的备份;提示词同步要求覆盖旧文件)。
2669
+ * ② 归属:备份 JSON 顶层含 planId/subtaskId 则必须与本计划/本子任务
2670
+ * 一致(裸 JSON 或标记块内 JSON 两个入口都查;无这些字段的旧格式
2671
+ * 备份仍受新鲜度闸约束,adjudicateResult 对额外顶层字段容忍)。
2672
+ * ③ 任一不满足 ⇒ 不采纳,写 record.errors 审计行(含文件 mtime 与
2673
+ * startedAt),落回下方既有 EVIDENCE_MISSING 有界回喂路径。
2674
+ * 结算严格性不变:缺失永不计 done。
2675
+ */
2676
+ let backupRejectReason = '';
2677
+ let backupMtimeMs = null;
2678
+ const backupAttemptStartedAt = Number(attemptRow()?.startedAt ?? 0);
2389
2679
  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 ?? '')))
2397
- backupVerdict = null;
2680
+ const backupStat = statSync(settleBackup);
2681
+ backupMtimeMs = backupStat.mtimeMs;
2682
+ if (backupStat.mtimeMs < backupAttemptStartedAt) {
2683
+ backupRejectReason = '陈旧备份(mtime 早于本次尝试 startedAt,非本次执行新写)';
2684
+ }
2685
+ else {
2686
+ backupText = readFileSync(settleBackup, 'utf8');
2687
+ let backupMeta = null;
2688
+ try {
2689
+ backupMeta = JSON.parse(backupText);
2690
+ }
2691
+ catch {
2692
+ const beginAt = backupText.lastIndexOf(EVIDENCE_MARKER_BEGIN);
2693
+ const endAt = backupText.indexOf(EVIDENCE_MARKER_END, beginAt + EVIDENCE_MARKER_BEGIN.length);
2694
+ if (beginAt >= 0 && endAt > beginAt) {
2695
+ try {
2696
+ backupMeta = JSON.parse(backupText.slice(beginAt + EVIDENCE_MARKER_BEGIN.length, endAt).trim());
2697
+ }
2698
+ catch {
2699
+ backupMeta = null;
2700
+ }
2701
+ }
2702
+ }
2703
+ const metaPlanId = typeof backupMeta?.planId === 'string' && backupMeta.planId ? backupMeta.planId : null;
2704
+ const metaSubtaskId = typeof backupMeta?.subtaskId === 'string' && backupMeta.subtaskId ? backupMeta.subtaskId : null;
2705
+ if (metaPlanId && metaPlanId !== record.plan.planId) {
2706
+ backupRejectReason = `归属不匹配(备份 planId=${metaPlanId} ≠ 本计划 ${record.plan.planId})`;
2707
+ }
2708
+ else if (metaSubtaskId && metaSubtaskId !== subtask.id) {
2709
+ backupRejectReason = `归属不匹配(备份 subtaskId=${metaSubtaskId} ≠ 本子任务 ${subtask.id})`;
2710
+ }
2711
+ else {
2712
+ backupVerdict = adjudicateResult({
2713
+ output: backupText,
2714
+ strict: true,
2715
+ expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
2716
+ });
2717
+ if (!backupVerdict || /结果块缺失|无法解析/.test(String(backupVerdict.error ?? '')))
2718
+ backupVerdict = null;
2719
+ }
2720
+ }
2398
2721
  }
2399
2722
  catch {
2400
2723
  backupVerdict = null;
2401
2724
  }
2725
+ if (backupRejectReason) {
2726
+ record.errors = [
2727
+ ...(record.errors ?? []),
2728
+ `${subtask.id}: 拒绝采纳盘上结算备份 ${settleBackup}——${backupRejectReason}(文件 mtime=${backupMtimeMs === null ? '未知' : new Date(backupMtimeMs).toISOString()},本次尝试 startedAt=${new Date(backupAttemptStartedAt).toISOString()};[2.5.2][T4b][D2] 新鲜度/归属闸),落回 EVIDENCE_MISSING 回喂`,
2729
+ ].slice(-20);
2730
+ }
2402
2731
  if (backupVerdict) {
2403
2732
  settleFromOutput(record, subtask, backupText, guard, options, backupVerdict, probeInterruptedEvidence(backupText, subtask, options.cwd, options.artifactExists));
2404
2733
  record.errors = [
@@ -2727,6 +3056,72 @@ export function mergePreservedArtifacts(artifacts, preservedRefs) {
2727
3056
  }
2728
3057
  return list.slice(-40);
2729
3058
  }
3059
+ /**
3060
+ * [2.5.0][R4] 第三层叶子「已完成产物在盘」探测:delegate 下级重派(重试/续跑)
3061
+ * 前先核盘它上次按任务书约定写下的结算备份(buildDelegateePrompt:
3062
+ * reports/wp-member-<成员名>-<任务代号>.json),随重试任务书附给新叶子。
3063
+ * 只读目录、不改任何判定;目录不存在/读取失败返回空清单(绝不编造产物)。
3064
+ * listDir 可注入,纯逻辑可脱离真实文件系统回归。
3065
+ */
3066
+ export function probeDelegateLandedArtifacts(cwd, member, listDir = readdirSync) {
3067
+ const name = String(member ?? '').trim();
3068
+ if (!name || typeof cwd !== 'string' || !cwd)
3069
+ return [];
3070
+ const prefix = `wp-member-${name}-`;
3071
+ let entries = [];
3072
+ try {
3073
+ entries = listDir(join(cwd, 'reports'));
3074
+ }
3075
+ catch {
3076
+ return [];
3077
+ }
3078
+ return (Array.isArray(entries) ? entries : [])
3079
+ .map((entry) => String(entry ?? ''))
3080
+ .filter((file) => file.startsWith(prefix) && file.endsWith('.json'))
3081
+ .slice(0, 6)
3082
+ .map((file) => `reports/${file}`);
3083
+ }
3084
+ /**
3085
+ * [2.5.0][R4] 第三层叶子重试/续跑简报(根因修复):旧实现 delegate 重派时给
3086
+ * 叶子一张全新任务书——上一次尝试的状态、失败原因、已回报结论与在盘产物
3087
+ * 全部丢失,叶子只能整步重跑(违反用户要求 4「禁止丢弃已完成部分」,与
3088
+ * 第二层 buildTakeoverBrief/结果块回喂同一语义在第三层的落点)。现在重派
3089
+ * 时把本简报经 buildDelegateePrompt.extraContext 附进任务书:上次尝试状态/
3090
+ * 错误/摘要 + 已核实在盘产物清单 + 负责人梳理思路 + 「请勿重做已完成的工作」
3091
+ * 硬约束。纯函数,可脱离宿主回归。prior 为空(首发)返回 ''。
3092
+ */
3093
+ export function buildDelegateRetryBrief(prior, landedRefs, approach) {
3094
+ if (!prior || typeof prior !== 'object')
3095
+ return '';
3096
+ const refs = (Array.isArray(landedRefs) ? landedRefs : [])
3097
+ .map((item) => String(item ?? '').trim())
3098
+ .filter(Boolean)
3099
+ .slice(0, 6);
3100
+ const status = String(prior.status ?? '');
3101
+ const lines = [
3102
+ `【重试/续跑简报——禁止丢弃已完成部分】这不是你的首次尝试:上一次尝试的状态为 ${status || '未知'}。`,
3103
+ ];
3104
+ if (typeof prior.error === 'string' && prior.error.trim()) {
3105
+ lines.push(`- 上次失败原因:${truncate(prior.error.trim(), 300)}`);
3106
+ }
3107
+ if (typeof prior.summary === 'string' && prior.summary.trim()) {
3108
+ lines.push(`- 上次已回报的结论(含已完成工作):${truncate(prior.summary.trim(), 300)}`);
3109
+ }
3110
+ if (refs.length > 0) {
3111
+ lines.push(`- 已核实在盘的已完成产物:${refs.join('、')}`);
3112
+ }
3113
+ const approachLines = (Array.isArray(approach) ? approach : [])
3114
+ .map((item) => String(item ?? '').trim())
3115
+ .filter(Boolean)
3116
+ .slice(0, 6);
3117
+ if (approachLines.length > 0) {
3118
+ lines.push(`- 部门负责人的梳理思路(供参考):${approachLines.join(';')}`);
3119
+ }
3120
+ lines.push(status === 'done'
3121
+ ? '- 硬约束:上次尝试已完成——先核对上述产物与结论,只补缺口;请勿重做已完成的工作,禁止删除或覆盖既有产物。'
3122
+ : '- 硬约束:请勿重做已完成的工作——以上述在盘产物与结论为基础,只继续补齐未完成部分;禁止删除或覆盖既有产物、禁止整步重跑。');
3123
+ return lines.join('\n');
3124
+ }
2730
3125
  /**
2731
3126
  * [2.3.0][T1] 放宽成功后告知执行中的专家最新时限(A2 的「告知」半边)。
2732
3127
  * 走 ctx.subagents.sendMessage 与 follow-up 同一投递通道:运行中的子会话在下一
@@ -2750,7 +3145,7 @@ async function notifyExpertOfExtension(ctx, agent, record, subtaskId, deadlineAt
2750
3145
  + '你必须在保证工作质量的前提下高效率执行:优先推进高价值步骤,已完成内容及时落盘,'
2751
3146
  + '并在回报中明确区分「已完成 / 未完成」。收到本通知后请继续当前工作,不要重新开始。';
2752
3147
  try {
2753
- await service.sendMessage(agent, childId, [{ type: 'text', text }], {});
3148
+ await service.sendMessage(agent, childId, [{ type: 'text', text }], { signal: new AbortController().signal }); // [T11] 缺陷②:延期告知携带有效 signal,消除 throwIfAborted
2754
3149
  if (row) {
2755
3150
  const journal = Array.isArray(row.timeJournal) ? row.timeJournal : [];
2756
3151
  journal.push({ at: Date.now(), action: 'notify-expert', deadlineAt: Number(deadlineAt), by: 'system' });
@@ -2840,8 +3235,8 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
2840
3235
  const preRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2841
3236
  const timeoutCountAtFire = Number(preRow?.timeoutCount ?? 0) + 1;
2842
3237
  const message = timeoutCountAtFire >= TAKEOVER_AFTER_TIMEOUTS
2843
- ? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑)`
2844
- : `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 立即放宽(extendMs,放宽后插件自动告知专家最新时限与保证质量高效率要求)/ 重试 / 接受,或转新轮续跑、人工裁决)`;
3238
+ ? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑;接手仅发生在已批准延期的场景)`
3239
+ : `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按运行层安全兜底结算(待裁决:判据层 10 分钟完成目标未达成且无用户批准 → 判未完成,优先 replan(replace) 转新子任务只补缺口;或经用户批准并留痕后 extendMs 放宽;或重试 / 接受、转新轮续跑、人工裁决)`;
2845
3240
  try {
2846
3241
  // [1.8.19] Keep the evidence of what already landed on disk.
2847
3242
  const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
@@ -2874,6 +3269,50 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
2874
3269
  const settleRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2875
3270
  if (settleRow)
2876
3271
  settleRow.pendingAdjudication = true;
3272
+ /*
3273
+ * [SCv2-T4][Q1-B/Q3-B/Q6-A] 到点结算的判据层判定(仅生效计划):
3274
+ * 运行层兜底已完成(blocked+产物抢救照旧),这里追加判据结果与违规
3275
+ * 审计;unmet 时把「判未完成→replan(replace) 接替」写进 error/summary,
3276
+ * 与 C15 文案同向。pendingAdjudication 事实标记保留(C16 不改)。
3277
+ */
3278
+ if (settleRow && criterionV2Active(record.plan?.createdAt)) {
3279
+ try {
3280
+ let leaderForCriterion = null;
3281
+ try {
3282
+ leaderForCriterion = deriveLeaderEstimate(settleRow);
3283
+ }
3284
+ catch {
3285
+ leaderForCriterion = null;
3286
+ }
3287
+ const exAnte = criterionExAnte(settleRow, leaderForCriterion);
3288
+ const wallClockMs = attemptWallClockMsOf(settleRow);
3289
+ const evaluation = evaluateCriterion({
3290
+ exAnteMinutes: exAnte.minutes,
3291
+ exAnteComplete: exAnte.complete,
3292
+ wallClockMs,
3293
+ exception: sanitizeCriterionException(settleRow.criterionException),
3294
+ settledAt: Date.now(),
3295
+ });
3296
+ settleRow.criterionResult = evaluation.criterionResult;
3297
+ if (evaluation.criterionResult === 'unmet') {
3298
+ settleRow.criterionViolations = appendCriterionViolation(settleRow.criterionViolations, {
3299
+ at: Date.now(),
3300
+ attempt: timeoutCountAtFire,
3301
+ wallClockMs,
3302
+ exAnteMinutes: exAnte.minutes,
3303
+ reasons: evaluation.reasons,
3304
+ });
3305
+ const criterionNote = `判据违规(criterion-overrun):${evaluation.reasons.join(';')}。`
3306
+ + '未获用户批准不得以 done 收尾(Q1-B);已完成产物只读保留,优先 replan(replace) 转接替子任务只补缺口,'
3307
+ + '或先向用户申请例外批准并留痕(criterionApproval)后放宽。';
3308
+ settleRow.error = truncate(`${settleRow.error ?? ''};${criterionNote}`, 3000);
3309
+ settleRow.summary = truncate(`未完成:${criterionNote}`, 3000);
3310
+ }
3311
+ }
3312
+ catch (error) {
3313
+ record.errors = [...(record.errors ?? []), `${subtask.id}: 判据层判定写入失败:${truncate(String(error?.message ?? error), 300)}`].slice(-20);
3314
+ }
3315
+ }
2877
3316
  /*
2878
3317
  * [2.3.0][T1] 超时计数与二次超时接手(用户要求 1/2 的机读落点):
2879
3318
  * 每次到点收束给状态行 timeoutCount +1 并记入 timeJournal(action:'timeout')。
@@ -2901,8 +3340,12 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
2901
3340
  ? `子任务 ${subtask.id} 已第 ${timeoutCount} 次达到协商时限(二次超时):按 2.3.0 机制本行已置「主 Agent 接手」(takeoverRequired)。`
2902
3341
  + `专家已完成并登记保护的部分(只读、禁止丢弃):${ceilingLanded.slice(0, 8).join('、') || '(见 takeoverBrief)'};`
2903
3342
  + '请主 Agent 直接接手继续未完成部分,不要整步重跑、不要删除或覆盖已登记产物。'
2904
- : `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
2905
- + '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。';
3343
+ : (criterionV2Active(record.plan?.createdAt)
3344
+ ? `子任务 ${subtask.id} 第 1 次达到协商时限:按用户 2026-11-13 裁决 Q1-B,第一次超时不再自动放宽——请先向用户申请例外批准并留痕`
3345
+ + '(任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=未批准),批准后才可用 dsh_workplan_update(extendMs, criterionApproval) 放宽;'
3346
+ + '未获批准不得放宽,按判据层未达标处理(不 done、replan(replace) 转接替子任务只补缺口,已完成产物只读保护)。'
3347
+ : `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
3348
+ + '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。');
2906
3349
  announceSubtaskInterrupt(record, options.session ?? options.agent?.session, subtask.id, takeoverText);
2907
3350
  }
2908
3351
  catch {
@@ -3089,92 +3532,130 @@ async function runWithConcurrency(items, limit, worker) {
3089
3532
  */
3090
3533
  export function modelStatusLines(statuses) {
3091
3534
  const list = Array.isArray(statuses) ? statuses : [];
3092
- return list.map((item) => ({
3093
- subtaskId: item.subtaskId,
3094
- title: item.title,
3095
- department: item.department,
3096
- status: item.status,
3097
- progress: item.progress,
3098
- summary: truncate(item.summary ?? item.error ?? '', 2000),
3099
- error: item.error ?? null,
3100
- verification: item.verification ?? null,
3101
- // [1.8.13] The model must see *which* acceptance item failed, not just the
3102
- // verdict; it cannot repair a gap it cannot name.
3103
- acceptance: Array.isArray(item.acceptance)
3104
- ? item.acceptance.slice(0, 8).map((entry) => ({
3105
- criterion: truncate(String(entry?.criterion ?? ''), 200),
3106
- result: String(entry?.result ?? ''),
3107
- evidence: truncate(String(entry?.evidence ?? ''), 300),
3108
- }))
3109
- : [],
3110
- revision: Number(item.revision ?? 0),
3111
- updatedBy: item.updatedBy ?? null,
3112
- missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
3113
- needs: Array.isArray(item.needs) ? item.needs : [],
3114
- // [1.11.0] 闭环阶段必须进入模型可读面:只暴露四值 status 时,
3115
- // 「在等指示」和「做失败了」在工具输出里长得一模一样。
3116
- closure: item.closure ?? null,
3117
- blockedKind: item.blockedKind ?? null,
3118
- question: item.question ?? null,
3119
- options: Array.isArray(item.options) ? item.options : [],
3120
- ackOverdue: item.ackOverdue === true,
3121
- escalatedAt: item.escalatedAt ?? null,
3122
- instruction: item.instruction?.text ? truncate(item.instruction.text, 500) : null,
3123
- /*
3124
- * [1.11.0] 跨部门需求的待处理项必须出现在模型可读面(用户 m00687)。
3125
- *
3126
- * 只放在结果消息里时,主 Agent 一旦错过那一轮就再也看不到「还有一条
3127
- * 需求没处置」,而交付门禁却一直拦着。status 工具是与进度同源的读取口,
3128
- * 这里只暴露未处置项,避免把已答复的历史反复塞进上下文。
3129
- */
3130
- openHandoffs: openHandoffs(item).map((handoff) => ({
3131
- id: handoff.id,
3132
- request: truncate(String(handoff.request ?? ''), 300),
3133
- department: handoff.department ?? null,
3134
- status: handoff.status,
3135
- })),
3136
- reportedAt: item.reportedAt ?? null,
3137
- /*
3138
- * [2.2.0][T4/O-3b][O-2.4] 柔性时长协商字段进入模型可读面(纯展示):
3139
- * 协商截止 deadlineAt、尝试起点 startedAt、剩余协商时间、预警标记 timeWarning、
3140
- * 待裁决标记 pendingAdjudication 与时间链审计 timeJournal。验收合同
3141
- * tests/time-estimate-negotiation.test.ts C3 直接从 statusTool 输出读
3142
- * deadlineAt/startedAt(字段名/单位照合同原文)。
3143
- */
3144
- startedAt: item.startedAt ?? null,
3145
- deadlineAt: item.deadlineAt ?? null,
3146
- deadlineRemainingMs: Number.isFinite(Number(item.deadlineAt))
3147
- ? Math.max(0, Number(item.deadlineAt) - Date.now())
3148
- : null,
3149
- timeWarning: item.timeWarning ?? null,
3150
- timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
3151
- pendingAdjudication: item.pendingAdjudication === true,
3152
- // [2.3.0][T1] 预估上报(A1)也要进模型可读面:主 Agent 告知用户前先读这里。
3153
- timeNotice: item.timeNotice ?? null,
3154
- /*
3155
- * [2.3.0][T1] 超时计数 / 二次超时接手进入模型可读面:主 Agent 一眼能看出
3156
- * 该行第几次超时、是否必须接手、接手包里哪些是只读保护的已完成产物。
3157
- */
3158
- timeoutCount: Number(item.timeoutCount ?? 0),
3159
- takeoverRequired: item.takeoverRequired === true,
3160
- takeoverBrief: item.takeoverBrief ?? null,
3535
+ return list.map((item) => {
3161
3536
  /*
3162
- * [2.3.0][T1] 已完成产物的只读保护登记必须进模型可读面:statusTool 的行
3163
- * 来自本函数,此前不序列化 artifacts,导致 takeoverRequired 的「禁止丢弃
3164
- * 已完成部分」清单对主 Agent 不可见。只透出对象形条目,照录不改写。
3537
+ * [T7][lead-decisions J2/G2] 负责人时长聚合:与看板载荷(plan.ts
3538
+ * normaliseStatusEntry)挂同一读时派生纯函数,模型可读面不是第二套计算。
3539
+ * null=空 roster(无下属分工)/replanned 旧行/越界 fail-closed;
3540
+ * roster 非空且非 replanned 却为 null ⇒ 总和越界异常,显式标注拒绝展示(J8)。
3165
3541
  */
3166
- artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
3167
- .filter((entry) => entry && typeof entry === 'object' && typeof entry.ref === 'string')
3168
- .map((entry) => ({ ...entry })),
3169
- /*
3170
- * [2.2.0][T3/O-2a] 子→主预告通道的结论必须进入模型可读面。
3171
- *
3172
- * 这条能力的目标就是「可观测」:主 Agent 要能一眼看出该子任务的开工预告
3173
- * 有没有真的到达(observed/not-observed)、目标是谁、什么时候、失败原因。
3174
- * 只写状态行不让读,等于又是一个「看不见的失败」。
3175
- */
3176
- noticeChannel: item.noticeChannel ?? null,
3177
- }));
3542
+ const leaderEstimate = deriveLeaderEstimate(item);
3543
+ const leaderEstimateAnomaly = leaderEstimate === null
3544
+ && item?.closure !== 'replanned'
3545
+ && leaderEstimateRoster(item).length > 0
3546
+ ? '下属开工预估聚合异常(总和超出安全整数范围),拒绝展示数值;请核对 delegateEstimates 台账'
3547
+ : null;
3548
+ // [SCv2-T4][Q4-B/C22] 事前预估口径(有叶子=和;直做=负责人自身预估,D-2)。
3549
+ const exAnteView = criterionExAnte(item, leaderEstimate);
3550
+ return {
3551
+ subtaskId: item.subtaskId,
3552
+ title: item.title,
3553
+ department: item.department,
3554
+ status: item.status,
3555
+ progress: item.progress,
3556
+ summary: truncate(item.summary ?? item.error ?? '', 2000),
3557
+ error: item.error ?? null,
3558
+ verification: item.verification ?? null,
3559
+ // [1.8.13] The model must see *which* acceptance item failed, not just the
3560
+ // verdict; it cannot repair a gap it cannot name.
3561
+ acceptance: Array.isArray(item.acceptance)
3562
+ ? item.acceptance.slice(0, 8).map((entry) => ({
3563
+ criterion: truncate(String(entry?.criterion ?? ''), 200),
3564
+ result: String(entry?.result ?? ''),
3565
+ evidence: truncate(String(entry?.evidence ?? ''), 300),
3566
+ }))
3567
+ : [],
3568
+ revision: Number(item.revision ?? 0),
3569
+ updatedBy: item.updatedBy ?? null,
3570
+ missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
3571
+ needs: Array.isArray(item.needs) ? item.needs : [],
3572
+ // [1.11.0] 闭环阶段必须进入模型可读面:只暴露四值 status 时,
3573
+ // 「在等指示」和「做失败了」在工具输出里长得一模一样。
3574
+ closure: item.closure ?? null,
3575
+ blockedKind: item.blockedKind ?? null,
3576
+ question: item.question ?? null,
3577
+ options: Array.isArray(item.options) ? item.options : [],
3578
+ ackOverdue: item.ackOverdue === true,
3579
+ escalatedAt: item.escalatedAt ?? null,
3580
+ instruction: item.instruction?.text ? truncate(item.instruction.text, 500) : null,
3581
+ /*
3582
+ * [1.11.0] 跨部门需求的待处理项必须出现在模型可读面(用户 m00687)。
3583
+ *
3584
+ * 只放在结果消息里时,主 Agent 一旦错过那一轮就再也看不到「还有一条
3585
+ * 需求没处置」,而交付门禁却一直拦着。status 工具是与进度同源的读取口,
3586
+ * 这里只暴露未处置项,避免把已答复的历史反复塞进上下文。
3587
+ */
3588
+ openHandoffs: openHandoffs(item).map((handoff) => ({
3589
+ id: handoff.id,
3590
+ request: truncate(String(handoff.request ?? ''), 300),
3591
+ department: handoff.department ?? null,
3592
+ status: handoff.status,
3593
+ })),
3594
+ reportedAt: item.reportedAt ?? null,
3595
+ /*
3596
+ * [2.2.0][T4/O-3b][O-2.4] 柔性时长协商字段进入模型可读面(纯展示):
3597
+ * 协商截止 deadlineAt、尝试起点 startedAt、剩余协商时间、预警标记 timeWarning、
3598
+ * 待裁决标记 pendingAdjudication 与时间链审计 timeJournal。验收合同
3599
+ * tests/time-estimate-negotiation.test.ts C3 直接从 statusTool 输出读
3600
+ * deadlineAt/startedAt(字段名/单位照合同原文)。
3601
+ */
3602
+ startedAt: item.startedAt ?? null,
3603
+ deadlineAt: item.deadlineAt ?? null,
3604
+ deadlineRemainingMs: Number.isFinite(Number(item.deadlineAt))
3605
+ ? Math.max(0, Number(item.deadlineAt) - Date.now())
3606
+ : null,
3607
+ timeWarning: item.timeWarning ?? null,
3608
+ timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
3609
+ pendingAdjudication: item.pendingAdjudication === true,
3610
+ // [2.3.0][T1] 预估上报(A1)也要进模型可读面:主 Agent 告知用户前先读这里。
3611
+ timeNotice: item.timeNotice ?? null,
3612
+ /*
3613
+ * [2.3.0][T1] 超时计数 / 二次超时接手进入模型可读面:主 Agent 一眼能看出
3614
+ * 该行第几次超时、是否必须接手、接手包里哪些是只读保护的已完成产物。
3615
+ */
3616
+ timeoutCount: Number(item.timeoutCount ?? 0),
3617
+ takeoverRequired: item.takeoverRequired === true,
3618
+ takeoverBrief: item.takeoverBrief ?? null,
3619
+ /*
3620
+ * [2.3.0][T1] 已完成产物的只读保护登记必须进模型可读面:statusTool 的行
3621
+ * 来自本函数,此前不序列化 artifacts,导致 takeoverRequired 的「禁止丢弃
3622
+ * 已完成部分」清单对主 Agent 不可见。只透出对象形条目,照录不改写。
3623
+ */
3624
+ artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
3625
+ .filter((entry) => entry && typeof entry === 'object' && typeof entry.ref === 'string')
3626
+ .map((entry) => ({ ...entry })),
3627
+ /*
3628
+ * [2.2.0][T3/O-2a] 子→主预告通道的结论必须进入模型可读面。
3629
+ *
3630
+ * 这条能力的目标就是「可观测」:主 Agent 要能一眼看出该子任务的开工预告
3631
+ * 有没有真的到达(observed/not-observed)、目标是谁、什么时候、失败原因。
3632
+ * 只写状态行不让读,等于又是一个「看不见的失败」。
3633
+ */
3634
+ noticeChannel: item.noticeChannel ?? null,
3635
+ /*
3636
+ * [T6][契约v1 §3] 第三层开工预估进入模型可读面:delegates 行透出 estimate
3637
+ * (declaredMinutes/delivery 等,照录不改写),任务级 delegateEstimates 台账
3638
+ * 一并透传——主 Agent/负责人据此核对「谁预估了多少分钟、是否已送达」。
3639
+ */
3640
+ delegates: (Array.isArray(item.delegates) ? item.delegates : [])
3641
+ .filter((entry) => entry && typeof entry === 'object')
3642
+ .map((entry) => ({ ...entry })),
3643
+ delegateEstimates: item.delegateEstimates ?? null,
3644
+ // [T7][J1 冻结结构] {totalMinutes, reported, expected, missing[], failed[]} | null。
3645
+ leaderEstimate,
3646
+ ...(leaderEstimateAnomaly ? { leaderEstimateAnomaly } : {}),
3647
+ /*
3648
+ * [SCv2-T4] 判据层字段进入模型可读面(与看板载荷 normaliseStatusEntry 同源):
3649
+ * 单次尝试墙钟(缺失=null 未验证,绝不按 0)、结算三选一、用户批准留痕、
3650
+ * 违规审计(append-only)、事前预估超判据布尔(服务端算术,客户端不计算)。
3651
+ */
3652
+ attemptWallClockMs: attemptWallClockMsOf(item),
3653
+ criterionResult: item.criterionResult ?? null,
3654
+ criterionException: item.criterionException ?? null,
3655
+ criterionViolations: Array.isArray(item.criterionViolations) ? item.criterionViolations.slice(-10) : [],
3656
+ leaderEstimateOverCriterion: exAnteView.minutes !== null && exAnteView.minutes > CRITERION_TARGET_MINUTES,
3657
+ };
3658
+ });
3178
3659
  }
3179
3660
  export function buildRoundResult(record, sessionId, limits) {
3180
3661
  const { statuses, stats } = derivePlanSnapshot(record.statuses);
@@ -3352,6 +3833,53 @@ export async function dispatchPlan(ctx, record, options) {
3352
3833
  record.dispatchedAt = Date.now();
3353
3834
  record.phase = 'executing';
3354
3835
  record.updatedAt = record.dispatchedAt;
3836
+ /*
3837
+ * [3.0.0][用户要求 4] 分配完成后,会话内必须输出固定文案
3838
+ * 「任务已经完成分配,正在执行中......」。放在本轮真正开跑(phase=executing、
3839
+ * 子 Agent 即将启动)之后、任何子任务结算之前,自动派发与手工派发同一路径,
3840
+ * 因此只输出一次、不会漏也不会重复。逐字冻结,不得改写。
3841
+ */
3842
+ {
3843
+ const assignSession = options.session ?? agent?.session;
3844
+ /*
3845
+ * [3.0.0][幂等键] 同一份计划只发一次:续跑/重派/durable 回放都会再次走到
3846
+ * 这里,若不加键就会重复刷屏。键=planId,随 record 持久化(record 本身
3847
+ * 走 durable 快照),刷新后仍然生效。
3848
+ */
3849
+ const noticeKey = String(record.plan?.planId ?? record.planId ?? '');
3850
+ if (assignSession && noticeKey && record.assignedNoticeKey !== noticeKey) {
3851
+ record.assignedNoticeKey = noticeKey;
3852
+ appendUserMessage(assignSession, STATUS_ASSIGNED_TEXT);
3853
+ }
3854
+ }
3855
+ /*
3856
+ * [2.5.2][stall-fix] 执行期进度心跳(用户报告「提交任务后长时间无反应/以为
3857
+ * 死机」):规划心跳只覆盖 runPlanner,派发后的执行轮次(可能十几分钟)
3858
+ * 旧实现期间零会话输出。现在只要本轮还在跑,就按固定间隔(默认 45s,
3859
+ * DSH_WORKPLAN_DISPATCH_HEARTBEAT_MS 可调,≥5000ms)经唯一合规写入器发
3860
+ * 「已用时+完成进度+不是卡死」的可见通知。与规划心跳同一收束纪律:
3861
+ * finally 里 stop(成功/超时/中止都收束),maxNotices 保险丝防失控,
3862
+ * 不新增事件类型、不触碰 system/message。
3863
+ */
3864
+ const dispatchHbSession = options.session ?? agent?.session;
3865
+ // [T7] C3 整轮预算:新一轮开跑即重置注入预算(roundKey=planId:dispatchedAt,与 finishRound 同键;
3866
+ // 会话取 dispatchHbSession,与本轮 appendUserMessage 同一对象,WeakMap 键一致)。
3867
+ if (dispatchHbSession)
3868
+ resetRoundInjectionBudget(dispatchHbSession, `${record.plan.planId}:${record.dispatchedAt}`);
3869
+ const dispatchHeartbeat = dispatchHbSession ? createPlanningHeartbeat({
3870
+ signal: childController.signal,
3871
+ appendNotice: (text) => appendUserMessage(dispatchHbSession, text),
3872
+ // 默认值引用 PLANNING_HEARTBEAT_MS 单一真源(同为 45s 心跳间隔);
3873
+ // 环境变量名 DSH_WORKPLAN_DISPATCH_HEARTBEAT_MS 保持不变。
3874
+ intervalMs: planningHeartbeatIntervalMs(process.env.DSH_WORKPLAN_DISPATCH_HEARTBEAT_MS ?? PLANNING_HEARTBEAT_MS),
3875
+ startedAt: record.dispatchedAt,
3876
+ maxAttempts: 1,
3877
+ buildMessage: (elapsedMs) => {
3878
+ const snap = derivePlanSnapshot(record.statuses);
3879
+ return buildDispatchHeartbeat(elapsedMs, snap.stats?.done, snap.stats?.total, snap.stats?.inProgress);
3880
+ },
3881
+ }) : { start: () => { }, stop: () => { } };
3882
+ dispatchHeartbeat.start();
3355
3883
  try {
3356
3884
  let guard = 0;
3357
3885
  /*
@@ -3394,7 +3922,50 @@ export async function dispatchPlan(ctx, record, options) {
3394
3922
  && !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
3395
3923
  }
3396
3924
  : {});
3397
- if (ready.length === 0) {
3925
+ /*
3926
+ * [3.0.0+] 派发质量闸(2026-11-15 用户裁决):主 Agent 派给部门负责人的
3927
+ * 每个子任务必须携带 qualityRequirements(质量要求)。缺失的子任务本轮
3928
+ * 直接拒发(不启动部门 Agent),落 blocked + closure:'escalated'——等主
3929
+ * Agent replan 补齐后重派:该形态不参与自动续跑(canResumePlan 排除
3930
+ * escalated)、不会被 readySubtasks 重复选中,天然防重试空转;其余合格
3931
+ * 子任务照常并发执行,互不影响。旧计划(createdAt 早于
3932
+ * QUALITY_GATE_ACTIVATED_AT)豁免,零回归。
3933
+ */
3934
+ let runnable = ready;
3935
+ if (isQualityGatePlan(record.plan)) {
3936
+ const rejected = [];
3937
+ runnable = [];
3938
+ for (const item of ready) {
3939
+ const check = checkSubtaskQualityRequirements(item);
3940
+ if (check.ok) {
3941
+ runnable.push(item);
3942
+ continue;
3943
+ }
3944
+ rejected.push(`${item.id}(${String(item.title ?? '无标题')}):${check.error}`);
3945
+ record.statuses = applyStatus(record.statuses, item.id, {
3946
+ status: 'blocked',
3947
+ closure: 'escalated',
3948
+ blockedKind: 'escalated',
3949
+ question: `${check.error} ${check.hint}`,
3950
+ error: check.error,
3951
+ escalatedAt: Date.now(),
3952
+ });
3953
+ record.errors = [...(record.errors ?? []), `${item.id}: ${check.code} ${check.error}`].slice(-20);
3954
+ }
3955
+ if (rejected.length > 0) {
3956
+ const noticeSession = options.session ?? agent?.session;
3957
+ if (noticeSession) {
3958
+ appendUserMessage(noticeSession, [
3959
+ `【派发拒发 · 质量要求缺失】${rejected.length} 个子任务未携带质量要求(qualityRequirements),`
3960
+ + '已被系统直接拒发(DISPATCH_QUALITY_REQUIREMENTS_MISSING),未启动任何部门 Agent:',
3961
+ ...rejected.map((line, index) => ` ${index + 1}. ${line}`),
3962
+ '请立刻用 dsh_workplan_replan 为这些子任务补写质量要求(至少 1 条可检查:什么算合格、什么算不合格),'
3963
+ + '然后重新派发;本次其余合格子任务正常执行、不受影响。',
3964
+ ].join('\n'));
3965
+ }
3966
+ }
3967
+ }
3968
+ if (runnable.length === 0) {
3398
3969
  /*
3399
3970
  * [1.8.6] "Nothing is ready" is not the same thing as "everything
3400
3971
  * failed".
@@ -3414,7 +3985,7 @@ export async function dispatchPlan(ctx, record, options) {
3414
3985
  }
3415
3986
  break;
3416
3987
  }
3417
- await runWithConcurrency(ready, MAX_CONCURRENT, async (item) => {
3988
+ await runWithConcurrency(runnable, MAX_CONCURRENT, async (item) => {
3418
3989
  // readySubtasks() returns subtask objects (they carry `id`, not
3419
3990
  // `subtaskId`); using the status key here silently skipped every task
3420
3991
  // and spun the dispatcher until DISPATCH_LOOP marked all blocked.
@@ -3624,6 +4195,7 @@ export async function dispatchPlan(ctx, record, options) {
3624
4195
  }
3625
4196
  }
3626
4197
  finally {
4198
+ dispatchHeartbeat.stop();
3627
4199
  clearTimeout(totalTimer);
3628
4200
  parentSignal.removeEventListener('abort', onAbort);
3629
4201
  if (!childController.signal.aborted)
@@ -4003,6 +4575,8 @@ export function reconstructFromSession(session, targetPlanId) {
4003
4575
  errors: [],
4004
4576
  planRevision: Number(plan?.planRevision ?? 0) || 0,
4005
4577
  changeRequest: null,
4578
+ mainDeepThink: null,
4579
+ mainDeepThinkPlanId: null,
4006
4580
  };
4007
4581
  snapshots.set(plan.planId, snap);
4008
4582
  }
@@ -4100,7 +4674,7 @@ export function reconstructFromSession(session, targetPlanId) {
4100
4674
  const rebuiltRow = snap.statuses.find((item) => item?.subtaskId === entry?.subtaskId);
4101
4675
  if (!rebuiltRow || !isRecord(entry))
4102
4676
  continue;
4103
- for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
4677
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief', 'criterionResult', 'criterionException', 'criterionViolations']) {
4104
4678
  if (entry[field] !== undefined)
4105
4679
  rebuiltRow[field] = entry[field];
4106
4680
  }
@@ -4155,178 +4729,214 @@ export function reconstructFromSession(session, targetPlanId) {
4155
4729
  * a strictly-lower revision never overwrites; equal revision passes
4156
4730
  * (dedup for the same write lives in `appliedUpdates`).
4157
4731
  */
4158
- const update = parseUpdateMessage(event.data);
4159
- if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
4160
- const snap = snapshots.get(update.planId);
4161
- if (snap) {
4162
- try {
4163
- /*
4164
- * [2.2.9][T2][mono-gate] 结算事件写入单调性闸(M1,症状①主闸)。
4165
- *
4166
- * 事故形状(wp-215ed52f T5 实证):结算 rev16 已落 durable 结果消息,
4167
- * 主 Agent 基于落后的 live 快照做 handoff 答复,追加了 rev9/10 的
4168
- * workplan-update(seq 更晚)。回放按 seq 升序,后到的旧事件无条件
4169
- * 覆盖先落盘的新结算——「后到即覆盖」与「revision 单调、已结算内容
4170
- * 不可回退」的业务不变量正面冲突。
4171
- *
4172
- * 闸语义(与 plan.ts applyResultStatuses 的 result 族闸对齐):
4173
- * - evRev < rowRev → 回退事件:拒绝整事件语义(含 3936 一带的直写
4174
- * 白名单与 extendMs 合成,防止旧事件的状态性字段漏进新行),只有
4175
- * handoffs 走逐项单调合并(M2:答复是字段级增量,新登记永远合法、
4176
- * answered/closed 终态永不回退);
4177
- * - 仍必须 appliedUpdates.set:否则同一次改判的 tool/result 配对
4178
- * 记录(patch 不带 rev,applyStatus 强算 current+1)会绕过本闸从
4179
- * 第二通道把旧内容灌回;
4180
- * - evRev === rowRev → 前向通过(等 rev 补写是合法场景;同一条写入
4181
- * 的重复应用由既有 appliedUpdates/1.8.11 去重通道拦截);
4182
- * - evRev 为 null(旧格式无 revision 字段 / 非整数)→ 不猜、放行,
4183
- * 向后兼容(applyStatus 尾部按 current+1 单调抬号)。
4184
- */
4185
- const gateRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4186
- const rowRev = Number(gateRow?.revision ?? 0);
4187
- const evRev = Number.isInteger(update.revision) ? Number(update.revision) : null;
4188
- if (gateRow && evRev !== null && evRev < rowRev) {
4189
- if (Array.isArray(update.handoffs)) {
4190
- const merged = mergeHandoffEntriesByUpdatedAt(gateRow.handoffs, update.handoffs);
4191
- if (merged.changed)
4192
- gateRow.handoffs = merged.value;
4732
+ /* [2.5.5][T10] 合并汇总消息按序展开成多条 update,逐条应用(与逐条落盘等价)。 */
4733
+ for (const update of parseUpdateMessages(event.data)) {
4734
+ /*
4735
+ * [2.5.1] 主 Agent 两轮深度思考产物回放(计划级字段):写入侧
4736
+ * (dispatchTool 门禁登记)把 mainDeepThink/mainDeepThinkPlanId 随
4737
+ * durable workplan-update 落盘(subtaskId=null,不挂任何子任务行);
4738
+ * 消费侧同一判据消毒(sanitizeMainDeepThink)后抬进计划快照——刷新/
4739
+ * 重启后续跑读档放行,不必重新提交;旧日志无该字段零迁移不报错。
4740
+ */
4741
+ if (update && typeof update.planId === 'string' && update.mainDeepThink !== undefined) {
4742
+ const deepThinkSnap = snapshots.get(update.planId);
4743
+ if (deepThinkSnap) {
4744
+ deepThinkSnap.mainDeepThink = sanitizeMainDeepThink(update.mainDeepThink);
4745
+ deepThinkSnap.mainDeepThinkPlanId = typeof update.mainDeepThinkPlanId === 'string' ? update.mainDeepThinkPlanId : null;
4746
+ }
4747
+ }
4748
+ if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
4749
+ const snap = snapshots.get(update.planId);
4750
+ if (snap) {
4751
+ try {
4752
+ /*
4753
+ * [2.2.9][T2][mono-gate] 结算事件写入单调性闸(M1,症状①主闸)。
4754
+ *
4755
+ * 事故形状(wp-215ed52f T5 实证):结算 rev16 已落 durable 结果消息,
4756
+ * 主 Agent 基于落后的 live 快照做 handoff 答复,追加了 rev9/10 的
4757
+ * workplan-update(seq 更晚)。回放按 seq 升序,后到的旧事件无条件
4758
+ * 覆盖先落盘的新结算——「后到即覆盖」与「revision 单调、已结算内容
4759
+ * 不可回退」的业务不变量正面冲突。
4760
+ *
4761
+ * 闸语义(与 plan.ts applyResultStatuses 的 result 族闸对齐):
4762
+ * - evRev < rowRev → 回退事件:拒绝整事件语义(含 3936 一带的直写
4763
+ * 白名单与 extendMs 合成,防止旧事件的状态性字段漏进新行),只有
4764
+ * handoffs 走逐项单调合并(M2:答复是字段级增量,新登记永远合法、
4765
+ * answered/closed 终态永不回退);
4766
+ * - 仍必须 appliedUpdates.set:否则同一次改判的 tool/result 配对
4767
+ * 记录(patch 不带 rev,applyStatus 强算 current+1)会绕过本闸从
4768
+ * 第二通道把旧内容灌回;
4769
+ * - evRev === rowRev → 前向通过(等 rev 补写是合法场景;同一条写入
4770
+ * 的重复应用由既有 appliedUpdates/1.8.11 去重通道拦截);
4771
+ * - evRev 为 null(旧格式无 revision 字段 / 非整数)→ 不猜、放行,
4772
+ * 向后兼容(applyStatus 尾部按 current+1 单调抬号)。
4773
+ */
4774
+ const gateRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4775
+ const rowRev = Number(gateRow?.revision ?? 0);
4776
+ const evRev = Number.isInteger(update.revision) ? Number(update.revision) : null;
4777
+ if (gateRow && evRev !== null && evRev < rowRev) {
4778
+ if (Array.isArray(update.handoffs)) {
4779
+ const merged = mergeHandoffEntriesByUpdatedAt(gateRow.handoffs, update.handoffs);
4780
+ if (merged.changed)
4781
+ gateRow.handoffs = merged.value;
4782
+ }
4783
+ console.warn('[dsh-workplan] monotonicity gate skipped a stale replayed update: '
4784
+ + `${String(update.planId)}/${String(update.subtaskId)} `
4785
+ + `(event rev ${evRev} < row rev ${rowRev}); row content kept, `
4786
+ + 'handoff entries merged monotonically');
4787
+ appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
4788
+ seq: Number(event.seq ?? 0),
4789
+ status: String(update.status ?? ''),
4790
+ });
4791
+ continue;
4193
4792
  }
4194
- console.warn('[dsh-workplan] monotonicity gate skipped a stale replayed update: '
4195
- + `${String(update.planId)}/${String(update.subtaskId)} `
4196
- + `(event rev ${evRev} < row rev ${rowRev}); row content kept, `
4197
- + 'handoff entries merged monotonically');
4198
- appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
4199
- seq: Number(event.seq ?? 0),
4200
- status: String(update.status ?? ''),
4793
+ /*
4794
+ * [2.3.0][hotfix] 回放兼容「已回报行 + 旧版 closure:'done' 错误快照」(用户 2026-11-10 截图:
4795
+ * wp-3080d01d T6/T7「非法闭环迁移:reported → done」回放忽略)。
4796
+ *
4797
+ * 2.0.4 之前 live 侧 applyStatus 把 reported 行的 closure 误写回 'done',durable 改判
4798
+ * 消息因此嵌着这个错误快照。2.2.6 D-1 给回放补了 closure 透传,但没有豁免这一组合:
4799
+ * 回放大方把 'done' 当显式闭环意图传给迁移表 → reported → done 被拒 → 整条改判
4800
+ * (含 verification/acceptance 证据)被裸 catch 吞掉,重启后行退回缺证据态。
4801
+ *
4802
+ * 口径与 2.0.4 live 侧镜像:事件 closure='done' 且当前行 closure='reported' 时,这是
4803
+ * 「复核补齐」而非「退回未回报」,丢弃该显式值,让 done 分支按 2.0.4 保留已回报事实。
4804
+ * 其余透传分支(escalated/instructed 等,D-1 语义)零改动。
4805
+ */
4806
+ const preReplayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4807
+ const replayClosure = typeof update.closure === 'string'
4808
+ ? (update.closure === 'done' && preReplayRow?.closure === 'reported' ? undefined : update.closure)
4809
+ : undefined;
4810
+ snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
4811
+ /*
4812
+ * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
4813
+ * 重放时若再走 done 分支,会把已经 reported 的行打回 done 并抛
4814
+ * INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
4815
+ */
4816
+ status: update.handoffs === undefined ? update.status : undefined,
4817
+ /*
4818
+ * [2.2.6][D-1] 人工改判的 closure 必须随 patch 回放。
4819
+ *
4820
+ * durable 的 workplan-update 自 1.11.0 起携带 closure
4821
+ * (buildUpdateMessage),但这里的 patch 一直没把它传给
4822
+ * applyStatus:行停在 escalated 时,status=done 的改判会因
4823
+ * 「非法闭环迁移 escalated→done / closure=escalated 必须同时
4824
+ * status=blocked」被拒,整条 update 被下面的裸 catch 吞掉,
4825
+ * 重启后「待指示」行永久卡死(2026-11-08 wp-3c8c84b2 T2 实证,
4826
+ * 见 artifacts/2.2.5-post-restart-regression.md §4 D-1)。
4827
+ */
4828
+ closure: replayClosure,
4829
+ progress: typeof update.progress === 'number' ? update.progress : undefined,
4830
+ summary: typeof update.note === 'string' ? update.note : undefined,
4831
+ // [1.8.13] Evidence written through the update tool must survive replay.
4832
+ verification: update.verification,
4833
+ acceptance: update.acceptance,
4834
+ artifacts: update.artifacts,
4835
+ missingArtifacts: update.missingArtifacts,
4836
+ handoffs: update.handoffs,
4837
+ revision: Number.isInteger(update.revision) ? update.revision : undefined,
4838
+ // [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
4839
+ // update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
4840
+ timeoutMs: update.timeoutMs,
4841
+ /*
4842
+ * [2.5.0][G1] 整体任务等级与第三层梳理/台账必须随 durable
4843
+ * workplan-update 回放:写入侧(plan.ts buildUpdateMessage)已携带
4844
+ * effortOverride/consolidation/delegates,消费端 patch 此前漏传,
4845
+ * 刷新/重启后整体等级丢失(resolveTaskEffort 回落旧档)、梳理登记
4846
+ * 与第三层台账同丢。三字段在 applyStatus 均有路由分支,undefined
4847
+ * 保留旧值——旧日志零迁移,与 live 侧同一口径。
4848
+ */
4849
+ effortOverride: update.effortOverride,
4850
+ consolidation: update.consolidation,
4851
+ delegates: update.delegates,
4852
+ delegateSelfEfforts: update.delegateSelfEfforts,
4853
+ // [2.5.2] 叶子执行前两轮思考台账回放(applyStatus 同口径消毒)。
4854
+ delegateDeepThinks: update.delegateDeepThinks,
4855
+ // [T6][契约v1 §3] 第三层开工预估台账回放(applyStatus 同口径消毒,
4856
+ // undefined 保留旧值):刷新/重启后预估不丢,重派读档门禁据此判定。
4857
+ delegateEstimates: update.delegateEstimates,
4858
+ // [2.5.4][T3R1] 分派前深度梳理门禁审计回放(A3:刷新/重启后
4859
+ // 拒绝/放行记录仍可复核;applyStatus 同口径消毒,undefined 保留旧值)。
4860
+ gateAudit: update.gateAudit,
4861
+ updatedBy: 'agent',
4201
4862
  });
4202
- continue;
4203
- }
4204
- /*
4205
- * [2.3.0][hotfix] 回放兼容「已回报行 + 旧版 closure:'done' 错误快照」(用户 2026-11-10 截图:
4206
- * wp-3080d01d T6/T7「非法闭环迁移:reported → done」回放忽略)。
4207
- *
4208
- * 2.0.4 之前 live 侧 applyStatus 把 reported 行的 closure 误写回 'done',durable 改判
4209
- * 消息因此嵌着这个错误快照。2.2.6 D-1 给回放补了 closure 透传,但没有豁免这一组合:
4210
- * 回放大方把 'done' 当显式闭环意图传给迁移表 → reported → done 被拒 → 整条改判
4211
- * (含 verification/acceptance 证据)被裸 catch 吞掉,重启后行退回缺证据态。
4212
- *
4213
- * 口径与 2.0.4 live 侧镜像:事件 closure='done' 且当前行 closure='reported' 时,这是
4214
- * 「复核补齐」而非「退回未回报」,丢弃该显式值,让 done 分支按 2.0.4 保留已回报事实。
4215
- * 其余透传分支(escalated/instructed 等,D-1 语义)零改动。
4216
- */
4217
- const preReplayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4218
- const replayClosure = typeof update.closure === 'string'
4219
- ? (update.closure === 'done' && preReplayRow?.closure === 'reported' ? undefined : update.closure)
4220
- : undefined;
4221
- snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
4222
4863
  /*
4223
- * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
4224
- * 重放时若再走 done 分支,会把已经 reported 的行打回 done 并抛
4225
- * INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
4864
+ * [2.2.9][T3][M4] 回放侧人工改判的回报闭环——与 live 路径(改判
4865
+ * 工具在 durable 落盘成功后 markReported)配成同一条不变量:
4866
+ * durable 的 workplan-update 携带显式 status:'done' 时,这条消息
4867
+ * 本身就是主 Agent 亲笔写进会话日志的「完成已回报」证据。旧日志
4868
+ * 嵌的是 closure:'done'(2.2.9 之前的口径),回放在此一并升级为
4869
+ * reported;report.ref 指向这条 durable 消息的 seq——引用真实存在、
4870
+ * 可复核。不升 handoffs 快照消息(它们的 status 未被应用,handoff
4871
+ * 记录不是一次回报),子结算行的回报仍须来自结果消息或 pre-step
4872
+ * 自愈(M4.2)。live 与重建由此在同一份日志上逐行同判,
4873
+ * 「可交付↔门禁未放行」的震荡失去立足点。
4226
4874
  */
4227
- status: update.handoffs === undefined ? update.status : undefined,
4875
+ if (update.status === 'done' && update.handoffs === undefined) {
4876
+ const healedRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4877
+ if (healedRow?.status === 'done' && healedRow?.closure === 'done') {
4878
+ healedRow.closure = 'reported';
4879
+ healedRow.reportedAt = Number(update.at) || Date.now();
4880
+ healedRow.report = {
4881
+ state: 'sent',
4882
+ at: Number(update.at) || Date.now(),
4883
+ ref: `${String(update.planId)}:replay:${String(Number(event.seq ?? 0))}`,
4884
+ turn: null,
4885
+ };
4886
+ }
4887
+ }
4228
4888
  /*
4229
- * [2.2.6][D-1] 人工改判的 closure 必须随 patch 回放。
4889
+ * [2.2.0][T4/O-3b][E] 柔性时长协商新字段回放(E 项,runtime.ts 2931 一带)。
4230
4890
  *
4231
- * durable 的 workplan-update 自 1.11.0 起携带 closure
4232
- * (buildUpdateMessage),但这里的 patch 一直没把它传给
4233
- * applyStatus:行停在 escalated 时,status=done 的改判会因
4234
- * 「非法闭环迁移 escalated→done / closure=escalated 必须同时
4235
- * status=blocked」被拒,整条 update 被下面的裸 catch 吞掉,
4236
- * 重启后「待指示」行永久卡死(2026-11-08 wp-3c8c84b2 T2 实证,
4237
- * 见 artifacts/2.2.5-post-restart-regression.md §4 D-1)。
4891
+ * deadlineAt/timeNotice/timeWarning/timeJournal/待裁决标记在 applyStatus
4892
+ * (src/plan.ts,T3 领地)无路由分支,走 patch 会被静默丢弃;按 T3b
4893
+ * plan.ts:2966-2971 同名修复口径在此直写重建行。extendMs 走累加语义
4894
+ * (与线上 extendDeadline 一致:deadlineAt += extendMs 并追加 timeJournal),
4895
+ * 仅当记录未自带 timeJournal 时合成,避免同一条 journal 被回放两次。
4238
4896
  */
4239
- closure: replayClosure,
4240
- progress: typeof update.progress === 'number' ? update.progress : undefined,
4241
- summary: typeof update.note === 'string' ? update.note : undefined,
4242
- // [1.8.13] Evidence written through the update tool must survive replay.
4243
- verification: update.verification,
4244
- acceptance: update.acceptance,
4245
- artifacts: update.artifacts,
4246
- missingArtifacts: update.missingArtifacts,
4247
- handoffs: update.handoffs,
4248
- revision: Number.isInteger(update.revision) ? update.revision : undefined,
4249
- // [2.2.0][T4/O-3b][E] 回放白名单(T3b TODO#2):O-3b/O-2c 留档字段随
4250
- // update 记录回放;timeoutMs 有 applyStatus 分支,走 patch 即可。
4251
- timeoutMs: update.timeoutMs,
4252
- updatedBy: 'agent',
4253
- });
4254
- /*
4255
- * [2.2.9][T3][M4] 回放侧人工改判的回报闭环——与 live 路径(改判
4256
- * 工具在 durable 落盘成功后 markReported)配成同一条不变量:
4257
- * durable 的 workplan-update 携带显式 status:'done' 时,这条消息
4258
- * 本身就是主 Agent 亲笔写进会话日志的「完成已回报」证据。旧日志
4259
- * 嵌的是 closure:'done'(2.2.9 之前的口径),回放在此一并升级为
4260
- * reported;report.ref 指向这条 durable 消息的 seq——引用真实存在、
4261
- * 可复核。不升 handoffs 快照消息(它们的 status 未被应用,handoff
4262
- * 记录不是一次回报),子结算行的回报仍须来自结果消息或 pre-step
4263
- * 自愈(M4.2)。live 与重建由此在同一份日志上逐行同判,
4264
- * 「可交付↔门禁未放行」的震荡失去立足点。
4265
- */
4266
- if (update.status === 'done' && update.handoffs === undefined) {
4267
- const healedRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4268
- if (healedRow?.status === 'done' && healedRow?.closure === 'done') {
4269
- healedRow.closure = 'reported';
4270
- healedRow.reportedAt = Number(update.at) || Date.now();
4271
- healedRow.report = {
4272
- state: 'sent',
4273
- at: Number(update.at) || Date.now(),
4274
- ref: `${String(update.planId)}:replay:${String(Number(event.seq ?? 0))}`,
4275
- turn: null,
4276
- };
4897
+ const replayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4898
+ if (replayRow) {
4899
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief', 'criterionResult', 'criterionException', 'criterionViolations']) {
4900
+ if (update[field] !== undefined)
4901
+ replayRow[field] = update[field];
4902
+ }
4903
+ const replayExtend = Number(update.extendMs);
4904
+ if (update.timeJournal === undefined && Number.isFinite(replayExtend) && replayExtend > 0
4905
+ && Number.isFinite(Number(replayRow.deadlineAt))) {
4906
+ replayRow.deadlineAt = Number(replayRow.deadlineAt) + Math.floor(replayExtend);
4907
+ replayRow.timeJournal = [
4908
+ ...(Array.isArray(replayRow.timeJournal) ? replayRow.timeJournal : []),
4909
+ {
4910
+ at: Date.now(),
4911
+ action: 'extend',
4912
+ extendMs: Math.floor(replayExtend),
4913
+ by: 'agent',
4914
+ reason: truncate(String(update.reason ?? ''), 300),
4915
+ },
4916
+ ].slice(-20);
4917
+ }
4277
4918
  }
4919
+ appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
4920
+ seq: Number(event.seq ?? 0),
4921
+ status: String(update.status ?? ''),
4922
+ });
4278
4923
  }
4279
- /*
4280
- * [2.2.0][T4/O-3b][E] 柔性时长协商新字段回放(E 项,runtime.ts 2931 一带)。
4281
- *
4282
- * deadlineAt/timeNotice/timeWarning/timeJournal/待裁决标记在 applyStatus
4283
- * (src/plan.ts,T3 领地)无路由分支,走 patch 会被静默丢弃;按 T3b
4284
- * plan.ts:2966-2971 同名修复口径在此直写重建行。extendMs 走累加语义
4285
- * (与线上 extendDeadline 一致:deadlineAt += extendMs 并追加 timeJournal),
4286
- * 仅当记录未自带 timeJournal 时合成,避免同一条 journal 被回放两次。
4287
- */
4288
- const replayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4289
- if (replayRow) {
4290
- for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
4291
- if (update[field] !== undefined)
4292
- replayRow[field] = update[field];
4293
- }
4294
- const replayExtend = Number(update.extendMs);
4295
- if (update.timeJournal === undefined && Number.isFinite(replayExtend) && replayExtend > 0
4296
- && Number.isFinite(Number(replayRow.deadlineAt))) {
4297
- replayRow.deadlineAt = Number(replayRow.deadlineAt) + Math.floor(replayExtend);
4298
- replayRow.timeJournal = [
4299
- ...(Array.isArray(replayRow.timeJournal) ? replayRow.timeJournal : []),
4300
- {
4301
- at: Date.now(),
4302
- action: 'extend',
4303
- extendMs: Math.floor(replayExtend),
4304
- by: 'agent',
4305
- reason: truncate(String(update.reason ?? ''), 300),
4306
- },
4307
- ].slice(-20);
4308
- }
4924
+ catch (error) {
4925
+ /*
4926
+ * [2.2.6][D-1] fail-closed 而非 fail-silent:历史 update 不合法时
4927
+ * 至少留一条日志,否则「改判丢失」永远无从发现(本缺陷因此潜伏
4928
+ * 自 1.7.0)。回放继续,不让单条坏记录拖垮整个重建。
4929
+ */
4930
+ console.warn('[dsh-workplan] 回放忽略一条不合法的历史改判:'
4931
+ + `${String(update?.planId ?? '')}/${String(update?.subtaskId ?? '')}:`
4932
+ + /*
4933
+ * [2.2.9][T3][M4.3] 可诊断化:旧快照携带的 closure/revision 与被保留
4934
+ * 的行现状一并带出,「改判丢失」不再只有一句 error.message。
4935
+ */
4936
+ `event rev=${String(update?.revision ?? 'none')} closure=${String(update?.closure ?? 'none')} `
4937
+ + `vs row rev=${String(snap.statuses.find((item) => item?.subtaskId === update?.subtaskId)?.revision ?? 'none')}:`
4938
+ + `${error instanceof Error ? error.message : String(error)}`);
4309
4939
  }
4310
- appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
4311
- seq: Number(event.seq ?? 0),
4312
- status: String(update.status ?? ''),
4313
- });
4314
- }
4315
- catch (error) {
4316
- /*
4317
- * [2.2.6][D-1] fail-closed 而非 fail-silent:历史 update 不合法时
4318
- * 至少留一条日志,否则「改判丢失」永远无从发现(本缺陷因此潜伏
4319
- * 自 1.7.0)。回放继续,不让单条坏记录拖垮整个重建。
4320
- */
4321
- console.warn('[dsh-workplan] 回放忽略一条不合法的历史改判:'
4322
- + `${String(update?.planId ?? '')}/${String(update?.subtaskId ?? '')}:`
4323
- + /*
4324
- * [2.2.9][T3][M4.3] 可诊断化:旧快照携带的 closure/revision 与被保留
4325
- * 的行现状一并带出,「改判丢失」不再只有一句 error.message。
4326
- */
4327
- `event rev=${String(update?.revision ?? 'none')} closure=${String(update?.closure ?? 'none')} `
4328
- + `vs row rev=${String(snap.statuses.find((item) => item?.subtaskId === update?.subtaskId)?.revision ?? 'none')}:`
4329
- + `${error instanceof Error ? error.message : String(error)}`);
4330
4940
  }
4331
4941
  }
4332
4942
  }
@@ -4493,6 +5103,9 @@ export function reconstructFromSession(session, targetPlanId) {
4493
5103
  updatedAt: Date.now(),
4494
5104
  createdTurn: plan.createdTurn,
4495
5105
  resumeCount,
5106
+ /* [2.5.1] 主 Agent 两轮深度思考产物随回放回到记录(续跑读档放行)。 */
5107
+ mainDeepThink: chosen.mainDeepThink ?? null,
5108
+ mainDeepThinkPlanId: chosen.mainDeepThinkPlanId ?? null,
4496
5109
  /*
4497
5110
  * [1.8.17] A reconstructed record must carry every field the live dispatch
4498
5111
  * path spreads/pushes unconditionally. `errors` was the one that was
@@ -4500,8 +5113,10 @@ export function reconstructFromSession(session, targetPlanId) {
4500
5113
  * abort that marked the rest of the plan blocked.
4501
5114
  */
4502
5115
  errors: (chosen.errors ?? []).slice(-20),
4503
- resumeLimit: MAX_PLAN_RESUMES,
4504
- resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, MAX_PLAN_RESUMES).resume,
5116
+ // [2.5.7] 与 serialisePlan/status 输出同口径:优先读档内 resumeLimit,
5117
+ // 缺失才回落 MAX_PLAN_RESUMES(三源统一,消除第四套口径)。
5118
+ resumeLimit: Number(chosen?.resumeLimit ?? MAX_PLAN_RESUMES),
5119
+ resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, Number(chosen?.resumeLimit ?? MAX_PLAN_RESUMES)).resume,
4505
5120
  stale: stalePending,
4506
5121
  /*
4507
5122
  * [1.8.14] Two facts, one from the log: whether the plan is cancelled and
@@ -4687,8 +5302,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
4687
5302
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
4688
5303
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
4689
5304
  : MAX_PLAN_RESUMES,
5305
+ // [1.12.0] 默认开启:仅显式 `autoResume:false`(或
5306
+ // `DSH_WORKPLAN_AUTO_RESUME=0`)才关闭,与 `AUTO_RESUME_DEFAULTS.enabled=true` 一致。
4690
5307
  autoResume: {
4691
- enabled: options.autoResume === true,
5308
+ enabled: options.autoResume !== false,
4692
5309
  maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
4693
5310
  },
4694
5311
  };
@@ -4702,6 +5319,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
4702
5319
  * - 失败只记录错误,不把「派发失败」伪装成「计划生成失败」。
4703
5320
  */
4704
5321
  function startAutoDispatch(record, session, agent) {
5322
+ // [2.5.5][T6] payload.agent 缺失时按 session.id 兜底解析活体 agent,
5323
+ // 避免宿主 spec.parent.id 毫秒级崩溃(自动派发与工具路径同病实测)。
5324
+ agent = agent ?? resolveLiveAgent(ctx, session?.id);
4705
5325
  const controller = new AbortController();
4706
5326
  record.abortDispatch = (reason) => {
4707
5327
  if (!controller.signal.aborted) {
@@ -4915,6 +5535,32 @@ export function createWorkplanRuntime(ctx, options = {}) {
4915
5535
  });
4916
5536
  row.timeJournal = journal.slice(-20);
4917
5537
  record.updatedAt = at;
5538
+ /*
5539
+ * [SCv2-T4][Q4-B/C22] 部门行事前预估落档后的超判据告警(仅生效计划):
5540
+ * 叶子预估之和(或无叶子直做时负责人自身预估)>10 ⇒ 即时告知主 Agent
5541
+ * 拆分或向用户申请例外批准;预估未齐只显示部分和、不得视为达标(D-3)。
5542
+ * 告警是观测设施:写失败只留档 errors,绝不影响记录与执行。
5543
+ */
5544
+ try {
5545
+ if (criterionV2Active(record?.plan?.createdAt) && session) {
5546
+ let leaderForNotice = null;
5547
+ try {
5548
+ leaderForNotice = deriveLeaderEstimate(row);
5549
+ }
5550
+ catch {
5551
+ leaderForNotice = null;
5552
+ }
5553
+ const exAnte = criterionExAnte(row, leaderForNotice);
5554
+ if (exAnte.minutes !== null && exAnte.minutes > CRITERION_TARGET_MINUTES) {
5555
+ appendUserMessage(session, `【dsh-workplan·判据告警】子任务 ${subtaskId} 的事前预估为 ${exAnte.minutes} 分钟,`
5556
+ + `超过判据层完成目标 ${CRITERION_TARGET_MINUTES} 分钟(Q4-B)。请事前拆分工作,或向用户申请例外批准并留痕(criterionApproval);`
5557
+ + '预估未报齐时只显示部分和,不得视为「简单判据达标」。');
5558
+ }
5559
+ }
5560
+ }
5561
+ catch (error) {
5562
+ record.errors = [...(record.errors ?? []), `${subtaskId} 判据告警写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20);
5563
+ }
4918
5564
  /*
4919
5565
  * [2.3.0][T1] 预估上报 → 告知用户(用户要求 1 的前半段闭环):专家的开工
4920
5566
  * 预告落档后,插件立即向主会话推送一条即时通知,明确「请把此预期执行
@@ -4927,7 +5573,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4927
5573
  + `预估执行时间 ${Number(notice?.declaredMinutes)} 分钟`
4928
5574
  + (reason ? `(${reason})` : '')
4929
5575
  + `;请把此预期执行时间告知用户。若执行中超时,请主 Agent 放宽(extendMs)`
4930
- + '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。');
5576
+ + '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。', undefined, { allowBanned: true });
4931
5577
  }
4932
5578
  catch (error) {
4933
5579
  record.errors = [...(record.errors ?? []), `${subtaskId} 预估上报通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20);
@@ -4975,25 +5621,59 @@ export function createWorkplanRuntime(ctx, options = {}) {
4975
5621
  };
4976
5622
  }
4977
5623
  /*
4978
- * [2.2.0][T5/O-4c] timeNotice 的校验放在入口统一做(所有路径共享):
4979
- * 非法预告不该因为调用同时带了 status/instruction 就被静默接受。
5624
+ * [SCv2-T4][Q1-B/C05/C06] extendMs 用户批准闸(判据 v2 生效计划专用):
5625
+ * 第一次超时不再自动放宽——未携带合格用户批准留痕(criterionApproval)一律
5626
+ * 拒绝(EXTEND_NEEDS_USER_APPROVAL),批准时间晚于当前时刻 likewise 拒绝
5627
+ * (C-4 推荐 A:批准仅在本次尝试结算前有效,事后追认无效)。
5628
+ * 未生效计划(历史/在途,Q5-A/D-1)保持 2.3.0 旧行为,既有回归零改动。
5629
+ * 留痕 5 项:任务 ID(subtaskId)、批准原文/来源(reason/source)、批准时间
5630
+ * (at)、放宽后分钟数(extendedMinutes,事务内回填)、适用范围(scope)。
4980
5631
  */
4981
- if (hasTimeNotice) {
4982
- const problem = validateTimeNotice(timeNoticeArg);
4983
- if (problem) {
5632
+ const criterionActive = criterionV2Active(record.plan?.createdAt);
5633
+ let criterionApproval = null;
5634
+ if (hasExtend && criterionActive) {
5635
+ criterionApproval = sanitizeCriterionException(args?.criterionApproval);
5636
+ if (!criterionApproval) {
4984
5637
  return {
4985
5638
  ok: false,
4986
- code: problem.code,
5639
+ code: 'EXTEND_NEEDS_USER_APPROVAL',
4987
5640
  planId: record.plan.planId,
4988
5641
  subtaskId,
4989
- error: problem.error,
4990
- hint: problem.hint,
5642
+ error: '判据 v2 已对该计划生效:extendMs 放宽必须先取得用户明确批准并留痕(Q1-B),本次调用未携带合格的 criterionApproval。',
5643
+ hint: '请先向用户申请例外批准,再随 extendMs 传 criterionApproval={ approvedBy:"user", at:<批准时间 epoch 毫秒>, reason:<批准原文/来源>, scope:"task"|"plan" }(5 项留痕:任务 ID、批准原文/来源、批准时间、放宽后分钟数、适用范围;无留痕=未批准)。未获批准时不得放宽:按判据层未达标处理,用 dsh_workplan_replan(replace) 转接替子任务只补缺口。',
4991
5644
  };
4992
5645
  }
4993
- }
4994
- /*
4995
- * [2.2.0][T5/O-4c] 延期事务与状态改判分开提交:方案 §2.2 把 extendMs 定为
4996
- * 「放宽时间的唯一写路径」,要求原子与可审计;一次调用既改判定又改时限会让
5646
+ if (criterionApproval.at > Date.now()) {
5647
+ return {
5648
+ ok: false,
5649
+ code: 'EXTEND_APPROVAL_INVALID_TIME',
5650
+ planId: record.plan.planId,
5651
+ subtaskId,
5652
+ error: `criterionApproval.at(${criterionApproval.at})晚于当前时刻:批准必须在本次尝试结算前取得,事后追认无效(C-4 推荐 A)。`,
5653
+ hint: '请使用用户实际批准的时间(epoch 毫秒,Asia/Shanghai 展示);结算后只能批准接替行,不能追改本次判定。',
5654
+ };
5655
+ }
5656
+ }
5657
+ /*
5658
+ * [2.2.0][T5/O-4c] timeNotice 的校验放在入口统一做(所有路径共享):
5659
+ * 非法预告不该因为调用同时带了 status/instruction 就被静默接受。
5660
+ */
5661
+ if (hasTimeNotice) {
5662
+ const problem = validateTimeNotice(timeNoticeArg);
5663
+ if (problem) {
5664
+ return {
5665
+ ok: false,
5666
+ code: problem.code,
5667
+ planId: record.plan.planId,
5668
+ subtaskId,
5669
+ error: problem.error,
5670
+ hint: problem.hint,
5671
+ };
5672
+ }
5673
+ }
5674
+ /*
5675
+ * [2.2.0][T5/O-4c] 延期事务与状态改判分开提交:方案 §2.2 把 extendMs 定为
5676
+ * 「放宽时间的唯一写路径」,要求原子与可审计;一次调用既改判定又改时限会让
4997
5677
  * 失败路径出现半写(判定已落、时限未落,或相反)。组合调用显式拒绝,模型分
4998
5678
  * 两次提交即可(两者都不需要 force)。
4999
5679
  */
@@ -5177,6 +5857,31 @@ export function createWorkplanRuntime(ctx, options = {}) {
5177
5857
  };
5178
5858
  }
5179
5859
  extension = extended;
5860
+ /*
5861
+ * [SCv2-T4][Q1-B/C08] 批准留痕落行(criterionException,最终定名):
5862
+ * 放宽后分钟数由本次 extendMs 回填;timeJournal 追加 action:'criterion-exception'
5863
+ * 审计条目。回放白名单已追加 criterionException,刷新/重启不丢批准记录。
5864
+ */
5865
+ if (criterionActive && criterionApproval) {
5866
+ const extendRow = record.statuses.find((item) => item?.subtaskId === subtaskId);
5867
+ if (extendRow) {
5868
+ extendRow.criterionException = {
5869
+ ...criterionApproval,
5870
+ extendedMs: extendMsArg,
5871
+ extendedMinutes: Math.round((extendMsArg / 60000) * 100) / 100,
5872
+ };
5873
+ const approvalJournal = Array.isArray(extendRow.timeJournal) ? extendRow.timeJournal : [];
5874
+ approvalJournal.push({
5875
+ at: Date.now(),
5876
+ action: 'criterion-exception',
5877
+ by: 'user',
5878
+ extendMs: extendMsArg,
5879
+ scope: criterionApproval.scope,
5880
+ reason: truncate(criterionApproval.reason, 300),
5881
+ });
5882
+ extendRow.timeJournal = approvalJournal.slice(-20);
5883
+ }
5884
+ }
5180
5885
  /*
5181
5886
  * [2.3.0][T1] 用户要求 1 后半段:放宽成功后必须把「最新执行时间」告知
5182
5887
  * 专家,同时附「必须在保证工作质量的前提下高效率执行」硬要求,让专家
@@ -5218,6 +5923,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
5218
5923
  }
5219
5924
  : {}),
5220
5925
  ...(hasTimeNotice ? { timeNotice: written?.timeNotice ?? null } : {}),
5926
+ // [SCv2-T4] 批准留痕随纯时限事务回执下发(仅生效计划且本次携带批准时)。
5927
+ ...(criterionActive && criterionApproval ? { criterionException: written?.criterionException ?? null } : {}),
5221
5928
  timeJournal: Array.isArray(written?.timeJournal) ? written.timeJournal.slice(-10) : [],
5222
5929
  stats: snapshot.stats,
5223
5930
  deliveryReady: readiness.ready,
@@ -5237,6 +5944,49 @@ export function createWorkplanRuntime(ctx, options = {}) {
5237
5944
  * sanitised by `applyStatus`, persisted in the durable update message and
5238
5945
  * replayed. Omitted fields keep their previous values.
5239
5946
  */
5947
+ /*
5948
+ * [SCv2-T4][Q1-B/S-Q1-3] 人工改判 done 的判据闸(仅生效计划):
5949
+ * 未达标且无用户批准 ⇒ CRITERION_UNMET 拒绝(不得以 done 收尾);
5950
+ * 随调用携带 criterionApproval 或行上已有有效批准 ⇒ 记例外后放行。
5951
+ * 这是「复核改判」恢复路径的判据边界:恢复也必须经用户批准留痕。
5952
+ */
5953
+ let manualCriterionFields = null;
5954
+ if (status === 'done' && criterionActive) {
5955
+ const settledAt = Date.now();
5956
+ let leaderForCriterion = null;
5957
+ try {
5958
+ leaderForCriterion = deriveLeaderEstimate(current);
5959
+ }
5960
+ catch {
5961
+ leaderForCriterion = null;
5962
+ }
5963
+ const exAnte = criterionExAnte(current, leaderForCriterion);
5964
+ const approval = sanitizeCriterionException(args?.criterionApproval)
5965
+ ?? sanitizeCriterionException(current?.criterionException);
5966
+ const evaluation = evaluateCriterion({
5967
+ exAnteMinutes: exAnte.minutes,
5968
+ exAnteComplete: exAnte.complete,
5969
+ wallClockMs: attemptWallClockMsOf({ startedAt: current?.startedAt, finishedAt: current?.finishedAt ?? settledAt }),
5970
+ exception: approval,
5971
+ settledAt,
5972
+ });
5973
+ if (!evaluation.canBeDone) {
5974
+ return {
5975
+ ok: false,
5976
+ code: 'CRITERION_UNMET',
5977
+ planId: record.plan.planId,
5978
+ subtaskId,
5979
+ criterionResult: evaluation.criterionResult,
5980
+ reasons: evaluation.reasons,
5981
+ error: `判据层未达标(criterion-overrun),不得以 done 收尾:${evaluation.reasons.join(';')}`,
5982
+ hint: '唯一例外=用户明确批准并留痕:向用户申请后随本次调用传 criterionApproval={ approvedBy:"user", at, reason, scope };或改用 dsh_workplan_replan(replace) 生成接替子任务只补缺口(已完成产物只读保护)。',
5983
+ };
5984
+ }
5985
+ manualCriterionFields = {
5986
+ criterionResult: evaluation.criterionResult,
5987
+ ...(approval && evaluation.exceptionRecorded ? { criterionException: approval } : {}),
5988
+ };
5989
+ }
5240
5990
  const evidencePatch = {};
5241
5991
  if (args?.verification !== undefined)
5242
5992
  evidencePatch.verification = args.verification;
@@ -5310,6 +6060,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
5310
6060
  options: writtenRow?.options,
5311
6061
  instruction: writtenRow?.instruction,
5312
6062
  instructionSeq: writtenRow?.instructionSeq,
6063
+ // [T7] C1 白名单:仅四态(开始/完成/受阻/待指示)注入一行关键进度;
6064
+ // instructed(指示已下发恢复执行)等过程改判文本置空。标题取自计划
6065
+ // 定义(渲染输入,不进 durable 载荷)。
6066
+ keyProgress: writtenRow?.closure === 'escalated'
6067
+ || (['in_progress', 'done', 'blocked'].includes(String(status)) && writtenRow?.closure !== 'instructed'),
6068
+ title: flattenSubtasks(record.plan).find((entry) => entry.subtask?.id === subtaskId)?.subtask?.title,
5313
6069
  }));
5314
6070
  /*
5315
6071
  * [2.2.9][T3][M4] 人工改判的这条 durable update 消息本身就是「完成已
@@ -5948,7 +6704,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
5948
6704
  return changed;
5949
6705
  }
5950
6706
  /**
5951
- * [2.2.0][T6/O-1a] 完成即时通知的插件兜底投递器(后台轮次专用)。
6707
+ * [2.2.0][T6/O-1a] 完成即时通知的插件兜底投递器。
6708
+ * [T9][用户要求6] 起 wait/async 两模式均启用:部门负责人完成即独立汇报主 Agent。
5952
6709
  *
5953
6710
  * 方案 §2.3 双通道:①协议通道由子 Agent 完成即 `send_message`;②兜底通道
5954
6711
  * 由这里在 `settleFromOutput` 结算成功后立刻写一条纯文本 `user/message`
@@ -5970,27 +6727,315 @@ export function createWorkplanRuntime(ctx, options = {}) {
5970
6727
  const acceptance = Array.isArray(verdict?.acceptance) ? verdict.acceptance : [];
5971
6728
  const passed = acceptance.filter((item) => item?.result === 'pass').length;
5972
6729
  const acceptanceCount = acceptance.length > 0
5973
- ? `验收 ${passed}/${acceptance.length} 通过`
5974
- : '验收记录 0 条(legacy 未提供结构化验收)';
6730
+ ? `验收结论:${passed}/${acceptance.length} 通过`
6731
+ : '验收结论:0 条验收记录(legacy 未提供结构化验收)';
5975
6732
  const elapsedMs = Number.isFinite(Number(row?.startedAt))
5976
6733
  ? Math.max(0, Date.now() - Number(row.startedAt))
5977
6734
  : 0;
5978
6735
  const elapsed = elapsedMs < 1000 ? `${elapsedMs}ms` : `${(elapsedMs / 1000).toFixed(1)}s`;
5979
6736
  const summary = truncate(String(row?.summary ?? '').replace(/\s+/g, ' ').trim(), 160) || '(无摘要)';
5980
- const text = `[dsh-workplan] 子任务 ${String(subtask?.id ?? '')} 已完成并结算:${summary};${acceptanceCount};用时 ${elapsed}`;
6737
+ /*
6738
+ * [T9][用户要求6/D7] 部门负责人完成 → 主 Agent 即时汇报的文本增强。
6739
+ * 行级「完美完成」判据与 deliveryReadiness 的行级口径同源(plan.ts):
6740
+ * verification==='structured' + acceptance 非空 + 每项 result==='pass'
6741
+ * + 无 missingArtifacts。达到才允许声称「完美完成」;未达到仍保留结算
6742
+ * 通知,但必须显式写明缺口,绝不声称完美(D7)。
6743
+ */
6744
+ const rowAcceptance = Array.isArray(row?.acceptance) ? row.acceptance : acceptance;
6745
+ const missingArtifacts = Array.isArray(row?.missingArtifacts) ? row.missingArtifacts : [];
6746
+ const d7Reasons = [];
6747
+ if (row?.verification !== 'structured')
6748
+ d7Reasons.push(`证据等级为 ${String(row?.verification ?? '缺失')}(需 structured)`);
6749
+ if (rowAcceptance.length === 0)
6750
+ d7Reasons.push('未提供验收项(acceptance 为空)');
6751
+ else if (rowAcceptance.some((item) => item?.result !== 'pass'))
6752
+ d7Reasons.push('验收未全部 pass');
6753
+ if (missingArtifacts.length > 0) {
6754
+ d7Reasons.push(`缺少声明产物:${missingArtifacts.slice(0, 5).map((ref) => truncate(String(ref ?? ''), 80)).join('、')}`);
6755
+ }
6756
+ const conclusion = d7Reasons.length === 0
6757
+ ? `完美完成(验收 ${rowAcceptance.length}/${rowAcceptance.length} 全部 pass,structured)`
6758
+ : `未达完美完成判据:${d7Reasons.join(';')}`;
6759
+ const acceptanceLines = rowAcceptance.map((item) => ` - ${truncate(String(item?.criterion ?? '未命名验收项').replace(/\s+/g, ' ').trim(), 80)} → ${String(item?.result ?? '缺失')}`);
6760
+ const needs = Array.isArray(row?.needs) ? row.needs : [];
6761
+ const todoLines = [
6762
+ '待主 Agent 执行事项:',
6763
+ ' - 核验本行证据与验收结论,处置 needs/待指示(如有)',
6764
+ ...needs.map((item) => ` - 跨部门需求:${truncate(needEntryText(item), 300)}`),
6765
+ ...missingArtifacts.map((ref) => ` - 缺失产物待补:${truncate(String(ref ?? ''), 200)}`),
6766
+ ' - 生效建议:插件源码改动需用户手动重启 dsh web 生效,无需安装;Agent 不得自行重启或安装(D8)',
6767
+ ];
6768
+ /*
6769
+ * [3.0.0][用户要求 11] 部门负责人的汇总报告完成后必须直接交给主 Agent:
6770
+ * 完成通知里原样带上 departmentSummary 的 JSON(不经二次概括、不裁剪),
6771
+ * 主 Agent 收到即可直接汇总最终成果(用户要求 12)。
6772
+ */
6773
+ const departmentSummaryBlock = row?.departmentSummary && typeof row.departmentSummary === 'object'
6774
+ ? ['部门汇总报告(JSON,直接交给主 Agent):', JSON.stringify(row.departmentSummary)]
6775
+ : [];
6776
+ const text = truncate([
6777
+ `[dsh-workplan] 子任务 ${String(subtask?.id ?? '')} 已完成并结算:${summary};${acceptanceCount};用时 ${elapsed}`,
6778
+ conclusion,
6779
+ ...(acceptanceLines.length > 0 ? ['逐条验收结论:', ...acceptanceLines] : []),
6780
+ ...departmentSummaryBlock,
6781
+ ...todoLines,
6782
+ ].join('\n'), 4000);
6783
+ const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`;
6784
+ /*
6785
+ * [T9][T5 冻结契约 §1/§4/§5] head→root 完成留痕 kind='completion'(复用
6786
+ * channelJournal 统一入口,不另造通道)。留痕结果与投递结果分开报、绝不
6787
+ * 互相掩盖:留痕写失败只 warn+pushRecordError,不阻塞通知投递与回报标记。
6788
+ */
6789
+ const journalCompletion = (delivery) => {
6790
+ try {
6791
+ const artifacts = (Array.isArray(row?.artifacts) ? row.artifacts : [])
6792
+ .map((artifact) => truncate(String(artifact?.ref ?? ''), 200))
6793
+ .filter(Boolean)
6794
+ .slice(0, 20);
6795
+ const written = channelJournal({
6796
+ planId: String(record?.plan?.planId ?? ''),
6797
+ subtaskId: String(subtask?.id ?? ''),
6798
+ kind: 'completion',
6799
+ from: { sessionId: String(row?.childId || session.id), role: 'head' },
6800
+ to: { sessionId: String(session.id), role: 'root' },
6801
+ body: text,
6802
+ data: { status: 'done', acceptanceCount: passed, artifacts },
6803
+ delivery,
6804
+ });
6805
+ if (!written.result?.ok) {
6806
+ ctx.logger?.warn?.(`dsh-workplan: 完成汇报留痕写入失败 ${String(subtask?.id ?? '')}:${String(written.result?.error ?? 'JOURNAL_WRITE_FAILED')}`);
6807
+ pushRecordError(record, `完成汇报留痕写入失败(通知投递结果=${String(delivery?.status ?? 'unknown')}):${String(written.result?.error ?? 'JOURNAL_WRITE_FAILED')}`);
6808
+ }
6809
+ }
6810
+ catch (error) {
6811
+ ctx.logger?.warn?.(`dsh-workplan: 完成汇报留痕写入失败 ${String(subtask?.id ?? '')}:${error instanceof Error ? error.message : String(error)}`);
6812
+ pushRecordError(record, `完成汇报留痕写入失败(通知投递结果=${String(delivery?.status ?? 'unknown')}):${error instanceof Error ? error.message : String(error)}`);
6813
+ }
6814
+ };
6815
+ /*
6816
+ * [T7] C1/C2/C3:注入正文裁剪为一行关键进度(ID+完成状态+验收计数+
6817
+ * 用时+D7 结论+摘要+needs/缺失产物计数+下一步);逐条验收全文与待办
6818
+ * 清单只保留在 channelJournal completion 留痕(按需通道:journal/reports
6819
+ * 产物/dsh_workplan_status),不再默认注入模型上下文。
6820
+ */
6821
+ /*
6822
+ * [T9][F1/F2] C1 必含字段补齐「子任务标题」;C2 禁止注入回报正文——summary
6823
+ * 只保留在 channelJournal completion 留痕与既有全量 text 里,不再拼进模型
6824
+ * 可见通知;回报正文里的 <!-- WORKPLAN_EVIDENCE... --> 证据块因此不会进入
6825
+ * 上下文(此前 summary 截 160 字仍可能把证据 JSON 头部带进模型可见面)。
6826
+ */
6827
+ const titleText = truncate(String(subtask?.title ?? '').replace(/\s+/g, ' ').trim(), 60);
6828
+ const keyText = capKeyProgressText([
6829
+ `【关键进度】${String(subtask?.id ?? '')} 完成`,
6830
+ ...(titleText ? [`标题:${titleText}`] : []),
6831
+ acceptanceCount,
6832
+ `用时 ${elapsed}`,
6833
+ truncate(conclusion, 160),
6834
+ ...(needs.length > 0 ? [`跨部门需求 ${needs.length} 条待处置(dsh_workplan_handoff list)`] : []),
6835
+ ...(missingArtifacts.length > 0 ? [`缺失产物 ${missingArtifacts.length} 项待补`] : []),
6836
+ '下一步:主 Agent 核验证据与验收后整合(按需:dsh_workplan_status/结算文件)',
6837
+ ].join('|'));
5981
6838
  try {
5982
- appendUserMessage(session, text);
6839
+ appendUserMessage(session, keyText);
5983
6840
  }
5984
6841
  catch (error) {
5985
6842
  ctx.logger?.warn?.(`dsh-workplan: 完成即时通知写入失败 ${String(subtask?.id ?? '')}:`
5986
6843
  + `${error instanceof Error ? error.message : String(error)}`);
6844
+ /* [T9][D6] 投递失败显式留 failed 痕(可重试、不静默),维持 reportPending
6845
+ * 交 finishRound 补齐——「先写通知后记回报、绝不留无证据已回报」不变。 */
6846
+ journalCompletion({ status: 'failed', error: truncate(String(error instanceof Error ? error.message : error), 300) });
5987
6847
  record.reportPending = true;
5988
6848
  return;
5989
6849
  }
5990
- const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`;
6850
+ journalCompletion({ status: 'sent' });
5991
6851
  markReported(record, session, ref, subtask?.id);
5992
6852
  }
6853
+ /**
6854
+ * [T8] 第三层叶子完成即时通知:收件方 = 原分派部门负责人会话。
6855
+ *
6856
+ * 改动前验证结论(2026-11-12):两处叶子结算回调(delegateTool dispatch /
6857
+ * selfEffortTool 自配档接续)此前只把 durable workplan-update 写到根会话;
6858
+ * 负责人会话只能靠宿主 delivery=caller 转达子会话原文,没有插件侧「已结算
6859
+ * 为 done」的即时完成汇报,delegates 条目也没有回报幂等标记。负责人会话
6860
+ * id 的反查判据:根计划部门行 row.childId(executeSubtask 派发时登记,
6861
+ * delegateTool 按 statuses[].childId===负责人会话 id 定位行),与
6862
+ * escalateDelegateLeaf 的 headChildId 同一判据。
6863
+ *
6864
+ * 复用 T5 冻结契约(_t5_channel_20261112/00-contract-v1.md §1/§5):
6865
+ * - 投递:ctx.subagents.sendMessage(根 agent → row.childId 负责人会话,
6866
+ * 宿主 lineage 校验与 instructDelegate/followup 同范式);辅助
6867
+ * user/message 纯文本通知(appendUserMessage 唯一合规写入器,尽力而为,
6868
+ * 不改变投递判定);
6869
+ * - 留痕:channelJournal kind='completion',data={status:'done'},
6870
+ * from 叶子 → to head;
6871
+ * - done-only:只对 delegates[].status==='done' 通知(failed/待指示不产生
6872
+ * 「已完成」措辞);
6873
+ * - 幂等:只有 report.state==='sent' 拦重报(T5 教训:failed 必须可重试);
6874
+ * 先投递、成功才记 sent;
6875
+ * - 兜底:投递失败显式 DELIVERY_FAILED + report.state='failed' +
6876
+ * record.errors 留痕,下一次结算(含其他成员结算)自动补发所有 done
6877
+ * 未 sent 条目——与 reportPending「绝不留无证据的已回报」同一纪律;
6878
+ * 不触碰主行 closure/deriveReportPending,通知失败绝不回滚或阻塞完成判定。
6879
+ * 主计划子任务通知仍 → 根会话(emitSubtaskDoneNotice 不变,T9 范围)。
6880
+ */
6881
+ /*
6882
+ * [T8][race-fix] 并发结算竞态治本(负责人独立审读发现,2026-11-12):
6883
+ * 旧实现在 pending 过滤与 report 标记写回之间隔着 await sendMessage——
6884
+ * 8 名下属同一 tick 完成时,回调 A 在 await 处让出事件循环,回调 B 随即
6885
+ * 把 m1(尚未写 sent 标记)也视为 pending → 重复投递,击穿「8 人=恰 8 条」;
6886
+ * 且各回调用入口捕获的 delegates 快照写回,会互相覆盖对方的结算与标记
6887
+ * (lost update)。治本 = 等价串行化:每 record 一条 promise 链(闭包级
6888
+ * WeakMap,随 record 生命周期回收,无定时器/认领泄漏),入队在同步段完成
6889
+ * (任何 await 之前);链节内「读最新台账 → 投递 → 写标记」整段互斥,
6890
+ * 上一节完全结束才跑下一节;异常在节内捕获,链永不断裂。failed 天然可重试
6891
+ * (无认领,state!=='sent' 即补发)。
6892
+ */
6893
+ const delegateNoticeChains = new WeakMap();
6894
+ const delegateNoticeKey = (item) => `${String(item?.childId ?? '')}|${String(item?.member ?? '')}`;
6895
+ function emitDelegateDoneNotices(record, leaderSession, rootSession, subtaskId) {
6896
+ if (!record || !leaderSession)
6897
+ return Promise.resolve();
6898
+ const prior = delegateNoticeChains.get(record) ?? Promise.resolve();
6899
+ const task = prior
6900
+ .then(() => deliverDelegateDoneNotices(record, leaderSession, rootSession, subtaskId))
6901
+ .catch((error) => {
6902
+ // 意外异常只留痕:链不得断裂,也不得影响结算判定。
6903
+ try {
6904
+ ctx.logger?.warn?.(`dsh-workplan: 第三层完成通知链节异常 ${subtaskId}:${error instanceof Error ? error.message : String(error)}`);
6905
+ record.errors = [...(record.errors ?? []), `${subtaskId} 完成通知链节异常:${truncate(String(error instanceof Error ? error.message : error), 200)}`].slice(-20);
6906
+ }
6907
+ catch { /* 留痕失败不影响主链路 */ }
6908
+ });
6909
+ delegateNoticeChains.set(record, task);
6910
+ return task;
6911
+ }
6912
+ async function deliverDelegateDoneNotices(record, leaderSession, rootSession, subtaskId) {
6913
+ if (!record || !leaderSession)
6914
+ return;
6915
+ const row = Array.isArray(record.statuses)
6916
+ ? record.statuses.find((item) => item?.subtaskId === subtaskId)
6917
+ : null;
6918
+ const delegates = Array.isArray(row?.delegates) ? row.delegates : [];
6919
+ const pending = delegates.filter((item) => item?.status === 'done' && item?.report?.state !== 'sent');
6920
+ if (pending.length === 0)
6921
+ return;
6922
+ const headChildId = typeof row?.childId === 'string' && row.childId ? row.childId : String(leaderSession?.id ?? '');
6923
+ const service = ctx.subagents;
6924
+ /*
6925
+ * 发送者必须是根会话 agent:负责人会话是根会话的直接子会话,宿主 lineage
6926
+ * 校验只允许父→子投递(instructDelegate 同范式)。结算回调闭包里的 agent
6927
+ * 是负责人自己(delegateTool 调用者),不能作发送者。解析失败 fail-closed
6928
+ * 记 failed,绝不静默跳过。
6929
+ */
6930
+ const rootAgent = resolveLiveAgent(ctx, rootSession?.id);
6931
+ const rawTurn = Number(state.activeTurns?.get?.(leaderSession?.id) ?? NaN);
6932
+ const turn = Number.isFinite(rawTurn) ? rawTurn : null;
6933
+ const ref = `${record?.plan?.planId ?? 'plan'}:${record?.dispatchedAt ?? 0}`;
6934
+ const marks = new Map();
6935
+ for (const member of pending) {
6936
+ const startedAt = Number(member?.startedAt);
6937
+ const finishedAt = Number(member?.finishedAt);
6938
+ const elapsedMs = Number.isFinite(startedAt) && Number.isFinite(finishedAt) ? Math.max(0, finishedAt - startedAt) : 0;
6939
+ const elapsed = elapsedMs < 1000 ? `${elapsedMs}ms` : `${(elapsedMs / 1000).toFixed(1)}s`;
6940
+ const summary = truncate(String(member?.summary ?? '').replace(/\s+/g, ' ').trim(), 300) || '(无摘要)';
6941
+ const body = truncate([
6942
+ `【第三层完成汇报|${String(member?.member ?? '')} → 部门负责人】`,
6943
+ `子任务 ${subtaskId} 的第三层成员 ${String(member?.member ?? '')} 已完成并结算(status=done)。`,
6944
+ `摘要:${summary}`,
6945
+ `用时:${elapsed}`,
6946
+ '请核验并汇总该成员产物;收齐后写最终结果块。',
6947
+ ].join('\n'), 4000);
6948
+ const deliveryStartedAt = Date.now();
6949
+ let messageId = '';
6950
+ let deliveryError = '';
6951
+ if (!headChildId)
6952
+ deliveryError = '部门行没有登记负责人会话(childId 缺失),无法投递完成汇报';
6953
+ else if (!service || typeof service.sendMessage !== 'function')
6954
+ deliveryError = '当前部署没有可用的 subagent 服务(NO_SUBAGENT_SERVICE),无法投递完成汇报';
6955
+ else if (!rootAgent)
6956
+ deliveryError = '根会话 agent 解析失败,无法向负责人会话投递完成汇报';
6957
+ else {
6958
+ try {
6959
+ messageId = String(await service.sendMessage(rootAgent, headChildId, [{ type: 'text', text: body }], { signal: new AbortController().signal }) ?? ''); // [T11] 缺陷②:完成汇报携带有效 signal,消除 throwIfAborted
6960
+ }
6961
+ catch (error) {
6962
+ deliveryError = truncate(error instanceof Error ? error.message : String(error), 500);
6963
+ }
6964
+ }
6965
+ const delivery = deliveryError ? 'failed' : 'sent';
6966
+ const journal = channelJournal({
6967
+ planId: String(record?.plan?.planId ?? ''),
6968
+ subtaskId,
6969
+ kind: 'completion',
6970
+ from: { sessionId: String(member?.childId ?? ''), role: 'expert', member: String(member?.member ?? '') },
6971
+ to: { sessionId: headChildId, role: 'head' },
6972
+ body,
6973
+ data: { status: 'done' },
6974
+ delivery: { status: delivery, ...(messageId ? { messageId } : {}), latencyMs: Date.now() - deliveryStartedAt, ...(deliveryError ? { code: 'DELIVERY_FAILED', error: deliveryError } : {}) },
6975
+ });
6976
+ // 契约 §4:留痕写失败本身也要显式报 JOURNAL_WRITE_FAILED,且不得掩盖投递结果。
6977
+ if (!journal.result.ok) {
6978
+ record.errors = [...(record.errors ?? []), `${subtaskId}/${String(member?.member ?? '')} 完成留痕写入失败 JOURNAL_WRITE_FAILED:${truncate(String(journal.result.error ?? ''), 200)}`].slice(-20);
6979
+ }
6980
+ // 辅助用户可见纯文本通知(user/message 通道,尽力而为):不替代 sendMessage 投递,不改变投递判定。
6981
+ if (typeof leaderSession.append === 'function') {
6982
+ try {
6983
+ appendUserMessage(leaderSession, `[dsh-workplan] 第三层成员 ${String(member?.member ?? '')}(子任务 ${subtaskId})已完成并结算:${truncate(summary, 160)};用时 ${elapsed}。请核验并汇总该成员产物。`);
6984
+ }
6985
+ catch (error) {
6986
+ ctx.logger?.warn?.(`dsh-workplan: 第三层完成纯文本通知写入失败 ${subtaskId}/${String(member?.member ?? '')}:${error instanceof Error ? error.message : String(error)}`);
6987
+ }
6988
+ }
6989
+ if (deliveryError) {
6990
+ ctx.logger?.warn?.(`dsh-workplan: 第三层完成即时通知投递失败 ${subtaskId}/${String(member?.member ?? '')}:DELIVERY_FAILED ${deliveryError}`);
6991
+ record.errors = [...(record.errors ?? []), `${subtaskId}/${String(member?.member ?? '')} 完成即时通知投递失败 DELIVERY_FAILED(report.state=failed,待兜底补发):${truncate(deliveryError, 200)}`].slice(-20);
6992
+ }
6993
+ marks.set(delegateNoticeKey(member), { state: delivery, at: Date.now(), ref, turn });
6994
+ }
6995
+ /*
6996
+ * 幂等标记写回台账(applyStatus 唯一写入口 + delegates.report 消毒)并
6997
+ * durable 回放到根会话:刷新/重启后「已通知」不丢、重复结算不重报。
6998
+ * 标记写失败只留痕:下次结算按 state!=='sent' 补发,不影响结算判定。
6999
+ */
7000
+ try {
7001
+ // [T8][race-fix] 写时重读当前行+按键贴标记:不用入口快照,对
7002
+ // escalate/instruct 等非结算路径的并发写也免疫(不覆盖请示/指示子对象)。
7003
+ const currentRow = Array.isArray(record.statuses)
7004
+ ? record.statuses.find((item) => item?.subtaskId === subtaskId)
7005
+ : null;
7006
+ const currentDelegates = Array.isArray(currentRow?.delegates) ? currentRow.delegates : delegates;
7007
+ const list = currentDelegates.map((item) => {
7008
+ const mark = marks.get(delegateNoticeKey(item));
7009
+ return mark ? { ...item, report: mark } : item;
7010
+ });
7011
+ const revision = Number(currentRow?.revision ?? row?.revision ?? 0) + 1;
7012
+ record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'system' });
7013
+ record.updatedAt = Date.now();
7014
+ const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
7015
+ appendUserMessage(rootSession, buildUpdateMessage({
7016
+ planId: record?.plan?.planId,
7017
+ subtaskId,
7018
+ status: written?.status ?? row?.status,
7019
+ delegates: written?.delegates ?? list,
7020
+ revision,
7021
+ note: '第三层成员完成即时通知已回报原分派负责人会话(delegates[].report)',
7022
+ }));
7023
+ }
7024
+ catch (error) {
7025
+ record.errors = [...(record.errors ?? []), `${subtaskId} delegates[].report 标记写入失败:${truncate(String(error instanceof Error ? error.message : error), 200)}`].slice(-20);
7026
+ }
7027
+ }
5993
7028
  function finishRound(record, session) {
7029
+ /*
7030
+ * [2.5.5][T10] 结算前先合并落盘缓冲的台账事件:本轮最后一批非关键更新
7031
+ * 不能因为「后面没有别的消息」而滞留内存(刷新/重启即丢)。
7032
+ */
7033
+ try {
7034
+ flushPendingWorkplanUpdates(session);
7035
+ }
7036
+ catch (error) {
7037
+ ctx.logger?.warn?.(`dsh-workplan: 合并台账落盘失败:${error instanceof Error ? error.message : String(error)}`);
7038
+ }
5994
7039
  const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`;
5995
7040
  if (!record.resultWritten) {
5996
7041
  /*
@@ -6035,10 +7080,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
6035
7080
  }
6036
7081
  else {
6037
7082
  /*
6038
- * 旧日志 / 上一次写失败的重试:结果消息已在,但仍有 done 行没到
6039
- * reported。幂等补齐,不重复追加消息。
7083
+ * [2.2.9][T3][M4] 旧日志 / 上一次写失败的重试:结果消息已在,但仍有
7084
+ * 本轮完成、未回报的 done 行(closure==='done')。幂等补齐,不重复追加
7085
+ * 消息。判据与 deriveReportPending(runtime.ts:245 严格口径
7086
+ * `status==='done' && closure==='done'`)收敛为同一套:旧日志
7087
+ * closure=null 的历史 done 行本来就已回报过,不在此补标。
6040
7088
  */
6041
- const pending = (record.statuses ?? []).some((item) => item?.status === 'done' && item?.closure !== 'reported');
7089
+ const pending = (record.statuses ?? []).some((item) => item?.status === 'done' && item?.closure === 'done');
6042
7090
  if (pending) {
6043
7091
  markReported(record, session, ref);
6044
7092
  // [2.2.9][T3][M4] 镜像按派生回填:部分标记失败时不谎报「已回报」。
@@ -6320,6 +7368,205 @@ export function createWorkplanRuntime(ctx, options = {}) {
6320
7368
  message: '插件核验通过:三阶段证据齐全、验证全部通过。现在把同一份 phases 写进结果块并提交。',
6321
7369
  };
6322
7370
  }
7371
+ /**
7372
+ * [2.5.6] 第三层叶子归属反查(叶子↔负责人双向请示/指示通道的读侧)。
7373
+ *
7374
+ * 叶子会话的父链是「叶子 → 部门负责人 → 根会话」,计划只挂在根会话上。
7375
+ * 沿父链向上(≤3 跳,防环)找到第一个有计划记录的祖先,再按 delegate
7376
+ * 登记(行 delegates[].childId)定位叶子所属的部门行与成员条目——与
7377
+ * selfEffortTool 同一判据,不信任自报 subtaskId。找不到计划或 childId
7378
+ * 未登记时返回 null,由调用方维持原错误语义。
7379
+ */
7380
+ function findDelegateLeafContext(childSession) {
7381
+ let ancestorId = childSession?.header?.parentSession;
7382
+ for (let hop = 0; hop < 3 && typeof ancestorId === 'string' && ancestorId; hop += 1) {
7383
+ let rec = state.records.get(ancestorId);
7384
+ if (!rec?.plan) {
7385
+ const sess = ctx.sessions?.get?.(ancestorId);
7386
+ if (sess) {
7387
+ try {
7388
+ rec = reconstructFromSession(sess);
7389
+ }
7390
+ catch (error) {
7391
+ pushRecordError({ errors: [] }, error);
7392
+ }
7393
+ }
7394
+ }
7395
+ if (rec?.plan) {
7396
+ const deptRow = (rec.statuses ?? []).find((item) => Array.isArray(item?.delegates)
7397
+ && item.delegates.some((d) => d?.childId === childSession.id));
7398
+ if (!deptRow)
7399
+ return null;
7400
+ const member = deptRow.delegates.find((d) => d?.childId === childSession.id);
7401
+ return { record: rec, row: deptRow, member, ownerId: ancestorId };
7402
+ }
7403
+ const sess = ctx.sessions?.get?.(ancestorId);
7404
+ ancestorId = sess?.header?.parentSession;
7405
+ }
7406
+ return null;
7407
+ }
7408
+ /**
7409
+ * [T5-channel][契约v1 §1/§2] 通道留痕统一入口:补齐 v/id/ts 后交
7410
+ * appendDeptMessage(fail-closed 校验+显式 JOURNAL_WRITE_FAILED)。返回
7411
+ * 消息 id 与写盘结果,供调用方把「投递结果」与「留痕结果」两者都报,
7412
+ * 绝不互相掩盖(契约 §4)。
7413
+ */
7414
+ function channelJournal(fields) {
7415
+ const message = { v: 1, id: makeDeptMessageId(), ts: Date.now(), ...fields };
7416
+ const written = appendDeptMessage(message);
7417
+ return { id: message.id, result: written };
7418
+ }
7419
+ /*
7420
+ * [T6][契约v1 §3/§5] 叶子开工预估的读侧消毒(与 plan.ts sanitizeDelegateEstimate
7421
+ * 同一判据,G1 双侧接线):declaredMinutes 正整数分钟(Number.isInteger 且
7422
+ * 1..10080,不做字符串强转)、at 正数、delivery 枚举 sent/failed;reason ≤300、
7423
+ * messageId ≤200 均可选。任一必填非法 ⇒ 整个 estimate 视为未登记(null)。
7424
+ * 重派读档门禁与 self_effort 幂等判据据此判定「预估已登记」。
7425
+ */
7426
+ function sanitizeLeafEstimate(value) {
7427
+ if (!value || typeof value !== 'object' || Array.isArray(value))
7428
+ return null;
7429
+ const minutes = value.declaredMinutes;
7430
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > 10080)
7431
+ return null;
7432
+ const at = Number(value.at);
7433
+ if (!Number.isFinite(at) || at <= 0)
7434
+ return null;
7435
+ if (value.delivery !== 'sent' && value.delivery !== 'failed')
7436
+ return null;
7437
+ return {
7438
+ declaredMinutes: minutes,
7439
+ ...(typeof value.reason === 'string' && value.reason.trim() ? { reason: truncate(value.reason.trim(), 300) } : {}),
7440
+ at,
7441
+ ...(typeof value.messageId === 'string' && value.messageId ? { messageId: truncate(value.messageId, 200) } : {}),
7442
+ delivery: value.delivery,
7443
+ };
7444
+ }
7445
+ /**
7446
+ * [T5-channel][契约v1 §3a] 第三层叶子的请示落档(写侧):question/options/
7447
+ * needs 经 ctx.subagents.sendMessage 投给部门负责人会话(row.childId),写
7448
+ * kind='escalation' 留痕,经 applyStatus 把 delegates[i].escalation 子对象
7449
+ * 持久化并发 durable update 到根会话。部门行本身的 status/closure 不变——
7450
+ * 问题等负责人答,不是等主 Agent。announceSubtaskInterrupt 仅作辅助用户
7451
+ * 可见通知,不替代给负责人的 sendMessage 投递。
7452
+ */
7453
+ async function escalateDelegateLeaf(agent, leaf, args) {
7454
+ const { record, row, member, ownerId } = leaf;
7455
+ if (member.status === 'done') {
7456
+ return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, member: member.member, error: '该成员已结算,不能再提交请示' };
7457
+ }
7458
+ const question = truncate(String(args?.question ?? '').trim(), MAX_QUESTION_CHARS);
7459
+ if (!question) {
7460
+ return { ok: false, code: 'INVALID_QUESTION', subtaskId: row.subtaskId, member: member.member, error: 'question 必填:写清需要部门负责人决定的单个问题' };
7461
+ }
7462
+ // [T5-channel][D6] 投递失败的请示允许重试:delivery='failed' 不走幂等分支,
7463
+ // 重新投递并覆盖留档;只有已成功送达(sent)的请示才拦截重复提交。
7464
+ if (member.escalation && member.escalation.delivery !== 'failed') {
7465
+ return {
7466
+ ok: true,
7467
+ alreadyEscalated: true,
7468
+ routedTo: 'head',
7469
+ planId: record.plan.planId,
7470
+ subtaskId: row.subtaskId,
7471
+ member: member.member,
7472
+ question: member.escalation.question ?? question,
7473
+ message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待部门负责人指示。',
7474
+ };
7475
+ }
7476
+ const options = (Array.isArray(args?.options) ? args.options : [])
7477
+ .slice(0, MAX_ESCALATION_OPTIONS)
7478
+ .map((item) => truncate(needEntryText(item), 300))
7479
+ .filter(Boolean);
7480
+ const needs = (Array.isArray(args?.needs) ? args.needs : [])
7481
+ .slice(0, 10)
7482
+ .map((item) => truncate(needEntryText(item), 300))
7483
+ .filter(Boolean);
7484
+ const headChildId = typeof row.childId === 'string' ? row.childId : '';
7485
+ if (!headChildId) {
7486
+ return { ok: false, code: 'NO_SUBTASK', subtaskId: row.subtaskId, member: member.member, error: '部门行没有登记负责人会话(childId 缺失),无法投递请示' };
7487
+ }
7488
+ const service = ctx.subagents;
7489
+ if (!service || typeof service.sendMessage !== 'function') {
7490
+ return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId: row.subtaskId, member: member.member, error: '当前部署没有可用的 subagent 服务,无法投递请示' };
7491
+ }
7492
+ const now = Date.now();
7493
+ const body = truncate([
7494
+ `【第三层请示|${member.member} → 部门负责人】`,
7495
+ `子任务 ${row.subtaskId} 的第三层成员 ${member.member} 执行中请求指示:`,
7496
+ question,
7497
+ options.length ? `可选方向:${options.join(';')}` : '',
7498
+ needs.length ? `跨部门需求:${needs.join(';')}` : '',
7499
+ `请答复:dsh_workplan_instruct(subtaskId=${row.subtaskId},member=${member.member},instruction=你的决定)。答复前该成员停止推进、只做只读核对。`,
7500
+ ].filter(Boolean).join('\n'), 4000);
7501
+ const startedAt = Date.now();
7502
+ let messageId = '';
7503
+ let deliveryError = '';
7504
+ try {
7505
+ messageId = String(await service.sendMessage(agent, headChildId, [{ type: 'text', text: body }], { signal: new AbortController().signal }) ?? ''); // [T11] 缺陷②:请示上报携带有效 signal,消除 throwIfAborted
7506
+ }
7507
+ catch (error) {
7508
+ deliveryError = truncate(error instanceof Error ? error.message : String(error), 500);
7509
+ }
7510
+ const latencyMs = Date.now() - startedAt;
7511
+ const delivery = deliveryError ? 'failed' : 'sent';
7512
+ const journal = channelJournal({
7513
+ planId: record.plan.planId,
7514
+ subtaskId: row.subtaskId,
7515
+ kind: 'escalation',
7516
+ from: { sessionId: String(agent?.session?.id ?? ''), role: 'expert', member: member.member },
7517
+ to: { sessionId: headChildId, role: 'head' },
7518
+ body,
7519
+ data: { options, needs },
7520
+ delivery: { status: delivery, ...(messageId ? { messageId } : {}), latencyMs, ...(deliveryError ? { code: 'DELIVERY_FAILED', error: deliveryError } : {}) },
7521
+ });
7522
+ const journalInfo = journal.result.ok ? {} : { journal: { ok: false, code: journal.result.code, error: journal.result.error } };
7523
+ const revision = Number(row.revision ?? 0) + 1;
7524
+ const delegates = (Array.isArray(row.delegates) ? row.delegates : []).map((item) => (item?.childId === member.childId
7525
+ ? { ...item, escalation: { question, options, needs, at: now, ...(messageId ? { messageId } : {}), delivery } }
7526
+ : item));
7527
+ record.statuses = applyStatus(record.statuses, row.subtaskId, { delegates, revision, updatedBy: 'child' });
7528
+ record.updatedAt = now;
7529
+ try {
7530
+ const written = record.statuses.find((item) => item?.subtaskId === row.subtaskId);
7531
+ const ownerSession = ctx.sessions?.get?.(ownerId);
7532
+ // durable 回放挂在计划所有者(根会话)上:刷新/重启后请示不丢。
7533
+ appendUserMessage(ownerSession, buildUpdateMessage({
7534
+ planId: record.plan.planId,
7535
+ subtaskId: row.subtaskId,
7536
+ status: written?.status ?? row.status,
7537
+ delegates: written?.delegates ?? delegates,
7538
+ revision,
7539
+ note: `第三层成员 ${member.member} 提交请示(待指示)`,
7540
+ // [T7] C1 白名单:第三层请示=待指示事件,注入一行关键进度(含阻塞原因)。
7541
+ keyProgress: true,
7542
+ stateLabel: '待指示(第三层)',
7543
+ question,
7544
+ title: flattenSubtasks(record.plan).find((entry) => entry.subtask?.id === row.subtaskId)?.subtask?.title,
7545
+ }));
7546
+ // 辅助用户可见通知(不替代 sendMessage 投递):负责人当下看到谁在等谁。
7547
+ const leader = ctx.sessions?.get?.(headChildId);
7548
+ announceSubtaskInterrupt(record, leader, row.subtaskId, `第三层成员 ${member.member} 请求指示:${truncate(question, 160)};性质:等待部门负责人拍板,不是执行失败;处理:负责人用 dsh_workplan_instruct(subtaskId=${row.subtaskId},member=${member.member})答复后,该成员恢复执行。`);
7549
+ }
7550
+ catch (error) {
7551
+ pushRecordError(record, error);
7552
+ }
7553
+ if (deliveryError) {
7554
+ return { ok: false, code: 'DELIVERY_FAILED', subtaskId: row.subtaskId, member: member.member, error: deliveryError, ...journalInfo };
7555
+ }
7556
+ return {
7557
+ ok: true,
7558
+ routedTo: 'head',
7559
+ planId: record.plan.planId,
7560
+ subtaskId: row.subtaskId,
7561
+ member: member.member,
7562
+ messageId,
7563
+ latencyMs,
7564
+ question,
7565
+ revision,
7566
+ ...journalInfo,
7567
+ message: '已上报部门负责人。请立即停止推进,只允许做只读核对;等待指示期间不要开始新的写入或大改。',
7568
+ };
7569
+ }
6323
7570
  /**
6324
7571
  * [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
6325
7572
  *
@@ -6353,15 +7600,25 @@ export function createWorkplanRuntime(ctx, options = {}) {
6353
7600
  }
6354
7601
  }
6355
7602
  }
6356
- if (!record?.plan) {
6357
- return {
6358
- ok: false,
6359
- code: 'NO_PLAN',
6360
- error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
6361
- };
6362
- }
6363
- const row = (record.statuses ?? []).find((item) => item?.childId === childSession.id);
6364
- if (!row) {
7603
+ const row = (record?.statuses ?? []).find((item) => item?.childId === childSession.id);
7604
+ /*
7605
+ * [2.5.6] 第三层叶子兜底(治本):叶子的直接父会话是部门负责人,负责人
7606
+ * 自己没有计划记录——旧实现在这里直接 NO_PLAN,叶子永远无法请示。现在
7607
+ * 经 delegate 登记(根计划行 delegates[].childId)反查所属部门行,把
7608
+ * 「待指示」落在该行的第三层台账上,并通知负责人。第一层(父会话即计划
7609
+ * 所有者)路径逐字节不变。
7610
+ */
7611
+ if (!record?.plan || !row) {
7612
+ const leaf = findDelegateLeafContext(childSession);
7613
+ if (leaf)
7614
+ return await escalateDelegateLeaf(agent, leaf, args);
7615
+ if (!record?.plan) {
7616
+ return {
7617
+ ok: false,
7618
+ code: 'NO_PLAN',
7619
+ error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
7620
+ };
7621
+ }
6365
7622
  return {
6366
7623
  ok: false,
6367
7624
  code: 'NO_SUBTASK',
@@ -6430,6 +7687,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
6430
7687
  escalatedAt: now,
6431
7688
  escalationSeq: revision,
6432
7689
  revision,
7690
+ // [T7] C1 白名单:第一层请示=待指示事件,注入一行关键进度。
7691
+ keyProgress: true,
7692
+ title: flattenSubtasks(record.plan).find((entry) => entry.subtask?.id === row.subtaskId)?.subtask?.title,
6433
7693
  }));
6434
7694
  // [2.2.7] 中断即报:请示同样要让用户当下看到「有人卡在哪、等什么决定」,
6435
7695
  // 结构化 update 消息是给回放/主 Agent 的,这条纯文本是给用户的。
@@ -6573,21 +7833,51 @@ export function createWorkplanRuntime(ctx, options = {}) {
6573
7833
  /**
6574
7834
  * [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
6575
7835
  *
6576
- * 只有根会话能调用;只接受 `closure:'escalated'` 的行;只投递给本会话直接
6577
- * 子会话。投递失败时不改状态(不伪造成「已指示」),把错误原样交给主 Agent。
7836
+ * [T5-channel][契约v1 §3b] 放权为「目标子会话的直接父会话」可调用:根会话
7837
+ * 答复第一层部门行(行为逐字节不变);部门负责人答复自己派出的第三层叶子
7838
+ * (严格 lineage:调用者必须是该部门行的 childId,目标必须登记在本行
7839
+ * delegates 且在调用者的直接子会话 catalog 里)。非直系(跨行、跨层、无关
7840
+ * 会话)一律拒绝。根路径只接受 `closure:'escalated'` 的行;负责人路径按
7841
+ * member/sessionId 指定目标。投递失败时不改状态(不伪造成「已指示」),
7842
+ * 把错误原样交给调用方。
6578
7843
  */
6579
7844
  async function instructSubtask(agent, args, signal, existingRecord) {
6580
7845
  const session = agent?.session;
6581
7846
  if (!session)
6582
7847
  return { ok: false, code: 'NO_SESSION', error: '只能在会话内下发指示' };
6583
- if (!isRootSession(session))
6584
- return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' };
6585
- let record = existingRecord ?? state.records.get(session.id);
6586
- if (!record?.plan)
6587
- record = reconstructFromSession(session, args?.planId);
6588
- record = adoptRequestedPlan(session, record, args?.planId);
6589
- if (!record?.plan)
6590
- return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' };
7848
+ const callerIsRoot = isRootSession(session);
7849
+ let record;
7850
+ if (callerIsRoot) {
7851
+ record = existingRecord ?? state.records.get(session.id);
7852
+ if (!record?.plan)
7853
+ record = reconstructFromSession(session, args?.planId);
7854
+ record = adoptRequestedPlan(session, record, args?.planId);
7855
+ if (!record?.plan)
7856
+ return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' };
7857
+ }
7858
+ else {
7859
+ /*
7860
+ * [T5-channel][契约v1 §3b] 负责人答复自己的叶子:先沿父链反查根计划,
7861
+ * 再判负责人身份(根记录中 statuses[].childId === session.id 的行)。
7862
+ * 既非根也非登记负责人 ⇒ 维持 NOT_ROOT;subtaskId 可省略(默认自己的
7863
+ * 行),给了必须等于自己的行,否则 UNKNOWN_SUBTASK。目标登记/catalog/
7864
+ * 父链的严格 lineage 在 instructDelegateLeaf 内硬校验。
7865
+ */
7866
+ record = findAncestorPlanRecord(session);
7867
+ if (!record?.plan)
7868
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' };
7869
+ if (typeof args?.planId === 'string' && args.planId && record.plan.planId !== args.planId) {
7870
+ return { ok: false, code: 'NO_PLAN', error: `指定计划 ${args.planId} 与当前会话关联的计划不一致` };
7871
+ }
7872
+ const headRow = (record.statuses ?? []).find((item) => item?.childId === session.id);
7873
+ if (!headRow)
7874
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' };
7875
+ const requested = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : '';
7876
+ if (requested && requested !== String(headRow.subtaskId)) {
7877
+ return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId: requested, error: `未知子任务:${requested}(负责人只能答复自己的部门行 ${String(headRow.subtaskId)})` };
7878
+ }
7879
+ return instructDelegateLeaf(agent, args, signal, record, headRow);
7880
+ }
6591
7881
  clearAutoResumeTimer(record, 'manual-instruct');
6592
7882
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : '';
6593
7883
  if (!subtaskId)
@@ -6698,14 +7988,316 @@ export function createWorkplanRuntime(ctx, options = {}) {
6698
7988
  };
6699
7989
  }
6700
7990
  /**
6701
- * [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
6702
- *
6703
- * 单独一层包装而不是让 host 直接调内部函数:`escalateSubtask` 需要
6704
- * `record`/`ctx` 闭包,host 侧只拿得到 runtime 的公开面;这一层也是
6705
- * 唯一被 `dsh_workplan_escalate` 触发的地方,便于测试替身注入。
7991
+ * [2.5.6] 沿父链向上(≤3 跳,防环)找到第一个有计划记录的祖先会话。
7992
+ * 负责人 instruct 与叶子 escalate 共用同一父链判据;不信任自报 planId。
6706
7993
  */
6707
- async function escalateTool(agent, args) {
6708
- return escalateSubtask(agent, args);
7994
+ function findAncestorPlanRecord(session) {
7995
+ let ancestorId = session?.header?.parentSession;
7996
+ for (let hop = 0; hop < 3 && typeof ancestorId === 'string' && ancestorId; hop += 1) {
7997
+ let rec = state.records.get(ancestorId);
7998
+ if (!rec?.plan) {
7999
+ const sess = ctx.sessions?.get?.(ancestorId);
8000
+ if (sess) {
8001
+ try {
8002
+ rec = reconstructFromSession(sess);
8003
+ }
8004
+ catch (error) {
8005
+ pushRecordError({ errors: [] }, error);
8006
+ }
8007
+ }
8008
+ }
8009
+ if (rec?.plan)
8010
+ return rec;
8011
+ const sess = ctx.sessions?.get?.(ancestorId);
8012
+ ancestorId = sess?.header?.parentSession;
8013
+ }
8014
+ return null;
8015
+ }
8016
+ /**
8017
+ * [T5-channel][契约v1 §3b] 负责人 → 第三层叶子的指示投递(instruct 的叶子分支)。
8018
+ *
8019
+ * 负责人身份与行级 lineage 已在 instructSubtask 校验(调用者 == 部门行
8020
+ * childId);这里按 member/sessionId(至少其一)定位本行 delegates 登记的
8021
+ * 目标,再校验 spawnedChildIds 直接子会话证据+父链双保险。投递复用
8022
+ * ctx.subagents.sendMessage 既有通道(与 follow-up/延期告知同一条),不新建
8023
+ * 队列;写 kind='instruction' 留痕(data.inReplyTo 指向被答复的请示);
8024
+ * 持久化 delegates[i].lastInstruction 并清 escalation;负责人行 closure
8025
+ * 不变。投递失败不改状态(不伪造成「已指示」)。
8026
+ */
8027
+ async function instructDelegateLeaf(agent, args, signal, record, current) {
8028
+ const session = agent.session;
8029
+ const subtaskId = String(current.subtaskId);
8030
+ const memberName = typeof args?.member === 'string' ? args.member.trim() : '';
8031
+ const targetSessionId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : '';
8032
+ if (!memberName && !targetSessionId) {
8033
+ return { ok: false, code: 'MISSING_TARGET', subtaskId, error: 'member 与 sessionId 至少提供其一:指定要答复的第三层成员' };
8034
+ }
8035
+ const delegates = Array.isArray(current.delegates) ? current.delegates : [];
8036
+ const target = memberName
8037
+ ? delegates.find((item) => item?.member === memberName)
8038
+ : delegates.find((item) => item?.childId === targetSessionId);
8039
+ if (!target) {
8040
+ return memberName
8041
+ ? { ok: false, code: 'UNKNOWN_MEMBER', subtaskId, member: memberName, error: `成员 ${memberName} 未登记在本行 delegates[]` }
8042
+ : { ok: false, code: 'NOT_DELEGATE', subtaskId, sessionId: targetSessionId, error: `${targetSessionId} 不是本行登记的第三层成员(跨部门/未登记目标一律拒绝)` };
8043
+ }
8044
+ if (memberName && targetSessionId && target.childId !== targetSessionId) {
8045
+ return { ok: false, code: 'NOT_DELEGATE', subtaskId, error: 'member 与 sessionId 指向不同成员,拒绝投递' };
8046
+ }
8047
+ const childId = typeof target.childId === 'string' ? target.childId : '';
8048
+ if (!childId) {
8049
+ return { ok: false, code: 'NOT_DELEGATE', subtaskId, member: target.member, error: '该成员没有登记子会话 childId,无法投递指示' };
8050
+ }
8051
+ if (!spawnedChildIds(session).has(childId)) {
8052
+ return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递` };
8053
+ }
8054
+ const targetSession = ctx.sessions?.get?.(childId);
8055
+ if (targetSession?.header?.parentSession && targetSession.header.parentSession !== session.id) {
8056
+ return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: '严格血缘校验失败:目标子会话的直接父会话不是调用者,拒绝投递' };
8057
+ }
8058
+ const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS);
8059
+ if (!instruction)
8060
+ return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要成员执行的决定' };
8061
+ const service = ctx.subagents;
8062
+ if (!service || typeof service.sendMessage !== 'function') {
8063
+ return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId, error: '当前部署没有可用的 subagent 服务,无法投递指示' };
8064
+ }
8065
+ // inReplyTo(可选):从留痕回放找该成员最近一条请示消息 id;读失败不阻断投递。
8066
+ let inReplyTo = '';
8067
+ try {
8068
+ const prior = readDeptMessages(record.plan.planId, { kind: 'escalation' });
8069
+ if (prior.ok) {
8070
+ const match = [...prior.messages].reverse().find((m) => m.from?.sessionId === childId && m.subtaskId === subtaskId);
8071
+ inReplyTo = match?.id ?? '';
8072
+ }
8073
+ }
8074
+ catch { /* 留痕读失败不阻断投递;inReplyTo 可选 */ }
8075
+ const body = truncate([
8076
+ '【部门负责人指示(对应你此前提交的请示)】',
8077
+ instruction,
8078
+ '',
8079
+ '请按上述指示继续原任务。若仍受阻,先调用 dsh_workplan_escalate 再次上报,然后停止推进等待指示;不要自行猜测未被回答的部分。',
8080
+ ].join('\n'), 4000);
8081
+ const startedAt = Date.now();
8082
+ let messageId = '';
8083
+ try {
8084
+ messageId = String(await service.sendMessage(agent, childId, [{ type: 'text', text: body }], { signal }) ?? '');
8085
+ }
8086
+ catch (error) {
8087
+ const errorText = truncate(error instanceof Error ? error.message : String(error), 500);
8088
+ const failedJournal = channelJournal({
8089
+ planId: record.plan.planId,
8090
+ subtaskId,
8091
+ kind: 'instruction',
8092
+ from: { sessionId: session.id, role: 'head' },
8093
+ to: { sessionId: childId, role: 'expert', member: target.member },
8094
+ body,
8095
+ ...(inReplyTo ? { data: { inReplyTo } } : {}),
8096
+ delivery: { status: 'failed', code: 'DELIVERY_FAILED', error: errorText, latencyMs: Date.now() - startedAt },
8097
+ });
8098
+ return {
8099
+ ok: false,
8100
+ code: 'DELIVERY_FAILED',
8101
+ subtaskId,
8102
+ member: target.member,
8103
+ sessionId: childId,
8104
+ error: errorText,
8105
+ hint: '状态未改变,该成员仍是待指示;可重试投递。',
8106
+ ...(failedJournal.result.ok ? {} : { journal: { ok: false, code: failedJournal.result.code, error: failedJournal.result.error } }),
8107
+ };
8108
+ }
8109
+ const latencyMs = Date.now() - startedAt;
8110
+ const now = Date.now();
8111
+ const journal = channelJournal({
8112
+ planId: record.plan.planId,
8113
+ subtaskId,
8114
+ kind: 'instruction',
8115
+ from: { sessionId: session.id, role: 'head' },
8116
+ to: { sessionId: childId, role: 'expert', member: target.member },
8117
+ body,
8118
+ ...(inReplyTo ? { data: { inReplyTo } } : {}),
8119
+ delivery: { status: 'sent', ...(messageId ? { messageId } : {}), latencyMs },
8120
+ });
8121
+ const revision = Number(current.revision ?? 0) + 1;
8122
+ const delegatesList = (Array.isArray(current.delegates) ? current.delegates : []).map((item) => (item?.childId === childId
8123
+ ? {
8124
+ ...item,
8125
+ status: 'running',
8126
+ closure: 'instructed',
8127
+ lastInstruction: { text: instruction, at: now, ...(messageId ? { messageId } : {}), delivery: 'sent' },
8128
+ escalation: undefined,
8129
+ instructionSeq: revision,
8130
+ instructionOverdue: false,
8131
+ ackedAt: null,
8132
+ blockedKind: null,
8133
+ error: null,
8134
+ finishedAt: null,
8135
+ }
8136
+ : item));
8137
+ record.statuses = applyStatus(record.statuses, subtaskId, { delegates: delegatesList, revision, updatedBy: 'agent' });
8138
+ record.updatedAt = now;
8139
+ try {
8140
+ const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
8141
+ const update = buildUpdateMessage({
8142
+ planId: record.plan.planId,
8143
+ subtaskId,
8144
+ status: written?.status ?? current.status,
8145
+ delegates: written?.delegates ?? delegatesList,
8146
+ revision,
8147
+ note: `负责人已向第三层成员 ${target.member} 下发指示`,
8148
+ });
8149
+ // durable 回放挂在计划所有者(根会话)上;负责人会话留一份供其回放核对。
8150
+ const ownerSession = ctx.sessions?.get?.(record.plan.sessionId);
8151
+ appendUserMessage(ownerSession, update);
8152
+ if (ownerSession !== session)
8153
+ appendUserMessage(session, update);
8154
+ }
8155
+ catch (error) {
8156
+ pushRecordError(record, error);
8157
+ }
8158
+ scheduleDelegateInstructionAck(record, subtaskId, target.member, childId, revision);
8159
+ return {
8160
+ ok: true,
8161
+ planId: record.plan.planId,
8162
+ subtaskId,
8163
+ member: target.member,
8164
+ sessionId: childId,
8165
+ messageId,
8166
+ latencyMs,
8167
+ revision,
8168
+ ...(journal.result.ok ? {} : { journal: { ok: false, code: journal.result.code, error: journal.result.error } }),
8169
+ hint: '指示已投递给第三层成员,该成员已变为「已收到指示」。它会开启新一轮;收齐结论前仍不得写最终结果块。',
8170
+ };
8171
+ }
8172
+ /**
8173
+ * [2.5.6] 叶子指示回执:与 scheduleInstructionAck 同一套三观察点语义
8174
+ * (轮询 seq 增长=acknowledged;60s 无增长=instructionOverdue;180s 无
8175
+ * 增长=blocked/no-ack),只是读写目标从部门行换成行内 delegates 成员条目。
8176
+ * 独立实现而不改动根会话共用的 scheduleInstructionAck,保证第一层零回归。
8177
+ */
8178
+ function scheduleDelegateInstructionAck(record, subtaskId, member, childId, revision) {
8179
+ const rowOf = () => record.statuses.find((item) => item?.subtaskId === subtaskId);
8180
+ const entryOf = () => {
8181
+ const row = rowOf();
8182
+ return (Array.isArray(row?.delegates) ? row.delegates : []).find((item) => item?.member === member) ?? null;
8183
+ };
8184
+ const patchEntry = (patch) => {
8185
+ const row = rowOf();
8186
+ if (!row)
8187
+ return null;
8188
+ const list = (Array.isArray(row.delegates) ? row.delegates : [])
8189
+ .map((item) => (item?.member === member ? { ...item, ...patch } : item));
8190
+ const nextRevision = Number(row.revision ?? 0) + 1;
8191
+ record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision: nextRevision, updatedBy: 'system' });
8192
+ record.updatedAt = Date.now();
8193
+ return entryOf();
8194
+ };
8195
+ const readSeq = () => {
8196
+ try {
8197
+ const seq = Number(ctx.sessions?.get?.(childId)?.seq);
8198
+ return Number.isFinite(seq) ? seq : undefined;
8199
+ }
8200
+ catch {
8201
+ return undefined;
8202
+ }
8203
+ };
8204
+ const baseline = readSeq();
8205
+ let stopped = false;
8206
+ const timers = [];
8207
+ const stop = () => {
8208
+ if (stopped)
8209
+ return;
8210
+ stopped = true;
8211
+ for (const timer of timers) {
8212
+ clearTimeout(timer);
8213
+ clearInterval(timer);
8214
+ }
8215
+ };
8216
+ const sameAttempt = (entry) => {
8217
+ if (stopped)
8218
+ return false;
8219
+ if (!entry || entry.closure !== 'instructed')
8220
+ return false;
8221
+ return Number(entry.instructionSeq ?? 0) === Number(revision);
8222
+ };
8223
+ const unchanged = (entry) => {
8224
+ if (!sameAttempt(entry))
8225
+ return false;
8226
+ const seq = readSeq();
8227
+ if (seq === undefined || baseline === undefined)
8228
+ return true;
8229
+ return seq <= baseline;
8230
+ };
8231
+ const poll = setInterval(() => {
8232
+ const entry = entryOf();
8233
+ if (!sameAttempt(entry)) {
8234
+ stop();
8235
+ return;
8236
+ }
8237
+ const seq = readSeq();
8238
+ if (seq === undefined || baseline === undefined || seq <= baseline)
8239
+ return;
8240
+ try {
8241
+ patchEntry({
8242
+ closure: 'acknowledged',
8243
+ ackedAt: Date.now(),
8244
+ instructionOverdue: false,
8245
+ });
8246
+ }
8247
+ catch {
8248
+ return;
8249
+ }
8250
+ stop();
8251
+ }, INSTRUCTION_POLL_MS);
8252
+ poll.unref?.();
8253
+ timers.push(poll);
8254
+ const notice = setTimeout(() => {
8255
+ if (!unchanged(entryOf()))
8256
+ return;
8257
+ try {
8258
+ patchEntry({ instructionOverdue: true });
8259
+ }
8260
+ catch { /* entry moved on */ }
8261
+ }, INSTRUCTION_ACK_NOTICE_MS);
8262
+ notice.unref?.();
8263
+ timers.push(notice);
8264
+ const deadline = setTimeout(() => {
8265
+ if (!unchanged(entryOf())) {
8266
+ stop();
8267
+ return;
8268
+ }
8269
+ const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000);
8270
+ const message = `指示下发后 ${seconds}s 成员会话仍无任何新事件(no-ack):指示没有被执行`;
8271
+ try {
8272
+ patchEntry({
8273
+ status: 'blocked',
8274
+ closure: 'blocked',
8275
+ blockedKind: 'no-ack',
8276
+ progress: 100,
8277
+ error: message,
8278
+ summary: `未完成:${message}`,
8279
+ finishedAt: Date.now(),
8280
+ });
8281
+ // [2.5.6] 与第一层 scheduleInstructionAck 对齐:no-ack 收束必须写入
8282
+ // 错误台账(主行 recordSubtaskError 同款),不留「静默 blocked」。
8283
+ recordSubtaskError(record, subtaskId, message, { timedOut: false });
8284
+ }
8285
+ catch {
8286
+ // Entry already left instructed.
8287
+ }
8288
+ stop();
8289
+ }, INSTRUCTION_ACK_DEADLINE_MS);
8290
+ timers.push(deadline);
8291
+ }
8292
+ /**
8293
+ * [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
8294
+ *
8295
+ * 单独一层包装而不是让 host 直接调内部函数:`escalateSubtask` 需要
8296
+ * `record`/`ctx` 闭包,host 侧只拿得到 runtime 的公开面;这一层也是
8297
+ * 唯一被 `dsh_workplan_escalate` 触发的地方,便于测试替身注入。
8298
+ */
8299
+ async function escalateTool(agent, args) {
8300
+ return escalateSubtask(agent, args);
6709
8301
  }
6710
8302
  /**
6711
8303
  * [1.11.0] 工具层入口:主 Agent 下发指示(T4 C-10 / T6 M6)。
@@ -6823,51 +8415,455 @@ export function createWorkplanRuntime(ctx, options = {}) {
6823
8415
  instruction: `跨部门需求 ${answer.id} 已答复${answer.department ? `(${answer.department})` : ''}:${answer.response}。按此答复继续原任务。`,
6824
8416
  }, signal);
6825
8417
  }
6826
- const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses));
8418
+ const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses));
8419
+ return {
8420
+ ok: true,
8421
+ planId: record.plan.planId,
8422
+ subtaskId,
8423
+ handoff: record.statuses.find((item) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
8424
+ deliveryReady: finalReadiness.ready,
8425
+ deliveryBlockers: finalReadiness.blockers,
8426
+ ...(instruction ? { instruction } : {}),
8427
+ hint: action === 'assign'
8428
+ ? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
8429
+ : instruction && instruction.ok !== true
8430
+ ? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
8431
+ : '已记录处置结果;交付阻塞按最新状态重新计算。',
8432
+ };
8433
+ }
8434
+ /**
8435
+ * [2.3.9][T4b] 第三层派发(用户强制要求 4/5):部门负责人专用工具。
8436
+ *
8437
+ * 层级模型:主 Agent(根会话, depth 0) → 部门负责人子会话(depth 1) →
8438
+ * 顶尖专家/组员子会话(depth 2, 叶子层)。三道硬边界:
8439
+ * 1. 调用者必须是计划内某行的部门负责人子会话(childId 反查行);
8440
+ * 根会话被拒(用 dsh_workplan_dispatch),第三层成员也被拒——
8441
+ * 其父会话是部门会话、没有计划记录,NO_PLAN/NO_SUBTASK 即叶子层禁令;
8442
+ * 2. 梳理门禁:dispatch 前必须先 review 提交「全面梳理产物 + 分工表」
8443
+ * (planDelegations 唯一判据,durable 回放后依然生效);
8444
+ * 3. 深度:成员 spawn 传 maxDepth:2,第四层(depth 3)由宿主
8445
+ * SubagentDepthError 硬拒(resolveChildDepth 绝对上限)。
8446
+ *
8447
+ * 每位下级的推理等级按其任务复杂度由负责人配置,经 planDelegations 按
8448
+ * 当前模型家族合法集合(qwen→low/medium/xhigh;非qwen→low/high/max)
8449
+ * 钳制并留痕(delegates[].requested/effort 对),随 spawn 的 agentOptions
8450
+ * 下发且全生命周期生效(要求 5)。
8451
+ */
8452
+ /**
8453
+ * [2.5.0][自配档] 叶子自配推理等级(用户要求 2 新口径):第三层专家/组员专用。
8454
+ * 先配置后开工——phase-0 以 low 启动,叶子评估自己任务复杂度后经此提交自配档;
8455
+ * 平台登记(五档白名单 + 家族钳制留痕 + delegates[].selfEffort + delegateSelfEfforts
8456
+ * 持久化回放)后立即中断 phase-0 回合,并以自配档接续 phase-1。宿主契约:
8457
+ * reasoningEffort 在子会话创建时解析(resolveChildAgentOptions),同会话换档不可行
8458
+ * ⇒ 接续 = interruptByParent(continuable) + 新激活携带 phase-0 产物与完整任务书,
8459
+ * childId 台账更新,旧结算回调按旧 childId 自动失配。接续失败重试 1 次仍败 ⇒
8460
+ * 明确 SELF_EFFORT_CONTINUATION_FAILED,禁止静默降档。
8461
+ */
8462
+ async function selfEffortTool(agent, args, signal) {
8463
+ const childSession = agent?.session;
8464
+ if (!childSession?.id)
8465
+ return { ok: false, code: 'NO_SESSION', error: 'self_effort 只能在会话内使用' };
8466
+ const leaderId = childSession.header?.parentSession;
8467
+ const leaderSession = leaderId ? ctx.sessions?.get?.(leaderId) : null;
8468
+ const rootId = leaderSession?.header?.parentSession;
8469
+ let record = rootId ? state.records.get(rootId) : undefined;
8470
+ if (!record?.plan && rootId) {
8471
+ const rootSession = ctx.sessions?.get?.(rootId);
8472
+ if (rootSession) {
8473
+ try {
8474
+ record = reconstructFromSession(rootSession);
8475
+ }
8476
+ catch (error) {
8477
+ pushRecordError({ errors: [] }, error);
8478
+ }
8479
+ }
8480
+ }
8481
+ let row = (record?.statuses ?? []).find((item) => Array.isArray(item?.delegates) && item.delegates.some((d) => d?.childId === childSession.id));
8482
+ /*
8483
+ * [T11] 血缘懒加载回退(治本,缺陷①):重启早期负责人会话可能尚未载入
8484
+ * ctx.sessions,rootId 取不到会在旧逻辑里被误报 SELF_EFFORT_NOT_LEAF。
8485
+ * 此处不直接拒绝,改按 childId 扫描既有台账定位归属计划(与 rootId 路径
8486
+ * reconstructFromSession 回退同范式)。只有真正未被任何部门行登记为叶子的
8487
+ * 会话(根会话/负责人自调用)才命中下方 NOT_LEAF 拒绝——安全边界不变。
8488
+ */
8489
+ if (!record?.plan || !row) {
8490
+ for (const candidate of state.records.values()) {
8491
+ const candidateRow = (candidate?.statuses ?? []).find((item) => Array.isArray(item?.delegates) && item.delegates.some((d) => d?.childId === childSession.id));
8492
+ if (candidate?.plan && candidateRow) {
8493
+ record = candidate;
8494
+ row = candidateRow;
8495
+ break;
8496
+ }
8497
+ }
8498
+ }
8499
+ if (!record?.plan || !row) {
8500
+ return { ok: false, code: 'SELF_EFFORT_NOT_LEAF', error: '找不到与本子会话关联的第三层台账(childId 未登记):self_effort 仅限部门负责人派出的全球顶尖专家叶子会话调用。' };
8501
+ }
8502
+ const member = row.delegates.find((d) => d?.childId === childSession.id);
8503
+ if (member.status === 'done')
8504
+ return { ok: false, code: 'ALREADY_DONE', error: '该成员已结算,不能再自配等级。' };
8505
+ const FIVE = ['low', 'medium', 'high', 'xhigh', 'max'];
8506
+ const raw = args?.reasoningEffort;
8507
+ if (typeof raw !== 'string' || !FIVE.includes(raw)) {
8508
+ return { ok: false, code: 'SELF_EFFORT_INVALID', error: `reasoningEffort "${String(raw)}" 非法:必须是 low / medium / high / xhigh / max 之一(按你自己任务复杂度自配:轻度=low;qwen 中等=medium、非 qwen 中等=high;qwen 非常复杂=xhigh、非 qwen 非常复杂=max)。` };
8509
+ }
8510
+ const rationale = String(args?.complexityRationale ?? '').trim();
8511
+ if (!rationale)
8512
+ return { ok: false, code: 'SELF_EFFORT_RATIONALE_MISSING', error: 'complexityRationale 必填:写清你分到的单项任务为何是该复杂度档(事实/依赖/验证难度)。' };
8513
+ /*
8514
+ * [2.5.2] 叶子执行前两轮深度思考硬门禁(用户 2026-11-12 要求:四角色在
8515
+ * 开始具体执行前都被机制强制先思考后执行,且全程少走弯路)。
8516
+ *
8517
+ * 此前专家/组员只有任务书注入 + 结算时 validatePhaseEvidence——思考产物
8518
+ * 在「执行后」才被迫补齐,不满足「先思考后执行」。现在把 phase-0 提交
8519
+ * 升级为原子对:self_effort 必须同时携带合格 deepThink(与主 Agent/负责人
8520
+ * 同一 validateMainDeepThink 判据、同一 40/40/20 字口径),缺交/不合格
8521
+ * 硬拒(DEEP_THINK_MISSING / DEEP_THINK_INCOMPLETE),不登记、不接续;
8522
+ * 两者齐全才登记并以自配档接续 phase-1——正式执行只能发生在两轮思考
8523
+ * 登记之后,且必须按第二轮理清的方法、流程、步骤执行(少走弯路)。
8524
+ * 已登记自配档的旧叶子重派直接 phase-1(零迁移),其结算门禁仍验产物。
8525
+ */
8526
+ const leafDeepThinkCheck = validateMainDeepThink(args?.deepThink);
8527
+ if (!leafDeepThinkCheck.ok) {
8528
+ const missing = leafDeepThinkCheck.code === 'MAIN_DEEP_THINK_MISSING';
8529
+ return {
8530
+ ok: false,
8531
+ code: missing ? 'DEEP_THINK_MISSING' : 'DEEP_THINK_INCOMPLETE',
8532
+ subtaskId: String(row.subtaskId),
8533
+ member: member.member,
8534
+ error: `执行前两轮深度思考产物${missing ? '缺失' : '不合格'}:全球顶尖专家开始执行自己的任务前,必须先全面、全盘、深入梳理、研究、思考自己的任务(第一轮),再基于第一轮完成好的所有结果再全面、全盘、深入地开展梳理、研究和思考,理清具体如何一步步以最高效率、少走弯路、完美完成自己任务的方法、流程和步骤(第二轮),最后才按此执行。请在 self_effort 一并携带 deepThink={ problemAnalysis[], approach[], approachBasis[] }。${leafDeepThinkCheck.error ?? ''}`,
8535
+ };
8536
+ }
8537
+ const leafDeepThink = leafDeepThinkCheck.deepThink;
8538
+ /*
8539
+ * [T6][D9] 开工前预估硬门禁(T6 冻结契约 §2,校验顺序最后一项:
8540
+ * reasoningEffort→complexityRationale→deepThink→timeNotice)。timeNotice=
8541
+ * { declaredMinutes: 正整数分钟(1..10080), reason?: ≤300 }。缺交=ESTIMATE_MISSING;
8542
+ * 非对象/非整数/越界=ESTIMATE_INVALID;error 必须含 D9 原话+形状说明。拒绝一律
8543
+ * 不登记、不投递、不接续(A1)。预估登记后经 T5 通道送达部门负责人(§4)才准
8544
+ * 接续 phase-1——「没有告知部门负责人预估时间,先拦截」。
8545
+ */
8546
+ const D9_ESTIMATE = '你必须自己预估时间,汇报给对应负责人后,才可以重试或继续执行';
8547
+ const rawTimeNotice = args?.timeNotice;
8548
+ if (rawTimeNotice === undefined) {
8549
+ return {
8550
+ ok: false,
8551
+ code: 'ESTIMATE_MISSING',
8552
+ subtaskId: String(row.subtaskId),
8553
+ member: member.member,
8554
+ error: `开工前预估缺失:${D9_ESTIMATE}。请在 self_effort 一并携带 timeNotice={ declaredMinutes: 正整数分钟(1..10080), reason?: 可选理由(≤300 字符) }。`,
8555
+ };
8556
+ }
8557
+ if (!rawTimeNotice || typeof rawTimeNotice !== 'object' || Array.isArray(rawTimeNotice)) {
8558
+ return {
8559
+ ok: false,
8560
+ code: 'ESTIMATE_INVALID',
8561
+ subtaskId: String(row.subtaskId),
8562
+ member: member.member,
8563
+ error: `开工前预估形状非法:timeNotice 必须是对象 { declaredMinutes: 正整数分钟(1..10080), reason? },现值 ${JSON.stringify(rawTimeNotice) ?? String(rawTimeNotice)}。${D9_ESTIMATE}。`,
8564
+ };
8565
+ }
8566
+ const rawMinutes = rawTimeNotice.declaredMinutes;
8567
+ if (!Number.isInteger(rawMinutes) || rawMinutes < 1 || rawMinutes > 10080) {
8568
+ return {
8569
+ ok: false,
8570
+ code: 'ESTIMATE_INVALID',
8571
+ subtaskId: String(row.subtaskId),
8572
+ member: member.member,
8573
+ error: `开工前预估非法:declaredMinutes 必须是正整数分钟(Number.isInteger 且 1..10080),现值 ${JSON.stringify(rawMinutes) ?? String(rawMinutes)}。${D9_ESTIMATE}。`,
8574
+ };
8575
+ }
8576
+ const rawEstimateReason = rawTimeNotice.reason;
8577
+ if (rawEstimateReason !== undefined && typeof rawEstimateReason !== 'string') {
8578
+ return {
8579
+ ok: false,
8580
+ code: 'ESTIMATE_INVALID',
8581
+ subtaskId: String(row.subtaskId),
8582
+ member: member.member,
8583
+ error: `开工前预估非法:reason 可选但必须是字符串(trim 后 ≤300 字符),现值类型 ${typeof rawEstimateReason}。${D9_ESTIMATE}。`,
8584
+ };
8585
+ }
8586
+ const estimateReason = typeof rawEstimateReason === 'string' && rawEstimateReason.trim() ? truncate(rawEstimateReason.trim(), 300) : '';
8587
+ const modelSelection = resolveModelSelection(ctx, { agent });
8588
+ const model = typeof modelSelection?.model === 'string' && modelSelection.model.trim() ? modelSelection.model.trim() : null;
8589
+ const correction = correctEffortForModel(raw, model);
8590
+ const selfEffort = correction.effort;
8591
+ if (correction.adjusted) {
8592
+ console.warn('[dsh-workplan] delegate self-effort corrected by LLM family rules:', JSON.stringify({ member: member.member, model, requested: raw, corrected: selfEffort, reason: correction.reason }));
8593
+ }
8594
+ const subtaskId = String(row.subtaskId);
8595
+ const rootSession = ctx.sessions?.get?.(rootId);
8596
+ const persistSelf = (patch) => {
8597
+ const current = record.statuses.find((item) => item?.subtaskId === subtaskId);
8598
+ const revision = Number(current?.revision ?? 0) + 1;
8599
+ record.statuses = applyStatus(record.statuses, subtaskId, { ...patch, revision, updatedBy: 'child' });
8600
+ record.updatedAt = Date.now();
8601
+ const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
8602
+ try {
8603
+ appendUserMessage(rootSession, buildUpdateMessage({
8604
+ planId: record.plan.planId,
8605
+ subtaskId,
8606
+ status: written?.status ?? row.status,
8607
+ ...(patch.delegates === undefined ? {} : { delegates: written?.delegates }),
8608
+ ...(patch.delegateSelfEfforts === undefined ? {} : { delegateSelfEfforts: written?.delegateSelfEfforts }),
8609
+ ...(patch.delegateDeepThinks === undefined ? {} : { delegateDeepThinks: written?.delegateDeepThinks }),
8610
+ // [T6][契约v1 §3] 预估台账随 durable workplan-update 回放(重启不丢)。
8611
+ ...(patch.delegateEstimates === undefined ? {} : { delegateEstimates: written?.delegateEstimates }),
8612
+ revision: written?.revision ?? revision,
8613
+ }));
8614
+ }
8615
+ catch (error) {
8616
+ pushRecordError(record, error);
8617
+ }
8618
+ return written;
8619
+ };
8620
+ const currentRow = () => record.statuses.find((item) => item?.subtaskId === subtaskId);
8621
+ // [T6][契约v1 §4] 预估读档(幂等判据):已 sent ⇒ 不重复投递;failed/缺失 ⇒
8622
+ // 本次投递。读侧消毒与 plan.ts sanitizeDelegateEstimate 同口径(正整数分钟才算已登记)。
8623
+ const priorEstimate = sanitizeLeafEstimate(currentRow()?.delegateEstimates?.[member.member])
8624
+ ?? sanitizeLeafEstimate((currentRow()?.delegates ?? []).find((d) => d?.childId === childSession.id)?.estimate);
8625
+ const estimateAlreadySent = priorEstimate?.delivery === 'sent';
8626
+ const estimateDraft = estimateAlreadySent
8627
+ ? priorEstimate
8628
+ : { declaredMinutes: rawMinutes, ...(estimateReason ? { reason: estimateReason } : {}), at: Date.now(), delivery: 'failed' };
8629
+ const registerList = (currentRow()?.delegates ?? row.delegates)
8630
+ .map((d) => (d?.childId === childSession.id
8631
+ ? { ...d, selfEffort, ...(correction.adjusted ? { selfEffortRequested: raw } : {}), complexityRationale: truncate(rationale, 300), deepThink: leafDeepThink, estimate: estimateDraft, status: 'running', error: null }
8632
+ : d));
8633
+ const stash = { ...(currentRow()?.delegateSelfEfforts ?? {}), [member.member]: selfEffort };
8634
+ // [2.5.2] 两轮思考产物与自配档同为任务级配置:delegates[].deepThink +
8635
+ // delegateDeepThinks 双通道落档,重置保留、durable 回放(G1 双侧接线)。
8636
+ const deepThinkStash = { ...(currentRow()?.delegateDeepThinks ?? {}), [member.member]: leafDeepThink };
8637
+ // [T6][契约v1 §3] 预估双通道:delegates[].estimate + delegateEstimates(任务级
8638
+ // 配置,重置保留、durable 回放),与 selfEffort/deepThink 同范式。
8639
+ const estimateStash = { ...(currentRow()?.delegateEstimates ?? {}), [member.member]: estimateDraft };
8640
+ persistSelf({ delegates: registerList, delegateSelfEfforts: stash, delegateDeepThinks: deepThinkStash, delegateEstimates: estimateStash });
8641
+ /*
8642
+ * [T6][D9][契约v1 §4] 预估送达部门负责人:登记之后、interrupt/接续之前。
8643
+ * 路由 row.childId(部门行负责人会话),缺失回退 leaderId;两者皆缺 ⇒
8644
+ * ESTIMATE_DELIVERY_FAILED(显式,不静默)。投递失败 ⇒ delivery:'failed' 已落档
8645
+ * +显式报错,不接续 phase-1;重试只重投 failed(sent 幂等跳过,不重复投递)。
8646
+ * 留痕 kind='estimate' 走 channelJournal 统一入口;journal 写失败不掩盖投递结果
8647
+ * (ok:true 附 journal:{ok:false,...},同 escalateDelegateLeaf journalInfo 口径)。
8648
+ */
8649
+ let estimateFinal = estimateDraft;
8650
+ let estimateJournalInfo = {};
8651
+ if (!estimateAlreadySent) {
8652
+ const headChildId = typeof row.childId === 'string' && row.childId ? row.childId : (typeof leaderId === 'string' ? leaderId : '');
8653
+ const estimateBody = `【第三层开工预估|${member.member} → 部门负责人】子任务 ${subtaskId} 成员 ${member.member} 开工前预估:执行本人任务约需 ${rawMinutes} 分钟(整数分钟)。理由:${estimateReason || '无'}。该预估已登记,平台即将以自配档接续其正式执行。`;
8654
+ const estimateStartedAt = Date.now();
8655
+ let estimateMessageId = '';
8656
+ let estimateDeliveryError = '';
8657
+ if (!headChildId) {
8658
+ estimateDeliveryError = '部门行未登记负责人会话(childId 缺失)且父会话 leaderId 缺失,无法投递预估';
8659
+ }
8660
+ else {
8661
+ const estimateService = ctx.subagents;
8662
+ if (!estimateService || typeof estimateService.sendMessage !== 'function') {
8663
+ estimateDeliveryError = '当前部署没有可用的 subagent 服务,无法投递预估';
8664
+ }
8665
+ else {
8666
+ try {
8667
+ estimateMessageId = String(await estimateService.sendMessage(agent, headChildId, [{ type: 'text', text: estimateBody }], { signal: new AbortController().signal }) ?? ''); // [T11] 缺陷②:预估投递携带有效 signal,消除 throwIfAborted
8668
+ }
8669
+ catch (error) {
8670
+ estimateDeliveryError = truncate(error instanceof Error ? error.message : String(error), 500);
8671
+ }
8672
+ }
8673
+ }
8674
+ const estimateLatencyMs = Date.now() - estimateStartedAt;
8675
+ const estimateDelivery = estimateDeliveryError ? 'failed' : 'sent';
8676
+ estimateFinal = { ...estimateDraft, delivery: estimateDelivery, ...(estimateMessageId ? { messageId: estimateMessageId } : {}) };
8677
+ const estimateList = (currentRow()?.delegates ?? [])
8678
+ .map((d) => (d?.childId === childSession.id ? { ...d, estimate: estimateFinal } : d));
8679
+ const estimateMap = { ...(currentRow()?.delegateEstimates ?? {}), [member.member]: estimateFinal };
8680
+ persistSelf({ delegates: estimateList, delegateEstimates: estimateMap });
8681
+ const estimateJournal = channelJournal({
8682
+ planId: record.plan.planId,
8683
+ subtaskId,
8684
+ kind: 'estimate',
8685
+ from: { sessionId: String(childSession.id), role: 'expert', member: member.member },
8686
+ to: { sessionId: headChildId, role: 'head' },
8687
+ body: estimateBody,
8688
+ data: { declaredMinutes: rawMinutes, ...(estimateReason ? { reason: estimateReason } : {}) },
8689
+ delivery: { status: estimateDelivery, ...(estimateMessageId ? { messageId: estimateMessageId } : {}), latencyMs: estimateLatencyMs, ...(estimateDeliveryError ? { code: 'DELIVERY_FAILED', error: estimateDeliveryError } : {}) },
8690
+ });
8691
+ estimateJournalInfo = estimateJournal.result.ok ? {} : { journal: { ok: false, code: estimateJournal.result.code, error: estimateJournal.result.error } };
8692
+ if (estimateDeliveryError) {
8693
+ return {
8694
+ ok: false,
8695
+ code: 'ESTIMATE_DELIVERY_FAILED',
8696
+ subtaskId,
8697
+ member: member.member,
8698
+ error: `预估投递失败(预估已以 delivery:'failed' 落档,未接续执行):${estimateDeliveryError}。请重试 self_effort(携带完整原子对:reasoningEffort+complexityRationale+deepThink+timeNotice),重试将重新投递。`,
8699
+ ...estimateJournalInfo,
8700
+ };
8701
+ }
8702
+ }
8703
+ /*
8704
+ * [2.5.2][T4b][D1] 负责人 agent 解析必须先于 interrupt,且用宿主同款安全
8705
+ * 访问器。根因(reports/D1-D2-root-cause-diagnosis.md §1):旧实现在
8706
+ * interrupt 之后用属性访问 `(ctx as any).agents?.get?.(leaderId)`,而插件
8707
+ * inject 清单(host.ts)不含 'agents'——Cordis 上下文代理对未注入服务的
8708
+ * 属性访问直接抛 `cannot get property "agents" without inject`(可选链挡
8709
+ * 不住代理 getter 抛错)。异常发生在 interrupt 之后、startActivation 之前、
8710
+ * 且不在任何 try/catch 内 ⇒ 接续会话从未创建、失败台账路径不可达,四个
8711
+ * 叶子永久死亡。现在:
8712
+ * ① 解析移到 interrupt 之前:ctx.get('agents') 安全访问器(宿主
8713
+ * dsh-subagent / dsh-tool-jobs 同款范式),整体 try/catch;无 get 方法
8714
+ * 的上下文(旧测试夹具)回退属性访问,同样在 try/catch 内。
8715
+ * ② 解析失败 ⇒ 不中断 phase-0;自配档与两轮思考产物已登记保留
8716
+ * (delegateSelfEfforts / delegateDeepThinks 已 durable 落档,负责人
8717
+ * 重派该成员时读档直连 phase-1),显式返回
8718
+ * SELF_EFFORT_CONTINUATION_FAILED,绝不静默。
8719
+ */
8720
+ let leaderAgent = null;
8721
+ try {
8722
+ const agentsService = typeof ctx.get === 'function' ? ctx.get('agents') : ctx.agents;
8723
+ leaderAgent = agentsService?.get?.(leaderId) ?? null;
8724
+ }
8725
+ catch {
8726
+ leaderAgent = null;
8727
+ }
8728
+ if (!leaderAgent) {
8729
+ const message = '自配档与两轮思考产物已登记,但负责人 agent 解析失败(agents 服务不可用):phase-0 未被中断,登记保留——负责人可重派该成员,重派将读档直接以自配档接续 phase-1(禁止静默降档)';
8730
+ const failedList = (currentRow()?.delegates ?? [])
8731
+ .map((d) => (d?.childId === childSession.id ? { ...d, status: 'failed', error: truncate(message, 300), finishedAt: Date.now() } : d));
8732
+ persistSelf({ delegates: failedList });
8733
+ return { ok: false, code: 'SELF_EFFORT_CONTINUATION_FAILED', subtaskId, member: member.member, selfEffort, error: message };
8734
+ }
8735
+ // 接续:中断 phase-0(parent authority, continuable),尽力而为。
8736
+ try {
8737
+ if (typeof ctx.subagents?.interruptByParent === 'function') {
8738
+ ctx.subagents.interruptByParent(childSession.id, leaderId, 'continuable');
8739
+ }
8740
+ }
8741
+ catch { /* 中断失败不阻断接续 */ }
8742
+ const departmentLabel = DEPARTMENTS[row.department]?.zh ?? String(row.department ?? '部门');
8743
+ const assignment = (Array.isArray(row.consolidation?.assignments) ? row.consolidation.assignments : [])
8744
+ .find((a) => a?.member === member.member);
8745
+ const fullTask = assignment?.task ?? member.task;
8746
+ /*
8747
+ * [3.0.0][用户要求 6] 质量要求随 phase-1 任务书一起交给专家:优先取 review
8748
+ * 登记的分工表原文(含质量要求),缺省时取成员记录,再缺省为空数组
8749
+ * (由提示词侧 renderQualityRequirementsBlock 如实显示「未交代」)。
8750
+ */
8751
+ const qualityRequirements = Array.isArray(assignment?.qualityRequirements) && assignment.qualityRequirements.length > 0
8752
+ ? assignment.qualityRequirements
8753
+ : (Array.isArray(member?.qualityRequirements) ? member.qualityRequirements : []);
8754
+ const rulesBrief = buildLlmRulesBrief({ model, effort: selfEffort, requested: correction.adjusted ? raw : null, correctionReason: correction.reason ?? null, tier: 'delegate', memberName: member.member, memberRole: member.role });
8755
+ const promptText = buildDelegateePrompt({
8756
+ departmentLabel,
8757
+ leaderSubtaskId: subtaskId,
8758
+ leaderSubtaskTitle: String(row.title ?? ''),
8759
+ member: { member: member.member, role: 'expert', task: fullTask, qualityRequirements, effort: selfEffort },
8760
+ rulesBrief,
8761
+ cwd: typeof childSession.header?.cwd === 'string' ? childSession.header.cwd : '',
8762
+ leadSessionId: leaderId,
8763
+ extraContext: `【phase-0→phase-1 接续——继续勿重做】你已在 phase-0 完成复杂度评估并自配推理等级 \`${selfEffort}\`(依据:${truncate(rationale, 300)}${correction.adjusted ? `;请求档 ${raw} 越界已被平台钳制为 ${selfEffort}` : ''}),并登记了执行前两轮深度思考产物。平台已按你的自配档接续:直接执行正式任务,不要重新评估复杂度,不要重做 phase-0 已完成的工作。正式执行必须严格按你第二轮理清的方法、流程、步骤进行(你的第二轮产物:${leafDeepThink.approach.join(';').slice(0, 300)}…),全程少走弯路:先查历史教训、先验证再动手、不重复试错。`,
8764
+ });
8765
+ let activation = null;
8766
+ let lastError = null;
8767
+ for (let i = 0; i < 2; i += 1) {
8768
+ try {
8769
+ // [2.5.5][治本] 第三处 spawn 同口径:spec 顶层契约(prompt/parent/cwd/agentOptions/maxDepth)。
8770
+ activation = await ctx.subagents.startActivation({
8771
+ provider: 'spawn',
8772
+ label: `${row.department}:${subtaskId}→${member.member}(self:${selfEffort})`.slice(0, 120),
8773
+ prompt: [{ type: 'text', text: promptText }],
8774
+ parent: leaderAgent ?? agent,
8775
+ cwd: typeof childSession.header?.cwd === 'string' && childSession.header.cwd ? childSession.header.cwd : undefined,
8776
+ agentOptions: {
8777
+ ...(modelSelection?.provider && modelSelection?.model ? { provider: modelSelection.provider, model: modelSelection.model } : {}),
8778
+ reasoningEffort: selfEffort,
8779
+ },
8780
+ maxDepth: 2,
8781
+ /*
8782
+ * [2.5.2][T4b][D1] 接续是平台驱动的重激活:signal 不得复用调用方
8783
+ * (phase-0 回合)的 signal——phase-0 即将被 interrupt,复用会让接续
8784
+ * 在 publication 前被连带取消。宿主契约 spec.signal 必填、语义只管
8785
+ * publication 前取消 ⇒ 用独立不中止的控制器。
8786
+ */
8787
+ signal: new AbortController().signal,
8788
+ delivery: 'caller',
8789
+ });
8790
+ break;
8791
+ }
8792
+ catch (error) {
8793
+ lastError = error;
8794
+ }
8795
+ }
8796
+ if (!activation) {
8797
+ const message = `自配档已登记但接续失败(已重试 1 次):${String(lastError?.message ?? lastError)}——禁止静默降档;该成员记为 failed,负责人可重派(自配档保留,重派直接以自配档接续)`;
8798
+ const failedList = (currentRow()?.delegates ?? [])
8799
+ .map((d) => (d?.childId === childSession.id ? { ...d, status: 'failed', error: truncate(message, 300), finishedAt: Date.now() } : d));
8800
+ persistSelf({ delegates: failedList });
8801
+ return { ok: false, code: 'SELF_EFFORT_CONTINUATION_FAILED', subtaskId, member: member.member, selfEffort, error: message };
8802
+ }
8803
+ const newChildId = typeof activation.childId === 'string' ? activation.childId : null;
8804
+ const continuedList = (currentRow()?.delegates ?? [])
8805
+ .map((d) => (d?.childId === childSession.id ? { ...d, childId: newChildId, status: 'running', startedAt: Date.now(), finishedAt: null, error: null } : d));
8806
+ const written = persistSelf({ delegates: continuedList });
8807
+ if (activation && typeof activation.result?.then === 'function') {
8808
+ // [T8] 结算回调异步化:完成即时通知经 sendMessage 定向投递(T5 契约)。
8809
+ activation.result.then(async (outcome) => {
8810
+ try {
8811
+ const completed = outcome?.stopReason === 'completed';
8812
+ // [3.0.0] F10:专家汇报入口强制核验(adjudicateExpertReport),
8813
+ // 未过即退回(failed + F10 拒因),绝不记 done。
8814
+ const f10 = completed ? adjudicateExpertReport(outcome) : { ok: true };
8815
+ const settledDone = completed && f10.ok;
8816
+ const current = (record.statuses ?? []).find((item) => item?.subtaskId === subtaskId);
8817
+ const list = (Array.isArray(current?.delegates) ? current.delegates : [])
8818
+ .map((item) => (item?.childId === newChildId
8819
+ // [T5-channel] 与 delegateTool 结算同款:待指示优先于结算——escalation
8820
+ // 子对象存在即请示未答复,不得覆盖成 done/failed(契约v1 权威形状)。
8821
+ ? (item?.escalation
8822
+ ? item
8823
+ : { ...item, status: settledDone ? 'done' : 'failed', closure: null, summary: truncate(resultText(outcome), 300), error: settledDone ? null : truncate(f10.ok ? String(outcome?.diagnostic ?? `子会话结束状态 ${outcome?.stopReason}`) : f10.rejection, 300), finishedAt: Date.now() })
8824
+ : item));
8825
+ const revision = Number(current?.revision ?? 0) + 1;
8826
+ record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'child' });
8827
+ record.updatedAt = Date.now();
8828
+ appendUserMessage(rootSession, buildUpdateMessage({ planId: record.plan.planId, subtaskId, status: current?.status ?? row.status, delegates: list, revision }));
8829
+ // [T8] 与 delegateTool 结算同款:完成即时通知 → 原分派负责人会话(leaderId)。
8830
+ await emitDelegateDoneNotices(record, ctx.sessions?.get?.(String(leaderId ?? '')) ?? leaderSession, rootSession, subtaskId);
8831
+ }
8832
+ catch { /* 结算留痕失败不影响主链路 */ }
8833
+ }).catch(() => { });
8834
+ }
6827
8835
  return {
6828
8836
  ok: true,
6829
8837
  planId: record.plan.planId,
6830
8838
  subtaskId,
6831
- handoff: record.statuses.find((item) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
6832
- deliveryReady: finalReadiness.ready,
6833
- deliveryBlockers: finalReadiness.blockers,
6834
- ...(instruction ? { instruction } : {}),
6835
- hint: action === 'assign'
6836
- ? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
6837
- : instruction && instruction.ok !== true
6838
- ? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
6839
- : '已记录处置结果;交付阻塞按最新状态重新计算。',
8839
+ action: 'self_effort',
8840
+ member: member.member,
8841
+ selfEffort,
8842
+ requested: raw,
8843
+ ...(correction.adjusted ? { clamped: { requested: raw, corrected: selfEffort, reason: correction.reason } } : {}),
8844
+ childId: newChildId,
8845
+ delegates: written?.delegates ?? continuedList,
8846
+ // [T6][契约v1 §2/§4] 成功回执附预估(declaredMinutes/reason?/delivery);
8847
+ // 留痕写失败不掩盖投递结果(journal:{ok:false,...},同 escalateDelegateLeaf 口径)。
8848
+ estimate: { declaredMinutes: estimateFinal.declaredMinutes, ...(estimateFinal.reason ? { reason: estimateFinal.reason } : {}), delivery: estimateFinal.delivery },
8849
+ ...estimateJournalInfo,
8850
+ hint: `自配档 \`${selfEffort}\` 已登记并以该档接续 phase-1(继续勿重做)。请执行正式任务,完成后把结论回报部门负责人会话。`,
6840
8851
  };
6841
8852
  }
6842
- /**
6843
- * [2.3.9][T4b] 第三层派发(用户强制要求 4/5):部门负责人专用工具。
6844
- *
6845
- * 层级模型:主 Agent(根会话, depth 0) → 部门负责人子会话(depth 1) →
6846
- * 顶尖专家/组员子会话(depth 2, 叶子层)。三道硬边界:
6847
- * 1. 调用者必须是计划内某行的部门负责人子会话(childId 反查行);
6848
- * 根会话被拒(用 dsh_workplan_dispatch),第三层成员也被拒——
6849
- * 其父会话是部门会话、没有计划记录,NO_PLAN/NO_SUBTASK 即叶子层禁令;
6850
- * 2. 梳理门禁:dispatch 前必须先 review 提交「全面梳理产物 + 分工表」
6851
- * (planDelegations 唯一判据,durable 回放后依然生效);
6852
- * 3. 深度:成员 spawn 传 maxDepth:2,第四层(depth 3)由宿主
6853
- * SubagentDepthError 硬拒(resolveChildDepth 绝对上限)。
6854
- *
6855
- * 每位下级的推理等级按其任务复杂度由负责人配置,经 planDelegations 按
6856
- * 当前模型家族合法集合(qwen→low/medium/xhigh;非qwen→low/high/max)
6857
- * 钳制并留痕(delegates[].requested/effort 对),随 spawn 的 agentOptions
6858
- * 下发且全生命周期生效(要求 5)。
6859
- */
6860
8853
  async function delegateTool(agent, args, signal) {
6861
8854
  const childSession = agent?.session;
6862
8855
  if (!childSession?.id) {
6863
8856
  return { ok: false, code: 'NO_SESSION', error: '只能在会话内使用第三层派发' };
6864
8857
  }
8858
+ // [2.5.0][自配档] self_effort 是叶子专属动作:先于负责人校验路由。
8859
+ if (args?.action === 'self_effort')
8860
+ return selfEffortTool(agent, args, signal);
6865
8861
  const parentId = childSession.header?.parentSession;
6866
8862
  if (!parentId) {
6867
8863
  return {
6868
8864
  ok: false,
6869
8865
  code: 'NOT_LEADER_SESSION',
6870
- error: '只有「部门负责人子会话」可以使用 dsh_workplan_delegate:根会话请用 dsh_workplan_dispatch 派发主计划;第三层专家/组员是叶子层,不得再派发(用户要求 4:只有一层下级)。',
8866
+ error: '只有「部门负责人子会话」可以使用 dsh_workplan_delegate:根会话请用 dsh_workplan_dispatch 派发主计划;第三层全球顶尖专家是叶子层,不得再派发(用户要求 4:只有一层下级)。',
6871
8867
  };
6872
8868
  }
6873
8869
  let record = state.records.get(parentId);
@@ -6886,7 +8882,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
6886
8882
  return {
6887
8883
  ok: false,
6888
8884
  code: 'NO_PLAN',
6889
- error: '父会话没有可关联的计划。若你是第三层专家/组员(叶子层):不得再派发,完成自身任务后把结论回报部门负责人即可。',
8885
+ error: '父会话没有可关联的计划。若你是第三层全球顶尖专家(叶子层):不得再派发,完成自身任务后把结论回报部门负责人即可。',
6890
8886
  };
6891
8887
  }
6892
8888
  const row = (record.statuses ?? []).find((item) => item?.childId === childSession.id);
@@ -6900,11 +8896,19 @@ export function createWorkplanRuntime(ctx, options = {}) {
6900
8896
  if (row.status === 'done') {
6901
8897
  return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已完成,不能再派发第三层。' };
6902
8898
  }
6903
- const action = ['review', 'dispatch', 'status'].includes(args?.action) ? String(args.action) : '';
8899
+ const action = ['review', 'dispatch', 'direct', 'status'].includes(args?.action) ? String(args.action) : '';
6904
8900
  if (!action) {
6905
- return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 review(提交全面梳理产物)/ dispatch(派发给顶尖专家与组员)/ status(查看梳理与下级进度)' };
8901
+ return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 review(提交全面梳理产物)/ dispatch(派发给本部门全球顶尖专家)/ direct(low 任务负责人亲自执行登记)/ status(查看梳理与下级进度)' };
6906
8902
  }
6907
8903
  const subtaskId = String(row.subtaskId);
8904
+ // [2.5.5][T3] D1 兜底:任务行记录等级。计划形状=stages[].subtasks[](不存在
8905
+ // record.plan.subtasks 平铺数组),复用 findSubtaskById(本文件 :1547)。
8906
+ // 五档消毒:非法/缺失一律 undefined(视同未配置),不把脏值传进判定链。
8907
+ const plannedRow = findSubtaskById(record.plan, subtaskId);
8908
+ const taskRowEffort = typeof plannedRow?.reasoningEffort === 'string'
8909
+ && REASONING_EFFORTS.includes(plannedRow.reasoningEffort)
8910
+ ? plannedRow.reasoningEffort
8911
+ : undefined;
6908
8912
  const modelSelection = resolveModelSelection(ctx, { agent });
6909
8913
  const model = typeof modelSelection?.model === 'string' && modelSelection.model.trim() ? modelSelection.model.trim() : null;
6910
8914
  const parentSession = ctx.sessions?.get?.(parentId);
@@ -6920,6 +8924,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
6920
8924
  status: written?.status ?? row.status,
6921
8925
  ...(patch.consolidation === undefined ? {} : { consolidation: written?.consolidation }),
6922
8926
  ...(patch.delegates === undefined ? {} : { delegates: written?.delegates }),
8927
+ // [2.5.4][T3R1] 门禁审计随 durable workplan-update 落盘(A3 可复核)。
8928
+ ...(patch.gateAudit === undefined ? {} : { gateAudit: written?.gateAudit }),
8929
+ // [2.5.0] 整体任务等级随 durable workplan-update 回放,重启不丢。
8930
+ ...(patch.effortOverride === undefined ? {} : { effortOverride: written?.effortOverride }),
6923
8931
  revision: written?.revision ?? revision,
6924
8932
  }));
6925
8933
  }
@@ -6928,6 +8936,17 @@ export function createWorkplanRuntime(ctx, options = {}) {
6928
8936
  }
6929
8937
  return record.statuses.find((item) => item?.subtaskId === subtaskId);
6930
8938
  };
8939
+ /*
8940
+ * [2.5.4][T3R1] 门禁审计记录器(T3 A3):review/dispatch 的每次拒绝都经
8941
+ * persist 留痕(durable workplan-update + applyStatus 消毒,有界 20 条)。
8942
+ * 放行记录并入各自动作既有的 persist 补丁(review 登记/dispatch 台账),
8943
+ * 避免同一动作二次 persist 造成 revision 竞争。
8944
+ */
8945
+ const recordGate = (gateAction, ok, code) => {
8946
+ const prior = Array.isArray(row.gateAudit) ? row.gateAudit : [];
8947
+ const entry = { at: Date.now(), action: gateAction, ok, code: ok ? null : String(code ?? 'UNKNOWN') };
8948
+ return persist({ gateAudit: [...prior, entry].slice(-20) });
8949
+ };
6931
8950
  if (action === 'status') {
6932
8951
  const delegates = Array.isArray(row.delegates) ? row.delegates : [];
6933
8952
  return {
@@ -6936,12 +8955,115 @@ export function createWorkplanRuntime(ctx, options = {}) {
6936
8955
  subtaskId,
6937
8956
  action,
6938
8957
  consolidation: row.consolidation ?? null,
8958
+ effortOverride: row.effortOverride ?? null,
8959
+ // [2.5.4][T3R1] 门禁审计对负责人可见(A3:拒绝/放行记录可复核)。
8960
+ gateAudit: Array.isArray(row.gateAudit) ? row.gateAudit : [],
6939
8961
  delegates,
6940
- hint: !row.consolidation
6941
- ? '尚未提交梳理产物:先调用 action="review"(用户要求 4 的硬门禁)。'
6942
- : delegates.length === 0
6943
- ? '梳理产物已登记,可调用 action="dispatch" 正式派发给顶尖专家与组员。'
6944
- : '第三层已派发;各下级结论会送回本会话,收齐后汇总核验,再写最终结果块。',
8962
+ // [T7][lead-decisions J2] 负责人时长聚合:与看板/模型面同一读时派生纯函数
8963
+ // (J1 冻结结构;null=无下属分工/replanned 旧行/越界 fail-closed,J8/R8)。
8964
+ leaderEstimate: deriveLeaderEstimate(row),
8965
+ // [2.5.5][T3] low 直执分支(派生判据,不新增持久化标记):effortOverride='low'
8966
+ // 且分工表为空/缺失 ⇒ low 直执;复杂任务被钳制到 low 的行(assignments 非空)
8967
+ // 不命中,避免误导(规格 §5.6)。
8968
+ hint: row.effortOverride === 'low' && (!Array.isArray(row.consolidation?.assignments) || row.consolidation.assignments.length === 0)
8969
+ ? 'low 任务(含视同 low):禁止第三层下派,负责人亲自执行;两轮思考产物经 action="direct" 登记(已登记则直接执行)。'
8970
+ : !row.consolidation
8971
+ ? '尚未提交梳理产物:先调用 action="review"(用户要求 4 的硬门禁)。'
8972
+ : delegates.length === 0
8973
+ ? '梳理产物已登记,可调用 action="dispatch" 正式派发给本部门全球顶尖专家。'
8974
+ : '第三层已派发;各下级结论会送回本会话,收齐后汇总核验,再写最终结果块。若有成员 closure=escalated(待指示),必须当轮用 dsh_workplan_instruct(subtaskId=本部门行 ID,多个成员同时请示时加 member)答复,不要沉默略过。',
8975
+ };
8976
+ }
8977
+ /*
8978
+ * [2.5.5][T3] 用户裁决 D2/D4:low 任务负责人亲自执行登记(direct)。
8979
+ * low(含视同 low)任务禁止第三层下派——planDelegations 禁派闸对 review/dispatch
8980
+ * 一律硬拒(DELEGATE_LOW_TASK_FORBIDDEN);负责人亲自执行,两轮深度思考产物经
8981
+ * 本动作登记(复用 validateMainDeepThink,与主 Agent/叶子/review 同一 40/40/20
8982
+ * 判据)。登记 effortOverride='low' ⇒ phase-0 结算闸(runSubtaskAttempt 内
8983
+ * SELF_EFFORT_MISSING 分支)只查 effortOverride 非空,逻辑零改动即可接续。
8984
+ * 防旁路(规格 §5.8):不收 consolidation/分工表;只接受 reasoningEffort='low'
8985
+ * (缺省默认 low);已有复杂分工表的行不得降级;下级 running 中不得改走;
8986
+ * 叶子调用在上方调用者边界命中 NOT_LEADER_SESSION/NO_PLAN。无任何例外通道(D5)。
8987
+ */
8988
+ if (action === 'direct') {
8989
+ if (Array.isArray(row.delegates) && row.delegates.some((item) => item?.status === 'running')) {
8990
+ recordGate('direct', false, 'DELEGATE_ALREADY_RUNNING');
8991
+ return {
8992
+ ok: false,
8993
+ code: 'DELEGATE_ALREADY_RUNNING',
8994
+ subtaskId,
8995
+ error: '第三层仍在派发中(有下级 running):不能改走 low 直执。先等当前下级结算(action="status" 查看进度)。',
8996
+ };
8997
+ }
8998
+ const priorAssignments = Array.isArray(row.consolidation?.assignments) ? row.consolidation.assignments : [];
8999
+ if (priorAssignments.length > 0) {
9000
+ recordGate('direct', false, 'DELEGATE_DIRECT_CONFLICT');
9001
+ return {
9002
+ ok: false,
9003
+ code: 'DELEGATE_DIRECT_CONFLICT',
9004
+ subtaskId,
9005
+ error: '本行已登记非空分工表(复杂流程已启动):不得降级改走 low 直执。复杂任务请继续 review/dispatch;low 禁派闸只拦 low/视同 low 任务。',
9006
+ };
9007
+ }
9008
+ if (args?.consolidation !== undefined && args?.consolidation !== null) {
9009
+ recordGate('direct', false, 'DELEGATE_DIRECT_ASSIGNMENTS_FORBIDDEN');
9010
+ return {
9011
+ ok: false,
9012
+ code: 'DELEGATE_DIRECT_ASSIGNMENTS_FORBIDDEN',
9013
+ subtaskId,
9014
+ error: 'direct 不接受 consolidation/分工表(low 任务禁止下派,用户裁决 D2):只提交 deepThink={problemAnalysis[],approach[],approachBasis[]}(40/40/20 字判据)与可选 reasoningEffort="low"。',
9015
+ };
9016
+ }
9017
+ const think = validateMainDeepThink(args?.deepThink);
9018
+ if (!think.ok || !think.deepThink) {
9019
+ const code = think.code === 'MAIN_DEEP_THINK_MISSING' ? 'DELEGATE_DIRECT_THINK_MISSING' : 'DELEGATE_DIRECT_THINK_INCOMPLETE';
9020
+ recordGate('direct', false, code);
9021
+ return {
9022
+ ok: false,
9023
+ code,
9024
+ subtaskId,
9025
+ error: `${think.error ?? '两轮深度思考产物缺失或不合格。'}(direct 登记与主 Agent/叶子同一判据:problemAnalysis 合计 ≥40 字、approach 合计 ≥40 字、approachBasis 合计 ≥20 字。)`,
9026
+ };
9027
+ }
9028
+ const directEffortRaw = args?.reasoningEffort;
9029
+ if (directEffortRaw !== undefined && directEffortRaw !== null && directEffortRaw !== 'low') {
9030
+ recordGate('direct', false, 'DELEGATE_DIRECT_EFFORT_INVALID');
9031
+ return {
9032
+ ok: false,
9033
+ code: 'DELEGATE_DIRECT_EFFORT_INVALID',
9034
+ subtaskId,
9035
+ error: `direct 只接受 reasoningEffort="low"(缺失默认 low);"${String(directEffortRaw)}" 不被接受。复杂任务(medium/high/xhigh/max)请走 review+dispatch(≥8 人闸),direct 不是复杂任务通道。`,
9036
+ };
9037
+ }
9038
+ const hadEffortOverride = typeof row.effortOverride === 'string' && row.effortOverride.length > 0;
9039
+ const written = persist({
9040
+ consolidation: {
9041
+ problemAnalysis: think.deepThink.problemAnalysis,
9042
+ approach: think.deepThink.approach,
9043
+ approachBasis: think.deepThink.approachBasis,
9044
+ assignments: [], // 空分工表=直执标记(派生判据,规格 §5.6)
9045
+ taskReasoningEffort: 'low',
9046
+ submittedAt: Date.now(),
9047
+ },
9048
+ effortOverride: 'low',
9049
+ gateAudit: [...(Array.isArray(row.gateAudit) ? row.gateAudit : []), { at: Date.now(), action: 'direct', ok: true, code: null }].slice(-20),
9050
+ });
9051
+ // 中断镜像 review 的 stall-fix 口径:仅「本次登记前尚无 effortOverride」
9052
+ // (真正的 phase-0→登记转变)才中断;phase-1 重新 direct 只更新产物。
9053
+ try {
9054
+ if (!hadEffortOverride && typeof ctx.subagents?.interruptByParent === 'function') {
9055
+ ctx.subagents.interruptByParent(childSession.id, parentId, 'continuable');
9056
+ }
9057
+ }
9058
+ catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
9059
+ return {
9060
+ ok: true,
9061
+ planId: record.plan.planId,
9062
+ subtaskId,
9063
+ action: 'direct',
9064
+ effortOverride: 'low',
9065
+ consolidation: written?.consolidation ?? null,
9066
+ hint: 'low 直执已登记(durable,刷新后门禁依然生效):平台将以 low 档接续本会话进入 phase-1。负责人亲自执行本任务,禁止再调用 review/dispatch(low 禁派闸会硬拒);完成后按三阶段契约提交证据与结论。',
6945
9067
  };
6946
9068
  }
6947
9069
  if (action === 'review') {
@@ -6951,11 +9073,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
6951
9073
  ok: false,
6952
9074
  code: 'MISSING_CONSOLIDATION',
6953
9075
  subtaskId,
6954
- error: 'review 必须携带 consolidation:{ problemAnalysis[], constraints[]?, unknowns[]?, approach[]?, assignments[{member, role:"expert"|"member", task, reasoningEffort}] }——用户要求 4 的「全面、全盘、深入梳理」产物 + 分工表(至少 1 名顶尖专家 + 1 名组员)。',
9076
+ error: 'review 必须携带 consolidation:{ problemAnalysis[], constraints[]?, unknowns[]?, approach[], approachBasis[], assignments[{member, role:"expert", task, qualityRequirements[], reasoningEffort}] }——两轮深度思考产物(第一轮全面、全盘、深入梳理研究思考自己的任务=problemAnalysis;第二轮基于第一轮全部结果理清方法、流程、步骤=approach,依据对应=approachBasis)+ 分工表(至少 1 名、最多 12 名本部门全球顶尖专家;组员角色已取消;每项任务必须极简并附质量要求)。',
6955
9077
  };
6956
9078
  }
6957
- const preview = planDelegations({ consolidation: input, model });
9079
+ // [2.5.0][R2×R4] 重新 review 未再配整体等级时,继承行上已持久化的
9080
+ // effortOverride(重置不清除的任务级配置),全程贯穿不丢。
9081
+ // [2.5.5][T3] 防注入:钳制前声明记忆只由平台写入,review 新输入不得携带
9082
+ // (否则 {taskReasoningEffort:'low', taskReasoningEffortDeclared:'max'} 可绕过禁派闸)。
9083
+ const { taskReasoningEffortDeclared: _stripped, ...reviewInput } = input;
9084
+ const preview = planDelegations({ consolidation: reviewInput, model, taskEffortFallback: row.effortOverride, taskRowEffort });
6958
9085
  if (!preview.ok) {
9086
+ // [2.5.4][T3R1] 门禁拒绝留痕(A3):薄产物/缺产物都记入 gateAudit。
9087
+ recordGate('review', false, preview.code ?? 'DELEGATE_CONSOLIDATION_INVALID');
6959
9088
  return {
6960
9089
  ok: false,
6961
9090
  code: preview.code ?? 'DELEGATE_CONSOLIDATION_INVALID',
@@ -6964,16 +9093,49 @@ export function createWorkplanRuntime(ctx, options = {}) {
6964
9093
  hint: '修正梳理产物后重新 action="review";未登记前 action="dispatch" 会持续被硬门禁拒绝。',
6965
9094
  };
6966
9095
  }
9096
+ // [2.5.2][stall-fix] 中断判据快照:本次 review 之前是否已登记整体档。
9097
+ const hadEffortOverride = typeof row.effortOverride === 'string' && row.effortOverride.length > 0;
6967
9098
  const written = persist({
6968
9099
  consolidation: {
6969
9100
  problemAnalysis: input.problemAnalysis,
6970
9101
  constraints: input.constraints,
6971
9102
  unknowns: input.unknowns,
6972
9103
  approach: input.approach,
9104
+ // [2.5.1] 两轮深度思考协议:第二轮依据随梳理产物留档,dispatch 读回同口径。
9105
+ approachBasis: input.approachBasis,
6973
9106
  assignments: input.assignments,
9107
+ // [2.5.0] 整体任务等级随梳理产物留档,dispatch 读回时同口径消费。
9108
+ ...(preview.taskEffort ? { taskReasoningEffort: preview.taskEffort } : {}),
9109
+ // [2.5.5][T3] 钳制前声明记忆随梳理产物留档:dispatch 读回时防
9110
+ // 「非 qwen medium 钳制后 low」误杀复杂声明(规格 §3.4)。
9111
+ ...(preview.taskEffortDeclared ? { taskReasoningEffortDeclared: preview.taskEffortDeclared } : {}),
6974
9112
  submittedAt: Date.now(),
6975
9113
  },
9114
+ // [2.5.0] 用户要求 2:负责人配置的整体等级写入状态行,本任务每次
9115
+ // 派发/重试/续跑优先读它(resolveTaskEffort),全程生效、durable 回放。
9116
+ ...(preview.taskEffort ? { effortOverride: preview.taskEffort } : {}),
9117
+ // [2.5.4][T3R1] 门禁放行留痕(A3):合格梳理登记成功记入 gateAudit。
9118
+ gateAudit: [...(Array.isArray(row.gateAudit) ? row.gateAudit : []), { at: Date.now(), action: 'review', ok: true, code: null }].slice(-20),
6976
9119
  });
9120
+ /*
9121
+ * [2.5.0][自配档] 登记后立即中断 phase-0 回合(parent authority, continuable);
9122
+ * runSubtaskAttempt 检测到 effortOverride 即以自配档接续 phase-1。尽力而为:
9123
+ * interrupt 不可用时 phase-0 自然结束,平台接续仍然成立。
9124
+ *
9125
+ * [2.5.2][stall-fix] 根因修复(用户报告「提交任务后长时间无反应」):
9126
+ * 旧实现只要 preview.taskEffort 非空就中断——负责人已在 phase-1 时重新
9127
+ * review(哪怕等级不变)也会触发中断,而接续逻辑只存在于 phase-0 结算
9128
+ * 分支:phase-1 回合被中断后无人接续,子会话 aborted、产物丢失、台账
9129
+ * blocked,用户看到的就是长时间停滞。现在仅当「本次 review 之前尚未
9130
+ * 登记 effortOverride」(真正的 phase-0→登记 转变)才中断;phase-1 的
9131
+ * 重新 review 只更新梳理产物,绝不中断正在执行的回合。
9132
+ */
9133
+ try {
9134
+ if (preview.taskEffort && !hadEffortOverride && typeof ctx.subagents?.interruptByParent === 'function') {
9135
+ ctx.subagents.interruptByParent(childSession.id, parentId, 'continuable');
9136
+ }
9137
+ }
9138
+ catch { /* 中断失败不影响登记;接续由 runSubtaskAttempt 保证 */ }
6977
9139
  return {
6978
9140
  ok: true,
6979
9141
  planId: record.plan.planId,
@@ -6982,14 +9144,21 @@ export function createWorkplanRuntime(ctx, options = {}) {
6982
9144
  consolidation: written?.consolidation ?? null,
6983
9145
  members: preview.members,
6984
9146
  clamped: preview.clamped,
9147
+ taskEffort: preview.taskEffort,
9148
+ ...(preview.taskEffortClamped ? { taskEffortClamped: preview.taskEffortClamped } : {}),
6985
9149
  model: model ?? '(未知,未施加静态等级约束)',
6986
- hint: '梳理产物已登记(durable,刷新后门禁依然生效)。现在可调用 action="dispatch" 正式派发;每位下级的推理等级已按当前模型家族合法集合钳制(clamped 列出越界修正与原因,留痕可审计)。',
9150
+ hint: '梳理产物已登记(durable,刷新后门禁依然生效)。现在可调用 action="dispatch" 正式派发;每位下级的推理等级已按当前模型家族合法集合钳制(clamped 列出越界修正与原因,留痕可审计)。'
9151
+ + (preview.taskEffort ? `整体任务等级已配置为 ${preview.taskEffort}(负责人自配档),本任务重试/续跑全程沿用;下级以 self_effort 自配为权威。` : '未配置整体任务等级:负责人须按先配置后开工经 review 自配(consolidation.taskReasoningEffort);下级经 self_effort 自配。'),
6987
9152
  };
6988
9153
  }
6989
9154
  // action === 'dispatch'
6990
9155
  const consolidation = isRecord(row.consolidation) ? row.consolidation : null;
6991
- const delegationPlan = planDelegations({ consolidation, model });
9156
+ // [2.5.0][R2×R4] dispatch 读回梳理产物时,整体等级缺失同样回落行上
9157
+ // effortOverride(durable 回放/重置后依然全程贯穿)。
9158
+ const delegationPlan = planDelegations({ consolidation, model, taskEffortFallback: row.effortOverride, taskRowEffort });
6992
9159
  if (!delegationPlan.ok) {
9160
+ // [2.5.4][T3R1] 分派门禁拒绝留痕(A3):未梳理/薄产物一律记录拒因。
9161
+ recordGate('dispatch', false, delegationPlan.code ?? 'DELEGATE_CONSOLIDATION_MISSING');
6993
9162
  return {
6994
9163
  ok: false,
6995
9164
  code: delegationPlan.code ?? 'DELEGATE_CONSOLIDATION_MISSING',
@@ -7015,6 +9184,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
7015
9184
  ? parentSession.header.cwd
7016
9185
  : undefined);
7017
9186
  const delegates = [];
9187
+ /*
9188
+ * [2.5.0][R4] 重试/续跑不丢已完成部分(第三层落点):重派时 row.delegates
9189
+ * 仍是上一次尝试的台账——为每位下级附上次状态/失败原因/已回报结论与已核实
9190
+ * 在盘产物(buildDelegateRetryBrief),经 extraContext 写进新任务书。
9191
+ * 旧实现这里直接发全新任务书,叶子失败后重派只能整步重跑。
9192
+ */
9193
+ const priorDelegates = Array.isArray(row.delegates) ? row.delegates : [];
9194
+ const consolidationApproach = Array.isArray(row.consolidation?.approach) ? row.consolidation.approach : [];
7018
9195
  for (const assignment of delegationPlan.members) {
7019
9196
  const rulesBrief = buildLlmRulesBrief({
7020
9197
  model,
@@ -7025,7 +9202,45 @@ export function createWorkplanRuntime(ctx, options = {}) {
7025
9202
  memberName: assignment.member,
7026
9203
  memberRole: assignment.role,
7027
9204
  });
7028
- const promptText = buildDelegateePrompt({
9205
+ const prior = priorDelegates.find((item) => item?.member === assignment.member) ?? null;
9206
+ const retryBrief = prior
9207
+ ? buildDelegateRetryBrief(prior, probeDelegateLandedArtifacts(cwd, assignment.member), consolidationApproach)
9208
+ : '';
9209
+ // [2.5.0][自配档] 先配置后开工:未登记自配档 ⇒ phase-0 以 low 启动(唯一
9210
+ // 职责=self_effort);已有自配档(含重置保留的 delegateSelfEfforts)⇒ 直接
9211
+ // 以自配档接续 phase-1。分工表 effort 降为建议(台账保留供看板对照)。
9212
+ const stashedSelf = row.delegateSelfEfforts?.[assignment.member];
9213
+ const priorSelf = typeof stashedSelf === 'string' && stashedSelf ? stashedSelf
9214
+ : (typeof prior?.selfEffort === 'string' && prior.selfEffort ? prior.selfEffort : '');
9215
+ /*
9216
+ * [2.5.2] 执行前两轮思考读档:已登记思考产物(delegateDeepThinks 或
9217
+ * delegates[].deepThink)⇒ 随接续提示词下发执行蓝图,直接 phase-1;
9218
+ * 未登记(含旧计划遗留叶子)⇒ 仍走 phase-0 补齐思考+自配后才准执行。
9219
+ */
9220
+ const stashedThink = sanitizeMainDeepThink(row.delegateDeepThinks?.[assignment.member])
9221
+ ?? sanitizeMainDeepThink(prior?.deepThink);
9222
+ /*
9223
+ * [T6][D9][契约v1 §5] 预估读档门禁:已登记且已送达(delivery='sent')的预估
9224
+ * 才算门禁通过。未预估、或预估投递失败(failed)⇒ 回 phase-0 补交完整原子对
9225
+ * (self_effort 重试只重投 failed,sent 幂等不重投)。D9 唯一权威:「汇报给对应
9226
+ * 负责人后,才可以重试或继续执行」——failed 若放行 phase-1 将永远无人补投,
9227
+ * 故门禁以 sent 为准(正整数 declaredMinutes 才算已登记,消毒同 plan.ts 口径)。
9228
+ */
9229
+ const stashedEstimate = sanitizeLeafEstimate(row.delegateEstimates?.[assignment.member])
9230
+ ?? sanitizeLeafEstimate(prior?.estimate);
9231
+ const registeredEstimate = stashedEstimate?.delivery === 'sent' ? stashedEstimate : null;
9232
+ const leafPhaseZero = !priorSelf || !stashedThink || !registeredEstimate;
9233
+ const selfContinuation = priorSelf && stashedThink && registeredEstimate
9234
+ ? `【自配档接续·两轮思考读档】你的自配推理等级 \`${priorSelf}\` 与执行前两轮深度思考产物均已登记生效(成员自配为权威)。继续勿重做:直接执行正式任务,不要重新评估复杂度、不要重复提交思考产物。正式执行必须严格按你第二轮理清的方法、流程、步骤进行(你的第一轮产物:${stashedThink.problemAnalysis.join(';').slice(0, 200)}…;你的第二轮产物:${stashedThink.approach.join(';').slice(0, 300)}…),全程少走弯路:先查历史教训、先验证再动手、不重复试错。你的开工预估已登记并送达部门负责人(约 ${registeredEstimate.declaredMinutes} 分钟,整数分钟),无需重复上报。`
9235
+ : (priorSelf
9236
+ ? `【自配档接续】你的自配推理等级 \`${priorSelf}\` 已登记生效(成员自配为权威)。继续勿重做:直接执行正式任务,不要重新评估复杂度。`
9237
+ : '');
9238
+ const promptText = leafPhaseZero ? buildPhaseZeroDelegateePrompt({
9239
+ departmentLabel,
9240
+ member: assignment,
9241
+ cwd: cwd ?? '',
9242
+ ...(retryBrief ? { extraContext: retryBrief } : {}),
9243
+ }) : buildDelegateePrompt({
7029
9244
  departmentLabel,
7030
9245
  leaderSubtaskId: subtaskId,
7031
9246
  leaderSubtaskTitle: String(row.title ?? ''),
@@ -7033,47 +9248,61 @@ export function createWorkplanRuntime(ctx, options = {}) {
7033
9248
  rulesBrief,
7034
9249
  cwd: cwd ?? '',
7035
9250
  leadSessionId: childSession.id,
9251
+ ...(retryBrief || selfContinuation ? { extraContext: [selfContinuation, retryBrief].filter(Boolean).join('\n') } : {}),
7036
9252
  });
7037
9253
  let childId = null;
7038
9254
  let memberStatus = 'running';
7039
9255
  let memberError = null;
7040
9256
  try {
9257
+ // [2.5.5][治本] 同 executeSubtask:spec 顶层契约(prompt/parent/cwd/agentOptions/maxDepth)。
7041
9258
  const activation = await ctx.subagents.startActivation({
7042
9259
  provider: 'spawn',
7043
9260
  label: `${row.department}:${subtaskId}→${assignment.member}`.slice(0, 120),
7044
- request: {
7045
- prompt: [{ type: 'text', text: promptText }],
7046
- parent: agent,
7047
- cwd,
7048
- agentOptions: {
7049
- ...(modelSelection?.provider && modelSelection?.model
7050
- ? { provider: modelSelection.provider, model: modelSelection.model }
7051
- : {}),
7052
- // 要求 5:等级随任务复杂度配置并全程应用;'' = 模型无 reasoning 元数据 ⇒ 不发送。
7053
- ...(assignment.effort ? { reasoningEffort: assignment.effort } : {}),
7054
- },
7055
- // 成员在 depth 2;任何第四层(depth 3)被宿主绝对深度上限硬拒。
7056
- maxDepth: 2,
9261
+ prompt: [{ type: 'text', text: promptText }],
9262
+ parent: agent,
9263
+ cwd,
9264
+ agentOptions: {
9265
+ ...(modelSelection?.provider && modelSelection?.model
9266
+ ? { provider: modelSelection.provider, model: modelSelection.model }
9267
+ : {}),
9268
+ // [2.5.0][自配档] phase-0 强制 low;phase-1 用成员自配档(权威)。
9269
+ reasoningEffort: leafPhaseZero ? 'low' : priorSelf,
7057
9270
  },
9271
+ // 成员在 depth 2;任何第四层(depth 3)被宿主绝对深度上限硬拒。
9272
+ maxDepth: 2,
7058
9273
  signal,
7059
9274
  delivery: 'caller',
7060
9275
  });
7061
9276
  childId = typeof activation?.childId === 'string' ? activation.childId : null;
7062
9277
  if (activation && typeof activation.result?.then === 'function') {
7063
9278
  const settledChildId = childId;
7064
- activation.result.then((outcome) => {
9279
+ // [T8] 结算回调异步化:完成即时通知经 sendMessage 定向投递(T5 契约)。
9280
+ activation.result.then(async (outcome) => {
7065
9281
  try {
7066
9282
  const completed = outcome?.stopReason === 'completed';
9283
+ // [3.0.0] F10:专家汇报入口强制核验(adjudicateExpertReport),
9284
+ // 未过即退回(failed + F10 拒因),绝不记 done。
9285
+ const f10 = completed ? adjudicateExpertReport(outcome) : { ok: true };
9286
+ const settledDone = completed && f10.ok;
7067
9287
  const current = (record.statuses ?? []).find((item) => item?.subtaskId === subtaskId);
7068
9288
  const list = (Array.isArray(current?.delegates) ? current.delegates : [])
7069
9289
  .map((item) => (item?.childId === settledChildId
7070
- ? {
7071
- ...item,
7072
- status: completed ? 'done' : 'failed',
7073
- summary: truncate(resultText(outcome), 300),
7074
- error: completed ? null : truncate(String(outcome?.diagnostic ?? `子会话结束状态 ${outcome?.stopReason}`), 300),
7075
- finishedAt: Date.now(),
7076
- }
9290
+ /*
9291
+ * [2.5.6] 待指示优先于结算:叶子请示后结束回合(stopReason
9292
+ * 可能是 completed),但请示还没被负责人答复——结算不得把
9293
+ * escalated 覆盖成 done/failed,否则「待指示」凭空消失。
9294
+ * 负责人 instruct 投递后叶子恢复执行,正常结算再收敛。
9295
+ */
9296
+ ? (item?.escalation
9297
+ ? item
9298
+ : {
9299
+ ...item,
9300
+ status: settledDone ? 'done' : 'failed',
9301
+ closure: null,
9302
+ summary: truncate(resultText(outcome), 300),
9303
+ error: settledDone ? null : truncate(f10.ok ? String(outcome?.diagnostic ?? `子会话结束状态 ${outcome?.stopReason}`) : f10.rejection, 300),
9304
+ finishedAt: Date.now(),
9305
+ })
7077
9306
  : item));
7078
9307
  const revision = Number(current?.revision ?? 0) + 1;
7079
9308
  record.statuses = applyStatus(record.statuses, subtaskId, { delegates: list, revision, updatedBy: 'child' });
@@ -7085,6 +9314,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
7085
9314
  delegates: list,
7086
9315
  revision,
7087
9316
  }));
9317
+ // [T8] 完成即时通知 → 原分派负责人会话(row.childId):done-only、
9318
+ // report.state='sent' 幂等、投递失败留 failed 待兜底补发,绝不回滚结算。
9319
+ await emitDelegateDoneNotices(record, ctx.sessions?.get?.(String(row.childId ?? '')) ?? childSession, parentSession, subtaskId);
7088
9320
  }
7089
9321
  catch {
7090
9322
  // 结算留痕失败不影响主链路:看板下次刷新按内存行渲染。
@@ -7110,7 +9342,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
7110
9342
  finishedAt: null,
7111
9343
  });
7112
9344
  }
7113
- const written = persist({ delegates });
9345
+ // [2.5.4][T3R1] 分派门禁放行留痕(A3):并入台账 persist,同一动作不二次
9346
+ // persist(避免 revision 竞争);gateAudit 经 applyStatus 消毒 + durable 回放。
9347
+ const written = persist({
9348
+ delegates,
9349
+ gateAudit: [...(Array.isArray(row.gateAudit) ? row.gateAudit : []), { at: Date.now(), action: 'dispatch', ok: true, code: null }].slice(-20),
9350
+ });
7114
9351
  const rejected = delegates.filter((item) => item.status === 'rejected');
7115
9352
  return {
7116
9353
  ok: rejected.length < delegates.length,
@@ -7119,8 +9356,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
7119
9356
  action,
7120
9357
  delegates: written?.delegates ?? delegates,
7121
9358
  clamped: delegationPlan.clamped,
9359
+ taskEffort: delegationPlan.taskEffort,
9360
+ effortOverride: written?.effortOverride ?? row.effortOverride ?? null,
7122
9361
  ...(rejected.length ? { rejected: rejected.map((item) => ({ member: item.member, error: item.error })) } : {}),
7123
- hint: '第三层已派发(一层下级、叶子层,第四层会被硬拒)。每位专家/组员的完成结论会送回本会话(delivery=caller);收齐后由你汇总核验,再写最终结果块。用 action="status" 查看进度。',
9362
+ hint: '第三层已派发(一层下级、叶子层,第四层会被硬拒)。每位全球顶尖专家的完成结论会送回本会话(delivery=caller);收齐后由你汇总核验,再写最终结果块。用 action="status" 查看进度。成员遇阻会经 dsh_workplan_escalate 在你这里落「待指示」(delegates[].closure=escalated):必须当轮用 dsh_workplan_instruct(subtaskId=本部门行 ID,多个成员同时请示时加 member)答复,投递成功后该成员恢复执行。',
7124
9363
  };
7125
9364
  }
7126
9365
  async function dispatchTool(agent, args, signal) {
@@ -7214,6 +9453,61 @@ export function createWorkplanRuntime(ctx, options = {}) {
7214
9453
  : '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
7215
9454
  };
7216
9455
  }
9456
+ /*
9457
+ * [2.5.1] 主 Agent 两轮深度思考协议硬门禁(用户 2026-11-11 补充要求)。
9458
+ *
9459
+ * 主 Agent 执行自己的任务同样必须:先全面、全盘、深入梳理、研究、思考
9460
+ * 自己的任务(第一轮),再基于第一轮完成好的所有结果再全面、全盘、深入
9461
+ * 地开展梳理、研究和思考,理清方法、流程和步骤(第二轮),最后才基于
9462
+ * 第二轮的方法、流程、步骤开始具体执行——派发就是主 Agent 执行的起点,
9463
+ * 因此首次派发必须随附 deepThink 产物,未交/不合格硬拒,提示词绕不过。
9464
+ *
9465
+ * 落点=已通过 NO_PLAN / PLAN_ID_MISMATCH / 终态闸门之后、派发预告与任何
9466
+ * 子 Agent 启动之前:拒绝不产生副作用,也不刷派发预告。登记后持久化
9467
+ * (record + durable workplan-update),续跑/重试/join/重启回放读档放行;
9468
+ * 产物按 planId 记账——重规划换新计划是新任务,必须重新两轮思考。
9469
+ */
9470
+ if (!record.mainDeepThink || record.mainDeepThinkPlanId !== record.plan.planId) {
9471
+ const deepThinkCheck = validateMainDeepThink(args?.deepThink);
9472
+ if (!deepThinkCheck.ok) {
9473
+ const snapshot = derivePlanSnapshot(record.statuses);
9474
+ return {
9475
+ ok: false,
9476
+ planId: record.plan.planId,
9477
+ phase: record.phase,
9478
+ running: false,
9479
+ alreadyRunning: false,
9480
+ complete: false,
9481
+ remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
9482
+ stats: snapshot.stats,
9483
+ code: deepThinkCheck.code,
9484
+ error: deepThinkCheck.error,
9485
+ hint: '先完成两轮深度思考再派发:第一轮全面、全盘、深入梳理研究思考自己的任务,第二轮基于第一轮全部结果理清方法、流程、步骤(含依据 approachBasis),随 dsh_workplan_dispatch 的 deepThink 参数提交;登记后续跑/重启自动读档,无需重复提交。',
9486
+ };
9487
+ }
9488
+ record.mainDeepThink = deepThinkCheck.deepThink;
9489
+ record.mainDeepThinkPlanId = record.plan.planId;
9490
+ // durable 持久化(计划级字段,subtaskId=null 不落任何子任务行);回放消费端同口径消毒。
9491
+ appendUserMessage(session, buildUpdateMessage({
9492
+ planId: record.plan.planId,
9493
+ subtaskId: null,
9494
+ mainDeepThink: deepThinkCheck.deepThink,
9495
+ mainDeepThinkPlanId: record.plan.planId,
9496
+ }));
9497
+ }
9498
+ /*
9499
+ * [2.3.10][T2] 用户要求1(P2):派发前会话内预告执行耗时。落点=已通过
9500
+ * 全部拒绝闸门(NO_PLAN / PLAN_ID_MISMATCH / 终态)、尚未启动任何子 Agent。
9501
+ * 幂等守卫:同一 planId 只预告一次——dispatch 工具契约是重复调用幂等,
9502
+ * 续跑/重复派发/join 在途回合都不得重复刷屏;重规划换新 planId 时自然
9503
+ * 重新预告。只追加 notice,不改派发语义与任何返回体。
9504
+ */
9505
+ if (record.preAnnouncedPlanId !== record.plan.planId) {
9506
+ record.preAnnouncedPlanId = record.plan.planId;
9507
+ const preAnnouncement = buildDispatchPreAnnouncement(record.plan);
9508
+ if (preAnnouncement)
9509
+ appendUserMessage(session, preAnnouncement);
9510
+ }
7217
9511
  /*
7218
9512
  * [1.7.0] Two dispatch modes.
7219
9513
  *
@@ -7339,11 +9633,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
7339
9633
  cwd: session.header?.cwd ?? options.cwd,
7340
9634
  conversationContext: record.conversationContext ?? '',
7341
9635
  /*
7342
- * [2.2.0][T6/O-1a] 只有后台(async)轮次推即时通知:wait 模式主 Agent
7343
- * 在调用栈内等待,轮级结果消息就是该模式的完成通道,避免同一轮重复
7344
- * 两条消息;既有的「每轮恰 1 条持久结果消息」断言因此保持不变。
9636
+ * [T9][用户要求6] 两种模式都推完成即时汇报:各部门负责人任务完成必须
9637
+ * 立刻、独立地向主 Agent 汇报,不分 wait/async(2.2.0「wait 不推」语义
9638
+ * 由 T9 取代)。即时通知是纯文本 user/message、不带 workplan 标记,
9639
+ * 不是轮级结果消息——「每轮恰 1 条持久结果消息」断言不受影响。
9640
+ * 结算备份采纳路径(settleFromOutput 同一 options)因此同样覆盖。
7345
9641
  */
7346
- notifyCompletion: mode === 'async',
9642
+ notifyCompletion: true,
7347
9643
  onSubtaskDone: (recordArg, subtask, verdict) => emitSubtaskDoneNotice(recordArg, session, subtask, verdict),
7348
9644
  };
7349
9645
  record.dispatchPromise = dispatchPlan(ctx, record, {
@@ -8439,7 +10735,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
8439
10735
  statusTool,
8440
10736
  followupTool,
8441
10737
  escalateTool,
8442
- // [2.3.9][T4b] 第三层派发(部门负责人专用):review 梳理门禁 → dispatch 专家/组员。
10738
+ // [2.3.9][T4b] 第三层派发(部门负责人专用):review 梳理门禁 → dispatch 全球顶尖专家。
8443
10739
  delegateTool,
8444
10740
  verifyTool: verifySubtask,
8445
10741
  lessonsTool,
@@ -8494,10 +10790,24 @@ function resolveModelSelection(ctx, payload) {
8494
10790
  }
8495
10791
  async function maybePlan(ctx, state, payload, downstream, options) {
8496
10792
  const session = payload.agent?.session;
8497
- if (!session || !isRootSession(session))
10793
+ if (!session)
10794
+ return downstream;
10795
+ /*
10796
+ * [2.5.5][T10] 每个 pre-step 先把该会话缓冲的台账合并落盘:合并闸把有界延迟
10797
+ * 从「整轮」缩短到一个 step,进程崩溃最多丢当前 step 未落盘的台账。
10798
+ */
10799
+ try {
10800
+ flushPendingWorkplanUpdates(session);
10801
+ }
10802
+ catch {
10803
+ /* 合并失败不拦规划:下一次落盘/结算再试。 */
10804
+ }
10805
+ if (!isRootSession(session))
8498
10806
  return downstream;
8499
10807
  if (payload.step !== 1)
8500
10808
  return downstream;
10809
+ // [2.5.5][T3] pre-step 窗口标记:规划/自动派发的头前通知一律暂存(治本)。
10810
+ enterPreHeadWindow(session);
8501
10811
  const planMode = isPlanModeActive(ctx, session);
8502
10812
  const human = humanMessages(payload.messages);
8503
10813
  const existing = state.records.get(session.id);
@@ -8522,7 +10832,8 @@ async function maybePlan(ctx, state, payload, downstream, options) {
8522
10832
  *
8523
10833
  * `agent/turn-stopping` must only object on turns whose plan belongs to the
8524
10834
  * user's actual request. A plan left paused in an earlier turn must not turn
8525
- * every later "谢谢/进度如何" turn into a forced 20-minute dispatch, so the
10835
+ * every later "谢谢/进度如何" turn into a forced dispatch(现行轮次预算默认
10836
+ * 关闭,TOTAL_TIMEOUT_MS=0;此处只拦「带真实任务文本的轮次」),so the
8526
10837
  * stop gate reads this marker and stays silent on social or status turns.
8527
10838
  */
8528
10839
  if (!state.activeTurns)
@@ -8703,6 +11014,21 @@ async function maybePlan(ctx, state, payload, downstream, options) {
8703
11014
  createdTurn: payload.turn,
8704
11015
  };
8705
11016
  state.records.set(session.id, planningRecord);
11017
+ /*
11018
+ * [2.3.10][T2] 用户要求1(P1):规划前会话内预告规划耗时。此前该时点只有
11019
+ * 侧栏占位卡、无会话输出(T1 E6);现在在 runPlanner 之前经唯一合规写入器
11020
+ * appendUserMessage 发一条【规划预告】。预估与 runPlanner 同源:同一个
11021
+ * normalisePlannerWindow 解析出的实际窗口(含配置/环境变量覆盖)。
11022
+ */
11023
+ /*
11024
+ * [3.0.0][用户要求 2] 从接收到用户任何任务开始,会话内必须输出固定文案
11025
+ * 「任务正在分配中,请稍等一下......」。逐字冻结文案来自 v3-contract,
11026
+ * 与用户原文逐字一致(6 个半角点),不得拼接、不得改写。
11027
+ * 位置:任何规划动作之前(含规划预告之前),保证用户先看到「正在分配」。
11028
+ * deferUntilHead:受保护系统头未落地前暂存,落地后按序补发(2.5.5 治本)。
11029
+ */
11030
+ appendUserMessage(session, STATUS_ASSIGNING_TEXT, undefined, { deferUntilHead: true });
11031
+ appendUserMessage(session, buildPlanningPreAnnouncement(normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS), PLANNER_MAX_ATTEMPTS), undefined, { deferUntilHead: true });
8706
11032
  /*
8707
11033
  * [2.2.5][T5] 进度回调落点(T1 P-6 / T3 §3 C2/C3、§4 频率规则):
8708
11034
  * 通道 A = 占位卡片 errors 区追加重试摘要(≤2 行,保底通道);通道 B =
@@ -8710,163 +11036,296 @@ async function maybePlan(ctx, state, payload, downstream, options) {
8710
11036
  * 文案组装与频率硬规则全部在 createPlannerProgressReporter / plannerProgressLines
8711
11037
  * (plan.ts,可独立回归);这里只注入宿主交互面。
8712
11038
  */
8713
- const onPlannerProgress = createPlannerProgressReporter({
8714
- signal: payload.signal,
8715
- record: planningRecord,
8716
- setRecord: (record) => state.records.set(session.id, record),
8717
- appendNotice: (text) => appendUserMessage(session, text),
8718
- maxAttempts: PLANNER_MAX_ATTEMPTS,
8719
- });
8720
- try {
8721
- plan = await runPlanner(ctx, {
8722
- taskText,
8723
- cwd: session.header?.cwd ?? options.cwd,
8724
- sessionId: session.id,
8725
- modelSelection,
11039
+ /*
11040
+ * [3.0.0][用户要求 1 / 2 治本 —— 依据 T4 根因报告(reports/T4b-会话内容丢失根因报告-20261114.md)]
11041
+ *
11042
+ * 缺陷实证(T4,3497 个会话 / 4034 轮对照):宿主在 pre-step 之前就认领
11043
+ * 用户消息,人类 user/message 只在首个 model step 内部落盘;而本插件在
11044
+ * pre-step 里 `await runPlanner`,把这一步推迟到分钟级(含规划轮的轮次
11045
+ * p50=58.4s、p90=250s,不含的 p50=0.04s)。这段时间里会话日志没有任何
11046
+ * 可渲染的任务正文,屏幕上唯一副本是客户端回声,而客户端在收到回执后
11047
+ * 无条件退休该回声——于是「切走会话再切回」就看不到用户刚输入的任务。
11048
+ *
11049
+ * 治本:pre-step 不再等待规划。先同步放行本步(模型立即看到「正在分配」
11050
+ * 的注入说明,不会自己去执行用户任务),规划转后台继续:计划一成即经唯一
11051
+ * 合规写入器 appendUserMessage 写入会话并按既有路径自动派发。这样首 step
11052
+ * 在秒级启动 → 宿主立即落盘人类消息、暂存的通知按序补发,任务正文与固定
11053
+ * 文案都在切会话前后稳定可见。
11054
+ *
11055
+ * 中止语义不变:仍沿用本步的 payload.signal(宿主只在 cancel/中断时 abort
11056
+ * 该信号,正常收尾不 abort),用户中断时后台规划与以前一样静默退出。
11057
+ * 幂等:同一会话已有规划在跑时直接放行本步,不会重复规划。
11058
+ */
11059
+ const deliver = (messages) => {
11060
+ for (const message of messages) {
11061
+ try {
11062
+ /*
11063
+ * 后台路径没有 pre-step 的返回值可用,只能写进会话(append-only)。
11064
+ * deferUntilHead 由 appendUserMessage 自身按「受保护系统头是否已落地」
11065
+ * 判定,与本步的窗口标记无关,因此不会写出头前 surface。
11066
+ */
11067
+ appendUserMessage(session, message);
11068
+ }
11069
+ catch (error) {
11070
+ pushRecordError(planningRecord, error);
11071
+ }
11072
+ }
11073
+ };
11074
+ if (!state.planningInFlight)
11075
+ state.planningInFlight = new Map();
11076
+ if (state.planningInFlight.has(session.id))
11077
+ return downstream;
11078
+ state.planningInFlight.set(session.id, planningStartedAt);
11079
+ const runPlanningInBackground = async () => {
11080
+ let plannerAttempt = 1;
11081
+ const onPlannerProgress = createPlannerProgressReporter({
8726
11082
  signal: payload.signal,
8727
- plannerTimeoutMs: normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
8728
- plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
8729
- telemetry: plannerTelemetry,
8730
- // [2.2.5][T5] 分解期间进度事件(T1 P-6):只追加观察回调,不改重试语义。
8731
- onProgress: onPlannerProgress,
8732
- conversationContext,
8733
- sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
8734
- /*
8735
- * Hand the real limits to the planner. Without them it had no idea the
8736
- * round budget was 20 minutes and happily planned 15 heavy subtasks,
8737
- * which then died at the budget wall. The prompt now states the budget
8738
- * and asks for `estimateMinutes` on every subtask.
8739
- */
8740
- budget: {
8741
- totalMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
8742
- ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
8743
- : 0,
8744
- childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
8745
- concurrency: MAX_CONCURRENT,
8746
- maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
8747
- },
11083
+ record: planningRecord,
11084
+ setRecord: (record) => state.records.set(session.id, record),
11085
+ appendNotice: (text) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
11086
+ maxAttempts: PLANNER_MAX_ATTEMPTS,
8748
11087
  });
8749
- }
8750
- catch (error) {
8751
- if (payload.signal.aborted) {
11088
+ /*
11089
+ * [2.5.2] 规划期间心跳(治本:用户 2026-11-11 报告本会话 turn 1 规划 12.5
11090
+ * 分钟全程零会话输出、以为死机并手动中断)。失败重试回报器只在「失败且
11091
+ * 退避重试」时发通知;一次持续流式但很慢的尝试不失败也不触发 idle,于是
11092
+ * 预告之后整段静默。心跳与重试正交:只要 runPlanner 还在跑,就按固定间隔
11093
+ * 经唯一合规写入器发一条「仍在生成、已用时多久、不是卡死」的可见通知。
11094
+ * 写入仍是 user/message(surfaceOp:'append'、形状校验),不新增事件类型、
11095
+ * 不触碰 system/message,不会引入会话日志损坏;finally 里 stop,绝不残留。
11096
+ */
11097
+ const planningHeartbeat = createPlanningHeartbeat({
11098
+ signal: payload.signal,
11099
+ appendNotice: (text) => appendUserMessage(session, text, undefined, { deferUntilHead: true }),
11100
+ intervalMs: planningHeartbeatIntervalMs(process.env.DSH_WORKPLAN_PLANNING_HEARTBEAT_MS ?? PLANNING_HEARTBEAT_MS),
11101
+ startedAt: planningStartedAt,
11102
+ getAttempt: () => plannerAttempt,
11103
+ maxAttempts: PLANNER_MAX_ATTEMPTS,
11104
+ });
11105
+ planningHeartbeat.start();
11106
+ try {
11107
+ plan = await runPlanner(ctx, {
11108
+ taskText,
11109
+ cwd: session.header?.cwd ?? options.cwd,
11110
+ sessionId: session.id,
11111
+ modelSelection,
11112
+ signal: payload.signal,
11113
+ plannerTimeoutMs: normalisePlannerWindow(options?.limits?.plannerTimeoutMs ?? options?.plannerTimeoutMs, PLANNER_TIMEOUT_MS),
11114
+ plannerIdleTimeoutMs: normalisePlannerWindow(options?.limits?.plannerIdleTimeoutMs ?? options?.plannerIdleTimeoutMs, PLANNER_IDLE_TIMEOUT_MS),
11115
+ telemetry: plannerTelemetry,
11116
+ // [2.2.5][T5] 分解期间进度事件(T1 P-6):只追加观察回调,不改重试语义。
11117
+ onProgress: (report) => {
11118
+ // [2.5.2] 顺带记录当前尝试序号,供心跳文案显示「第 N/M 次尝试」。
11119
+ const failedAttempt = Number(report?.attempt) || 0;
11120
+ if (failedAttempt > 0) {
11121
+ const willRetry = Number(report?.retryBackoffMs) > 0 && failedAttempt < PLANNER_MAX_ATTEMPTS;
11122
+ plannerAttempt = Math.min(PLANNER_MAX_ATTEMPTS, willRetry ? failedAttempt + 1 : failedAttempt);
11123
+ }
11124
+ onPlannerProgress(report);
11125
+ },
11126
+ conversationContext,
11127
+ sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
11128
+ /*
11129
+ * Hand the real limits to the planner. Without them it had no idea the
11130
+ * round budget was 20 minutes and happily planned 15 heavy subtasks,
11131
+ * which then died at the budget wall. The prompt now states the budget
11132
+ * and asks for `estimateMinutes` on every subtask.
11133
+ */
11134
+ budget: {
11135
+ totalMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
11136
+ ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
11137
+ : 0,
11138
+ childMinutes: Math.max(1, Math.round(Number(options?.limits?.childTimeoutMs ?? CHILD_TIMEOUT_MS) / 60000)),
11139
+ concurrency: MAX_CONCURRENT,
11140
+ maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
11141
+ },
11142
+ });
11143
+ }
11144
+ catch (error) {
11145
+ if (payload.signal.aborted) {
11146
+ /*
11147
+ * [2.2.5][T5] 用户中止:静默退出(T3 §2 中止分支,不发通知)。占位卡片
11148
+ * 若本轮前无旧记录,交给 serialisePlan 终态收敛转 'ended',不留假
11149
+ * 「进行中」;若本轮前已有旧计划记录,恢复它——中止不该把用户上一份
11150
+ * 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
11151
+ */
11152
+ if (existing?.plan)
11153
+ state.records.set(session.id, existing);
11154
+ return;
11155
+ }
8752
11156
  /*
8753
- * [2.2.5][T5] 用户中止:静默退出(T3 §2 中止分支,不发通知)。占位卡片
8754
- * 若本轮前无旧记录,交给 serialisePlan 终态收敛转 'ended',不留假
8755
- * 「进行中」;若本轮前已有旧计划记录,恢复它——中止不该把用户上一份
8756
- * 终态进度从内存里挤掉(旧实现中止路径不写记录,此行为保持不变)。
11157
+ * [3.0.1] 规划守卫判定「只有用户能答复」(CLARIFY_NEEDED):与规划前的
11158
+ * C1–C4 澄清闸同一条出口——写 clarify 记录、把问题原样转给用户、本轮回合
11159
+ * 直接结束。不降级、不生成计划、不派发;用户的下一条答复会带着答案重新
11160
+ * 进入规划。在降级路径之前拦截,否则这里会把「等用户」误报成「分解失败」。
8757
11161
  */
11162
+ if (error instanceof PlanError && error.code === 'CLARIFY_NEEDED') {
11163
+ const createdAt = Date.now();
11164
+ state.records.set(session.id, {
11165
+ planId: null,
11166
+ plan: null,
11167
+ title: '任务信息不足(先澄清)',
11168
+ degraded: false,
11169
+ clarify: true,
11170
+ error: error.message,
11171
+ statuses: [],
11172
+ phase: 'clarify',
11173
+ errors: [truncate(error.message, 1000)],
11174
+ createdAt,
11175
+ updatedAt: createdAt,
11176
+ createdTurn: payload.turn,
11177
+ });
11178
+ return enterDecision(downstream, [buildClarifyMessage({
11179
+ rule: 'AUDIT',
11180
+ reason: error.message,
11181
+ question: typeof error.details === 'string' && error.details.trim() !== '' ? error.details : '',
11182
+ })]);
11183
+ }
11184
+ const planId = `wp-${randomUUID()}`;
11185
+ const createdAt = Date.now();
11186
+ const message = buildDegradedMessage({
11187
+ planId,
11188
+ sessionId: session.id,
11189
+ createdTurn: payload.turn,
11190
+ createdAt,
11191
+ error: error instanceof Error ? error.message : String(error),
11192
+ detail: plannerTelemetryLine(plannerTelemetry),
11193
+ taskText,
11194
+ });
11195
+ state.records.set(session.id, {
11196
+ planId,
11197
+ plan: null,
11198
+ title: '自动分解降级',
11199
+ degraded: true,
11200
+ error: error instanceof Error ? error.message : String(error),
11201
+ planner: { ...plannerTelemetry, at: createdAt },
11202
+ statuses: [],
11203
+ phase: 'degraded',
11204
+ errors: [truncate(error instanceof Error ? error.message : String(error), 1000)],
11205
+ createdAt,
11206
+ updatedAt: createdAt,
11207
+ createdTurn: payload.turn,
11208
+ });
11209
+ return deliver([message]);
11210
+ }
11211
+ finally {
11212
+ // [2.5.2] 无论成功/降级/中止,规划结束即停心跳,绝不残留定时器。
11213
+ planningHeartbeat.stop();
11214
+ }
11215
+ if (payload.signal.aborted) {
11216
+ // [2.2.5][T5] 计划已生成但回合被中止:同中止分支,恢复旧记录再静默退出。
8758
11217
  if (existing?.plan)
8759
11218
  state.records.set(session.id, existing);
8760
- return downstream;
11219
+ return;
8761
11220
  }
8762
11221
  const planId = `wp-${randomUUID()}`;
8763
11222
  const createdAt = Date.now();
8764
- const message = buildDegradedMessage({
11223
+ const fullPlan = attachPlanMeta(plan, {
8765
11224
  planId,
8766
11225
  sessionId: session.id,
8767
11226
  createdTurn: payload.turn,
8768
11227
  createdAt,
8769
- error: error instanceof Error ? error.message : String(error),
8770
- detail: plannerTelemetryLine(plannerTelemetry),
8771
- taskText,
11228
+ sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
8772
11229
  });
8773
- state.records.set(session.id, {
8774
- planId,
8775
- plan: null,
8776
- title: '自动分解降级',
8777
- degraded: true,
8778
- error: error instanceof Error ? error.message : String(error),
8779
- planner: { ...plannerTelemetry, at: createdAt },
8780
- statuses: [],
8781
- phase: 'degraded',
8782
- errors: [truncate(error instanceof Error ? error.message : String(error), 1000)],
11230
+ const record = {
11231
+ plan: fullPlan,
11232
+ statuses: createStatuses(fullPlan),
11233
+ phase: 'pending',
11234
+ errors: [],
11235
+ // [2.1.6] 规划这一步花了多久、用的哪个模型:成功也留痕,失败才好对比。
11236
+ // [2.1.7] 抢救成功的计划保留 SALVAGED 判定,别被 'ok' 覆盖——它是复盘的关键证据。
11237
+ planner: { ...plannerTelemetry, outcome: plannerTelemetry.outcome === 'SALVAGED' ? 'SALVAGED' : 'ok', at: createdAt },
8783
11238
  createdAt,
8784
11239
  updatedAt: createdAt,
8785
- createdTurn: payload.turn,
11240
+ dispatchedAt: null,
11241
+ dispatchPromise: null,
11242
+ modelSelection,
11243
+ conversationContext,
11244
+ planMode,
11245
+ };
11246
+ state.records.set(session.id, record);
11247
+ /*
11248
+ * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
11249
+ * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
11250
+ * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
11251
+ */
11252
+ const autoDispatched = !planMode && options?.autoDispatch !== false;
11253
+ /*
11254
+ * Plan-first: commit the plan with this step and let the main Agent call
11255
+ * dsh_workplan_dispatch. Dispatching here would hide the plan until every
11256
+ * child finished, which is exactly the "没动静/没完成" failure.
11257
+ *
11258
+ * [1.12.0] There is no tool guard that forces dispatch before other work —
11259
+ * `toolGuardReason` only denies dispatch in plan mode and `present` when the
11260
+ * plan is not ready. What actually enforces the ordering is the system
11261
+ * prompt, plus the turn-stopping gate steering at most twice per turn
11262
+ * (`STOP_STEER_LIMIT`); if the model still never dispatches, the next turn
11263
+ * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
11264
+ */
11265
+ const planMessage = buildPlanMessage(fullPlan, {
11266
+ totalBudgetMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
11267
+ ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
11268
+ : 0,
11269
+ maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
11270
+ planMode,
11271
+ autoDispatched,
8786
11272
  });
8787
- return enterDecision(downstream, [message]);
8788
- }
8789
- if (payload.signal.aborted) {
8790
- // [2.2.5][T5] 计划已生成但回合被中止:同中止分支,恢复旧记录再静默退出。
8791
- if (existing?.plan)
8792
- state.records.set(session.id, existing);
8793
- return downstream;
8794
- }
8795
- const planId = `wp-${randomUUID()}`;
8796
- const createdAt = Date.now();
8797
- const fullPlan = attachPlanMeta(plan, {
8798
- planId,
8799
- sessionId: session.id,
8800
- createdTurn: payload.turn,
8801
- createdAt,
8802
- sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
8803
- });
8804
- const record = {
8805
- plan: fullPlan,
8806
- statuses: createStatuses(fullPlan),
8807
- phase: 'pending',
8808
- errors: [],
8809
- // [2.1.6] 规划这一步花了多久、用的哪个模型:成功也留痕,失败才好对比。
8810
- // [2.1.7] 抢救成功的计划保留 SALVAGED 判定,别被 'ok' 覆盖——它是复盘的关键证据。
8811
- planner: { ...plannerTelemetry, outcome: plannerTelemetry.outcome === 'SALVAGED' ? 'SALVAGED' : 'ok', at: createdAt },
8812
- createdAt,
8813
- updatedAt: createdAt,
8814
- dispatchedAt: null,
8815
- dispatchPromise: null,
8816
- modelSelection,
8817
- conversationContext,
8818
- planMode,
11273
+ /*
11274
+ * [3.0.0][顺序] 必须先让计划可见,再开跑、再发「分配完成」:
11275
+ * 用户要求 4 的文案由 dispatchPlan 在真正开跑时写入,若自动派发抢在计划
11276
+ * 消息之前,用户会先看到「分配完成」再看到计划(T6 设计复核 D2)。因此这里
11277
+ * 先 deliver 计划消息,再启动自动派发。
11278
+ */
11279
+ if (!planMode) {
11280
+ deliver([planMessage]);
11281
+ if (autoDispatched) {
11282
+ record.dispatchedAt = Date.now();
11283
+ // [T7] C3 整轮预算:自动派发同样重置(与显式派发同口径)。
11284
+ resetRoundInjectionBudget(session, `${record.plan.planId}:${record.dispatchedAt}`);
11285
+ state.startAutoDispatch?.(record, session, payload.agent);
11286
+ }
11287
+ return;
11288
+ }
11289
+ /*
11290
+ * Plan mode is a planning-only collaboration state: the plugin must still
11291
+ * decompose the task and show the plan, but it must not start department
11292
+ * Agents before the user approves/leaves plan mode. The main Agent is told
11293
+ * to present this plan; dsh_workplan_dispatch is separately denied while
11294
+ * plan mode is active.
11295
+ */
11296
+ const note = {
11297
+ id: randomUUID(),
11298
+ role: 'user',
11299
+ content: [{
11300
+ type: 'text',
11301
+ text: '当前处于 plan 模式:本计划只用于规划,不会启动部门 Agent。请先把上面的任务分解交给用户审阅;用户退出 plan 模式后,再调用 dsh_workplan_dispatch 执行。',
11302
+ }],
11303
+ source: { kind: 'workplan', form: 'notice', summary: 'plan 模式:计划已生成,等待用户审阅后派发' },
11304
+ };
11305
+ return deliver([planMessage, note]);
8819
11306
  };
8820
- state.records.set(session.id, record);
8821
- /*
8822
- * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
8823
- * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
8824
- * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
8825
- */
8826
- const autoDispatched = !planMode && options?.autoDispatch !== false;
8827
- if (autoDispatched) {
8828
- record.dispatchedAt = Date.now();
8829
- state.startAutoDispatch?.(record, session, payload.agent);
8830
- }
8831
- /*
8832
- * Plan-first: commit the plan with this step and let the main Agent call
8833
- * dsh_workplan_dispatch. Dispatching here would hide the plan until every
8834
- * child finished, which is exactly the "没动静/没完成" failure.
8835
- *
8836
- * [1.12.0] There is no tool guard that forces dispatch before other work —
8837
- * `toolGuardReason` only denies dispatch in plan mode and `present` when the
8838
- * plan is not ready. What actually enforces the ordering is the system
8839
- * prompt, plus the turn-stopping gate steering at most twice per turn
8840
- * (`STOP_STEER_LIMIT`); if the model still never dispatches, the next turn
8841
- * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
8842
- */
8843
- const planMessage = buildPlanMessage(fullPlan, {
8844
- totalBudgetMinutes: Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) > 0
8845
- ? Math.max(1, Math.round(Number(options.limits.totalTimeoutMs) / 60000))
8846
- : 0,
8847
- maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
8848
- planMode,
8849
- autoDispatched,
8850
- });
8851
- if (!planMode)
8852
- return enterDecision(downstream, [planMessage]);
11307
+ void (async () => {
11308
+ try {
11309
+ await runPlanningInBackground();
11310
+ }
11311
+ catch (error) {
11312
+ pushRecordError(planningRecord, error);
11313
+ }
11314
+ finally {
11315
+ state.planningInFlight.delete(session.id);
11316
+ }
11317
+ })();
8853
11318
  /*
8854
- * Plan mode is a planning-only collaboration state: the plugin must still
8855
- * decompose the task and show the plan, but it must not start department
8856
- * Agents before the user approves/leaves plan mode. The main Agent is told
8857
- * to present this plan; dsh_workplan_dispatch is separately denied while
8858
- * plan mode is active.
11319
+ * 同步注入给本步模型的说明:先等计划,不要自己动手做用户的活。文案复用
11320
+ * 用户逐字冻结的 STATUS_ASSIGNING_TEXT,不另造第二份固定文案。
8859
11321
  */
8860
- const note = {
8861
- id: randomUUID(),
8862
- role: 'user',
8863
- content: [{
8864
- type: 'text',
8865
- text: '当前处于 plan 模式:本计划只用于规划,不会启动部门 Agent。请先把上面的任务分解交给用户审阅;用户退出 plan 模式后,再调用 dsh_workplan_dispatch 执行。',
8866
- }],
8867
- source: { kind: 'workplan', form: 'notice', summary: 'plan 模式:计划已生成,等待用户审阅后派发' },
8868
- };
8869
- return enterDecision(downstream, [planMessage, note]);
11322
+ return enterDecision(downstream, [makeUserMessage(
11323
+ /*
11324
+ * [3.0.0][不重复] 固定文案已由上面的 appendUserMessage(STATUS_ASSIGNING_TEXT)
11325
+ * 写入会话,这里只给本步模型一条行为说明——绝不第二次复述同一句固定文案,
11326
+ * 否则用户会看到两条一模一样的「任务正在分配中」。
11327
+ */
11328
+ '(dsh-workplan:任务分解已在后台生成中,计划一生成就立即显示在本会话并自动派发;现在请不要自己动手执行用户任务,也不要提前收尾,先简短告知用户正在分配。)', { kind: 'workplan', form: 'notice', summary: '任务分解已转为后台生成' })]);
8870
11329
  }
8871
11330
  export function plannerOutputSchema() {
8872
11331
  return {