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/src/plan.ts CHANGED
@@ -13,6 +13,12 @@ import { DEPARTMENT_CAPABILITIES, DEPARTMENT_EXPERT_STANDARD, departmentCapabili
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,25 @@ 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
+ * [2.2.7][T2/五档] 白名单由三档(low / high / max)扩展为五档
198
+ * (low / medium / high / xhigh / max)。唯二事实源:本常量与 client.ts 的
199
+ * UI Pill 内联数组,二者必须同步;本文件校验、runtime.ts env 校验(L775)
200
+ * 与派发透传(L1910)三处均由本常量驱动,改一处全链生效。旧三档值是五档
201
+ * 的子集,旧计划序列化/回放/派发零迁移。
202
+ *
203
+ * 用户规则原文(五档版):「禁止子agent继承主agent的推理等级。其中,轻度
204
+ * 复杂的任务必须使用low,中等复杂的任务必须使用medium或high,非常复杂的
205
+ * 任务必须使用xhigh或max。主agent和子agent必须分别根据自己要执行的任务的
206
+ * 复杂度,分别自己判断使用哪个推理等级,推理等级包括low、medium、high、
207
+ * xhigh或max。」
208
+ * 子任务未声明该字段时回落 high(中等档默认,D1 决策保持;缺失合法语义
209
+ * 不变);执行侧绝不读取主 Agent 的等级。
210
+ */
211
+ export const REASONING_EFFORTS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max'])
212
+ export const DEFAULT_REASONING_EFFORT = 'high'
213
+
189
214
  export const DEPARTMENTS = Object.freeze({
190
215
  engineering: { zh: '工程研发', en: 'Engineering' },
191
216
  research: { zh: '研究分析', en: 'Research' },
@@ -668,6 +693,63 @@ function readSubtasks(value: any, stageIndex: any, errors: any) {
668
693
  if (!DEPARTMENTS[department as keyof typeof DEPARTMENTS]) {
669
694
  push(errors, `${base}.department`, `必须是 ${DEPARTMENT_IDS.join(' / ')} 之一`)
670
695
  }
696
+ /*
697
+ * [2.2.0][T3/O-2b] 预估区间改判:1-240 整数,越界拒绝、区间内原样保留。
698
+ *
699
+ * 方案原文(docs/dsh-workplan_优化方案_20261107.md):
700
+ * - §2.2「estimateMinutes 钳制放宽为 1–240 整数(仅防离谱值,advisory 不变)」;
701
+ * - §1⑤ O-5c「固定区间去钳制:同 O-2b」;
702
+ * - §1② B2「estimateMinutes: 90 的计划通过校验且原样保留(不再被钳成 15)」。
703
+ * 「去钳制 + 原样保留 + 仅防离谱值」的唯一自洽合成:合法区间内不再改写值,
704
+ * 0/241 等离谱值**拒绝**并点名字段(不是钳成 1/240 蒙混通过)——与同源用例
705
+ * tests/time-estimate-negotiation.test.ts(0 与 241 被拒、1/90/240 原样保留)一致。
706
+ * 可选与缺省合法的宽容面保留(旧计划零回归,验收 ②B4):没有 estimateMinutes
707
+ * 的计划照旧通过校验。歧义链与 Z8 红线取舍见
708
+ * docs/dsh-workplan_T3_plan改动说明_20261107.md。
709
+ */
710
+ const hasEstimate = source.estimateMinutes !== undefined && source.estimateMinutes !== null
711
+ const estimateValue = hasEstimate ? Number(source.estimateMinutes) : NaN
712
+ const estimateOk = hasEstimate
713
+ && typeof source.estimateMinutes === 'number'
714
+ && Number.isInteger(estimateValue)
715
+ && estimateValue >= 1
716
+ && estimateValue <= 240
717
+ if (hasEstimate && !estimateOk) {
718
+ push(errors, `${base}.estimateMinutes`, '必须是 1-240 的整数(仅防离谱值:越界或非整数拒绝、不改写;该字段可选,缺失合法)')
719
+ }
720
+ /*
721
+ * [2.2.0][T3/O-3a] per-subtask 协商上限(timeoutMs,毫秒)可选透传。
722
+ *
723
+ * 方案 §2.2:「timeoutMs(可选)|本子任务的协商上限;缺省由 estimateMinutes
724
+ * × 2.0 派生并钳制|readSubtasks + validatePlan 只校验类型与范围,缺省合法」。
725
+ * 原样透传、不在此处钳到 MAX(同源用例 tests/time-estimate-negotiation.test.ts
726
+ * 固化 timeoutMs: 3600000 原样保留);只校验类型与范围:正数毫秒,缺失合法。
727
+ * 范围上界方案未给定(未知/待核实,见改动说明歧义点 3)。
728
+ */
729
+ const hasTimeout = source.timeoutMs !== undefined && source.timeoutMs !== null
730
+ const timeoutValue = hasTimeout ? Number(source.timeoutMs) : NaN
731
+ const timeoutOk = hasTimeout
732
+ && typeof source.timeoutMs === 'number'
733
+ && Number.isFinite(timeoutValue)
734
+ && timeoutValue > 0
735
+ if (hasTimeout && !timeoutOk) {
736
+ push(errors, `${base}.timeoutMs`, '必须是正数毫秒(协商上限,可选字段,缺失合法)')
737
+ }
738
+ /*
739
+ * [2.2.0][T13/推理等级] 子任务自带的推理等级(可选,仅 low / medium / high / xhigh / max)。
740
+ *
741
+ * 用户规则原文见 REASONING_EFFORTS 上方注释。语义与 estimateMinutes 同风格:
742
+ * 缺失合法(旧计划/回放零回归),但非法值**拒绝**并点名字段,不静默改写成
743
+ * 其它档位;执行侧对缺失值回落 DEFAULT_REASONING_EFFORT(high),绝不继承
744
+ * 主 Agent 的等级。
745
+ */
746
+ const hasEffort = source.reasoningEffort !== undefined && source.reasoningEffort !== null
747
+ const effortOk = hasEffort
748
+ && typeof source.reasoningEffort === 'string'
749
+ && REASONING_EFFORTS.includes(source.reasoningEffort)
750
+ if (hasEffort && !effortOk) {
751
+ push(errors, `${base}.reasoningEffort`, '必须是 low / medium / high / xhigh / max 之一(可选字段,缺失时回落 high;非法值拒绝,不改写)')
752
+ }
671
753
  return {
672
754
  id: readString(source.id, `${base}.id`, 1, 16, errors),
673
755
  title: readString(source.title, `${base}.title`, 1, 200, errors),
@@ -701,14 +783,48 @@ function readSubtasks(value: any, stageIndex: any, errors: any) {
701
783
  * [1.7.0] Optional time estimate, advisory only. Validation never fails on
702
784
  * a missing or out-of-range value: a plan that cannot be dispatched is
703
785
  * worse than one carrying a rough estimate.
786
+ * [2.2.0][T3/O-2b] 语义演进(上方校验块注释引方案原文):缺省仍然合法;
787
+ * 越界自 2.2.0 起拒绝而非钳制(§1⑤ O-5c 固定区间去钳制),本注释保留为
788
+ * [1.7.0] 历史记录。
704
789
  */
705
- ...(Number.isFinite(Number(source.estimateMinutes))
706
- ? { estimateMinutes: Math.min(15, Math.max(1, Math.round(Number(source.estimateMinutes)))) }
707
- : {}),
790
+ ...(estimateOk ? { estimateMinutes: estimateValue } : {}),
791
+ ...(timeoutOk ? { timeoutMs: timeoutValue } : {}),
792
+ // [2.2.7][T4/五档] 缺省回落保持 high(DEFAULT_REASONING_EFFORT,D1 决策):
793
+ // 白名单由三档扩为五档(low / medium / high / xhigh / max)后,high 仍是
794
+ // 缺失时的默认档——high 属「中等复杂」区间,向后兼容旧三档计划与回放,
795
+ // 零迁移;非法值已在上方校验块拒绝,不会静默改写。
796
+ reasoningEffort: effortOk ? String(source.reasoningEffort) : DEFAULT_REASONING_EFFORT,
708
797
  }
709
798
  })
710
799
  }
711
800
 
801
+ /**
802
+ * [2.2.0][T3/O-3a] per-subtask 协商上限(negotiated ceiling)派生公式。
803
+ *
804
+ * 方案 §1③ O-3a:「缺省时由预估派生:协商上限 = clamp(预估分钟 × 安全系数
805
+ * (建议 2.0), 全局下限, 单次绝对上限)」;§2.2 timeoutMs 行:「缺省由
806
+ * `estimateMinutes × 2.0` 派生并钳制」。分钟→毫秒按 ×60000 换算(同源用例
807
+ * tests/time-estimate-negotiation.test.ts 的 expected 公式逐字一致)。
808
+ *
809
+ * 消费序(O-3b 接线契约,runtime 侧):显式 subtask.timeoutMs(O-3c:预告经
810
+ * 主 Agent 确认后写入,原样透传)→ 缺省调用本函数派生(钳在 [minMs, maxMs],
811
+ * 验收 ③C3)→ 两者皆无(旧计划无 estimateMinutes 也无 timeoutMs)返回
812
+ * undefined,消费侧回落原行为(normaliseChildTimeout 全局兜底,验收 ③C2)。
813
+ * 本函数只做「预估→派生值」纯换算,不读 subtask 对象。
814
+ *
815
+ * MIN_CHILD_TIMEOUT_MS=1,000 毫秒不变(与 src/runtime.ts:220 现状同值)。
816
+ * MAX_CHILD_TIMEOUT_MS=7,200,000 毫秒(120 分钟)=plan.ts 侧派生上限——
817
+ * 【用户 2026-11-07 决断】方案 §6 未知第 4 条已由用户拍板上调;runtime.ts:221
818
+ * 常量本体由 T4 波次同步改(改前两处不同值时以本决断为准)。
819
+ * plan.ts 被 runtime.ts 反向依赖(runtime.ts import './plan.js'),不能反向
820
+ * import,故此处带默认值、调用方可传入权威常量。
821
+ */
822
+ export function deriveSubtaskTimeoutMs(estimateMinutes: any, minMs = 1000, maxMs = 7200000): number | undefined {
823
+ const estimate = Number(estimateMinutes)
824
+ if (!Number.isFinite(estimate) || estimate <= 0) return undefined
825
+ return Math.min(maxMs, Math.max(minMs, estimate * 2.0 * 60_000))
826
+ }
827
+
712
828
  function readStages(value: any, errors: any) {
713
829
  if (!Array.isArray(value)) {
714
830
  push(errors, 'stages', '必须是数组')
@@ -1103,7 +1219,10 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1103
1219
  const departments = DEPARTMENT_CAPABILITIES
1104
1220
  .map((entry) => `- ${entry.id}(${entry.zh} / ${entry.en}):职责 ${entry.responsibilities.join(';')};典型产物 ${entry.outputs.join(';')}`)
1105
1221
  .join('\n')
1106
- const totalMinutes = Math.max(1, Math.round(Number(budget?.totalMinutes) || 20))
1222
+ const rawTotalMinutes = Number(budget?.totalMinutes)
1223
+ const totalMinutes = Number.isFinite(rawTotalMinutes) && rawTotalMinutes > 0
1224
+ ? Math.max(1, Math.round(rawTotalMinutes))
1225
+ : 0
1107
1226
  const childMinutes = Math.max(1, Math.round(Number(budget?.childMinutes) || 15))
1108
1227
  const concurrency = Math.max(1, Number(budget?.concurrency) || MAX_CONCURRENT)
1109
1228
  const resumes = Number.isFinite(Number(budget?.maxResumes)) ? Number(budget.maxResumes) : MAX_PLAN_RESUMES
@@ -1140,13 +1259,31 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1140
1259
  '- unknowns 和 assumptions 必须如实列出;没有就写空数组,不能把假设写成事实。',
1141
1260
  '- 子任务必须可独立执行、可验收;不要为了凑数拆无意义任务。',
1142
1261
  '- 子任务由子 Agent 独立执行:它们没有派发权限、不能重启服务、不能安装或升级依赖。禁止把「调用 dsh_workplan_dispatch」「重启/停止 dsh web」「安装或升级插件」这类只有主 Agent 才能执行的动作写进子任务;确实需要时,写成“给出结论或建议,由主 Agent 执行”。',
1143
- '- 单个子任务应能在 10 分钟内完成;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1262
+ '- 单个子任务无须在 10 分钟内完成——10 分钟只是拆步规模建议,不是完成期限、也不构成承诺;实际时长由执行专家开工预告协商决定,不设固定完成时间;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1144
1263
  '- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
1145
1264
  '',
1146
1265
  '本轮时间预算(硬事实,请据此规划规模):',
1147
- `- 一轮总预算约 ${totalMinutes} 分钟;单个子任务上限 ${childMinutes} 分钟;同时最多 ${concurrency} 个子任务并行。`,
1148
- `- 受阻后自动续跑额度 ${resumes} 次;总工作量超过一轮预算时,计划会被暂停并在下一轮继续。`,
1149
- '- 每个子任务必须写 estimateMinutes(整数 1-15):你预估它需要多少分钟。宁可估高,不要估低。',
1266
+ totalMinutes > 0
1267
+ ? `- 一轮总预算约 ${totalMinutes} 分钟(安全兜底,不是交付期限);单个子任务规模参考 ${childMinutes} 分钟量级(仅供参考、非承诺,实际时长由执行专家开工预告协商决定);同时最多 ${concurrency} 个子任务并行。`
1268
+ : `- 本轮不设固定总预算;单个子任务按自身 estimateMinutes 与协商截止/延期执行;同时最多 ${concurrency} 个子任务并行。`,
1269
+ resumes > 0
1270
+ ? `- 受阻后自动续跑额度 ${resumes} 次;需要时计划会暂停并在下一轮继续。`
1271
+ : '- 自动续跑额度为 0;计划不会因轮次预算被暂停。',
1272
+ '- 每个子任务必须写 estimateMinutes(整数 1-240,宁可估高):你预估它需要多少分钟。宁可估高,不要估低。取值必须是整数,越界或非整数会被校验拒绝(仅防离谱值),缺失不报错。',
1273
+ /*
1274
+ * [2.2.0][T13/推理等级] 子 Agent 必须自决推理等级,禁止继承主 Agent。
1275
+ * 用户规则原文见 plan.ts 顶部 REASONING_EFFORTS 注释;五档映射与五个示例
1276
+ * 按用户规则逐字展开,规划器输出由 readSubtasks 校验(只收
1277
+ * low/medium/high/xhigh/max)。
1278
+ * [2.2.7][T3/五档扩展] 中等="medium"或"high"、非常="xhigh"或"max" 是 OR 语义,
1279
+ * 二选一必须有确定性判据,否则同一输入会产生不同档位——下面逐字加入
1280
+ * 「同等复杂度优先较低档」消歧指令;提示词行与 tests/reasoning-effort.test.ts
1281
+ * 的契约正则逐字耦合,改任一必须同步改另一。
1282
+ */
1283
+ '- 每个子任务必须按它自身的复杂度写 reasoningEffort(推理等级,只允许 low / medium / high / xhigh / max 五档):轻度复杂="low",中等复杂="medium"或"high",非常复杂="xhigh"或"max"。',
1284
+ '- 档位二选一消歧(硬性要求,保证同等输入产生稳定档位):同等复杂度下优先选择较低档(medium 优先于 high,xhigh 优先于 max),除非有明确理由需较高档(如需要自建测试并跑回归、涉及多文件/多子系统共享状态、需要全链路原子性同步);没有明确理由不得升高档位,也不得无理由降低档位。',
1285
+ '- reasoningEffort 五档示例:整理并校对一份已有清单="low";补充单个工具函数并补齐单元测试="medium";独立实现一个模块并补齐测试="high";跨多个模块排查根因并修复="xhigh";跨多个系统排查根因并给出架构级修复方案="max"。',
1286
+ '- 禁止沿用/继承主 Agent 的推理等级:reasoningEffort 只由该子任务自身的复杂度决定,不得因为主 Agent 当前是某一档就照抄;缺失时执行侧回落 "high",但你必须显式写出该字段。',
1150
1287
  '- 规模大就如实拆成多轮,不要为了塞进一轮而把多个交付物压进一个子任务。',
1151
1288
  '',
1152
1289
  '可用部门(每个部门的执行者都是来自全球相关领域的顶尖专家,不是普通部门人员):',
@@ -1205,7 +1342,8 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1205
1342
  ' "dependsOn": [],',
1206
1343
  ' "acceptance": ["可测试的验收标准"],',
1207
1344
  ' "risk": "主要风险",',
1208
- ' "estimateMinutes": 5',
1345
+ ' "estimateMinutes": 5,',
1346
+ ' "reasoningEffort": "high"',
1209
1347
  ' }',
1210
1348
  ' ]',
1211
1349
  ' }',
@@ -1241,6 +1379,122 @@ export function makeUserMessage(text: any, source: any) {
1241
1379
  }
1242
1380
  }
1243
1381
 
1382
+ /**
1383
+ * [2.2.1] Validate the exact payload shape DSH requires for a `user/message`
1384
+ * event before it reaches the append-only log.
1385
+ *
1386
+ * Incident it prevents (2026-11-08, session-a404d49d…): the plugin appended
1387
+ * plain strings as `user/message` data. `Session.append()` only validates
1388
+ * payloads that are records, so the strings were persisted; on replay the
1389
+ * `goal` projection read `event.data.source.kind` and threw
1390
+ * "Cannot read properties of undefined (reading 'kind')", which surfaced as
1391
+ * "历史加载失败 / failed to project session". A malformed event is
1392
+ * unrecoverable once appended, so rejection must happen here, before append.
1393
+ */
1394
+ function userMessageShapeProblem(message: any): string | null {
1395
+ if (!isRecord(message)) return 'payload must be a plain object'
1396
+ if (typeof message.id !== 'string' || message.id.length === 0) return 'missing message id'
1397
+ if (message.role !== 'user') return 'role must be "user"'
1398
+ if (!Array.isArray(message.content) || message.content.length === 0) return 'content must be a non-empty array'
1399
+ if (!isRecord(message.source)) return 'missing source'
1400
+ if (typeof message.source.kind !== 'string' || message.source.kind.length === 0) return 'missing source.kind'
1401
+ return null
1402
+ }
1403
+
1404
+ /**
1405
+ * [2.2.1] The single approved writer for `user/message` events in this plugin.
1406
+ *
1407
+ * A raw string is wrapped into a complete DSH `UserMessage` (stable id, role,
1408
+ * text content, source with a nonempty `kind`); an already-built message is
1409
+ * shape-checked. Either way a malformed payload throws BEFORE `session.append`,
1410
+ * so a bad notice can never corrupt a session log again. All appends use
1411
+ * `surfaceOp: 'append'`, matching the previous call sites.
1412
+ */
1413
+ export function appendUserMessage(session: any, payload: any, source?: any) {
1414
+ if (!session || typeof session.append !== 'function') return undefined
1415
+ let message = payload
1416
+ if (typeof payload === 'string') {
1417
+ const summary = truncate(String(payload).replace(/\s+/g, ' ').trim() || '(无摘要)', 120)
1418
+ message = makeUserMessage(payload, source ?? { kind: 'workplan', form: 'notice', summary })
1419
+ }
1420
+ const problem = userMessageShapeProblem(message)
1421
+ if (problem !== null) throw new Error(`dsh-workplan: refusing to append malformed user/message (${problem})`)
1422
+ return session.append('user/message', message, { surfaceOp: 'append' })
1423
+ }
1424
+
1425
+ /*
1426
+ * [2.2.5][T5] 分解期间进度文案与回报器(T3 交互规范 §3 C2/C3、§4 频率规则)。
1427
+ *
1428
+ * 缺陷:runPlanner 全程(最长 3 次尝试 × 300s 窗口 + 退避)插件既不写会话
1429
+ * 消息也不放内存记录(T1 断点层判定=未发出),用户无法区分「正在重试」与
1430
+ * 「卡死」。本组函数只负责「把一次失败尝试翻译成用户能看懂的两句话」:
1431
+ * - cardLine:通道 A(侧栏占位卡片的 errors 区,4 秒轮询可见,保底通道);
1432
+ * - notice:通道 B(appendUserMessage 聊天通知,仅「会退避重试」的失败才
1433
+ * 发,每轮至多 2 条——第 3 次失败直接进降级文案,不再叠加通知)。
1434
+ * 文案硬规则(T3 §3):真因链截断 ≤120 字符(错误码原样保留,供用户报障);
1435
+ * 分母 3 由 maxAttempts 参数注入,不在文案里硬编码;等待时长按实际退避
1436
+ * 四舍五入到秒;aborted 由调用方(回报器)静默,本函数不涉及。
1437
+ */
1438
+ export function plannerProgressLines(report: any, maxAttempts: number) {
1439
+ const attempt = Number(report?.attempt) || 0
1440
+ const outcome = String(report?.outcome ?? 'PLANNER_ERROR')
1441
+ const causes = Array.isArray(report?.lastErrors) ? report.lastErrors : []
1442
+ const cause = truncate(causes.join(';').replace(/\s+/g, ' ').trim(), 120)
1443
+ if (attempt <= 0 || !cause) return { cardLine: '', notice: null }
1444
+ const terminal = report?.terminal === true
1445
+ const backoffMs = Number(report?.retryBackoffMs) || 0
1446
+ const total = Number(maxAttempts) || attempt
1447
+ const willRetry = !terminal && backoffMs > 0 && attempt < total
1448
+ const waitSecs = Math.max(1, Math.round(backoffMs / 1000))
1449
+ const prefix = `第 ${attempt} 次尝试失败(${outcome}):${cause}`
1450
+ const cardLine = willRetry
1451
+ ? `${prefix};正在重试(约 ${waitSecs} 秒后),第 ${attempt + 1}/${total} 次`
1452
+ : backoffMs > 0
1453
+ ? `${prefix};正在重试`
1454
+ : `${prefix}`
1455
+ const notice = willRetry
1456
+ ? `【自动分解】第 ${attempt} 次尝试失败:${cause};正在重试(约 ${waitSecs} 秒后),第 ${attempt + 1}/${total} 次`
1457
+ : null
1458
+ return { cardLine, notice }
1459
+ }
1460
+
1461
+ /*
1462
+ * [2.2.5][T5] 进度回报器工厂:把 runPlanner 的 onProgress 回调落到两个既有
1463
+ * 通道上(T3 §2 S2、§4 频率规则)。依赖全部以参数注入(signal / 落记录 /
1464
+ * 发通知),便于脱离宿主运行态做单元回归:
1465
+ * - signal.aborted 后一律静默(用户自己取消的,不再打扰,也不写记录);
1466
+ * - 通道 A 每轮至多 2 行(maxLines),通道 B 每轮至多 2 条(maxNotices);
1467
+ * - 记录更新走 setRecord 回调(maybePlan 侧即 state.records.set),失败
1468
+ * 尝试的摘要在成功/降级后被既有 records.set 整体覆盖,无残留。
1469
+ */
1470
+ export function createPlannerProgressReporter(options: {
1471
+ signal?: any
1472
+ record: any
1473
+ setRecord: (record: any) => void
1474
+ appendNotice: (text: string) => void
1475
+ maxAttempts: number
1476
+ maxLines?: number
1477
+ maxNotices?: number
1478
+ }) {
1479
+ const maxLines = Math.max(1, Number(options.maxLines) || 2)
1480
+ const maxNotices = Math.max(0, Number(options.maxNotices) || 2)
1481
+ const errors: string[] = []
1482
+ let notices = 0
1483
+ return (report: any) => {
1484
+ if (options.signal?.aborted) return
1485
+ const lines = plannerProgressLines(report, options.maxAttempts)
1486
+ if (!lines.cardLine) return
1487
+ if (errors.length < maxLines) errors.push(lines.cardLine)
1488
+ options.record.errors = [...errors]
1489
+ options.record.updatedAt = Date.now()
1490
+ options.setRecord(options.record)
1491
+ if (lines.notice && notices < maxNotices) {
1492
+ notices += 1
1493
+ options.appendNotice(lines.notice)
1494
+ }
1495
+ }
1496
+ }
1497
+
1244
1498
  export function buildPlanSummary(plan: any) {
1245
1499
  const total = flattenSubtasks(plan).length
1246
1500
  const primary = plan.contradictions.primary.statement
@@ -1272,17 +1526,31 @@ export function estimatePlanMinutes(plan: any, fallbackMinutes = 15, concurrency
1272
1526
  return Math.max(waves * maxEstimate, Math.ceil(totalEstimate / Math.max(1, concurrency)))
1273
1527
  }
1274
1528
 
1275
- export function buildBudgetWarning(plan: any, totalBudgetMinutes = 20, maxResumes = MAX_PLAN_RESUMES) {
1529
+ export function buildBudgetWarning(plan: any, totalBudgetMinutes = 0, maxResumes = MAX_PLAN_RESUMES) {
1276
1530
  const minutes = estimatePlanMinutes(plan)
1277
- const budget = Math.max(1, Math.round(Number(totalBudgetMinutes) || 20))
1278
- if (minutes <= budget) return ''
1531
+ const rawBudget = Number(totalBudgetMinutes)
1532
+ const budget = Number.isFinite(rawBudget) && rawBudget > 0 ? Math.max(1, Math.round(rawBudget)) : 0
1533
+ /*
1534
+ * [2.2.0][T3/O-5b] 固定预算措辞改为「预估仅供参考,非承诺;实际时长协商
1535
+ * 决定」(方案 §2.6 #5 的目标措辞;O-5b 三处承诺禁令之一):预算提示只讲
1536
+ * 估算与轮次,不构成任何固定交付承诺。
1537
+ *
1538
+ * 标注行是输出的固定组成部分——预算内也返回(验收 E2「预算预告/计划消息
1539
+ * 把预估标注为仅供参考/非承诺」:凡 buildBudgetWarning 有输出必带该标注,
1540
+ * 计划消息经 warning 路径同享,不再按超预算与否吞掉)。
1541
+ */
1542
+ const advisory = '(子任务 estimateMinutes 预估仅供参考,非承诺;实际时长协商决定:由执行专家开工预告协商,不设固定完成时间。)'
1543
+ // [2.2.5] 0 = 本轮不设固定总预算:只保留“预估仅供参考”的标注,不再输出
1544
+ // “超过本轮预算/需要 N 轮”的提示,避免与“不强制限制”的目标矛盾。
1545
+ if (budget === 0 || minutes <= budget) return advisory
1279
1546
  const rounds = Math.max(1, Math.ceil(minutes / budget))
1280
1547
  const missing = flattenSubtasks(plan).some((entry: any) => !Number.isFinite(Number(entry.subtask?.estimateMinutes)))
1281
1548
  return [
1282
1549
  `⚠ 预算提示:本计划 ${flattenSubtasks(plan).length} 项,按其估计约需 ${minutes} 分钟 > 本轮 ${budget} 分钟,`
1283
1550
  + `预计需要约 ${rounds} 轮(续跑额度 ${maxResumes} 次)。`,
1551
+ advisory,
1284
1552
  '建议:拆成多轮,或减少同时进行的子任务。',
1285
- ...(missing ? ['(部分子任务缺少 estimateMinutes,已按 15 分钟上限估算。)'] : []),
1553
+ ...(missing ? ['(部分子任务缺少 estimateMinutes,已按每项 15 分钟默认值估算。)'] : []),
1286
1554
  ].join('\n')
1287
1555
  }
1288
1556
 
@@ -1299,11 +1567,17 @@ export function buildPlanMessage(plan: any, options: any = {}) {
1299
1567
  }
1300
1568
  const warning = buildBudgetWarning(
1301
1569
  plan,
1302
- options.totalBudgetMinutes ?? 20,
1570
+ options.totalBudgetMinutes ?? 0,
1303
1571
  options.maxResumes ?? MAX_PLAN_RESUMES,
1304
1572
  )
1305
1573
  const text = [
1306
1574
  summary,
1575
+ /*
1576
+ * [2.2.0][T3/O-5b/E2] 计划消息中的预估一律标注「非承诺」(方案 §1⑤ O-5b:
1577
+ * 「预估一律标注『仅供参考,实际时长由执行专家预告协商』」;验收 E2)。
1578
+ * 标注由 buildBudgetWarning 的固定 advisory 行携带(预算内也返回,见该
1579
+ * 函数注释),warning 恒非空随消息带出,此处不再重复一份。
1580
+ */
1307
1581
  ...(warning ? ['', warning] : []),
1308
1582
  '',
1309
1583
  /*
@@ -1328,6 +1602,11 @@ export function buildPlanMessage(plan: any, options: any = {}) {
1328
1602
 
1329
1603
  export function buildDegradedMessage(options: any) {
1330
1604
  const error = truncate(options.error ?? '未知错误', 600)
1605
+ /*
1606
+ * [2.1.6] 失败现场:模型、耗时、收到几个输出块、判定码。没有它,用户只看到
1607
+ * 一句「超时」,既不知道是不是模型太慢,也不知道该改哪个旋钮。
1608
+ */
1609
+ const detail = truncate(options.detail ?? '', 400)
1331
1610
  const summary = truncate(`【自动分解降级】${error}`, 300)
1332
1611
  const payload = {
1333
1612
  kind: 'workplan',
@@ -1338,6 +1617,7 @@ export function buildDegradedMessage(options: any) {
1338
1617
  createdAt: options.createdAt,
1339
1618
  degraded: true,
1340
1619
  error,
1620
+ ...(detail ? { detail } : {}),
1341
1621
  title: '自动分解降级',
1342
1622
  taskUnderstanding: {
1343
1623
  originalRequest: truncate(options.taskText ?? '', 2000),
@@ -1351,6 +1631,7 @@ export function buildDegradedMessage(options: any) {
1351
1631
  }
1352
1632
  const text = [
1353
1633
  summary,
1634
+ ...(detail ? ['', detail] : []),
1354
1635
  '',
1355
1636
  '自动任务分解失败,部门 Agent 未启动。',
1356
1637
  '请先向用户说明失败原因,并询问是否重试;在用户确认前不要开始执行任务。',
@@ -1527,7 +1808,10 @@ export function buildResultMessage(result: any) {
1527
1808
  return handoffs.map((handoff: any) =>
1528
1809
  `${item.subtaskId} ${String(handoff?.id ?? 'H?')}(${String(handoff?.status ?? 'open')}):${String(handoff?.request ?? '')}`)
1529
1810
  }
1530
- return (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${need}`)
1811
+ // [2.2.6][T4] needs 条目自本版起可能为结构化对象 {request, department},
1812
+ // 旧记录仍是字符串;统一经 needEntryText 渲染,两条形状都不会再出现
1813
+ // "[object Object]"(字符串路径逐字不变)。
1814
+ return (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${needEntryText(need)}`)
1531
1815
  })
1532
1816
  const review: string[] = []
1533
1817
  if (escalations.length > 0) {
@@ -2018,10 +2302,88 @@ function readEvidenceArtifacts(value: any) {
2018
2302
  }).filter((item: any) => item.ref !== '')
2019
2303
  }
2020
2304
 
2305
+ /*
2306
+ * [2.2.6][T4] 循环引用/undefined 安全的 JSON 文本化兜底(缺陷二修复件)。
2307
+ *
2308
+ * 对象形 needs 的兜底路径不允许再用隐式 String()——它把任意对象变成字面量
2309
+ * "[object Object]",department 等字段当场丢失(wp-db6de2f0 的 T1–T4 四条
2310
+ * handoff 即因此损坏)。JSON.stringify 对循环引用会抛错、对顶层 undefined
2311
+ * 返回 undefined,这里统一兜成可读文本,任何形状都不会炸掉结果块解析。
2312
+ */
2313
+ function safeJsonText(value: any): string {
2314
+ const seen = new WeakSet<object>()
2315
+ try {
2316
+ return JSON.stringify(value, (_key, entry) => {
2317
+ if (entry !== null && typeof entry === 'object') {
2318
+ if (seen.has(entry)) return '[Circular]'
2319
+ seen.add(entry)
2320
+ }
2321
+ return entry === undefined ? null : entry
2322
+ }) ?? ''
2323
+ } catch {
2324
+ return '[Unserializable object]'
2325
+ }
2326
+ }
2327
+
2328
+ /** [2.2.6][T4] 本插件 readEvidenceNeeds 产出的规范化条目形状(回放幂等判定)。 */
2329
+ function isStructuredNeedEntry(item: any) {
2330
+ return isRecord(item) && typeof item.request === 'string' && item.request.trim() !== ''
2331
+ && Object.keys(item).every((key) => key === 'request' || key === 'department')
2332
+ }
2333
+
2334
+ /*
2335
+ * [2.2.6][T4] 对象感知的 needs/options 文本提取(取代一切 String(对象))。
2336
+ *
2337
+ * 字符串原样返回(历史行为逐字不变);对象优先读取 need/request/text/
2338
+ * message/question 中首个非空文本字段,拼上 purpose(用途)与 department
2339
+ * (部门)前缀,与子 Agent 实际写入的 {"department","need","purpose"} 形状
2340
+ * 对齐(T1 §2.4 子会话日志原文实证);完全无法识别的形状回退受控 JSON 文本。
2341
+ * 注意:本插件自己的结构化条目 {request, department} 视为已定稿文本原样返回,
2342
+ * 否则 mergeHandoffsFromNeeds 会二次拼「部门:」前缀。
2343
+ */
2344
+ export function needEntryText(item: any): string {
2345
+ if (typeof item === 'string') return item
2346
+ if (typeof item === 'number' || typeof item === 'boolean') return String(item)
2347
+ if (!isRecord(item)) return item == null ? '' : safeJsonText(item)
2348
+ if (isStructuredNeedEntry(item)) return item.request
2349
+ const text = [item.need, item.request, item.text, item.message, item.question]
2350
+ .find((entry: any) => typeof entry === 'string' && entry.trim() !== '')
2351
+ const purpose = typeof item.purpose === 'string' && item.purpose.trim() !== '' ? item.purpose.trim() : ''
2352
+ const department = typeof item.department === 'string' && item.department.trim() !== '' ? item.department.trim() : ''
2353
+ if (typeof text === 'string') {
2354
+ const body = purpose !== '' ? `${text.trim()}(用途:${purpose})` : text.trim()
2355
+ return department !== '' ? `${department}:${body}` : body
2356
+ }
2357
+ return safeJsonText(item)
2358
+ }
2359
+
2360
+ /** [2.2.6][T4] 对象形 needs 的合法部门键提取(与 normaliseHandoffs 同一判定)。 */
2361
+ export function needEntryDepartment(item: any): string | null {
2362
+ if (!isRecord(item)) return null
2363
+ const department = item.department
2364
+ return typeof department === 'string' && DEPARTMENTS[department as keyof typeof DEPARTMENTS]
2365
+ ? department
2366
+ : null
2367
+ }
2368
+
2021
2369
  function readEvidenceNeeds(value: any) {
2022
2370
  if (!Array.isArray(value)) return []
2023
2371
  return value.slice(0, MAX_EVIDENCE_NEEDS)
2024
- .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
2372
+ .map((item: any) => {
2373
+ if (typeof item === 'string') return truncate(item, 300)
2374
+ /*
2375
+ * [2.2.6][T4] 回放/重读幂等:本插件自己产出的结构化条目(仅含
2376
+ * request/department 两个键)原样保留,不二次拼「部门:」前缀——
2377
+ * 否则结果消息回放时文本会变化,绕过去重键造成重复登记。
2378
+ */
2379
+ if (isStructuredNeedEntry(item)) {
2380
+ return { request: truncate(item.request, 300), department: needEntryDepartment(item) }
2381
+ }
2382
+ const request = truncate(needEntryText(item), 300).trim()
2383
+ if (!request) return null
2384
+ const department = needEntryDepartment(item)
2385
+ return department !== null ? { request, department } : request
2386
+ })
2025
2387
  .filter(Boolean)
2026
2388
  }
2027
2389
 
@@ -2060,6 +2422,69 @@ export function normaliseHandoffs(value: any): any[] {
2060
2422
  return out
2061
2423
  }
2062
2424
 
2425
+ /**
2426
+ * [2.2.9][T2][mono-gate] handoff 逐项单调合并(M2):「整组替换」改「字段级增量」。
2427
+ *
2428
+ * 背景(wp-215ed52f T5 实证):handoff 答复的 durable 记录携带的是读取时刻的
2429
+ * 整数组快照;回放时低 rev 事件若走 normaliseHandoffs 整组替换,会把高 rev 结算
2430
+ * 之后才落盘的答复/新登记一起抹掉。答复本质是逐项增量(status/response/
2431
+ * updatedAt 三个字段变化),不该被行级覆盖语义绑架。
2432
+ *
2433
+ * 合并不变量(按 request 文本对齐——normaliseHandoffs 的既有去重键;id 是
2434
+ * 位置式生成,跨世代不可靠):
2435
+ * 1. 新需求登记永远合法:current 没有的 request 直接追加(受 MAX_HANDOFFS 约束,
2436
+ * 与 normaliseHandoffs 同口径)。
2437
+ * 2. 状态单调序 open < routed < {answered, closed}(终态)。**前进只看秩、
2438
+ * 不看时间戳**:needs 派生的 open 条目在回放时由 normaliseHandoffs 以
2439
+ * Date.now() 打戳(回放时刻的产物,不是事实时刻),拿它比较会误拒真实的
2440
+ * 历史答复——正是「处理过的事情不能被重放抹掉」这条既有铁律要防的形状。
2441
+ * 3. 同秩(含终态之间 answered↔closed)只在 incoming.updatedAt 严格更大时
2442
+ * 采纳(response/department 等增量的精化);低秩覆盖一律拒绝,终态永不
2443
+ * 回退。
2444
+ * 4. 采纳时 id 保持稳定(界面与 needs 引用按 id 认条目),其余字段随快照前进。
2445
+ *
2446
+ * 幂等性:同一条记录二次进入(写侧、回放、重读共用本函数)结果不变——updatedAt
2447
+ * 相等时保留 current,normaliseHandoffs 按 request 去重挡住重复追加。
2448
+ */
2449
+ export function mergeHandoffEntriesByUpdatedAt(
2450
+ current: any,
2451
+ incoming: any,
2452
+ ): { changed: boolean; value: any[] } {
2453
+ const base = normaliseHandoffs(current)
2454
+ const list = normaliseHandoffs(incoming)
2455
+ if (list.length === 0) return { changed: false, value: base }
2456
+ const rank = (status: any) => {
2457
+ if (status === 'answered' || status === 'closed') return 2
2458
+ if (status === 'routed') return 1
2459
+ return 0
2460
+ }
2461
+ const snapshot = JSON.stringify(base)
2462
+ const byRequest = new Map<string, any>()
2463
+ for (const item of base) byRequest.set(item.request, item)
2464
+ for (const item of list) {
2465
+ const target = byRequest.get(item.request)
2466
+ if (!target) {
2467
+ // 新需求登记:append-only(对齐 mergeHandoffsFromNeeds 的语义)。
2468
+ if (base.length >= MAX_HANDOFFS) continue
2469
+ const used = new Set(base.map((entry) => entry.id))
2470
+ const appended = used.has(item.id) ? { ...item, id: `H${base.length + 1}` } : { ...item }
2471
+ base.push(appended)
2472
+ byRequest.set(appended.request, appended)
2473
+ continue
2474
+ }
2475
+ const targetRank = rank(target.status)
2476
+ const itemRank = rank(item.status)
2477
+ if (itemRank < targetRank) continue // 永不回退(含终态不接受 open/routed 覆盖)
2478
+ if (itemRank === targetRank && !(Number(item.updatedAt) > Number(target.updatedAt))) continue
2479
+ // 秩前进只看状态序(工具端 open→routed→answered/closed 单调,回放同样只进不退);
2480
+ // 同秩精化才比 updatedAt。id 保持稳定(界面与 needs 引用都按 id 认条目)。
2481
+ const index = base.indexOf(target)
2482
+ base[index] = { ...item, id: target.id }
2483
+ byRequest.set(item.request, base[index])
2484
+ }
2485
+ return { changed: JSON.stringify(base) !== snapshot, value: base }
2486
+ }
2487
+
2063
2488
  /**
2064
2489
  * 每一条 `needs` 都必须变成一条可追踪的 handoff。
2065
2490
  *
@@ -2071,8 +2496,17 @@ export function mergeHandoffsFromNeeds(current: any, needs: any, overflow: strin
2071
2496
  const next = normaliseHandoffs(current)
2072
2497
  const list = Array.isArray(needs) ? needs : []
2073
2498
  for (const raw of list) {
2074
- const request = truncate(String(raw ?? ''), 300).trim()
2499
+ /*
2500
+ * [2.2.6][T4] 对象安全序列化(缺陷二第二触点 W2):needs 条目可能是子
2501
+ * Agent 直接写的对象({"department","need","purpose"}),也可能是
2502
+ * readEvidenceNeeds 产出的结构化条目 {request, department}。request 一律
2503
+ * 经 needEntryText 取文本、department 经 needEntryDepartment 提取合法
2504
+ * 部门键——本函数不再有任何 String(对象) 分支,对象不再被写成
2505
+ * "[object Object]"、department 不再被丢弃。去重键仍是 request 文本。
2506
+ */
2507
+ const request = truncate(typeof raw === 'string' ? raw : needEntryText(raw), 300).trim()
2075
2508
  if (!request) continue
2509
+ const department = needEntryDepartment(raw)
2076
2510
  if (next.some((item) => item.request === request)) continue
2077
2511
  /*
2078
2512
  * [1.12.0][D-30] 容量溢出必须可审计,不能静默 `break`。
@@ -2088,7 +2522,7 @@ export function mergeHandoffsFromNeeds(current: any, needs: any, overflow: strin
2088
2522
  next.push({
2089
2523
  id: `H${next.length + 1}`,
2090
2524
  request,
2091
- department: null,
2525
+ department,
2092
2526
  status: 'open',
2093
2527
  response: null,
2094
2528
  at: Date.now(),
@@ -2114,11 +2548,28 @@ export function openHandoffs(status: any): any[] {
2114
2548
  */
2115
2549
  function readEvidenceOptions(value: any) {
2116
2550
  if (!Array.isArray(value)) return []
2551
+ // [2.2.6][T4] 同模式共犯(T1 W3):对象感知读取,消灭 String(对象) 分支。
2117
2552
  return value.slice(0, MAX_ESCALATION_OPTIONS)
2118
- .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
2553
+ .map((item: any) => truncate(needEntryText(item), 300))
2119
2554
  .filter(Boolean)
2120
2555
  }
2121
2556
 
2557
+ /**
2558
+ * [2.2.0][T3/O-2c] 用时回填字段(timeSpentMinutes / finalEstimateMinutes)
2559
+ * 的 advisory 读取器。
2560
+ *
2561
+ * 方案 §2.5:「时间字段纯 advisory:不参与可交付判定,不加拒绝码」;方案
2562
+ * §2.4 结果块契约「模板增加 timeSpentMinutes、finalEstimateMinutes 字段」。
2563
+ * 只在给出合法非负有限数值时以整数分钟透传;缺失/非法一律省略(返回
2564
+ * undefined、不占键名),不判不合规——字段本来就是可选的。
2565
+ */
2566
+ function readAdvisoryMinutes(value: any): number | undefined {
2567
+ if (value === undefined || value === null) return undefined
2568
+ const num = Number(value)
2569
+ if (!Number.isFinite(num) || num < 0) return undefined
2570
+ return Math.round(num)
2571
+ }
2572
+
2122
2573
  /**
2123
2574
  * [2.1.0] 顶层证据字段被误写进 `phases` 时,把它们提回顶层(用户 2026-11-05)。
2124
2575
  *
@@ -2306,9 +2757,10 @@ export function parseEvidenceBlock(output: any) {
2306
2757
  rescued: true,
2307
2758
  payload: rescued.payload,
2308
2759
  raw: rescued.raw,
2760
+ parseError: '',
2309
2761
  }
2310
2762
  }
2311
- return { found: false, malformed: false, truncated: false, repaired: false, rescued: false, payload: null, raw: '' }
2763
+ return { found: false, malformed: false, truncated: false, repaired: false, rescued: false, payload: null, raw: '', parseError: '' }
2312
2764
  }
2313
2765
  const bodyStart = begin + EVIDENCE_MARKER_BEGIN.length
2314
2766
  const end = text.indexOf(EVIDENCE_MARKER_END, bodyStart)
@@ -2321,18 +2773,39 @@ export function parseEvidenceBlock(output: any) {
2321
2773
  */
2322
2774
  const raw = (end < 0 ? text.slice(bodyStart) : text.slice(bodyStart, end)).trim()
2323
2775
  const truncated = end < 0 || raw.length > MAX_EVIDENCE_BLOCK_CHARS
2324
- const accept = (payload: any, repaired: boolean) => {
2776
+ /*
2777
+ * [2.2.8][T7] 回喂重报需要的「解析器具体错误」。
2778
+ *
2779
+ * 旧实现把 JSON.parse 的异常吞掉,只留一句「结果块 JSON 非法」;子会话收到
2780
+ * 回喂时看不到是哪个字符、哪一列坏了,只能整块盲改。现在把解析器的原始
2781
+ * 报错(含 position/line/column)随 malformed 一并带回,供结算回喂与
2782
+ * blocked 记录逐字引用。
2783
+ */
2784
+ const accept = (payload: any, repaired: boolean, parseError = '') => {
2325
2785
  if (!isRecord(payload) || !EVIDENCE_STATUSES.includes(payload.status)) {
2326
- return { found: true, malformed: true, truncated, repaired, rescued: false, payload: null, raw }
2786
+ return {
2787
+ found: true,
2788
+ malformed: true,
2789
+ truncated,
2790
+ repaired,
2791
+ rescued: false,
2792
+ payload: null,
2793
+ raw,
2794
+ parseError: parseError
2795
+ || (isRecord(payload)
2796
+ ? `JSON 可解析,但 status 缺失或取值非法("${String(payload.status ?? '')}"),只能是 done / blocked / partial`
2797
+ : 'JSON 可解析,但顶层不是对象,无法作为证据块结算'),
2798
+ }
2327
2799
  }
2328
- return { found: true, malformed: false, truncated, repaired, rescued: false, payload, raw }
2800
+ return { found: true, malformed: false, truncated, repaired, rescued: false, payload, raw, parseError: '' }
2329
2801
  }
2330
2802
  try {
2331
2803
  return accept(JSON.parse(raw), false)
2332
- } catch {
2804
+ } catch (error: any) {
2805
+ const parseError = truncate(String(error?.message ?? error), 300)
2333
2806
  const repaired = repairEvidenceJson(raw)
2334
2807
  if (repaired) return accept(repaired, true)
2335
- return { found: true, malformed: true, truncated, repaired: false, payload: null, raw }
2808
+ return { found: true, malformed: true, truncated, repaired: false, payload: null, raw, parseError }
2336
2809
  }
2337
2810
  }
2338
2811
 
@@ -2345,7 +2818,42 @@ const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i
2345
2818
  * the acceptance table cannot drift apart between the runtime and the replay.
2346
2819
  * It never invents evidence and never upgrades a failed self-check to done.
2347
2820
  */
2348
- export function adjudicateResult({ output, strict = true, expectedAcceptance = [], requirePhases = true }: any) {
2821
+ /**
2822
+ * [2.2.0][T3/O-2c] `adjudicateResult` 的显式返回契约。
2823
+ *
2824
+ * 为什么不沿用结构化推断:7 个 payload 分支透传 `...advisoryTime` 之后,TS 对
2825
+ * 「spread + 多返回对象字面量」的联合归并会劣化(实测消费点 runtime.ts:1201
2826
+ * 一带 TS2339 × 8:把判别字段宽化成 string,`.question`/`.phases` 等既有访问
2827
+ * 全部失去收窄保护)。显式钉死契约后,既有消费面(status/question/phases/
2828
+ * options/blockedKind/commFormat* …)的可选性与类型不再随推断波动。
2829
+ *
2830
+ * 字段语义与 [1.11.0]-[2.1.0] 各分支保持一致;`timeSpentMinutes` /
2831
+ * `finalEstimateMinutes` 为 [2.2.0][T3/O-2c] 纯 advisory 可选字段(方案 §2.5
2832
+ * 「时间字段纯 advisory:不参与可交付判定」),缺失即省略。
2833
+ */
2834
+ export interface AdjudicateResult {
2835
+ status: 'done' | 'blocked'
2836
+ verification: string
2837
+ acceptance: any[]
2838
+ artifacts: any[]
2839
+ needs: any[]
2840
+ error: string | null
2841
+ question?: string
2842
+ options?: string[]
2843
+ phases?: any
2844
+ phaseSummary?: string | null
2845
+ blockedKind?: string
2846
+ commFormatViolations?: any[]
2847
+ commFormatRejection?: string
2848
+ /** [2.2.0][T3/O-2c] 实际耗时回填(整数分钟,advisory)。 */
2849
+ timeSpentMinutes?: number
2850
+ /** [2.2.0][T3/O-2c] 最终预估回填(整数分钟,advisory)。 */
2851
+ finalEstimateMinutes?: number
2852
+ /** 各版本分支的附加诊断字段经此放行(回放/新字段向前兼容)。 */
2853
+ [extra: string]: unknown
2854
+ }
2855
+
2856
+ export function adjudicateResult({ output, strict = true, expectedAcceptance = [], requirePhases = true }: any): AdjudicateResult {
2349
2857
  const text = typeof output === 'string' ? output : ''
2350
2858
  const parsed = parseEvidenceBlock(text)
2351
2859
  if (!strict) {
@@ -2375,10 +2883,18 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2375
2883
  * 也不说该重发还是该改格式,于是只能靠读原始输出猜。现在按截断/非法
2376
2884
  * 分档给出可执行提示。
2377
2885
  */
2378
- error: parsed.truncated
2886
+ error: (parsed.truncated
2379
2887
  ? '结果块被截断(缺少结束标记或超过长度上限):请让该子 Agent 重新回报,'
2380
2888
  + '只保留 status/summary/acceptance/artifacts/needs 字段,删掉大段执行日志后重发'
2381
- : '结果块 JSON 非法(不是截断):请检查引号、逗号与括号是否成对,修正后重新回报',
2889
+ : '结果块 JSON 非法(不是截断):请检查引号、逗号与括号是否成对,修正后重新回报')
2890
+ /*
2891
+ * [2.2.8][T7] 解析器原始报错(含 position/line/column)一并写进判定:
2892
+ * 结算回喂时子 Agent 能看到「坏在哪个字符」,blocked 记录也留档同一句。
2893
+ */
2894
+ + (typeof parsed.parseError === 'string' && parsed.parseError !== ''
2895
+ ? `。解析器报告:${parsed.parseError}`
2896
+ : ''),
2897
+ parseError: typeof parsed.parseError === 'string' ? parsed.parseError : '',
2382
2898
  }
2383
2899
  }
2384
2900
  if (!parsed.found) {
@@ -2428,8 +2944,25 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2428
2944
  const question = truncate(String(payload.question ?? ''), MAX_QUESTION_CHARS)
2429
2945
  const options = readEvidenceOptions(payload.options)
2430
2946
  const blockedReason = truncate(String(payload.blockedReason ?? payload.error ?? ''), 2000)
2947
+ /*
2948
+ * [2.2.0][T3/O-2c] 用时回填字段(方案 §2.2/§2.4:「模板增加
2949
+ * timeSpentMinutes、finalEstimateMinutes 字段」)。纯 advisory(方案 §2.5
2950
+ * 「时间字段纯 advisory:不参与可交付判定,不加拒绝码」):合法即整数分钟
2951
+ * 透传到判定结果的每一个 payload 分支,缺失/非法即省略(不占键名),既有
2952
+ * 字段与 F1-F9 零改动。
2953
+ */
2954
+ const timeSpentMinutes = readAdvisoryMinutes(payload.timeSpentMinutes)
2955
+ const finalEstimateMinutes = readAdvisoryMinutes(payload.finalEstimateMinutes)
2956
+ const advisoryTime: { timeSpentMinutes?: number; finalEstimateMinutes?: number } =
2957
+ timeSpentMinutes === undefined && finalEstimateMinutes === undefined
2958
+ ? {}
2959
+ : {
2960
+ ...(timeSpentMinutes === undefined ? {} : { timeSpentMinutes }),
2961
+ ...(finalEstimateMinutes === undefined ? {} : { finalEstimateMinutes }),
2962
+ }
2431
2963
  if (payload.status === 'blocked') {
2432
2964
  return {
2965
+ ...advisoryTime,
2433
2966
  status: 'blocked',
2434
2967
  verification: 'structured',
2435
2968
  acceptance,
@@ -2443,6 +2976,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2443
2976
  if (payload.status === 'partial') {
2444
2977
  const detail = truncate(String(payload.summary ?? payload.blockedReason ?? ''), 2000)
2445
2978
  return {
2979
+ ...advisoryTime,
2446
2980
  status: 'blocked',
2447
2981
  verification: 'structured',
2448
2982
  acceptance,
@@ -2456,6 +2990,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2456
2990
  const failed = acceptance.filter((item: any) => item.result === 'fail')
2457
2991
  if (failed.length > 0) {
2458
2992
  return {
2993
+ ...advisoryTime,
2459
2994
  status: 'blocked',
2460
2995
  verification: 'failed',
2461
2996
  acceptance,
@@ -2501,6 +3036,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2501
3036
  ? '(结果块 JSON 有语法错误,已修复;若 acceptance 位于错误点之后,会被一起裁掉)'
2502
3037
  : ''
2503
3038
  return {
3039
+ ...advisoryTime,
2504
3040
  status: 'blocked',
2505
3041
  verification: 'unverified',
2506
3042
  acceptance,
@@ -2525,6 +3061,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2525
3061
  : validatePhaseEvidence(payload.phases, expectedAcceptance)
2526
3062
  if (phaseCheck && !phaseCheck.ok) {
2527
3063
  return {
3064
+ ...advisoryTime,
2528
3065
  status: 'blocked',
2529
3066
  verification: 'unverified',
2530
3067
  acceptance,
@@ -2560,6 +3097,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2560
3097
  )
2561
3098
  if (!commFormat.compliant) {
2562
3099
  return {
3100
+ ...advisoryTime,
2563
3101
  status: 'blocked',
2564
3102
  verification: 'unverified',
2565
3103
  acceptance,
@@ -2575,6 +3113,7 @@ export function adjudicateResult({ output, strict = true, expectedAcceptance = [
2575
3113
  }
2576
3114
  }
2577
3115
  return {
3116
+ ...advisoryTime,
2578
3117
  status: 'done',
2579
3118
  verification: hasUnverified ? 'unverified' : 'structured',
2580
3119
  acceptance,
@@ -2637,6 +3176,17 @@ export function buildUpdateMessage(update: any) {
2637
3176
  ...(update.instructionOverdue === undefined ? {} : { instructionOverdue: update.instructionOverdue }),
2638
3177
  ...(update.handoffs === undefined ? {} : { handoffs: update.handoffs }),
2639
3178
  ...(update.reportedAt === undefined ? {} : { reportedAt: update.reportedAt }),
3179
+ /*
3180
+ * [2.2.0][T3/O-3c] 协商上限持久化臂(方案 §1③ O-3c:「专家预告(O-2a)经
3181
+ * 主 Agent 确认后写入 timeoutMs(经 dsh_workplan_update 新字段或计划消息)」)。
3182
+ *
3183
+ * 主 Agent 把确认后的 timeoutMs 随改判/进度更新记录留档,刷新/重启后按同
3184
+ * 顺序回放(回放侧 update 载荷的字段透传白名单在 src/runtime.ts:2931,属
3185
+ * T4 接线范围;applyStatus 侧已接受该字段);缺省合法(undefined 跳过,
3186
+ * 不改 2.1.x 语义)。计划内该字段的读取/派生见 readSubtasks +
3187
+ * deriveSubtaskTimeoutMs。
3188
+ */
3189
+ ...(update.timeoutMs === undefined ? {} : { timeoutMs: update.timeoutMs }),
2640
3190
  ...(update.revision === undefined ? {} : { revision: update.revision }),
2641
3191
  at: update.at ?? Date.now(),
2642
3192
  }
@@ -2752,6 +3302,20 @@ export function applyResultStatuses(statuses: any, result: any) {
2752
3302
  const replayedClosure = entry.status === 'done' && entry.closure === undefined
2753
3303
  ? 'reported'
2754
3304
  : entry.closure
3305
+ /*
3306
+ * [2.2.1][T5][F1] 回放容错:结果载荷里的通道字段可能是 null / 非法值
3307
+ * (旧版本遗留、人工改日志、或早期重建写回的脏值)。applyStatus 是写入
3308
+ * 单点校验,遇到非法值会整条抛错,被下面的 catch 吞掉后这一行的
3309
+ * done / summary / verification / acceptance 全都不落地 —— 一条完成行
3310
+ * 回放成 pending 的假阴性(T4 残余项复核 A2/B2 实测)。
3311
+ *
3312
+ * 这里在进入 patch 之前判定:只有能通过校验的值才参与回放,null / 非法值
3313
+ * 按「字段缺失」处理。applyStatus 的 fail-closed 校验保持不变(其它写入方
3314
+ * 仍然不能写脏值),本改动只影响「读旧日志」这一侧。
3315
+ */
3316
+ const replayedNoticeChannel = entry.noticeChannel !== undefined && validateNoticeChannel(entry.noticeChannel).ok
3317
+ ? entry.noticeChannel
3318
+ : undefined
2755
3319
  try {
2756
3320
  next = applyStatus(next, entry.subtaskId, {
2757
3321
  status: entry.status,
@@ -2783,6 +3347,16 @@ export function applyResultStatuses(statuses: any, result: any) {
2783
3347
  instructionSeq: entry.instructionSeq,
2784
3348
  instructionOverdue: entry.instructionOverdue,
2785
3349
  reportedAt: entry.reportedAt,
3350
+ // [2.2.0][T3/O-2c/O-3c] 柔性时长协商留档字段随结果快照回放(方案 §2.5
3351
+ // 「旧消息回放零改动读取」:字段缺失时 applyStatus 分支自动跳过)。
3352
+ timeSpentMinutes: entry.timeSpentMinutes,
3353
+ finalEstimateMinutes: entry.finalEstimateMinutes,
3354
+ timeoutMs: entry.timeoutMs,
3355
+ // [2.2.0][T3/O-2a] 子→主预告通道结论必须随结果快照回放;写入由
3356
+ // applyStatus 单点校验,非法值在 catch 中 fail-closed(不落脏值)。
3357
+ // [2.2.1][T5][F1] 但非法值只能丢「这个字段」,不能丢「整条结果行」:
3358
+ // 上面的 replayedNoticeChannel 已把 null / 非法值归一为 undefined。
3359
+ noticeChannel: replayedNoticeChannel,
2786
3360
  // [1.11.0] 回报证据与重规划留档必须随结果快照回放(T7 C-06/C-11)。
2787
3361
  report: entry.report,
2788
3362
  replannedReason: entry.replannedReason,
@@ -2906,6 +3480,45 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
2906
3480
  next.instructionSeq = Number.isInteger(Number(patch.instructionSeq)) ? Number(patch.instructionSeq) : null
2907
3481
  }
2908
3482
  if (patch.reportedAt !== undefined) next.reportedAt = numberOrNull(patch.reportedAt)
3483
+ /*
3484
+ * [2.2.0][T3/O-2c/O-3c] 柔性时长协商的留档字段(方案 §2.2/§2.4/§2.5)。
3485
+ *
3486
+ * timeSpentMinutes/finalEstimateMinutes 是结果块回填的实际耗时与收尾预估
3487
+ * (纯 advisory:缺失或非法不判不合规,按缺省处理;不参与可交付判定,
3488
+ * 方案 §2.5「时间字段纯 advisory:不参与可交付判定,不加拒绝码」);
3489
+ * timeoutMs 是 O-3c「预告经主 Agent 确认后写入」的协商上限留档,校验与
3490
+ * readSubtasks 同口径(正数毫秒;null 表示清除)。三者只写同一条状态条目,
3491
+ * 走 StatusEntry 未知字段保留通道,旧消息回放零改动。
3492
+ */
3493
+ if (patch.timeSpentMinutes !== undefined) {
3494
+ next.timeSpentMinutes = readAdvisoryMinutes(patch.timeSpentMinutes) ?? null
3495
+ }
3496
+ if (patch.finalEstimateMinutes !== undefined) {
3497
+ next.finalEstimateMinutes = readAdvisoryMinutes(patch.finalEstimateMinutes) ?? null
3498
+ }
3499
+ if (patch.timeoutMs !== undefined) {
3500
+ if (patch.timeoutMs === null) next.timeoutMs = null
3501
+ else {
3502
+ const value = Number(patch.timeoutMs)
3503
+ if (!Number.isFinite(value) || value <= 0) {
3504
+ throw new PlanError('timeoutMs 必须是正数毫秒(协商上限)', 'INVALID_TIMEOUT_MS')
3505
+ }
3506
+ next.timeoutMs = value
3507
+ }
3508
+ }
3509
+ /*
3510
+ * [2.2.0][T3/O-2a] 子→主预告通道的可观测条目(方案 §2.4 状态行字段)。
3511
+ *
3512
+ * 这条字段存在的理由就是「不静默丢失」:旧实现里预告发不出去,主 Agent
3513
+ * 只能从子 Agent 的自述里猜,计划记录上没有任何痕迹。现在通道的
3514
+ * target / caller / at / observedAt / reason 全部落在状态行,写入前统一
3515
+ * 校验(未知状态或未知原因直接拒绝),回放与刷新都不会丢。
3516
+ */
3517
+ if (patch.noticeChannel !== undefined) {
3518
+ const checked = validateNoticeChannel(patch.noticeChannel)
3519
+ if (!checked.ok) throw new PlanError(`非法 noticeChannel:${checked.error}`, 'INVALID_NOTICE_CHANNEL')
3520
+ next.noticeChannel = checked.value
3521
+ }
2909
3522
  /*
2910
3523
  * [1.11.0] 完成回报与重规划的留档字段(T7 C-06/C-11)。
2911
3524
  *
@@ -3014,7 +3627,17 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
3014
3627
  }
3015
3628
  }
3016
3629
  }
3017
- if (patch.handoffs !== undefined) next.handoffs = normaliseHandoffs(patch.handoffs)
3630
+ /*
3631
+ * [2.2.9][T2][mono-gate] 整组替换 → 逐项单调合并(M2)。
3632
+ *
3633
+ * 旧语义 `next.handoffs = normaliseHandoffs(patch.handoffs)` 让携带旧快照的
3634
+ * 事件(handoff 答复、人工改判、低 rev 回放)连行上更新的答复一起抹掉。
3635
+ * mergeHandoffEntriesByUpdatedAt 只前进不回退:新登记追加、同项仅在
3636
+ * updatedAt 严格更大时采纳、answered/closed 终态永不回退。
3637
+ */
3638
+ if (patch.handoffs !== undefined) {
3639
+ next.handoffs = mergeHandoffEntriesByUpdatedAt(next.handoffs, patch.handoffs).value
3640
+ }
3018
3641
  /*
3019
3642
  * [1.12.0][D-30] 溢出记录必须能随结果消息回放。
3020
3643
  *
@@ -4148,7 +4771,22 @@ export function buildChildPrompt({
4148
4771
  statuses = null,
4149
4772
  previousFailure = null,
4150
4773
  lessonsBrief = '',
4774
+ /*
4775
+ * [2.2.0][T3/O-2a] 子→主预告通道的目标。
4776
+ *
4777
+ * 宿主只对**非 caller** 投递注入父会话 id(dsh-subagent/lib/index.js:1466),
4778
+ * 而本插件用 `delivery: 'caller'` 派发,所以这段 id 必须由插件自己注入。
4779
+ * 不注入时的旧行为是让子 Agent 去喊 `"lead"`——那不是任何会话的 id,
4780
+ * 真实派发中只会得到 `subagent "lead" is unavailable`。
4781
+ */
4782
+ leadAgentId = '',
4783
+ leadAgentIdSource = 'none',
4151
4784
  }: any) {
4785
+ const noticeTarget = readLeadAgentId(leadAgentId)
4786
+ const noticeCall = leadNoticeCallForm(noticeTarget)
4787
+ const noticeTargetLine = noticeTarget
4788
+ ? `- 目标会话 id(**由插件注入,唯一合法目标**):\`${noticeTarget}\`(来源:${leadAgentIdSource || 'unknown'})。它就是本轮主 Agent 的会话 id,宿主的父子血缘校验只认它。`
4789
+ : `- **本提示词没有注入父会话 id**(来源:${leadAgentIdSource || 'none'}):禁止猜测、禁止自行拼一个 id。跳过 send_message 预告,改为在结果块首行写 \`noticeChannel: {"target":"${NOTICE_TARGET_MISSING_TEXT}","at":<毫秒时间戳>,"error":"LEAD_ID_MISSING"}\`——供主 Agent 阅读;**插件不解析这一行**,通道结论以状态行观测为准。`
4152
4790
  /*
4153
4791
  * Every field below is read defensively.
4154
4792
  *
@@ -4330,6 +4968,30 @@ export function buildChildPrompt({
4330
4968
  '- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,并按下方「遇阻上报」给出 question。',
4331
4969
  '- 完成后用简洁中文汇报:做了什么、证据/文件、验收结果、遗留问题。',
4332
4970
  '',
4971
+ /*
4972
+ * [2.2.0][T3/O-2a] 柔性时长协商协议(方案 §2.6 #3:「开工前预告、超预期
4973
+ * 预警、完成即回报」;O-1a①+O-2a+O-4a 合并一段,矩阵 Z1 三条款一次插入)。
4974
+ * 时间是协商出来的安全兜底,不是固定交付期限(方案 §0/§3.2)。
4975
+ *
4976
+ * 2026-11-08 修复(真实环境复现 `subagent "lead" is unavailable`):
4977
+ * 旧文案写的是 `send_message(target: "lead")`——字段名与宿主 schema
4978
+ * 不一致(宿主只有 `agent_id`),值 `"lead"` 也不是任何会话 id,于是
4979
+ * 预告在目标解析阶段必然失败。现在改为:注入真实父会话 id + 用宿主
4980
+ * 契约里的字段名 + 明确失败后的确定性重试与留痕,不再有「猜目标」的余地。
4981
+ */
4982
+ '柔性时长协商协议(不设固定完成时间;时间是协商出来的安全兜底,不是固定交付期限):',
4983
+ noticeTargetLine,
4984
+ `- 开工前先报预估时长(预计完成本子任务要多久就报多久):用 \`${noticeCall}\` 报预估完成时长,新预估覆盖旧预估;预估仅供参考、非承诺,实际时长协商决定。`,
4985
+ `- 发现预计将超预估时,立即用同一个目标报新预估并申请延期(说明还要多久、为什么),不要等超时才预警。`,
4986
+ `- 完成即回报:用同一个目标报核心结论(做了什么、证据/文件、验收结果),不要等整轮结束。`,
4987
+ ...(noticeTarget
4988
+ ? [
4989
+ '- 失败后的确定性处理(禁止静默丢弃):`send_message` 若返回错误(`is unavailable` / `UNAUTHORIZED` / 工具不存在),先在汇报首行原样记录 `noticeChannel: {"target":"' + noticeTarget + '","at":<毫秒时间戳>,"error":"<错误原文>"}`,再用**同一个** agent_id 重试一次;仍失败就继续把子任务做完,把这条记录留在结果里(供主 Agent 阅读;插件不解析这一行,通道结论以状态行观测为准)。**不得改用其它目标,也不得向任何非本轮父会话发送**——那是越权发送,会触发宿主 lineage 拒绝。',
4990
+ ]
4991
+ : []),
4992
+ // [T3 扩展点·T6] 供 T6 在此行之后追加「完成即时通知」条款(O-1a 插件兜底通道语义);上方三条款为 O-1a①+O-2a+O-4a 合并协议段(矩阵 Z1),既有条款不得删改。
4993
+ // [2.2.0][T6/O-1a] 完成即时通知条款(插件兜底通道):完成即报是第一通道(见上方「完成即回报」);插件另设兜底——子任务结算成功后立即向主会话推送一条含子任务 ID、摘要、验收计数与用时的即时通知,不等待整轮结束。兜底不替代主动回报。
4994
+ '',
4333
4995
  '遇阻上报(强制,先于继续动作):',
4334
4996
  '- 出现以下任一情况,第一动作是上报,不是猜测、绕过或静默继续:缺少权限/输入/依赖产物;需求自相矛盾;无法验证;同一命令连续两次失败;需要主 Agent 决定方向。',
4335
4997
  '- 优先调用工具:`dsh_workplan_escalate({ "subtaskId": "<你的子任务 ID>", "question": "需要主 Agent 回答的单个问题", "options": ["可选项 A", "可选项 B"], "needs": ["需要谁提供什么"] })`。调用成功后停止推进,只做只读核对。',
@@ -4339,13 +5001,20 @@ export function buildChildPrompt({
4339
5001
  '',
4340
5002
  '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
4341
5003
  EVIDENCE_MARKER_BEGIN,
4342
- '{"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":[]}',
5004
+ '{"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}',
4343
5005
  EVIDENCE_MARKER_END,
4344
5006
  '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
4345
5007
  '- acceptance 必须逐条覆盖上面的验收标准:criterion 以 A1、A2… 开头对号入座(编号不可省略);result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
4346
5008
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
4347
5009
  '- needs 写需要其他部门配合的事项,每条写清「哪个部门 + 需要什么 + 用来做什么」;它会被登记为待处理需求,主 Agent 必须处置后计划才能交付。不要直连其他子 Agent。',
4348
5010
  '- question/options 只在受阻上报时填写;done 时保持空字符串/空数组。',
5011
+ /*
5012
+ * [2.2.0][T3/O-2c] 用时回填字段(方案 §2.2/§2.4 结果块契约:「模板增加
5013
+ * timeSpentMinutes、finalEstimateMinutes 字段」)。纯 advisory:F1-F9 与
5014
+ * 既有字段零改动,缺失/非法即省略,不判不合规、不影响验收判定(方案 §2.5
5015
+ * 「时间字段纯 advisory」)。
5016
+ */
5017
+ '- timeSpentMinutes / finalEstimateMinutes(可选,整数分钟):完成后把实际耗时与最终预估回填进结果块,未知可省略;两项仅供参考与协商审计,不影响验收判定。',
4349
5018
  '- 整块不超过 12000 字符;不要把这段模板本身抄进结果块。',
4350
5019
  '',
4351
5020
  /*