dsh-workplan 1.8.18 → 1.10.6

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
@@ -1299,7 +1363,26 @@ export function parseResultMessage(message: any) {
1299
1363
  }
1300
1364
  }
1301
1365
 
1302
- 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
+ }
1303
1386
  const summary = `【任务已取消】${truncate(String(reason || '用户取消'), 120)}`
1304
1387
  const payload = {
1305
1388
  kind: 'workplan-cancel',
@@ -1333,6 +1416,60 @@ export function buildCancelMessage(planId: any, reason: any = '用户取消') {
1333
1416
  })
1334
1417
  }
1335
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
+ '交付时只能使用承接计划通过交付就绪检查的产物;原计划不作为完成证据。',
1461
+ '',
1462
+ CANCEL_MARKER_BEGIN,
1463
+ JSON.stringify(payload),
1464
+ CANCEL_MARKER_END,
1465
+ ]
1466
+ return makeUserMessage(lines.join('\n'), {
1467
+ kind: 'workplan-cancel',
1468
+ form: 'notice',
1469
+ summary,
1470
+ })
1471
+ }
1472
+
1336
1473
  export function parseCancelMessage(message: any) {
1337
1474
  const body = extractBetween(messageText(message), CANCEL_MARKER_BEGIN, CANCEL_MARKER_END)
1338
1475
  if (!body) return null
@@ -1608,11 +1745,13 @@ export function applyResultStatuses(statuses: any, result: any) {
1608
1745
  if (!current) continue
1609
1746
  /*
1610
1747
  * A manually re-adjudicated status (durable `workplan-update`) must not be
1611
- * rolled back by an older result snapshot. Only comparable revisions are
1612
- * ordered; legacy entries without `revision` keep the old "last wins" rule.
1748
+ * rolled back by an older result snapshot — and the *same* snapshot must not
1749
+ * be applied twice. 1.9.1 skipped only `entry.revision < current.revision`,
1750
+ * so an equal revision was re-applied and bumped every row by one revision
1751
+ * on each replay (T1 实测:T1–T7 各 +1)。
1613
1752
  */
1614
1753
  if (Number.isInteger(entry.revision) && Number.isInteger(current.revision)
1615
- && Number(entry.revision) < Number(current.revision)) continue
1754
+ && Number(entry.revision) <= Number(current.revision)) continue
1616
1755
  try {
1617
1756
  next = applyStatus(next, entry.subtaskId, {
1618
1757
  status: entry.status,
@@ -1676,7 +1815,19 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1676
1815
  if (patch.startedAt !== undefined) next.startedAt = patch.startedAt
1677
1816
  if (patch.finishedAt !== undefined) next.finishedAt = patch.finishedAt
1678
1817
  if (patch.summary !== undefined) next.summary = truncate(String(patch.summary), 3000)
1679
- if (patch.error !== undefined) next.error = patch.error === null ? null : truncate(String(patch.error), 2000)
1818
+ if (patch.error !== undefined) {
1819
+ /*
1820
+ * [1.10.0] 显式清空 `error` 也属于一次「失败记录退场」:先留档再清空。
1821
+ *
1822
+ * 回放路径(`applyResultStatuses`)对 done 行传的是 `error: null`,如果这里
1823
+ * 只是把它抹掉,事故记录里「为什么这一行曾经没做完」就再也查不到了。
1824
+ */
1825
+ if (patch.error === null && typeof current.error === 'string' && current.error.trim() !== '') {
1826
+ next.lastError = current.error
1827
+ next.lastErrorAt = Date.now()
1828
+ }
1829
+ next.error = patch.error === null ? null : truncate(String(patch.error), 2000)
1830
+ }
1680
1831
  if (patch.verification !== undefined) {
1681
1832
  if (!VERIFICATIONS.includes(patch.verification)) {
1682
1833
  throw new PlanError(`非法 verification:${String(patch.verification)}`, 'INVALID_VERIFICATION')
@@ -1697,6 +1848,20 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1697
1848
  })
1698
1849
  }
1699
1850
  if (patch.needs !== undefined) next.needs = readEvidenceNeeds(patch.needs)
1851
+ /*
1852
+ * [1.10.6] The files a retry refused to touch.
1853
+ *
1854
+ * A ceiling timeout can be retried once, but only when the artifacts the first
1855
+ * attempt landed are unchanged. When they did change, `runtime.ts` records
1856
+ * their refs here instead of overwriting them, so "why was there no retry"
1857
+ * stays answerable from the plan record alone.
1858
+ */
1859
+ if (patch.artifactConflict !== undefined) {
1860
+ next.artifactConflict = (Array.isArray(patch.artifactConflict) ? patch.artifactConflict : [])
1861
+ .slice(0, 8)
1862
+ .map((ref: any) => truncate(String(ref ?? ''), 300))
1863
+ .filter((ref: string) => ref !== '')
1864
+ }
1700
1865
  if (patch.blockedBy !== undefined) {
1701
1866
  next.blockedBy = (Array.isArray(patch.blockedBy) ? patch.blockedBy : [])
1702
1867
  .slice(0, 10)
@@ -1716,6 +1881,45 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1716
1881
  if (patch.status === 'done') {
1717
1882
  next.progress = 100
1718
1883
  if (next.finishedAt === null) next.finishedAt = Date.now()
1884
+ /*
1885
+ * [1.10.0] R-01:「完成」与「失败原因」不能同时成立。
1886
+ *
1887
+ * 1.9.1 及以前,done 分支根本不碰 `error`,而改判路径对非 blocked 传的是
1888
+ * `undefined`,被上面 1816 行解释成「保留旧值」。于是「预算用尽,等待续跑」
1889
+ * 这类上一轮的失败文本会永久留在一个 status=done 的行上,界面再无条件把它
1890
+ * 渲染成「卡住原因」——同一行同时写着「已完成」和「卡住了」,就是这次
1891
+ * 事故的同屏矛盾。
1892
+ *
1893
+ * 旧文本不丢弃,迁入 `lastError` 供审计;`error` 只描述「当前这一行为什么
1894
+ * 没做完」,完成的行没有这种原因。
1895
+ */
1896
+ if (typeof next.error === 'string' && next.error.trim() !== '') {
1897
+ next.lastError = next.error
1898
+ next.lastErrorAt = Date.now()
1899
+ }
1900
+ /*
1901
+ * [1.10.2] 写侧补漏:显式传 `error` 的 done 也必须清空。
1902
+ *
1903
+ * 1.10.0/1.10.1 只在 `patch.error` 为 `undefined`/`null` 时清空,因此
1904
+ * `applyStatus(rows, id, { status: 'done', error: '...' })`(以及把子会话
1905
+ * result 原样回放的 `applyResultStatuses`)仍能把「完成 + 失败文本」写进
1906
+ * 持久化记录。读侧 `normaliseStatusEntry` 会在下发的载荷里清洗,界面看不到,
1907
+ * 但只要有任何消费者直接读 `record.statuses`(审计、导出、后续新增字段),
1908
+ * 这个不变量就又破了。这里与读侧使用同一条规则:旧文本只进 `lastError`。
1909
+ */
1910
+ next.error = null
1911
+ next.completedBy = ['child', 'agent', 'system'].includes(patch.completedBy)
1912
+ ? patch.completedBy
1913
+ : (next.completedBy ?? (next.updatedBy as any) ?? 'system')
1914
+ if (next.attemptOutcome !== undefined && next.attemptOutcome !== null
1915
+ && next.attemptOutcome !== 'completed' && next.attemptOutcome !== 'manual') {
1916
+ next.priorOutcome = next.attemptOutcome
1917
+ }
1918
+ next.attemptOutcome = patch.attemptOutcome
1919
+ ?? (next.completedBy === 'agent' ? 'manual' : 'completed')
1920
+ next.attemptEndedAt = patch.attemptEndedAt ?? Date.now()
1921
+ // [1.10.6] A finished row cannot also be "we refused to overwrite it".
1922
+ if (patch.artifactConflict === undefined) next.artifactConflict = undefined
1719
1923
  }
1720
1924
  if (patch.status === 'pending') {
1721
1925
  /*
@@ -1740,9 +1944,13 @@ export function applyStatus(statuses: any, subtaskId: any, patch: any) {
1740
1944
  if (patch.missingArtifacts === undefined) next.missingArtifacts = undefined
1741
1945
  if (patch.needs === undefined) next.needs = undefined
1742
1946
  if (patch.blockedBy === undefined) next.blockedBy = undefined
1947
+ // [1.10.6] A conflict belongs to one attempt; a reset starts a new one.
1948
+ if (patch.artifactConflict === undefined) next.artifactConflict = undefined
1743
1949
  }
1744
1950
  if (patch.status === 'in_progress') {
1745
1951
  if (next.startedAt === null) next.startedAt = Date.now()
1952
+ // [1.10.6] The retry of a conflicting row is itself the new attempt.
1953
+ if (patch.artifactConflict === undefined) next.artifactConflict = undefined
1746
1954
  /*
1747
1955
  * [1.5.2] 「正在做」不允许自称 100%。
1748
1956
  *
@@ -1862,6 +2070,21 @@ export function normaliseStatusEntry(entry: any): StatusEntry {
1862
2070
  const source: any = entry ?? {}
1863
2071
  const status: SubtaskStatus = isSubtaskStatus(source.status) ? source.status : 'pending'
1864
2072
  const progress = status === 'done' ? 100 : status === 'pending' ? 0 : clampProgress(source.progress)
2073
+ /*
2074
+ * [1.10.0] R-01 读侧兜底:历史脏数据在载荷层就要干净。
2075
+ *
2076
+ * 1.9.1 写下的记录里,被人工改判为 done 的行仍带着上一轮的失败文本。只修写
2077
+ * 入口不会让已经落盘的记录自愈,而状态只存在于会话事件日志里、不会重写,
2078
+ * 所以必须在每次派生载荷时把「done + error」拆成「done + lastError」,
2079
+ * 否则用户刷新一次就又能看到「已完成 + 卡住原因」。
2080
+ */
2081
+ const legacyError = typeof source.error === 'string' && source.error.trim() !== ''
2082
+ ? source.error
2083
+ : null
2084
+ const error = status === 'done' ? null : legacyError
2085
+ const lastError = status === 'done'
2086
+ ? (typeof source.lastError === 'string' && source.lastError !== '' ? source.lastError : legacyError)
2087
+ : (typeof source.lastError === 'string' ? source.lastError : null)
1865
2088
  return {
1866
2089
  ...source,
1867
2090
  subtaskId: stringOr(source.subtaskId, ''),
@@ -1875,7 +2098,8 @@ export function normaliseStatusEntry(entry: any): StatusEntry {
1875
2098
  startedAt: status === 'pending' ? null : numberOrNull(source.startedAt),
1876
2099
  finishedAt: status === 'pending' ? null : numberOrNull(source.finishedAt),
1877
2100
  summary: stringOr(source.summary, ''),
1878
- error: typeof source.error === 'string' ? source.error : null,
2101
+ error,
2102
+ ...(lastError ? { lastError } : {}),
1879
2103
  }
1880
2104
  }
1881
2105
 
@@ -1907,7 +2131,7 @@ export function normaliseStatuses(statuses: any): StatusEntry[] {
1907
2131
  * therefore never drag the plan's percentage up to where the cards say it is
1908
2132
  * finished — that was the “100% 但 11/12” contradiction users saw.
1909
2133
  */
1910
- export function deriveAggregates(statuses: readonly StatusEntry[]): {
2134
+ export function deriveAggregates(statuses: readonly StatusEntry[], expectedTotal?: number): {
1911
2135
  stats: Stats
1912
2136
  departments: DepartmentSummary[]
1913
2137
  } {
@@ -1946,7 +2170,20 @@ export function deriveAggregates(statuses: readonly StatusEntry[]): {
1946
2170
  departments.set(item.department, department)
1947
2171
  }
1948
2172
 
1949
- const total = statuses.length
2173
+ /*
2174
+ * [1.10.0] R-07:分母必须来自「计划定义」,不能是「实际有几行状态」。
2175
+ *
2176
+ * 1.9.1 的 `total = statuses.length`,而 I1 又只是拿它和自身比较(同义反复),
2177
+ * 于是构造出「定义 13 项、只写 5 行状态」就得到 5/5 = 100%(T3 反例 C16)。
2178
+ * 现在调用方把定义条数传进来:缺的行按 pending 计入总数,既不会把分母缩小,
2179
+ * 也不会凭空造出几行明细。
2180
+ */
2181
+ const defined = Number.isInteger(expectedTotal) && Number(expectedTotal) > 0
2182
+ ? Number(expectedTotal)
2183
+ : 0
2184
+ const total = Math.max(statuses.length, defined)
2185
+ const missing = Math.max(0, total - statuses.length)
2186
+ pending += missing
1950
2187
  const allDone = total > 0 && done === total
1951
2188
  /*
1952
2189
  * [1.5.2] 加权进度在「未全部完成」时不得四舍五入成 100。
@@ -1977,9 +2214,9 @@ export function deriveAggregates(statuses: readonly StatusEntry[]): {
1977
2214
  * values share one array instance, so `stats`, `departments` and `statuses` in
1978
2215
  * a single payload cannot disagree.
1979
2216
  */
1980
- export function derivePlanSnapshot(raw: any): PlanSnapshot {
2217
+ export function derivePlanSnapshot(raw: any, expectedTotal?: number): PlanSnapshot {
1981
2218
  const statuses = normaliseStatuses(raw)
1982
- const { stats, departments } = deriveAggregates(statuses)
2219
+ const { stats, departments } = deriveAggregates(statuses, expectedTotal)
1983
2220
  return { statuses, stats, departments }
1984
2221
  }
1985
2222
 
@@ -2009,8 +2246,23 @@ export function aggregateInvariantViolations(snapshot: PlanSnapshot, phase?: any
2009
2246
  const violations: string[] = []
2010
2247
  const { statuses, stats, departments } = snapshot
2011
2248
 
2012
- if (stats.total !== statuses.length) {
2013
- violations.push(`I1 stats.total=${stats.total} 与 statuses.length=${statuses.length} 不一致`)
2249
+ /*
2250
+ * [1.10.0] I1 改为「不得小于」,并新增 I12/I13。
2251
+ *
2252
+ * 旧 I1 是 `stats.total === statuses.length`——与产生它的表达式同义反复,
2253
+ * 永远成立,等于没检查(T3 实测 C16)。现在分母允许大于明细行数(缺行按
2254
+ * pending 计入),真正要禁止的是「分母比明细还小」这种把 100% 造出来的情形。
2255
+ * I12 封住本次事故的同屏矛盾:done 行不允许带 error。
2256
+ * I13 封住反过来的一侧:全部 done 却写着 progress<100。
2257
+ */
2258
+ if (stats.total < statuses.length) {
2259
+ violations.push(`I1 stats.total=${stats.total} 小于 statuses.length=${statuses.length}`)
2260
+ }
2261
+ if (stats.total > 0 && stats.done === stats.total && stats.progress !== 100) {
2262
+ violations.push(`I13 全部 ${stats.total} 项已 done,但 stats.progress=${stats.progress}`)
2263
+ }
2264
+ if (stats.done < stats.total && stats.progress >= 100) {
2265
+ violations.push(`I13 仅 ${stats.done}/${stats.total} 项 done,但 stats.progress=100`)
2014
2266
  }
2015
2267
  const counted = stats.done + stats.blocked + stats.inProgress + stats.pending
2016
2268
  if (counted !== stats.total) {
@@ -2041,6 +2293,10 @@ export function aggregateInvariantViolations(snapshot: PlanSnapshot, phase?: any
2041
2293
  if (item.status === 'done' && item.progress !== 100) {
2042
2294
  violations.push(`I6 ${item.subtaskId} 是 done 但 progress=${item.progress}`)
2043
2295
  }
2296
+ /* [1.10.0] I12:「完成」与「卡住原因」不能同屏。 */
2297
+ if (item.status === 'done' && typeof item.error === 'string' && item.error.trim() !== '') {
2298
+ violations.push(`I12 ${item.subtaskId} 是 done 但仍带 error=${item.error.slice(0, 80)}`)
2299
+ }
2044
2300
  }
2045
2301
 
2046
2302
  const sums = { total: 0, done: 0, blocked: 0, inProgress: 0 }
@@ -2154,6 +2410,11 @@ export function planPhase(statuses: any, _resultSeen = false) {
2154
2410
  * 它们携带状态列表里没有的信息(预算暂停、用户取消)。
2155
2411
  */
2156
2412
  export function reconcilePhase(phase: any, statuses: any) {
2413
+ /*
2414
+ * [1.9.0] 终态优先:superseded 的记录即使状态全部 done,也不得被对账成
2415
+ * done(T8 §5.5 C6)。cancelled 保持 1.8.19 的既有对账语义不变。
2416
+ */
2417
+ if (phase === 'superseded') return phase
2157
2418
  const derived = planPhase(statuses)
2158
2419
  if (derived === 'done') return 'done'
2159
2420
  if (phase === 'done' || phase === 'integrating') return derived
@@ -2235,6 +2496,18 @@ export function deliveryReadiness(snapshot: PlanSnapshot, options: { phase?: any
2235
2496
  }
2236
2497
  const done = Number(snapshot?.stats?.done ?? 0)
2237
2498
  const total = Number(snapshot?.stats?.total ?? 0)
2499
+ /*
2500
+ * [1.10.1] DF-05(P0):分母对账必须同时作用在交付门上。
2501
+ *
2502
+ * 1.10.0 把 `stats.total` 改成了计划定义条数,但 `deliveryReadiness` 仍然只遍历
2503
+ * 实际存在的状态行——于是「定义 13 项、只写 5 行且全 done」会得到
2504
+ * `done=5 / total=13` 却 **ready=true**,present 门禁可放行只做了 5/13 的计划
2505
+ * (T10 实测 `[done=5,total=13,ready=True]`)。缺失的行就是没做完,必须算阻塞。
2506
+ */
2507
+ const missingRows = total - statuses.length
2508
+ if (total > 0 && missingRows > 0) {
2509
+ blockers.push(`状态明细缺少 ${missingRows} 行(计划定义 ${total} 项,实际只写 ${statuses.length} 行):缺失项按未完成计`)
2510
+ }
2238
2511
  if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2239
2512
  blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`)
2240
2513
  }
@@ -2469,6 +2742,28 @@ export function buildChildPrompt({
2469
2742
  '请针对上面这个原因调整做法,不要重复相同的失败路径;如果仍然无法完成,第一行输出 `BLOCKED: 原因` 并说明缺少什么。',
2470
2743
  ].join('\n')
2471
2744
  : ''
2745
+ /*
2746
+ * [1.8.19] A retried subtask must not pretend the prior attempt never existed.
2747
+ *
2748
+ * The timeout/budget paths record the declared outputs that already landed on
2749
+ * disk (`artifacts[].exists === true`). Feeding them back into the next
2750
+ * attempt turns a 15-minute restart into "check what is there and finish",
2751
+ * which is the difference between a recoverable ceiling and silent rework.
2752
+ */
2753
+ const previousStatus = Array.isArray(statuses)
2754
+ ? statuses.find((item: any) => item && item.subtaskId === subtask?.id)
2755
+ : null
2756
+ const landedArtifacts = (Array.isArray(previousStatus?.artifacts) ? previousStatus.artifacts : [])
2757
+ .filter((item: any) => item && item.exists === true && typeof item.ref === 'string')
2758
+ .map((item: any) => String(item.ref))
2759
+ const resumeHint = landedArtifacts.length > 0
2760
+ ? [
2761
+ '',
2762
+ '上一次这一子任务被中止,但以下声明产物已经在盘上(先用 read/grep 核对,不要重写):',
2763
+ ...landedArtifacts.slice(0, 8).map((ref: string) => `- ${ref}`),
2764
+ '已经覆盖验收标准的部分保持原样,只补缺失部分;结尾按契约给出证据块。',
2765
+ ].join('\n')
2766
+ : ''
2472
2767
  /*
2473
2768
  * [1.8.12] 提示词整体过一遍 session-reference 消毒。
2474
2769
  *
@@ -2501,6 +2796,7 @@ export function buildChildPrompt({
2501
2796
  dependencies,
2502
2797
  ...(team ? ['', '兄弟部门进展(同一计划内的其他子任务;不要直接联系它们,需要协作请写进 needs 由主 Agent 转达):', team] : []),
2503
2798
  ...(failure ? [failure] : []),
2799
+ ...(resumeHint ? [resumeHint] : []),
2504
2800
  '',
2505
2801
  '执行要求:',
2506
2802
  '- 只完成本子任务,不擅自扩大范围;不要派生新的 Agent。',