dsh-workplan 1.8.3 → 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/lib/plan.js CHANGED
@@ -82,6 +82,43 @@ export function messageText(message) {
82
82
  .map((block) => block.text)
83
83
  .join('\n');
84
84
  }
85
+ /*
86
+ * [1.8.12] 不能让正文里的「包名:行号」变成跨会话引用。
87
+ *
88
+ * Harness 的 session-reference 在 `agent/pre-step` 阶段扫描每条
89
+ * `source.kind === 'user'` 消息的文本块,正则会把裸的
90
+ * `dsh-session:<payload>` 当成引用候选;候选无法按 base64url+JSON 解码时抛
91
+ * SessionReferenceError,整个 turn 在第一次模型调用之前就结束。部门子 Agent
92
+ * 的首条消息正是 user 消息,所以父会话历史里只要有人写过
93
+ * `dsh-session:1980`(“dsh-session 包第 1980 行”),子任务就会表现为
94
+ * “处理失败 / 无响应”,且没有任何模型步可以解释。
95
+ *
96
+ * 插件侧的防线:拼装子任务提示词时,把无法规范化的裸 token 转义成
97
+ * `dsh-session\:<payload>`,肉眼仍是同一段文字,但不再命中引用正则。
98
+ * 规范 URI(真正的跨会话引用)保持原样。
99
+ */
100
+ const SESSION_URI_PREFIX = 'dsh-session:';
101
+ const BARE_SESSION_URI = /dsh-session:([A-Za-z0-9_-]+)/gu;
102
+ export function isCanonicalSessionUri(uri) {
103
+ if (typeof uri !== 'string' || !uri.startsWith(SESSION_URI_PREFIX))
104
+ return false;
105
+ const payload = uri.slice(SESSION_URI_PREFIX.length);
106
+ if (!/^[A-Za-z0-9_-]+$/.test(payload))
107
+ return false;
108
+ try {
109
+ const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
110
+ return typeof decoded === 'string'
111
+ && Buffer.from(JSON.stringify(decoded), 'utf8').toString('base64url') === payload;
112
+ }
113
+ catch {
114
+ return false;
115
+ }
116
+ }
117
+ export function defuseSessionReferenceText(text) {
118
+ if (typeof text !== 'string' || !text.includes(SESSION_URI_PREFIX))
119
+ return text;
120
+ return text.replace(BARE_SESSION_URI, (match, payload) => (isCanonicalSessionUri(`${SESSION_URI_PREFIX}${payload}`) ? match : `dsh-session\\:${payload}`));
121
+ }
85
122
  /*
86
123
  * Lightweight conversational inputs must not start the planning pipeline.
87
124
  *
@@ -889,10 +926,60 @@ export function buildDegradedMessage(options) {
889
926
  }
890
927
  export function buildResultSummary(result) {
891
928
  const stats = result.stats ?? { done: 0, total: 0, blocked: 0 };
892
- return truncate(`【部门执行结果】完成 ${stats.done}/${stats.total},受阻 ${stats.blocked},请主 Agent 核对并整合`, 300);
929
+ const done = Number(stats.done ?? 0);
930
+ const total = Number(stats.total ?? 0);
931
+ const remaining = Math.max(0, total - done);
932
+ /*
933
+ * [1.8.7] 「请主 Agent 核对并整合」在未完成时也是一条误导:它把这一轮当成
934
+ * 已经可以交付,只差整合。剩余项必须出现在摘要第一句,模型只读摘要也能看到。
935
+ */
936
+ /*
937
+ * [1.8.15] Cancel is a terminal state, not a pause.
938
+ *
939
+ * 1.8.13 already refused `present` for a cancelled plan, but the round's
940
+ * result message still said "请继续派发", and `dsh_workplan_dispatch`
941
+ * complied by really starting another round (T4e F1/C16: `activationCalled:
942
+ * true`, `ok: true`). A summary that tells the model to dispatch a cancelled
943
+ * plan is the root of that contradiction; this text now has one meaning:
944
+ * cancelled ≠ complete, and there is nothing left to resume.
945
+ */
946
+ if (result.phase === 'cancelled') {
947
+ return truncate(remaining > 0
948
+ ? `【部门执行结果】已取消:只完成 ${done}/${total},剩余 ${remaining} 项未完成;取消只停止执行,不得交付,也不要再次派发`
949
+ : `【部门执行结果】已取消:完成 ${done}/${total};取消只停止执行,不得交付`, 300);
950
+ }
951
+ if (remaining > 0) {
952
+ return truncate(`【部门执行结果】未完成:完成 ${done}/${total},剩余 ${remaining} 项,受阻 ${Number(stats.blocked ?? 0)};请主 Agent 核对后继续派发,完成前不得交付`, 300);
953
+ }
954
+ /*
955
+ * [1.8.13] All rows done is not the same as deliverable. The summary used to
956
+ * say "请核对并整合" even when every done row had legacy/empty evidence, so a
957
+ * model that only read the summary could close the turn as finished.
958
+ */
959
+ const statuses = Array.isArray(result.statuses) ? result.statuses : [];
960
+ if (statuses.length > 0) {
961
+ const readiness = deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase });
962
+ if (!readiness.ready) {
963
+ const shown = readiness.blockers.slice(0, 2).join(';');
964
+ return truncate(`【部门执行结果】未完成:完成 ${done}/${total} 但证据未通过${shown ? `(${shown}${readiness.blockers.length > 2 ? '…' : ''})` : ''};证据补齐前不得交付`, 300);
965
+ }
966
+ }
967
+ return truncate(`【部门执行结果】完成 ${done}/${total},受阻 ${Number(stats.blocked ?? 0)},请主 Agent 核对并整合`, 300);
893
968
  }
894
969
  export function buildResultMessage(result) {
895
970
  const summary = buildResultSummary(result);
971
+ /*
972
+ * [1.8.13] Compute delivery readiness once, from the same statuses that ship
973
+ * in the payload. The result message used to tell the model "给出最终答复"
974
+ * whenever done === total, even when present would immediately refuse the
975
+ * delivery for legacy/empty evidence. One predicate now feeds the summary,
976
+ * the instruction block and the durable payload.
977
+ */
978
+ const statuses = Array.isArray(result.statuses) ? result.statuses : [];
979
+ const readiness = statuses.length > 0
980
+ ? deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
981
+ : null;
982
+ const deliveryBlockers = readiness?.blockers ?? [];
896
983
  const payload = {
897
984
  kind: 'workplan-result',
898
985
  version: PLAN_VERSION,
@@ -913,6 +1000,10 @@ export function buildResultMessage(result) {
913
1000
  // "never resumed", instead of promising a retry that will be refused.
914
1001
  resumeCount: Number(result.resumeCount ?? 0),
915
1002
  resumeAvailable: result.resumeAvailable === true,
1003
+ // [1.8.13] The delivery verdict travels with the round so a reload cannot
1004
+ // re-derive a more optimistic "done" from the statuses alone.
1005
+ deliveryReady: readiness ? readiness.ready : undefined,
1006
+ deliveryBlockers: deliveryBlockers.slice(0, 12),
916
1007
  };
917
1008
  const blocked = Number(result.stats?.blocked ?? 0);
918
1009
  const paused = Number(result.stats?.pending ?? 0) > 0 && result.phase === 'paused';
@@ -924,7 +1015,6 @@ export function buildResultMessage(result) {
924
1015
  * are missing, and what a sibling department asked for. Keeping this out of
925
1016
  * the payload (it is derived) keeps the durable message small.
926
1017
  */
927
- const statuses = Array.isArray(result.statuses) ? result.statuses : [];
928
1018
  const unverified = statuses.filter((item) => item?.verification === 'unverified');
929
1019
  const failed = statuses.filter((item) => item?.verification === 'failed');
930
1020
  const legacy = statuses.filter((item) => item?.status === 'done' && item?.verification === 'legacy');
@@ -944,27 +1034,67 @@ export function buildResultMessage(result) {
944
1034
  if (missingArtifacts.length > 0) {
945
1035
  review.push(`- 声明产物缺失:${missingArtifacts.slice(0, 10).join(';')}`);
946
1036
  }
1037
+ /*
1038
+ * [1.8.7] 未完成时不能再命令「给出最终答复」。
1039
+ *
1040
+ * 事故(session-99984ebd…,2026-10-31 12:02):预算到点返回 10/13,本条消息
1041
+ * 第 3 条却写着「给出最终答复」,第 4 条又要求「再次派发续跑」。两条命令
1042
+ * 互相抵触,模型照前者收尾,于是用户在计划只完成 10/13 时拿到了「成品」。
1043
+ * 现在:未完成时第 3 条改为「禁止交付」,恢复动作固定为第 4 条;只有全部
1044
+ * 子任务 done 才允许收尾。
1045
+ */
1046
+ const doneCount = Number(result.stats?.done ?? 0);
1047
+ const totalCount = Number(result.stats?.total ?? 0);
1048
+ const remaining = Math.max(0, totalCount - doneCount);
1049
+ const incomplete = totalCount > 0 && remaining > 0;
1050
+ /*
1051
+ * [1.8.13] All rows done but evidence not passing is a distinct blocked
1052
+ * state. It must not fall into the "完成 ⇒ 给出最终答复" branch: present
1053
+ * would reject the very delivery the message just ordered.
1054
+ */
1055
+ const evidenceBlocked = !incomplete && Boolean(readiness && !readiness.ready);
1056
+ /*
1057
+ * [1.8.15] A cancelled round has no legal next dispatch.
1058
+ *
1059
+ * T4e F1/C16 proved the old text ("再次调用 dsh_workplan_dispatch 即可继续跑")
1060
+ * started a real round on a cancelled plan. Cancel is terminal here: no
1061
+ * present, no "已完成", no dispatch — only an honest 未完成 reply.
1062
+ */
1063
+ const cancelled = result.phase === 'cancelled';
1064
+ const shownBlockers = deliveryBlockers.slice(0, 8).join(';');
1065
+ const recovery = blocked > 0
1066
+ ? (result.resumeAvailable === false
1067
+ ? `本计划已用尽自动续跑额度(${Number(result.resumeCount ?? 0)}/${MAX_PLAN_RESUMES}),受阻项不会再自动重跑:请主 Agent 直接接手完成剩余 ${remaining} 项,完成前同样不得交付。`
1068
+ : `受阻项可再次调用 dsh_workplan_dispatch 从受阻处续跑(已完成的不会重跑,本计划剩余续跑额度 ${MAX_PLAN_RESUMES - Number(result.resumeCount ?? 0)} 次)。`)
1069
+ : paused
1070
+ ? `本轮执行预算用尽,剩余 ${Number(result.stats?.pending ?? 0)} 项未完成(不是失败、未计入续跑额度):再次调用 dsh_workplan_dispatch 即可从剩下的步骤继续,已完成的不重跑。`
1071
+ : `剩余 ${remaining} 项子任务还没有完成:再次调用 dsh_workplan_dispatch 即可继续跑,已完成的不重跑。`;
947
1072
  const lines = [
948
1073
  summary,
949
1074
  '',
950
1075
  '各部门子任务结果如下,请主 Agent:',
951
1076
  '1. 核对每个完成项的证据与验收标准;',
952
1077
  '2. 处理受阻项,必要时向用户确认;',
953
- '3. 给出最终答复,不要声称未验证的完成。',
1078
+ ...(cancelled
1079
+ ? [
1080
+ `3. 【已取消但未完成,禁止交付】计划只完成 ${doneCount}/${totalCount},剩余 ${remaining} 项(取消只停止执行,不等于完成):不要调用 present,不要写“已完成/最终版/已交付”,不要给出收尾性最终答复,不要声称未验证的完成。`,
1081
+ '4. 不要再调用 dsh_workplan_dispatch(计划已取消,不会启动任何部门 Agent)。如需继续这项工作,请向用户确认后重新生成计划。答复开头必须写「未完成:剩余 N 项与原因」。',
1082
+ ]
1083
+ : incomplete
1084
+ ? [
1085
+ `3. 【未完成,禁止交付】计划只完成 ${doneCount}/${totalCount},还有 ${remaining} 项没做完:不要调用 present 交付当前产物,不要写“已完成/最终版/已交付”,也不要给出收尾性最终答复,不要声称未验证的完成。`,
1086
+ `4. ${recovery}`,
1087
+ ]
1088
+ : evidenceBlocked
1089
+ ? [
1090
+ `3. 【证据未通过,禁止交付】计划 ${doneCount}/${totalCount} 虽已全部 done,但以下证据缺口未通过:${shownBlockers}${deliveryBlockers.length > 8 ? '…' : ''}。不要调用 present,不要写“已完成/最终版/已交付”,不要给出收尾性最终答复,不要声称未验证的完成。`,
1091
+ '4. 先用 dsh_workplan_update 为这些子任务补齐 verification=\'structured\' 与 acceptance(每项 result=\'pass\',并附证据),或把对应子任务改回 blocked 并写明原因;缺口补齐、deliveryReady 变为 true 之后 present 才会放行。',
1092
+ ]
1093
+ : ['3. 给出最终答复,不要声称未验证的完成。']),
954
1094
  ...(review.length > 0 ? ['', '验收核对:', ...review] : []),
955
1095
  ...(needs.length > 0
956
1096
  ? ['', '跨部门待转达(子 Agent 提出的需求,请逐条处理):', ...needs.slice(0, 10).map((line) => `- ${line}`)]
957
1097
  : []),
958
- // A blocked plan used to look identical to a finished one. State the exact
959
- // recovery move so the model retries the failed work instead of rebuilding
960
- // the whole plan or stopping to ask the user for a repeated request.
961
- ...(blocked > 0
962
- ? [result.resumeAvailable === false
963
- ? `4. 本计划已用尽自动续跑额度(${Number(result.resumeCount ?? 0)}/${MAX_PLAN_RESUMES}),受阻项不会再自动重跑:请主 Agent 直接接手完成,不要重复派发。`
964
- : `4. 受阻项可再次调用 dsh_workplan_dispatch 从受阻处续跑(已完成的不会重跑,本计划剩余续跑额度 ${MAX_PLAN_RESUMES - Number(result.resumeCount ?? 0)} 次)。`]
965
- : paused
966
- ? [`4. 本轮执行预算用尽,剩余 ${Number(result.stats?.pending ?? 0)} 项未完成(不是失败、未计入续跑额度):再次调用 dsh_workplan_dispatch 即可从剩下的步骤继续,已完成的不重跑。`]
967
- : []),
968
1098
  '',
969
1099
  RESULT_MARKER_BEGIN,
970
1100
  JSON.stringify(payload),
@@ -976,6 +1106,94 @@ export function buildResultMessage(result) {
976
1106
  summary,
977
1107
  });
978
1108
  }
1109
+ /**
1110
+ * [1.8.7] 回合收尾前注入的「计划没做完」指令。
1111
+ *
1112
+ * 事故(session-99984ebd…)里,计划停在 10/13,主 Agent 却已经 present 了报告
1113
+ * 并给出收尾答复。软约束(系统提示词)挡不住这种收尾,所以由 runtime 在
1114
+ * `agent/turn-stopping` 里 `agent.steer()` 这条消息,强制再跑一步去续跑。
1115
+ *
1116
+ * 措辞必须同时做到三件事:说清剩余量、禁止交付措辞、给出唯一恢复动作;不含
1117
+ * 任何「已完成」的暗示,也不假装这是用户说的话(source.kind 单独标记)。
1118
+ */
1119
+ export function buildStopSteerText(input) {
1120
+ const stats = input?.stats ?? {};
1121
+ const total = Number(stats.total ?? 0);
1122
+ const done = Number(stats.done ?? 0);
1123
+ const remaining = Math.max(0, total - done);
1124
+ const statuses = Array.isArray(input?.statuses) ? input.statuses : [];
1125
+ const snapshot = statuses.length > 0 ? derivePlanSnapshot(statuses) : null;
1126
+ const readiness = snapshot ? deliveryReadiness(snapshot, { phase: input?.phase }) : null;
1127
+ const blockers = readiness?.blockers ?? [];
1128
+ const ids = statuses
1129
+ .filter((item) => item?.status !== 'done')
1130
+ .map((item) => String(item?.subtaskId ?? ''))
1131
+ .filter((id) => id !== '')
1132
+ .slice(0, 10);
1133
+ const runnable = statuses.filter((item) => item?.status === 'pending' || item?.status === 'in_progress').length;
1134
+ const attempt = Number(input?.attempt ?? 1);
1135
+ const planLabel = `计划 ${String(input?.planId ?? '')}`;
1136
+ const footer = `(这是 dsh-workplan 在回合收尾前自动发出的第 ${attempt} 次提醒:计划未通过交付就绪检查,这个回合暂不关闭。)`;
1137
+ /*
1138
+ * [1.8.13] One gate, four truthful messages.
1139
+ *
1140
+ * 1.8.8 only steered while `pending/in_progress` existed, so an all-done plan
1141
+ * with legacy/empty evidence closed the turn normally (T5-B/D), and a
1142
+ * cancelled plan was released outright (T5-C). Each branch below keeps the
1143
+ * same contract — no present, no completion wording, start with 未完成 —
1144
+ * but only the first asks for another dispatch, because only it has runnable
1145
+ * work. The others would otherwise spin forever on an empty dispatch.
1146
+ */
1147
+ if (readiness?.cancelled && !readiness.ready) {
1148
+ const scope = remaining > 0
1149
+ ? `已取消,只完成 ${done}/${total},还有 ${remaining} 项没做完${ids.length > 0 ? `(${ids.join('、')})` : ''}`
1150
+ : `已取消,完成 ${done}/${total},但证据未通过:${blockers.slice(0, 4).join(';')}`;
1151
+ return [
1152
+ `【计划已取消但未完成 · 禁止收尾】${planLabel} ${scope}。`,
1153
+ '',
1154
+ '取消只停止执行,不等于完成;当前内容不能当作最终结果交付。',
1155
+ '1. 不要再调用 dsh_workplan_dispatch(计划已取消,不会继续执行)。',
1156
+ '2. 不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。',
1157
+ `3. 答复开头必须写「未完成:剩余 ${Math.max(remaining, blockers.length)} 项(列出 ID)与原因」,说明取消原因与未完成范围。`,
1158
+ '',
1159
+ footer,
1160
+ ].join('\n');
1161
+ }
1162
+ if (readiness && !readiness.ready && remaining === 0) {
1163
+ return [
1164
+ `【证据未通过 · 禁止交付】${planLabel} 的 ${done}/${total} 个子任务虽都已 done,但证据未通过:${blockers.slice(0, 8).join(';')}${blockers.length > 8 ? '…' : ''}。`,
1165
+ '',
1166
+ '当前内容不能作为成品交付。请立即处理证据缺口:',
1167
+ "1. 不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。",
1168
+ "2. 用 dsh_workplan_update 为这些子任务补齐 verification='structured' 与 acceptance(每项 result='pass',并附证据),或把对应子任务改回 blocked 并写明原因。",
1169
+ '3. 在证据补齐、deliveryReady 变为 true 之前,不得声称完成;确实无法补齐时,答复开头写「未完成:剩余 N 项与原因」。',
1170
+ '',
1171
+ footer,
1172
+ ].join('\n');
1173
+ }
1174
+ if (remaining > 0 && runnable === 0) {
1175
+ return [
1176
+ `【剩余项全部受阻 · 禁止收尾】${planLabel} 只完成 ${done}/${total},还有 ${remaining} 项没完成${ids.length > 0 ? `(${ids.join('、')})` : ''},当前没有可自动续跑的项。`,
1177
+ '',
1178
+ '现在不能把当前内容当作最终结果交付。',
1179
+ '1. 不要调用 present;不要写“已完成/最终版/已交付”;不要声称完成。',
1180
+ '2. 向用户说明受阻项与原因,答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。',
1181
+ '3. 如用户确认终止,可调用 dsh_workplan_cancel;取消只停止执行,不改变“未完成”的结论。',
1182
+ '',
1183
+ footer,
1184
+ ].join('\n');
1185
+ }
1186
+ return [
1187
+ `【计划未完成 · 禁止收尾】${planLabel} 只完成 ${done}/${total},还有 ${remaining} 项没做完${ids.length > 0 ? `(${ids.join('、')})` : ''}。`,
1188
+ '',
1189
+ '现在不能把当前内容当作最终结果交付。请立即继续:',
1190
+ '1. 调用 dsh_workplan_dispatch(默认 wait)续跑剩余子任务;已完成的不重跑。',
1191
+ '2. 在计划通过交付就绪检查之前:不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。',
1192
+ '3. 若续跑被拒绝或持续失败,答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」,不得把它包装成成品。',
1193
+ '',
1194
+ footer,
1195
+ ].join('\n');
1196
+ }
979
1197
  function extractBetween(text, begin, end) {
980
1198
  if (typeof text !== 'string')
981
1199
  return null;
@@ -1028,6 +1246,15 @@ export function buildCancelMessage(planId, reason = '用户取消') {
1028
1246
  summary,
1029
1247
  '',
1030
1248
  '这次任务分解已取消。取消只停止后续执行,不会把未完成项标成完成;已完成项保留原记录。',
1249
+ /*
1250
+ * [1.8.13] Cancel is not a delivery permit. The old text stopped at "不会
1251
+ * 标成完成" and never told the model what that means for the reply, so the
1252
+ * T5-C snapshot could cancel 1/3 and then present. The same readiness
1253
+ * predicate now rejects that present, and this message states the output
1254
+ * contract so the model does not try.
1255
+ */
1256
+ '取消不等于完成:如仍有未完成项或证据缺口,不要调用 present,不要写“已完成/最终版/已交付”;',
1257
+ '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。',
1031
1258
  '',
1032
1259
  CANCEL_MARKER_BEGIN,
1033
1260
  JSON.stringify(payload),
@@ -1198,7 +1425,19 @@ export function adjudicateResult({ output, strict = true }) {
1198
1425
  error: `自检未通过:${failed.map((item) => item.criterion).join(';')}`,
1199
1426
  };
1200
1427
  }
1201
- const hasUnverified = acceptance.some((item) => item.result === 'unverified');
1428
+ /*
1429
+ * [1.8.13] No acceptance rows is not "structured and passing".
1430
+ *
1431
+ * `acceptance: []` used to fall through to `structured` because only the
1432
+ * literal `unverified` result was checked. A child that omitted the whole
1433
+ * acceptance list therefore looked better than one that honestly marked a
1434
+ * row unverified. Treat the absence of a check as unverified evidence; the
1435
+ * main Agent can still supply a real check through `dsh_workplan_update`
1436
+ * (now carrying verification/acceptance), and delivery readiness will then
1437
+ * re-evaluate it.
1438
+ */
1439
+ const hasUnverified = acceptance.length === 0
1440
+ || acceptance.some((item) => item.result === 'unverified');
1202
1441
  return {
1203
1442
  status: 'done',
1204
1443
  verification: hasUnverified ? 'unverified' : 'structured',
@@ -1218,6 +1457,19 @@ export function buildUpdateMessage(update) {
1218
1457
  ...(update.progress === undefined ? {} : { progress: update.progress }),
1219
1458
  ...(update.note === undefined ? {} : { note: update.note }),
1220
1459
  ...(update.evidence === undefined ? {} : { evidence: update.evidence }),
1460
+ /*
1461
+ * [1.8.13] A manual verdict is now allowed to carry real evidence.
1462
+ *
1463
+ * `dsh_workplan_update` could set `status:'done'` but had no field for
1464
+ * verification/acceptance, and this durable message only carried a free
1465
+ * text note. After a refresh the evidence was gone, so the row came back
1466
+ * as done-without-proof and present had no way to recover. Persisting the
1467
+ * structured fields makes the repair itself replayable.
1468
+ */
1469
+ ...(update.verification === undefined ? {} : { verification: update.verification }),
1470
+ ...(update.acceptance === undefined ? {} : { acceptance: update.acceptance }),
1471
+ ...(update.artifacts === undefined ? {} : { artifacts: update.artifacts }),
1472
+ ...(update.missingArtifacts === undefined ? {} : { missingArtifacts: update.missingArtifacts }),
1221
1473
  ...(update.revision === undefined ? {} : { revision: update.revision }),
1222
1474
  at: update.at ?? Date.now(),
1223
1475
  };
@@ -1740,6 +1992,18 @@ export function aggregateInvariantViolations(snapshot, phase) {
1740
1992
  violations.push(`I10 子任务 ${String(item?.subtaskId)} 状态为 in_progress 但 progress=${item?.progress}`);
1741
1993
  }
1742
1994
  }
1995
+ /*
1996
+ * [1.8.4] I11:「已结束」与「正在做」不能同屏。
1997
+ *
1998
+ * 本次事故截图(session-b83e4a75…,2026-10-30 20:06:33)里,同一张卡片既在
1999
+ * 「已结束」组、又在第 4 步写着「正在做」。根因是 `turn/end` 早于异步派发
2000
+ * 结束(派发又跑了近 4 分钟)。修复后 `ended` 只在「没有任何活派发」时才会
2001
+ * 出现,那时不可能还有子任务在跑;一旦这条关系被未来的改动破坏,
2002
+ * 这个断言会把具体计数带出来,而不是等用户截图发现。
2003
+ */
2004
+ if (phase === 'ended' && stats.inProgress > 0) {
2005
+ violations.push(`I11 phase=ended 但仍有 ${stats.inProgress} 个子任务 in_progress(已结束与正在做同屏)`);
2006
+ }
1743
2007
  return violations;
1744
2008
  }
1745
2009
  /**
@@ -1798,6 +2062,74 @@ export function reconcilePhase(phase, statuses) {
1798
2062
  }
1799
2063
  return phase ?? derived;
1800
2064
  }
2065
+ function verificationGap(item) {
2066
+ const verification = typeof item?.verification === 'string' ? item.verification : '';
2067
+ if (verification === 'structured')
2068
+ return '';
2069
+ if (verification === '')
2070
+ return '未提供自检结果(verification)';
2071
+ if (verification === 'legacy')
2072
+ return '旧格式回传,没有结构化自检';
2073
+ if (verification === 'unverified')
2074
+ return '自检标记为未验证';
2075
+ if (verification === 'failed')
2076
+ return '自检失败';
2077
+ if (verification === 'unparsable')
2078
+ return '自检块无法解析';
2079
+ return `自检状态非法:${verification}`;
2080
+ }
2081
+ export function deliveryReadiness(snapshot, options = {}) {
2082
+ const phase = typeof options.phase === 'string' ? options.phase : '';
2083
+ const statuses = Array.isArray(snapshot?.statuses) ? snapshot.statuses : [];
2084
+ const remaining = [];
2085
+ const blockers = [];
2086
+ for (const item of statuses) {
2087
+ const id = String(item?.subtaskId ?? '');
2088
+ if (item?.status !== 'done') {
2089
+ if (id)
2090
+ remaining.push(id);
2091
+ continue;
2092
+ }
2093
+ const gap = verificationGap(item);
2094
+ if (gap)
2095
+ blockers.push(`${id} ${gap}`);
2096
+ const acceptance = Array.isArray(item?.acceptance) ? item.acceptance : [];
2097
+ /*
2098
+ * An empty acceptance list is not "everything passed"; it is the absence
2099
+ * of a check. `adjudicateResult` used to call that `structured`, which is
2100
+ * exactly how the T5-D snapshot still looked deliverable.
2101
+ */
2102
+ if (acceptance.length === 0)
2103
+ blockers.push(`${id} 未提供验收项(acceptance 为空)`);
2104
+ for (const entry of acceptance) {
2105
+ if (entry?.result !== 'pass') {
2106
+ blockers.push(`${id} 验收未通过:${truncate(String(entry?.criterion ?? '未命名验收项'), 80)}`);
2107
+ }
2108
+ }
2109
+ const missing = Array.isArray(item?.missingArtifacts) ? item.missingArtifacts : [];
2110
+ if (missing.length > 0)
2111
+ blockers.push(`${id} 缺少声明产物:${missing.slice(0, 5).join('、')}`);
2112
+ const artifacts = Array.isArray(item?.artifacts) ? item.artifacts : [];
2113
+ for (const artifact of artifacts) {
2114
+ if (artifact?.exists === false) {
2115
+ blockers.push(`${id} 声明产物不存在:${truncate(String(artifact?.ref ?? '未命名产物'), 120)}`);
2116
+ }
2117
+ }
2118
+ }
2119
+ const done = Number(snapshot?.stats?.done ?? 0);
2120
+ const total = Number(snapshot?.stats?.total ?? 0);
2121
+ if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2122
+ blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`);
2123
+ }
2124
+ return {
2125
+ ready: total > 0 && remaining.length === 0 && blockers.length === 0,
2126
+ total,
2127
+ done,
2128
+ remaining,
2129
+ blockers,
2130
+ cancelled: phase === 'cancelled',
2131
+ };
2132
+ }
1801
2133
  export function nextReadyInStage(plan, statuses, stageId) {
1802
2134
  const byId = new Map(statuses.map((item) => [item.subtaskId, item]));
1803
2135
  const stage = plan.stages.find((item) => item.id === stageId);
@@ -2013,7 +2345,14 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
2013
2345
  '请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
2014
2346
  ].join('\n')
2015
2347
  : '';
2016
- return [
2348
+ /*
2349
+ * [1.8.12] 提示词整体过一遍 session-reference 消毒。
2350
+ *
2351
+ * 背景、依赖结果、兄弟部门摘要都可能是父会话原文的摘录,任何一处出现
2352
+ * 裸的 `dsh-session:<payload>` 都会让子 Agent 的首轮在 harness 里直接失败。
2353
+ * 在唯一的出口统一消毒,避免逐个字段漏掉。
2354
+ */
2355
+ return defuseSessionReferenceText([
2017
2356
  `你是「${departmentLabel(subtask.department)}」部门的执行 Agent,只负责下面这一个子任务。`,
2018
2357
  '',
2019
2358
  `全局任务:${understanding.originalRequest ?? '(未记录)'}`,
@@ -2058,5 +2397,5 @@ export function buildChildPrompt({ plan, subtask, stage, dependencyResults, cwd,
2058
2397
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
2059
2398
  '- 需要其他部门配合时写进 needs(每条一句话),主 Agent 会转达;不要直连其他子 Agent。',
2060
2399
  '- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
2061
- ].join('\n');
2400
+ ].join('\n'));
2062
2401
  }