dsh-workplan 1.9.1 → 1.11.0

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
@@ -48,6 +48,8 @@ export const PRESENT_DENY_CODES = {
48
48
  EVIDENCE_GAP: 'EVIDENCE_GAP',
49
49
  CANCELLED_NAMED: 'CANCELLED_NAMED',
50
50
  SUPERSEDED_STALE: 'SUPERSEDED_STALE',
51
+ /* [1.11.0] 子会话不是交付主体:present 只能由根会话发起(T7 P9)。 */
52
+ NOT_ROOT: 'NOT_ROOT',
51
53
  } as const
52
54
 
53
55
  export type PresentDenyCode = (typeof PRESENT_DENY_CODES)[keyof typeof PRESENT_DENY_CODES]
@@ -109,6 +111,71 @@ export const EVIDENCE_STATUSES = Object.freeze(['done', 'blocked', 'partial'])
109
111
  export const ACCEPTANCE_RESULTS = Object.freeze(['pass', 'fail', 'unverified'])
110
112
 
111
113
  export const STATUSES = Object.freeze(['pending', 'in_progress', 'done', 'blocked'])
114
+ /**
115
+ * [1.11.0] 正交闭环状态(T4 C-01 / T6 M1)。
116
+ *
117
+ * `status` 仍是唯一的呈现层四值枚举,左侧栏、计数、交付门禁全部只看它。
118
+ * `closure` 记录「这条子任务在双向闭环里走到哪一步」:是否被接收方确认、
119
+ * 是否在等待主 Agent 指示、是否已回报。两者同时写入同一条状态条目,但只有
120
+ * `applyStatus` 一个写入口,不引入第二份存储。
121
+ *
122
+ * 历史日志没有 `closure`(`undefined`)时按 `null` 解释,语义退回 1.10.6;
123
+ * 因此旧会话回放、旧测试夹具都不需要迁移。
124
+ */
125
+ export const CLOSURES = Object.freeze([
126
+ 'pending',
127
+ 'assigned',
128
+ 'acknowledged',
129
+ 'instructed',
130
+ 'escalated',
131
+ 'blocked',
132
+ 'done',
133
+ 'reported',
134
+ 'replanned',
135
+ ])
136
+ /** Why a `blocked` / `escalated` row stopped. Read by the dashboard and result message. */
137
+ export const BLOCKED_KINDS = Object.freeze(['failed', 'timeout', 'no-ack', 'escalated'])
138
+ /**
139
+ * [1.11.0] 合法闭环迁移(T4 §4 的 19 条,M1)。
140
+ *
141
+ * 没有这张表时,「已重规划」的行可以被重新派发、「已完成」的行能被写成
142
+ * 「等待指示」,状态机只是装饰。`applyStatus` 在这里拒绝契约外迁移并抛
143
+ * `INVALID_TRANSITION`;`null`(历史日志 / 全新行)不设入边限制。
144
+ *
145
+ * 注意 `pending` 仍可作为「重置」的目标:续跑会把未完成行重新排队,这是
146
+ * 1.10.x 就有的既有语义,不是新增的合法化。
147
+ */
148
+ export const CLOSURE_TRANSITIONS: Record<string, readonly string[]> = Object.freeze({
149
+ pending: Object.freeze(['assigned', 'blocked', 'instructed', 'escalated', 'done', 'reported', 'replanned']),
150
+ assigned: Object.freeze(['acknowledged', 'escalated', 'blocked', 'done', 'replanned', 'pending']),
151
+ acknowledged: Object.freeze(['escalated', 'blocked', 'done', 'replanned', 'pending']),
152
+ escalated: Object.freeze(['instructed', 'blocked', 'replanned', 'pending']),
153
+ instructed: Object.freeze(['acknowledged', 'done', 'blocked', 'escalated', 'replanned']),
154
+ // 'assigned' 是既有重试路径:同一行的第 2 次尝试会重新下发(1.10.3 行为)。
155
+ blocked: Object.freeze(['assigned', 'instructed', 'pending', 'escalated', 'done', 'replanned']),
156
+ done: Object.freeze(['reported', 'replanned', 'pending', 'blocked']),
157
+ reported: Object.freeze(['replanned', 'pending', 'blocked']),
158
+ replanned: Object.freeze([]),
159
+ })
160
+ export const MAX_QUESTION_CHARS = 2000
161
+ export const MAX_ESCALATION_OPTIONS = 6
162
+ export const MAX_INSTRUCTION_CHARS = 4000
163
+ /*
164
+ * [1.11.0] 跨部门协作闭环(T2 G8 / 用户 m00687)。
165
+ *
166
+ * `needs` 原先只是一段被结果消息顺带转达的文本:主 Agent 忘了处理,计划照样
167
+ * 可交付;下游部门拿不到上游的交接物,也没人记录「这条需求最后怎么办了」。
168
+ * 这里把每条需求升级成一条有生命周期的 handoff,挂在提出需求的那一行上:
169
+ * - open :已记录,还没指派给任何部门(交付门禁拦截);
170
+ * - routed :已指派给某个部门,等工作产出(交付门禁拦截);
171
+ * - answered :已给出书面答复或已由对应子任务交付(解除拦截);
172
+ * - closed :经判定无需动作(解除拦截)。
173
+ * 不新建存储:handoff 与 status 同表、同写入口,刷新后随状态行一起回放。
174
+ */
175
+ export const HANDOFF_STATUSES = Object.freeze(['open', 'routed', 'answered', 'closed'])
176
+ /* needs 上限是 10;handoff 上限更小时,第 9/10 条会「不登记、不拦门禁」地消失。 */
177
+ export const MAX_HANDOFFS = MAX_EVIDENCE_NEEDS
178
+ export const MAX_HANDOFF_RESPONSE_CHARS = 4000
112
179
  export const LIKELIHOODS = Object.freeze(['low', 'medium', 'high'])
113
180
 
114
181
  export const DEPARTMENTS = Object.freeze({
@@ -800,8 +867,14 @@ export function extractJson(text: any) {
800
867
 
801
868
  export function departmentLabel(id: any, language: any = 'zh') {
802
869
  const entry = DEPARTMENTS[id as keyof typeof DEPARTMENTS]
803
- if (!entry) return id
804
- return language === 'en' ? entry.en : entry.zh
870
+ if (entry) return language === 'en' ? entry.en : entry.zh
871
+ /*
872
+ * [1.11.0] 部门名会进入子 Agent 提示词首行(「你是「X」部门的执行 Agent」)。
873
+ * 历史日志或 replan 里的非法值若原样回显,等于给提示词开了一个注入口;
874
+ * 这里只保留可打印的短标签,未知值统一显示为「未知部门」。
875
+ */
876
+ const raw = typeof id === 'string' ? id.replace(/[\r\n`"'<>]/g, '').trim().slice(0, 40) : ''
877
+ return raw === '' ? '未知部门' : raw
805
878
  }
806
879
 
807
880
  export function buildPlannerPrompt(taskText: any, cwd: any, conversationContext: any = '', budget: any = {}) {
@@ -1000,6 +1073,17 @@ export function buildPlanMessage(plan: any, options: any = {}) {
1000
1073
  summary,
1001
1074
  ...(warning ? ['', warning] : []),
1002
1075
  '',
1076
+ /*
1077
+ * [1.11.0] 计划消息必须给出唯一的下一步。
1078
+ *
1079
+ * 1.10.6 只展示计划,模型有时把「已生成计划」当成「已下发」,用户看到的
1080
+ * 就是一条静止的分解。现在把「不派发就不启动」写成明确指令;plan 模式
1081
+ * 例外,否则会和「等用户审阅」互相矛盾。
1082
+ */
1083
+ options.planMode === true
1084
+ ? '下一步:当前处于 plan 模式,先把计划交给用户审阅;用户退出 plan 模式后,再调用 dsh_workplan_dispatch 执行。'
1085
+ : '下一步:必须调用 dsh_workplan_dispatch 派发本计划;只展示计划而不派发,部门 Agent 不会启动。',
1086
+ '',
1003
1087
  PLAN_MARKER_BEGIN,
1004
1088
  JSON.stringify(payload),
1005
1089
  PLAN_MARKER_END,
@@ -1083,7 +1167,11 @@ export function buildResultSummary(result: any) {
1083
1167
  */
1084
1168
  const statuses = Array.isArray(result.statuses) ? result.statuses : []
1085
1169
  if (statuses.length > 0) {
1086
- const readiness = deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
1170
+ const readiness = deliveryReadiness(derivePlanSnapshot(statuses), {
1171
+ phase: result.phase,
1172
+ changePending: result.changePending === true,
1173
+ reportPending: result.reportPending === true,
1174
+ })
1087
1175
  if (!readiness.ready) {
1088
1176
  const shown = readiness.blockers.slice(0, 2).join(';')
1089
1177
  return truncate(
@@ -1109,7 +1197,11 @@ export function buildResultMessage(result: any) {
1109
1197
  */
1110
1198
  const statuses = Array.isArray(result.statuses) ? result.statuses : []
1111
1199
  const readiness = statuses.length > 0
1112
- ? deliveryReadiness(derivePlanSnapshot(statuses), { phase: result.phase })
1200
+ ? deliveryReadiness(derivePlanSnapshot(statuses), {
1201
+ phase: result.phase,
1202
+ changePending: result.changePending === true,
1203
+ reportPending: result.reportPending === true,
1204
+ })
1113
1205
  : null
1114
1206
  const deliveryBlockers = readiness?.blockers ?? []
1115
1207
  const payload = {
@@ -1150,12 +1242,44 @@ export function buildResultMessage(result: any) {
1150
1242
  const unverified = statuses.filter((item: any) => item?.verification === 'unverified')
1151
1243
  const failed = statuses.filter((item: any) => item?.verification === 'failed')
1152
1244
  const legacy = statuses.filter((item: any) => item?.status === 'done' && item?.verification === 'legacy')
1245
+ /*
1246
+ * [1.11.0] 待指示项必须在结果消息里单独成行。
1247
+ *
1248
+ * 它们和普通 blocked 不一样:普通 blocked 是“做失败了”,这些是“做到一半
1249
+ * 停下来等人拍板”。如果只混在 blocked 计数里,主 Agent 会直接 dispatch
1250
+ * 续跑,而 resetBlockedStatuses 现在会跳过它们,于是一轮什么也没发生。
1251
+ */
1252
+ const escalations = statuses.filter((item: any) => item?.closure === 'escalated')
1153
1253
  const missingArtifacts = statuses.flatMap((item: any) =>
1154
1254
  (Array.isArray(item?.missingArtifacts) ? item.missingArtifacts : [])
1155
1255
  .map((ref: any) => `${item.subtaskId}:${ref}`))
1156
- const needs = statuses.flatMap((item: any) =>
1157
- (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${need}`))
1256
+ /*
1257
+ * [1.11.0] 结果消息里的跨部门需求必须带可操作编号(用户 m00687)。
1258
+ *
1259
+ * 只列一段需求原文时,主 Agent 只能「知道有这回事」,无法在下一轮用
1260
+ * `dsh_workplan_handoff` 精确处置。优先读 handoffs(带 H 编号与状态),
1261
+ * 没有 handoffs 的旧记录才退回 needs 原文。
1262
+ */
1263
+ const needs = statuses.flatMap((item: any) => {
1264
+ const handoffs = Array.isArray(item?.handoffs) ? item.handoffs : []
1265
+ if (handoffs.length > 0) {
1266
+ return handoffs.map((handoff: any) =>
1267
+ `${item.subtaskId} ${String(handoff?.id ?? 'H?')}(${String(handoff?.status ?? 'open')}):${String(handoff?.request ?? '')}`)
1268
+ }
1269
+ return (Array.isArray(item?.needs) ? item.needs : []).map((need: any) => `${item.subtaskId}:${need}`)
1270
+ })
1158
1271
  const review: string[] = []
1272
+ if (escalations.length > 0) {
1273
+ const detail = escalations.slice(0, 5).map((item: any) => {
1274
+ const question = typeof item?.question === 'string' && item.question.trim() !== ''
1275
+ ? `问题:${truncate(item.question, 120)}`
1276
+ : '未附问题文本(按受阻处理)'
1277
+ return `${item.subtaskId}(${question})`
1278
+ }).join(';')
1279
+ review.push(
1280
+ `- 待指示 ${escalations.length} 条:${detail}。这些行不会自动续跑:先用 dsh_workplan_update 给出指示(status=in_progress + instruction)或明确放弃(status=blocked),再处理其余项。`,
1281
+ )
1282
+ }
1159
1283
  if (unverified.length > 0) {
1160
1284
  review.push(`- 未验证 ${unverified.length} 条:${unverified.map((item: any) => item.subtaskId).join('、')}(完成但证据不足,需主 Agent 核对)`)
1161
1285
  }
@@ -1196,7 +1320,10 @@ export function buildResultMessage(result: any) {
1196
1320
  */
1197
1321
  const cancelled = result.phase === 'cancelled'
1198
1322
  const shownBlockers = deliveryBlockers.slice(0, 8).join(';')
1199
- const recovery = blocked > 0
1323
+ const escalationIds = escalations.slice(0, 8).map((item: any) => item.subtaskId).join('、')
1324
+ const recovery = escalations.length > 0
1325
+ ? `本轮有 ${escalations.length} 条待指示项(${escalationIds}),它们不会自动续跑:请先用 dsh_workplan_update 对每条给出指示(status='in_progress' + instruction,投递成功后 closure 变为 instructed)或明确放弃(status='blocked'),处理完这些请示后再 dispatch 其余项。`
1326
+ : blocked > 0
1200
1327
  ? (result.resumeAvailable === false
1201
1328
  ? `本计划已用尽自动续跑额度(${Number(result.resumeCount ?? 0)}/${MAX_PLAN_RESUMES}),受阻项不会再自动重跑:请主 Agent 直接接手完成剩余 ${remaining} 项,完成前同样不得交付。`
1202
1329
  : `受阻项可再次调用 dsh_workplan_dispatch 从受阻处续跑(已完成的不会重跑,本计划剩余续跑额度 ${MAX_PLAN_RESUMES - Number(result.resumeCount ?? 0)} 次)。`)
@@ -1227,7 +1354,7 @@ export function buildResultMessage(result: any) {
1227
1354
  : ['3. 给出最终答复,不要声称未验证的完成。']),
1228
1355
  ...(review.length > 0 ? ['', '验收核对:', ...review] : []),
1229
1356
  ...(needs.length > 0
1230
- ? ['', '跨部门待转达(子 Agent 提出的需求,请逐条处理):', ...needs.slice(0, 10).map((line: string) => `- ${line}`)]
1357
+ ? ['', '跨部门待转达(子 Agent 提出的需求;用 dsh_workplan_handoff 逐条 assign/resolve/close,未处置会拦住交付):', ...needs.slice(0, 10).map((line: string) => `- ${line}`)]
1231
1358
  : []),
1232
1359
  '',
1233
1360
  RESULT_MARKER_BEGIN,
@@ -1258,7 +1385,13 @@ export function buildStopSteerText(input: any) {
1258
1385
  const remaining = Math.max(0, total - done)
1259
1386
  const statuses = Array.isArray(input?.statuses) ? input.statuses : []
1260
1387
  const snapshot = statuses.length > 0 ? derivePlanSnapshot(statuses) : null
1261
- const readiness = snapshot ? deliveryReadiness(snapshot, { phase: input?.phase }) : null
1388
+ const readiness = snapshot
1389
+ ? deliveryReadiness(snapshot, {
1390
+ phase: input?.phase,
1391
+ changePending: input?.changePending === true,
1392
+ reportPending: input?.reportPending === true,
1393
+ })
1394
+ : null
1262
1395
  const blockers = readiness?.blockers ?? []
1263
1396
  const ids = statuses
1264
1397
  .filter((item: any) => item?.status !== 'done')
@@ -1482,15 +1615,57 @@ export function parseCancelMessage(message: any) {
1482
1615
  }
1483
1616
  }
1484
1617
 
1618
+ /**
1619
+ * [1.11.0] 验收覆盖:计划写了什么,证据就必须逐条回应什么。
1620
+ *
1621
+ * 1.10.6 只检查证据自身的 result/evidence,于是子 Agent 写一条自创的
1622
+ * 「自创验收项:pass」就能把 5 条计划验收全部绕开(T5 C4 / T10 D-01)。
1623
+ * 这里用规范化后的包含关系做匹配:允许「必须给出命令与退出码」与
1624
+ * 「给出命令与退出码」这类措辞差异,但不允许完全不同的一条顶替。
1625
+ * 短文本(< 6 字)只接受等值,避免 "ok" 命中任意单词。
1626
+ */
1627
+ export function normaliseCriterion(value: any) {
1628
+ return String(value ?? '')
1629
+ .toLowerCase()
1630
+ .replace(/[\s,。;、,.;::!!??"'“”‘’()()\[\]【】《》<>]/g, '')
1631
+ .replace(/^(必须|需要|应当|应该|请|务必)/, '')
1632
+ }
1633
+
1634
+ export function acceptanceCoverage(expected: any, actual: any) {
1635
+ const want = (Array.isArray(expected) ? expected : []).map(normaliseCriterion).filter(Boolean)
1636
+ const got = (Array.isArray(actual) ? actual : [])
1637
+ .map((item: any) => normaliseCriterion(item?.criterion))
1638
+ .filter(Boolean)
1639
+ const missing: string[] = []
1640
+ for (const [index, criterion] of want.entries()) {
1641
+ const covered = got.some((row: string) => {
1642
+ if (row === criterion) return true
1643
+ if (Math.min(row.length, criterion.length) < 6) return false
1644
+ return row.includes(criterion) || criterion.includes(row)
1645
+ })
1646
+ if (!covered) missing.push(String((Array.isArray(expected) ? expected : [])[index] ?? criterion))
1647
+ }
1648
+ return { total: want.length, covered: want.length - missing.length, missing }
1649
+ }
1650
+
1485
1651
  function readEvidenceAcceptance(value: any) {
1486
1652
  if (!Array.isArray(value)) return []
1487
1653
  return value.slice(0, MAX_EVIDENCE_ACCEPTANCE).map((item: any) => {
1488
1654
  const source = isRecord(item) ? item : {}
1489
- const result = ACCEPTANCE_RESULTS.includes(source.result) ? source.result : 'unverified'
1655
+ const stated = ACCEPTANCE_RESULTS.includes(source.result) ? source.result : 'unverified'
1656
+ const evidence = truncate(String(source.evidence ?? ''), 300)
1657
+ /*
1658
+ * [1.11.0] C-19:`pass` 必须有证据。
1659
+ *
1660
+ * 「验收:pass,证据:空」是自述而不是验证。1.10.6 把它当通过,于是
1661
+ * 子 Agent 只要写一排 pass 就能让验收表全绿。没有证据的 pass 降级为
1662
+ * `unverified`,交付门禁据此继续拦,而不是被一行空字符串骗过。
1663
+ */
1664
+ const result = stated === 'pass' && evidence.trim() === '' ? 'unverified' : stated
1490
1665
  return {
1491
1666
  criterion: truncate(String(source.criterion ?? ''), 500),
1492
1667
  result,
1493
- evidence: truncate(String(source.evidence ?? ''), 300),
1668
+ evidence,
1494
1669
  }
1495
1670
  }).filter((item: any) => item.criterion !== '')
1496
1671
  }
@@ -1513,6 +1688,90 @@ function readEvidenceNeeds(value: any) {
1513
1688
  .filter(Boolean)
1514
1689
  }
1515
1690
 
1691
+ /**
1692
+ * [1.11.0] 跨部门需求的唯一规范化入口(用户 m00687)。
1693
+ *
1694
+ * 去重键是 `request` 文本:同一条需求可能出现在结果块、人工改判、结果消息
1695
+ * 回放三条路径上,重复登记会让交付门禁数出 3 条未落实。状态、部门、答复
1696
+ * 都由服务端校验,客户端与模型只能提供文本。
1697
+ */
1698
+ export function normaliseHandoffs(value: any): any[] {
1699
+ const list = Array.isArray(value) ? value : []
1700
+ const seen = new Set<string>()
1701
+ const out: any[] = []
1702
+ for (const raw of list.slice(0, MAX_HANDOFFS)) {
1703
+ if (!isRecord(raw)) continue
1704
+ const request = truncate(String(raw.request ?? ''), 300).trim()
1705
+ if (!request || seen.has(request)) continue
1706
+ seen.add(request)
1707
+ const status = HANDOFF_STATUSES.includes(raw.status) ? raw.status : 'open'
1708
+ const department = typeof raw.department === 'string' && DEPARTMENTS[raw.department as keyof typeof DEPARTMENTS]
1709
+ ? raw.department
1710
+ : null
1711
+ const response = truncate(String(raw.response ?? ''), MAX_HANDOFF_RESPONSE_CHARS).trim() || null
1712
+ out.push({
1713
+ id: truncate(String(raw.id ?? ''), 16).trim() || `H${out.length + 1}`,
1714
+ request,
1715
+ department,
1716
+ status,
1717
+ response,
1718
+ at: numberOrNull(raw.at) ?? Date.now(),
1719
+ updatedAt: numberOrNull(raw.updatedAt) ?? numberOrNull(raw.at) ?? Date.now(),
1720
+ by: ['child', 'agent', 'system'].includes(raw.by) ? raw.by : 'system',
1721
+ })
1722
+ }
1723
+ return out
1724
+ }
1725
+
1726
+ /**
1727
+ * 每一条 `needs` 都必须变成一条可追踪的 handoff。
1728
+ *
1729
+ * 已经登记过的需求(无论最后是 answered 还是 closed)保留原状态,不会因为
1730
+ * 结果消息再次回放而退回 open;这是「处理过的事情不能被重放抹掉」的最基本
1731
+ * 要求,也是交付门禁能给出稳定结论的前提。
1732
+ */
1733
+ export function mergeHandoffsFromNeeds(current: any, needs: any): any[] {
1734
+ const next = normaliseHandoffs(current)
1735
+ const list = Array.isArray(needs) ? needs : []
1736
+ for (const raw of list) {
1737
+ const request = truncate(String(raw ?? ''), 300).trim()
1738
+ if (!request) continue
1739
+ if (next.some((item) => item.request === request)) continue
1740
+ if (next.length >= MAX_HANDOFFS) break
1741
+ next.push({
1742
+ id: `H${next.length + 1}`,
1743
+ request,
1744
+ department: null,
1745
+ status: 'open',
1746
+ response: null,
1747
+ at: Date.now(),
1748
+ updatedAt: Date.now(),
1749
+ by: 'child',
1750
+ })
1751
+ }
1752
+ return next
1753
+ }
1754
+
1755
+ /** 还挡着交付的跨部门需求(open/routed),answered/closed 视为已处理。 */
1756
+ export function openHandoffs(status: any): any[] {
1757
+ const list = Array.isArray(status?.handoffs) ? status.handoffs : []
1758
+ return list.filter((item: any) => item?.status === 'open' || item?.status === 'routed')
1759
+ }
1760
+
1761
+ /**
1762
+ * [1.11.0] Candidate decisions attached to an escalation.
1763
+ *
1764
+ * The main Agent is asked to decide, not to guess. Options are advisory text,
1765
+ * never auto-applied: an option the child invented must not become an
1766
+ * instruction just because it was listed first.
1767
+ */
1768
+ function readEvidenceOptions(value: any) {
1769
+ if (!Array.isArray(value)) return []
1770
+ return value.slice(0, MAX_ESCALATION_OPTIONS)
1771
+ .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
1772
+ .filter(Boolean)
1773
+ }
1774
+
1516
1775
  /**
1517
1776
  * Parse the child's structured evidence block.
1518
1777
  *
@@ -1549,7 +1808,7 @@ const BLOCKED_LINE = /^\s*(BLOCKED|受阻|无法完成)\s*[::]\s*/i
1549
1808
  * the acceptance table cannot drift apart between the runtime and the replay.
1550
1809
  * It never invents evidence and never upgrades a failed self-check to done.
1551
1810
  */
1552
- export function adjudicateResult({ output, strict = true }: any) {
1811
+ export function adjudicateResult({ output, strict = true, expectedAcceptance = [] }: any) {
1553
1812
  const text = typeof output === 'string' ? output : ''
1554
1813
  const parsed = parseEvidenceBlock(text)
1555
1814
  if (!strict) {
@@ -1586,12 +1845,40 @@ export function adjudicateResult({ output, strict = true }: any) {
1586
1845
  error: text.replace(BLOCKED_LINE, '').trim() || '子 Agent 报告受阻',
1587
1846
  }
1588
1847
  }
1589
- return { status: 'done', verification: 'legacy', acceptance: [], artifacts: [], needs: [], error: null }
1848
+ /*
1849
+ * [1.11.0] 沉默不是成功(C-05 / M3)。
1850
+ *
1851
+ * 1.10.6 在这里返回 `done/legacy`:子 Agent 只回一段散文、没有证据块、
1852
+ * 也没写 BLOCKED,就被记成「已完成」。进度栏先显示完成,交付门禁再事后
1853
+ * 拦一次,用户看到的是「明明做完了却交付不了」。完成必须有结构化回报,
1854
+ * 没有回报只能算未完成,并明确写出缺什么。
1855
+ *
1856
+ * `strict:false` 保留旧行为,用于回放 1.11.0 之前的会话日志。
1857
+ */
1858
+ return {
1859
+ status: 'blocked',
1860
+ verification: 'unverified',
1861
+ acceptance: [],
1862
+ artifacts: [],
1863
+ needs: [],
1864
+ error: '子 Agent 未提供结构化证据块(完成必回报):结果块缺失,无法确认验收项是否真的通过',
1865
+ }
1590
1866
  }
1591
1867
  const payload: any = parsed.payload
1592
1868
  const acceptance = readEvidenceAcceptance(payload.acceptance)
1593
1869
  const artifacts = readEvidenceArtifacts(payload.artifacts)
1594
1870
  const needs = readEvidenceNeeds(payload.needs)
1871
+ /*
1872
+ * [1.11.0] A blocked result may carry the question it is waiting on.
1873
+ *
1874
+ * When the escalation tool is unavailable (a child session running an older
1875
+ * tool table), the prompt's text fallback writes `blockedReason` +
1876
+ * `question` + `options` into the same evidence block. Surfacing them here
1877
+ * keeps one parser for both paths; without this the runtime could only say
1878
+ * "blocked" and the pending decision was lost.
1879
+ */
1880
+ const question = truncate(String(payload.question ?? ''), MAX_QUESTION_CHARS)
1881
+ const options = readEvidenceOptions(payload.options)
1595
1882
  const blockedReason = truncate(String(payload.blockedReason ?? payload.error ?? ''), 2000)
1596
1883
  if (payload.status === 'blocked') {
1597
1884
  return {
@@ -1600,6 +1887,8 @@ export function adjudicateResult({ output, strict = true }: any) {
1600
1887
  acceptance,
1601
1888
  artifacts,
1602
1889
  needs,
1890
+ question,
1891
+ options,
1603
1892
  error: blockedReason || '子 Agent 报告受阻',
1604
1893
  }
1605
1894
  }
@@ -1611,6 +1900,8 @@ export function adjudicateResult({ output, strict = true }: any) {
1611
1900
  acceptance,
1612
1901
  artifacts,
1613
1902
  needs,
1903
+ question,
1904
+ options,
1614
1905
  error: detail ? `部分完成:${detail}` : '部分完成',
1615
1906
  }
1616
1907
  }
@@ -1622,6 +1913,8 @@ export function adjudicateResult({ output, strict = true }: any) {
1622
1913
  acceptance,
1623
1914
  artifacts,
1624
1915
  needs,
1916
+ question,
1917
+ options,
1625
1918
  error: `自检未通过:${failed.map((item: any) => item.criterion).join(';')}`,
1626
1919
  }
1627
1920
  }
@@ -1638,6 +1931,24 @@ export function adjudicateResult({ output, strict = true }: any) {
1638
1931
  */
1639
1932
  const hasUnverified = acceptance.length === 0
1640
1933
  || acceptance.some((item: any) => item.result === 'unverified')
1934
+ /*
1935
+ * [1.11.0] 计划验收必须被逐条回应(T5 C4 / T10 D-01,阻断级)。
1936
+ *
1937
+ * 只有证据不完整时才算缺口:全部 pass 但少回一条,仍然是「没做完」。
1938
+ * 旧计划/旧日志没有 expectedAcceptance 时保持原语义,避免历史回放翻红。
1939
+ */
1940
+ const coverage = acceptanceCoverage(expectedAcceptance, acceptance)
1941
+ if (coverage.total > 0 && coverage.missing.length > 0) {
1942
+ return {
1943
+ status: 'blocked',
1944
+ verification: 'unverified',
1945
+ acceptance,
1946
+ artifacts,
1947
+ needs,
1948
+ error: `验收项未被逐条回应(${coverage.covered}/${coverage.total}):缺少 ${coverage.missing
1949
+ .map((item: string) => truncate(String(item), 120)).slice(0, 5).join(';')}。请按计划验收逐条给出证据后再回报。`,
1950
+ }
1951
+ }
1641
1952
  return {
1642
1953
  status: 'done',
1643
1954
  verification: hasUnverified ? 'unverified' : 'structured',
@@ -1671,6 +1982,34 @@ export function buildUpdateMessage(update: any) {
1671
1982
  ...(update.acceptance === undefined ? {} : { acceptance: update.acceptance }),
1672
1983
  ...(update.artifacts === undefined ? {} : { artifacts: update.artifacts }),
1673
1984
  ...(update.missingArtifacts === undefined ? {} : { missingArtifacts: update.missingArtifacts }),
1985
+ /*
1986
+ * [1.11.0] 闭环字段随人工改判一起留档。
1987
+ *
1988
+ * `escalate` 工具在子会话里立刻写一条这样的记录,所以即使页面在回合结束
1989
+ * 前刷新,「有一条请示在等指示」也不会退回 pending。旧版本的日志没有这些
1990
+ * 键,回放时按 undefined 跳过,不改变 1.10.6 的语义。
1991
+ */
1992
+ ...(update.closure === undefined ? {} : { closure: update.closure }),
1993
+ ...(update.blockedKind === undefined ? {} : { blockedKind: update.blockedKind }),
1994
+ ...(update.question === undefined ? {} : { question: update.question }),
1995
+ ...(update.options === undefined ? {} : { options: update.options }),
1996
+ ...(update.assignedAt === undefined ? {} : { assignedAt: update.assignedAt }),
1997
+ ...(update.ackedAt === undefined ? {} : { ackedAt: update.ackedAt }),
1998
+ ...(update.ackEvidence === undefined ? {} : { ackEvidence: update.ackEvidence }),
1999
+ ...(update.ackOverdue === undefined ? {} : { ackOverdue: update.ackOverdue }),
2000
+ ...(update.escalatedAt === undefined ? {} : { escalatedAt: update.escalatedAt }),
2001
+ ...(update.escalationSeq === undefined ? {} : { escalationSeq: update.escalationSeq }),
2002
+ ...(update.instruction === undefined ? {} : { instruction: update.instruction }),
2003
+ ...(update.instructionSeq === undefined ? {} : { instructionSeq: update.instructionSeq }),
2004
+ /*
2005
+ * [1.11.0] 指示回执提醒也要能回放(T10 N4)。
2006
+ *
2007
+ * 否则刷新页面后「指示已发出、子会话还没动」这条事实只剩内存里的一份,
2008
+ * 记录重建时被静默抹掉,主 Agent 会以为指示已经被执行。
2009
+ */
2010
+ ...(update.instructionOverdue === undefined ? {} : { instructionOverdue: update.instructionOverdue }),
2011
+ ...(update.handoffs === undefined ? {} : { handoffs: update.handoffs }),
2012
+ ...(update.reportedAt === undefined ? {} : { reportedAt: update.reportedAt }),
1674
2013
  ...(update.revision === undefined ? {} : { revision: update.revision }),
1675
2014
  at: update.at ?? Date.now(),
1676
2015
  }
@@ -1745,11 +2084,26 @@ export function applyResultStatuses(statuses: any, result: any) {
1745
2084
  if (!current) continue
1746
2085
  /*
1747
2086
  * A manually re-adjudicated status (durable `workplan-update`) must not be
1748
- * rolled back by an older result snapshot. Only comparable revisions are
1749
- * ordered; legacy entries without `revision` keep the old "last wins" rule.
2087
+ * rolled back by an older result snapshot — and the *same* snapshot must not
2088
+ * be applied twice. 1.9.1 skipped only `entry.revision < current.revision`,
2089
+ * so an equal revision was re-applied and bumped every row by one revision
2090
+ * on each replay (T1 实测:T1–T7 各 +1)。
1750
2091
  */
1751
2092
  if (Number.isInteger(entry.revision) && Number.isInteger(current.revision)
1752
- && Number(entry.revision) < Number(current.revision)) continue
2093
+ && Number(entry.revision) <= Number(current.revision)) continue
2094
+ /*
2095
+ * [1.11.0] 回放一条结果消息 = 「这条完成结果已经回报过」。
2096
+ *
2097
+ * 1.10.6 的结果载荷没有 `closure`。若原样交给 `applyStatus`,它的 done
2098
+ * 分支会把闭包补成 `done`(= 完成但未回报),而 `deliveryReadiness` 的
2099
+ * reportPending 拦截就会把**每一份历史计划**判成不可交付 —— 升级后用户
2100
+ * 手里所有旧会话都会突然“差一步回报”。结果消息本身就是回报的证据,
2101
+ * 所以旧载荷的 done 行按 `reported` 解释;新载荷已经显式带 `reported`
2102
+ * (finishRound 先 markReported 再构消息),不受影响。
2103
+ */
2104
+ const replayedClosure = entry.status === 'done' && entry.closure === undefined
2105
+ ? 'reported'
2106
+ : entry.closure
1753
2107
  try {
1754
2108
  next = applyStatus(next, entry.subtaskId, {
1755
2109
  status: entry.status,
@@ -1764,7 +2118,31 @@ export function applyResultStatuses(statuses: any, result: any) {
1764
2118
  artifacts: entry.artifacts,
1765
2119
  missingArtifacts: entry.missingArtifacts,
1766
2120
  needs: entry.needs,
2121
+ handoffs: entry.handoffs,
1767
2122
  blockedBy: entry.blockedBy,
2123
+ closure: replayedClosure,
2124
+ blockedKind: entry.blockedKind,
2125
+ question: entry.question,
2126
+ options: entry.options,
2127
+ assignedAt: entry.assignedAt,
2128
+ ackedAt: entry.ackedAt,
2129
+ ackEvidence: entry.ackEvidence,
2130
+ ackOverdue: entry.ackOverdue,
2131
+ escalatedAt: entry.escalatedAt,
2132
+ escalationSeq: entry.escalationSeq,
2133
+ instruction: entry.instruction,
2134
+ instructionSeq: entry.instructionSeq,
2135
+ instructionOverdue: entry.instructionOverdue,
2136
+ reportedAt: entry.reportedAt,
2137
+ // [1.11.0] 回报证据与重规划留档必须随结果快照回放(T7 C-06/C-11)。
2138
+ report: entry.report,
2139
+ replannedReason: entry.replannedReason,
2140
+ replannedAt: entry.replannedAt,
2141
+ replacedBy: entry.replacedBy,
2142
+ replannedFrom: entry.replannedFrom,
2143
+ replannedFromClosure: entry.replannedFromClosure,
2144
+ insertedBy: entry.insertedBy,
2145
+ replaces: entry.replaces,
1768
2146
  revision: entry.revision,
1769
2147
  updatedBy: entry.updatedBy,
1770
2148
  })
@@ -1783,6 +2161,7 @@ export function createStatuses(plan: any) {
1783
2161
  department: subtask.department,
1784
2162
  role: subtask.role,
1785
2163
  status: 'pending',
2164
+ closure: 'pending',
1786
2165
  progress: 0,
1787
2166
  childId: null,
1788
2167
  startedAt: null,
@@ -1803,6 +2182,123 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1803
2182
  }
1804
2183
  next.status = patch.status
1805
2184
  }
2185
+ /*
2186
+ * [1.11.0] 闭环字段与 status 同表、同写入口(T4 D1/D2)。
2187
+ *
2188
+ * 校验放在这里而不是各个调用点:escalate 工具、看门狗、结果回放、页面
2189
+ * 刷新后的重建都走 applyStatus,任何一条路径都无法绕过枚举检查,也不会
2190
+ * 出现「status 说完成、closure 说还在等指示」的双份真相。
2191
+ */
2192
+ if (patch.closure !== undefined) {
2193
+ if (patch.closure === null) next.closure = null
2194
+ else if (!CLOSURES.includes(patch.closure)) {
2195
+ throw new PlanError(`非法 closure:${String(patch.closure)}`, 'INVALID_CLOSURE')
2196
+ } else next.closure = patch.closure
2197
+ }
2198
+ if (patch.blockedKind !== undefined) {
2199
+ if (patch.blockedKind === null) next.blockedKind = null
2200
+ else if (!BLOCKED_KINDS.includes(patch.blockedKind)) {
2201
+ throw new PlanError(`非法 blockedKind:${String(patch.blockedKind)}`, 'INVALID_BLOCKED_KIND')
2202
+ } else next.blockedKind = patch.blockedKind
2203
+ }
2204
+ if (patch.question !== undefined) {
2205
+ const text = truncate(String(patch.question ?? ''), MAX_QUESTION_CHARS)
2206
+ next.question = text || null
2207
+ }
2208
+ if (patch.options !== undefined) next.options = readEvidenceOptions(patch.options)
2209
+ if (patch.assignedAt !== undefined) next.assignedAt = numberOrNull(patch.assignedAt)
2210
+ if (patch.ackedAt !== undefined) next.ackedAt = numberOrNull(patch.ackedAt)
2211
+ if (patch.ackEvidence !== undefined) {
2212
+ next.ackEvidence = isRecord(patch.ackEvidence)
2213
+ ? {
2214
+ seq: Number.isInteger(Number(patch.ackEvidence.seq)) ? Number(patch.ackEvidence.seq) : null,
2215
+ elapsedMs: Number.isFinite(Number(patch.ackEvidence.elapsedMs))
2216
+ ? Math.max(0, Number(patch.ackEvidence.elapsedMs))
2217
+ : null,
2218
+ }
2219
+ : undefined
2220
+ }
2221
+ if (patch.ackOverdue !== undefined) next.ackOverdue = patch.ackOverdue === true
2222
+ /*
2223
+ * [1.11.0] 指示回执状态也必须能在同一条状态条目上落盘(T10 N4)。
2224
+ *
2225
+ * `scheduleInstructionAck` 在 60s 写 `instructionOverdue:true`,但这里原先
2226
+ * 没有对应分支,字段被静默丢弃:界面看不到「指示已发出、子会话还没动」,
2227
+ * 主 Agent 也无从判断该催还是该重发。它和 `ackOverdue` 是同一类事实,
2228
+ * 只是方向相反(主 → 子)。
2229
+ */
2230
+ if (patch.instructionOverdue !== undefined) next.instructionOverdue = patch.instructionOverdue === true
2231
+ if (patch.escalatedAt !== undefined) next.escalatedAt = numberOrNull(patch.escalatedAt)
2232
+ if (patch.escalationSeq !== undefined) {
2233
+ next.escalationSeq = Number.isInteger(Number(patch.escalationSeq)) ? Number(patch.escalationSeq) : null
2234
+ }
2235
+ if (patch.instruction !== undefined) {
2236
+ if (patch.instruction === null) next.instruction = null
2237
+ else if (isRecord(patch.instruction)) {
2238
+ const text = truncate(String(patch.instruction.text ?? ''), MAX_INSTRUCTION_CHARS)
2239
+ if (!text) throw new PlanError('instruction.text 不能为空', 'INVALID_INSTRUCTION')
2240
+ const delivery = ['sent', 'failed', 'not-sent'].includes(patch.instruction.delivery)
2241
+ ? patch.instruction.delivery
2242
+ : 'not-sent'
2243
+ next.instruction = {
2244
+ text,
2245
+ at: numberOrNull(patch.instruction.at) ?? Date.now(),
2246
+ by: ['agent', 'system', 'child'].includes(patch.instruction.by) ? patch.instruction.by : 'agent',
2247
+ delivery,
2248
+ ...(typeof patch.instruction.messageId === 'string'
2249
+ ? { messageId: truncate(patch.instruction.messageId, 200) }
2250
+ : {}),
2251
+ }
2252
+ } else {
2253
+ throw new PlanError('instruction 必须是对象或 null', 'INVALID_INSTRUCTION')
2254
+ }
2255
+ }
2256
+ if (patch.instructionSeq !== undefined) {
2257
+ next.instructionSeq = Number.isInteger(Number(patch.instructionSeq)) ? Number(patch.instructionSeq) : null
2258
+ }
2259
+ if (patch.reportedAt !== undefined) next.reportedAt = numberOrNull(patch.reportedAt)
2260
+ /*
2261
+ * [1.11.0] 完成回报与重规划的留档字段(T7 C-06/C-11)。
2262
+ *
2263
+ * `report` 是「这条完成结果回报给主 Agent 了吗」的唯一证据,`ref` 指向本轮
2264
+ * `workplan-result` 消息的稳定标识;`replanned*` 让旧行在刷新后仍能显示
2265
+ * 「被哪次修订替换、替换前是什么状态」。两者都只写同一条状态条目,
2266
+ * 不新增存储。
2267
+ */
2268
+ if (patch.report !== undefined) {
2269
+ if (patch.report === null) next.report = null
2270
+ else if (isRecord(patch.report)) {
2271
+ const state = ['sent', 'failed', 'pending'].includes(patch.report.state)
2272
+ ? patch.report.state
2273
+ : 'sent'
2274
+ next.report = {
2275
+ state,
2276
+ at: numberOrNull(patch.report.at),
2277
+ ref: typeof patch.report.ref === 'string' ? truncate(patch.report.ref, 300) : null,
2278
+ turn: Number.isInteger(Number(patch.report.turn)) ? Number(patch.report.turn) : null,
2279
+ }
2280
+ } else {
2281
+ throw new PlanError('report 必须是对象或 null', 'INVALID_REPORT')
2282
+ }
2283
+ }
2284
+ if (patch.replannedReason !== undefined) {
2285
+ next.replannedReason = truncate(String(patch.replannedReason ?? ''), 2000) || null
2286
+ }
2287
+ if (patch.replannedAt !== undefined) next.replannedAt = numberOrNull(patch.replannedAt)
2288
+ if (patch.replacedBy !== undefined) {
2289
+ next.replacedBy = (Array.isArray(patch.replacedBy) ? patch.replacedBy : [])
2290
+ .slice(0, 8)
2291
+ .map((id: any) => truncate(String(id ?? ''), 16))
2292
+ .filter(Boolean)
2293
+ }
2294
+ if (patch.replannedFrom !== undefined) {
2295
+ next.replannedFrom = typeof patch.replannedFrom === 'string' ? patch.replannedFrom : null
2296
+ }
2297
+ if (patch.replannedFromClosure !== undefined) {
2298
+ next.replannedFromClosure = typeof patch.replannedFromClosure === 'string' ? patch.replannedFromClosure : null
2299
+ }
2300
+ if (patch.insertedBy !== undefined) next.insertedBy = truncate(String(patch.insertedBy), 40) || null
2301
+ if (patch.replaces !== undefined) next.replaces = truncate(String(patch.replaces), 16) || null
1806
2302
  if (patch.progress !== undefined) {
1807
2303
  if (!Number.isInteger(patch.progress) || patch.progress < 0 || patch.progress > 100) {
1808
2304
  throw new PlanError('progress 必须是 0-100 的整数', 'INVALID_PROGRESS')
@@ -1813,7 +2309,19 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1813
2309
  if (patch.startedAt !== undefined) next.startedAt = patch.startedAt
1814
2310
  if (patch.finishedAt !== undefined) next.finishedAt = patch.finishedAt
1815
2311
  if (patch.summary !== undefined) next.summary = truncate(String(patch.summary), 3000)
1816
- if (patch.error !== undefined) next.error = patch.error === null ? null : truncate(String(patch.error), 2000)
2312
+ if (patch.error !== undefined) {
2313
+ /*
2314
+ * [1.10.0] 显式清空 `error` 也属于一次「失败记录退场」:先留档再清空。
2315
+ *
2316
+ * 回放路径(`applyResultStatuses`)对 done 行传的是 `error: null`,如果这里
2317
+ * 只是把它抹掉,事故记录里「为什么这一行曾经没做完」就再也查不到了。
2318
+ */
2319
+ if (patch.error === null && typeof current.error === 'string' && current.error.trim() !== '') {
2320
+ next.lastError = current.error
2321
+ next.lastErrorAt = Date.now()
2322
+ }
2323
+ next.error = patch.error === null ? null : truncate(String(patch.error), 2000)
2324
+ }
1817
2325
  if (patch.verification !== undefined) {
1818
2326
  if (!VERIFICATIONS.includes(patch.verification)) {
1819
2327
  throw new PlanError(`非法 verification:${String(patch.verification)}`, 'INVALID_VERIFICATION')
@@ -1833,7 +2341,32 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1833
2341
  return true
1834
2342
  })
1835
2343
  }
1836
- if (patch.needs !== undefined) next.needs = readEvidenceNeeds(patch.needs)
2344
+ if (patch.needs !== undefined) {
2345
+ next.needs = readEvidenceNeeds(patch.needs)
2346
+ /*
2347
+ * [1.11.0] 需求登记是自动的,处理不是(用户 m00687)。
2348
+ *
2349
+ * 任何一条 needs 写进来都立刻得到一条 open handoff,模型无法通过「只在
2350
+ * 文本里提一句」绕过交付门禁;但把它变成 answered/closed 必须走主 Agent
2351
+ * 的显式工具调用,子 Agent 自己不能宣称「跨部门需求已解决」。
2352
+ */
2353
+ next.handoffs = mergeHandoffsFromNeeds(next.handoffs, next.needs)
2354
+ }
2355
+ if (patch.handoffs !== undefined) next.handoffs = normaliseHandoffs(patch.handoffs)
2356
+ /*
2357
+ * [1.10.6] The files a retry refused to touch.
2358
+ *
2359
+ * A ceiling timeout can be retried once, but only when the artifacts the first
2360
+ * attempt landed are unchanged. When they did change, `runtime.ts` records
2361
+ * their refs here instead of overwriting them, so "why was there no retry"
2362
+ * stays answerable from the plan record alone.
2363
+ */
2364
+ if (patch.artifactConflict !== undefined) {
2365
+ next.artifactConflict = (Array.isArray(patch.artifactConflict) ? patch.artifactConflict : [])
2366
+ .slice(0, 8)
2367
+ .map((ref: any) => truncate(String(ref ?? ''), 300))
2368
+ .filter((ref: string) => ref !== '')
2369
+ }
1837
2370
  if (patch.blockedBy !== undefined) {
1838
2371
  next.blockedBy = (Array.isArray(patch.blockedBy) ? patch.blockedBy : [])
1839
2372
  .slice(0, 10)
@@ -1852,7 +2385,56 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1852
2385
  next.updatedBy = ['child', 'agent', 'system'].includes(patch.updatedBy) ? patch.updatedBy : 'system'
1853
2386
  if (patch.status === 'done') {
1854
2387
  next.progress = 100
2388
+ if (patch.closure === undefined) next.closure = 'done'
2389
+ /*
2390
+ * 一条已经完成的子任务不可能同时“在等指示”。旧的 question/options 是
2391
+ * 上一段受阻经历的证据,不能继续驱动模型把它当成未决请示;失败原因本身
2392
+ * 仍按既有规则迁入 lastError。
2393
+ */
2394
+ if (patch.blockedKind === undefined) next.blockedKind = null
2395
+ if (patch.question === undefined) next.question = null
2396
+ if (patch.options === undefined) next.options = []
2397
+ if (patch.ackOverdue === undefined) next.ackOverdue = false
1855
2398
  if (next.finishedAt === null) next.finishedAt = Date.now()
2399
+ /*
2400
+ * [1.10.0] R-01:「完成」与「失败原因」不能同时成立。
2401
+ *
2402
+ * 1.9.1 及以前,done 分支根本不碰 `error`,而改判路径对非 blocked 传的是
2403
+ * `undefined`,被上面 1816 行解释成「保留旧值」。于是「预算用尽,等待续跑」
2404
+ * 这类上一轮的失败文本会永久留在一个 status=done 的行上,界面再无条件把它
2405
+ * 渲染成「卡住原因」——同一行同时写着「已完成」和「卡住了」,就是这次
2406
+ * 事故的同屏矛盾。
2407
+ *
2408
+ * 旧文本不丢弃,迁入 `lastError` 供审计;`error` 只描述「当前这一行为什么
2409
+ * 没做完」,完成的行没有这种原因。
2410
+ */
2411
+ if (typeof next.error === 'string' && next.error.trim() !== '') {
2412
+ next.lastError = next.error
2413
+ next.lastErrorAt = Date.now()
2414
+ }
2415
+ /*
2416
+ * [1.10.2] 写侧补漏:显式传 `error` 的 done 也必须清空。
2417
+ *
2418
+ * 1.10.0/1.10.1 只在 `patch.error` 为 `undefined`/`null` 时清空,因此
2419
+ * `applyStatus(rows, id, { status: 'done', error: '...' })`(以及把子会话
2420
+ * result 原样回放的 `applyResultStatuses`)仍能把「完成 + 失败文本」写进
2421
+ * 持久化记录。读侧 `normaliseStatusEntry` 会在下发的载荷里清洗,界面看不到,
2422
+ * 但只要有任何消费者直接读 `record.statuses`(审计、导出、后续新增字段),
2423
+ * 这个不变量就又破了。这里与读侧使用同一条规则:旧文本只进 `lastError`。
2424
+ */
2425
+ next.error = null
2426
+ next.completedBy = ['child', 'agent', 'system'].includes(patch.completedBy)
2427
+ ? patch.completedBy
2428
+ : (next.completedBy ?? (next.updatedBy as any) ?? 'system')
2429
+ if (next.attemptOutcome !== undefined && next.attemptOutcome !== null
2430
+ && next.attemptOutcome !== 'completed' && next.attemptOutcome !== 'manual') {
2431
+ next.priorOutcome = next.attemptOutcome
2432
+ }
2433
+ next.attemptOutcome = patch.attemptOutcome
2434
+ ?? (next.completedBy === 'agent' ? 'manual' : 'completed')
2435
+ next.attemptEndedAt = patch.attemptEndedAt ?? Date.now()
2436
+ // [1.10.6] A finished row cannot also be "we refused to overwrite it".
2437
+ if (patch.artifactConflict === undefined) next.artifactConflict = undefined
1856
2438
  }
1857
2439
  if (patch.status === 'pending') {
1858
2440
  /*
@@ -1868,6 +2450,24 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1868
2450
  next.startedAt = null
1869
2451
  next.finishedAt = null
1870
2452
  next.childId = null
2453
+ /*
2454
+ * [1.11.0] A reset starts a new attempt; every closure-companion field of
2455
+ * the previous attempt goes with it, otherwise a re-queued row would still
2456
+ * advertise a stale ack deadline or a question nobody is waiting on.
2457
+ */
2458
+ if (patch.closure === undefined) next.closure = 'pending'
2459
+ if (patch.assignedAt === undefined) next.assignedAt = null
2460
+ if (patch.ackedAt === undefined) next.ackedAt = null
2461
+ if (patch.ackEvidence === undefined) next.ackEvidence = undefined
2462
+ if (patch.ackOverdue === undefined) next.ackOverdue = false
2463
+ if (patch.escalatedAt === undefined) next.escalatedAt = null
2464
+ if (patch.escalationSeq === undefined) next.escalationSeq = null
2465
+ if (patch.question === undefined) next.question = null
2466
+ if (patch.options === undefined) next.options = []
2467
+ if (patch.blockedKind === undefined) next.blockedKind = null
2468
+ if (patch.instruction === undefined) next.instruction = null
2469
+ if (patch.instructionSeq === undefined) next.instructionSeq = null
2470
+ if (patch.reportedAt === undefined) next.reportedAt = null
1871
2471
  if (patch.summary === undefined) next.summary = ''
1872
2472
  if (patch.error === undefined) next.error = null
1873
2473
  // The evidence of the failed attempt must not survive a reset either.
@@ -1877,9 +2477,13 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1877
2477
  if (patch.missingArtifacts === undefined) next.missingArtifacts = undefined
1878
2478
  if (patch.needs === undefined) next.needs = undefined
1879
2479
  if (patch.blockedBy === undefined) next.blockedBy = undefined
2480
+ // [1.10.6] A conflict belongs to one attempt; a reset starts a new one.
2481
+ if (patch.artifactConflict === undefined) next.artifactConflict = undefined
1880
2482
  }
1881
2483
  if (patch.status === 'in_progress') {
1882
2484
  if (next.startedAt === null) next.startedAt = Date.now()
2485
+ // [1.10.6] The retry of a conflicting row is itself the new attempt.
2486
+ if (patch.artifactConflict === undefined) next.artifactConflict = undefined
1883
2487
  /*
1884
2488
  * [1.5.2] 「正在做」不允许自称 100%。
1885
2489
  *
@@ -1889,8 +2493,53 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1889
2493
  */
1890
2494
  if (Number(next.progress) >= 100) next.progress = 99
1891
2495
  }
1892
- if (patch.status === 'blocked' && next.finishedAt === null) {
1893
- next.finishedAt = Date.now()
2496
+ if (patch.status === 'blocked') {
2497
+ /*
2498
+ * `escalated` is the one blocked reason that must not be flattened into a
2499
+ * plain failure: it is waiting for a decision, not out of options. A plain
2500
+ * blocked write (watchdog timeout, failed self-check) still gets a kind, so
2501
+ * the model can tell "timed out" from "the child said no".
2502
+ */
2503
+ if (patch.closure === undefined && next.closure !== 'escalated') next.closure = 'blocked'
2504
+ if (patch.blockedKind === undefined && next.blockedKind === undefined) next.blockedKind = 'failed'
2505
+ if (next.finishedAt === null) next.finishedAt = Date.now()
2506
+ }
2507
+ /*
2508
+ * [1.11.0] 单一不变量:escalated 只能投影成 blocked。
2509
+ *
2510
+ * 若允许 `status:'in_progress'` + `closure:'escalated'`,左侧栏会显示
2511
+ * 「正在做」而实际没有任何子会话在跑;反过来 `done` + `escalated` 会让交付
2512
+ * 门禁把一条待指示的请示当成完成。要恢复推进必须先写 closure:'instructed'。
2513
+ */
2514
+ /*
2515
+ * [1.11.0] 契约外迁移一律拒绝(M1)。
2516
+ *
2517
+ * 这条检查放在投影不变量之前:若先投影再查表,`replanned → assigned`
2518
+ * 会被下面两条不变量放行(它们只管 escalated/done 的组合),死状态就复活了。
2519
+ */
2520
+ const previousClosure = current.closure
2521
+ if (
2522
+ previousClosure != null
2523
+ && next.closure != null
2524
+ && next.closure !== previousClosure
2525
+ && !(CLOSURE_TRANSITIONS[String(previousClosure)] ?? []).includes(String(next.closure))
2526
+ ) {
2527
+ throw new PlanError(
2528
+ `非法闭环迁移:${String(previousClosure)} → ${String(next.closure)}`,
2529
+ 'INVALID_TRANSITION',
2530
+ )
2531
+ }
2532
+ if (next.closure === 'escalated' && next.status !== 'blocked') {
2533
+ throw new PlanError(
2534
+ 'closure=escalated 必须同时是 status=blocked;恢复推进请写 closure=instructed',
2535
+ 'INVALID_CLOSURE_PROJECTION',
2536
+ )
2537
+ }
2538
+ if (next.status === 'done' && ['assigned', 'acknowledged', 'instructed', 'escalated'].includes(next.closure)) {
2539
+ throw new PlanError(
2540
+ `status=done 不能与 closure=${String(next.closure)} 同时成立`,
2541
+ 'INVALID_CLOSURE_PROJECTION',
2542
+ )
1894
2543
  }
1895
2544
  const copy = statuses.slice()
1896
2545
  copy[index] = next
@@ -1999,6 +2648,29 @@ export function normaliseStatusEntry(entry: any): StatusEntry {
1999
2648
  const source: any = entry ?? {}
2000
2649
  const status: SubtaskStatus = isSubtaskStatus(source.status) ? source.status : 'pending'
2001
2650
  const progress = status === 'done' ? 100 : status === 'pending' ? 0 : clampProgress(source.progress)
2651
+ /*
2652
+ * [1.10.0] R-01 读侧兜底:历史脏数据在载荷层就要干净。
2653
+ *
2654
+ * 1.9.1 写下的记录里,被人工改判为 done 的行仍带着上一轮的失败文本。只修写
2655
+ * 入口不会让已经落盘的记录自愈,而状态只存在于会话事件日志里、不会重写,
2656
+ * 所以必须在每次派生载荷时把「done + error」拆成「done + lastError」,
2657
+ * 否则用户刷新一次就又能看到「已完成 + 卡住原因」。
2658
+ */
2659
+ const legacyError = typeof source.error === 'string' && source.error.trim() !== ''
2660
+ ? source.error
2661
+ : null
2662
+ const error = status === 'done' ? null : legacyError
2663
+ const lastError = status === 'done'
2664
+ ? (typeof source.lastError === 'string' && source.lastError !== '' ? source.lastError : legacyError)
2665
+ : (typeof source.lastError === 'string' ? source.lastError : null)
2666
+ /*
2667
+ * [1.11.0] 未知 closure 按 null 降级,而不是猜一个最接近的阶段。
2668
+ *
2669
+ * 「猜」会让一条 1.10.6 的 blocked 行在升级后显示成「等待指示」,主 Agent
2670
+ * 于是去处理一个从未存在过的请示。null 的语义就是「这条日志没有闭环信息」,
2671
+ * 界面按 status 原样展示,与旧版完全一致。
2672
+ */
2673
+ const closure = CLOSURES.includes(source.closure) ? source.closure : null
2002
2674
  return {
2003
2675
  ...source,
2004
2676
  subtaskId: stringOr(source.subtaskId, ''),
@@ -2007,12 +2679,14 @@ export function normaliseStatusEntry(entry: any): StatusEntry {
2007
2679
  department: stringOr(source.department, ''),
2008
2680
  role: stringOr(source.role, ''),
2009
2681
  status,
2682
+ closure,
2010
2683
  progress,
2011
2684
  childId: status === 'pending' ? null : (source.childId ?? null),
2012
2685
  startedAt: status === 'pending' ? null : numberOrNull(source.startedAt),
2013
2686
  finishedAt: status === 'pending' ? null : numberOrNull(source.finishedAt),
2014
2687
  summary: stringOr(source.summary, ''),
2015
- error: typeof source.error === 'string' ? source.error : null,
2688
+ error,
2689
+ ...(lastError ? { lastError } : {}),
2016
2690
  }
2017
2691
  }
2018
2692
 
@@ -2044,7 +2718,7 @@ export function normaliseStatuses(statuses: any): StatusEntry[] {
2044
2718
  * therefore never drag the plan's percentage up to where the cards say it is
2045
2719
  * finished — that was the “100% 但 11/12” contradiction users saw.
2046
2720
  */
2047
- export function deriveAggregates(statuses: readonly StatusEntry[]): {
2721
+ export function deriveAggregates(statuses: readonly StatusEntry[], expectedTotal?: number): {
2048
2722
  stats: Stats
2049
2723
  departments: DepartmentSummary[]
2050
2724
  } {
@@ -2055,7 +2729,15 @@ export function deriveAggregates(statuses: readonly StatusEntry[]): {
2055
2729
  let pending = 0
2056
2730
  let progressSum = 0
2057
2731
 
2058
- for (const item of statuses) {
2732
+ /*
2733
+ * [1.11.0] 重规划后的旧行保留在数组里用于追溯,但不计入任何统计。
2734
+ *
2735
+ * 判据与 runtime.liveStatuses 同为 `closure === 'replanned'`;旧行若仍被
2736
+ * 计入分母,卡片会长期停在「差一项」而计划实际已可交付。
2737
+ */
2738
+ const live = statuses.filter((item: any) => item?.closure !== 'replanned')
2739
+
2740
+ for (const item of live) {
2059
2741
  if (item.status === 'done') {
2060
2742
  done += 1
2061
2743
  progressSum += 100
@@ -2083,7 +2765,20 @@ export function deriveAggregates(statuses: readonly StatusEntry[]): {
2083
2765
  departments.set(item.department, department)
2084
2766
  }
2085
2767
 
2086
- const total = statuses.length
2768
+ /*
2769
+ * [1.10.0] R-07:分母必须来自「计划定义」,不能是「实际有几行状态」。
2770
+ *
2771
+ * 1.9.1 的 `total = statuses.length`,而 I1 又只是拿它和自身比较(同义反复),
2772
+ * 于是构造出「定义 13 项、只写 5 行状态」就得到 5/5 = 100%(T3 反例 C16)。
2773
+ * 现在调用方把定义条数传进来:缺的行按 pending 计入总数,既不会把分母缩小,
2774
+ * 也不会凭空造出几行明细。
2775
+ */
2776
+ const defined = Number.isInteger(expectedTotal) && Number(expectedTotal) > 0
2777
+ ? Number(expectedTotal)
2778
+ : 0
2779
+ const total = Math.max(live.length, defined)
2780
+ const missing = Math.max(0, total - live.length)
2781
+ pending += missing
2087
2782
  const allDone = total > 0 && done === total
2088
2783
  /*
2089
2784
  * [1.5.2] 加权进度在「未全部完成」时不得四舍五入成 100。
@@ -2114,9 +2809,9 @@ export function deriveAggregates(statuses: readonly StatusEntry[]): {
2114
2809
  * values share one array instance, so `stats`, `departments` and `statuses` in
2115
2810
  * a single payload cannot disagree.
2116
2811
  */
2117
- export function derivePlanSnapshot(raw: any): PlanSnapshot {
2812
+ export function derivePlanSnapshot(raw: any, expectedTotal?: number): PlanSnapshot {
2118
2813
  const statuses = normaliseStatuses(raw)
2119
- const { stats, departments } = deriveAggregates(statuses)
2814
+ const { stats, departments } = deriveAggregates(statuses, expectedTotal)
2120
2815
  return { statuses, stats, departments }
2121
2816
  }
2122
2817
 
@@ -2146,8 +2841,23 @@ export function aggregateInvariantViolations(snapshot: PlanSnapshot, phase?: any
2146
2841
  const violations: string[] = []
2147
2842
  const { statuses, stats, departments } = snapshot
2148
2843
 
2149
- if (stats.total !== statuses.length) {
2150
- violations.push(`I1 stats.total=${stats.total} 与 statuses.length=${statuses.length} 不一致`)
2844
+ /*
2845
+ * [1.10.0] I1 改为「不得小于」,并新增 I12/I13。
2846
+ *
2847
+ * 旧 I1 是 `stats.total === statuses.length`——与产生它的表达式同义反复,
2848
+ * 永远成立,等于没检查(T3 实测 C16)。现在分母允许大于明细行数(缺行按
2849
+ * pending 计入),真正要禁止的是「分母比明细还小」这种把 100% 造出来的情形。
2850
+ * I12 封住本次事故的同屏矛盾:done 行不允许带 error。
2851
+ * I13 封住反过来的一侧:全部 done 却写着 progress<100。
2852
+ */
2853
+ if (stats.total < statuses.length) {
2854
+ violations.push(`I1 stats.total=${stats.total} 小于 statuses.length=${statuses.length}`)
2855
+ }
2856
+ if (stats.total > 0 && stats.done === stats.total && stats.progress !== 100) {
2857
+ violations.push(`I13 全部 ${stats.total} 项已 done,但 stats.progress=${stats.progress}`)
2858
+ }
2859
+ if (stats.done < stats.total && stats.progress >= 100) {
2860
+ violations.push(`I13 仅 ${stats.done}/${stats.total} 项 done,但 stats.progress=100`)
2151
2861
  }
2152
2862
  const counted = stats.done + stats.blocked + stats.inProgress + stats.pending
2153
2863
  if (counted !== stats.total) {
@@ -2178,6 +2888,10 @@ export function aggregateInvariantViolations(snapshot: PlanSnapshot, phase?: any
2178
2888
  if (item.status === 'done' && item.progress !== 100) {
2179
2889
  violations.push(`I6 ${item.subtaskId} 是 done 但 progress=${item.progress}`)
2180
2890
  }
2891
+ /* [1.10.0] I12:「完成」与「卡住原因」不能同屏。 */
2892
+ if (item.status === 'done' && typeof item.error === 'string' && item.error.trim() !== '') {
2893
+ violations.push(`I12 ${item.subtaskId} 是 done 但仍带 error=${item.error.slice(0, 80)}`)
2894
+ }
2181
2895
  }
2182
2896
 
2183
2897
  const sums = { total: 0, done: 0, blocked: 0, inProgress: 0 }
@@ -2267,10 +2981,17 @@ export function aggregateInvariantViolations(snapshot: PlanSnapshot, phase?: any
2267
2981
  * 不再参与判定(旧的 integrating 窗口已由 dispatch 内的 `executing` 覆盖)。
2268
2982
  */
2269
2983
  export function planPhase(statuses: any, _resultSeen = false) {
2270
- if (statuses.length === 0) return 'pending'
2271
- if (statuses.every((item: any) => item.status === 'done')) return 'done'
2272
- if (statuses.some((item: any) => item.status === 'blocked')) return 'blocked'
2273
- if (statuses.some((item: any) => item.status === 'in_progress' || item.status === 'done')) return 'executing'
2984
+ /*
2985
+ * [1.11.0] 只由「仍有效」的行决定轮次阶段:closure='replanned' 的旧行是
2986
+ * 审计记录,既不能拖住 done,也不能制造 executing。
2987
+ */
2988
+ const live = Array.isArray(statuses)
2989
+ ? statuses.filter((item: any) => item?.closure !== 'replanned')
2990
+ : []
2991
+ if (live.length === 0) return 'pending'
2992
+ if (live.every((item: any) => item.status === 'done')) return 'done'
2993
+ if (live.some((item: any) => item.status === 'blocked')) return 'blocked'
2994
+ if (live.some((item: any) => item.status === 'in_progress' || item.status === 'done')) return 'executing'
2274
2995
  return 'pending'
2275
2996
  }
2276
2997
 
@@ -2302,6 +3023,17 @@ export function reconcilePhase(phase: any, statuses: any) {
2302
3023
  if (phase === 'pending' || phase === 'planning' || phase === 'executing') {
2303
3024
  return derived === 'pending' ? phase : derived
2304
3025
  }
3026
+ /*
3027
+ * [1.11.0] 「受阻」可以被指令解除(T10 N3)。
3028
+ *
3029
+ * 主 Agent 下发指示后,该行从 blocked/escalated 变成 in_progress/instructed,
3030
+ * 但缓存的 `phase` 仍是 blocked。规则 4 会把 blocked 原样保留,于是卡片
3031
+ * 继续显示「卡住了」,而事实是子会话已经在执行新的指示。派生值只会在
3032
+ * 有 in_progress/done 且没有任何 blocked 行时才是 executing,此时缓存
3033
+ * 的 blocked 已经过期,必须让位;仍有 blocked 行时派生值是 blocked,
3034
+ * 走不到这里。
3035
+ */
3036
+ if (phase === 'blocked' && derived === 'executing') return 'executing'
2305
3037
  return phase ?? derived
2306
3038
  }
2307
3039
 
@@ -2341,9 +3073,17 @@ function verificationGap(item: any) {
2341
3073
  return `自检状态非法:${verification}`
2342
3074
  }
2343
3075
 
2344
- export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any } = {}): DeliveryReadiness {
3076
+ export function deliveryReadiness(
3077
+ snapshot: PlanSnapshot,
3078
+ options: { phase?: any; changePending?: boolean; reportPending?: boolean; expectedAcceptance?: Record<string, any[]> } = {},
3079
+ ): DeliveryReadiness {
2345
3080
  const phase = typeof options.phase === 'string' ? options.phase : ''
2346
- const statuses = Array.isArray(snapshot?.statuses) ? snapshot.statuses : []
3081
+ const allStatuses = Array.isArray(snapshot?.statuses) ? snapshot.statuses : []
3082
+ /*
3083
+ * [1.11.0] 被重规划的旧行不参与交付判定:它们不是「没做完的剩余项」,
3084
+ * 而是已被新行接替的历史。旧行若仍进入 remaining,计划永远差一项。
3085
+ */
3086
+ const statuses = allStatuses.filter((item: any) => item?.closure !== 'replanned')
2347
3087
  const remaining: string[] = []
2348
3088
  const blockers: string[] = []
2349
3089
  for (const item of statuses) {
@@ -2354,6 +3094,18 @@ export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any
2354
3094
  }
2355
3095
  const gap = verificationGap(item)
2356
3096
  if (gap) blockers.push(`${id} ${gap}`)
3097
+ /*
3098
+ * [1.11.0] C-17:子 Agent 完成 ≠ 主 Agent 已收到回报。
3099
+ *
3100
+ * `closure:'done'` 是完成路径在写结果消息之前的中间态;结果消息写成功
3101
+ * 后由 `markReported`(runtime.ts,唯一写入点)改成 `reported` 并带
3102
+ * `report{state,at,ref,turn}`。只拦 `updatedBy:'child'` 的行:主 Agent 用
3103
+ * `dsh_workplan_update` 亲自改判的 done 本身就是裁决行为,没有子会话回报
3104
+ * 可言,若一并拦住会让“人工补完最后一项”永远无法交付。
3105
+ */
3106
+ if (item?.closure === 'done' && item?.updatedBy === 'child') {
3107
+ blockers.push(`${id} 已完成但尚未回报(closure=done):结果消息还没有写入会话`)
3108
+ }
2357
3109
  const acceptance = Array.isArray((item as any)?.acceptance) ? (item as any).acceptance : []
2358
3110
  /*
2359
3111
  * An empty acceptance list is not "everything passed"; it is the absence
@@ -2361,9 +3113,28 @@ export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any
2361
3113
  * exactly how the T5-D snapshot still looked deliverable.
2362
3114
  */
2363
3115
  if (acceptance.length === 0) blockers.push(`${id} 未提供验收项(acceptance 为空)`)
3116
+ /*
3117
+ * [1.11.0] 交付门也看「计划写了什么」(T5 C4 / T10 D-01)。
3118
+ *
3119
+ * adjudicate 在收尾时已经拦一次,但主 Agent 的 `update` 改判与历史回放
3120
+ * 不经过 adjudicate;只在收尾拦,交付门仍会放过「5 条验收只回 1 条」的
3121
+ * 计划。这里按同一份 acceptanceCoverage 复核,两处结论不会分叉。
3122
+ * 只对自称 structured 的行生效:legacy 行本来就会被上面的 gap 拦住。
3123
+ */
3124
+ const expected = options.expectedAcceptance?.[id]
3125
+ if ((item as any)?.verification === 'structured' && Array.isArray(expected) && expected.length > 0) {
3126
+ const coverage = acceptanceCoverage(expected, acceptance)
3127
+ if (coverage.missing.length > 0) {
3128
+ blockers.push(`${id} 验收项未被逐条回应(${coverage.covered}/${coverage.total}):${coverage.missing
3129
+ .map((entry: string) => truncate(entry, 80)).slice(0, 3).join(';')}`)
3130
+ }
3131
+ }
2364
3132
  for (const entry of acceptance) {
2365
3133
  if (entry?.result !== 'pass') {
2366
3134
  blockers.push(`${id} 验收未通过:${truncate(String(entry?.criterion ?? '未命名验收项'), 80)}`)
3135
+ } else if (String(entry?.evidence ?? '').trim() === '') {
3136
+ /* [1.11.0] C-19:自述通过但没有任何可复核证据,不算通过。 */
3137
+ blockers.push(`${id} 验收自称通过但没有证据:${truncate(String(entry?.criterion ?? '未命名验收项'), 80)}`)
2367
3138
  }
2368
3139
  }
2369
3140
  const missing = Array.isArray((item as any)?.missingArtifacts) ? (item as any).missingArtifacts : []
@@ -2374,9 +3145,47 @@ export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any
2374
3145
  blockers.push(`${id} 声明产物不存在:${truncate(String(artifact?.ref ?? '未命名产物'), 120)}`)
2375
3146
  }
2376
3147
  }
3148
+ /*
3149
+ * [1.11.0] 跨部门需求没有闭环就不能交付(用户 m00687)。
3150
+ *
3151
+ * 一条 open/routed 的 handoff 表示:某个部门明确说了「我需要谁提供什么」,
3152
+ * 而主 Agent 还没有指派或答复。此时说「全部做完、可以交付」是把未落实的
3153
+ * 协作当成不存在。answered/closed 才解除这条阻塞。
3154
+ */
3155
+ for (const handoff of openHandoffs(item)) {
3156
+ const target = handoff?.department ? ` → ${handoff.department}` : ''
3157
+ blockers.push(`${id} 跨部门需求未落实(${String(handoff?.id ?? 'H?')}${target}):${truncate(String(handoff?.request ?? ''), 100)}`)
3158
+ }
2377
3159
  }
2378
3160
  const done = Number(snapshot?.stats?.done ?? 0)
2379
3161
  const total = Number(snapshot?.stats?.total ?? 0)
3162
+ /*
3163
+ * [1.10.1] DF-05(P0):分母对账必须同时作用在交付门上。
3164
+ *
3165
+ * 1.10.0 把 `stats.total` 改成了计划定义条数,但 `deliveryReadiness` 仍然只遍历
3166
+ * 实际存在的状态行——于是「定义 13 项、只写 5 行且全 done」会得到
3167
+ * `done=5 / total=13` 却 **ready=true**,present 门禁可放行只做了 5/13 的计划
3168
+ * (T10 实测 `[done=5,total=13,ready=True]`)。缺失的行就是没做完,必须算阻塞。
3169
+ */
3170
+ const missingRows = total - statuses.length
3171
+ if (total > 0 && missingRows > 0) {
3172
+ blockers.push(`状态明细缺少 ${missingRows} 行(计划定义 ${total} 项,实际只写 ${statuses.length} 行):缺失项按未完成计`)
3173
+ }
3174
+ /*
3175
+ * [1.11.0] C-17:记录级闭环事实也必须进交付门。
3176
+ *
3177
+ * 这两项不在 `statuses` 里,但同样是“没闭环”:`changeRequest.pending`
3178
+ * 表示用户在执行中提的新要求还没被 replan/dispatch/cancel 判定,
3179
+ * `reportPending` 表示上一轮完成结果没写进会话(没有证据的完成)。
3180
+ * 由调用方(runtime 的 readinessOf / buildRoundResult)显式传入,避免
3181
+ * 在本函数里反查 record、把纯函数变成第二个状态源。
3182
+ */
3183
+ if (options.changePending === true) {
3184
+ blockers.push('存在未落实的需求变更(changeRequest.pending):先用 dsh_workplan_replan 判定并重规划,或 dispatch/cancel 明确判定')
3185
+ }
3186
+ if (options.reportPending === true) {
3187
+ blockers.push('上一轮完成结果尚未成功写入会话(reportPending):先补齐回报再交付')
3188
+ }
2380
3189
  if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2381
3190
  blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`)
2382
3191
  }
@@ -2418,12 +3227,52 @@ export function readySubtasks(plan: any, statuses: any[], options: any = {}) {
2418
3227
  return flattenSubtasks(plan)
2419
3228
  .map((entry: any) => entry.subtask)
2420
3229
  .filter((subtask: any) => {
3230
+ // [1.11.0] 已被 replace/cancel 的旧定义不再可调度。
3231
+ if (subtask.supersededAt) return false
2421
3232
  const status = byId.get(subtask.id)
2422
3233
  if (!status || status.status !== 'pending') return false
2423
3234
  return subtask.dependsOn.every((dependency: any) => dependencyOk(byId.get(dependency), dependency))
2424
3235
  })
2425
3236
  }
2426
3237
 
3238
+ /**
3239
+ * [1.11.0] 重规划 cancel 掉的上游必须显式收束下游(T4 D-T4-02)。
3240
+ *
3241
+ * cancel 只把旧行标成 superseded,不会重写下游的 dependsOn(replace 会)。
3242
+ * 于是下游永远等一个不再调度的 ID:不报错、不 blocked、不进入交付阻塞——
3243
+ * 用户看到的是「一直 pending」。这里在每次派发与交付判定前把这类下游标成
3244
+ * blocked,并写明该用 replan 重新安排,而不是让它静默死锁。
3245
+ */
3246
+ export function blockCancelledDependents(plan: any, statuses: any) {
3247
+ const list = Array.isArray(statuses) ? statuses : []
3248
+ const cancelled = new Set<string>()
3249
+ for (const { subtask } of flattenSubtasks(plan)) {
3250
+ if (!subtask?.supersededAt) continue
3251
+ const replacedBy = Array.isArray(subtask.replacedBy) ? subtask.replacedBy : []
3252
+ if (replacedBy.length === 0) cancelled.add(String(subtask.id))
3253
+ }
3254
+ if (cancelled.size === 0) return list
3255
+ let next = list.slice()
3256
+ for (const { subtask } of flattenSubtasks(plan)) {
3257
+ if (subtask?.supersededAt) continue
3258
+ const current = next.find((item: any) => item?.subtaskId === subtask.id)
3259
+ if (!current || current.status !== 'pending' || current.closure === 'replanned') continue
3260
+ const hit = (Array.isArray(subtask.dependsOn) ? subtask.dependsOn : []).filter((id: any) => cancelled.has(String(id)))
3261
+ if (hit.length === 0) continue
3262
+ try {
3263
+ next = applyStatus(next, subtask.id, {
3264
+ status: 'blocked',
3265
+ closure: 'blocked',
3266
+ error: `依赖已被重规划取消:${hit.join('、')}。请用 dsh_workplan_replan(action=replace) 重新安排这一项,或显式取消它。`,
3267
+ updatedBy: 'system',
3268
+ })
3269
+ } catch {
3270
+ // 单行冲突不应中断整轮;下一轮派发会再次尝试收束。
3271
+ }
3272
+ }
3273
+ return next
3274
+ }
3275
+
2427
3276
  export function markDependentsBlocked(plan: any, statuses: any, blockedId: any, cause: any = null) {
2428
3277
  let next = statuses.slice()
2429
3278
  let changed = true
@@ -2437,7 +3286,14 @@ export function markDependentsBlocked(plan: any, statuses: any, blockedId: any,
2437
3286
  for (const { subtask } of flattenSubtasks(plan)) {
2438
3287
  if (blocked.has(subtask.id)) continue
2439
3288
  const status = next.find((item: any) => item.subtaskId === subtask.id)
2440
- if (!status || status.status !== 'pending') continue
3289
+ /*
3290
+ * [1.11.0] 已被重规划的旧行不再参与级联(T6 F6-01)。
3291
+ *
3292
+ * 它们的 status 仍是 pending,但 closure 是 replanned;对它写 blocked
3293
+ * 会触发 `replanned → blocked` 的非法迁移,异常会冒泡到整轮派发。
3294
+ * 这些行本来就不参与调度与交付,跳过即可。
3295
+ */
3296
+ if (!status || status.status !== 'pending' || status.closure === 'replanned') continue
2441
3297
  if (subtask.dependsOn.some((dependency: any) => blocked.has(dependency))) {
2442
3298
  const direct = subtask.dependsOn.filter((id: any) => blocked.has(id))
2443
3299
  /*
@@ -2491,6 +3347,14 @@ export function resetBlockedStatuses(statuses: any) {
2491
3347
  let next = statuses.slice()
2492
3348
  for (const item of statuses) {
2493
3349
  if (item?.status !== 'blocked' && item?.status !== 'in_progress') continue
3350
+ /*
3351
+ * [1.11.0] 「等指示」不是「失败」,不能靠重新 dispatch 抹平。
3352
+ *
3353
+ * 旧逻辑把所有 blocked 行重置为 pending 再跑一遍,于是一条正等待主 Agent
3354
+ * 决策的请示会被静默重派、问题被丢掉。升级行必须由主 Agent 显式处理
3355
+ * (给出指示改判 instructed,或明确放弃改判 blocked)后才离开这个状态。
3356
+ */
3357
+ if (item?.closure === 'escalated' || item?.closure === 'instructed') continue
2494
3358
  next = applyStatus(next, item.subtaskId, {
2495
3359
  status: 'pending',
2496
3360
  progress: 0,
@@ -2528,7 +3392,17 @@ export function canResumePlan(record: any, maxResumes: number = MAX_PLAN_RESUMES
2528
3392
  * against the resume budget (it is a time slice, not a repair).
2529
3393
  */
2530
3394
  const paused = record?.phase === 'paused'
3395
+ /*
3396
+ * [1.11.0] 「等指示」不是失败,不能触发续跑(T10 N2)。
3397
+ *
3398
+ * `closure:'escalated'` 的行 status 也是 blocked,旧过滤会把它算成待修复:
3399
+ * 计划明明在等主 Agent 拍板,卡片却显示「可续跑」,点下去零派发(每行都在
3400
+ * 等指示),还白白消耗一次续跑额度。它需要的是 instruct,不是 dispatch。
3401
+ * 该行在收到指示后由 `applyStatus` 迁移成 instructed/in_progress,届时才
3402
+ * 重新参与续跑判定。
3403
+ */
2531
3404
  const failed = statuses.filter((item: any) => {
3405
+ if (item?.closure === 'escalated') return false
2532
3406
  if (item?.status === 'blocked' || item?.status === 'in_progress') return true
2533
3407
  return paused && item?.status === 'pending'
2534
3408
  })
@@ -2587,7 +3461,11 @@ export function buildChildPrompt({
2587
3461
  const dependencies = results.length === 0
2588
3462
  ? '无'
2589
3463
  : results
2590
- .map((item: any) => `- ${item.id} ${item.title}:${item.status}${item.summary ? `|${item.summary}` : ''}`)
3464
+ .map((item: any) => {
3465
+ const refs = Array.isArray(item?.artifacts) ? item.artifacts.filter(Boolean).slice(0, 8) : []
3466
+ return `- ${item.id} ${item.title}:${item.status}${item.summary ? `|${item.summary}` : ''}`
3467
+ + (refs.length ? `|可消费产物:${refs.join('、')}` : '')
3468
+ })
2591
3469
  .join('\n')
2592
3470
  /*
2593
3471
  * [1.7.0] No second truncation here.
@@ -2633,6 +3511,44 @@ export function buildChildPrompt({
2633
3511
  '已经覆盖验收标准的部分保持原样,只补缺失部分;结尾按契约给出证据块。',
2634
3512
  ].join('\n')
2635
3513
  : ''
3514
+ /*
3515
+ * [1.11.0] 主 Agent 已经回答过的请示必须随下一次激活送进子提示词(M6/P-04)。
3516
+ *
3517
+ * `dsh_workplan_instruct` 在子会话已结束时只能把指示写进状态行;若不在下一次
3518
+ * 激活的提示词里带上它,子 Agent 会重新从零猜测,指示等于没下发。这里读的是
3519
+ * 同一条状态行上的 `instruction.text`,与 `instructSubtask` 的写入同源。
3520
+ */
3521
+ const pendingInstruction = previousStatus?.closure === 'instructed'
3522
+ && typeof previousStatus?.instruction?.text === 'string'
3523
+ && previousStatus.instruction.text.trim() !== ''
3524
+ ? [
3525
+ '',
3526
+ '主 Agent 对你上一次请示的指示(这是决定,不是建议;必须按它执行):',
3527
+ truncate(String(previousStatus.instruction.text), MAX_INSTRUCTION_CHARS),
3528
+ '执行时不要再就同一问题重复请示;只有出现新的、未被这条指示覆盖的阻塞时才再次上报。',
3529
+ ].join('\n')
3530
+ : ''
3531
+ /*
3532
+ * [1.11.0] 跨部门需求的答复必须随下一次激活回到提出方(用户 m00687)。
3533
+ *
3534
+ * 需求被主 Agent 指派或答复后只存在状态行里;若子 Agent 再次被唤醒时看不到
3535
+ * 这份答复,它会再提一次同样的需求,或者按错误的前提继续。这里同时列出
3536
+ * 「已答复的」与「仍在等待的」,后者明确要求不要重复上报、先做不依赖它的部分。
3537
+ */
3538
+ const previousHandoffs = previousStatus && Array.isArray(previousStatus.handoffs)
3539
+ ? previousStatus.handoffs
3540
+ : []
3541
+ const answeredHandoffs = previousHandoffs.filter((item: any) => item?.status === 'answered' && item?.response)
3542
+ const waitingHandoffs = previousHandoffs.filter((item: any) => item?.status === 'open' || item?.status === 'routed')
3543
+ const handoffBrief = answeredHandoffs.length === 0 && waitingHandoffs.length === 0
3544
+ ? ''
3545
+ : [
3546
+ '跨部门需求处置结果(这是事实,不是建议):',
3547
+ ...answeredHandoffs.map((item: any) =>
3548
+ `- ${item.id} 已答复(${item.department ?? '主 Agent'}):${truncate(String(item.response), 600)}`),
3549
+ ...waitingHandoffs.map((item: any) =>
3550
+ `- ${item.id} 仍在等待:${truncate(String(item.request), 300)}。不要重复上报;先完成不依赖它的部分,若要继续必须等主 Agent 答复。`),
3551
+ ].join('\n')
2636
3552
  /*
2637
3553
  * [1.8.12] 提示词整体过一遍 session-reference 消毒。
2638
3554
  *
@@ -2664,27 +3580,37 @@ export function buildChildPrompt({
2664
3580
  '依赖子任务的已知结果:',
2665
3581
  dependencies,
2666
3582
  ...(team ? ['', '兄弟部门进展(同一计划内的其他子任务;不要直接联系它们,需要协作请写进 needs 由主 Agent 转达):', team] : []),
3583
+ ...(handoffBrief ? ['', handoffBrief] : []),
2667
3584
  ...(failure ? [failure] : []),
2668
3585
  ...(resumeHint ? [resumeHint] : []),
3586
+ ...(pendingInstruction ? [pendingInstruction] : []),
2669
3587
  '',
2670
3588
  '执行要求:',
2671
3589
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',
2672
- '- 你没有派发权限,也不能重启或安装任何服务;遇到这类步骤,直接写清“需要主 Agent 执行什么”,不要等待或空转。',
3590
+ '- 你没有派发权限,也不能重启或安装任何服务;遇到这类步骤,必须先上报(见下方「遇阻上报」),再停止推进等待指示,不要空转。',
2673
3591
  '- 不得编造事实、文件、命令结果或证据;无法确认时明确写“未验证”。',
2674
3592
  '- 可以读取工作目录、运行必要命令、修改与任务相关的文件。',
2675
3593
  '- 优先使用给定上下文和本地工具;只有任务明确需要最新外部信息时才联网搜索。',
2676
- '- 控制工具调用次数,证据足够就立即汇报;不要反复搜索或等待长时间任务。',
2677
- '- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,然后简要说明。',
3594
+ '- 先把该做的检查做完再汇报:每条验收标准至少要有一处可复核的证据(命令输出/文件/引用),不要为了省时间跳过验证。',
3595
+ '- 如果确实无法完成,第一行输出 `BLOCKED: 原因`,并按下方「遇阻上报」给出 question。',
2678
3596
  '- 完成后用简洁中文汇报:做了什么、证据/文件、验收结果、遗留问题。',
2679
3597
  '',
3598
+ '遇阻上报(强制,先于继续动作):',
3599
+ '- 出现以下任一情况,第一动作是上报,不是猜测、绕过或静默继续:缺少权限/输入/依赖产物;需求自相矛盾;无法验证;同一命令连续两次失败;需要主 Agent 决定方向。',
3600
+ '- 优先调用工具:`dsh_workplan_escalate({ "subtaskId": "<你的子任务 ID>", "question": "需要主 Agent 回答的单个问题", "options": ["可选项 A", "可选项 B"], "needs": ["需要谁提供什么"] })`。调用成功后停止推进,只做只读核对。',
3601
+ '- 如果该工具不可用:在结果块里写 `"status":"blocked"`、`"blockedReason":"..."`,并加上 `"question":"..."` 与 `"options":[...]`。',
3602
+ '- 上报必须写清:卡在哪一步、已经尝试过什么、需要谁做什么决定;不要把“未验证”当成受阻上报。',
3603
+ '- 能独立完成的部分先做完再上报;但一旦需要外部决定,立即停止写入,等待指示,不得自行选定一个选项继续。',
3604
+ '',
2680
3605
  '结果回传(必填):在汇报的最后附上一个结构化结果块,主 Agent 会按它逐项核对,不再只依赖自述。',
2681
3606
  EVIDENCE_MARKER_BEGIN,
2682
- '{"status":"done","blockedReason":"","acceptance":[{"criterion":"把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[]}',
3607
+ '{"status":"done","blockedReason":"","acceptance":[{"criterion":"把上面的验收标准原文抄在这里","result":"pass","evidence":"用命令输出、文件路径或引用证明"}],"artifacts":[{"kind":"file","ref":"相对工作目录的路径"}],"needs":[],"question":"","options":[]}',
2683
3608
  EVIDENCE_MARKER_END,
2684
3609
  '- status 只能是 done / blocked / partial;partial 会被当作受阻处理。',
2685
3610
  '- acceptance 必须逐条覆盖上面的验收标准;result 只能是 pass / fail / unverified。无法确认就写 unverified,不要写 pass。',
2686
3611
  '- artifacts 写你实际产出或修改的文件(kind=file,ref 用相对路径)、链接(kind=url)或说明(kind=note)。',
2687
- '- 需要其他部门配合时写进 needs(每条一句话),主 Agent 会转达;不要直连其他子 Agent。',
3612
+ '- needs 写需要其他部门配合的事项,每条写清「哪个部门 + 需要什么 + 用来做什么」;它会被登记为待处理需求,主 Agent 必须处置后计划才能交付。不要直连其他子 Agent。',
3613
+ '- question/options 只在受阻上报时填写;done 时保持空字符串/空数组。',
2688
3614
  '- 整块不超过 8000 字符;不要把这段模板本身抄进结果块。',
2689
3615
  ].join('\n'))
2690
3616
  }