dsh-workplan 2.3.0 → 2.3.9

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
@@ -211,6 +211,75 @@ export const LIKELIHOODS = Object.freeze(['low', 'medium', 'high'])
211
211
  export const REASONING_EFFORTS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max'])
212
212
  export const DEFAULT_REASONING_EFFORT = 'high'
213
213
 
214
+ /*
215
+ * [2.3.9][T3] LLM 家族静态规则(用户 2026-11-10 强制要求 1/2,主 Agent 权威口径)。
216
+ *
217
+ * 单一事实源:家族判定与等级集合只在本处定义;runtime(派发/规划入口)、
218
+ * replan(校验)、client(UI Pill)一律从这里取数,禁止第二份表。
219
+ *
220
+ * 用户规则原文:
221
+ * 1. 字母 qwen 开头的模型,推理等级只包括 low、medium、xhigh——轻度任务
222
+ * 使用 low,比较复杂的任务使用 medium,非常复杂的任务使用 xhigh。
223
+ * 2. 非 qwen 开头的其他大模型,推理等级只包括 low、high、max——轻度任务
224
+ * 使用 low,比较复杂的任务使用 high,非常复杂的任务使用 max。
225
+ *
226
+ * 与存储全集的关系(不得删档):REASONING_EFFORTS 五档仍是**存储全集**(计划
227
+ * JSON、序列化回放、旧计划的合法域);本表是**执行前约束**——派发/规划发送
228
+ * 前按当前模型家族收窄,再与宿主能力清单取交集钳制(两段各自留痕)。
229
+ * 模型名缺失 ⇒ classifyModelFamily 返回 null ⇒ 不施加静态约束,保持旧行为
230
+ * (与 [2.2.7]「无从判定⇒不阻断」同风格,防凭空收紧误伤五档全支持模型)。
231
+ */
232
+ export type ModelFamily = 'qwen' | 'other'
233
+ export const QWEN_MODEL_EFFORTS: readonly string[] = Object.freeze(['low', 'medium', 'xhigh'])
234
+ export const OTHER_MODEL_EFFORTS: readonly string[] = Object.freeze(['low', 'high', 'max'])
235
+
236
+ /** 判定模型家族:qwen 开头(trim+小写)→ 'qwen';其余非空 → 'other';空/缺失 → null(不约束)。 */
237
+ export function classifyModelFamily(modelId?: string | null): ModelFamily | null {
238
+ const normalized = String(modelId ?? '').trim().toLowerCase()
239
+ if (!normalized) return null
240
+ return normalized.startsWith('qwen') ? 'qwen' : 'other'
241
+ }
242
+
243
+ /** 家族 → 允许等级集合(用户要求 1/2 硬白名单);未知家族 → null = 不施加约束。 */
244
+ export function effortsForModelFamily(family?: ModelFamily | null): readonly string[] | null {
245
+ if (family === 'qwen') return QWEN_MODEL_EFFORTS
246
+ if (family === 'other') return OTHER_MODEL_EFFORTS
247
+ return null
248
+ }
249
+
250
+ /** 一步式:按模型 id 得到等级集合;模型名缺失返回 null(不约束)。 */
251
+ export function allowedEffortsForModel(modelId?: string | null): readonly string[] | null {
252
+ return effortsForModelFamily(classifyModelFamily(modelId))
253
+ }
254
+
255
+ /**
256
+ * 复杂度 → 档位映射表(要求 1/2 的「轻度/比较复杂/非常复杂」数值化;
257
+ * 部门负责人与专家/组员选档的官方依据,要求 5)。
258
+ */
259
+ export type TaskComplexity = 'light' | 'moderate' | 'heavy'
260
+ export const COMPLEXITY_EFFORT_BY_FAMILY: Readonly<Record<ModelFamily, Record<TaskComplexity, string>>> =
261
+ Object.freeze({
262
+ qwen: Object.freeze({ light: 'low', moderate: 'medium', heavy: 'xhigh' }),
263
+ other: Object.freeze({ light: 'low', moderate: 'high', heavy: 'max' }),
264
+ })
265
+
266
+ /** 按家族+复杂度取应使用档位;家族未知返回 null。 */
267
+ export function effortForComplexity(family: ModelFamily | null, complexity: TaskComplexity): string | null {
268
+ if (!family) return null
269
+ return COMPLEXITY_EFFORT_BY_FAMILY[family][complexity]
270
+ }
271
+
272
+ /** 集合内最高档(强度序与 runtime EFFORT_STRENGTH_ORDER 同源);空集合返回 null。 */
273
+ export function highestEffortOf(levels: readonly string[] | null): string | null {
274
+ if (!levels || levels.length === 0) return null
275
+ const order = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']
276
+ let best: string | null = null
277
+ for (const id of levels) {
278
+ if (best === null || order.indexOf(id) > order.indexOf(best)) best = id
279
+ }
280
+ return best
281
+ }
282
+
214
283
  export const DEPARTMENTS = Object.freeze({
215
284
  engineering: { zh: '工程研发', en: 'Engineering' },
216
285
  research: { zh: '研究分析', en: 'Research' },
@@ -251,10 +320,45 @@ export function truncate(value: any, max: any) {
251
320
 
252
321
  export function messageText(message: any) {
253
322
  if (!message || !Array.isArray(message.content)) return ''
254
- return message.content
323
+ const texts = message.content
255
324
  .filter((block: any) => block && block.type === 'text' && typeof block.text === 'string')
256
325
  .map((block: any) => block.text)
257
- .join('\n')
326
+ /*
327
+ * [2.3.1][D1] 附件事实渲染(用户 2026-11-10 点名的严重缺陷:规划器与 fresh
328
+ * 子 Agent 看不见用户图片)。
329
+ *
330
+ * 旧实现只收 text 块:image/file 块的 attachment 元数据(attachmentId/名称/
331
+ * 尺寸)在到达规划器 taskText 之前就被整块丢弃,专家被迫 escalate 请示
332
+ * 「截图在哪」,往返吃掉整段时间预算(wp-73bb2cd4 事故实证:修复主链 8 分钟、
333
+ * 往返 17 分钟)。
334
+ *
335
+ * 现在把附件渲染成一行标注并入文本面,taskText→taskAnchor→派发锚点块→回放
336
+ * 上下文全部同源受益;标注含 attachment-id(官方读图工具接受该 id 作为
337
+ * path),接收方可直接读取,不再靠猜。
338
+ * 消费方安全审计(2026-11-10):plan/result/cancel/update 四类 marker 解析
339
+ * 消息永不含图片块;replan/supersede 为用户消息子串匹配,附加行零误伤。
340
+ */
341
+ const notes = message.content
342
+ .filter((block: any) => block && (block.type === 'image' || block.type === 'file' || block.type === 'document') && (block.attachment ?? block.file))
343
+ .map((block: any) => renderAttachmentNote(block))
344
+ .filter((line: string) => line !== '')
345
+ if (notes.length === 0) return texts.join('\n')
346
+ return [...texts, ...notes].join('\n')
347
+ }
348
+
349
+ /** [2.3.1][D1] 单个附件块的只读标注行;元数据缺失时返回空串(不泄漏、不猜测)。 */
350
+ function renderAttachmentNote(block: any) {
351
+ const att = block.attachment ?? block.file ?? {}
352
+ const id = typeof att.attachmentId === 'string' ? att.attachmentId : ''
353
+ const name = typeof att.name === 'string' ? att.name : (typeof att.filename === 'string' ? att.filename : '')
354
+ if (!id && !name) return ''
355
+ const media = typeof att.mediaType === 'string' ? att.mediaType : ''
356
+ const size = Number.isFinite(Number(att.width)) && Number.isFinite(Number(att.height))
357
+ ? `|${String(att.width)}x${String(att.height)}` : ''
358
+ return `[用户附件] ${block.type === 'image' ? '图片' : '文件'} "${name || '未命名'}"`
359
+ + (media ? `|mediaType=${media}` : '') + size
360
+ + (id ? `|attachment-id: ${id}` : '')
361
+ + '|如需其内容:把 attachment-id 作为 path 传给可用的读图/视觉工具直接读取,禁止凭空猜测附件内容。'
258
362
  }
259
363
 
260
364
  /*
@@ -988,10 +1092,13 @@ function checkPlanGraph(plan: any, errors: string[]) {
988
1092
  /**
989
1093
  * Validate an untrusted planner object. Never throws for malformed input.
990
1094
  *
991
- * @param {unknown} raw
992
- * @returns {{ok: true, plan: object} | {ok: false, errors: string[]}}
1095
+ * [2.3.9][T3] options.allowedEfforts:当前模型家族的等级集合(真源
1096
+ * allowedEffortsForModel)。传入时,规划器**显式写出**的集合外档位直接拒绝并
1097
+ * 点名(事前约束,要求 1/2;缺失/回落的 high 不在此列——派发侧静态收窄会带
1098
+ * qwen-rule 留痕降级,向后兼容旧回放零迁移)。null/未传 ⇒ 不施加(回放、旧
1099
+ * 调用零行为变化)。REASONING_EFFORTS 五档仍是存储全集,不得删档。
993
1100
  */
994
- export function validatePlan(raw: any) {
1101
+ export function validatePlan(raw: any, options?: { allowedEfforts?: readonly string[] | null }) {
995
1102
  if (!isRecord(raw)) {
996
1103
  return { ok: false, errors: ['计划必须是 JSON 对象'] }
997
1104
  }
@@ -1008,6 +1115,31 @@ export function validatePlan(raw: any) {
1008
1115
  verification: readVerification(raw.verification, errors),
1009
1116
  practiceLoop: readPracticeLoop(raw.practiceLoop, errors),
1010
1117
  }
1118
+ const allowedEfforts = options && options.allowedEfforts ? options.allowedEfforts : null
1119
+ if (allowedEfforts !== null && Array.isArray(raw.stages)) {
1120
+ /*
1121
+ * [2.3.9][T3/llm-rules] 模型感知的校验收窄(用户要求 1/2,主 Agent 口径):
1122
+ * 五档仍是存储全集(不得删档),但调用方传入当前模型家族等级集合时,
1123
+ * 规划器**显式写出**的集合外档位拒绝并点名字段——错误经重试回路回喂
1124
+ * 规划器自纠,属于事前约束而非派发后静默钳制。缺失档位不在此拦(由
1125
+ * readSubtasks 回落 high、派发侧静态收窄带 qwen-rule 留痕降级);未传
1126
+ * options 的调用(回放/旧路径)零行为变化。
1127
+ */
1128
+ for (let stageIndex = 0; stageIndex < raw.stages.length; stageIndex += 1) {
1129
+ const stage = raw.stages[stageIndex]
1130
+ if (!isRecord(stage) || !Array.isArray(stage.subtasks)) continue
1131
+ for (let subtaskIndex = 0; subtaskIndex < stage.subtasks.length; subtaskIndex += 1) {
1132
+ const subtask = stage.subtasks[subtaskIndex]
1133
+ if (!isRecord(subtask)) continue
1134
+ const effort = subtask.reasoningEffort
1135
+ if (effort !== undefined && effort !== null
1136
+ && !(typeof effort === 'string' && allowedEfforts.includes(effort))) {
1137
+ push(errors, `stages[${stageIndex}].subtasks[${subtaskIndex}].reasoningEffort`,
1138
+ `"${String(effort)}" 不在当前模型家族的推理等级集合 {${allowedEfforts.join(' / ')}} 内(qwen 系仅 low / medium / xhigh;非 qwen 系仅 low / high / max),必须改用集合内档位或删除该字段`)
1139
+ }
1140
+ }
1141
+ }
1142
+ }
1011
1143
  checkPlanGraph(plan, errors)
1012
1144
  if (errors.length > 0) return { ok: false, errors }
1013
1145
  return { ok: true, plan }
@@ -1040,12 +1172,37 @@ export function flattenSubtasks(plan: any): Array<{ stage: any; subtask: any }>
1040
1172
  * 规划器返回的 JSON 常见三类损伤:少一个 `}`、多一个尾逗号、字符串里有裸换行。
1041
1173
  * 旧实现直接 JSON.parse,一个字符之差就抛 INVALID_JSON,整个计划降级。
1042
1174
  * 这里做的是纯结构修复:配对括号、去掉尾逗号、把字符串里的裸控制符转义。
1175
+ *
1176
+ * [2.3.2][D2-P0] D2 现场(qwen3.8-flash INVALID_JSON ×3、86.9 秒白烧)实测穿透的
1177
+ * 三类损伤——成员间漏逗号、字符串外全角标点、多余闭合括号——在同一趟扫描内补齐。
1178
+ * 旧实现只「补」不「插/删/归一」,这三类必然失败后靠全量重掷碰运气。三条新规则
1179
+ * 全部满足「只修结构、绝不碰内容」红线:
1180
+ * 1. 插逗号:容器内(栈非空)值结束符(`"`/`}`/`]`/数字/true|false|null)之后
1181
+ * 紧邻下一个起点 token 且无分隔符 → 插入 `,`;深度 0 不插(不吞多对象文档);
1182
+ * 2. 归一半角:仅字符串外 `,`→`,`、`:`→`:`、`“`/`”`→`"`;字符串内一字不动;
1183
+ * 3. 删多余闭合:栈已空时出现的 `}`/`]` 直接丢弃(旧实现原样保留 → 必解析失败)。
1043
1184
  * 绝不猜测、绝不编造任何字段或值——修不好就照旧抛错。
1044
1185
  */
1045
1186
  export function repairJsonStructure(input: string): string {
1046
1187
  const stack: string[] = []
1047
1188
  let inString = false
1048
1189
  let escaped = false
1190
+ // [2.3.2] afterValue = 上一个字符串外记号是「完整值收尾」(闭合引号/闭合括号/裸 token 结束)。
1191
+ let afterValue = false
1192
+ // [2.3.2] inToken = 正在读数字或 true/false/null 这类裸 token(须等它结束才可能插逗号)。
1193
+ let inToken = false
1194
+ // [2.3.2] 字符串定界样式:全角引号开的字符串须由 `”`(或半角 `"`)闭合,
1195
+ // 否则 `{“a”:1}` 的 `”` 会被当作字符串内容吞掉;半角字符串不受影响。
1196
+ let stringUnicode = false
1197
+ const isTokenChar = (ch: string) =>
1198
+ (ch >= '0' && ch <= '9')
1199
+ || (ch >= 'a' && ch <= 'z')
1200
+ || (ch >= 'A' && ch <= 'Z')
1201
+ || ch === '.' || ch === '+' || ch === '-'
1202
+ const separatorBefore = () => {
1203
+ // 只在「值收尾 → 新值起点」且确有容器时才插逗号;键后接冒号、值后接闭合都不走这里。
1204
+ if (afterValue && stack.length > 0) out += ','
1205
+ }
1049
1206
  let out = ''
1050
1207
  for (let i = 0; i < input.length; i += 1) {
1051
1208
  const ch = input[i] as string
@@ -1060,9 +1217,10 @@ export function repairJsonStructure(input: string): string {
1060
1217
  escaped = true
1061
1218
  continue
1062
1219
  }
1063
- if (ch === '"') {
1220
+ if (ch === '"' || (stringUnicode && ch === '”')) {
1064
1221
  inString = false
1065
- out += ch
1222
+ afterValue = true
1223
+ out += '"'
1066
1224
  continue
1067
1225
  }
1068
1226
  if (ch === '\n') {
@@ -1084,23 +1242,66 @@ export function repairJsonStructure(input: string): string {
1084
1242
  out += ch
1085
1243
  continue
1086
1244
  }
1245
+ if (inToken && !isTokenChar(ch)) {
1246
+ inToken = false
1247
+ afterValue = true
1248
+ }
1087
1249
  if (ch === '"') {
1250
+ separatorBefore()
1088
1251
  inString = true
1252
+ stringUnicode = false
1253
+ afterValue = false
1089
1254
  out += ch
1090
1255
  continue
1091
1256
  }
1257
+ // [2.3.2] 全角引号 → 半角双引号开字符串(仅字符串外;归一只动标点不动内容)。
1258
+ if (ch === '“' || ch === '”' || ch === '"') {
1259
+ separatorBefore()
1260
+ inString = true
1261
+ stringUnicode = true
1262
+ afterValue = false
1263
+ out += '"'
1264
+ continue
1265
+ }
1092
1266
  if (ch === '{' || ch === '[') {
1267
+ separatorBefore()
1093
1268
  stack.push(ch)
1269
+ afterValue = false
1094
1270
  out += ch
1095
1271
  continue
1096
1272
  }
1097
1273
  if (ch === '}' || ch === ']') {
1274
+ // [2.3.2] 规则 3:栈空 = 这个闭合符在语法上无处安放,丢弃(旧实现保留 → E 类穿透)。
1275
+ if (stack.length === 0) {
1276
+ afterValue = true
1277
+ continue
1278
+ }
1098
1279
  const want = ch === '}' ? '{' : '['
1099
1280
  while (stack.length > 0 && stack[stack.length - 1] !== want) {
1100
1281
  out += stack.pop() === '{' ? '}' : ']'
1101
1282
  }
1102
1283
  if (stack.length > 0) stack.pop()
1103
1284
  out += ch
1285
+ afterValue = true
1286
+ continue
1287
+ }
1288
+ if (ch === ',' || ch === ',') {
1289
+ // [2.3.2] 规则 2:字符串外全角逗号归一为半角。
1290
+ out += ','
1291
+ afterValue = false
1292
+ continue
1293
+ }
1294
+ if (ch === ':' || ch === ':') {
1295
+ // [2.3.2] 规则 2:字符串外全角冒号归一为半角;键后的冒号不是「新值起点」,不插逗号。
1296
+ out += ':'
1297
+ afterValue = false
1298
+ continue
1299
+ }
1300
+ if (isTokenChar(ch)) {
1301
+ separatorBefore()
1302
+ inToken = true
1303
+ afterValue = false
1304
+ out += ch
1104
1305
  continue
1105
1306
  }
1106
1307
  out += ch
@@ -1111,7 +1312,41 @@ export function repairJsonStructure(input: string): string {
1111
1312
  }
1112
1313
 
1113
1314
  function stripTrailingCommas(input: string): string {
1114
- return input.replace(/,(\s*[}\]])/g, '$1')
1315
+ /*
1316
+ * [2.3.2][D2-QA-1 修复] 字符串边界感知的尾逗号删除(T3 审查红线发现)。
1317
+ *
1318
+ * 旧实现正则 /,(\s*[}\]])/g 不感知字符串边界,会吃掉字符串值内部的
1319
+ * 「半角逗号+空白+闭括号」——`{"note":"p, } q"}` 被改成 `"p } q"`,是值
1320
+ * 篡改(缺陷自 2.1.0 既有,本补丁 P0 扩能后其可达面被扩大;T3 探针
1321
+ * TAMPER-3 实锤并定性为既有)。现在只有字符串外的逗号才会被删,
1322
+ * 与旧语义一致(只删逗号、保留其间空白与闭括号)。
1323
+ */
1324
+ let inString = false
1325
+ let escaped = false
1326
+ let out = ''
1327
+ for (let i = 0; i < input.length; i += 1) {
1328
+ const ch = input[i] as string
1329
+ if (inString) {
1330
+ out += ch
1331
+ if (escaped) escaped = false
1332
+ else if (ch === '\\') escaped = true
1333
+ else if (ch === '"') inString = false
1334
+ continue
1335
+ }
1336
+ if (ch === '"') {
1337
+ inString = true
1338
+ out += ch
1339
+ continue
1340
+ }
1341
+ if (ch === ',') {
1342
+ let j = i + 1
1343
+ while (j < input.length && (input[j] as string).trim() === '') j += 1
1344
+ const next = input[j]
1345
+ if (next === '}' || next === ']') continue
1346
+ }
1347
+ out += ch
1348
+ }
1349
+ return out
1115
1350
  }
1116
1351
 
1117
1352
  /** 找到最后一个「成员边界」逗号(在任何嵌套深度上、且不在字符串内)。 */
@@ -1147,6 +1382,25 @@ function* truncatedCandidates(input: string, rounds = 24): Generator<string> {
1147
1382
  }
1148
1383
  }
1149
1384
 
1385
+ /**
1386
+ * [2.3.2][D2-P1] 定向位置反馈:旧实现回喂只有「末尾 120 字符」,断点在 6KB 文档
1387
+ * 中部时模型依然盲,只能整段重掷(×3 ≈86.9 秒白烧的机制根因之一)。V8 对长输入的
1388
+ * 解析错误带 `at position N`,这里据此从候选文本切出断点 ±60 字符原文随错误一并
1389
+ * 回喂(runtime 的 lastErrors 直接透传该 message),让下一次请求是「定向修复」而
1390
+ * 非「盲目重生成」。短输入的新式消息本身已带上下文,正则不中则原样返回。
1391
+ */
1392
+ function parseFailureHint(candidate: string, error: unknown): string {
1393
+ const message = error instanceof Error ? error.message : String(error)
1394
+ const match = /at position (\d+)/.exec(message)
1395
+ if (!match) return ''
1396
+ const position = Math.min(Number(match[1]), candidate.length)
1397
+ const from = Math.max(0, position - 60)
1398
+ const to = Math.min(candidate.length, position + 60)
1399
+ const snippet = candidate.slice(from, to).replace(/\s+/g, ' ')
1400
+ return `;错误位置 ${position},断点附近原文(字符 ${from}-${to}):${JSON.stringify(snippet)}`
1401
+ + '——请只修复该处 JSON 语法后重新输出完整对象,不得改动任何字段值'
1402
+ }
1403
+
1150
1404
  export function extractJson(text: any) {
1151
1405
  if (typeof text !== 'string' || text.trim() === '') {
1152
1406
  throw new PlanError('规划器没有返回内容', 'EMPTY_OUTPUT')
@@ -1168,7 +1422,7 @@ export function extractJson(text: any) {
1168
1422
  const repaired = repairJsonStructure(candidate)
1169
1423
  try {
1170
1424
  const value2 = JSON.parse(repaired)
1171
- console.warn('[dsh-workplan] 规划器 JSON 结构已修复(只补括号/逗号,未改内容)')
1425
+ console.warn('[dsh-workplan] 规划器 JSON 结构已修复(只动括号/逗号/字符串外全角标点,未改内容)')
1172
1426
  return value2
1173
1427
  } catch {
1174
1428
  for (const attempt of truncatedCandidates(repaired)) {
@@ -1181,7 +1435,8 @@ export function extractJson(text: any) {
1181
1435
  }
1182
1436
  }
1183
1437
  }
1184
- throw new PlanError(`规划器返回的 JSON 无法解析:${error instanceof Error ? error.message : String(error)}`, 'INVALID_JSON')
1438
+ // [2.3.2][D2-P1] 抛出前附断点原文切片:重试请求据此定向修复,不再盲掷全文。
1439
+ throw new PlanError(`规划器返回的 JSON 无法解析:${error instanceof Error ? error.message : String(error)}${parseFailureHint(candidate, error)}`, 'INVALID_JSON')
1185
1440
  }
1186
1441
  }
1187
1442
 
@@ -1260,6 +1515,8 @@ export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext:
1260
1515
  '- 子任务必须可独立执行、可验收;不要为了凑数拆无意义任务。',
1261
1516
  '- 子任务由子 Agent 独立执行:它们没有派发权限、不能重启服务、不能安装或升级依赖。禁止把「调用 dsh_workplan_dispatch」「重启/停止 dsh web」「安装或升级插件」这类只有主 Agent 才能执行的动作写进子任务;确实需要时,写成“给出结论或建议,由主 Agent 执行”。',
1262
1517
  '- 单个子任务无须在 10 分钟内完成——10 分钟只是拆步规模建议,不是完成期限、也不构成承诺;实际时长由执行专家开工预告协商决定,不设固定完成时间;动手重的任务要拆成多个小步,避免整条计划被一个慢子任务拖住。',
1518
+ // [2.3.2][D2-P2] 半角/逗号/括号自检硬约束:与解析层兜底(P0)互为防线,中文模型全角标点高发。
1519
+ '- JSON 只允许半角标点(, : " { } [ ]);对象与数组的相邻成员之间必须有逗号;输出前自检括号成对、每个字符串以半角"闭合。',
1263
1520
  '- 不要输出 Markdown 代码围栏、解释或前后缀;只输出一个 JSON 对象。',
1264
1521
  '',
1265
1522
  '本轮时间预算(硬事实,请据此规划规模):',
@@ -3187,6 +3444,14 @@ export function buildUpdateMessage(update: any) {
3187
3444
  * deriveSubtaskTimeoutMs。
3188
3445
  */
3189
3446
  ...(update.timeoutMs === undefined ? {} : { timeoutMs: update.timeoutMs }),
3447
+ /*
3448
+ * [2.3.9][T4b] 梳理门禁与第三层分工必须随 durable workplan-update 回放:
3449
+ * 刷新后门禁判据(consolidation)若只剩内存一份,重启的负责人可以不经
3450
+ * 梳理直接 dispatch,硬门禁就只是「本进程内的礼貌」。delegates 是看板
3451
+ * 第三层的数据源,同理。
3452
+ */
3453
+ ...(update.consolidation === undefined ? {} : { consolidation: update.consolidation }),
3454
+ ...(update.delegates === undefined ? {} : { delegates: update.delegates }),
3190
3455
  ...(update.revision === undefined ? {} : { revision: update.revision }),
3191
3456
  at: update.at ?? Date.now(),
3192
3457
  }
@@ -3667,6 +3932,61 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
3667
3932
  .filter((item: any) => isRecord(item) && typeof item.id === 'string')
3668
3933
  .map((item: any) => ({ id: item.id, reason: truncate(String(item.reason ?? ''), 300) }))
3669
3934
  }
3935
+ /*
3936
+ * [2.3.9][T4b] 第三层派发的留档字段(用户要求 4/5:负责人「先全面梳理、
3937
+ * 再分配」的硬门禁产物 + 顶尖专家/组员的分工与实时状态)。
3938
+ *
3939
+ * `consolidation` 是梳理门禁的唯一判据:没有它,delegateTool 的 dispatch
3940
+ * 动作必须被拒(A4)。`delegates` 是看板第三层的渲染数据源(A3),其
3941
+ * requested/corrected 对就是等级钳制的留痕(A5)。两者只写同一条状态行、
3942
+ * 走同一个 durable workplan-update 回放,刷新/重启后门禁与看板不失效。
3943
+ */
3944
+ if (patch.consolidation !== undefined) {
3945
+ if (patch.consolidation === null) next.consolidation = null
3946
+ else if (isRecord(patch.consolidation)) {
3947
+ const briefStrings = (value: any, limit: number, itemMax: number) => (Array.isArray(value) ? value : [])
3948
+ .map((entry: any) => truncate(String(entry ?? '').trim(), itemMax))
3949
+ .filter(Boolean)
3950
+ .slice(0, limit)
3951
+ next.consolidation = {
3952
+ problemAnalysis: briefStrings(patch.consolidation.problemAnalysis, 12, 500),
3953
+ constraints: briefStrings(patch.consolidation.constraints, 12, 300),
3954
+ unknowns: briefStrings(patch.consolidation.unknowns, 12, 300),
3955
+ approach: briefStrings(patch.consolidation.approach, 12, 500),
3956
+ assignments: (Array.isArray(patch.consolidation.assignments) ? patch.consolidation.assignments : [])
3957
+ .slice(0, 6)
3958
+ .map((item: any) => ({
3959
+ member: truncate(String(item?.member ?? ''), 80),
3960
+ role: item?.role === 'expert' ? 'expert' : 'member',
3961
+ task: truncate(String(item?.task ?? ''), 800),
3962
+ reasoningEffort: REASONING_EFFORTS.includes(item?.reasoningEffort) ? item.reasoningEffort : 'low',
3963
+ ...(item?.requested && item.requested !== item.reasoningEffort
3964
+ ? { requested: String(item.requested) }
3965
+ : {}),
3966
+ })),
3967
+ submittedAt: numberOrNull(patch.consolidation.submittedAt) ?? Date.now(),
3968
+ }
3969
+ } else {
3970
+ throw new PlanError('consolidation 必须是对象或 null', 'INVALID_CONSOLIDATION')
3971
+ }
3972
+ }
3973
+ if (patch.delegates !== undefined) {
3974
+ next.delegates = (Array.isArray(patch.delegates) ? patch.delegates : [])
3975
+ .slice(0, 6)
3976
+ .map((item: any) => ({
3977
+ member: truncate(String(item?.member ?? ''), 80),
3978
+ role: item?.role === 'expert' ? 'expert' : 'member',
3979
+ task: truncate(String(item?.task ?? ''), 300),
3980
+ effort: REASONING_EFFORTS.includes(item?.effort) ? item.effort : 'low',
3981
+ ...(item?.requested && item.requested !== item.effort ? { requested: String(item.requested) } : {}),
3982
+ childId: typeof item?.childId === 'string' ? truncate(item.childId, 200) : null,
3983
+ status: ['running', 'done', 'failed', 'timeout', 'rejected'].includes(item?.status) ? item.status : 'running',
3984
+ summary: typeof item?.summary === 'string' ? truncate(item.summary, 300) : '',
3985
+ error: typeof item?.error === 'string' ? truncate(item.error, 300) : null,
3986
+ startedAt: numberOrNull(item?.startedAt),
3987
+ finishedAt: numberOrNull(item?.finishedAt),
3988
+ }))
3989
+ }
3670
3990
  /*
3671
3991
  * [1.7.0] Monotonic revision + author.
3672
3992
  *
@@ -3788,6 +4108,13 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
3788
4108
  if (patch.blockedBy === undefined) next.blockedBy = undefined
3789
4109
  // [1.10.6] A conflict belongs to one attempt; a reset starts a new one.
3790
4110
  if (patch.artifactConflict === undefined) next.artifactConflict = undefined
4111
+ /*
4112
+ * [2.3.9][T4b] 第三层痕迹属于上一次尝试:重置后新负责人必须重新梳理、
4113
+ * 旧专家/组员的子会话也已随上一attempt终止——留着它们会让新行「看起来
4114
+ * 已梳理/已在派」,门禁(consolidation)与看板(delegates)双双失真。
4115
+ */
4116
+ if (patch.consolidation === undefined) next.consolidation = undefined
4117
+ if (patch.delegates === undefined) next.delegates = undefined
3791
4118
  }
3792
4119
  if (patch.status === 'in_progress') {
3793
4120
  if (next.startedAt === null) next.startedAt = Date.now()
@@ -4791,6 +5118,13 @@ export function buildChildPrompt({
4791
5118
  */
4792
5119
  leadAgentId = '',
4793
5120
  leadAgentIdSource = 'none',
5121
+ /*
5122
+ * [2.3.9][T4b] 用户强制要求 3:分配任务时必须把要求 1/2 全文告知相关部门。
5123
+ * 注入唯一事实源在 llm-rules.ts(buildLlmRulesBrief,tier='department');
5124
+ * 由派发调用点传入(plan.ts 不能反向 import llm-rules.ts,会造成循环依赖)。
5125
+ * 空串 = 旧调用方(旧测试/旧路径)零变化;新派发链恒传非空。
5126
+ */
5127
+ llmRulesBrief = '',
4794
5128
  }: any) {
4795
5129
  const noticeTarget = readLeadAgentId(leadAgentId)
4796
5130
  const noticeCall = leadNoticeCallForm(noticeTarget)
@@ -4936,6 +5270,7 @@ export function buildChildPrompt({
4936
5270
  `全局任务:${understanding.originalRequest ?? '(未记录)'}`,
4937
5271
  `最终交付物:${understanding.deliverable ?? '(未记录)'}`,
4938
5272
  ...anchorBlock,
5273
+ ...(llmRulesBrief ? ['', String(llmRulesBrief), ''] : []),
4939
5274
  `主要矛盾:${contradiction}`,
4940
5275
  `当前阶段:${stageName}(${stageGoal})`,
4941
5276
  `工作目录:${cwd || '(未知)'}`,
package/src/replan.ts CHANGED
@@ -237,7 +237,7 @@ function mergeReplacement(old: any, replacement: any, id: string, reason: string
237
237
  * (T4 D-T4-03)。修复前 add 接受 14 条依赖、200 条 inputs 与 16 万字符
238
238
  * 载荷,这些计划再也回灌不了 validatePlan,却能被真实派发。
239
239
  */
240
- function replanFieldError(raw: any): string | null {
240
+ function replanFieldError(raw: any, allowedEfforts?: readonly string[] | null): string | null {
241
241
  const list = (key: string, max: number, itemMax: number, required = false): string | null => {
242
242
  const value = raw?.[key]
243
243
  if (value === undefined) return required ? `${key} 不能为空` : null
@@ -260,6 +260,10 @@ function replanFieldError(raw: any): string | null {
260
260
  }
261
261
  /*
262
262
  * [2.2.7][T4/五档+G1] reasoningEffort 入口白名单(replace/add 两路共用本函数):
263
+ * [2.3.9][T3/同步点] 此处按 REASONING_EFFORTS **存储全集五档**校验是刻意决策:
264
+ * 重规划的输入可能来自回放/他模型计划,删档会破坏零迁移契约;模型家族收窄
265
+ * 统一发生在派发入口(runtime.ts 静态收窄 + qwen-rule/non-qwen-rule 留痕)与
266
+ * 规划校验(validatePlan options.allowedEfforts),口径见 plan.ts L214-231 注释。
263
267
  * 与 plan.ts readSubtasks 语义对齐——缺失/显式 null 合法(replace 继承旧行、
264
268
  * add 留给派发期回落 high),非缺失值必须是 REASONING_EFFORTS 五档之一
265
269
  * (low / medium / high / xhigh / max),非法值拒绝、不改写。补上此校验前,
@@ -269,8 +273,15 @@ function replanFieldError(raw: any): string | null {
269
273
  const effortError = effort === undefined || effort === null
270
274
  ? null
271
275
  : typeof effort !== 'string' || !REASONING_EFFORTS.includes(effort)
272
- ? 'reasoningEffort 必须是 low / medium / high / xhigh / max 之一(缺失合法:replace 继承旧行、add 派发期回落;非法值拒绝,不改写)'
273
- : null
276
+ ? 'reasoningEffort 必须是 low / medium / high / xhigh / max 之一(缺失合法:replace 继承旧行、add 派发期回落;非法值拒绝,不改写;传入模型家族集合时进一步收窄为该集合)'
277
+ /*
278
+ * [2.3.9][T3] 模型感知收窄口径(用户要求 1/2;与 plan.ts validatePlan、
279
+ * runtime 派发侧同一真源):调用方传入当前模型家族等级集合时,五档合规
280
+ * 但家族越界的档位(如 qwen 系的 high/max)同样拒绝并点名集合,不改写。
281
+ */
282
+ : Array.isArray(allowedEfforts) && allowedEfforts.length > 0 && !allowedEfforts.includes(effort)
283
+ ? `reasoningEffort "${effort}" 不在当前模型家族的推理等级集合 {${allowedEfforts.join(' / ')}} 内(qwen 系仅 low / medium / xhigh;非 qwen 系仅 low / high / max),必须改用集合内档位`
284
+ : null
274
285
  return list('dependsOn', 12, 16)
275
286
  ?? list('method', 12, 800)
276
287
  ?? list('inputs', 12, 800)
@@ -360,7 +371,7 @@ export function planReplan(plan: any, changes: any, options: any = {}): ReplanRe
360
371
  if (replacement.department !== undefined && replanDepartment(replacement.department) === null) {
361
372
  return fail(REPLAN_CODES.INVALID_REPLACEMENT, `replacement.department 不是合法部门:${String(replacement.department)}`)
362
373
  }
363
- const replacementError = replanFieldError(replacement)
374
+ const replacementError = replanFieldError(replacement, options?.allowedEfforts)
364
375
  if (replacementError) return fail(REPLAN_CODES.INVALID_REPLACEMENT, `replacement 字段不合规:${replacementError}`)
365
376
  const requestedId = typeof replacement.id === 'string' ? replacement.id.trim() : ''
366
377
  if (requestedId && (requestedId === subtaskId || orderMap(next).has(requestedId))) {
@@ -414,7 +425,7 @@ export function planReplan(plan: any, changes: any, options: any = {}): ReplanRe
414
425
  if (department === null) {
415
426
  return fail(REPLAN_CODES.INVALID_SUBTASK, `newSubtask.department 不是合法部门:${String(raw.department)}`)
416
427
  }
417
- const fieldError = replanFieldError(raw)
428
+ const fieldError = replanFieldError(raw, options?.allowedEfforts)
418
429
  if (fieldError) return fail(REPLAN_CODES.INVALID_SUBTASK, `newSubtask 字段不合规:${fieldError}`)
419
430
  const goal = typeof raw.objective === 'string' ? raw.objective.trim() : ''
420
431
  const title = typeof raw.title === 'string' ? raw.title.trim() : ''