dsh-workplan 2.1.5 → 2.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/plan.js CHANGED
@@ -11,6 +11,7 @@ import { DEPARTMENT_CAPABILITIES, DEPARTMENT_EXPERT_STANDARD, departmentCapabili
11
11
  import { MAX_TASK_ANCHOR_CHARS } from './understanding.js';
12
12
  import { isMappingDigest, verifyMappingDigest } from './supersede-digest.js';
13
13
  import { phaseSummaryLine, threePhasePromptLines, validatePhaseEvidence } from './three-phase.js';
14
+ import { NOTICE_TARGET_MISSING_TEXT, leadNoticeCallForm, readLeadAgentId, validateNoticeChannel, } from './notice-channel.js';
14
15
  import { checkCommFormatCompliance, renderCommFormatRejection, renderCommFormatSpec, } from './comm-format.js';
15
16
  export const PLAN_VERSION = 1;
16
17
  /**
@@ -160,6 +161,24 @@ export const HANDOFF_STATUSES = Object.freeze(['open', 'routed', 'answered', 'cl
160
161
  export const MAX_HANDOFFS = MAX_EVIDENCE_NEEDS;
161
162
  export const MAX_HANDOFF_RESPONSE_CHARS = 4000;
162
163
  export const LIKELIHOODS = Object.freeze(['low', 'medium', 'high']);
164
+ /*
165
+ * [2.2.0][T13/推理等级] 子 Agent 的推理等级白名单(用户强制规则)。
166
+ * [2.2.7][T2/五档] 白名单由三档(low / high / max)扩展为五档
167
+ * (low / medium / high / xhigh / max)。唯二事实源:本常量与 client.ts 的
168
+ * UI Pill 内联数组,二者必须同步;本文件校验、runtime.ts env 校验(L775)
169
+ * 与派发透传(L1910)三处均由本常量驱动,改一处全链生效。旧三档值是五档
170
+ * 的子集,旧计划序列化/回放/派发零迁移。
171
+ *
172
+ * 用户规则原文(五档版):「禁止子agent继承主agent的推理等级。其中,轻度
173
+ * 复杂的任务必须使用low,中等复杂的任务必须使用medium或high,非常复杂的
174
+ * 任务必须使用xhigh或max。主agent和子agent必须分别根据自己要执行的任务的
175
+ * 复杂度,分别自己判断使用哪个推理等级,推理等级包括low、medium、high、
176
+ * xhigh或max。」
177
+ * 子任务未声明该字段时回落 high(中等档默认,D1 决策保持;缺失合法语义
178
+ * 不变);执行侧绝不读取主 Agent 的等级。
179
+ */
180
+ export const REASONING_EFFORTS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
181
+ export const DEFAULT_REASONING_EFFORT = 'high';
163
182
  export const DEPARTMENTS = Object.freeze({
164
183
  engineering: { zh: '工程研发', en: 'Engineering' },
165
184
  research: { zh: '研究分析', en: 'Research' },
@@ -600,6 +619,63 @@ function readSubtasks(value, stageIndex, errors) {
600
619
  if (!DEPARTMENTS[department]) {
601
620
  push(errors, `${base}.department`, `必须是 ${DEPARTMENT_IDS.join(' / ')} 之一`);
602
621
  }
622
+ /*
623
+ * [2.2.0][T3/O-2b] 预估区间改判:1-240 整数,越界拒绝、区间内原样保留。
624
+ *
625
+ * 方案原文(docs/dsh-workplan_优化方案_20261107.md):
626
+ * - §2.2「estimateMinutes 钳制放宽为 1–240 整数(仅防离谱值,advisory 不变)」;
627
+ * - §1⑤ O-5c「固定区间去钳制:同 O-2b」;
628
+ * - §1② B2「estimateMinutes: 90 的计划通过校验且原样保留(不再被钳成 15)」。
629
+ * 「去钳制 + 原样保留 + 仅防离谱值」的唯一自洽合成:合法区间内不再改写值,
630
+ * 0/241 等离谱值**拒绝**并点名字段(不是钳成 1/240 蒙混通过)——与同源用例
631
+ * tests/time-estimate-negotiation.test.ts(0 与 241 被拒、1/90/240 原样保留)一致。
632
+ * 可选与缺省合法的宽容面保留(旧计划零回归,验收 ②B4):没有 estimateMinutes
633
+ * 的计划照旧通过校验。歧义链与 Z8 红线取舍见
634
+ * docs/dsh-workplan_T3_plan改动说明_20261107.md。
635
+ */
636
+ const hasEstimate = source.estimateMinutes !== undefined && source.estimateMinutes !== null;
637
+ const estimateValue = hasEstimate ? Number(source.estimateMinutes) : NaN;
638
+ const estimateOk = hasEstimate
639
+ && typeof source.estimateMinutes === 'number'
640
+ && Number.isInteger(estimateValue)
641
+ && estimateValue >= 1
642
+ && estimateValue <= 240;
643
+ if (hasEstimate && !estimateOk) {
644
+ push(errors, `${base}.estimateMinutes`, '必须是 1-240 的整数(仅防离谱值:越界或非整数拒绝、不改写;该字段可选,缺失合法)');
645
+ }
646
+ /*
647
+ * [2.2.0][T3/O-3a] per-subtask 协商上限(timeoutMs,毫秒)可选透传。
648
+ *
649
+ * 方案 §2.2:「timeoutMs(可选)|本子任务的协商上限;缺省由 estimateMinutes
650
+ * × 2.0 派生并钳制|readSubtasks + validatePlan 只校验类型与范围,缺省合法」。
651
+ * 原样透传、不在此处钳到 MAX(同源用例 tests/time-estimate-negotiation.test.ts
652
+ * 固化 timeoutMs: 3600000 原样保留);只校验类型与范围:正数毫秒,缺失合法。
653
+ * 范围上界方案未给定(未知/待核实,见改动说明歧义点 3)。
654
+ */
655
+ const hasTimeout = source.timeoutMs !== undefined && source.timeoutMs !== null;
656
+ const timeoutValue = hasTimeout ? Number(source.timeoutMs) : NaN;
657
+ const timeoutOk = hasTimeout
658
+ && typeof source.timeoutMs === 'number'
659
+ && Number.isFinite(timeoutValue)
660
+ && timeoutValue > 0;
661
+ if (hasTimeout && !timeoutOk) {
662
+ push(errors, `${base}.timeoutMs`, '必须是正数毫秒(协商上限,可选字段,缺失合法)');
663
+ }
664
+ /*
665
+ * [2.2.0][T13/推理等级] 子任务自带的推理等级(可选,仅 low / medium / high / xhigh / max)。
666
+ *
667
+ * 用户规则原文见 REASONING_EFFORTS 上方注释。语义与 estimateMinutes 同风格:
668
+ * 缺失合法(旧计划/回放零回归),但非法值**拒绝**并点名字段,不静默改写成
669
+ * 其它档位;执行侧对缺失值回落 DEFAULT_REASONING_EFFORT(high),绝不继承
670
+ * 主 Agent 的等级。
671
+ */
672
+ const hasEffort = source.reasoningEffort !== undefined && source.reasoningEffort !== null;
673
+ const effortOk = hasEffort
674
+ && typeof source.reasoningEffort === 'string'
675
+ && REASONING_EFFORTS.includes(source.reasoningEffort);
676
+ if (hasEffort && !effortOk) {
677
+ push(errors, `${base}.reasoningEffort`, '必须是 low / medium / high / xhigh / max 之一(可选字段,缺失时回落 high;非法值拒绝,不改写)');
678
+ }
603
679
  return {
604
680
  id: readString(source.id, `${base}.id`, 1, 16, errors),
605
681
  title: readString(source.title, `${base}.title`, 1, 200, errors),
@@ -633,13 +709,47 @@ function readSubtasks(value, stageIndex, errors) {
633
709
  * [1.7.0] Optional time estimate, advisory only. Validation never fails on
634
710
  * a missing or out-of-range value: a plan that cannot be dispatched is
635
711
  * worse than one carrying a rough estimate.
712
+ * [2.2.0][T3/O-2b] 语义演进(上方校验块注释引方案原文):缺省仍然合法;
713
+ * 越界自 2.2.0 起拒绝而非钳制(§1⑤ O-5c 固定区间去钳制),本注释保留为
714
+ * [1.7.0] 历史记录。
636
715
  */
637
- ...(Number.isFinite(Number(source.estimateMinutes))
638
- ? { estimateMinutes: Math.min(15, Math.max(1, Math.round(Number(source.estimateMinutes)))) }
639
- : {}),
716
+ ...(estimateOk ? { estimateMinutes: estimateValue } : {}),
717
+ ...(timeoutOk ? { timeoutMs: timeoutValue } : {}),
718
+ // [2.2.7][T4/五档] 缺省回落保持 high(DEFAULT_REASONING_EFFORT,D1 决策):
719
+ // 白名单由三档扩为五档(low / medium / high / xhigh / max)后,high 仍是
720
+ // 缺失时的默认档——high 属「中等复杂」区间,向后兼容旧三档计划与回放,
721
+ // 零迁移;非法值已在上方校验块拒绝,不会静默改写。
722
+ reasoningEffort: effortOk ? String(source.reasoningEffort) : DEFAULT_REASONING_EFFORT,
640
723
  };
641
724
  });
642
725
  }
726
+ /**
727
+ * [2.2.0][T3/O-3a] per-subtask 协商上限(negotiated ceiling)派生公式。
728
+ *
729
+ * 方案 §1③ O-3a:「缺省时由预估派生:协商上限 = clamp(预估分钟 × 安全系数
730
+ * (建议 2.0), 全局下限, 单次绝对上限)」;§2.2 timeoutMs 行:「缺省由
731
+ * `estimateMinutes × 2.0` 派生并钳制」。分钟→毫秒按 ×60000 换算(同源用例
732
+ * tests/time-estimate-negotiation.test.ts 的 expected 公式逐字一致)。
733
+ *
734
+ * 消费序(O-3b 接线契约,runtime 侧):显式 subtask.timeoutMs(O-3c:预告经
735
+ * 主 Agent 确认后写入,原样透传)→ 缺省调用本函数派生(钳在 [minMs, maxMs],
736
+ * 验收 ③C3)→ 两者皆无(旧计划无 estimateMinutes 也无 timeoutMs)返回
737
+ * undefined,消费侧回落原行为(normaliseChildTimeout 全局兜底,验收 ③C2)。
738
+ * 本函数只做「预估→派生值」纯换算,不读 subtask 对象。
739
+ *
740
+ * MIN_CHILD_TIMEOUT_MS=1,000 毫秒不变(与 src/runtime.ts:220 现状同值)。
741
+ * MAX_CHILD_TIMEOUT_MS=7,200,000 毫秒(120 分钟)=plan.ts 侧派生上限——
742
+ * 【用户 2026-11-07 决断】方案 §6 未知第 4 条已由用户拍板上调;runtime.ts:221
743
+ * 常量本体由 T4 波次同步改(改前两处不同值时以本决断为准)。
744
+ * plan.ts 被 runtime.ts 反向依赖(runtime.ts import './plan.js'),不能反向
745
+ * import,故此处带默认值、调用方可传入权威常量。
746
+ */
747
+ export function deriveSubtaskTimeoutMs(estimateMinutes, minMs = 1000, maxMs = 7200000) {
748
+ const estimate = Number(estimateMinutes);
749
+ if (!Number.isFinite(estimate) || estimate <= 0)
750
+ return undefined;
751
+ return Math.min(maxMs, Math.max(minMs, estimate * 2.0 * 60_000));
752
+ }
643
753
  function readStages(value, errors) {
644
754
  if (!Array.isArray(value)) {
645
755
  push(errors, 'stages', '必须是数组');
@@ -1042,7 +1152,10 @@ export function buildPlannerPrompt(taskText, cwd, conversationContext = '', budg
1042
1152
  const departments = DEPARTMENT_CAPABILITIES
1043
1153
  .map((entry) => `- ${entry.id}(${entry.zh} / ${entry.en}):职责 ${entry.responsibilities.join(';')};典型产物 ${entry.outputs.join(';')}`)
1044
1154
  .join('\n');
1045
- const totalMinutes = Math.max(1, Math.round(Number(budget?.totalMinutes) || 20));
1155
+ const rawTotalMinutes = Number(budget?.totalMinutes);
1156
+ const totalMinutes = Number.isFinite(rawTotalMinutes) && rawTotalMinutes > 0
1157
+ ? Math.max(1, Math.round(rawTotalMinutes))
1158
+ : 0;
1046
1159
  const childMinutes = Math.max(1, Math.round(Number(budget?.childMinutes) || 15));
1047
1160
  const concurrency = Math.max(1, Number(budget?.concurrency) || MAX_CONCURRENT);
1048
1161
  const resumes = Number.isFinite(Number(budget?.maxResumes)) ? Number(budget.maxResumes) : MAX_PLAN_RESUMES;
@@ -1079,13 +1192,31 @@ export function buildPlannerPrompt(taskText, cwd, conversationContext = '', budg
1079
1192
  '- unknowns 和 assumptions 必须如实列出;没有就写空数组,不能把假设写成事实。',
1080
1193
  '- 子任务必须可独立执行、可验收;不要为了凑数拆无意义任务。',
1081
1194
  '- 子任务由子 Agent 独立执行:它们没有派发权限、不能重启服务、不能安装或升级依赖。禁止把「调用 dsh_workplan_dispatch」「重启/停止 dsh web」「安装或升级插件」这类只有主 Agent 才能执行的动作写进子任务;确实需要时,写成“给出结论或建议,由主 Agent 执行”。',
1082
- '- 单个子任务应能在 10 分钟内完成;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1195
+ '- 单个子任务无须在 10 分钟内完成——10 分钟只是拆步规模建议,不是完成期限、也不构成承诺;实际时长由执行专家开工预告协商决定,不设固定完成时间;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1083
1196
  '- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
1084
1197
  '',
1085
1198
  '本轮时间预算(硬事实,请据此规划规模):',
1086
- `- 一轮总预算约 ${totalMinutes} 分钟;单个子任务上限 ${childMinutes} 分钟;同时最多 ${concurrency} 个子任务并行。`,
1087
- `- 受阻后自动续跑额度 ${resumes} 次;总工作量超过一轮预算时,计划会被暂停并在下一轮继续。`,
1088
- '- 每个子任务必须写 estimateMinutes(整数 1-15):你预估它需要多少分钟。宁可估高,不要估低。',
1199
+ totalMinutes > 0
1200
+ ? `- 一轮总预算约 ${totalMinutes} 分钟(安全兜底,不是交付期限);单个子任务规模参考 ${childMinutes} 分钟量级(仅供参考、非承诺,实际时长由执行专家开工预告协商决定);同时最多 ${concurrency} 个子任务并行。`
1201
+ : `- 本轮不设固定总预算;单个子任务按自身 estimateMinutes 与协商截止/延期执行;同时最多 ${concurrency} 个子任务并行。`,
1202
+ resumes > 0
1203
+ ? `- 受阻后自动续跑额度 ${resumes} 次;需要时计划会暂停并在下一轮继续。`
1204
+ : '- 自动续跑额度为 0;计划不会因轮次预算被暂停。',
1205
+ '- 每个子任务必须写 estimateMinutes(整数 1-240,宁可估高):你预估它需要多少分钟。宁可估高,不要估低。取值必须是整数,越界或非整数会被校验拒绝(仅防离谱值),缺失不报错。',
1206
+ /*
1207
+ * [2.2.0][T13/推理等级] 子 Agent 必须自决推理等级,禁止继承主 Agent。
1208
+ * 用户规则原文见 plan.ts 顶部 REASONING_EFFORTS 注释;五档映射与五个示例
1209
+ * 按用户规则逐字展开,规划器输出由 readSubtasks 校验(只收
1210
+ * low/medium/high/xhigh/max)。
1211
+ * [2.2.7][T3/五档扩展] 中等="medium"或"high"、非常="xhigh"或"max" 是 OR 语义,
1212
+ * 二选一必须有确定性判据,否则同一输入会产生不同档位——下面逐字加入
1213
+ * 「同等复杂度优先较低档」消歧指令;提示词行与 tests/reasoning-effort.test.ts
1214
+ * 的契约正则逐字耦合,改任一必须同步改另一。
1215
+ */
1216
+ '- 每个子任务必须按它自身的复杂度写 reasoningEffort(推理等级,只允许 low / medium / high / xhigh / max 五档):轻度复杂="low",中等复杂="medium"或"high",非常复杂="xhigh"或"max"。',
1217
+ '- 档位二选一消歧(硬性要求,保证同等输入产生稳定档位):同等复杂度下优先选择较低档(medium 优先于 high,xhigh 优先于 max),除非有明确理由需较高档(如需要自建测试并跑回归、涉及多文件/多子系统共享状态、需要全链路原子性同步);没有明确理由不得升高档位,也不得无理由降低档位。',
1218
+ '- reasoningEffort 五档示例:整理并校对一份已有清单="low";补充单个工具函数并补齐单元测试="medium";独立实现一个模块并补齐测试="high";跨多个模块排查根因并修复="xhigh";跨多个系统排查根因并给出架构级修复方案="max"。',
1219
+ '- 禁止沿用/继承主 Agent 的推理等级:reasoningEffort 只由该子任务自身的复杂度决定,不得因为主 Agent 当前是某一档就照抄;缺失时执行侧回落 "high",但你必须显式写出该字段。',
1089
1220
  '- 规模大就如实拆成多轮,不要为了塞进一轮而把多个交付物压进一个子任务。',
1090
1221
  '',
1091
1222
  '可用部门(每个部门的执行者都是来自全球相关领域的顶尖专家,不是普通部门人员):',
@@ -1144,7 +1275,8 @@ export function buildPlannerPrompt(taskText, cwd, conversationContext = '', budg
1144
1275
  ' "dependsOn": [],',
1145
1276
  ' "acceptance": ["可测试的验收标准"],',
1146
1277
  ' "risk": "主要风险",',
1147
- ' "estimateMinutes": 5',
1278
+ ' "estimateMinutes": 5,',
1279
+ ' "reasoningEffort": "high"',
1148
1280
  ' }',
1149
1281
  ' ]',
1150
1282
  ' }',
@@ -1178,6 +1310,122 @@ export function makeUserMessage(text, source) {
1178
1310
  source,
1179
1311
  };
1180
1312
  }
1313
+ /**
1314
+ * [2.2.1] Validate the exact payload shape DSH requires for a `user/message`
1315
+ * event before it reaches the append-only log.
1316
+ *
1317
+ * Incident it prevents (2026-11-08, session-a404d49d…): the plugin appended
1318
+ * plain strings as `user/message` data. `Session.append()` only validates
1319
+ * payloads that are records, so the strings were persisted; on replay the
1320
+ * `goal` projection read `event.data.source.kind` and threw
1321
+ * "Cannot read properties of undefined (reading 'kind')", which surfaced as
1322
+ * "历史加载失败 / failed to project session". A malformed event is
1323
+ * unrecoverable once appended, so rejection must happen here, before append.
1324
+ */
1325
+ function userMessageShapeProblem(message) {
1326
+ if (!isRecord(message))
1327
+ return 'payload must be a plain object';
1328
+ if (typeof message.id !== 'string' || message.id.length === 0)
1329
+ return 'missing message id';
1330
+ if (message.role !== 'user')
1331
+ return 'role must be "user"';
1332
+ if (!Array.isArray(message.content) || message.content.length === 0)
1333
+ return 'content must be a non-empty array';
1334
+ if (!isRecord(message.source))
1335
+ return 'missing source';
1336
+ if (typeof message.source.kind !== 'string' || message.source.kind.length === 0)
1337
+ return 'missing source.kind';
1338
+ return null;
1339
+ }
1340
+ /**
1341
+ * [2.2.1] The single approved writer for `user/message` events in this plugin.
1342
+ *
1343
+ * A raw string is wrapped into a complete DSH `UserMessage` (stable id, role,
1344
+ * text content, source with a nonempty `kind`); an already-built message is
1345
+ * shape-checked. Either way a malformed payload throws BEFORE `session.append`,
1346
+ * so a bad notice can never corrupt a session log again. All appends use
1347
+ * `surfaceOp: 'append'`, matching the previous call sites.
1348
+ */
1349
+ export function appendUserMessage(session, payload, source) {
1350
+ if (!session || typeof session.append !== 'function')
1351
+ return undefined;
1352
+ let message = payload;
1353
+ if (typeof payload === 'string') {
1354
+ const summary = truncate(String(payload).replace(/\s+/g, ' ').trim() || '(无摘要)', 120);
1355
+ message = makeUserMessage(payload, source ?? { kind: 'workplan', form: 'notice', summary });
1356
+ }
1357
+ const problem = userMessageShapeProblem(message);
1358
+ if (problem !== null)
1359
+ throw new Error(`dsh-workplan: refusing to append malformed user/message (${problem})`);
1360
+ return session.append('user/message', message, { surfaceOp: 'append' });
1361
+ }
1362
+ /*
1363
+ * [2.2.5][T5] 分解期间进度文案与回报器(T3 交互规范 §3 C2/C3、§4 频率规则)。
1364
+ *
1365
+ * 缺陷:runPlanner 全程(最长 3 次尝试 × 300s 窗口 + 退避)插件既不写会话
1366
+ * 消息也不放内存记录(T1 断点层判定=未发出),用户无法区分「正在重试」与
1367
+ * 「卡死」。本组函数只负责「把一次失败尝试翻译成用户能看懂的两句话」:
1368
+ * - cardLine:通道 A(侧栏占位卡片的 errors 区,4 秒轮询可见,保底通道);
1369
+ * - notice:通道 B(appendUserMessage 聊天通知,仅「会退避重试」的失败才
1370
+ * 发,每轮至多 2 条——第 3 次失败直接进降级文案,不再叠加通知)。
1371
+ * 文案硬规则(T3 §3):真因链截断 ≤120 字符(错误码原样保留,供用户报障);
1372
+ * 分母 3 由 maxAttempts 参数注入,不在文案里硬编码;等待时长按实际退避
1373
+ * 四舍五入到秒;aborted 由调用方(回报器)静默,本函数不涉及。
1374
+ */
1375
+ export function plannerProgressLines(report, maxAttempts) {
1376
+ const attempt = Number(report?.attempt) || 0;
1377
+ const outcome = String(report?.outcome ?? 'PLANNER_ERROR');
1378
+ const causes = Array.isArray(report?.lastErrors) ? report.lastErrors : [];
1379
+ const cause = truncate(causes.join(';').replace(/\s+/g, ' ').trim(), 120);
1380
+ if (attempt <= 0 || !cause)
1381
+ return { cardLine: '', notice: null };
1382
+ const terminal = report?.terminal === true;
1383
+ const backoffMs = Number(report?.retryBackoffMs) || 0;
1384
+ const total = Number(maxAttempts) || attempt;
1385
+ const willRetry = !terminal && backoffMs > 0 && attempt < total;
1386
+ const waitSecs = Math.max(1, Math.round(backoffMs / 1000));
1387
+ const prefix = `第 ${attempt} 次尝试失败(${outcome}):${cause}`;
1388
+ const cardLine = willRetry
1389
+ ? `${prefix};正在重试(约 ${waitSecs} 秒后),第 ${attempt + 1}/${total} 次`
1390
+ : backoffMs > 0
1391
+ ? `${prefix};正在重试`
1392
+ : `${prefix}`;
1393
+ const notice = willRetry
1394
+ ? `【自动分解】第 ${attempt} 次尝试失败:${cause};正在重试(约 ${waitSecs} 秒后),第 ${attempt + 1}/${total} 次`
1395
+ : null;
1396
+ return { cardLine, notice };
1397
+ }
1398
+ /*
1399
+ * [2.2.5][T5] 进度回报器工厂:把 runPlanner 的 onProgress 回调落到两个既有
1400
+ * 通道上(T3 §2 S2、§4 频率规则)。依赖全部以参数注入(signal / 落记录 /
1401
+ * 发通知),便于脱离宿主运行态做单元回归:
1402
+ * - signal.aborted 后一律静默(用户自己取消的,不再打扰,也不写记录);
1403
+ * - 通道 A 每轮至多 2 行(maxLines),通道 B 每轮至多 2 条(maxNotices);
1404
+ * - 记录更新走 setRecord 回调(maybePlan 侧即 state.records.set),失败
1405
+ * 尝试的摘要在成功/降级后被既有 records.set 整体覆盖,无残留。
1406
+ */
1407
+ export function createPlannerProgressReporter(options) {
1408
+ const maxLines = Math.max(1, Number(options.maxLines) || 2);
1409
+ const maxNotices = Math.max(0, Number(options.maxNotices) || 2);
1410
+ const errors = [];
1411
+ let notices = 0;
1412
+ return (report) => {
1413
+ if (options.signal?.aborted)
1414
+ return;
1415
+ const lines = plannerProgressLines(report, options.maxAttempts);
1416
+ if (!lines.cardLine)
1417
+ return;
1418
+ if (errors.length < maxLines)
1419
+ errors.push(lines.cardLine);
1420
+ options.record.errors = [...errors];
1421
+ options.record.updatedAt = Date.now();
1422
+ options.setRecord(options.record);
1423
+ if (lines.notice && notices < maxNotices) {
1424
+ notices += 1;
1425
+ options.appendNotice(lines.notice);
1426
+ }
1427
+ };
1428
+ }
1181
1429
  export function buildPlanSummary(plan) {
1182
1430
  const total = flattenSubtasks(plan).length;
1183
1431
  const primary = plan.contradictions.primary.statement;
@@ -1205,18 +1453,32 @@ export function estimatePlanMinutes(plan, fallbackMinutes = 15, concurrency = MA
1205
1453
  const totalEstimate = estimates.reduce((sum, value) => sum + value, 0);
1206
1454
  return Math.max(waves * maxEstimate, Math.ceil(totalEstimate / Math.max(1, concurrency)));
1207
1455
  }
1208
- export function buildBudgetWarning(plan, totalBudgetMinutes = 20, maxResumes = MAX_PLAN_RESUMES) {
1456
+ export function buildBudgetWarning(plan, totalBudgetMinutes = 0, maxResumes = MAX_PLAN_RESUMES) {
1209
1457
  const minutes = estimatePlanMinutes(plan);
1210
- const budget = Math.max(1, Math.round(Number(totalBudgetMinutes) || 20));
1211
- if (minutes <= budget)
1212
- return '';
1458
+ const rawBudget = Number(totalBudgetMinutes);
1459
+ const budget = Number.isFinite(rawBudget) && rawBudget > 0 ? Math.max(1, Math.round(rawBudget)) : 0;
1460
+ /*
1461
+ * [2.2.0][T3/O-5b] 固定预算措辞改为「预估仅供参考,非承诺;实际时长协商
1462
+ * 决定」(方案 §2.6 #5 的目标措辞;O-5b 三处承诺禁令之一):预算提示只讲
1463
+ * 估算与轮次,不构成任何固定交付承诺。
1464
+ *
1465
+ * 标注行是输出的固定组成部分——预算内也返回(验收 E2「预算预告/计划消息
1466
+ * 把预估标注为仅供参考/非承诺」:凡 buildBudgetWarning 有输出必带该标注,
1467
+ * 计划消息经 warning 路径同享,不再按超预算与否吞掉)。
1468
+ */
1469
+ const advisory = '(子任务 estimateMinutes 预估仅供参考,非承诺;实际时长协商决定:由执行专家开工预告协商,不设固定完成时间。)';
1470
+ // [2.2.5] 0 = 本轮不设固定总预算:只保留“预估仅供参考”的标注,不再输出
1471
+ // “超过本轮预算/需要 N 轮”的提示,避免与“不强制限制”的目标矛盾。
1472
+ if (budget === 0 || minutes <= budget)
1473
+ return advisory;
1213
1474
  const rounds = Math.max(1, Math.ceil(minutes / budget));
1214
1475
  const missing = flattenSubtasks(plan).some((entry) => !Number.isFinite(Number(entry.subtask?.estimateMinutes)));
1215
1476
  return [
1216
1477
  `⚠ 预算提示:本计划 ${flattenSubtasks(plan).length} 项,按其估计约需 ${minutes} 分钟 > 本轮 ${budget} 分钟,`
1217
1478
  + `预计需要约 ${rounds} 轮(续跑额度 ${maxResumes} 次)。`,
1479
+ advisory,
1218
1480
  '建议:拆成多轮,或减少同时进行的子任务。',
1219
- ...(missing ? ['(部分子任务缺少 estimateMinutes,已按 15 分钟上限估算。)'] : []),
1481
+ ...(missing ? ['(部分子任务缺少 estimateMinutes,已按每项 15 分钟默认值估算。)'] : []),
1220
1482
  ].join('\n');
1221
1483
  }
1222
1484
  export function buildPlanMessage(plan, options = {}) {
@@ -1230,9 +1492,15 @@ export function buildPlanMessage(plan, options = {}) {
1230
1492
  createdAt: plan.createdAt,
1231
1493
  plan,
1232
1494
  };
1233
- const warning = buildBudgetWarning(plan, options.totalBudgetMinutes ?? 20, options.maxResumes ?? MAX_PLAN_RESUMES);
1495
+ const warning = buildBudgetWarning(plan, options.totalBudgetMinutes ?? 0, options.maxResumes ?? MAX_PLAN_RESUMES);
1234
1496
  const text = [
1235
1497
  summary,
1498
+ /*
1499
+ * [2.2.0][T3/O-5b/E2] 计划消息中的预估一律标注「非承诺」(方案 §1⑤ O-5b:
1500
+ * 「预估一律标注『仅供参考,实际时长由执行专家预告协商』」;验收 E2)。
1501
+ * 标注由 buildBudgetWarning 的固定 advisory 行携带(预算内也返回,见该
1502
+ * 函数注释),warning 恒非空随消息带出,此处不再重复一份。
1503
+ */
1236
1504
  ...(warning ? ['', warning] : []),
1237
1505
  '',
1238
1506
  /*
@@ -1256,6 +1524,11 @@ export function buildPlanMessage(plan, options = {}) {
1256
1524
  }
1257
1525
  export function buildDegradedMessage(options) {
1258
1526
  const error = truncate(options.error ?? '未知错误', 600);
1527
+ /*
1528
+ * [2.1.6] 失败现场:模型、耗时、收到几个输出块、判定码。没有它,用户只看到
1529
+ * 一句「超时」,既不知道是不是模型太慢,也不知道该改哪个旋钮。
1530
+ */
1531
+ const detail = truncate(options.detail ?? '', 400);
1259
1532
  const summary = truncate(`【自动分解降级】${error}`, 300);
1260
1533
  const payload = {
1261
1534
  kind: 'workplan',
@@ -1266,6 +1539,7 @@ export function buildDegradedMessage(options) {
1266
1539
  createdAt: options.createdAt,
1267
1540
  degraded: true,
1268
1541
  error,
1542
+ ...(detail ? { detail } : {}),
1269
1543
  title: '自动分解降级',
1270
1544
  taskUnderstanding: {
1271
1545
  originalRequest: truncate(options.taskText ?? '', 2000),
@@ -1279,6 +1553,7 @@ export function buildDegradedMessage(options) {
1279
1553
  };
1280
1554
  const text = [
1281
1555
  summary,
1556
+ ...(detail ? ['', detail] : []),
1282
1557
  '',
1283
1558
  '自动任务分解失败,部门 Agent 未启动。',
1284
1559
  '请先向用户说明失败原因,并询问是否重试;在用户确认前不要开始执行任务。',
@@ -1438,7 +1713,10 @@ export function buildResultMessage(result) {
1438
1713
  if (handoffs.length > 0) {
1439
1714
  return handoffs.map((handoff) => `${item.subtaskId} ${String(handoff?.id ?? 'H?')}(${String(handoff?.status ?? 'open')}):${String(handoff?.request ?? '')}`);
1440
1715
  }
1441
- return (Array.isArray(item?.needs) ? item.needs : []).map((need) => `${item.subtaskId}:${need}`);
1716
+ // [2.2.6][T4] needs 条目自本版起可能为结构化对象 {request, department},
1717
+ // 旧记录仍是字符串;统一经 needEntryText 渲染,两条形状都不会再出现
1718
+ // "[object Object]"(字符串路径逐字不变)。
1719
+ return (Array.isArray(item?.needs) ? item.needs : []).map((need) => `${item.subtaskId}:${needEntryText(need)}`);
1442
1720
  });
1443
1721
  const review = [];
1444
1722
  if (escalations.length > 0) {
@@ -1941,11 +2219,94 @@ function readEvidenceArtifacts(value) {
1941
2219
  return artifact;
1942
2220
  }).filter((item) => item.ref !== '');
1943
2221
  }
2222
+ /*
2223
+ * [2.2.6][T4] 循环引用/undefined 安全的 JSON 文本化兜底(缺陷二修复件)。
2224
+ *
2225
+ * 对象形 needs 的兜底路径不允许再用隐式 String()——它把任意对象变成字面量
2226
+ * "[object Object]",department 等字段当场丢失(wp-db6de2f0 的 T1–T4 四条
2227
+ * handoff 即因此损坏)。JSON.stringify 对循环引用会抛错、对顶层 undefined
2228
+ * 返回 undefined,这里统一兜成可读文本,任何形状都不会炸掉结果块解析。
2229
+ */
2230
+ function safeJsonText(value) {
2231
+ const seen = new WeakSet();
2232
+ try {
2233
+ return JSON.stringify(value, (_key, entry) => {
2234
+ if (entry !== null && typeof entry === 'object') {
2235
+ if (seen.has(entry))
2236
+ return '[Circular]';
2237
+ seen.add(entry);
2238
+ }
2239
+ return entry === undefined ? null : entry;
2240
+ }) ?? '';
2241
+ }
2242
+ catch {
2243
+ return '[Unserializable object]';
2244
+ }
2245
+ }
2246
+ /** [2.2.6][T4] 本插件 readEvidenceNeeds 产出的规范化条目形状(回放幂等判定)。 */
2247
+ function isStructuredNeedEntry(item) {
2248
+ return isRecord(item) && typeof item.request === 'string' && item.request.trim() !== ''
2249
+ && Object.keys(item).every((key) => key === 'request' || key === 'department');
2250
+ }
2251
+ /*
2252
+ * [2.2.6][T4] 对象感知的 needs/options 文本提取(取代一切 String(对象))。
2253
+ *
2254
+ * 字符串原样返回(历史行为逐字不变);对象优先读取 need/request/text/
2255
+ * message/question 中首个非空文本字段,拼上 purpose(用途)与 department
2256
+ * (部门)前缀,与子 Agent 实际写入的 {"department","need","purpose"} 形状
2257
+ * 对齐(T1 §2.4 子会话日志原文实证);完全无法识别的形状回退受控 JSON 文本。
2258
+ * 注意:本插件自己的结构化条目 {request, department} 视为已定稿文本原样返回,
2259
+ * 否则 mergeHandoffsFromNeeds 会二次拼「部门:」前缀。
2260
+ */
2261
+ export function needEntryText(item) {
2262
+ if (typeof item === 'string')
2263
+ return item;
2264
+ if (typeof item === 'number' || typeof item === 'boolean')
2265
+ return String(item);
2266
+ if (!isRecord(item))
2267
+ return item == null ? '' : safeJsonText(item);
2268
+ if (isStructuredNeedEntry(item))
2269
+ return item.request;
2270
+ const text = [item.need, item.request, item.text, item.message, item.question]
2271
+ .find((entry) => typeof entry === 'string' && entry.trim() !== '');
2272
+ const purpose = typeof item.purpose === 'string' && item.purpose.trim() !== '' ? item.purpose.trim() : '';
2273
+ const department = typeof item.department === 'string' && item.department.trim() !== '' ? item.department.trim() : '';
2274
+ if (typeof text === 'string') {
2275
+ const body = purpose !== '' ? `${text.trim()}(用途:${purpose})` : text.trim();
2276
+ return department !== '' ? `${department}:${body}` : body;
2277
+ }
2278
+ return safeJsonText(item);
2279
+ }
2280
+ /** [2.2.6][T4] 对象形 needs 的合法部门键提取(与 normaliseHandoffs 同一判定)。 */
2281
+ export function needEntryDepartment(item) {
2282
+ if (!isRecord(item))
2283
+ return null;
2284
+ const department = item.department;
2285
+ return typeof department === 'string' && DEPARTMENTS[department]
2286
+ ? department
2287
+ : null;
2288
+ }
1944
2289
  function readEvidenceNeeds(value) {
1945
2290
  if (!Array.isArray(value))
1946
2291
  return [];
1947
2292
  return value.slice(0, MAX_EVIDENCE_NEEDS)
1948
- .map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
2293
+ .map((item) => {
2294
+ if (typeof item === 'string')
2295
+ return truncate(item, 300);
2296
+ /*
2297
+ * [2.2.6][T4] 回放/重读幂等:本插件自己产出的结构化条目(仅含
2298
+ * request/department 两个键)原样保留,不二次拼「部门:」前缀——
2299
+ * 否则结果消息回放时文本会变化,绕过去重键造成重复登记。
2300
+ */
2301
+ if (isStructuredNeedEntry(item)) {
2302
+ return { request: truncate(item.request, 300), department: needEntryDepartment(item) };
2303
+ }
2304
+ const request = truncate(needEntryText(item), 300).trim();
2305
+ if (!request)
2306
+ return null;
2307
+ const department = needEntryDepartment(item);
2308
+ return department !== null ? { request, department } : request;
2309
+ })
1949
2310
  .filter(Boolean);
1950
2311
  }
1951
2312
  /**
@@ -1984,6 +2345,72 @@ export function normaliseHandoffs(value) {
1984
2345
  }
1985
2346
  return out;
1986
2347
  }
2348
+ /**
2349
+ * [2.2.9][T2][mono-gate] handoff 逐项单调合并(M2):「整组替换」改「字段级增量」。
2350
+ *
2351
+ * 背景(wp-215ed52f T5 实证):handoff 答复的 durable 记录携带的是读取时刻的
2352
+ * 整数组快照;回放时低 rev 事件若走 normaliseHandoffs 整组替换,会把高 rev 结算
2353
+ * 之后才落盘的答复/新登记一起抹掉。答复本质是逐项增量(status/response/
2354
+ * updatedAt 三个字段变化),不该被行级覆盖语义绑架。
2355
+ *
2356
+ * 合并不变量(按 request 文本对齐——normaliseHandoffs 的既有去重键;id 是
2357
+ * 位置式生成,跨世代不可靠):
2358
+ * 1. 新需求登记永远合法:current 没有的 request 直接追加(受 MAX_HANDOFFS 约束,
2359
+ * 与 normaliseHandoffs 同口径)。
2360
+ * 2. 状态单调序 open < routed < {answered, closed}(终态)。**前进只看秩、
2361
+ * 不看时间戳**:needs 派生的 open 条目在回放时由 normaliseHandoffs 以
2362
+ * Date.now() 打戳(回放时刻的产物,不是事实时刻),拿它比较会误拒真实的
2363
+ * 历史答复——正是「处理过的事情不能被重放抹掉」这条既有铁律要防的形状。
2364
+ * 3. 同秩(含终态之间 answered↔closed)只在 incoming.updatedAt 严格更大时
2365
+ * 采纳(response/department 等增量的精化);低秩覆盖一律拒绝,终态永不
2366
+ * 回退。
2367
+ * 4. 采纳时 id 保持稳定(界面与 needs 引用按 id 认条目),其余字段随快照前进。
2368
+ *
2369
+ * 幂等性:同一条记录二次进入(写侧、回放、重读共用本函数)结果不变——updatedAt
2370
+ * 相等时保留 current,normaliseHandoffs 按 request 去重挡住重复追加。
2371
+ */
2372
+ export function mergeHandoffEntriesByUpdatedAt(current, incoming) {
2373
+ const base = normaliseHandoffs(current);
2374
+ const list = normaliseHandoffs(incoming);
2375
+ if (list.length === 0)
2376
+ return { changed: false, value: base };
2377
+ const rank = (status) => {
2378
+ if (status === 'answered' || status === 'closed')
2379
+ return 2;
2380
+ if (status === 'routed')
2381
+ return 1;
2382
+ return 0;
2383
+ };
2384
+ const snapshot = JSON.stringify(base);
2385
+ const byRequest = new Map();
2386
+ for (const item of base)
2387
+ byRequest.set(item.request, item);
2388
+ for (const item of list) {
2389
+ const target = byRequest.get(item.request);
2390
+ if (!target) {
2391
+ // 新需求登记:append-only(对齐 mergeHandoffsFromNeeds 的语义)。
2392
+ if (base.length >= MAX_HANDOFFS)
2393
+ continue;
2394
+ const used = new Set(base.map((entry) => entry.id));
2395
+ const appended = used.has(item.id) ? { ...item, id: `H${base.length + 1}` } : { ...item };
2396
+ base.push(appended);
2397
+ byRequest.set(appended.request, appended);
2398
+ continue;
2399
+ }
2400
+ const targetRank = rank(target.status);
2401
+ const itemRank = rank(item.status);
2402
+ if (itemRank < targetRank)
2403
+ continue; // 永不回退(含终态不接受 open/routed 覆盖)
2404
+ if (itemRank === targetRank && !(Number(item.updatedAt) > Number(target.updatedAt)))
2405
+ continue;
2406
+ // 秩前进只看状态序(工具端 open→routed→answered/closed 单调,回放同样只进不退);
2407
+ // 同秩精化才比 updatedAt。id 保持稳定(界面与 needs 引用都按 id 认条目)。
2408
+ const index = base.indexOf(target);
2409
+ base[index] = { ...item, id: target.id };
2410
+ byRequest.set(item.request, base[index]);
2411
+ }
2412
+ return { changed: JSON.stringify(base) !== snapshot, value: base };
2413
+ }
1987
2414
  /**
1988
2415
  * 每一条 `needs` 都必须变成一条可追踪的 handoff。
1989
2416
  *
@@ -1995,9 +2422,18 @@ export function mergeHandoffsFromNeeds(current, needs, overflow = []) {
1995
2422
  const next = normaliseHandoffs(current);
1996
2423
  const list = Array.isArray(needs) ? needs : [];
1997
2424
  for (const raw of list) {
1998
- const request = truncate(String(raw ?? ''), 300).trim();
2425
+ /*
2426
+ * [2.2.6][T4] 对象安全序列化(缺陷二第二触点 W2):needs 条目可能是子
2427
+ * Agent 直接写的对象({"department","need","purpose"}),也可能是
2428
+ * readEvidenceNeeds 产出的结构化条目 {request, department}。request 一律
2429
+ * 经 needEntryText 取文本、department 经 needEntryDepartment 提取合法
2430
+ * 部门键——本函数不再有任何 String(对象) 分支,对象不再被写成
2431
+ * "[object Object]"、department 不再被丢弃。去重键仍是 request 文本。
2432
+ */
2433
+ const request = truncate(typeof raw === 'string' ? raw : needEntryText(raw), 300).trim();
1999
2434
  if (!request)
2000
2435
  continue;
2436
+ const department = needEntryDepartment(raw);
2001
2437
  if (next.some((item) => item.request === request))
2002
2438
  continue;
2003
2439
  /*
@@ -2014,7 +2450,7 @@ export function mergeHandoffsFromNeeds(current, needs, overflow = []) {
2014
2450
  next.push({
2015
2451
  id: `H${next.length + 1}`,
2016
2452
  request,
2017
- department: null,
2453
+ department,
2018
2454
  status: 'open',
2019
2455
  response: null,
2020
2456
  at: Date.now(),
@@ -2039,10 +2475,28 @@ export function openHandoffs(status) {
2039
2475
  function readEvidenceOptions(value) {
2040
2476
  if (!Array.isArray(value))
2041
2477
  return [];
2478
+ // [2.2.6][T4] 同模式共犯(T1 W3):对象感知读取,消灭 String(对象) 分支。
2042
2479
  return value.slice(0, MAX_ESCALATION_OPTIONS)
2043
- .map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
2480
+ .map((item) => truncate(needEntryText(item), 300))
2044
2481
  .filter(Boolean);
2045
2482
  }
2483
+ /**
2484
+ * [2.2.0][T3/O-2c] 用时回填字段(timeSpentMinutes / finalEstimateMinutes)
2485
+ * 的 advisory 读取器。
2486
+ *
2487
+ * 方案 §2.5:「时间字段纯 advisory:不参与可交付判定,不加拒绝码」;方案
2488
+ * §2.4 结果块契约「模板增加 timeSpentMinutes、finalEstimateMinutes 字段」。
2489
+ * 只在给出合法非负有限数值时以整数分钟透传;缺失/非法一律省略(返回
2490
+ * undefined、不占键名),不判不合规——字段本来就是可选的。
2491
+ */
2492
+ function readAdvisoryMinutes(value) {
2493
+ if (value === undefined || value === null)
2494
+ return undefined;
2495
+ const num = Number(value);
2496
+ if (!Number.isFinite(num) || num < 0)
2497
+ return undefined;
2498
+ return Math.round(num);
2499
+ }
2046
2500
  /**
2047
2501
  * [2.1.0] 顶层证据字段被误写进 `phases` 时,把它们提回顶层(用户 2026-11-05)。
2048
2502
  *
@@ -2251,9 +2705,10 @@ export function parseEvidenceBlock(output) {
2251
2705
  rescued: true,
2252
2706
  payload: rescued.payload,
2253
2707
  raw: rescued.raw,
2708
+ parseError: '',
2254
2709
  };
2255
2710
  }
2256
- return { found: false, malformed: false, truncated: false, repaired: false, rescued: false, payload: null, raw: '' };
2711
+ return { found: false, malformed: false, truncated: false, repaired: false, rescued: false, payload: null, raw: '', parseError: '' };
2257
2712
  }
2258
2713
  const bodyStart = begin + EVIDENCE_MARKER_BEGIN.length;
2259
2714
  const end = text.indexOf(EVIDENCE_MARKER_END, bodyStart);
@@ -2266,30 +2721,44 @@ export function parseEvidenceBlock(output) {
2266
2721
  */
2267
2722
  const raw = (end < 0 ? text.slice(bodyStart) : text.slice(bodyStart, end)).trim();
2268
2723
  const truncated = end < 0 || raw.length > MAX_EVIDENCE_BLOCK_CHARS;
2269
- const accept = (payload, repaired) => {
2724
+ /*
2725
+ * [2.2.8][T7] 回喂重报需要的「解析器具体错误」。
2726
+ *
2727
+ * 旧实现把 JSON.parse 的异常吞掉,只留一句「结果块 JSON 非法」;子会话收到
2728
+ * 回喂时看不到是哪个字符、哪一列坏了,只能整块盲改。现在把解析器的原始
2729
+ * 报错(含 position/line/column)随 malformed 一并带回,供结算回喂与
2730
+ * blocked 记录逐字引用。
2731
+ */
2732
+ const accept = (payload, repaired, parseError = '') => {
2270
2733
  if (!isRecord(payload) || !EVIDENCE_STATUSES.includes(payload.status)) {
2271
- return { found: true, malformed: true, truncated, repaired, rescued: false, payload: null, raw };
2734
+ return {
2735
+ found: true,
2736
+ malformed: true,
2737
+ truncated,
2738
+ repaired,
2739
+ rescued: false,
2740
+ payload: null,
2741
+ raw,
2742
+ parseError: parseError
2743
+ || (isRecord(payload)
2744
+ ? `JSON 可解析,但 status 缺失或取值非法("${String(payload.status ?? '')}"),只能是 done / blocked / partial`
2745
+ : 'JSON 可解析,但顶层不是对象,无法作为证据块结算'),
2746
+ };
2272
2747
  }
2273
- return { found: true, malformed: false, truncated, repaired, rescued: false, payload, raw };
2748
+ return { found: true, malformed: false, truncated, repaired, rescued: false, payload, raw, parseError: '' };
2274
2749
  };
2275
2750
  try {
2276
2751
  return accept(JSON.parse(raw), false);
2277
2752
  }
2278
- catch {
2753
+ catch (error) {
2754
+ const parseError = truncate(String(error?.message ?? error), 300);
2279
2755
  const repaired = repairEvidenceJson(raw);
2280
2756
  if (repaired)
2281
2757
  return accept(repaired, true);
2282
- return { found: true, malformed: true, truncated, repaired: false, payload: null, raw };
2758
+ return { found: true, malformed: true, truncated, repaired: false, payload: null, raw, parseError };
2283
2759
  }
2284
2760
  }
2285
2761
  const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i;
2286
- /**
2287
- * Deterministic verdict for one child result.
2288
- *
2289
- * This is the single place that decides done vs blocked, so the eight cases in
2290
- * the acceptance table cannot drift apart between the runtime and the replay.
2291
- * It never invents evidence and never upgrades a failed self-check to done.
2292
- */
2293
2762
  export function adjudicateResult({ output, strict = true, expectedAcceptance = [], requirePhases = true }) {
2294
2763
  const text = typeof output === 'string' ? output : '';
2295
2764
  const parsed = parseEvidenceBlock(text);
@@ -2320,10 +2789,18 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2320
2789
  * 也不说该重发还是该改格式,于是只能靠读原始输出猜。现在按截断/非法
2321
2790
  * 分档给出可执行提示。
2322
2791
  */
2323
- error: parsed.truncated
2792
+ error: (parsed.truncated
2324
2793
  ? '结果块被截断(缺少结束标记或超过长度上限):请让该子 Agent 重新回报,'
2325
2794
  + '只保留 status/summary/acceptance/artifacts/needs 字段,删掉大段执行日志后重发'
2326
- : '结果块 JSON 非法(不是截断):请检查引号、逗号与括号是否成对,修正后重新回报',
2795
+ : '结果块 JSON 非法(不是截断):请检查引号、逗号与括号是否成对,修正后重新回报')
2796
+ /*
2797
+ * [2.2.8][T7] 解析器原始报错(含 position/line/column)一并写进判定:
2798
+ * 结算回喂时子 Agent 能看到「坏在哪个字符」,blocked 记录也留档同一句。
2799
+ */
2800
+ + (typeof parsed.parseError === 'string' && parsed.parseError !== ''
2801
+ ? `。解析器报告:${parsed.parseError}`
2802
+ : ''),
2803
+ parseError: typeof parsed.parseError === 'string' ? parsed.parseError : '',
2327
2804
  };
2328
2805
  }
2329
2806
  if (!parsed.found) {
@@ -2373,8 +2850,24 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2373
2850
  const question = truncate(String(payload.question ?? ''), MAX_QUESTION_CHARS);
2374
2851
  const options = readEvidenceOptions(payload.options);
2375
2852
  const blockedReason = truncate(String(payload.blockedReason ?? payload.error ?? ''), 2000);
2853
+ /*
2854
+ * [2.2.0][T3/O-2c] 用时回填字段(方案 §2.2/§2.4:「模板增加
2855
+ * timeSpentMinutes、finalEstimateMinutes 字段」)。纯 advisory(方案 §2.5
2856
+ * 「时间字段纯 advisory:不参与可交付判定,不加拒绝码」):合法即整数分钟
2857
+ * 透传到判定结果的每一个 payload 分支,缺失/非法即省略(不占键名),既有
2858
+ * 字段与 F1-F9 零改动。
2859
+ */
2860
+ const timeSpentMinutes = readAdvisoryMinutes(payload.timeSpentMinutes);
2861
+ const finalEstimateMinutes = readAdvisoryMinutes(payload.finalEstimateMinutes);
2862
+ const advisoryTime = timeSpentMinutes === undefined && finalEstimateMinutes === undefined
2863
+ ? {}
2864
+ : {
2865
+ ...(timeSpentMinutes === undefined ? {} : { timeSpentMinutes }),
2866
+ ...(finalEstimateMinutes === undefined ? {} : { finalEstimateMinutes }),
2867
+ };
2376
2868
  if (payload.status === 'blocked') {
2377
2869
  return {
2870
+ ...advisoryTime,
2378
2871
  status: 'blocked',
2379
2872
  verification: 'structured',
2380
2873
  acceptance,
@@ -2388,6 +2881,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2388
2881
  if (payload.status === 'partial') {
2389
2882
  const detail = truncate(String(payload.summary ?? payload.blockedReason ?? ''), 2000);
2390
2883
  return {
2884
+ ...advisoryTime,
2391
2885
  status: 'blocked',
2392
2886
  verification: 'structured',
2393
2887
  acceptance,
@@ -2401,6 +2895,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2401
2895
  const failed = acceptance.filter((item) => item.result === 'fail');
2402
2896
  if (failed.length > 0) {
2403
2897
  return {
2898
+ ...advisoryTime,
2404
2899
  status: 'blocked',
2405
2900
  verification: 'failed',
2406
2901
  acceptance,
@@ -2446,6 +2941,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2446
2941
  ? '(结果块 JSON 有语法错误,已修复;若 acceptance 位于错误点之后,会被一起裁掉)'
2447
2942
  : '';
2448
2943
  return {
2944
+ ...advisoryTime,
2449
2945
  status: 'blocked',
2450
2946
  verification: 'unverified',
2451
2947
  acceptance,
@@ -2470,6 +2966,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2470
2966
  : validatePhaseEvidence(payload.phases, expectedAcceptance);
2471
2967
  if (phaseCheck && !phaseCheck.ok) {
2472
2968
  return {
2969
+ ...advisoryTime,
2473
2970
  status: 'blocked',
2474
2971
  verification: 'unverified',
2475
2972
  acceptance,
@@ -2501,6 +2998,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2501
2998
  : checkCommFormatCompliance(payload, text, Array.isArray(expectedAcceptance) ? expectedAcceptance.length : 0);
2502
2999
  if (!commFormat.compliant) {
2503
3000
  return {
3001
+ ...advisoryTime,
2504
3002
  status: 'blocked',
2505
3003
  verification: 'unverified',
2506
3004
  acceptance,
@@ -2516,6 +3014,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2516
3014
  };
2517
3015
  }
2518
3016
  return {
3017
+ ...advisoryTime,
2519
3018
  status: 'done',
2520
3019
  verification: hasUnverified ? 'unverified' : 'structured',
2521
3020
  acceptance,
@@ -2577,6 +3076,17 @@ export function buildUpdateMessage(update) {
2577
3076
  ...(update.instructionOverdue === undefined ? {} : { instructionOverdue: update.instructionOverdue }),
2578
3077
  ...(update.handoffs === undefined ? {} : { handoffs: update.handoffs }),
2579
3078
  ...(update.reportedAt === undefined ? {} : { reportedAt: update.reportedAt }),
3079
+ /*
3080
+ * [2.2.0][T3/O-3c] 协商上限持久化臂(方案 §1③ O-3c:「专家预告(O-2a)经
3081
+ * 主 Agent 确认后写入 timeoutMs(经 dsh_workplan_update 新字段或计划消息)」)。
3082
+ *
3083
+ * 主 Agent 把确认后的 timeoutMs 随改判/进度更新记录留档,刷新/重启后按同
3084
+ * 顺序回放(回放侧 update 载荷的字段透传白名单在 src/runtime.ts:2931,属
3085
+ * T4 接线范围;applyStatus 侧已接受该字段);缺省合法(undefined 跳过,
3086
+ * 不改 2.1.x 语义)。计划内该字段的读取/派生见 readSubtasks +
3087
+ * deriveSubtaskTimeoutMs。
3088
+ */
3089
+ ...(update.timeoutMs === undefined ? {} : { timeoutMs: update.timeoutMs }),
2580
3090
  ...(update.revision === undefined ? {} : { revision: update.revision }),
2581
3091
  at: update.at ?? Date.now(),
2582
3092
  };
@@ -2694,6 +3204,20 @@ export function applyResultStatuses(statuses, result) {
2694
3204
  const replayedClosure = entry.status === 'done' && entry.closure === undefined
2695
3205
  ? 'reported'
2696
3206
  : entry.closure;
3207
+ /*
3208
+ * [2.2.1][T5][F1] 回放容错:结果载荷里的通道字段可能是 null / 非法值
3209
+ * (旧版本遗留、人工改日志、或早期重建写回的脏值)。applyStatus 是写入
3210
+ * 单点校验,遇到非法值会整条抛错,被下面的 catch 吞掉后这一行的
3211
+ * done / summary / verification / acceptance 全都不落地 —— 一条完成行
3212
+ * 回放成 pending 的假阴性(T4 残余项复核 A2/B2 实测)。
3213
+ *
3214
+ * 这里在进入 patch 之前判定:只有能通过校验的值才参与回放,null / 非法值
3215
+ * 按「字段缺失」处理。applyStatus 的 fail-closed 校验保持不变(其它写入方
3216
+ * 仍然不能写脏值),本改动只影响「读旧日志」这一侧。
3217
+ */
3218
+ const replayedNoticeChannel = entry.noticeChannel !== undefined && validateNoticeChannel(entry.noticeChannel).ok
3219
+ ? entry.noticeChannel
3220
+ : undefined;
2697
3221
  try {
2698
3222
  next = applyStatus(next, entry.subtaskId, {
2699
3223
  status: entry.status,
@@ -2725,6 +3249,16 @@ export function applyResultStatuses(statuses, result) {
2725
3249
  instructionSeq: entry.instructionSeq,
2726
3250
  instructionOverdue: entry.instructionOverdue,
2727
3251
  reportedAt: entry.reportedAt,
3252
+ // [2.2.0][T3/O-2c/O-3c] 柔性时长协商留档字段随结果快照回放(方案 §2.5
3253
+ // 「旧消息回放零改动读取」:字段缺失时 applyStatus 分支自动跳过)。
3254
+ timeSpentMinutes: entry.timeSpentMinutes,
3255
+ finalEstimateMinutes: entry.finalEstimateMinutes,
3256
+ timeoutMs: entry.timeoutMs,
3257
+ // [2.2.0][T3/O-2a] 子→主预告通道结论必须随结果快照回放;写入由
3258
+ // applyStatus 单点校验,非法值在 catch 中 fail-closed(不落脏值)。
3259
+ // [2.2.1][T5][F1] 但非法值只能丢「这个字段」,不能丢「整条结果行」:
3260
+ // 上面的 replayedNoticeChannel 已把 null / 非法值归一为 undefined。
3261
+ noticeChannel: replayedNoticeChannel,
2728
3262
  // [1.11.0] 回报证据与重规划留档必须随结果快照回放(T7 C-06/C-11)。
2729
3263
  report: entry.report,
2730
3264
  replannedReason: entry.replannedReason,
@@ -2864,6 +3398,47 @@ export function applyStatus(statuses, subtaskId, patch) {
2864
3398
  }
2865
3399
  if (patch.reportedAt !== undefined)
2866
3400
  next.reportedAt = numberOrNull(patch.reportedAt);
3401
+ /*
3402
+ * [2.2.0][T3/O-2c/O-3c] 柔性时长协商的留档字段(方案 §2.2/§2.4/§2.5)。
3403
+ *
3404
+ * timeSpentMinutes/finalEstimateMinutes 是结果块回填的实际耗时与收尾预估
3405
+ * (纯 advisory:缺失或非法不判不合规,按缺省处理;不参与可交付判定,
3406
+ * 方案 §2.5「时间字段纯 advisory:不参与可交付判定,不加拒绝码」);
3407
+ * timeoutMs 是 O-3c「预告经主 Agent 确认后写入」的协商上限留档,校验与
3408
+ * readSubtasks 同口径(正数毫秒;null 表示清除)。三者只写同一条状态条目,
3409
+ * 走 StatusEntry 未知字段保留通道,旧消息回放零改动。
3410
+ */
3411
+ if (patch.timeSpentMinutes !== undefined) {
3412
+ next.timeSpentMinutes = readAdvisoryMinutes(patch.timeSpentMinutes) ?? null;
3413
+ }
3414
+ if (patch.finalEstimateMinutes !== undefined) {
3415
+ next.finalEstimateMinutes = readAdvisoryMinutes(patch.finalEstimateMinutes) ?? null;
3416
+ }
3417
+ if (patch.timeoutMs !== undefined) {
3418
+ if (patch.timeoutMs === null)
3419
+ next.timeoutMs = null;
3420
+ else {
3421
+ const value = Number(patch.timeoutMs);
3422
+ if (!Number.isFinite(value) || value <= 0) {
3423
+ throw new PlanError('timeoutMs 必须是正数毫秒(协商上限)', 'INVALID_TIMEOUT_MS');
3424
+ }
3425
+ next.timeoutMs = value;
3426
+ }
3427
+ }
3428
+ /*
3429
+ * [2.2.0][T3/O-2a] 子→主预告通道的可观测条目(方案 §2.4 状态行字段)。
3430
+ *
3431
+ * 这条字段存在的理由就是「不静默丢失」:旧实现里预告发不出去,主 Agent
3432
+ * 只能从子 Agent 的自述里猜,计划记录上没有任何痕迹。现在通道的
3433
+ * target / caller / at / observedAt / reason 全部落在状态行,写入前统一
3434
+ * 校验(未知状态或未知原因直接拒绝),回放与刷新都不会丢。
3435
+ */
3436
+ if (patch.noticeChannel !== undefined) {
3437
+ const checked = validateNoticeChannel(patch.noticeChannel);
3438
+ if (!checked.ok)
3439
+ throw new PlanError(`非法 noticeChannel:${checked.error}`, 'INVALID_NOTICE_CHANNEL');
3440
+ next.noticeChannel = checked.value;
3441
+ }
2867
3442
  /*
2868
3443
  * [1.11.0] 完成回报与重规划的留档字段(T7 C-06/C-11)。
2869
3444
  *
@@ -2984,8 +3559,17 @@ export function applyStatus(statuses, subtaskId, patch) {
2984
3559
  };
2985
3560
  }
2986
3561
  }
2987
- if (patch.handoffs !== undefined)
2988
- next.handoffs = normaliseHandoffs(patch.handoffs);
3562
+ /*
3563
+ * [2.2.9][T2][mono-gate] 整组替换 → 逐项单调合并(M2)。
3564
+ *
3565
+ * 旧语义 `next.handoffs = normaliseHandoffs(patch.handoffs)` 让携带旧快照的
3566
+ * 事件(handoff 答复、人工改判、低 rev 回放)连行上更新的答复一起抹掉。
3567
+ * mergeHandoffEntriesByUpdatedAt 只前进不回退:新登记追加、同项仅在
3568
+ * updatedAt 严格更大时采纳、answered/closed 终态永不回退。
3569
+ */
3570
+ if (patch.handoffs !== undefined) {
3571
+ next.handoffs = mergeHandoffEntriesByUpdatedAt(next.handoffs, patch.handoffs).value;
3572
+ }
2989
3573
  /*
2990
3574
  * [1.12.0][D-30] 溢出记录必须能随结果消息回放。
2991
3575
  *
@@ -4065,7 +4649,21 @@ export function findSubtask(plan, subtaskId) {
4065
4649
  }
4066
4650
  return null;
4067
4651
  }
4068
- export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd, conversationContext = '', statuses = null, previousFailure = null, lessonsBrief = '', }) {
4652
+ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd, conversationContext = '', statuses = null, previousFailure = null, lessonsBrief = '',
4653
+ /*
4654
+ * [2.2.0][T3/O-2a] 子→主预告通道的目标。
4655
+ *
4656
+ * 宿主只对**非 caller** 投递注入父会话 id(dsh-subagent/lib/index.js:1466),
4657
+ * 而本插件用 `delivery: 'caller'` 派发,所以这段 id 必须由插件自己注入。
4658
+ * 不注入时的旧行为是让子 Agent 去喊 `"lead"`——那不是任何会话的 id,
4659
+ * 真实派发中只会得到 `subagent "lead" is unavailable`。
4660
+ */
4661
+ leadAgentId = '', leadAgentIdSource = 'none', }) {
4662
+ const noticeTarget = readLeadAgentId(leadAgentId);
4663
+ const noticeCall = leadNoticeCallForm(noticeTarget);
4664
+ const noticeTargetLine = noticeTarget
4665
+ ? `- 目标会话 id(**由插件注入,唯一合法目标**):\`${noticeTarget}\`(来源:${leadAgentIdSource || 'unknown'})。它就是本轮主 Agent 的会话 id,宿主的父子血缘校验只认它。`
4666
+ : `- **本提示词没有注入父会话 id**(来源:${leadAgentIdSource || 'none'}):禁止猜测、禁止自行拼一个 id。跳过 send_message 预告,改为在结果块首行写 \`noticeChannel: {"target":"${NOTICE_TARGET_MISSING_TEXT}","at":<毫秒时间戳>,"error":"LEAD_ID_MISSING"}\`——供主 Agent 阅读;**插件不解析这一行**,通道结论以状态行观测为准。`;
4069
4667
  /*
4070
4668
  * Every field below is read defensively.
4071
4669
  *
@@ -4245,6 +4843,30 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
4245
4843
  '- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,并按下方「遇阻上报」给出 question。',
4246
4844
  '- 完成后用简洁中文汇报:做了什么、证据/文件、验收结果、遗留问题。',
4247
4845
  '',
4846
+ /*
4847
+ * [2.2.0][T3/O-2a] 柔性时长协商协议(方案 §2.6 #3:「开工前预告、超预期
4848
+ * 预警、完成即回报」;O-1a①+O-2a+O-4a 合并一段,矩阵 Z1 三条款一次插入)。
4849
+ * 时间是协商出来的安全兜底,不是固定交付期限(方案 §0/§3.2)。
4850
+ *
4851
+ * 2026-11-08 修复(真实环境复现 `subagent "lead" is unavailable`):
4852
+ * 旧文案写的是 `send_message(target: "lead")`——字段名与宿主 schema
4853
+ * 不一致(宿主只有 `agent_id`),值 `"lead"` 也不是任何会话 id,于是
4854
+ * 预告在目标解析阶段必然失败。现在改为:注入真实父会话 id + 用宿主
4855
+ * 契约里的字段名 + 明确失败后的确定性重试与留痕,不再有「猜目标」的余地。
4856
+ */
4857
+ '柔性时长协商协议(不设固定完成时间;时间是协商出来的安全兜底,不是固定交付期限):',
4858
+ noticeTargetLine,
4859
+ `- 开工前先报预估时长(预计完成本子任务要多久就报多久):用 \`${noticeCall}\` 报预估完成时长,新预估覆盖旧预估;预估仅供参考、非承诺,实际时长协商决定。`,
4860
+ `- 发现预计将超预估时,立即用同一个目标报新预估并申请延期(说明还要多久、为什么),不要等超时才预警。`,
4861
+ `- 完成即回报:用同一个目标报核心结论(做了什么、证据/文件、验收结果),不要等整轮结束。`,
4862
+ ...(noticeTarget
4863
+ ? [
4864
+ '- 失败后的确定性处理(禁止静默丢弃):`send_message` 若返回错误(`is unavailable` / `UNAUTHORIZED` / 工具不存在),先在汇报首行原样记录 `noticeChannel: {"target":"' + noticeTarget + '","at":<毫秒时间戳>,"error":"<错误原文>"}`,再用**同一个** agent_id 重试一次;仍失败就继续把子任务做完,把这条记录留在结果里(供主 Agent 阅读;插件不解析这一行,通道结论以状态行观测为准)。**不得改用其它目标,也不得向任何非本轮父会话发送**——那是越权发送,会触发宿主 lineage 拒绝。',
4865
+ ]
4866
+ : []),
4867
+ // [T3 扩展点·T6] 供 T6 在此行之后追加「完成即时通知」条款(O-1a 插件兜底通道语义);上方三条款为 O-1a①+O-2a+O-4a 合并协议段(矩阵 Z1),既有条款不得删改。
4868
+ // [2.2.0][T6/O-1a] 完成即时通知条款(插件兜底通道):完成即报是第一通道(见上方「完成即回报」);插件另设兜底——子任务结算成功后立即向主会话推送一条含子任务 ID、摘要、验收计数与用时的即时通知,不等待整轮结束。兜底不替代主动回报。
4869
+ '',
4248
4870
  '遇阻上报(强制,先于继续动作):',
4249
4871
  '- 出现以下任一情况,第一动作是上报,不是猜测、绕过或静默继续:缺少权限/输入/依赖产物;需求自相矛盾;无法验证;同一命令连续两次失败;需要主 Agent 决定方向。',
4250
4872
  '- 优先调用工具:`dsh_workplan_escalate({ "subtaskId": "<你的子任务 ID>", "question": "需要主 Agent 回答的单个问题", "options": ["可选项 A", "可选项 B"], "needs": ["需要谁提供什么"] })`。调用成功后停止推进,只做只读核对。',
@@ -4254,13 +4876,20 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
4254
4876
  '',
4255
4877
  '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
4256
4878
  EVIDENCE_MARKER_BEGIN,
4257
- '{"status":"done","blockedReason":"","phases":{"planning":{"problemAnalysis":["要解决的问题 1(含现状/约束/未知/主要矛盾)"],"constraints":["..."],"unknowns":["..."],"approach":["第 1 步:做什么 → 产出什么 → 如何证明"]},"execution":{"steps":["实际执行的步骤"],"deviations":[]},"verification":{"allPassed":true,"checks":[{"criterion":"A1","method":"怎么验证","evidence":"命令输出/文件/引用"}],"requirementCheck":"逐条核对用户原要求的结果","retrospective":{"problems":["本次遇到的问题(现象+根因)"],"detours":["走过的弯路/返工/无效尝试;确实没有就写 []"],"resolutions":["最终是如何解决的"],"prevention":["以后如何预防再犯:遇到…先…"]}}},"acceptance":[{"criterion":"A1 把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[]}',
4879
+ '{"status":"done","blockedReason":"","phases":{"planning":{"problemAnalysis":["要解决的问题 1(含现状/约束/未知/主要矛盾)"],"constraints":["..."],"unknowns":["..."],"approach":["第 1 步:做什么 → 产出什么 → 如何证明"]},"execution":{"steps":["实际执行的步骤"],"deviations":[]},"verification":{"allPassed":true,"checks":[{"criterion":"A1","method":"怎么验证","evidence":"命令输出/文件/引用"}],"requirementCheck":"逐条核对用户原要求的结果","retrospective":{"problems":["本次遇到的问题(现象+根因)"],"detours":["走过的弯路/返工/无效尝试;确实没有就写 []"],"resolutions":["最终是如何解决的"],"prevention":["以后如何预防再犯:遇到…先…"]}}},"acceptance":[{"criterion":"A1 把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[],"timeSpentMinutes":0,"finalEstimateMinutes":0}',
4258
4880
  EVIDENCE_MARKER_END,
4259
4881
  '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
4260
4882
  '- acceptance 必须逐条覆盖上面的验收标准:criterion 以 A1、A2… 开头对号入座(编号不可省略);result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
4261
4883
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
4262
4884
  '- needs 写需要其他部门配合的事项,每条写清「哪个部门 + 需要什么 + 用来做什么」;它会被登记为待处理需求,主 Agent 必须处置后计划才能交付。不要直连其他子 Agent。',
4263
4885
  '- question/options 只在受阻上报时填写;done 时保持空字符串/空数组。',
4886
+ /*
4887
+ * [2.2.0][T3/O-2c] 用时回填字段(方案 §2.2/§2.4 结果块契约:「模板增加
4888
+ * timeSpentMinutes、finalEstimateMinutes 字段」)。纯 advisory:F1-F9 与
4889
+ * 既有字段零改动,缺失/非法即省略,不判不合规、不影响验收判定(方案 §2.5
4890
+ * 「时间字段纯 advisory」)。
4891
+ */
4892
+ '- timeSpentMinutes / finalEstimateMinutes(可选,整数分钟):完成后把实际耗时与最终预估回填进结果块,未知可省略;两项仅供参考与协商审计,不影响验收判定。',
4264
4893
  '- 整块不超过 12000 字符;不要把这段模板本身抄进结果块。',
4265
4894
  '',
4266
4895
  /*