dsh-workplan 2.2.9 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/plan.js CHANGED
@@ -215,10 +215,46 @@ export function truncate(value, max) {
215
215
  export function messageText(message) {
216
216
  if (!message || !Array.isArray(message.content))
217
217
  return '';
218
- return message.content
218
+ const texts = message.content
219
219
  .filter((block) => block && block.type === 'text' && typeof block.text === 'string')
220
- .map((block) => block.text)
221
- .join('\n');
220
+ .map((block) => block.text);
221
+ /*
222
+ * [2.3.1][D1] 附件事实渲染(用户 2026-11-10 点名的严重缺陷:规划器与 fresh
223
+ * 子 Agent 看不见用户图片)。
224
+ *
225
+ * 旧实现只收 text 块:image/file 块的 attachment 元数据(attachmentId/名称/
226
+ * 尺寸)在到达规划器 taskText 之前就被整块丢弃,专家被迫 escalate 请示
227
+ * 「截图在哪」,往返吃掉整段时间预算(wp-73bb2cd4 事故实证:修复主链 8 分钟、
228
+ * 往返 17 分钟)。
229
+ *
230
+ * 现在把附件渲染成一行标注并入文本面,taskText→taskAnchor→派发锚点块→回放
231
+ * 上下文全部同源受益;标注含 attachment-id(官方读图工具接受该 id 作为
232
+ * path),接收方可直接读取,不再靠猜。
233
+ * 消费方安全审计(2026-11-10):plan/result/cancel/update 四类 marker 解析
234
+ * 消息永不含图片块;replan/supersede 为用户消息子串匹配,附加行零误伤。
235
+ */
236
+ const notes = message.content
237
+ .filter((block) => block && (block.type === 'image' || block.type === 'file' || block.type === 'document') && (block.attachment ?? block.file))
238
+ .map((block) => renderAttachmentNote(block))
239
+ .filter((line) => line !== '');
240
+ if (notes.length === 0)
241
+ return texts.join('\n');
242
+ return [...texts, ...notes].join('\n');
243
+ }
244
+ /** [2.3.1][D1] 单个附件块的只读标注行;元数据缺失时返回空串(不泄漏、不猜测)。 */
245
+ function renderAttachmentNote(block) {
246
+ const att = block.attachment ?? block.file ?? {};
247
+ const id = typeof att.attachmentId === 'string' ? att.attachmentId : '';
248
+ const name = typeof att.name === 'string' ? att.name : (typeof att.filename === 'string' ? att.filename : '');
249
+ if (!id && !name)
250
+ return '';
251
+ const media = typeof att.mediaType === 'string' ? att.mediaType : '';
252
+ const size = Number.isFinite(Number(att.width)) && Number.isFinite(Number(att.height))
253
+ ? `|${String(att.width)}x${String(att.height)}` : '';
254
+ return `[用户附件] ${block.type === 'image' ? '图片' : '文件'} "${name || '未命名'}"`
255
+ + (media ? `|mediaType=${media}` : '') + size
256
+ + (id ? `|attachment-id: ${id}` : '')
257
+ + '|如需其内容:把 attachment-id 作为 path 传给可用的读图/视觉工具直接读取,禁止凭空猜测附件内容。';
222
258
  }
223
259
  /*
224
260
  * [1.8.12] 不能让正文里的「包名:行号」变成跨会话引用。
@@ -967,12 +1003,37 @@ export function flattenSubtasks(plan) {
967
1003
  * 规划器返回的 JSON 常见三类损伤:少一个 `}`、多一个尾逗号、字符串里有裸换行。
968
1004
  * 旧实现直接 JSON.parse,一个字符之差就抛 INVALID_JSON,整个计划降级。
969
1005
  * 这里做的是纯结构修复:配对括号、去掉尾逗号、把字符串里的裸控制符转义。
1006
+ *
1007
+ * [2.3.2][D2-P0] D2 现场(qwen3.8-flash INVALID_JSON ×3、86.9 秒白烧)实测穿透的
1008
+ * 三类损伤——成员间漏逗号、字符串外全角标点、多余闭合括号——在同一趟扫描内补齐。
1009
+ * 旧实现只「补」不「插/删/归一」,这三类必然失败后靠全量重掷碰运气。三条新规则
1010
+ * 全部满足「只修结构、绝不碰内容」红线:
1011
+ * 1. 插逗号:容器内(栈非空)值结束符(`"`/`}`/`]`/数字/true|false|null)之后
1012
+ * 紧邻下一个起点 token 且无分隔符 → 插入 `,`;深度 0 不插(不吞多对象文档);
1013
+ * 2. 归一半角:仅字符串外 `,`→`,`、`:`→`:`、`“`/`”`→`"`;字符串内一字不动;
1014
+ * 3. 删多余闭合:栈已空时出现的 `}`/`]` 直接丢弃(旧实现原样保留 → 必解析失败)。
970
1015
  * 绝不猜测、绝不编造任何字段或值——修不好就照旧抛错。
971
1016
  */
972
1017
  export function repairJsonStructure(input) {
973
1018
  const stack = [];
974
1019
  let inString = false;
975
1020
  let escaped = false;
1021
+ // [2.3.2] afterValue = 上一个字符串外记号是「完整值收尾」(闭合引号/闭合括号/裸 token 结束)。
1022
+ let afterValue = false;
1023
+ // [2.3.2] inToken = 正在读数字或 true/false/null 这类裸 token(须等它结束才可能插逗号)。
1024
+ let inToken = false;
1025
+ // [2.3.2] 字符串定界样式:全角引号开的字符串须由 `”`(或半角 `"`)闭合,
1026
+ // 否则 `{“a”:1}` 的 `”` 会被当作字符串内容吞掉;半角字符串不受影响。
1027
+ let stringUnicode = false;
1028
+ const isTokenChar = (ch) => (ch >= '0' && ch <= '9')
1029
+ || (ch >= 'a' && ch <= 'z')
1030
+ || (ch >= 'A' && ch <= 'Z')
1031
+ || ch === '.' || ch === '+' || ch === '-';
1032
+ const separatorBefore = () => {
1033
+ // 只在「值收尾 → 新值起点」且确有容器时才插逗号;键后接冒号、值后接闭合都不走这里。
1034
+ if (afterValue && stack.length > 0)
1035
+ out += ',';
1036
+ };
976
1037
  let out = '';
977
1038
  for (let i = 0; i < input.length; i += 1) {
978
1039
  const ch = input[i];
@@ -987,9 +1048,10 @@ export function repairJsonStructure(input) {
987
1048
  escaped = true;
988
1049
  continue;
989
1050
  }
990
- if (ch === '"') {
1051
+ if (ch === '"' || (stringUnicode && ch === '”')) {
991
1052
  inString = false;
992
- out += ch;
1053
+ afterValue = true;
1054
+ out += '"';
993
1055
  continue;
994
1056
  }
995
1057
  if (ch === '\n') {
@@ -1011,17 +1073,40 @@ export function repairJsonStructure(input) {
1011
1073
  out += ch;
1012
1074
  continue;
1013
1075
  }
1076
+ if (inToken && !isTokenChar(ch)) {
1077
+ inToken = false;
1078
+ afterValue = true;
1079
+ }
1014
1080
  if (ch === '"') {
1081
+ separatorBefore();
1015
1082
  inString = true;
1083
+ stringUnicode = false;
1084
+ afterValue = false;
1016
1085
  out += ch;
1017
1086
  continue;
1018
1087
  }
1088
+ // [2.3.2] 全角引号 → 半角双引号开字符串(仅字符串外;归一只动标点不动内容)。
1089
+ if (ch === '“' || ch === '”' || ch === '"') {
1090
+ separatorBefore();
1091
+ inString = true;
1092
+ stringUnicode = true;
1093
+ afterValue = false;
1094
+ out += '"';
1095
+ continue;
1096
+ }
1019
1097
  if (ch === '{' || ch === '[') {
1098
+ separatorBefore();
1020
1099
  stack.push(ch);
1100
+ afterValue = false;
1021
1101
  out += ch;
1022
1102
  continue;
1023
1103
  }
1024
1104
  if (ch === '}' || ch === ']') {
1105
+ // [2.3.2] 规则 3:栈空 = 这个闭合符在语法上无处安放,丢弃(旧实现保留 → E 类穿透)。
1106
+ if (stack.length === 0) {
1107
+ afterValue = true;
1108
+ continue;
1109
+ }
1025
1110
  const want = ch === '}' ? '{' : '[';
1026
1111
  while (stack.length > 0 && stack[stack.length - 1] !== want) {
1027
1112
  out += stack.pop() === '{' ? '}' : ']';
@@ -1029,6 +1114,26 @@ export function repairJsonStructure(input) {
1029
1114
  if (stack.length > 0)
1030
1115
  stack.pop();
1031
1116
  out += ch;
1117
+ afterValue = true;
1118
+ continue;
1119
+ }
1120
+ if (ch === ',' || ch === ',') {
1121
+ // [2.3.2] 规则 2:字符串外全角逗号归一为半角。
1122
+ out += ',';
1123
+ afterValue = false;
1124
+ continue;
1125
+ }
1126
+ if (ch === ':' || ch === ':') {
1127
+ // [2.3.2] 规则 2:字符串外全角冒号归一为半角;键后的冒号不是「新值起点」,不插逗号。
1128
+ out += ':';
1129
+ afterValue = false;
1130
+ continue;
1131
+ }
1132
+ if (isTokenChar(ch)) {
1133
+ separatorBefore();
1134
+ inToken = true;
1135
+ afterValue = false;
1136
+ out += ch;
1032
1137
  continue;
1033
1138
  }
1034
1139
  out += ch;
@@ -1040,7 +1145,46 @@ export function repairJsonStructure(input) {
1040
1145
  return stripTrailingCommas(out);
1041
1146
  }
1042
1147
  function stripTrailingCommas(input) {
1043
- return input.replace(/,(\s*[}\]])/g, '$1');
1148
+ /*
1149
+ * [2.3.2][D2-QA-1 修复] 字符串边界感知的尾逗号删除(T3 审查红线发现)。
1150
+ *
1151
+ * 旧实现正则 /,(\s*[}\]])/g 不感知字符串边界,会吃掉字符串值内部的
1152
+ * 「半角逗号+空白+闭括号」——`{"note":"p, } q"}` 被改成 `"p } q"`,是值
1153
+ * 篡改(缺陷自 2.1.0 既有,本补丁 P0 扩能后其可达面被扩大;T3 探针
1154
+ * TAMPER-3 实锤并定性为既有)。现在只有字符串外的逗号才会被删,
1155
+ * 与旧语义一致(只删逗号、保留其间空白与闭括号)。
1156
+ */
1157
+ let inString = false;
1158
+ let escaped = false;
1159
+ let out = '';
1160
+ for (let i = 0; i < input.length; i += 1) {
1161
+ const ch = input[i];
1162
+ if (inString) {
1163
+ out += ch;
1164
+ if (escaped)
1165
+ escaped = false;
1166
+ else if (ch === '\\')
1167
+ escaped = true;
1168
+ else if (ch === '"')
1169
+ inString = false;
1170
+ continue;
1171
+ }
1172
+ if (ch === '"') {
1173
+ inString = true;
1174
+ out += ch;
1175
+ continue;
1176
+ }
1177
+ if (ch === ',') {
1178
+ let j = i + 1;
1179
+ while (j < input.length && input[j].trim() === '')
1180
+ j += 1;
1181
+ const next = input[j];
1182
+ if (next === '}' || next === ']')
1183
+ continue;
1184
+ }
1185
+ out += ch;
1186
+ }
1187
+ return out;
1044
1188
  }
1045
1189
  /** 找到最后一个「成员边界」逗号(在任何嵌套深度上、且不在字符串内)。 */
1046
1190
  function lastMemberComma(input) {
@@ -1079,6 +1223,25 @@ function* truncatedCandidates(input, rounds = 24) {
1079
1223
  yield repairJsonStructure(working);
1080
1224
  }
1081
1225
  }
1226
+ /**
1227
+ * [2.3.2][D2-P1] 定向位置反馈:旧实现回喂只有「末尾 120 字符」,断点在 6KB 文档
1228
+ * 中部时模型依然盲,只能整段重掷(×3 ≈86.9 秒白烧的机制根因之一)。V8 对长输入的
1229
+ * 解析错误带 `at position N`,这里据此从候选文本切出断点 ±60 字符原文随错误一并
1230
+ * 回喂(runtime 的 lastErrors 直接透传该 message),让下一次请求是「定向修复」而
1231
+ * 非「盲目重生成」。短输入的新式消息本身已带上下文,正则不中则原样返回。
1232
+ */
1233
+ function parseFailureHint(candidate, error) {
1234
+ const message = error instanceof Error ? error.message : String(error);
1235
+ const match = /at position (\d+)/.exec(message);
1236
+ if (!match)
1237
+ return '';
1238
+ const position = Math.min(Number(match[1]), candidate.length);
1239
+ const from = Math.max(0, position - 60);
1240
+ const to = Math.min(candidate.length, position + 60);
1241
+ const snippet = candidate.slice(from, to).replace(/\s+/g, ' ');
1242
+ return `;错误位置 ${position},断点附近原文(字符 ${from}-${to}):${JSON.stringify(snippet)}`
1243
+ + '——请只修复该处 JSON 语法后重新输出完整对象,不得改动任何字段值';
1244
+ }
1082
1245
  export function extractJson(text) {
1083
1246
  if (typeof text !== 'string' || text.trim() === '') {
1084
1247
  throw new PlanError('规划器没有返回内容', 'EMPTY_OUTPUT');
@@ -1101,7 +1264,7 @@ export function extractJson(text) {
1101
1264
  const repaired = repairJsonStructure(candidate);
1102
1265
  try {
1103
1266
  const value2 = JSON.parse(repaired);
1104
- console.warn('[dsh-workplan] 规划器 JSON 结构已修复(只补括号/逗号,未改内容)');
1267
+ console.warn('[dsh-workplan] 规划器 JSON 结构已修复(只动括号/逗号/字符串外全角标点,未改内容)');
1105
1268
  return value2;
1106
1269
  }
1107
1270
  catch {
@@ -1116,7 +1279,8 @@ export function extractJson(text) {
1116
1279
  }
1117
1280
  }
1118
1281
  }
1119
- throw new PlanError(`规划器返回的 JSON 无法解析:${error instanceof Error ? error.message : String(error)}`, 'INVALID_JSON');
1282
+ // [2.3.2][D2-P1] 抛出前附断点原文切片:重试请求据此定向修复,不再盲掷全文。
1283
+ throw new PlanError(`规划器返回的 JSON 无法解析:${error instanceof Error ? error.message : String(error)}${parseFailureHint(candidate, error)}`, 'INVALID_JSON');
1120
1284
  }
1121
1285
  }
1122
1286
  export function departmentLabel(id, language = 'zh') {
@@ -1193,6 +1357,8 @@ export function buildPlannerPrompt(taskText, cwd, conversationContext = '', budg
1193
1357
  '- 子任务必须可独立执行、可验收;不要为了凑数拆无意义任务。',
1194
1358
  '- 子任务由子 Agent 独立执行:它们没有派发权限、不能重启服务、不能安装或升级依赖。禁止把「调用 dsh_workplan_dispatch」「重启/停止 dsh web」「安装或升级插件」这类只有主 Agent 才能执行的动作写进子任务;确实需要时,写成“给出结论或建议,由主 Agent 执行”。',
1195
1359
  '- 单个子任务无须在 10 分钟内完成——10 分钟只是拆步规模建议,不是完成期限、也不构成承诺;实际时长由执行专家开工预告协商决定,不设固定完成时间;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1360
+ // [2.3.2][D2-P2] 半角/逗号/括号自检硬约束:与解析层兜底(P0)互为防线,中文模型全角标点高发。
1361
+ '- JSON 只允许半角标点(, : " { } [ ]);对象与数组的相邻成员之间必须有逗号;输出前自检括号成对、每个字符串以半角"闭合。',
1196
1362
  '- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
1197
1363
  '',
1198
1364
  '本轮时间预算(硬事实,请据此规划规模):',
@@ -4566,6 +4732,17 @@ export function resetBlockedStatuses(statuses) {
4566
4732
  */
4567
4733
  if (item?.closure === 'escalated' || item?.closure === 'instructed')
4568
4734
  continue;
4735
+ /*
4736
+ * [2.3.0][T1] 二次超时 = 主 Agent 接手,不再把专家重派一遍。
4737
+ *
4738
+ * 用户要求 2:预估时间超时两次后由主 Agent 接手尚未完成的事,且禁止丢弃
4739
+ * 专家已完成部分。若续跑把这行重置为 pending 重派,等于让新专家从零重做、
4740
+ * 绕开 takeoverBrief 的只读保护——这里直接跳过:行保持 blocked,
4741
+ * takeoverRequired/takeoverBrief/artifacts 保护登记原样保留,由主 Agent
4742
+ * 用 dsh_workplan_update 复核改判(只补缺口)或人工裁决后离开该状态。
4743
+ */
4744
+ if (item?.takeoverRequired === true)
4745
+ continue;
4569
4746
  next = applyStatus(next, item.subtaskId, {
4570
4747
  status: 'pending',
4571
4748
  progress: 0,
@@ -4866,6 +5043,16 @@ leadAgentId = '', leadAgentIdSource = 'none', }) {
4866
5043
  : []),
4867
5044
  // [T3 扩展点·T6] 供 T6 在此行之后追加「完成即时通知」条款(O-1a 插件兜底通道语义);上方三条款为 O-1a①+O-2a+O-4a 合并协议段(矩阵 Z1),既有条款不得删改。
4868
5045
  // [2.2.0][T6/O-1a] 完成即时通知条款(插件兜底通道):完成即报是第一通道(见上方「完成即回报」);插件另设兜底——子任务结算成功后立即向主会话推送一条含子任务 ID、摘要、验收计数与用时的即时通知,不等待整轮结束。兜底不替代主动回报。
5046
+ /*
5047
+ * [2.3.0][T1] 超时放宽告知与二次超时接手条款(用户 2026-11-10 要求 1/2):
5048
+ * 预告会由插件自动转告主 Agent「请把预期时间告知用户」;超时后主 Agent
5049
+ * 放宽时插件会把最新执行时限推送给你;连续两次超时改由主 Agent 接手,
5050
+ * 因此专家任何时候都要把已完成内容及时落盘并在回报中列路径——已完成部分
5051
+ * 会被登记为只读保护,禁止被丢弃。以下既有条款零删改。
5052
+ */
5053
+ '- 预估上报会被插件即时转告主 Agent(含「请把此预期执行时间告知用户」提示),主 Agent 会把你报的预估时间告知用户,让双方都有准备。',
5054
+ '- 超时后主 Agent 放宽时,插件会向你的会话推送【延期告知】:内含最新执行时间与剩余余量,并要求你在保证工作质量的前提下高效率执行——收到通知继续当前工作,不要重新开始;已完成内容及时落盘。',
5055
+ '- 连续两次超时后本行转为「主 Agent 接手」(takeoverRequired):你已完成的产物会被登记为只读保护(禁止丢弃),主 Agent 只继续未完成部分;所以每个阶段都要及时落盘并在回报中列出已完成路径。',
4869
5056
  '',
4870
5057
  '遇阻上报(强制,先于继续动作):',
4871
5058
  '- 出现以下任一情况,第一动作是上报,不是猜测、绕过或静默继续:缺少权限/输入/依赖产物;需求自相矛盾;无法验证;同一命令连续两次失败;需要主 Agent 决定方向。',
package/lib/runtime.js CHANGED
@@ -948,7 +948,9 @@ export async function runPlanner(ctx, options) {
948
948
  message,
949
949
  `输出共 ${lastText.length} 字符,末尾原文:${JSON.stringify(tail)}`,
950
950
  closed
951
- ? '末尾已闭合 → 断点在正文中间,属语法写错(漏逗号/括号不匹配)'
951
+ // [2.3.2][D2-P1] 定向修复指令:message 已含「错误位置 + 断点附近原文」(extractJson
952
+ // 的 parseFailureHint),这里明确要求只修语法、不动内容,替代旧「整段重掷」。
953
+ ? '末尾已闭合 → 断点在正文中间,属语法写错(漏逗号/括号不匹配):请按上文「错误位置/断点附近原文」只修复该处语法,禁止改动字段值与整体结构'
952
954
  : '末尾未闭合(没有结尾 })→ 疑似输出被截断,请给出更紧凑的完整 JSON',
953
955
  ];
954
956
  }
@@ -2576,6 +2578,105 @@ export function extendDeadline(record, subtaskId, extendMs, meta = {}) {
2576
2578
  record.updatedAt = Date.now();
2577
2579
  return { ok: true, deadlineAt, timerRearmed: true, watchdogRearmed: Boolean(handle.watchdog) };
2578
2580
  }
2581
+ /*
2582
+ * [2.3.0][T1] 专家执行时间机制 v2.3.0(用户 2026-11-10 四项要求,全链路):
2583
+ * (a) 预估上报 → 告知用户:recordTimeNotice 落档后向主会话推送「请把预期用时
2584
+ * 转告用户」的即时通知;
2585
+ * (b) 超时 → 放宽 → 告知专家:延期事务成功后把最新执行时限推送给执行中的专家
2586
+ * 子会话,并附「必须在保证工作质量的前提下高效率执行」硬要求;
2587
+ * (c) 二次超时 → 主 Agent 接手:runSubtaskAttempt 的到点收束对每行计数
2588
+ * (timeoutCount),第二次超时置 takeoverRequired,并用 buildTakeoverBrief
2589
+ * 登记专家已完成产物、mergePreservedArtifacts 做「禁止丢弃已完成部分」的
2590
+ * 只读保护合并。
2591
+ * 向后兼容:全部走 StatusEntry 未知字段直写通道(与 deadlineAt/timeJournal
2592
+ * 同族),回放白名单同步透传;不改任何既有判定与既有字段语义。
2593
+ */
2594
+ export const TAKEOVER_AFTER_TIMEOUTS = 2;
2595
+ /**
2596
+ * [2.3.0][T1] 组装「主 Agent 接手包」:已完成部分(专家已落盘产物 + 已登记
2597
+ * artifacts)逐条快照,未完成部分按 outputs 反推。instruction 是硬约束文案:
2598
+ * 禁止丢弃已完成部分——接手只补缺口,不整步重跑、不删除或覆盖专家产物。
2599
+ */
2600
+ export function buildTakeoverBrief(subtask, row, landedRefs, timeoutCount) {
2601
+ const refs = (Array.isArray(landedRefs) ? landedRefs : [])
2602
+ .map((item) => String(item ?? ''))
2603
+ .filter(Boolean)
2604
+ .slice(0, 20);
2605
+ const completedArtifacts = (Array.isArray(row?.artifacts) ? row.artifacts : [])
2606
+ .filter((item) => item?.kind === 'file' && typeof item?.ref === 'string' && item.ref)
2607
+ .map((item) => ({ kind: 'file', ref: item.ref, exists: item.exists !== false }))
2608
+ .slice(0, 20);
2609
+ const outputs = (Array.isArray(subtask?.outputs) ? subtask.outputs : [])
2610
+ .map((item) => String(item ?? ''))
2611
+ .filter(Boolean);
2612
+ const remainingOutputs = outputs.filter((ref) => !refs.includes(ref));
2613
+ return {
2614
+ at: Date.now(),
2615
+ timeoutCount: Number(timeoutCount) || 0,
2616
+ landedRefs: refs,
2617
+ completedArtifacts,
2618
+ remainingOutputs,
2619
+ instruction: '主 Agent 只接手未完成部分:landedRefs/completedArtifacts 是专家已'
2620
+ + '完成并登记保护的产物,只读、禁止丢弃、禁止删除或覆盖、禁止整步重跑;'
2621
+ + '仅继续 remainingOutputs 与未满足的验收标准。',
2622
+ };
2623
+ }
2624
+ /**
2625
+ * [2.3.0][T1] 「禁止丢弃已完成部分」的只读保护合并(A4 硬编码点):
2626
+ * 接手登记的保护清单(takeoverBrief.landedRefs)与行上 artifacts 取并集,
2627
+ * 只增不减——任何后续对 artifacts 的写入都不可能丢掉已完成部分。
2628
+ * 纯函数,可脱离宿主回归。
2629
+ */
2630
+ export function mergePreservedArtifacts(artifacts, preservedRefs) {
2631
+ const list = (Array.isArray(artifacts) ? artifacts : [])
2632
+ .filter((item) => item && typeof item === 'object' && typeof item.ref === 'string')
2633
+ .map((item) => ({ ...item }));
2634
+ const seen = new Set(list.map((item) => String(item.ref)));
2635
+ for (const rawRef of Array.isArray(preservedRefs) ? preservedRefs : []) {
2636
+ const ref = String(rawRef ?? '');
2637
+ if (!ref || seen.has(ref))
2638
+ continue;
2639
+ // 保护条目固定 kind:'file'/exists:true:登记发生在产物确认在盘的时刻。
2640
+ list.push({ kind: 'file', ref, exists: true, preservedByTakeover: true });
2641
+ seen.add(ref);
2642
+ }
2643
+ return list.slice(-40);
2644
+ }
2645
+ /**
2646
+ * [2.3.0][T1] 放宽成功后告知执行中的专家最新时限(A2 的「告知」半边)。
2647
+ * 走 ctx.subagents.sendMessage 与 follow-up 同一投递通道:运行中的子会话在下一
2648
+ * 步收到。投递失败不阻断延期事务(时限已经推移),只留档 record.errors。
2649
+ */
2650
+ async function notifyExpertOfExtension(ctx, agent, record, subtaskId, deadlineAt) {
2651
+ const row = Array.isArray(record?.statuses)
2652
+ ? record.statuses.find((item) => item?.subtaskId === subtaskId)
2653
+ : null;
2654
+ const childId = String(row?.childId ?? '');
2655
+ const service = ctx?.subagents;
2656
+ if (!childId) {
2657
+ return { ok: false, error: '该行没有活跃子会话(childId 缺失),专家续跑时可从状态行 deadlineAt 读取最新时限' };
2658
+ }
2659
+ if (!service || typeof service.sendMessage !== 'function') {
2660
+ return { ok: false, error: '当前部署没有可用的 subagent 服务,无法投递延期告知' };
2661
+ }
2662
+ const remainingMin = Math.max(1, Math.ceil((Number(deadlineAt) - Date.now()) / 60000));
2663
+ const text = `【dsh-workplan·延期告知】子任务 ${subtaskId} 的执行时限已由主 Agent 放宽:`
2664
+ + `最新执行时间为 ${new Date(Number(deadlineAt)).toISOString()}(约剩 ${remainingMin} 分钟)。`
2665
+ + '你必须在保证工作质量的前提下高效率执行:优先推进高价值步骤,已完成内容及时落盘,'
2666
+ + '并在回报中明确区分「已完成 / 未完成」。收到本通知后请继续当前工作,不要重新开始。';
2667
+ try {
2668
+ await service.sendMessage(agent, childId, [{ type: 'text', text }], {});
2669
+ if (row) {
2670
+ const journal = Array.isArray(row.timeJournal) ? row.timeJournal : [];
2671
+ journal.push({ at: Date.now(), action: 'notify-expert', deadlineAt: Number(deadlineAt), by: 'system' });
2672
+ row.timeJournal = journal.slice(-20);
2673
+ }
2674
+ return { ok: true };
2675
+ }
2676
+ catch (error) {
2677
+ return { ok: false, error: truncate(error instanceof Error ? error.message : String(error), 300) };
2678
+ }
2679
+ }
2579
2680
  /*
2580
2681
  * One attempt under a deadline that belongs to that attempt alone.
2581
2682
  *
@@ -2647,7 +2748,15 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
2647
2748
  // 续跑、人工裁决)。Reached only when the child ignored both its idle window
2648
2749
  // and its abort signal; the message says so, otherwise the cause looks like
2649
2750
  // a plain "too slow" and the next investigation goes down the wrong path.
2650
- const message = `子任务 ${subtask.id} 达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 决定延期 / 重试 / 接受,或转新轮续跑、人工裁决)`;
2751
+ // [2.3.0][T1] 计数在组装文案前预读:第 1 次超时的文案要求「必须放宽并
2752
+ // 告知专家」;第 2 次及以后的文案要求「主 Agent 接手、已完成部分只读
2753
+ // 保护、禁止丢弃」。错误文本是结果消息/看板/续跑判定的共同来源,所以
2754
+ // 接手语义必须在这里就落进 message,而不是只进即时通知。
2755
+ const preRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2756
+ const timeoutCountAtFire = Number(preRow?.timeoutCount ?? 0) + 1;
2757
+ const message = timeoutCountAtFire >= TAKEOVER_AFTER_TIMEOUTS
2758
+ ? `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:takeoverRequired——预估时间已两次超时,请主 Agent 直接接手完成尚未完成的部分;专家已完成并落盘的部分已登记只读保护,禁止丢弃、禁止整步重跑)`
2759
+ : `子任务 ${subtask.id} 第 ${timeoutCountAtFire} 次达到协商执行上限(${timeoutMs}ms),已按安全兜底结算(待裁决:请主 Agent 立即放宽(extendMs,放宽后插件自动告知专家最新时限与保证质量高效率要求)/ 重试 / 接受,或转新轮续跑、人工裁决)`;
2651
2760
  try {
2652
2761
  // [1.8.19] Keep the evidence of what already landed on disk.
2653
2762
  const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
@@ -2680,6 +2789,41 @@ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs
2680
2789
  const settleRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
2681
2790
  if (settleRow)
2682
2791
  settleRow.pendingAdjudication = true;
2792
+ /*
2793
+ * [2.3.0][T1] 超时计数与二次超时接手(用户要求 1/2 的机读落点):
2794
+ * 每次到点收束给状态行 timeoutCount +1 并记入 timeJournal(action:'timeout')。
2795
+ * 第 1 次超时 → 即时通知主 Agent「必须放宽(extendMs)并告知专家最新时限」,
2796
+ * 告知专家由延期事务自动投递(notifyExpertOfExtension);
2797
+ * 第 2 次超时 → takeoverRequired=true + buildTakeoverBrief 登记已完成部分,
2798
+ * mergePreservedArtifacts 把已落盘产物并入行 artifacts(只读保护、只增不减),
2799
+ * 主 Agent 接手只继续 remainingOutputs 与未满足验收,禁止丢弃已完成部分。
2800
+ * 计数走 StatusEntry 未知字段直写通道,回放白名单同步透传。
2801
+ */
2802
+ if (settleRow) {
2803
+ const timeoutCount = timeoutCountAtFire;
2804
+ settleRow.timeoutCount = timeoutCount;
2805
+ const timeoutJournal = Array.isArray(settleRow.timeJournal) ? settleRow.timeJournal : [];
2806
+ timeoutJournal.push({ at: Date.now(), action: 'timeout', timeoutCount, by: 'system' });
2807
+ settleRow.timeJournal = timeoutJournal.slice(-20);
2808
+ if (timeoutCount >= TAKEOVER_AFTER_TIMEOUTS) {
2809
+ // 禁止丢弃已完成部分:接手包 + artifacts 只增不减的并集合并。
2810
+ settleRow.takeoverRequired = true;
2811
+ settleRow.takeoverBrief = buildTakeoverBrief(subtask, settleRow, ceilingLanded, timeoutCount);
2812
+ settleRow.artifacts = mergePreservedArtifacts(settleRow.artifacts, settleRow.takeoverBrief.landedRefs);
2813
+ }
2814
+ try {
2815
+ const takeoverText = timeoutCount >= TAKEOVER_AFTER_TIMEOUTS
2816
+ ? `子任务 ${subtask.id} 已第 ${timeoutCount} 次达到协商时限(二次超时):按 2.3.0 机制本行已置「主 Agent 接手」(takeoverRequired)。`
2817
+ + `专家已完成并登记保护的部分(只读、禁止丢弃):${ceilingLanded.slice(0, 8).join('、') || '(见 takeoverBrief)'};`
2818
+ + '请主 Agent 直接接手继续未完成部分,不要整步重跑、不要删除或覆盖已登记产物。'
2819
+ : `子任务 ${subtask.id} 第 1 次达到协商时限:按 2.3.0 机制请主 Agent 尽快用 dsh_workplan_update(extendMs) 放宽,`
2820
+ + '延期成功后插件会自动把最新时限与「保证质量、高效率执行」要求告知专家;如判断无需再放宽,请接手继续未完成部分(已完成产物将只读保护)。';
2821
+ announceSubtaskInterrupt(record, options.session ?? options.agent?.session, subtask.id, takeoverText);
2822
+ }
2823
+ catch {
2824
+ // 通知失败不影响结算(与预警同一纪律)。
2825
+ }
2826
+ }
2683
2827
  record.updatedAt = Date.now();
2684
2828
  }
2685
2829
  catch (error) {
@@ -2920,6 +3064,23 @@ export function modelStatusLines(statuses) {
2920
3064
  timeWarning: item.timeWarning ?? null,
2921
3065
  timeJournal: Array.isArray(item.timeJournal) ? item.timeJournal.slice(-10) : [],
2922
3066
  pendingAdjudication: item.pendingAdjudication === true,
3067
+ // [2.3.0][T1] 预估上报(A1)也要进模型可读面:主 Agent 告知用户前先读这里。
3068
+ timeNotice: item.timeNotice ?? null,
3069
+ /*
3070
+ * [2.3.0][T1] 超时计数 / 二次超时接手进入模型可读面:主 Agent 一眼能看出
3071
+ * 该行第几次超时、是否必须接手、接手包里哪些是只读保护的已完成产物。
3072
+ */
3073
+ timeoutCount: Number(item.timeoutCount ?? 0),
3074
+ takeoverRequired: item.takeoverRequired === true,
3075
+ takeoverBrief: item.takeoverBrief ?? null,
3076
+ /*
3077
+ * [2.3.0][T1] 已完成产物的只读保护登记必须进模型可读面:statusTool 的行
3078
+ * 来自本函数,此前不序列化 artifacts,导致 takeoverRequired 的「禁止丢弃
3079
+ * 已完成部分」清单对主 Agent 不可见。只透出对象形条目,照录不改写。
3080
+ */
3081
+ artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
3082
+ .filter((entry) => entry && typeof entry === 'object' && typeof entry.ref === 'string')
3083
+ .map((entry) => ({ ...entry })),
2923
3084
  /*
2924
3085
  * [2.2.0][T3/O-2a] 子→主预告通道的结论必须进入模型可读面。
2925
3086
  *
@@ -3854,7 +4015,7 @@ export function reconstructFromSession(session, targetPlanId) {
3854
4015
  const rebuiltRow = snap.statuses.find((item) => item?.subtaskId === entry?.subtaskId);
3855
4016
  if (!rebuiltRow || !isRecord(entry))
3856
4017
  continue;
3857
- for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
4018
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
3858
4019
  if (entry[field] !== undefined)
3859
4020
  rebuiltRow[field] = entry[field];
3860
4021
  }
@@ -3955,6 +4116,23 @@ export function reconstructFromSession(session, targetPlanId) {
3955
4116
  });
3956
4117
  continue;
3957
4118
  }
4119
+ /*
4120
+ * [2.3.0][hotfix] 回放兼容「已回报行 + 旧版 closure:'done' 错误快照」(用户 2026-11-10 截图:
4121
+ * wp-3080d01d T6/T7「非法闭环迁移:reported → done」回放忽略)。
4122
+ *
4123
+ * 2.0.4 之前 live 侧 applyStatus 把 reported 行的 closure 误写回 'done',durable 改判
4124
+ * 消息因此嵌着这个错误快照。2.2.6 D-1 给回放补了 closure 透传,但没有豁免这一组合:
4125
+ * 回放大方把 'done' 当显式闭环意图传给迁移表 → reported → done 被拒 → 整条改判
4126
+ * (含 verification/acceptance 证据)被裸 catch 吞掉,重启后行退回缺证据态。
4127
+ *
4128
+ * 口径与 2.0.4 live 侧镜像:事件 closure='done' 且当前行 closure='reported' 时,这是
4129
+ * 「复核补齐」而非「退回未回报」,丢弃该显式值,让 done 分支按 2.0.4 保留已回报事实。
4130
+ * 其余透传分支(escalated/instructed 等,D-1 语义)零改动。
4131
+ */
4132
+ const preReplayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4133
+ const replayClosure = typeof update.closure === 'string'
4134
+ ? (update.closure === 'done' && preReplayRow?.closure === 'reported' ? undefined : update.closure)
4135
+ : undefined;
3958
4136
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
3959
4137
  /*
3960
4138
  * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
@@ -3973,7 +4151,7 @@ export function reconstructFromSession(session, targetPlanId) {
3973
4151
  * 重启后「待指示」行永久卡死(2026-11-08 wp-3c8c84b2 T2 实证,
3974
4152
  * 见 artifacts/2.2.5-post-restart-regression.md §4 D-1)。
3975
4153
  */
3976
- closure: typeof update.closure === 'string' ? update.closure : undefined,
4154
+ closure: replayClosure,
3977
4155
  progress: typeof update.progress === 'number' ? update.progress : undefined,
3978
4156
  summary: typeof update.note === 'string' ? update.note : undefined,
3979
4157
  // [1.8.13] Evidence written through the update tool must survive replay.
@@ -4024,7 +4202,7 @@ export function reconstructFromSession(session, targetPlanId) {
4024
4202
  */
4025
4203
  const replayRow = snap.statuses.find((item) => item?.subtaskId === update.subtaskId);
4026
4204
  if (replayRow) {
4027
- for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication']) {
4205
+ for (const field of ['deadlineAt', 'timeNotice', 'timeWarning', 'timeJournal', 'pendingAdjudication', 'timeoutCount', 'takeoverRequired', 'takeoverBrief']) {
4028
4206
  if (update[field] !== undefined)
4029
4207
  replayRow[field] = update[field];
4030
4208
  }
@@ -4628,7 +4806,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4628
4806
  * 路由分支,按 T4 直写通道写行(StatusEntry 保留未知字段;回放白名单已透传
4629
4807
  * timeNotice,刷新后不丢)。
4630
4808
  */
4631
- function recordTimeNotice(record, subtaskId, notice) {
4809
+ function recordTimeNotice(record, subtaskId, notice, session) {
4632
4810
  const row = Array.isArray(record?.statuses)
4633
4811
  ? record.statuses.find((item) => item?.subtaskId === subtaskId)
4634
4812
  : null;
@@ -4652,6 +4830,24 @@ export function createWorkplanRuntime(ctx, options = {}) {
4652
4830
  });
4653
4831
  row.timeJournal = journal.slice(-20);
4654
4832
  record.updatedAt = at;
4833
+ /*
4834
+ * [2.3.0][T1] 预估上报 → 告知用户(用户要求 1 的前半段闭环):专家的开工
4835
+ * 预告落档后,插件立即向主会话推送一条即时通知,明确「请把此预期执行
4836
+ * 时间告知用户」;新预告覆盖旧预告(每条新预告各通知一次,与「开工预告」
4837
+ * 协议一致)。通知是观测设施:写失败只留档 errors,绝不影响记录与执行。
4838
+ */
4839
+ if (session) {
4840
+ try {
4841
+ appendUserMessage(session, `【dsh-workplan·专家预估上报】子任务 ${subtaskId} 的执行专家`
4842
+ + `预估执行时间 ${Number(notice?.declaredMinutes)} 分钟`
4843
+ + (reason ? `(${reason})` : '')
4844
+ + `;请把此预期执行时间告知用户。若执行中超时,请主 Agent 放宽(extendMs)`
4845
+ + '并告知专家最新时限,连续两次超时则由主 Agent 接手未完成部分(已完成产物只读保护,禁止丢弃)。');
4846
+ }
4847
+ catch (error) {
4848
+ record.errors = [...(record.errors ?? []), `${subtaskId} 预估上报通知写入失败:${truncate(String(error?.message ?? error), 200)}`].slice(-20);
4849
+ }
4850
+ }
4655
4851
  }
4656
4852
  async function updateStatus(agent, args) {
4657
4853
  const session = agent?.session;
@@ -4829,7 +5025,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4829
5025
  * 指示失败不该留下一笔「专家已预告」的记录。
4830
5026
  */
4831
5027
  if (hasTimeNotice && instructed?.ok !== false)
4832
- recordTimeNotice(record, subtaskId, timeNoticeArg);
5028
+ recordTimeNotice(record, subtaskId, timeNoticeArg, session);
4833
5029
  return instructed;
4834
5030
  }
4835
5031
  if (current?.closure === 'escalated') {
@@ -4896,10 +5092,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
4896
5092
  };
4897
5093
  }
4898
5094
  extension = extended;
5095
+ /*
5096
+ * [2.3.0][T1] 用户要求 1 后半段:放宽成功后必须把「最新执行时间」告知
5097
+ * 专家,同时附「必须在保证工作质量的前提下高效率执行」硬要求,让专家
5098
+ * 有准备(收到通知继续当前工作,不重新开始)。投递失败不回滚延期——
5099
+ * 时限已经推移,只是告知通道未达:留档 errors,回执带 childNotified
5100
+ * 供主 Agent 决定是否用 dsh_workplan_followup 补发。
5101
+ */
5102
+ extension.childNotified = (await notifyExpertOfExtension(ctx, agent, record, subtaskId, extension.deadlineAt)).ok;
4899
5103
  }
4900
5104
  if (!statusRequested) {
4901
5105
  if (hasTimeNotice)
4902
- recordTimeNotice(record, subtaskId, timeNoticeArg);
5106
+ recordTimeNotice(record, subtaskId, timeNoticeArg, session);
4903
5107
  /*
4904
5108
  * 纯时限事务到此结束。方案 §2.2 效果 3:状态行 revision +1(延期/预告也是
4905
5109
  * 行变更,同样受 STALE_WRITE 乐观锁保护);状态与判定一个字段都不改。
@@ -4925,6 +5129,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
4925
5129
  deadlineAt: extension.deadlineAt,
4926
5130
  timerRearmed: extension.timerRearmed,
4927
5131
  watchdogRearmed: extension.watchdogRearmed,
5132
+ childNotified: extension.childNotified === true,
4928
5133
  }
4929
5134
  : {}),
4930
5135
  ...(hasTimeNotice ? { timeNotice: written?.timeNotice ?? null } : {}),
@@ -4972,12 +5177,25 @@ export function createWorkplanRuntime(ctx, options = {}) {
4972
5177
  revision,
4973
5178
  updatedBy: 'agent',
4974
5179
  });
5180
+ /*
5181
+ * [2.3.0][T1] 禁止丢弃已完成部分(A4 的第二个硬编码保护点):接手行
5182
+ * (takeoverRequired)后续任何一次 artifacts 写入,都把 takeoverBrief 登记
5183
+ * 的保护产物并集合并回来——只增不减,主 Agent 改判时不可能删掉专家已完成
5184
+ * 的产物清单,只能在其基础上补缺口。
5185
+ */
5186
+ if (args?.artifacts !== undefined) {
5187
+ const protectedRow = record.statuses.find((item) => item?.subtaskId === subtaskId);
5188
+ if (protectedRow?.takeoverRequired === true && Array.isArray(protectedRow?.takeoverBrief?.landedRefs)
5189
+ && protectedRow.takeoverBrief.landedRefs.length > 0) {
5190
+ protectedRow.artifacts = mergePreservedArtifacts(protectedRow.artifacts, protectedRow.takeoverBrief.landedRefs);
5191
+ }
5192
+ }
4975
5193
  /*
4976
5194
  * [2.2.0][T5/O-4c] 带 status 的调用同时带 timeNotice 时,预告记录在改判落行
4977
5195
  * 之后写入:applyStatus 抛错(如非法 verification)时不会留下半写的预告。
4978
5196
  */
4979
5197
  if (hasTimeNotice)
4980
- recordTimeNotice(record, subtaskId, timeNoticeArg);
5198
+ recordTimeNotice(record, subtaskId, timeNoticeArg, session);
4981
5199
  if (status === 'blocked') {
4982
5200
  record.statuses = markDependentsBlocked(record.plan, record.statuses, subtaskId, { reason: summary || '主 Agent 标记受阻' });
4983
5201
  }