dsh-workplan 1.8.4 → 1.8.18

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
@@ -93,6 +93,44 @@ export function messageText(message: any) {
93
93
  .join('\n')
94
94
  }
95
95
 
96
+ /*
97
+ * [1.8.12] 不能让正文里的「包名:行号」变成跨会话引用。
98
+ *
99
+ * Harness 的 session-reference 在 `agent/pre-step` 阶段扫描每条
100
+ * `source.kind === 'user'` 消息的文本块,正则会把裸的
101
+ * `dsh-session:<payload>` 当成引用候选;候选无法按 base64url+JSON 解码时抛
102
+ * SessionReferenceError,整个 turn 在第一次模型调用之前就结束。部门子 Agent
103
+ * 的首条消息正是 user 消息,所以父会话历史里只要有人写过
104
+ * `dsh-session:1980`(“dsh-session 包第 1980 行”),子任务就会表现为
105
+ * “处理失败 / 无响应”,且没有任何模型步可以解释。
106
+ *
107
+ * 插件侧的防线:拼装子任务提示词时,把无法规范化的裸 token 转义成
108
+ * `dsh-session\:<payload>`,肉眼仍是同一段文字,但不再命中引用正则。
109
+ * 规范 URI(真正的跨会话引用)保持原样。
110
+ */
111
+ const SESSION_URI_PREFIX = 'dsh-session:'
112
+ const BARE_SESSION_URI = /dsh-session:([A-Za-z0-9_-]+)/gu
113
+
114
+ export function isCanonicalSessionUri(uri: any) {
115
+ if (typeof uri !== 'string' || !uri.startsWith(SESSION_URI_PREFIX)) return false
116
+ const payload = uri.slice(SESSION_URI_PREFIX.length)
117
+ if (!/^[A-Za-z0-9_-]+$/.test(payload)) return false
118
+ try {
119
+ const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
120
+ return typeof decoded === 'string'
121
+ && Buffer.from(JSON.stringify(decoded), 'utf8').toString('base64url') === payload
122
+ } catch {
123
+ return false
124
+ }
125
+ }
126
+
127
+ export function defuseSessionReferenceText(text: any) {
128
+ if (typeof text !== 'string' || !text.includes(SESSION_URI_PREFIX)) return text
129
+ return text.replace(BARE_SESSION_URI, (match: string, payload: string) => (
130
+ isCanonicalSessionUri(`${SESSION_URI_PREFIX}${payload}`) ? match : `dsh-session\\:${payload}`
131
+ ))
132
+ }
133
+
96
134
  /*
97
135
  * Lightweight conversational inputs must not start the planning pipeline.
98
136
  *
@@ -943,14 +981,73 @@ export function buildDegradedMessage(options: any) {
943
981
 
944
982
  export function buildResultSummary(result: any) {
945
983
  const stats = result.stats ?? { done: 0, total: 0, blocked: 0 }
984
+ const done = Number(stats.done ?? 0)
985
+ const total = Number(stats.total ?? 0)
986
+ const remaining = Math.max(0, total - done)
987
+ /*
988
+ * [1.8.7] 「请主 Agent 核对并整合」在未完成时也是一条误导:它把这一轮当成
989
+ * 已经可以交付,只差整合。剩余项必须出现在摘要第一句,模型只读摘要也能看到。
990
+ */
991
+ /*
992
+ * [1.8.15] Cancel is a terminal state, not a pause.
993
+ *
994
+ * 1.8.13 already refused `present` for a cancelled plan, but the round's
995
+ * result message still said "请继续派发", and `dsh_workplan_dispatch`
996
+ * complied by really starting another round (T4e F1/C16: `activationCalled:
997
+ * true`, `ok: true`). A summary that tells the model to dispatch a cancelled
998
+ * plan is the root of that contradiction; this text now has one meaning:
999
+ * cancelled ≠ complete, and there is nothing left to resume.
1000
+ */
1001
+ if (result.phase === 'cancelled') {
1002
+ return truncate(
1003
+ remaining > 0
1004
+ ? `【部门执行结果】已取消:只完成 ${done}/${total},剩余 ${remaining} 项未完成;取消只停止执行,不得交付,也不要再次派发`
1005
+ : `【部门执行结果】已取消:完成 ${done}/${total};取消只停止执行,不得交付`,
1006
+ 300,
1007
+ )
1008
+ }
1009
+ if (remaining > 0) {
1010
+ return truncate(
1011
+ `【部门执行结果】未完成:完成 ${done}/${total},剩余 ${remaining} 项,受阻 ${Number(stats.blocked ?? 0)};请主 Agent 核对后继续派发,完成前不得交付`,
1012
+ 300,
1013
+ )
1014
+ }
1015
+ /*
1016
+ * [1.8.13] All rows done is not the same as deliverable. The summary used to
1017
+ * say "请核对并整合" even when every done row had legacy/empty evidence, so a
1018
+ * model that only read the summary could close the turn as finished.
1019
+ */
1020
+ const statuses = Array.isArray(result.statuses) ? result.statuses : []
1021
+ if (statuses.length > 0) {
1022
+ const readiness = deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
1023
+ if (!readiness.ready) {
1024
+ const shown = readiness.blockers.slice(0, 2).join(';')
1025
+ return truncate(
1026
+ `【部门执行结果】未完成:完成 ${done}/${total} 但证据未通过${shown ? `(${shown}${readiness.blockers.length > 2 ? '…' : ''})` : ''};证据补齐前不得交付`,
1027
+ 300,
1028
+ )
1029
+ }
1030
+ }
946
1031
  return truncate(
947
- `【部门执行结果】完成 ${stats.done}/${stats.total},受阻 ${stats.blocked},请主 Agent 核对并整合`,
1032
+ `【部门执行结果】完成 ${done}/${total},受阻 ${Number(stats.blocked ?? 0)},请主 Agent 核对并整合`,
948
1033
  300,
949
1034
  )
950
1035
  }
951
1036
 
952
1037
  export function buildResultMessage(result: any) {
953
1038
  const summary = buildResultSummary(result)
1039
+ /*
1040
+ * [1.8.13] Compute delivery readiness once, from the same statuses that ship
1041
+ * in the payload. The result message used to tell the model "给出最终答复"
1042
+ * whenever done === total, even when present would immediately refuse the
1043
+ * delivery for legacy/empty evidence. One predicate now feeds the summary,
1044
+ * the instruction block and the durable payload.
1045
+ */
1046
+ const statuses = Array.isArray(result.statuses) ? result.statuses : []
1047
+ const readiness = statuses.length > 0
1048
+ ? deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
1049
+ : null
1050
+ const deliveryBlockers = readiness?.blockers ?? []
954
1051
  const payload = {
955
1052
  kind: 'workplan-result',
956
1053
  version: PLAN_VERSION,
@@ -971,6 +1068,10 @@ export function buildResultMessage(result: any) {
971
1068
  // "never resumed", instead of promising a retry that will be refused.
972
1069
  resumeCount: Number(result.resumeCount ?? 0),
973
1070
  resumeAvailable: result.resumeAvailable === true,
1071
+ // [1.8.13] The delivery verdict travels with the round so a reload cannot
1072
+ // re-derive a more optimistic "done" from the statuses alone.
1073
+ deliveryReady: readiness ? readiness.ready : undefined,
1074
+ deliveryBlockers: deliveryBlockers.slice(0, 12),
974
1075
  }
975
1076
  const blocked = Number(result.stats?.blocked ?? 0)
976
1077
  const paused = Number(result.stats?.pending ?? 0) > 0 && result.phase === 'paused'
@@ -982,7 +1083,6 @@ export function buildResultMessage(result: any) {
982
1083
  * are missing, and what a sibling department asked for. Keeping this out of
983
1084
  * the payload (it is derived) keeps the durable message small.
984
1085
  */
985
- const statuses = Array.isArray(result.statuses) ? result.statuses : []
986
1086
  const unverified = statuses.filter((item: any) => item?.verification === 'unverified')
987
1087
  const failed = statuses.filter((item: any) => item?.verification === 'failed')
988
1088
  const legacy = statuses.filter((item: any) => item?.status === 'done' && item?.verification === 'legacy')
@@ -1004,27 +1104,67 @@ export function buildResultMessage(result: any) {
1004
1104
  if (missingArtifacts.length > 0) {
1005
1105
  review.push(`- 声明产物缺失:${missingArtifacts.slice(0, 10).join(';')}`)
1006
1106
  }
1107
+ /*
1108
+ * [1.8.7] 未完成时不能再命令「给出最终答复」。
1109
+ *
1110
+ * 事故(session-99984ebd…,2026-10-31 12:02):预算到点返回 10/13,本条消息
1111
+ * 第 3 条却写着「给出最终答复」,第 4 条又要求「再次派发续跑」。两条命令
1112
+ * 互相抵触,模型照前者收尾,于是用户在计划只完成 10/13 时拿到了「成品」。
1113
+ * 现在:未完成时第 3 条改为「禁止交付」,恢复动作固定为第 4 条;只有全部
1114
+ * 子任务 done 才允许收尾。
1115
+ */
1116
+ const doneCount = Number(result.stats?.done ?? 0)
1117
+ const totalCount = Number(result.stats?.total ?? 0)
1118
+ const remaining = Math.max(0, totalCount - doneCount)
1119
+ const incomplete = totalCount > 0 && remaining > 0
1120
+ /*
1121
+ * [1.8.13] All rows done but evidence not passing is a distinct blocked
1122
+ * state. It must not fall into the "完成 ⇒ 给出最终答复" branch: present
1123
+ * would reject the very delivery the message just ordered.
1124
+ */
1125
+ const evidenceBlocked = !incomplete && Boolean(readiness && !readiness.ready)
1126
+ /*
1127
+ * [1.8.15] A cancelled round has no legal next dispatch.
1128
+ *
1129
+ * T4e F1/C16 proved the old text ("再次调用 dsh_workplan_dispatch 即可继续跑")
1130
+ * started a real round on a cancelled plan. Cancel is terminal here: no
1131
+ * present, no "已完成", no dispatch — only an honest 未完成 reply.
1132
+ */
1133
+ const cancelled = result.phase === 'cancelled'
1134
+ const shownBlockers = deliveryBlockers.slice(0, 8).join(';')
1135
+ const recovery = blocked > 0
1136
+ ? (result.resumeAvailable === false
1137
+ ? `本计划已用尽自动续跑额度(${Number(result.resumeCount ?? 0)}/${MAX_PLAN_RESUMES}),受阻项不会再自动重跑:请主 Agent 直接接手完成剩余 ${remaining} 项,完成前同样不得交付。`
1138
+ : `受阻项可再次调用 dsh_workplan_dispatch 从受阻处续跑(已完成的不会重跑,本计划剩余续跑额度 ${MAX_PLAN_RESUMES - Number(result.resumeCount ?? 0)} 次)。`)
1139
+ : paused
1140
+ ? `本轮执行预算用尽,剩余 ${Number(result.stats?.pending ?? 0)} 项未完成(不是失败、未计入续跑额度):再次调用 dsh_workplan_dispatch 即可从剩下的步骤继续,已完成的不重跑。`
1141
+ : `剩余 ${remaining} 项子任务还没有完成:再次调用 dsh_workplan_dispatch 即可继续跑,已完成的不重跑。`
1007
1142
  const lines = [
1008
1143
  summary,
1009
1144
  '',
1010
1145
  '各部门子任务结果如下,请主 Agent:',
1011
1146
  '1. 核对每个完成项的证据与验收标准;',
1012
1147
  '2. 处理受阻项,必要时向用户确认;',
1013
- '3. 给出最终答复,不要声称未验证的完成。',
1148
+ ...(cancelled
1149
+ ? [
1150
+ `3. 【已取消但未完成,禁止交付】计划只完成 ${doneCount}/${totalCount},剩余 ${remaining} 项(取消只停止执行,不等于完成):不要调用 present,不要写“已完成/最终版/已交付”,不要给出收尾性最终答复,不要声称未验证的完成。`,
1151
+ '4. 不要再调用 dsh_workplan_dispatch(计划已取消,不会启动任何部门 Agent)。如需继续这项工作,请向用户确认后重新生成计划。答复开头必须写「未完成:剩余 N 项与原因」。',
1152
+ ]
1153
+ : incomplete
1154
+ ? [
1155
+ `3. 【未完成,禁止交付】计划只完成 ${doneCount}/${totalCount},还有 ${remaining} 项没做完:不要调用 present 交付当前产物,不要写“已完成/最终版/已交付”,也不要给出收尾性最终答复,不要声称未验证的完成。`,
1156
+ `4. ${recovery}`,
1157
+ ]
1158
+ : evidenceBlocked
1159
+ ? [
1160
+ `3. 【证据未通过,禁止交付】计划 ${doneCount}/${totalCount} 虽已全部 done,但以下证据缺口未通过:${shownBlockers}${deliveryBlockers.length > 8 ? '…' : ''}。不要调用 present,不要写“已完成/最终版/已交付”,不要给出收尾性最终答复,不要声称未验证的完成。`,
1161
+ '4. 先用 dsh_workplan_update 为这些子任务补齐 verification=\'structured\' 与 acceptance(每项 result=\'pass\',并附证据),或把对应子任务改回 blocked 并写明原因;缺口补齐、deliveryReady 变为 true 之后 present 才会放行。',
1162
+ ]
1163
+ : ['3. 给出最终答复,不要声称未验证的完成。']),
1014
1164
  ...(review.length > 0 ? ['', '验收核对:', ...review] : []),
1015
1165
  ...(needs.length > 0
1016
1166
  ? ['', '跨部门待转达(子 Agent 提出的需求,请逐条处理):', ...needs.slice(0, 10).map((line: string) => `- ${line}`)]
1017
1167
  : []),
1018
- // A blocked plan used to look identical to a finished one. State the exact
1019
- // recovery move so the model retries the failed work instead of rebuilding
1020
- // the whole plan or stopping to ask the user for a repeated request.
1021
- ...(blocked > 0
1022
- ? [result.resumeAvailable === false
1023
- ? `4. 本计划已用尽自动续跑额度(${Number(result.resumeCount ?? 0)}/${MAX_PLAN_RESUMES}),受阻项不会再自动重跑:请主 Agent 直接接手完成,不要重复派发。`
1024
- : `4. 受阻项可再次调用 dsh_workplan_dispatch 从受阻处续跑(已完成的不会重跑,本计划剩余续跑额度 ${MAX_PLAN_RESUMES - Number(result.resumeCount ?? 0)} 次)。`]
1025
- : paused
1026
- ? [`4. 本轮执行预算用尽,剩余 ${Number(result.stats?.pending ?? 0)} 项未完成(不是失败、未计入续跑额度):再次调用 dsh_workplan_dispatch 即可从剩下的步骤继续,已完成的不重跑。`]
1027
- : []),
1028
1168
  '',
1029
1169
  RESULT_MARKER_BEGIN,
1030
1170
  JSON.stringify(payload),
@@ -1037,6 +1177,95 @@ export function buildResultMessage(result: any) {
1037
1177
  })
1038
1178
  }
1039
1179
 
1180
+ /**
1181
+ * [1.8.7] 回合收尾前注入的「计划没做完」指令。
1182
+ *
1183
+ * 事故(session-99984ebd…)里,计划停在 10/13,主 Agent 却已经 present 了报告
1184
+ * 并给出收尾答复。软约束(系统提示词)挡不住这种收尾,所以由 runtime 在
1185
+ * `agent/turn-stopping` 里 `agent.steer()` 这条消息,强制再跑一步去续跑。
1186
+ *
1187
+ * 措辞必须同时做到三件事:说清剩余量、禁止交付措辞、给出唯一恢复动作;不含
1188
+ * 任何「已完成」的暗示,也不假装这是用户说的话(source.kind 单独标记)。
1189
+ */
1190
+ export function buildStopSteerText(input: any) {
1191
+ const stats = input?.stats ?? {}
1192
+ const total = Number(stats.total ?? 0)
1193
+ const done = Number(stats.done ?? 0)
1194
+ const remaining = Math.max(0, total - done)
1195
+ const statuses = Array.isArray(input?.statuses) ? input.statuses : []
1196
+ const snapshot = statuses.length > 0 ? derivePlanSnapshot(statuses) : null
1197
+ const readiness = snapshot ? deliveryReadiness(snapshot, { phase: input?.phase }) : null
1198
+ const blockers = readiness?.blockers ?? []
1199
+ const ids = statuses
1200
+ .filter((item: any) => item?.status !== 'done')
1201
+ .map((item: any) => String(item?.subtaskId ?? ''))
1202
+ .filter((id: string) => id !== '')
1203
+ .slice(0, 10)
1204
+ const runnable = statuses.filter((item: any) => item?.status === 'pending' || item?.status === 'in_progress').length
1205
+ const attempt = Number(input?.attempt ?? 1)
1206
+ const planLabel = `计划 ${String(input?.planId ?? '')}`
1207
+ const footer = `(这是 dsh-workplan 在回合收尾前自动发出的第 ${attempt} 次提醒:计划未通过交付就绪检查,这个回合暂不关闭。)`
1208
+ /*
1209
+ * [1.8.13] One gate, four truthful messages.
1210
+ *
1211
+ * 1.8.8 only steered while `pending/in_progress` existed, so an all-done plan
1212
+ * with legacy/empty evidence closed the turn normally (T5-B/D), and a
1213
+ * cancelled plan was released outright (T5-C). Each branch below keeps the
1214
+ * same contract — no present, no completion wording, start with 未完成 —
1215
+ * but only the first asks for another dispatch, because only it has runnable
1216
+ * work. The others would otherwise spin forever on an empty dispatch.
1217
+ */
1218
+ if (readiness?.cancelled && !readiness.ready) {
1219
+ const scope = remaining > 0
1220
+ ? `已取消,只完成 ${done}/${total},还有 ${remaining} 项没做完${ids.length > 0 ? `(${ids.join('、')})` : ''}`
1221
+ : `已取消,完成 ${done}/${total},但证据未通过:${blockers.slice(0, 4).join(';')}`
1222
+ return [
1223
+ `【计划已取消但未完成 · 禁止收尾】${planLabel} ${scope}。`,
1224
+ '',
1225
+ '取消只停止执行,不等于完成;当前内容不能当作最终结果交付。',
1226
+ '1. 不要再调用 dsh_workplan_dispatch(计划已取消,不会继续执行)。',
1227
+ '2. 不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。',
1228
+ `3. 答复开头必须写「未完成:剩余 ${Math.max(remaining, blockers.length)} 项(列出 ID)与原因」,说明取消原因与未完成范围。`,
1229
+ '',
1230
+ footer,
1231
+ ].join('\n')
1232
+ }
1233
+ if (readiness && !readiness.ready && remaining === 0) {
1234
+ return [
1235
+ `【证据未通过 · 禁止交付】${planLabel} 的 ${done}/${total} 个子任务虽都已 done,但证据未通过:${blockers.slice(0, 8).join(';')}${blockers.length > 8 ? '…' : ''}。`,
1236
+ '',
1237
+ '当前内容不能作为成品交付。请立即处理证据缺口:',
1238
+ "1. 不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。",
1239
+ "2. 用 dsh_workplan_update 为这些子任务补齐 verification='structured' 与 acceptance(每项 result='pass',并附证据),或把对应子任务改回 blocked 并写明原因。",
1240
+ '3. 在证据补齐、deliveryReady 变为 true 之前,不得声称完成;确实无法补齐时,答复开头写「未完成:剩余 N 项与原因」。',
1241
+ '',
1242
+ footer,
1243
+ ].join('\n')
1244
+ }
1245
+ if (remaining > 0 && runnable === 0) {
1246
+ return [
1247
+ `【剩余项全部受阻 · 禁止收尾】${planLabel} 只完成 ${done}/${total},还有 ${remaining} 项没完成${ids.length > 0 ? `(${ids.join('、')})` : ''},当前没有可自动续跑的项。`,
1248
+ '',
1249
+ '现在不能把当前内容当作最终结果交付。',
1250
+ '1. 不要调用 present;不要写“已完成/最终版/已交付”;不要声称完成。',
1251
+ '2. 向用户说明受阻项与原因,答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。',
1252
+ '3. 如用户确认终止,可调用 dsh_workplan_cancel;取消只停止执行,不改变“未完成”的结论。',
1253
+ '',
1254
+ footer,
1255
+ ].join('\n')
1256
+ }
1257
+ return [
1258
+ `【计划未完成 · 禁止收尾】${planLabel} 只完成 ${done}/${total},还有 ${remaining} 项没做完${ids.length > 0 ? `(${ids.join('、')})` : ''}。`,
1259
+ '',
1260
+ '现在不能把当前内容当作最终结果交付。请立即继续:',
1261
+ '1. 调用 dsh_workplan_dispatch(默认 wait)续跑剩余子任务;已完成的不重跑。',
1262
+ '2. 在计划通过交付就绪检查之前:不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。',
1263
+ '3. 若续跑被拒绝或持续失败,答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」,不得把它包装成成品。',
1264
+ '',
1265
+ footer,
1266
+ ].join('\n')
1267
+ }
1268
+
1040
1269
  function extractBetween(text: any, begin: any, end: any) {
1041
1270
  if (typeof text !== 'string') return null
1042
1271
  const start = text.indexOf(begin)
@@ -1083,6 +1312,15 @@ export function buildCancelMessage(planId: any, reason: any = '用户取消') {
1083
1312
  summary,
1084
1313
  '',
1085
1314
  '这次任务分解已取消。取消只停止后续执行,不会把未完成项标成完成;已完成项保留原记录。',
1315
+ /*
1316
+ * [1.8.13] Cancel is not a delivery permit. The old text stopped at "不会
1317
+ * 标成完成" and never told the model what that means for the reply, so the
1318
+ * T5-C snapshot could cancel 1/3 and then present. The same readiness
1319
+ * predicate now rejects that present, and this message states the output
1320
+ * contract so the model does not try.
1321
+ */
1322
+ '取消不等于完成:如仍有未完成项或证据缺口,不要调用 present,不要写“已完成/最终版/已交付”;',
1323
+ '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。',
1086
1324
  '',
1087
1325
  CANCEL_MARKER_BEGIN,
1088
1326
  JSON.stringify(payload),
@@ -1250,7 +1488,19 @@ export function adjudicateResult({ output, strict = true }: any) {
1250
1488
  error: `自检未通过:${failed.map((item: any) => item.criterion).join(';')}`,
1251
1489
  }
1252
1490
  }
1253
- const hasUnverified = acceptance.some((item: any) => item.result === 'unverified')
1491
+ /*
1492
+ * [1.8.13] No acceptance rows is not "structured and passing".
1493
+ *
1494
+ * `acceptance: []` used to fall through to `structured` because only the
1495
+ * literal `unverified` result was checked. A child that omitted the whole
1496
+ * acceptance list therefore looked better than one that honestly marked a
1497
+ * row unverified. Treat the absence of a check as unverified evidence; the
1498
+ * main Agent can still supply a real check through `dsh_workplan_update`
1499
+ * (now carrying verification/acceptance), and delivery readiness will then
1500
+ * re-evaluate it.
1501
+ */
1502
+ const hasUnverified = acceptance.length === 0
1503
+ || acceptance.some((item: any) => item.result === 'unverified')
1254
1504
  return {
1255
1505
  status: 'done',
1256
1506
  verification: hasUnverified ? 'unverified' : 'structured',
@@ -1271,6 +1521,19 @@ export function buildUpdateMessage(update: any) {
1271
1521
  ...(update.progress === undefined ? {} : { progress: update.progress }),
1272
1522
  ...(update.note === undefined ? {} : { note: update.note }),
1273
1523
  ...(update.evidence === undefined ? {} : { evidence: update.evidence }),
1524
+ /*
1525
+ * [1.8.13] A manual verdict is now allowed to carry real evidence.
1526
+ *
1527
+ * `dsh_workplan_update` could set `status:'done'` but had no field for
1528
+ * verification/acceptance, and this durable message only carried a free
1529
+ * text note. After a refresh the evidence was gone, so the row came back
1530
+ * as done-without-proof and present had no way to recover. Persisting the
1531
+ * structured fields makes the repair itself replayable.
1532
+ */
1533
+ ...(update.verification === undefined ? {} : { verification: update.verification }),
1534
+ ...(update.acceptance === undefined ? {} : { acceptance: update.acceptance }),
1535
+ ...(update.artifacts === undefined ? {} : { artifacts: update.artifacts }),
1536
+ ...(update.missingArtifacts === undefined ? {} : { missingArtifacts: update.missingArtifacts }),
1274
1537
  ...(update.revision === undefined ? {} : { revision: update.revision }),
1275
1538
  at: update.at ?? Date.now(),
1276
1539
  }
@@ -1900,6 +2163,91 @@ export function reconcilePhase(phase: any, statuses: any) {
1900
2163
  return phase ?? derived
1901
2164
  }
1902
2165
 
2166
+ /**
2167
+ * [1.8.13] The one machine-checkable definition of "this plan may be delivered".
2168
+ *
2169
+ * `status === 'done'` only says the child claims to be finished. 1.8.9 enforced
2170
+ * three hard gaps (failed self-check, failed acceptance row, missing declared
2171
+ * file) and treated a cancelled plan as complete, so three incident snapshots
2172
+ * still reached `present`:
2173
+ *
2174
+ * - B: all done + `legacy` verification + empty acceptance → allowed;
2175
+ * - C: cancelled 1/3 → allowed (cancel short-circuited "incomplete");
2176
+ * - D: all done + `acceptance: []` → adjudicated as `structured`.
2177
+ *
2178
+ * `present`, the result message, the turn-stopping gate and every status
2179
+ * payload now read this single predicate, so the four "done" judgments cannot
2180
+ * disagree again. Cancelling stops execution; it does not finish the work.
2181
+ */
2182
+ export interface DeliveryReadiness {
2183
+ ready: boolean
2184
+ total: number
2185
+ done: number
2186
+ remaining: string[]
2187
+ blockers: string[]
2188
+ cancelled: boolean
2189
+ }
2190
+
2191
+ function verificationGap(item: any) {
2192
+ const verification = typeof item?.verification === 'string' ? item.verification : ''
2193
+ if (verification === 'structured') return ''
2194
+ if (verification === '') return '未提供自检结果(verification)'
2195
+ if (verification === 'legacy') return '旧格式回传,没有结构化自检'
2196
+ if (verification === 'unverified') return '自检标记为未验证'
2197
+ if (verification === 'failed') return '自检失败'
2198
+ if (verification === 'unparsable') return '自检块无法解析'
2199
+ return `自检状态非法:${verification}`
2200
+ }
2201
+
2202
+ export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any } = {}): DeliveryReadiness {
2203
+ const phase = typeof options.phase === 'string' ? options.phase : ''
2204
+ const statuses = Array.isArray(snapshot?.statuses) ? snapshot.statuses : []
2205
+ const remaining: string[] = []
2206
+ const blockers: string[] = []
2207
+ for (const item of statuses) {
2208
+ const id = String((item as any)?.subtaskId ?? '')
2209
+ if (item?.status !== 'done') {
2210
+ if (id) remaining.push(id)
2211
+ continue
2212
+ }
2213
+ const gap = verificationGap(item)
2214
+ if (gap) blockers.push(`${id} ${gap}`)
2215
+ const acceptance = Array.isArray((item as any)?.acceptance) ? (item as any).acceptance : []
2216
+ /*
2217
+ * An empty acceptance list is not "everything passed"; it is the absence
2218
+ * of a check. `adjudicateResult` used to call that `structured`, which is
2219
+ * exactly how the T5-D snapshot still looked deliverable.
2220
+ */
2221
+ if (acceptance.length === 0) blockers.push(`${id} 未提供验收项(acceptance 为空)`)
2222
+ for (const entry of acceptance) {
2223
+ if (entry?.result !== 'pass') {
2224
+ blockers.push(`${id} 验收未通过:${truncate(String(entry?.criterion ?? '未命名验收项'), 80)}`)
2225
+ }
2226
+ }
2227
+ const missing = Array.isArray((item as any)?.missingArtifacts) ? (item as any).missingArtifacts : []
2228
+ if (missing.length > 0) blockers.push(`${id} 缺少声明产物:${missing.slice(0, 5).join('、')}`)
2229
+ const artifacts = Array.isArray((item as any)?.artifacts) ? (item as any).artifacts : []
2230
+ for (const artifact of artifacts) {
2231
+ if (artifact?.exists === false) {
2232
+ blockers.push(`${id} 声明产物不存在:${truncate(String(artifact?.ref ?? '未命名产物'), 120)}`)
2233
+ }
2234
+ }
2235
+ }
2236
+ const done = Number(snapshot?.stats?.done ?? 0)
2237
+ const total = Number(snapshot?.stats?.total ?? 0)
2238
+ if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2239
+ blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`)
2240
+ }
2241
+ return {
2242
+ ready: total > 0 && remaining.length === 0 && blockers.length === 0,
2243
+ total,
2244
+ done,
2245
+ remaining,
2246
+ blockers,
2247
+ cancelled: phase === 'cancelled',
2248
+ }
2249
+ }
2250
+
1903
2251
  export function nextReadyInStage(plan: any, statuses: any[], stageId: string) {
1904
2252
  const byId = new Map(statuses.map((item: any) => [item.subtaskId, item]))
1905
2253
  const stage = plan.stages.find((item: any) => item.id === stageId)
@@ -2121,7 +2469,14 @@ export function buildChildPrompt({
2121
2469
  '请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
2122
2470
  ].join('\n')
2123
2471
  : ''
2124
- return [
2472
+ /*
2473
+ * [1.8.12] 提示词整体过一遍 session-reference 消毒。
2474
+ *
2475
+ * 背景、依赖结果、兄弟部门摘要都可能是父会话原文的摘录,任何一处出现
2476
+ * 裸的 `dsh-session:<payload>` 都会让子 Agent 的首轮在 harness 里直接失败。
2477
+ * 在唯一的出口统一消毒,避免逐个字段漏掉。
2478
+ */
2479
+ return defuseSessionReferenceText([
2125
2480
  `你是「${departmentLabel(subtask.department)}」部门的执行 Agent,只负责下面这一个子任务。`,
2126
2481
  '',
2127
2482
  `全局任务:${understanding.originalRequest ?? '(未记录)'}`,
@@ -2166,5 +2521,5 @@ export function buildChildPrompt({
2166
2521
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
2167
2522
  '- 需要其他部门配合时写进 needs(每条一句话),主 Agent 会转达;不要直连其他子 Agent。',
2168
2523
  '- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
2169
- ].join('\n')
2524
+ ].join('\n'))
2170
2525
  }