dsh-workplan 1.8.4 → 1.9.1

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
@@ -9,7 +9,71 @@
9
9
 
10
10
  import { randomUUID } from 'node:crypto'
11
11
 
12
+ import { isMappingDigest, verifyMappingDigest } from './supersede-digest.js'
13
+
12
14
  export const PLAN_VERSION = 1
15
+
16
+ /**
17
+ * [1.9.0] 处置终态:cancelled(用户撤销)与 superseded(责任已转移)。
18
+ *
19
+ * 两者都是终态:记录与计数原样保留,永不算完成,也永不被自动选为
20
+ * `present` 的判定对象;只有「本回合结构化点名」时才判定(cancelled 仍硬拦)。
21
+ * 规则依据:_rerun_20261101/GATE_rule_design.md §3.1。
22
+ */
23
+ export const TERMINAL_PHASES: ReadonlySet<string> = new Set(['cancelled', 'superseded'])
24
+
25
+ export function isTerminalPhase(phase: any): boolean {
26
+ return typeof phase === 'string' && TERMINAL_PHASES.has(phase)
27
+ }
28
+
29
+ /**
30
+ * [1.9.2] `present` 拒绝码(P1 统一)。
31
+ *
32
+ * 规则出处:`_rerun_20261101/GATE_rule_design.md` §4.3(P1/P2 与
33
+ * `judgeEffective`)及 §4.4 真值表;最小修法出处:
34
+ * `_rerun_20261101/GATE_case_matrix.md` §3.2(T9 的唯一不一致格
35
+ * `C05.denyCode`)。
36
+ *
37
+ * T8 原文的 P1 把「全部 done 但证据缺口」和「还有子任务没做完」合并成
38
+ * 一个码值 `ACTIVE_NOT_READY`,于是 R2/G02 的 `EVIDENCE_GAP` 在未点名时
39
+ * 永远走不到。修法只拆一个维度:`remaining` 为空且 `blockers` 非空
40
+ * ⇒ `EVIDENCE_GAP`,其余仍是 `ACTIVE_NOT_READY`。这本来就是 1.8.19 的
41
+ * 既有语义(`remaining.length === 0` 有独立文案),不是新增语义。
42
+ *
43
+ * 码值是对外契约:测试、日志与后续 UI 按字面值断言。所有拒绝点只能引用
44
+ * 这里的常量或 `activeDenyCode()`,不得再手写字符串。
45
+ */
46
+ export const PRESENT_DENY_CODES = {
47
+ ACTIVE_NOT_READY: 'ACTIVE_NOT_READY',
48
+ EVIDENCE_GAP: 'EVIDENCE_GAP',
49
+ CANCELLED_NAMED: 'CANCELLED_NAMED',
50
+ SUPERSEDED_STALE: 'SUPERSEDED_STALE',
51
+ } as const
52
+
53
+ export type PresentDenyCode = (typeof PRESENT_DENY_CODES)[keyof typeof PRESENT_DENY_CODES]
54
+
55
+ /** `present` 判定结果:码值 + 拒绝文案(文案逐字保留,码值供断言/日志)。 */
56
+ export interface PresentDenialVerdict {
57
+ code: PresentDenyCode
58
+ message: string
59
+ }
60
+
61
+ /**
62
+ * P1 的单一映射:active 计划未就绪时,只由交付就绪结果决定拒绝码。
63
+ *
64
+ * 调用点(`present` 的未完成分支、点名 active 计划的判定)必须走这个函数,
65
+ * 不要在分支里各写一份判断——T9 的 C05 不一致正是「规则一个码、实现另一个
66
+ * 码」造成的。终态计划不走这里:cancelled 是 `CANCELLED_NAMED`,superseded
67
+ * 按覆盖链给 `SUPERSEDED_STALE` / `ACTIVE_NOT_READY`。
68
+ */
69
+ export function activeDenyCode(readiness: {
70
+ remaining: readonly string[]
71
+ blockers: readonly string[]
72
+ }): PresentDenyCode {
73
+ return readiness.remaining.length === 0 && readiness.blockers.length > 0
74
+ ? PRESENT_DENY_CODES.EVIDENCE_GAP
75
+ : PRESENT_DENY_CODES.ACTIVE_NOT_READY
76
+ }
13
77
  export const MAX_STAGES = 6
14
78
  export const MAX_SUBTASKS = 15
15
79
  export const MAX_CONCURRENT = 5
@@ -93,6 +157,44 @@ export function messageText(message: any) {
93
157
  .join('\n')
94
158
  }
95
159
 
160
+ /*
161
+ * [1.8.12] 不能让正文里的「包名:行号」变成跨会话引用。
162
+ *
163
+ * Harness 的 session-reference 在 `agent/pre-step` 阶段扫描每条
164
+ * `source.kind === 'user'` 消息的文本块,正则会把裸的
165
+ * `dsh-session:<payload>` 当成引用候选;候选无法按 base64url+JSON 解码时抛
166
+ * SessionReferenceError,整个 turn 在第一次模型调用之前就结束。部门子 Agent
167
+ * 的首条消息正是 user 消息,所以父会话历史里只要有人写过
168
+ * `dsh-session:1980`(“dsh-session 包第 1980 行”),子任务就会表现为
169
+ * “处理失败 / 无响应”,且没有任何模型步可以解释。
170
+ *
171
+ * 插件侧的防线:拼装子任务提示词时,把无法规范化的裸 token 转义成
172
+ * `dsh-session\:<payload>`,肉眼仍是同一段文字,但不再命中引用正则。
173
+ * 规范 URI(真正的跨会话引用)保持原样。
174
+ */
175
+ const SESSION_URI_PREFIX = 'dsh-session:'
176
+ const BARE_SESSION_URI = /dsh-session:([A-Za-z0-9_-]+)/gu
177
+
178
+ export function isCanonicalSessionUri(uri: any) {
179
+ if (typeof uri !== 'string' || !uri.startsWith(SESSION_URI_PREFIX)) return false
180
+ const payload = uri.slice(SESSION_URI_PREFIX.length)
181
+ if (!/^[A-Za-z0-9_-]+$/.test(payload)) return false
182
+ try {
183
+ const decoded = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
184
+ return typeof decoded === 'string'
185
+ && Buffer.from(JSON.stringify(decoded), 'utf8').toString('base64url') === payload
186
+ } catch {
187
+ return false
188
+ }
189
+ }
190
+
191
+ export function defuseSessionReferenceText(text: any) {
192
+ if (typeof text !== 'string' || !text.includes(SESSION_URI_PREFIX)) return text
193
+ return text.replace(BARE_SESSION_URI, (match: string, payload: string) => (
194
+ isCanonicalSessionUri(`${SESSION_URI_PREFIX}${payload}`) ? match : `dsh-session\\:${payload}`
195
+ ))
196
+ }
197
+
96
198
  /*
97
199
  * Lightweight conversational inputs must not start the planning pipeline.
98
200
  *
@@ -943,14 +1045,73 @@ export function buildDegradedMessage(options: any) {
943
1045
 
944
1046
  export function buildResultSummary(result: any) {
945
1047
  const stats = result.stats ?? { done: 0, total: 0, blocked: 0 }
1048
+ const done = Number(stats.done ?? 0)
1049
+ const total = Number(stats.total ?? 0)
1050
+ const remaining = Math.max(0, total - done)
1051
+ /*
1052
+ * [1.8.7] 「请主 Agent 核对并整合」在未完成时也是一条误导:它把这一轮当成
1053
+ * 已经可以交付,只差整合。剩余项必须出现在摘要第一句,模型只读摘要也能看到。
1054
+ */
1055
+ /*
1056
+ * [1.8.15] Cancel is a terminal state, not a pause.
1057
+ *
1058
+ * 1.8.13 already refused `present` for a cancelled plan, but the round's
1059
+ * result message still said "请继续派发", and `dsh_workplan_dispatch`
1060
+ * complied by really starting another round (T4e F1/C16: `activationCalled:
1061
+ * true`, `ok: true`). A summary that tells the model to dispatch a cancelled
1062
+ * plan is the root of that contradiction; this text now has one meaning:
1063
+ * cancelled ≠ complete, and there is nothing left to resume.
1064
+ */
1065
+ if (result.phase === 'cancelled') {
1066
+ return truncate(
1067
+ remaining > 0
1068
+ ? `【部门执行结果】已取消:只完成 ${done}/${total},剩余 ${remaining} 项未完成;取消只停止执行,不得交付,也不要再次派发`
1069
+ : `【部门执行结果】已取消:完成 ${done}/${total};取消只停止执行,不得交付`,
1070
+ 300,
1071
+ )
1072
+ }
1073
+ if (remaining > 0) {
1074
+ return truncate(
1075
+ `【部门执行结果】未完成:完成 ${done}/${total},剩余 ${remaining} 项,受阻 ${Number(stats.blocked ?? 0)};请主 Agent 核对后继续派发,完成前不得交付`,
1076
+ 300,
1077
+ )
1078
+ }
1079
+ /*
1080
+ * [1.8.13] All rows done is not the same as deliverable. The summary used to
1081
+ * say "请核对并整合" even when every done row had legacy/empty evidence, so a
1082
+ * model that only read the summary could close the turn as finished.
1083
+ */
1084
+ const statuses = Array.isArray(result.statuses) ? result.statuses : []
1085
+ if (statuses.length > 0) {
1086
+ const readiness = deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
1087
+ if (!readiness.ready) {
1088
+ const shown = readiness.blockers.slice(0, 2).join(';')
1089
+ return truncate(
1090
+ `【部门执行结果】未完成:完成 ${done}/${total} 但证据未通过${shown ? `(${shown}${readiness.blockers.length > 2 ? '…' : ''})` : ''};证据补齐前不得交付`,
1091
+ 300,
1092
+ )
1093
+ }
1094
+ }
946
1095
  return truncate(
947
- `【部门执行结果】完成 ${stats.done}/${stats.total},受阻 ${stats.blocked},请主 Agent 核对并整合`,
1096
+ `【部门执行结果】完成 ${done}/${total},受阻 ${Number(stats.blocked ?? 0)},请主 Agent 核对并整合`,
948
1097
  300,
949
1098
  )
950
1099
  }
951
1100
 
952
1101
  export function buildResultMessage(result: any) {
953
1102
  const summary = buildResultSummary(result)
1103
+ /*
1104
+ * [1.8.13] Compute delivery readiness once, from the same statuses that ship
1105
+ * in the payload. The result message used to tell the model "给出最终答复"
1106
+ * whenever done === total, even when present would immediately refuse the
1107
+ * delivery for legacy/empty evidence. One predicate now feeds the summary,
1108
+ * the instruction block and the durable payload.
1109
+ */
1110
+ const statuses = Array.isArray(result.statuses) ? result.statuses : []
1111
+ const readiness = statuses.length > 0
1112
+ ? deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
1113
+ : null
1114
+ const deliveryBlockers = readiness?.blockers ?? []
954
1115
  const payload = {
955
1116
  kind: 'workplan-result',
956
1117
  version: PLAN_VERSION,
@@ -971,6 +1132,10 @@ export function buildResultMessage(result: any) {
971
1132
  // "never resumed", instead of promising a retry that will be refused.
972
1133
  resumeCount: Number(result.resumeCount ?? 0),
973
1134
  resumeAvailable: result.resumeAvailable === true,
1135
+ // [1.8.13] The delivery verdict travels with the round so a reload cannot
1136
+ // re-derive a more optimistic "done" from the statuses alone.
1137
+ deliveryReady: readiness ? readiness.ready : undefined,
1138
+ deliveryBlockers: deliveryBlockers.slice(0, 12),
974
1139
  }
975
1140
  const blocked = Number(result.stats?.blocked ?? 0)
976
1141
  const paused = Number(result.stats?.pending ?? 0) > 0 && result.phase === 'paused'
@@ -982,7 +1147,6 @@ export function buildResultMessage(result: any) {
982
1147
  * are missing, and what a sibling department asked for. Keeping this out of
983
1148
  * the payload (it is derived) keeps the durable message small.
984
1149
  */
985
- const statuses = Array.isArray(result.statuses) ? result.statuses : []
986
1150
  const unverified = statuses.filter((item: any) => item?.verification === 'unverified')
987
1151
  const failed = statuses.filter((item: any) => item?.verification === 'failed')
988
1152
  const legacy = statuses.filter((item: any) => item?.status === 'done' && item?.verification === 'legacy')
@@ -1004,27 +1168,67 @@ export function buildResultMessage(result: any) {
1004
1168
  if (missingArtifacts.length > 0) {
1005
1169
  review.push(`- 声明产物缺失:${missingArtifacts.slice(0, 10).join(';')}`)
1006
1170
  }
1171
+ /*
1172
+ * [1.8.7] 未完成时不能再命令「给出最终答复」。
1173
+ *
1174
+ * 事故(session-99984ebd…,2026-10-31 12:02):预算到点返回 10/13,本条消息
1175
+ * 第 3 条却写着「给出最终答复」,第 4 条又要求「再次派发续跑」。两条命令
1176
+ * 互相抵触,模型照前者收尾,于是用户在计划只完成 10/13 时拿到了「成品」。
1177
+ * 现在:未完成时第 3 条改为「禁止交付」,恢复动作固定为第 4 条;只有全部
1178
+ * 子任务 done 才允许收尾。
1179
+ */
1180
+ const doneCount = Number(result.stats?.done ?? 0)
1181
+ const totalCount = Number(result.stats?.total ?? 0)
1182
+ const remaining = Math.max(0, totalCount - doneCount)
1183
+ const incomplete = totalCount > 0 && remaining > 0
1184
+ /*
1185
+ * [1.8.13] All rows done but evidence not passing is a distinct blocked
1186
+ * state. It must not fall into the "完成 ⇒ 给出最终答复" branch: present
1187
+ * would reject the very delivery the message just ordered.
1188
+ */
1189
+ const evidenceBlocked = !incomplete && Boolean(readiness && !readiness.ready)
1190
+ /*
1191
+ * [1.8.15] A cancelled round has no legal next dispatch.
1192
+ *
1193
+ * T4e F1/C16 proved the old text ("再次调用 dsh_workplan_dispatch 即可继续跑")
1194
+ * started a real round on a cancelled plan. Cancel is terminal here: no
1195
+ * present, no "已完成", no dispatch — only an honest 未完成 reply.
1196
+ */
1197
+ const cancelled = result.phase === 'cancelled'
1198
+ const shownBlockers = deliveryBlockers.slice(0, 8).join(';')
1199
+ const recovery = blocked > 0
1200
+ ? (result.resumeAvailable === false
1201
+ ? `本计划已用尽自动续跑额度(${Number(result.resumeCount ?? 0)}/${MAX_PLAN_RESUMES}),受阻项不会再自动重跑:请主 Agent 直接接手完成剩余 ${remaining} 项,完成前同样不得交付。`
1202
+ : `受阻项可再次调用 dsh_workplan_dispatch 从受阻处续跑(已完成的不会重跑,本计划剩余续跑额度 ${MAX_PLAN_RESUMES - Number(result.resumeCount ?? 0)} 次)。`)
1203
+ : paused
1204
+ ? `本轮执行预算用尽,剩余 ${Number(result.stats?.pending ?? 0)} 项未完成(不是失败、未计入续跑额度):再次调用 dsh_workplan_dispatch 即可从剩下的步骤继续,已完成的不重跑。`
1205
+ : `剩余 ${remaining} 项子任务还没有完成:再次调用 dsh_workplan_dispatch 即可继续跑,已完成的不重跑。`
1007
1206
  const lines = [
1008
1207
  summary,
1009
1208
  '',
1010
1209
  '各部门子任务结果如下,请主 Agent:',
1011
1210
  '1. 核对每个完成项的证据与验收标准;',
1012
1211
  '2. 处理受阻项,必要时向用户确认;',
1013
- '3. 给出最终答复,不要声称未验证的完成。',
1212
+ ...(cancelled
1213
+ ? [
1214
+ `3. 【已取消但未完成,禁止交付】计划只完成 ${doneCount}/${totalCount},剩余 ${remaining} 项(取消只停止执行,不等于完成):不要调用 present,不要写“已完成/最终版/已交付”,不要给出收尾性最终答复,不要声称未验证的完成。`,
1215
+ '4. 不要再调用 dsh_workplan_dispatch(计划已取消,不会启动任何部门 Agent)。如需继续这项工作,请向用户确认后重新生成计划。答复开头必须写「未完成:剩余 N 项与原因」。',
1216
+ ]
1217
+ : incomplete
1218
+ ? [
1219
+ `3. 【未完成,禁止交付】计划只完成 ${doneCount}/${totalCount},还有 ${remaining} 项没做完:不要调用 present 交付当前产物,不要写“已完成/最终版/已交付”,也不要给出收尾性最终答复,不要声称未验证的完成。`,
1220
+ `4. ${recovery}`,
1221
+ ]
1222
+ : evidenceBlocked
1223
+ ? [
1224
+ `3. 【证据未通过,禁止交付】计划 ${doneCount}/${totalCount} 虽已全部 done,但以下证据缺口未通过:${shownBlockers}${deliveryBlockers.length > 8 ? '…' : ''}。不要调用 present,不要写“已完成/最终版/已交付”,不要给出收尾性最终答复,不要声称未验证的完成。`,
1225
+ '4. 先用 dsh_workplan_update 为这些子任务补齐 verification=\'structured\' 与 acceptance(每项 result=\'pass\',并附证据),或把对应子任务改回 blocked 并写明原因;缺口补齐、deliveryReady 变为 true 之后 present 才会放行。',
1226
+ ]
1227
+ : ['3. 给出最终答复,不要声称未验证的完成。']),
1014
1228
  ...(review.length > 0 ? ['', '验收核对:', ...review] : []),
1015
1229
  ...(needs.length > 0
1016
1230
  ? ['', '跨部门待转达(子 Agent 提出的需求,请逐条处理):', ...needs.slice(0, 10).map((line: string) => `- ${line}`)]
1017
1231
  : []),
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
1232
  '',
1029
1233
  RESULT_MARKER_BEGIN,
1030
1234
  JSON.stringify(payload),
@@ -1037,6 +1241,95 @@ export function buildResultMessage(result: any) {
1037
1241
  })
1038
1242
  }
1039
1243
 
1244
+ /**
1245
+ * [1.8.7] 回合收尾前注入的「计划没做完」指令。
1246
+ *
1247
+ * 事故(session-99984ebd…)里,计划停在 10/13,主 Agent 却已经 present 了报告
1248
+ * 并给出收尾答复。软约束(系统提示词)挡不住这种收尾,所以由 runtime 在
1249
+ * `agent/turn-stopping` 里 `agent.steer()` 这条消息,强制再跑一步去续跑。
1250
+ *
1251
+ * 措辞必须同时做到三件事:说清剩余量、禁止交付措辞、给出唯一恢复动作;不含
1252
+ * 任何「已完成」的暗示,也不假装这是用户说的话(source.kind 单独标记)。
1253
+ */
1254
+ export function buildStopSteerText(input: any) {
1255
+ const stats = input?.stats ?? {}
1256
+ const total = Number(stats.total ?? 0)
1257
+ const done = Number(stats.done ?? 0)
1258
+ const remaining = Math.max(0, total - done)
1259
+ const statuses = Array.isArray(input?.statuses) ? input.statuses : []
1260
+ const snapshot = statuses.length > 0 ? derivePlanSnapshot(statuses) : null
1261
+ const readiness = snapshot ? deliveryReadiness(snapshot, { phase: input?.phase }) : null
1262
+ const blockers = readiness?.blockers ?? []
1263
+ const ids = statuses
1264
+ .filter((item: any) => item?.status !== 'done')
1265
+ .map((item: any) => String(item?.subtaskId ?? ''))
1266
+ .filter((id: string) => id !== '')
1267
+ .slice(0, 10)
1268
+ const runnable = statuses.filter((item: any) => item?.status === 'pending' || item?.status === 'in_progress').length
1269
+ const attempt = Number(input?.attempt ?? 1)
1270
+ const planLabel = `计划 ${String(input?.planId ?? '')}`
1271
+ const footer = `(这是 dsh-workplan 在回合收尾前自动发出的第 ${attempt} 次提醒:计划未通过交付就绪检查,这个回合暂不关闭。)`
1272
+ /*
1273
+ * [1.8.13] One gate, four truthful messages.
1274
+ *
1275
+ * 1.8.8 only steered while `pending/in_progress` existed, so an all-done plan
1276
+ * with legacy/empty evidence closed the turn normally (T5-B/D), and a
1277
+ * cancelled plan was released outright (T5-C). Each branch below keeps the
1278
+ * same contract — no present, no completion wording, start with 未完成 —
1279
+ * but only the first asks for another dispatch, because only it has runnable
1280
+ * work. The others would otherwise spin forever on an empty dispatch.
1281
+ */
1282
+ if (readiness?.cancelled && !readiness.ready) {
1283
+ const scope = remaining > 0
1284
+ ? `已取消,只完成 ${done}/${total},还有 ${remaining} 项没做完${ids.length > 0 ? `(${ids.join('、')})` : ''}`
1285
+ : `已取消,完成 ${done}/${total},但证据未通过:${blockers.slice(0, 4).join(';')}`
1286
+ return [
1287
+ `【计划已取消但未完成 · 禁止收尾】${planLabel} ${scope}。`,
1288
+ '',
1289
+ '取消只停止执行,不等于完成;当前内容不能当作最终结果交付。',
1290
+ '1. 不要再调用 dsh_workplan_dispatch(计划已取消,不会继续执行)。',
1291
+ '2. 不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。',
1292
+ `3. 答复开头必须写「未完成:剩余 ${Math.max(remaining, blockers.length)} 项(列出 ID)与原因」,说明取消原因与未完成范围。`,
1293
+ '',
1294
+ footer,
1295
+ ].join('\n')
1296
+ }
1297
+ if (readiness && !readiness.ready && remaining === 0) {
1298
+ return [
1299
+ `【证据未通过 · 禁止交付】${planLabel} 的 ${done}/${total} 个子任务虽都已 done,但证据未通过:${blockers.slice(0, 8).join(';')}${blockers.length > 8 ? '…' : ''}。`,
1300
+ '',
1301
+ '当前内容不能作为成品交付。请立即处理证据缺口:',
1302
+ "1. 不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。",
1303
+ "2. 用 dsh_workplan_update 为这些子任务补齐 verification='structured' 与 acceptance(每项 result='pass',并附证据),或把对应子任务改回 blocked 并写明原因。",
1304
+ '3. 在证据补齐、deliveryReady 变为 true 之前,不得声称完成;确实无法补齐时,答复开头写「未完成:剩余 N 项与原因」。',
1305
+ '',
1306
+ footer,
1307
+ ].join('\n')
1308
+ }
1309
+ if (remaining > 0 && runnable === 0) {
1310
+ return [
1311
+ `【剩余项全部受阻 · 禁止收尾】${planLabel} 只完成 ${done}/${total},还有 ${remaining} 项没完成${ids.length > 0 ? `(${ids.join('、')})` : ''},当前没有可自动续跑的项。`,
1312
+ '',
1313
+ '现在不能把当前内容当作最终结果交付。',
1314
+ '1. 不要调用 present;不要写“已完成/最终版/已交付”;不要声称完成。',
1315
+ '2. 向用户说明受阻项与原因,答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。',
1316
+ '3. 如用户确认终止,可调用 dsh_workplan_cancel;取消只停止执行,不改变“未完成”的结论。',
1317
+ '',
1318
+ footer,
1319
+ ].join('\n')
1320
+ }
1321
+ return [
1322
+ `【计划未完成 · 禁止收尾】${planLabel} 只完成 ${done}/${total},还有 ${remaining} 项没做完${ids.length > 0 ? `(${ids.join('、')})` : ''}。`,
1323
+ '',
1324
+ '现在不能把当前内容当作最终结果交付。请立即继续:',
1325
+ '1. 调用 dsh_workplan_dispatch(默认 wait)续跑剩余子任务;已完成的不重跑。',
1326
+ '2. 在计划通过交付就绪检查之前:不要调用 present;不要写“已完成/最终版/已交付”;不要输出收尾性最终结论。',
1327
+ '3. 若续跑被拒绝或持续失败,答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」,不得把它包装成成品。',
1328
+ '',
1329
+ footer,
1330
+ ].join('\n')
1331
+ }
1332
+
1040
1333
  function extractBetween(text: any, begin: any, end: any) {
1041
1334
  if (typeof text !== 'string') return null
1042
1335
  const start = text.indexOf(begin)
@@ -1070,7 +1363,26 @@ export function parseResultMessage(message: any) {
1070
1363
  }
1071
1364
  }
1072
1365
 
1073
- export function buildCancelMessage(planId: any, reason: any = '用户取消') {
1366
+ /*
1367
+ * [1.9.2] `workplan-cancel` 信封是 cancelled / superseded 的**唯一写入出口**。
1368
+ *
1369
+ * 规则出处:`_rerun_20261101/GATE_rule_design.md` §6.1(字段 schema)、§7.2
1370
+ * 第 7 条(写入 durable 记录后 replay 仍为 superseded)。写侧任何地方都不得
1371
+ * 自己拼这段 JSON:一旦有第二条拼装路径,`disposition`/`supersededBy` 的字段
1372
+ * 形状就会分叉,replay 与 present 的读侧判定随之失效(正是本子任务要杜绝的
1373
+ * 「绕过」)。
1374
+ *
1375
+ * 语义边界:本函数只负责把**运行时已经核验过**的处置结果写成信封;V1–V8
1376
+ * 核验与 digest 复算在 `src/supersede.ts`(唯一写入者)。因此这里对 superseded
1377
+ * 再做一次防线:`supersededBy.mapping` 与 `digest` 必须能逐字复算,否则抛错、
1378
+ * 不写日志、不改状态(fail-closed)。
1379
+ */
1380
+ export function buildCancelMessage(planId: any, reason: any = '用户取消', terminal: any = null) {
1381
+ const disposition = terminal?.disposition ?? 'cancelled'
1382
+ if (disposition === 'superseded') return buildSupersededMessage(planId, reason, terminal)
1383
+ if (disposition !== 'cancelled') {
1384
+ throw new Error(`buildCancelMessage: 非法处置 disposition=${String(disposition)}`)
1385
+ }
1074
1386
  const summary = `【任务已取消】${truncate(String(reason || '用户取消'), 120)}`
1075
1387
  const payload = {
1076
1388
  kind: 'workplan-cancel',
@@ -1083,6 +1395,69 @@ export function buildCancelMessage(planId: any, reason: any = '用户取消') {
1083
1395
  summary,
1084
1396
  '',
1085
1397
  '这次任务分解已取消。取消只停止后续执行,不会把未完成项标成完成;已完成项保留原记录。',
1398
+ /*
1399
+ * [1.8.13] Cancel is not a delivery permit. The old text stopped at "不会
1400
+ * 标成完成" and never told the model what that means for the reply, so the
1401
+ * T5-C snapshot could cancel 1/3 and then present. The same readiness
1402
+ * predicate now rejects that present, and this message states the output
1403
+ * contract so the model does not try.
1404
+ */
1405
+ '取消不等于完成:如仍有未完成项或证据缺口,不要调用 present,不要写“已完成/最终版/已交付”;',
1406
+ '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。',
1407
+ '',
1408
+ CANCEL_MARKER_BEGIN,
1409
+ JSON.stringify(payload),
1410
+ CANCEL_MARKER_END,
1411
+ ]
1412
+ return makeUserMessage(lines.join('\n'), {
1413
+ kind: 'workplan-cancel',
1414
+ form: 'notice',
1415
+ summary,
1416
+ })
1417
+ }
1418
+
1419
+ /**
1420
+ * [1.9.2] `disposition:'superseded'` 的信封正文(由 `buildCancelMessage` 独占调用)。
1421
+ *
1422
+ * 与 cancelled 共用同一个 `kind:'workplan-cancel'`:旧版本解析器只校验 `kind`
1423
+ * (`parseCancelMessage`),新增字段被忽略后按 cancelled 读——不可派发、不可
1424
+ * 交付,属安全降级(规则文档 §10.3)。这也是「不得新增第二种信封 kind」的原因:
1425
+ * 换 kind 会让旧回放彻底读不到这条处置记录。
1426
+ */
1427
+ function buildSupersededMessage(planId: any, reason: any, terminal: any) {
1428
+ const by = terminal?.supersededBy
1429
+ const verifiable = isRecord(by)
1430
+ && typeof by.planId === 'string'
1431
+ && by.planId !== ''
1432
+ && Array.isArray(by.mapping)
1433
+ && by.mapping.length > 0
1434
+ && isMappingDigest(by.digest)
1435
+ && verifyMappingDigest(by.mapping, by.digest)
1436
+ if (!verifiable) {
1437
+ throw new Error('buildCancelMessage: superseded 信封必须带可复算的 supersededBy.planId/mapping/digest')
1438
+ }
1439
+ const text = String(reason || '责任已转移')
1440
+ const supersededAt = Number.isFinite(Number(terminal?.supersededAt)) ? Number(terminal.supersededAt) : Date.now()
1441
+ const requiredCount = Number(by.requiredCount ?? 0)
1442
+ const coveredCount = Number(by.coveredCount ?? 0)
1443
+ const summary = `【计划已被取代】${truncate(text, 120)}|承接:${by.planId}`
1444
+ + `(映射 ${coveredCount}/${requiredCount})`
1445
+ const payload = {
1446
+ kind: 'workplan-cancel',
1447
+ version: PLAN_VERSION,
1448
+ planId,
1449
+ reason: text,
1450
+ cancelledAt: supersededAt,
1451
+ disposition: 'superseded',
1452
+ supersededAt,
1453
+ supersededBy: by,
1454
+ }
1455
+ const lines = [
1456
+ summary,
1457
+ '',
1458
+ '这次任务分解的责任已转移给一个可验证的承接计划。被取代不等于完成:',
1459
+ '原计划的记录与计数原样保留,未完成项永远不会因为这次转移而变成完成。',
1460
+ '交付时只能使用承接计划通过交付就绪检查的产物;原计划不作为完成证据。',
1086
1461
  '',
1087
1462
  CANCEL_MARKER_BEGIN,
1088
1463
  JSON.stringify(payload),
@@ -1250,7 +1625,19 @@ export function adjudicateResult({ output, strict = true }: any) {
1250
1625
  error: `自检未通过:${failed.map((item: any) => item.criterion).join(';')}`,
1251
1626
  }
1252
1627
  }
1253
- const hasUnverified = acceptance.some((item: any) => item.result === 'unverified')
1628
+ /*
1629
+ * [1.8.13] No acceptance rows is not "structured and passing".
1630
+ *
1631
+ * `acceptance: []` used to fall through to `structured` because only the
1632
+ * literal `unverified` result was checked. A child that omitted the whole
1633
+ * acceptance list therefore looked better than one that honestly marked a
1634
+ * row unverified. Treat the absence of a check as unverified evidence; the
1635
+ * main Agent can still supply a real check through `dsh_workplan_update`
1636
+ * (now carrying verification/acceptance), and delivery readiness will then
1637
+ * re-evaluate it.
1638
+ */
1639
+ const hasUnverified = acceptance.length === 0
1640
+ || acceptance.some((item: any) => item.result === 'unverified')
1254
1641
  return {
1255
1642
  status: 'done',
1256
1643
  verification: hasUnverified ? 'unverified' : 'structured',
@@ -1271,6 +1658,19 @@ export function buildUpdateMessage(update: any) {
1271
1658
  ...(update.progress === undefined ? {} : { progress: update.progress }),
1272
1659
  ...(update.note === undefined ? {} : { note: update.note }),
1273
1660
  ...(update.evidence === undefined ? {} : { evidence: update.evidence }),
1661
+ /*
1662
+ * [1.8.13] A manual verdict is now allowed to carry real evidence.
1663
+ *
1664
+ * `dsh_workplan_update` could set `status:'done'` but had no field for
1665
+ * verification/acceptance, and this durable message only carried a free
1666
+ * text note. After a refresh the evidence was gone, so the row came back
1667
+ * as done-without-proof and present had no way to recover. Persisting the
1668
+ * structured fields makes the repair itself replayable.
1669
+ */
1670
+ ...(update.verification === undefined ? {} : { verification: update.verification }),
1671
+ ...(update.acceptance === undefined ? {} : { acceptance: update.acceptance }),
1672
+ ...(update.artifacts === undefined ? {} : { artifacts: update.artifacts }),
1673
+ ...(update.missingArtifacts === undefined ? {} : { missingArtifacts: update.missingArtifacts }),
1274
1674
  ...(update.revision === undefined ? {} : { revision: update.revision }),
1275
1675
  at: update.at ?? Date.now(),
1276
1676
  }
@@ -1891,6 +2291,11 @@ export function planPhase(statuses: any, _resultSeen = false) {
1891
2291
  * 它们携带状态列表里没有的信息(预算暂停、用户取消)。
1892
2292
  */
1893
2293
  export function reconcilePhase(phase: any, statuses: any) {
2294
+ /*
2295
+ * [1.9.0] 终态优先:superseded 的记录即使状态全部 done,也不得被对账成
2296
+ * done(T8 §5.5 C6)。cancelled 保持 1.8.19 的既有对账语义不变。
2297
+ */
2298
+ if (phase === 'superseded') return phase
1894
2299
  const derived = planPhase(statuses)
1895
2300
  if (derived === 'done') return 'done'
1896
2301
  if (phase === 'done' || phase === 'integrating') return derived
@@ -1900,6 +2305,91 @@ export function reconcilePhase(phase: any, statuses: any) {
1900
2305
  return phase ?? derived
1901
2306
  }
1902
2307
 
2308
+ /**
2309
+ * [1.8.13] The one machine-checkable definition of "this plan may be delivered".
2310
+ *
2311
+ * `status === 'done'` only says the child claims to be finished. 1.8.9 enforced
2312
+ * three hard gaps (failed self-check, failed acceptance row, missing declared
2313
+ * file) and treated a cancelled plan as complete, so three incident snapshots
2314
+ * still reached `present`:
2315
+ *
2316
+ * - B: all done + `legacy` verification + empty acceptance → allowed;
2317
+ * - C: cancelled 1/3 → allowed (cancel short-circuited "incomplete");
2318
+ * - D: all done + `acceptance: []` → adjudicated as `structured`.
2319
+ *
2320
+ * `present`, the result message, the turn-stopping gate and every status
2321
+ * payload now read this single predicate, so the four "done" judgments cannot
2322
+ * disagree again. Cancelling stops execution; it does not finish the work.
2323
+ */
2324
+ export interface DeliveryReadiness {
2325
+ ready: boolean
2326
+ total: number
2327
+ done: number
2328
+ remaining: string[]
2329
+ blockers: string[]
2330
+ cancelled: boolean
2331
+ }
2332
+
2333
+ function verificationGap(item: any) {
2334
+ const verification = typeof item?.verification === 'string' ? item.verification : ''
2335
+ if (verification === 'structured') return ''
2336
+ if (verification === '') return '未提供自检结果(verification)'
2337
+ if (verification === 'legacy') return '旧格式回传,没有结构化自检'
2338
+ if (verification === 'unverified') return '自检标记为未验证'
2339
+ if (verification === 'failed') return '自检失败'
2340
+ if (verification === 'unparsable') return '自检块无法解析'
2341
+ return `自检状态非法:${verification}`
2342
+ }
2343
+
2344
+ export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any } = {}): DeliveryReadiness {
2345
+ const phase = typeof options.phase === 'string' ? options.phase : ''
2346
+ const statuses = Array.isArray(snapshot?.statuses) ? snapshot.statuses : []
2347
+ const remaining: string[] = []
2348
+ const blockers: string[] = []
2349
+ for (const item of statuses) {
2350
+ const id = String((item as any)?.subtaskId ?? '')
2351
+ if (item?.status !== 'done') {
2352
+ if (id) remaining.push(id)
2353
+ continue
2354
+ }
2355
+ const gap = verificationGap(item)
2356
+ if (gap) blockers.push(`${id} ${gap}`)
2357
+ const acceptance = Array.isArray((item as any)?.acceptance) ? (item as any).acceptance : []
2358
+ /*
2359
+ * An empty acceptance list is not "everything passed"; it is the absence
2360
+ * of a check. `adjudicateResult` used to call that `structured`, which is
2361
+ * exactly how the T5-D snapshot still looked deliverable.
2362
+ */
2363
+ if (acceptance.length === 0) blockers.push(`${id} 未提供验收项(acceptance 为空)`)
2364
+ for (const entry of acceptance) {
2365
+ if (entry?.result !== 'pass') {
2366
+ blockers.push(`${id} 验收未通过:${truncate(String(entry?.criterion ?? '未命名验收项'), 80)}`)
2367
+ }
2368
+ }
2369
+ const missing = Array.isArray((item as any)?.missingArtifacts) ? (item as any).missingArtifacts : []
2370
+ if (missing.length > 0) blockers.push(`${id} 缺少声明产物:${missing.slice(0, 5).join('、')}`)
2371
+ const artifacts = Array.isArray((item as any)?.artifacts) ? (item as any).artifacts : []
2372
+ for (const artifact of artifacts) {
2373
+ if (artifact?.exists === false) {
2374
+ blockers.push(`${id} 声明产物不存在:${truncate(String(artifact?.ref ?? '未命名产物'), 120)}`)
2375
+ }
2376
+ }
2377
+ }
2378
+ const done = Number(snapshot?.stats?.done ?? 0)
2379
+ const total = Number(snapshot?.stats?.total ?? 0)
2380
+ if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2381
+ blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`)
2382
+ }
2383
+ return {
2384
+ ready: total > 0 && remaining.length === 0 && blockers.length === 0,
2385
+ total,
2386
+ done,
2387
+ remaining,
2388
+ blockers,
2389
+ cancelled: phase === 'cancelled',
2390
+ }
2391
+ }
2392
+
1903
2393
  export function nextReadyInStage(plan: any, statuses: any[], stageId: string) {
1904
2394
  const byId = new Map(statuses.map((item: any) => [item.subtaskId, item]))
1905
2395
  const stage = plan.stages.find((item: any) => item.id === stageId)
@@ -2121,7 +2611,36 @@ export function buildChildPrompt({
2121
2611
  '请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
2122
2612
  ].join('\n')
2123
2613
  : ''
2124
- return [
2614
+ /*
2615
+ * [1.8.19] A retried subtask must not pretend the prior attempt never existed.
2616
+ *
2617
+ * The timeout/budget paths record the declared outputs that already landed on
2618
+ * disk (`artifacts[].exists === true`). Feeding them back into the next
2619
+ * attempt turns a 15-minute restart into "check what is there and finish",
2620
+ * which is the difference between a recoverable ceiling and silent rework.
2621
+ */
2622
+ const previousStatus = Array.isArray(statuses)
2623
+ ? statuses.find((item: any) => item && item.subtaskId === subtask?.id)
2624
+ : null
2625
+ const landedArtifacts = (Array.isArray(previousStatus?.artifacts) ? previousStatus.artifacts : [])
2626
+ .filter((item: any) => item && item.exists === true && typeof item.ref === 'string')
2627
+ .map((item: any) => String(item.ref))
2628
+ const resumeHint = landedArtifacts.length > 0
2629
+ ? [
2630
+ '',
2631
+ '上一次这一子任务被中止,但以下声明产物已经在盘上(先用 read/grep 核对,不要重写):',
2632
+ ...landedArtifacts.slice(0, 8).map((ref: string) => `- ${ref}`),
2633
+ '已经覆盖验收标准的部分保持原样,只补缺失部分;结尾按契约给出证据块。',
2634
+ ].join('\n')
2635
+ : ''
2636
+ /*
2637
+ * [1.8.12] 提示词整体过一遍 session-reference 消毒。
2638
+ *
2639
+ * 背景、依赖结果、兄弟部门摘要都可能是父会话原文的摘录,任何一处出现
2640
+ * 裸的 `dsh-session:<payload>` 都会让子 Agent 的首轮在 harness 里直接失败。
2641
+ * 在唯一的出口统一消毒,避免逐个字段漏掉。
2642
+ */
2643
+ return defuseSessionReferenceText([
2125
2644
  `你是「${departmentLabel(subtask.department)}」部门的执行 Agent,只负责下面这一个子任务。`,
2126
2645
  '',
2127
2646
  `全局任务:${understanding.originalRequest ?? '(未记录)'}`,
@@ -2146,6 +2665,7 @@ export function buildChildPrompt({
2146
2665
  dependencies,
2147
2666
  ...(team ? ['', '兄弟部门进展(同一计划内的其他子任务;不要直接联系它们,需要协作请写进 needs 由主 Agent 转达):', team] : []),
2148
2667
  ...(failure ? [failure] : []),
2668
+ ...(resumeHint ? [resumeHint] : []),
2149
2669
  '',
2150
2670
  '执行要求:',
2151
2671
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',
@@ -2166,5 +2686,5 @@ export function buildChildPrompt({
2166
2686
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
2167
2687
  '- 需要其他部门配合时写进 needs(每条一句话),主 Agent 会转达;不要直连其他子 Agent。',
2168
2688
  '- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
2169
- ].join('\n')
2689
+ ].join('\n'))
2170
2690
  }