dsh-workplan 2.1.3 → 2.2.6

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.
Files changed (38) hide show
  1. package/CHANGELOG.md +380 -1
  2. package/README.en.md +5 -2
  3. package/README.md +5 -2
  4. package/README.zh.md +5 -2
  5. package/client.js +143 -3
  6. package/docs/dsh-workplan_T4_runtime.patch +508 -0
  7. package/docs/release-records/_release_notes_2.1.2_20261106.md +44 -0
  8. package/docs/release-records/_t2_version_determination_20261106.md +39 -0
  9. package/docs/release-records/_t5_external_reverify_20261106.md +18 -0
  10. package/docs/release-records/release-dryrun-report-20261106.md +74 -0
  11. package/docs/release-records/release-notes-2.2.6-T3.md +128 -0
  12. package/docs/release-records/release-record-2.1.3-20261106.md +82 -0
  13. package/docs/release-records/release-steps-20261106.md +129 -0
  14. package/docs/release-records/version-freeze-20261109-T2.md +37 -0
  15. package/lib/client.js +143 -3
  16. package/lib/comm-format.js +17 -0
  17. package/lib/departments.js +19 -0
  18. package/lib/host.js +95 -17
  19. package/lib/notice-channel.js +290 -0
  20. package/lib/plan.js +541 -32
  21. package/lib/replan.js +4 -0
  22. package/lib/runtime.js +1481 -85
  23. package/lib/supersede.js +2 -2
  24. package/lib/understanding.js +8 -2
  25. package/lib/watchdog.js +52 -1
  26. package/package.json +3 -2
  27. package/scripts/repair-malformed-user-messages.mjs +312 -0
  28. package/src/client.ts +150 -2
  29. package/src/comm-format.ts +17 -0
  30. package/src/departments.ts +22 -0
  31. package/src/host.ts +90 -12
  32. package/src/notice-channel.ts +328 -0
  33. package/src/plan.ts +575 -24
  34. package/src/replan.ts +4 -0
  35. package/src/runtime.ts +1500 -86
  36. package/src/supersede.ts +2 -1
  37. package/src/understanding.ts +10 -2
  38. package/src/watchdog.ts +80 -1
package/src/plan.ts CHANGED
@@ -9,10 +9,16 @@
9
9
 
10
10
  import { createHash, randomUUID } from 'node:crypto'
11
11
 
12
- import { DEPARTMENT_CAPABILITIES, departmentCapability } from './departments.js'
12
+ import { DEPARTMENT_CAPABILITIES, DEPARTMENT_EXPERT_STANDARD, departmentCapability } from './departments.js'
13
13
  import { MAX_TASK_ANCHOR_CHARS } from './understanding.js'
14
14
  import { isMappingDigest, verifyMappingDigest } from './supersede-digest.js'
15
15
  import { phaseSummaryLine, threePhasePromptLines, validatePhaseEvidence } from './three-phase.js'
16
+ import {
17
+ NOTICE_TARGET_MISSING_TEXT,
18
+ leadNoticeCallForm,
19
+ readLeadAgentId,
20
+ validateNoticeChannel,
21
+ } from './notice-channel.js'
16
22
  import {
17
23
  checkCommFormatCompliance,
18
24
  renderCommFormatRejection,
@@ -186,6 +192,17 @@ export const MAX_HANDOFFS = MAX_EVIDENCE_NEEDS
186
192
  export const MAX_HANDOFF_RESPONSE_CHARS = 4000
187
193
  export const LIKELIHOODS = Object.freeze(['low', 'medium', 'high'])
188
194
 
195
+ /*
196
+ * [2.2.0][T13/推理等级] 子 Agent 的推理等级只有三档(用户强制规则)。
197
+ *
198
+ * 用户规则原文:「禁止子agent继承主agent的推理等级,子agent必须根据自身任务的
199
+ * 复杂度,自己使用推理等级为low、high或者是Max,其中,轻度复杂的任务使用low,
200
+ * 中等复杂的任务使用high,非常复杂的任务使用Max。」
201
+ * 子任务未声明该字段时回落 high(中等默认);执行侧绝不读取主 Agent 的等级。
202
+ */
203
+ export const REASONING_EFFORTS = Object.freeze(['low', 'high', 'max'])
204
+ export const DEFAULT_REASONING_EFFORT = 'high'
205
+
189
206
  export const DEPARTMENTS = Object.freeze({
190
207
  engineering: { zh: '工程研发', en: 'Engineering' },
191
208
  research: { zh: '研究分析', en: 'Research' },
@@ -668,6 +685,63 @@ function readSubtasks(value: any, stageIndex: any, errors: any) {
668
685
  if (!DEPARTMENTS[department as keyof typeof DEPARTMENTS]) {
669
686
  push(errors, `${base}.department`, `必须是 ${DEPARTMENT_IDS.join(' / ')} 之一`)
670
687
  }
688
+ /*
689
+ * [2.2.0][T3/O-2b] 预估区间改判:1-240 整数,越界拒绝、区间内原样保留。
690
+ *
691
+ * 方案原文(docs/dsh-workplan_优化方案_20261107.md):
692
+ * - §2.2「estimateMinutes 钳制放宽为 1–240 整数(仅防离谱值,advisory 不变)」;
693
+ * - §1⑤ O-5c「固定区间去钳制:同 O-2b」;
694
+ * - §1② B2「estimateMinutes: 90 的计划通过校验且原样保留(不再被钳成 15)」。
695
+ * 「去钳制 + 原样保留 + 仅防离谱值」的唯一自洽合成:合法区间内不再改写值,
696
+ * 0/241 等离谱值**拒绝**并点名字段(不是钳成 1/240 蒙混通过)——与同源用例
697
+ * tests/time-estimate-negotiation.test.ts(0 与 241 被拒、1/90/240 原样保留)一致。
698
+ * 可选与缺省合法的宽容面保留(旧计划零回归,验收 ②B4):没有 estimateMinutes
699
+ * 的计划照旧通过校验。歧义链与 Z8 红线取舍见
700
+ * docs/dsh-workplan_T3_plan改动说明_20261107.md。
701
+ */
702
+ const hasEstimate = source.estimateMinutes !== undefined && source.estimateMinutes !== null
703
+ const estimateValue = hasEstimate ? Number(source.estimateMinutes) : NaN
704
+ const estimateOk = hasEstimate
705
+ && typeof source.estimateMinutes === 'number'
706
+ && Number.isInteger(estimateValue)
707
+ && estimateValue >= 1
708
+ && estimateValue <= 240
709
+ if (hasEstimate && !estimateOk) {
710
+ push(errors, `${base}.estimateMinutes`, '必须是 1-240 的整数(仅防离谱值:越界或非整数拒绝、不改写;该字段可选,缺失合法)')
711
+ }
712
+ /*
713
+ * [2.2.0][T3/O-3a] per-subtask 协商上限(timeoutMs,毫秒)可选透传。
714
+ *
715
+ * 方案 §2.2:「timeoutMs(可选)|本子任务的协商上限;缺省由 estimateMinutes
716
+ * × 2.0 派生并钳制|readSubtasks + validatePlan 只校验类型与范围,缺省合法」。
717
+ * 原样透传、不在此处钳到 MAX(同源用例 tests/time-estimate-negotiation.test.ts
718
+ * 固化 timeoutMs: 3600000 原样保留);只校验类型与范围:正数毫秒,缺失合法。
719
+ * 范围上界方案未给定(未知/待核实,见改动说明歧义点 3)。
720
+ */
721
+ const hasTimeout = source.timeoutMs !== undefined && source.timeoutMs !== null
722
+ const timeoutValue = hasTimeout ? Number(source.timeoutMs) : NaN
723
+ const timeoutOk = hasTimeout
724
+ && typeof source.timeoutMs === 'number'
725
+ && Number.isFinite(timeoutValue)
726
+ && timeoutValue > 0
727
+ if (hasTimeout && !timeoutOk) {
728
+ push(errors, `${base}.timeoutMs`, '必须是正数毫秒(协商上限,可选字段,缺失合法)')
729
+ }
730
+ /*
731
+ * [2.2.0][T13/推理等级] 子任务自带的推理等级(可选,仅 low / high / max)。
732
+ *
733
+ * 用户规则原文见 REASONING_EFFORTS 上方注释。语义与 estimateMinutes 同风格:
734
+ * 缺失合法(旧计划/回放零回归),但非法值**拒绝**并点名字段,不静默改写成
735
+ * 其它档位;执行侧对缺失值回落 DEFAULT_REASONING_EFFORT(high),绝不继承
736
+ * 主 Agent 的等级。
737
+ */
738
+ const hasEffort = source.reasoningEffort !== undefined && source.reasoningEffort !== null
739
+ const effortOk = hasEffort
740
+ && typeof source.reasoningEffort === 'string'
741
+ && REASONING_EFFORTS.includes(source.reasoningEffort)
742
+ if (hasEffort && !effortOk) {
743
+ push(errors, `${base}.reasoningEffort`, '必须是 low / high / max 之一(可选字段,缺失时回落 high;非法值拒绝,不改写)')
744
+ }
671
745
  return {
672
746
  id: readString(source.id, `${base}.id`, 1, 16, errors),
673
747
  title: readString(source.title, `${base}.title`, 1, 200, errors),
@@ -701,14 +775,44 @@ function readSubtasks(value: any, stageIndex: any, errors: any) {
701
775
  * [1.7.0] Optional time estimate, advisory only. Validation never fails on
702
776
  * a missing or out-of-range value: a plan that cannot be dispatched is
703
777
  * worse than one carrying a rough estimate.
778
+ * [2.2.0][T3/O-2b] 语义演进(上方校验块注释引方案原文):缺省仍然合法;
779
+ * 越界自 2.2.0 起拒绝而非钳制(§1⑤ O-5c 固定区间去钳制),本注释保留为
780
+ * [1.7.0] 历史记录。
704
781
  */
705
- ...(Number.isFinite(Number(source.estimateMinutes))
706
- ? { estimateMinutes: Math.min(15, Math.max(1, Math.round(Number(source.estimateMinutes)))) }
707
- : {}),
782
+ ...(estimateOk ? { estimateMinutes: estimateValue } : {}),
783
+ ...(timeoutOk ? { timeoutMs: timeoutValue } : {}),
784
+ reasoningEffort: effortOk ? String(source.reasoningEffort) : DEFAULT_REASONING_EFFORT,
708
785
  }
709
786
  })
710
787
  }
711
788
 
789
+ /**
790
+ * [2.2.0][T3/O-3a] per-subtask 协商上限(negotiated ceiling)派生公式。
791
+ *
792
+ * 方案 §1③ O-3a:「缺省时由预估派生:协商上限 = clamp(预估分钟 × 安全系数
793
+ * (建议 2.0), 全局下限, 单次绝对上限)」;§2.2 timeoutMs 行:「缺省由
794
+ * `estimateMinutes × 2.0` 派生并钳制」。分钟→毫秒按 ×60000 换算(同源用例
795
+ * tests/time-estimate-negotiation.test.ts 的 expected 公式逐字一致)。
796
+ *
797
+ * 消费序(O-3b 接线契约,runtime 侧):显式 subtask.timeoutMs(O-3c:预告经
798
+ * 主 Agent 确认后写入,原样透传)→ 缺省调用本函数派生(钳在 [minMs, maxMs],
799
+ * 验收 ③C3)→ 两者皆无(旧计划无 estimateMinutes 也无 timeoutMs)返回
800
+ * undefined,消费侧回落原行为(normaliseChildTimeout 全局兜底,验收 ③C2)。
801
+ * 本函数只做「预估→派生值」纯换算,不读 subtask 对象。
802
+ *
803
+ * MIN_CHILD_TIMEOUT_MS=1,000 毫秒不变(与 src/runtime.ts:220 现状同值)。
804
+ * MAX_CHILD_TIMEOUT_MS=7,200,000 毫秒(120 分钟)=plan.ts 侧派生上限——
805
+ * 【用户 2026-11-07 决断】方案 §6 未知第 4 条已由用户拍板上调;runtime.ts:221
806
+ * 常量本体由 T4 波次同步改(改前两处不同值时以本决断为准)。
807
+ * plan.ts 被 runtime.ts 反向依赖(runtime.ts import './plan.js'),不能反向
808
+ * import,故此处带默认值、调用方可传入权威常量。
809
+ */
810
+ export function deriveSubtaskTimeoutMs(estimateMinutes: any, minMs = 1000, maxMs = 7200000): number | undefined {
811
+ const estimate = Number(estimateMinutes)
812
+ if (!Number.isFinite(estimate) || estimate <= 0) return undefined
813
+ return Math.min(maxMs, Math.max(minMs, estimate * 2.0 * 60_000))
814
+ }
815
+
712
816
  function readStages(value: any, errors: any) {
713
817
  if (!Array.isArray(value)) {
714
818
  push(errors, 'stages', '必须是数组')
@@ -1103,7 +1207,10 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1103
1207
  const departments = DEPARTMENT_CAPABILITIES
1104
1208
  .map((entry) => `- ${entry.id}(${entry.zh} / ${entry.en}):职责 ${entry.responsibilities.join(';')};典型产物 ${entry.outputs.join(';')}`)
1105
1209
  .join('\n')
1106
- const totalMinutes = Math.max(1, Math.round(Number(budget?.totalMinutes) || 20))
1210
+ const rawTotalMinutes = Number(budget?.totalMinutes)
1211
+ const totalMinutes = Number.isFinite(rawTotalMinutes) && rawTotalMinutes > 0
1212
+ ? Math.max(1, Math.round(rawTotalMinutes))
1213
+ : 0
1107
1214
  const childMinutes = Math.max(1, Math.round(Number(budget?.childMinutes) || 15))
1108
1215
  const concurrency = Math.max(1, Number(budget?.concurrency) || MAX_CONCURRENT)
1109
1216
  const resumes = Number.isFinite(Number(budget?.maxResumes)) ? Number(budget.maxResumes) : MAX_PLAN_RESUMES
@@ -1140,16 +1247,29 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1140
1247
  '- unknowns 和 assumptions 必须如实列出;没有就写空数组,不能把假设写成事实。',
1141
1248
  '- 子任务必须可独立执行、可验收;不要为了凑数拆无意义任务。',
1142
1249
  '- 子任务由子 Agent 独立执行:它们没有派发权限、不能重启服务、不能安装或升级依赖。禁止把「调用 dsh_workplan_dispatch」「重启/停止 dsh web」「安装或升级插件」这类只有主 Agent 才能执行的动作写进子任务;确实需要时,写成“给出结论或建议,由主 Agent 执行”。',
1143
- '- 单个子任务应能在 10 分钟内完成;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1250
+ '- 单个子任务无须在 10 分钟内完成——10 分钟只是拆步规模建议,不是完成期限、也不构成承诺;实际时长由执行专家开工预告协商决定,不设固定完成时间;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1144
1251
  '- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
1145
1252
  '',
1146
1253
  '本轮时间预算(硬事实,请据此规划规模):',
1147
- `- 一轮总预算约 ${totalMinutes} 分钟;单个子任务上限 ${childMinutes} 分钟;同时最多 ${concurrency} 个子任务并行。`,
1148
- `- 受阻后自动续跑额度 ${resumes} 次;总工作量超过一轮预算时,计划会被暂停并在下一轮继续。`,
1149
- '- 每个子任务必须写 estimateMinutes(整数 1-15):你预估它需要多少分钟。宁可估高,不要估低。',
1254
+ totalMinutes > 0
1255
+ ? `- 一轮总预算约 ${totalMinutes} 分钟(安全兜底,不是交付期限);单个子任务规模参考 ${childMinutes} 分钟量级(仅供参考、非承诺,实际时长由执行专家开工预告协商决定);同时最多 ${concurrency} 个子任务并行。`
1256
+ : `- 本轮不设固定总预算;单个子任务按自身 estimateMinutes 与协商截止/延期执行;同时最多 ${concurrency} 个子任务并行。`,
1257
+ resumes > 0
1258
+ ? `- 受阻后自动续跑额度 ${resumes} 次;需要时计划会暂停并在下一轮继续。`
1259
+ : '- 自动续跑额度为 0;计划不会因轮次预算被暂停。',
1260
+ '- 每个子任务必须写 estimateMinutes(整数 1-240,宁可估高):你预估它需要多少分钟。宁可估高,不要估低。取值必须是整数,越界或非整数会被校验拒绝(仅防离谱值),缺失不报错。',
1261
+ /*
1262
+ * [2.2.0][T13/推理等级] 子 Agent 必须自决推理等级,禁止继承主 Agent。
1263
+ * 用户规则原文见 plan.ts 顶部 REASONING_EFFORTS 注释;三档映射与三个示例
1264
+ * 按用户规则逐字展开,规划器输出由 readSubtasks 校验(只收 low/high/max)。
1265
+ */
1266
+ '- 每个子任务必须按它自身的复杂度写 reasoningEffort(推理等级,只允许 low / high / max 三档):轻度复杂="low",中等复杂="high",非常复杂="max"。',
1267
+ '- reasoningEffort 三档示例:整理并校对一份已有清单="low";独立实现一个模块并补齐测试="high";跨多个系统排查根因并给出架构级修复方案="max"。',
1268
+ '- 禁止沿用/继承主 Agent 的推理等级:reasoningEffort 只由该子任务自身的复杂度决定,不得因为主 Agent 当前是某一档就照抄;缺失时执行侧回落 "high",但你必须显式写出该字段。',
1150
1269
  '- 规模大就如实拆成多轮,不要为了塞进一轮而把多个交付物压进一个子任务。',
1151
1270
  '',
1152
- '可用部门:',
1271
+ '可用部门(每个部门的执行者都是来自全球相关领域的顶尖专家,不是普通部门人员):',
1272
+ DEPARTMENT_EXPERT_STANDARD.planner,
1153
1273
  departments,
1154
1274
  '',
1155
1275
  `工作目录:${directory}`,
@@ -1196,7 +1316,7 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1196
1316
  ' "title": "子任务",',
1197
1317
  ' "department": "engineering",',
1198
1318
  ' "departmentRationale": "为什么是该部门:命中哪条职责、对应任务哪个要素",',
1199
- ' "role": "部门内角色",',
1319
+ ' "role": "部门内角色(按该领域全球顶尖专家定位填写,如「资深架构师·全球顶尖水准」)",',
1200
1320
  ' "objective": "目标",',
1201
1321
  ' "method": ["具体方法/步骤"],',
1202
1322
  ' "inputs": ["输入;未知写待确认"],',
@@ -1204,7 +1324,8 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1204
1324
  ' "dependsOn": [],',
1205
1325
  ' "acceptance": ["可测试的验收标准"],',
1206
1326
  ' "risk": "主要风险",',
1207
- ' "estimateMinutes": 5',
1327
+ ' "estimateMinutes": 5,',
1328
+ ' "reasoningEffort": "high"',
1208
1329
  ' }',
1209
1330
  ' ]',
1210
1331
  ' }',
@@ -1240,6 +1361,122 @@ export function makeUserMessage(text: any, source: any) {
1240
1361
  }
1241
1362
  }
1242
1363
 
1364
+ /**
1365
+ * [2.2.1] Validate the exact payload shape DSH requires for a `user/message`
1366
+ * event before it reaches the append-only log.
1367
+ *
1368
+ * Incident it prevents (2026-11-08, session-a404d49d…): the plugin appended
1369
+ * plain strings as `user/message` data. `Session.append()` only validates
1370
+ * payloads that are records, so the strings were persisted; on replay the
1371
+ * `goal` projection read `event.data.source.kind` and threw
1372
+ * "Cannot read properties of undefined (reading 'kind')", which surfaced as
1373
+ * "历史加载失败 / failed to project session". A malformed event is
1374
+ * unrecoverable once appended, so rejection must happen here, before append.
1375
+ */
1376
+ function userMessageShapeProblem(message: any): string | null {
1377
+ if (!isRecord(message)) return 'payload must be a plain object'
1378
+ if (typeof message.id !== 'string' || message.id.length === 0) return 'missing message id'
1379
+ if (message.role !== 'user') return 'role must be "user"'
1380
+ if (!Array.isArray(message.content) || message.content.length === 0) return 'content must be a non-empty array'
1381
+ if (!isRecord(message.source)) return 'missing source'
1382
+ if (typeof message.source.kind !== 'string' || message.source.kind.length === 0) return 'missing source.kind'
1383
+ return null
1384
+ }
1385
+
1386
+ /**
1387
+ * [2.2.1] The single approved writer for `user/message` events in this plugin.
1388
+ *
1389
+ * A raw string is wrapped into a complete DSH `UserMessage` (stable id, role,
1390
+ * text content, source with a nonempty `kind`); an already-built message is
1391
+ * shape-checked. Either way a malformed payload throws BEFORE `session.append`,
1392
+ * so a bad notice can never corrupt a session log again. All appends use
1393
+ * `surfaceOp: 'append'`, matching the previous call sites.
1394
+ */
1395
+ export function appendUserMessage(session: any, payload: any, source?: any) {
1396
+ if (!session || typeof session.append !== 'function') return undefined
1397
+ let message = payload
1398
+ if (typeof payload === 'string') {
1399
+ const summary = truncate(String(payload).replace(/\s+/g, ' ').trim() || '(无摘要)', 120)
1400
+ message = makeUserMessage(payload, source ?? { kind: 'workplan', form: 'notice', summary })
1401
+ }
1402
+ const problem = userMessageShapeProblem(message)
1403
+ if (problem !== null) throw new Error(`dsh-workplan: refusing to append malformed user/message (${problem})`)
1404
+ return session.append('user/message', message, { surfaceOp: 'append' })
1405
+ }
1406
+
1407
+ /*
1408
+ * [2.2.5][T5] 分解期间进度文案与回报器(T3 交互规范 §3 C2/C3、§4 频率规则)。
1409
+ *
1410
+ * 缺陷:runPlanner 全程(最长 3 次尝试 × 300s 窗口 + 退避)插件既不写会话
1411
+ * 消息也不放内存记录(T1 断点层判定=未发出),用户无法区分「正在重试」与
1412
+ * 「卡死」。本组函数只负责「把一次失败尝试翻译成用户能看懂的两句话」:
1413
+ * - cardLine:通道 A(侧栏占位卡片的 errors 区,4 秒轮询可见,保底通道);
1414
+ * - notice:通道 B(appendUserMessage 聊天通知,仅「会退避重试」的失败才
1415
+ * 发,每轮至多 2 条——第 3 次失败直接进降级文案,不再叠加通知)。
1416
+ * 文案硬规则(T3 §3):真因链截断 ≤120 字符(错误码原样保留,供用户报障);
1417
+ * 分母 3 由 maxAttempts 参数注入,不在文案里硬编码;等待时长按实际退避
1418
+ * 四舍五入到秒;aborted 由调用方(回报器)静默,本函数不涉及。
1419
+ */
1420
+ export function plannerProgressLines(report: any, maxAttempts: number) {
1421
+ const attempt = Number(report?.attempt) || 0
1422
+ const outcome = String(report?.outcome ?? 'PLANNER_ERROR')
1423
+ const causes = Array.isArray(report?.lastErrors) ? report.lastErrors : []
1424
+ const cause = truncate(causes.join(';').replace(/\s+/g, ' ').trim(), 120)
1425
+ if (attempt <= 0 || !cause) return { cardLine: '', notice: null }
1426
+ const terminal = report?.terminal === true
1427
+ const backoffMs = Number(report?.retryBackoffMs) || 0
1428
+ const total = Number(maxAttempts) || attempt
1429
+ const willRetry = !terminal && backoffMs > 0 && attempt < total
1430
+ const waitSecs = Math.max(1, Math.round(backoffMs / 1000))
1431
+ const prefix = `第 ${attempt} 次尝试失败(${outcome}):${cause}`
1432
+ const cardLine = willRetry
1433
+ ? `${prefix};正在重试(约 ${waitSecs} 秒后),第 ${attempt + 1}/${total} 次`
1434
+ : backoffMs > 0
1435
+ ? `${prefix};正在重试`
1436
+ : `${prefix}`
1437
+ const notice = willRetry
1438
+ ? `【自动分解】第 ${attempt} 次尝试失败:${cause};正在重试(约 ${waitSecs} 秒后),第 ${attempt + 1}/${total} 次`
1439
+ : null
1440
+ return { cardLine, notice }
1441
+ }
1442
+
1443
+ /*
1444
+ * [2.2.5][T5] 进度回报器工厂:把 runPlanner 的 onProgress 回调落到两个既有
1445
+ * 通道上(T3 §2 S2、§4 频率规则)。依赖全部以参数注入(signal / 落记录 /
1446
+ * 发通知),便于脱离宿主运行态做单元回归:
1447
+ * - signal.aborted 后一律静默(用户自己取消的,不再打扰,也不写记录);
1448
+ * - 通道 A 每轮至多 2 行(maxLines),通道 B 每轮至多 2 条(maxNotices);
1449
+ * - 记录更新走 setRecord 回调(maybePlan 侧即 state.records.set),失败
1450
+ * 尝试的摘要在成功/降级后被既有 records.set 整体覆盖,无残留。
1451
+ */
1452
+ export function createPlannerProgressReporter(options: {
1453
+ signal?: any
1454
+ record: any
1455
+ setRecord: (record: any) => void
1456
+ appendNotice: (text: string) => void
1457
+ maxAttempts: number
1458
+ maxLines?: number
1459
+ maxNotices?: number
1460
+ }) {
1461
+ const maxLines = Math.max(1, Number(options.maxLines) || 2)
1462
+ const maxNotices = Math.max(0, Number(options.maxNotices) || 2)
1463
+ const errors: string[] = []
1464
+ let notices = 0
1465
+ return (report: any) => {
1466
+ if (options.signal?.aborted) return
1467
+ const lines = plannerProgressLines(report, options.maxAttempts)
1468
+ if (!lines.cardLine) return
1469
+ if (errors.length < maxLines) errors.push(lines.cardLine)
1470
+ options.record.errors = [...errors]
1471
+ options.record.updatedAt = Date.now()
1472
+ options.setRecord(options.record)
1473
+ if (lines.notice && notices < maxNotices) {
1474
+ notices += 1
1475
+ options.appendNotice(lines.notice)
1476
+ }
1477
+ }
1478
+ }
1479
+
1243
1480
  export function buildPlanSummary(plan: any) {
1244
1481
  const total = flattenSubtasks(plan).length
1245
1482
  const primary = plan.contradictions.primary.statement
@@ -1271,17 +1508,31 @@ export function estimatePlanMinutes(plan: any, fallbackMinutes = 15, concurrency
1271
1508
  return Math.max(waves * maxEstimate, Math.ceil(totalEstimate / Math.max(1, concurrency)))
1272
1509
  }
1273
1510
 
1274
- export function buildBudgetWarning(plan: any, totalBudgetMinutes = 20, maxResumes = MAX_PLAN_RESUMES) {
1511
+ export function buildBudgetWarning(plan: any, totalBudgetMinutes = 0, maxResumes = MAX_PLAN_RESUMES) {
1275
1512
  const minutes = estimatePlanMinutes(plan)
1276
- const budget = Math.max(1, Math.round(Number(totalBudgetMinutes) || 20))
1277
- if (minutes <= budget) return ''
1513
+ const rawBudget = Number(totalBudgetMinutes)
1514
+ const budget = Number.isFinite(rawBudget) && rawBudget > 0 ? Math.max(1, Math.round(rawBudget)) : 0
1515
+ /*
1516
+ * [2.2.0][T3/O-5b] 固定预算措辞改为「预估仅供参考,非承诺;实际时长协商
1517
+ * 决定」(方案 §2.6 #5 的目标措辞;O-5b 三处承诺禁令之一):预算提示只讲
1518
+ * 估算与轮次,不构成任何固定交付承诺。
1519
+ *
1520
+ * 标注行是输出的固定组成部分——预算内也返回(验收 E2「预算预告/计划消息
1521
+ * 把预估标注为仅供参考/非承诺」:凡 buildBudgetWarning 有输出必带该标注,
1522
+ * 计划消息经 warning 路径同享,不再按超预算与否吞掉)。
1523
+ */
1524
+ const advisory = '(子任务 estimateMinutes 预估仅供参考,非承诺;实际时长协商决定:由执行专家开工预告协商,不设固定完成时间。)'
1525
+ // [2.2.5] 0 = 本轮不设固定总预算:只保留“预估仅供参考”的标注,不再输出
1526
+ // “超过本轮预算/需要 N 轮”的提示,避免与“不强制限制”的目标矛盾。
1527
+ if (budget === 0 || minutes <= budget) return advisory
1278
1528
  const rounds = Math.max(1, Math.ceil(minutes / budget))
1279
1529
  const missing = flattenSubtasks(plan).some((entry: any) => !Number.isFinite(Number(entry.subtask?.estimateMinutes)))
1280
1530
  return [
1281
1531
  `⚠ 预算提示:本计划 ${flattenSubtasks(plan).length} 项,按其估计约需 ${minutes} 分钟 > 本轮 ${budget} 分钟,`
1282
1532
  + `预计需要约 ${rounds} 轮(续跑额度 ${maxResumes} 次)。`,
1533
+ advisory,
1283
1534
  '建议:拆成多轮,或减少同时进行的子任务。',
1284
- ...(missing ? ['(部分子任务缺少 estimateMinutes,已按 15 分钟上限估算。)'] : []),
1535
+ ...(missing ? ['(部分子任务缺少 estimateMinutes,已按每项 15 分钟默认值估算。)'] : []),
1285
1536
  ].join('\n')
1286
1537
  }
1287
1538
 
@@ -1298,11 +1549,17 @@ export function buildPlanMessage(plan: any, options: any = {}) {
1298
1549
  }
1299
1550
  const warning = buildBudgetWarning(
1300
1551
  plan,
1301
- options.totalBudgetMinutes ?? 20,
1552
+ options.totalBudgetMinutes ?? 0,
1302
1553
  options.maxResumes ?? MAX_PLAN_RESUMES,
1303
1554
  )
1304
1555
  const text = [
1305
1556
  summary,
1557
+ /*
1558
+ * [2.2.0][T3/O-5b/E2] 计划消息中的预估一律标注「非承诺」(方案 §1⑤ O-5b:
1559
+ * 「预估一律标注『仅供参考,实际时长由执行专家预告协商』」;验收 E2)。
1560
+ * 标注由 buildBudgetWarning 的固定 advisory 行携带(预算内也返回,见该
1561
+ * 函数注释),warning 恒非空随消息带出,此处不再重复一份。
1562
+ */
1306
1563
  ...(warning ? ['', warning] : []),
1307
1564
  '',
1308
1565
  /*
@@ -1327,6 +1584,11 @@ export function buildPlanMessage(plan: any, options: any = {}) {
1327
1584
 
1328
1585
  export function buildDegradedMessage(options: any) {
1329
1586
  const error = truncate(options.error ?? '未知错误', 600)
1587
+ /*
1588
+ * [2.1.6] 失败现场:模型、耗时、收到几个输出块、判定码。没有它,用户只看到
1589
+ * 一句「超时」,既不知道是不是模型太慢,也不知道该改哪个旋钮。
1590
+ */
1591
+ const detail = truncate(options.detail ?? '', 400)
1330
1592
  const summary = truncate(`【自动分解降级】${error}`, 300)
1331
1593
  const payload = {
1332
1594
  kind: 'workplan',
@@ -1337,6 +1599,7 @@ export function buildDegradedMessage(options: any) {
1337
1599
  createdAt: options.createdAt,
1338
1600
  degraded: true,
1339
1601
  error,
1602
+ ...(detail ? { detail } : {}),
1340
1603
  title: '自动分解降级',
1341
1604
  taskUnderstanding: {
1342
1605
  originalRequest: truncate(options.taskText ?? '', 2000),
@@ -1350,6 +1613,7 @@ export function buildDegradedMessage(options: any) {
1350
1613
  }
1351
1614
  const text = [
1352
1615
  summary,
1616
+ ...(detail ? ['', detail] : []),
1353
1617
  '',
1354
1618
  '自动任务分解失败,部门 Agent 未启动。',
1355
1619
  '请先向用户说明失败原因,并询问是否重试;在用户确认前不要开始执行任务。',
@@ -1526,7 +1790,10 @@ export function buildResultMessage(result: any) {
1526
1790
  return handoffs.map((handoff: any) =>
1527
1791
  `${item.subtaskId} ${String(handoff?.id ?? 'H?')}(${String(handoff?.status ?? 'open')}):${String(handoff?.request ?? '')}`)
1528
1792
  }
1529
- return (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${need}`)
1793
+ // [2.2.6][T4] needs 条目自本版起可能为结构化对象 {request, department},
1794
+ // 旧记录仍是字符串;统一经 needEntryText 渲染,两条形状都不会再出现
1795
+ // "[object Object]"(字符串路径逐字不变)。
1796
+ return (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${needEntryText(need)}`)
1530
1797
  })
1531
1798
  const review: string[] = []
1532
1799
  if (escalations.length > 0) {
@@ -2017,10 +2284,88 @@ function readEvidenceArtifacts(value: any) {
2017
2284
  }).filter((item: any) => item.ref !== '')
2018
2285
  }
2019
2286
 
2287
+ /*
2288
+ * [2.2.6][T4] 循环引用/undefined 安全的 JSON 文本化兜底(缺陷二修复件)。
2289
+ *
2290
+ * 对象形 needs 的兜底路径不允许再用隐式 String()——它把任意对象变成字面量
2291
+ * "[object Object]",department 等字段当场丢失(wp-db6de2f0 的 T1–T4 四条
2292
+ * handoff 即因此损坏)。JSON.stringify 对循环引用会抛错、对顶层 undefined
2293
+ * 返回 undefined,这里统一兜成可读文本,任何形状都不会炸掉结果块解析。
2294
+ */
2295
+ function safeJsonText(value: any): string {
2296
+ const seen = new WeakSet<object>()
2297
+ try {
2298
+ return JSON.stringify(value, (_key, entry) => {
2299
+ if (entry !== null && typeof entry === 'object') {
2300
+ if (seen.has(entry)) return '[Circular]'
2301
+ seen.add(entry)
2302
+ }
2303
+ return entry === undefined ? null : entry
2304
+ }) ?? ''
2305
+ } catch {
2306
+ return '[Unserializable object]'
2307
+ }
2308
+ }
2309
+
2310
+ /** [2.2.6][T4] 本插件 readEvidenceNeeds 产出的规范化条目形状(回放幂等判定)。 */
2311
+ function isStructuredNeedEntry(item: any) {
2312
+ return isRecord(item) && typeof item.request === 'string' && item.request.trim() !== ''
2313
+ && Object.keys(item).every((key) => key === 'request' || key === 'department')
2314
+ }
2315
+
2316
+ /*
2317
+ * [2.2.6][T4] 对象感知的 needs/options 文本提取(取代一切 String(对象))。
2318
+ *
2319
+ * 字符串原样返回(历史行为逐字不变);对象优先读取 need/request/text/
2320
+ * message/question 中首个非空文本字段,拼上 purpose(用途)与 department
2321
+ * (部门)前缀,与子 Agent 实际写入的 {"department","need","purpose"} 形状
2322
+ * 对齐(T1 §2.4 子会话日志原文实证);完全无法识别的形状回退受控 JSON 文本。
2323
+ * 注意:本插件自己的结构化条目 {request, department} 视为已定稿文本原样返回,
2324
+ * 否则 mergeHandoffsFromNeeds 会二次拼「部门:」前缀。
2325
+ */
2326
+ export function needEntryText(item: any): string {
2327
+ if (typeof item === 'string') return item
2328
+ if (typeof item === 'number' || typeof item === 'boolean') return String(item)
2329
+ if (!isRecord(item)) return item == null ? '' : safeJsonText(item)
2330
+ if (isStructuredNeedEntry(item)) return item.request
2331
+ const text = [item.need, item.request, item.text, item.message, item.question]
2332
+ .find((entry: any) => typeof entry === 'string' && entry.trim() !== '')
2333
+ const purpose = typeof item.purpose === 'string' && item.purpose.trim() !== '' ? item.purpose.trim() : ''
2334
+ const department = typeof item.department === 'string' && item.department.trim() !== '' ? item.department.trim() : ''
2335
+ if (typeof text === 'string') {
2336
+ const body = purpose !== '' ? `${text.trim()}(用途:${purpose})` : text.trim()
2337
+ return department !== '' ? `${department}:${body}` : body
2338
+ }
2339
+ return safeJsonText(item)
2340
+ }
2341
+
2342
+ /** [2.2.6][T4] 对象形 needs 的合法部门键提取(与 normaliseHandoffs 同一判定)。 */
2343
+ export function needEntryDepartment(item: any): string | null {
2344
+ if (!isRecord(item)) return null
2345
+ const department = item.department
2346
+ return typeof department === 'string' && DEPARTMENTS[department as keyof typeof DEPARTMENTS]
2347
+ ? department
2348
+ : null
2349
+ }
2350
+
2020
2351
  function readEvidenceNeeds(value: any) {
2021
2352
  if (!Array.isArray(value)) return []
2022
2353
  return value.slice(0, MAX_EVIDENCE_NEEDS)
2023
- .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
2354
+ .map((item: any) => {
2355
+ if (typeof item === 'string') return truncate(item, 300)
2356
+ /*
2357
+ * [2.2.6][T4] 回放/重读幂等:本插件自己产出的结构化条目(仅含
2358
+ * request/department 两个键)原样保留,不二次拼「部门:」前缀——
2359
+ * 否则结果消息回放时文本会变化,绕过去重键造成重复登记。
2360
+ */
2361
+ if (isStructuredNeedEntry(item)) {
2362
+ return { request: truncate(item.request, 300), department: needEntryDepartment(item) }
2363
+ }
2364
+ const request = truncate(needEntryText(item), 300).trim()
2365
+ if (!request) return null
2366
+ const department = needEntryDepartment(item)
2367
+ return department !== null ? { request, department } : request
2368
+ })
2024
2369
  .filter(Boolean)
2025
2370
  }
2026
2371
 
@@ -2070,8 +2415,17 @@ export function mergeHandoffsFromNeeds(current: any, needs: any, overflow: strin
2070
2415
  const next = normaliseHandoffs(current)
2071
2416
  const list = Array.isArray(needs) ? needs : []
2072
2417
  for (const raw of list) {
2073
- const request = truncate(String(raw ?? ''), 300).trim()
2418
+ /*
2419
+ * [2.2.6][T4] 对象安全序列化(缺陷二第二触点 W2):needs 条目可能是子
2420
+ * Agent 直接写的对象({"department","need","purpose"}),也可能是
2421
+ * readEvidenceNeeds 产出的结构化条目 {request, department}。request 一律
2422
+ * 经 needEntryText 取文本、department 经 needEntryDepartment 提取合法
2423
+ * 部门键——本函数不再有任何 String(对象) 分支,对象不再被写成
2424
+ * "[object Object]"、department 不再被丢弃。去重键仍是 request 文本。
2425
+ */
2426
+ const request = truncate(typeof raw === 'string' ? raw : needEntryText(raw), 300).trim()
2074
2427
  if (!request) continue
2428
+ const department = needEntryDepartment(raw)
2075
2429
  if (next.some((item) => item.request === request)) continue
2076
2430
  /*
2077
2431
  * [1.12.0][D-30] 容量溢出必须可审计,不能静默 `break`。
@@ -2087,7 +2441,7 @@ export function mergeHandoffsFromNeeds(current: any, needs: any, overflow: strin
2087
2441
  next.push({
2088
2442
  id: `H${next.length + 1}`,
2089
2443
  request,
2090
- department: null,
2444
+ department,
2091
2445
  status: 'open',
2092
2446
  response: null,
2093
2447
  at: Date.now(),
@@ -2113,11 +2467,28 @@ export function openHandoffs(status: any): any[] {
2113
2467
  */
2114
2468
  function readEvidenceOptions(value: any) {
2115
2469
  if (!Array.isArray(value)) return []
2470
+ // [2.2.6][T4] 同模式共犯(T1 W3):对象感知读取,消灭 String(对象) 分支。
2116
2471
  return value.slice(0, MAX_ESCALATION_OPTIONS)
2117
- .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
2472
+ .map((item: any) => truncate(needEntryText(item), 300))
2118
2473
  .filter(Boolean)
2119
2474
  }
2120
2475
 
2476
+ /**
2477
+ * [2.2.0][T3/O-2c] 用时回填字段(timeSpentMinutes / finalEstimateMinutes)
2478
+ * 的 advisory 读取器。
2479
+ *
2480
+ * 方案 §2.5:「时间字段纯 advisory:不参与可交付判定,不加拒绝码」;方案
2481
+ * §2.4 结果块契约「模板增加 timeSpentMinutes、finalEstimateMinutes 字段」。
2482
+ * 只在给出合法非负有限数值时以整数分钟透传;缺失/非法一律省略(返回
2483
+ * undefined、不占键名),不判不合规——字段本来就是可选的。
2484
+ */
2485
+ function readAdvisoryMinutes(value: any): number | undefined {
2486
+ if (value === undefined || value === null) return undefined
2487
+ const num = Number(value)
2488
+ if (!Number.isFinite(num) || num < 0) return undefined
2489
+ return Math.round(num)
2490
+ }
2491
+
2121
2492
  /**
2122
2493
  * [2.1.0] 顶层证据字段被误写进 `phases` 时,把它们提回顶层(用户 2026-11-05)。
2123
2494
  *
@@ -2344,7 +2715,42 @@ const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i
2344
2715
  * the acceptance table cannot drift apart between the runtime and the replay.
2345
2716
  * It never invents evidence and never upgrades a failed self-check to done.
2346
2717
  */
2347
- export function adjudicateResult({ output, strict = true, expectedAcceptance = [], requirePhases = true }: any) {
2718
+ /**
2719
+ * [2.2.0][T3/O-2c] `adjudicateResult` 的显式返回契约。
2720
+ *
2721
+ * 为什么不沿用结构化推断:7 个 payload 分支透传 `...advisoryTime` 之后,TS 对
2722
+ * 「spread + 多返回对象字面量」的联合归并会劣化(实测消费点 runtime.ts:1201
2723
+ * 一带 TS2339 × 8:把判别字段宽化成 string,`.question`/`.phases` 等既有访问
2724
+ * 全部失去收窄保护)。显式钉死契约后,既有消费面(status/question/phases/
2725
+ * options/blockedKind/commFormat* …)的可选性与类型不再随推断波动。
2726
+ *
2727
+ * 字段语义与 [1.11.0]-[2.1.0] 各分支保持一致;`timeSpentMinutes` /
2728
+ * `finalEstimateMinutes` 为 [2.2.0][T3/O-2c] 纯 advisory 可选字段(方案 §2.5
2729
+ * 「时间字段纯 advisory:不参与可交付判定」),缺失即省略。
2730
+ */
2731
+ export interface AdjudicateResult {
2732
+ status: 'done' | 'blocked'
2733
+ verification: string
2734
+ acceptance: any[]
2735
+ artifacts: any[]
2736
+ needs: any[]
2737
+ error: string | null
2738
+ question?: string
2739
+ options?: string[]
2740
+ phases?: any
2741
+ phaseSummary?: string | null
2742
+ blockedKind?: string
2743
+ commFormatViolations?: any[]
2744
+ commFormatRejection?: string
2745
+ /** [2.2.0][T3/O-2c] 实际耗时回填(整数分钟,advisory)。 */
2746
+ timeSpentMinutes?: number
2747
+ /** [2.2.0][T3/O-2c] 最终预估回填(整数分钟,advisory)。 */
2748
+ finalEstimateMinutes?: number
2749
+ /** 各版本分支的附加诊断字段经此放行(回放/新字段向前兼容)。 */
2750
+ [extra: string]: unknown
2751
+ }
2752
+
2753
+ export function adjudicateResult({ output, strict = true, expectedAcceptance = [], requirePhases = true }: any): AdjudicateResult {
2348
2754
  const text = typeof output === 'string' ? output : ''
2349
2755
  const parsed = parseEvidenceBlock(text)
2350
2756
  if (!strict) {
@@ -2427,8 +2833,25 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2427
2833
  const question = truncate(String(payload.question ?? ''), MAX_QUESTION_CHARS)
2428
2834
  const options = readEvidenceOptions(payload.options)
2429
2835
  const blockedReason = truncate(String(payload.blockedReason ?? payload.error ?? ''), 2000)
2836
+ /*
2837
+ * [2.2.0][T3/O-2c] 用时回填字段(方案 §2.2/§2.4:「模板增加
2838
+ * timeSpentMinutes、finalEstimateMinutes 字段」)。纯 advisory(方案 §2.5
2839
+ * 「时间字段纯 advisory:不参与可交付判定,不加拒绝码」):合法即整数分钟
2840
+ * 透传到判定结果的每一个 payload 分支,缺失/非法即省略(不占键名),既有
2841
+ * 字段与 F1-F9 零改动。
2842
+ */
2843
+ const timeSpentMinutes = readAdvisoryMinutes(payload.timeSpentMinutes)
2844
+ const finalEstimateMinutes = readAdvisoryMinutes(payload.finalEstimateMinutes)
2845
+ const advisoryTime: { timeSpentMinutes?: number; finalEstimateMinutes?: number } =
2846
+ timeSpentMinutes === undefined && finalEstimateMinutes === undefined
2847
+ ? {}
2848
+ : {
2849
+ ...(timeSpentMinutes === undefined ? {} : { timeSpentMinutes }),
2850
+ ...(finalEstimateMinutes === undefined ? {} : { finalEstimateMinutes }),
2851
+ }
2430
2852
  if (payload.status === 'blocked') {
2431
2853
  return {
2854
+ ...advisoryTime,
2432
2855
  status: 'blocked',
2433
2856
  verification: 'structured',
2434
2857
  acceptance,
@@ -2442,6 +2865,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2442
2865
  if (payload.status === 'partial') {
2443
2866
  const detail = truncate(String(payload.summary ?? payload.blockedReason ?? ''), 2000)
2444
2867
  return {
2868
+ ...advisoryTime,
2445
2869
  status: 'blocked',
2446
2870
  verification: 'structured',
2447
2871
  acceptance,
@@ -2455,6 +2879,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2455
2879
  const failed = acceptance.filter((item: any) => item.result === 'fail')
2456
2880
  if (failed.length > 0) {
2457
2881
  return {
2882
+ ...advisoryTime,
2458
2883
  status: 'blocked',
2459
2884
  verification: 'failed',
2460
2885
  acceptance,
@@ -2500,6 +2925,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2500
2925
  ? '(结果块 JSON 有语法错误,已修复;若 acceptance 位于错误点之后,会被一起裁掉)'
2501
2926
  : ''
2502
2927
  return {
2928
+ ...advisoryTime,
2503
2929
  status: 'blocked',
2504
2930
  verification: 'unverified',
2505
2931
  acceptance,
@@ -2524,6 +2950,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2524
2950
  : validatePhaseEvidence(payload.phases, expectedAcceptance)
2525
2951
  if (phaseCheck && !phaseCheck.ok) {
2526
2952
  return {
2953
+ ...advisoryTime,
2527
2954
  status: 'blocked',
2528
2955
  verification: 'unverified',
2529
2956
  acceptance,
@@ -2559,6 +2986,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2559
2986
  )
2560
2987
  if (!commFormat.compliant) {
2561
2988
  return {
2989
+ ...advisoryTime,
2562
2990
  status: 'blocked',
2563
2991
  verification: 'unverified',
2564
2992
  acceptance,
@@ -2574,6 +3002,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2574
3002
  }
2575
3003
  }
2576
3004
  return {
3005
+ ...advisoryTime,
2577
3006
  status: 'done',
2578
3007
  verification: hasUnverified ? 'unverified' : 'structured',
2579
3008
  acceptance,
@@ -2636,6 +3065,17 @@ export function buildUpdateMessage(update: any) {
2636
3065
  ...(update.instructionOverdue === undefined ? {} : { instructionOverdue: update.instructionOverdue }),
2637
3066
  ...(update.handoffs === undefined ? {} : { handoffs: update.handoffs }),
2638
3067
  ...(update.reportedAt === undefined ? {} : { reportedAt: update.reportedAt }),
3068
+ /*
3069
+ * [2.2.0][T3/O-3c] 协商上限持久化臂(方案 §1③ O-3c:「专家预告(O-2a)经
3070
+ * 主 Agent 确认后写入 timeoutMs(经 dsh_workplan_update 新字段或计划消息)」)。
3071
+ *
3072
+ * 主 Agent 把确认后的 timeoutMs 随改判/进度更新记录留档,刷新/重启后按同
3073
+ * 顺序回放(回放侧 update 载荷的字段透传白名单在 src/runtime.ts:2931,属
3074
+ * T4 接线范围;applyStatus 侧已接受该字段);缺省合法(undefined 跳过,
3075
+ * 不改 2.1.x 语义)。计划内该字段的读取/派生见 readSubtasks +
3076
+ * deriveSubtaskTimeoutMs。
3077
+ */
3078
+ ...(update.timeoutMs === undefined ? {} : { timeoutMs: update.timeoutMs }),
2639
3079
  ...(update.revision === undefined ? {} : { revision: update.revision }),
2640
3080
  at: update.at ?? Date.now(),
2641
3081
  }
@@ -2751,6 +3191,20 @@ export function applyResultStatuses(statuses: any, result: any) {
2751
3191
  const replayedClosure = entry.status === 'done' && entry.closure === undefined
2752
3192
  ? 'reported'
2753
3193
  : entry.closure
3194
+ /*
3195
+ * [2.2.1][T5][F1] 回放容错:结果载荷里的通道字段可能是 null / 非法值
3196
+ * (旧版本遗留、人工改日志、或早期重建写回的脏值)。applyStatus 是写入
3197
+ * 单点校验,遇到非法值会整条抛错,被下面的 catch 吞掉后这一行的
3198
+ * done / summary / verification / acceptance 全都不落地 —— 一条完成行
3199
+ * 回放成 pending 的假阴性(T4 残余项复核 A2/B2 实测)。
3200
+ *
3201
+ * 这里在进入 patch 之前判定:只有能通过校验的值才参与回放,null / 非法值
3202
+ * 按「字段缺失」处理。applyStatus 的 fail-closed 校验保持不变(其它写入方
3203
+ * 仍然不能写脏值),本改动只影响「读旧日志」这一侧。
3204
+ */
3205
+ const replayedNoticeChannel = entry.noticeChannel !== undefined && validateNoticeChannel(entry.noticeChannel).ok
3206
+ ? entry.noticeChannel
3207
+ : undefined
2754
3208
  try {
2755
3209
  next = applyStatus(next, entry.subtaskId, {
2756
3210
  status: entry.status,
@@ -2782,6 +3236,16 @@ export function applyResultStatuses(statuses: any, result: any) {
2782
3236
  instructionSeq: entry.instructionSeq,
2783
3237
  instructionOverdue: entry.instructionOverdue,
2784
3238
  reportedAt: entry.reportedAt,
3239
+ // [2.2.0][T3/O-2c/O-3c] 柔性时长协商留档字段随结果快照回放(方案 §2.5
3240
+ // 「旧消息回放零改动读取」:字段缺失时 applyStatus 分支自动跳过)。
3241
+ timeSpentMinutes: entry.timeSpentMinutes,
3242
+ finalEstimateMinutes: entry.finalEstimateMinutes,
3243
+ timeoutMs: entry.timeoutMs,
3244
+ // [2.2.0][T3/O-2a] 子→主预告通道结论必须随结果快照回放;写入由
3245
+ // applyStatus 单点校验,非法值在 catch 中 fail-closed(不落脏值)。
3246
+ // [2.2.1][T5][F1] 但非法值只能丢「这个字段」,不能丢「整条结果行」:
3247
+ // 上面的 replayedNoticeChannel 已把 null / 非法值归一为 undefined。
3248
+ noticeChannel: replayedNoticeChannel,
2785
3249
  // [1.11.0] 回报证据与重规划留档必须随结果快照回放(T7 C-06/C-11)。
2786
3250
  report: entry.report,
2787
3251
  replannedReason: entry.replannedReason,
@@ -2905,6 +3369,45 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
2905
3369
  next.instructionSeq = Number.isInteger(Number(patch.instructionSeq)) ? Number(patch.instructionSeq) : null
2906
3370
  }
2907
3371
  if (patch.reportedAt !== undefined) next.reportedAt = numberOrNull(patch.reportedAt)
3372
+ /*
3373
+ * [2.2.0][T3/O-2c/O-3c] 柔性时长协商的留档字段(方案 §2.2/§2.4/§2.5)。
3374
+ *
3375
+ * timeSpentMinutes/finalEstimateMinutes 是结果块回填的实际耗时与收尾预估
3376
+ * (纯 advisory:缺失或非法不判不合规,按缺省处理;不参与可交付判定,
3377
+ * 方案 §2.5「时间字段纯 advisory:不参与可交付判定,不加拒绝码」);
3378
+ * timeoutMs 是 O-3c「预告经主 Agent 确认后写入」的协商上限留档,校验与
3379
+ * readSubtasks 同口径(正数毫秒;null 表示清除)。三者只写同一条状态条目,
3380
+ * 走 StatusEntry 未知字段保留通道,旧消息回放零改动。
3381
+ */
3382
+ if (patch.timeSpentMinutes !== undefined) {
3383
+ next.timeSpentMinutes = readAdvisoryMinutes(patch.timeSpentMinutes) ?? null
3384
+ }
3385
+ if (patch.finalEstimateMinutes !== undefined) {
3386
+ next.finalEstimateMinutes = readAdvisoryMinutes(patch.finalEstimateMinutes) ?? null
3387
+ }
3388
+ if (patch.timeoutMs !== undefined) {
3389
+ if (patch.timeoutMs === null) next.timeoutMs = null
3390
+ else {
3391
+ const value = Number(patch.timeoutMs)
3392
+ if (!Number.isFinite(value) || value <= 0) {
3393
+ throw new PlanError('timeoutMs 必须是正数毫秒(协商上限)', 'INVALID_TIMEOUT_MS')
3394
+ }
3395
+ next.timeoutMs = value
3396
+ }
3397
+ }
3398
+ /*
3399
+ * [2.2.0][T3/O-2a] 子→主预告通道的可观测条目(方案 §2.4 状态行字段)。
3400
+ *
3401
+ * 这条字段存在的理由就是「不静默丢失」:旧实现里预告发不出去,主 Agent
3402
+ * 只能从子 Agent 的自述里猜,计划记录上没有任何痕迹。现在通道的
3403
+ * target / caller / at / observedAt / reason 全部落在状态行,写入前统一
3404
+ * 校验(未知状态或未知原因直接拒绝),回放与刷新都不会丢。
3405
+ */
3406
+ if (patch.noticeChannel !== undefined) {
3407
+ const checked = validateNoticeChannel(patch.noticeChannel)
3408
+ if (!checked.ok) throw new PlanError(`非法 noticeChannel:${checked.error}`, 'INVALID_NOTICE_CHANNEL')
3409
+ next.noticeChannel = checked.value
3410
+ }
2908
3411
  /*
2909
3412
  * [1.11.0] 完成回报与重规划的留档字段(T7 C-06/C-11)。
2910
3413
  *
@@ -4147,7 +4650,22 @@ export function buildChildPrompt({
4147
4650
  statuses = null,
4148
4651
  previousFailure = null,
4149
4652
  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 = '',
4662
+ leadAgentIdSource = 'none',
4150
4663
  }: any) {
4664
+ const noticeTarget = readLeadAgentId(leadAgentId)
4665
+ const noticeCall = leadNoticeCallForm(noticeTarget)
4666
+ const noticeTargetLine = noticeTarget
4667
+ ? `- 目标会话 id(**由插件注入,唯一合法目标**):\`${noticeTarget}\`(来源:${leadAgentIdSource || 'unknown'})。它就是本轮主 Agent 的会话 id,宿主的父子血缘校验只认它。`
4668
+ : `- **本提示词没有注入父会话 id**(来源:${leadAgentIdSource || 'none'}):禁止猜测、禁止自行拼一个 id。跳过 send_message 预告,改为在结果块首行写 \`noticeChannel: {"target":"${NOTICE_TARGET_MISSING_TEXT}","at":<毫秒时间戳>,"error":"LEAD_ID_MISSING"}\`——供主 Agent 阅读;**插件不解析这一行**,通道结论以状态行观测为准。`
4151
4669
  /*
4152
4670
  * Every field below is read defensively.
4153
4671
  *
@@ -4282,6 +4800,7 @@ export function buildChildPrompt({
4282
4800
  */
4283
4801
  return defuseSessionReferenceText([
4284
4802
  `你是「${departmentLabel(subtask.department)}」部门的执行 Agent,只负责下面这一个子任务。`,
4803
+ `专家定位:${DEPARTMENT_EXPERT_STANDARD.child}`,
4285
4804
  '',
4286
4805
  `全局任务:${understanding.originalRequest ?? '(未记录)'}`,
4287
4806
  `最终交付物:${understanding.deliverable ?? '(未记录)'}`,
@@ -4318,6 +4837,7 @@ export function buildChildPrompt({
4318
4837
  : []),
4319
4838
  '',
4320
4839
  '执行要求:',
4840
+ '- 以全球顶尖专家标准执行:先诊断根因再动手,产出与证据要能通过同行复核,不交浅层补丁、不遗留问题。',
4321
4841
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',
4322
4842
  '- 你没有派发权限,也不能重启或安装任何服务;遇到这类步骤,必须先上报(见下方「遇阻上报」),再停止推进等待指示,不要空转。',
4323
4843
  '- 不得编造事实、文件、命令结果或证据;无法确认时明确写“未验证”。',
@@ -4327,6 +4847,30 @@ export function buildChildPrompt({
4327
4847
  '- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,并按下方「遇阻上报」给出 question。',
4328
4848
  '- 完成后用简洁中文汇报:做了什么、证据/文件、验收结果、遗留问题。',
4329
4849
  '',
4850
+ /*
4851
+ * [2.2.0][T3/O-2a] 柔性时长协商协议(方案 §2.6 #3:「开工前预告、超预期
4852
+ * 预警、完成即回报」;O-1a①+O-2a+O-4a 合并一段,矩阵 Z1 三条款一次插入)。
4853
+ * 时间是协商出来的安全兜底,不是固定交付期限(方案 §0/§3.2)。
4854
+ *
4855
+ * 2026-11-08 修复(真实环境复现 `subagent "lead" is unavailable`):
4856
+ * 旧文案写的是 `send_message(target: "lead")`——字段名与宿主 schema
4857
+ * 不一致(宿主只有 `agent_id`),值 `"lead"` 也不是任何会话 id,于是
4858
+ * 预告在目标解析阶段必然失败。现在改为:注入真实父会话 id + 用宿主
4859
+ * 契约里的字段名 + 明确失败后的确定性重试与留痕,不再有「猜目标」的余地。
4860
+ */
4861
+ '柔性时长协商协议(不设固定完成时间;时间是协商出来的安全兜底,不是固定交付期限):',
4862
+ noticeTargetLine,
4863
+ `- 开工前先报预估时长(预计完成本子任务要多久就报多久):用 \`${noticeCall}\` 报预估完成时长,新预估覆盖旧预估;预估仅供参考、非承诺,实际时长协商决定。`,
4864
+ `- 发现预计将超预估时,立即用同一个目标报新预估并申请延期(说明还要多久、为什么),不要等超时才预警。`,
4865
+ `- 完成即回报:用同一个目标报核心结论(做了什么、证据/文件、验收结果),不要等整轮结束。`,
4866
+ ...(noticeTarget
4867
+ ? [
4868
+ '- 失败后的确定性处理(禁止静默丢弃):`send_message` 若返回错误(`is unavailable` / `UNAUTHORIZED` / 工具不存在),先在汇报首行原样记录 `noticeChannel: {"target":"' + noticeTarget + '","at":<毫秒时间戳>,"error":"<错误原文>"}`,再用**同一个** agent_id 重试一次;仍失败就继续把子任务做完,把这条记录留在结果里(供主 Agent 阅读;插件不解析这一行,通道结论以状态行观测为准)。**不得改用其它目标,也不得向任何非本轮父会话发送**——那是越权发送,会触发宿主 lineage 拒绝。',
4869
+ ]
4870
+ : []),
4871
+ // [T3 扩展点·T6] 供 T6 在此行之后追加「完成即时通知」条款(O-1a 插件兜底通道语义);上方三条款为 O-1a①+O-2a+O-4a 合并协议段(矩阵 Z1),既有条款不得删改。
4872
+ // [2.2.0][T6/O-1a] 完成即时通知条款(插件兜底通道):完成即报是第一通道(见上方「完成即回报」);插件另设兜底——子任务结算成功后立即向主会话推送一条含子任务 ID、摘要、验收计数与用时的即时通知,不等待整轮结束。兜底不替代主动回报。
4873
+ '',
4330
4874
  '遇阻上报(强制,先于继续动作):',
4331
4875
  '- 出现以下任一情况,第一动作是上报,不是猜测、绕过或静默继续:缺少权限/输入/依赖产物;需求自相矛盾;无法验证;同一命令连续两次失败;需要主 Agent 决定方向。',
4332
4876
  '- 优先调用工具:`dsh_workplan_escalate({ "subtaskId": "<你的子任务 ID>", "question": "需要主 Agent 回答的单个问题", "options": ["可选项 A", "可选项 B"], "needs": ["需要谁提供什么"] })`。调用成功后停止推进,只做只读核对。',
@@ -4336,13 +4880,20 @@ export function buildChildPrompt({
4336
4880
  '',
4337
4881
  '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
4338
4882
  EVIDENCE_MARKER_BEGIN,
4339
- '{"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":[]}',
4883
+ '{"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}',
4340
4884
  EVIDENCE_MARKER_END,
4341
4885
  '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
4342
4886
  '- acceptance 必须逐条覆盖上面的验收标准:criterion 以 A1、A2… 开头对号入座(编号不可省略);result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
4343
4887
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
4344
4888
  '- needs 写需要其他部门配合的事项,每条写清「哪个部门 + 需要什么 + 用来做什么」;它会被登记为待处理需求,主 Agent 必须处置后计划才能交付。不要直连其他子 Agent。',
4345
4889
  '- question/options 只在受阻上报时填写;done 时保持空字符串/空数组。',
4890
+ /*
4891
+ * [2.2.0][T3/O-2c] 用时回填字段(方案 §2.2/§2.4 结果块契约:「模板增加
4892
+ * timeSpentMinutes、finalEstimateMinutes 字段」)。纯 advisory:F1-F9 与
4893
+ * 既有字段零改动,缺失/非法即省略,不判不合规、不影响验收判定(方案 §2.5
4894
+ * 「时间字段纯 advisory」)。
4895
+ */
4896
+ '- timeSpentMinutes / finalEstimateMinutes(可选,整数分钟):完成后把实际耗时与最终预估回填进结果块,未知可省略;两项仅供参考与协商审计,不影响验收判定。',
4346
4897
  '- 整块不超过 12000 字符;不要把这段模板本身抄进结果块。',
4347
4898
  '',
4348
4899
  /*