dsh-workplan 1.8.18 → 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/runtime.ts CHANGED
@@ -36,6 +36,7 @@ import {
36
36
  flattenSubtasks,
37
37
  isRecord,
38
38
  isSocialMessage,
39
+ isTerminalPhase,
39
40
  isStatusQuestion,
40
41
  isVagueContinuation,
41
42
  makeUserMessage,
@@ -43,6 +44,7 @@ import {
43
44
  messageText,
44
45
  readySubtasks,
45
46
  MAX_PLAN_RESUMES,
47
+ PRESENT_DENY_CODES,
46
48
  canResumePlan,
47
49
  resetBlockedStatuses,
48
50
  parseCancelMessage,
@@ -54,10 +56,14 @@ import {
54
56
  validatePlan,
55
57
  applyResultStatuses,
56
58
  adjudicateResult,
59
+ activeDenyCode,
57
60
  MAX_CONVERSATION_CHARS,
58
61
  parseUpdateMessage,
59
62
  buildUpdateMessage,
60
63
  } from './plan.js'
64
+ import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
65
+ import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
66
+ import { supersedePlanRecord } from './supersede.js'
61
67
  import { createProgressWatchdog, describeError } from './watchdog.js'
62
68
 
63
69
  /**
@@ -513,6 +519,71 @@ export function probeInterruptedEvidence(output: any, subtask: any, cwd: any, ar
513
519
  return { artifacts, missingArtifacts }
514
520
  }
515
521
 
522
+ /**
523
+ * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
524
+ */
525
+ export function findSubtaskById(plan: any, subtaskId: string) {
526
+ for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
527
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
528
+ if (subtask?.id === subtaskId) return subtask
529
+ }
530
+ }
531
+ return null
532
+ }
533
+
534
+ /**
535
+ * [1.8.19] A hard per-subtask timeout must not erase what the child already wrote.
536
+ *
537
+ * Real incident (2026-10-31 23:23:38): T11/T12 were aborted by the 900 s
538
+ * per-subtask ceiling four seconds after their deliverables had landed
539
+ * (T11 32,996 B report + 140-row index; T12 51,547 B report). The parent only
540
+ * saw `blocked / 达到执行上限`, with no hint that the files existed, so the same
541
+ * work would be redone from scratch. This probe records the landed declared
542
+ * outputs in the status row and in the error text — it does not change the
543
+ * verdict (a timeout is still `blocked`), it only stops the evidence loss.
544
+ */
545
+ export function timeoutBlockedPatch(subtask: any, cwd: any, message: string, artifactExists: any = existsSync) {
546
+ const evidence = probeInterruptedEvidence(null, subtask, cwd, artifactExists)
547
+ const landed = evidence.artifacts.filter((item: any) => item?.exists === true).map((item: any) => String(item.ref))
548
+ const artifactNote = landed.length > 0
549
+ ? `;该步声明的产物已在盘上:${landed.slice(0, 6).join('、')}(先核对,不要当作从未运行)`
550
+ : ''
551
+ return {
552
+ patch: {
553
+ status: 'blocked',
554
+ progress: 100,
555
+ finishedAt: Date.now(),
556
+ error: message + artifactNote,
557
+ summary: truncate(`未完成:${message}${artifactNote}`, 3000),
558
+ ...(evidence.artifacts.length > 0 ? { artifacts: evidence.artifacts } : {}),
559
+ ...(evidence.missingArtifacts.length > 0 ? { missingArtifacts: evidence.missingArtifacts } : {}),
560
+ },
561
+ landed,
562
+ }
563
+ }
564
+
565
+ /**
566
+ * [1.8.19] The round budget reset used to erase every trace of the attempt.
567
+ *
568
+ * The 20-minute `TOTAL_TIMEOUT` branch resets unfinished rows to `pending`, and
569
+ * `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
570
+ * 2026-10-31 incident T10 had run for ~19 minutes and had already written its
571
+ * coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
572
+ * said "not started" and the user asked "why did T10 stop by itself". The
573
+ * attempt provenance and any landed declared outputs now travel in the error
574
+ * text, so the reset stays a pause but stops being an erasure.
575
+ */
576
+ export function budgetResetError(item: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
577
+ const landed = probeInterruptedArtifacts(null, subtask, cwd, artifactExists)
578
+ const parts = ['本轮预算用尽,等待续跑']
579
+ if (item?.childId) parts.push(`上一轮子会话 ${String(item.childId).slice(0, 8)}`)
580
+ if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
581
+ parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`)
582
+ }
583
+ if (landed.length > 0) parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`)
584
+ return parts.join(';')
585
+ }
586
+
516
587
  /**
517
588
  * Turn one child output into a status verdict.
518
589
  *
@@ -822,14 +893,10 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
822
893
  // plain "too slow" and the next investigation goes down the wrong path.
823
894
  const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`
824
895
  try {
825
- record.statuses = applyStatus(record.statuses, subtask.id, {
826
- status: 'blocked',
827
- progress: 100,
828
- finishedAt: Date.now(),
829
- error: message,
830
- summary: truncate(`未完成:${message}`, 3000),
831
- })
832
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${message}`].slice(-20)
896
+ // [1.8.19] Keep the evidence of what already landed on disk.
897
+ const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
898
+ record.statuses = applyStatus(record.statuses, subtask.id, patch)
899
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
833
900
  record.updatedAt = Date.now()
834
901
  } catch (error: any) {
835
902
  record.errors = [
@@ -1179,9 +1246,12 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1179
1246
  let reset = record.statuses
1180
1247
  for (const item of record.statuses) {
1181
1248
  if (item.status === 'done') continue
1249
+ // [1.8.19] Carry the aborted attempt's provenance and landed files into
1250
+ // the pause reason instead of silently erasing them.
1251
+ const definition = findSubtaskById(record.plan, item.subtaskId)
1182
1252
  reset = applyStatus(reset, item.subtaskId, {
1183
1253
  status: 'pending',
1184
- error: '本轮预算用尽,等待续跑',
1254
+ error: budgetResetError(item, definition, options.cwd, options.artifactExists),
1185
1255
  })
1186
1256
  }
1187
1257
  record.statuses = reset
@@ -1552,6 +1622,12 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1552
1622
  resultSeen: boolean
1553
1623
  resumeCount: number
1554
1624
  cancelled: boolean
1625
+ /*
1626
+ * [1.9.0] 被取代(责任已转移)。与 cancelled 互斥。本补丁只做读取、
1627
+ * 判定与拒绝;写入路径(V1–V8 核验 + 用户确认)见规则文档 §6,属下一批。
1628
+ */
1629
+ superseded: boolean
1630
+ supersededBy: any
1555
1631
  /*
1556
1632
  * [1.8.17] The durable result message carries the round's failure lines.
1557
1633
  * Replay used to drop them, and the reconstructed record then had no
@@ -1584,6 +1660,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1584
1660
  resultSeen: false,
1585
1661
  resumeCount: 0,
1586
1662
  cancelled: false,
1663
+ superseded: false,
1664
+ supersededBy: undefined,
1587
1665
  errors: [],
1588
1666
  }
1589
1667
  snapshots.set(plan.planId, snap)
@@ -1688,7 +1766,26 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1688
1766
  const cancel = parseCancelMessage(event.data)
1689
1767
  if (cancel && typeof cancel.planId === 'string') {
1690
1768
  const snap = snapshots.get(cancel.planId)
1691
- if (snap) snap.cancelled = true
1769
+ if (snap) {
1770
+ /*
1771
+ * [1.9.0] disposition='superseded' 的信封表示「责任已转移」,不是
1772
+ * 用户撤销。旧解析器只校验 kind,因此该字段对新旧版本都安全:旧版
1773
+ * 按 cancelled 读(不可派发、不可交付),不会复活成 active。
1774
+ */
1775
+ if (cancel.disposition === 'superseded') {
1776
+ snap.superseded = true
1777
+ snap.supersededBy = cancel.supersededBy
1778
+ /*
1779
+ * [1.9.2] 互斥(T6):取代永远发生在取消之后,所以日志里两条信封
1780
+ * 都在。只加 superseded 不清 cancelled,冷启动记录就会变成「既已
1781
+ * 取消、又被取代」,与 live 记录(`supersedePlanRecord` 写入时
1782
+ * 把 cancelled 置 false)分叉 —— 这正是写侧收敛要杜绝的那类分叉。
1783
+ */
1784
+ snap.cancelled = false
1785
+ } else {
1786
+ snap.cancelled = true
1787
+ }
1788
+ }
1692
1789
  }
1693
1790
  } else if (event.type === 'tool/call') {
1694
1791
  /*
@@ -1776,10 +1873,17 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1776
1873
  const resultPhase = chosen.resultPhase
1777
1874
  const resultSeen = chosen.resultSeen
1778
1875
  const resumeCount = chosen.resumeCount
1779
- const cancelled = chosen.cancelled
1876
+ const superseded = chosen.superseded
1877
+ /*
1878
+ * [1.9.2] 终态互斥(T6):superseded 与 cancelled 不会同时成立。手写/旧版
1879
+ * 日志里可能出现「supersede 信封之后又有一条取消信封」,此时按终态优先级
1880
+ * 只认 superseded(fail-closed:被取代依然不可派发、不可交付)。
1881
+ */
1882
+ const cancelled = chosen.cancelled && !superseded
1780
1883
  let phase = planPhase(statuses, resultSeen)
1781
1884
  if (resultPhase === 'paused' && statuses.some((item: any) => item.status !== 'done')) phase = 'paused'
1782
1885
  if (cancelled) phase = 'cancelled'
1886
+ if (superseded) phase = 'superseded'
1783
1887
  /*
1784
1888
  * [1.5.2] 回放也必须走同一套对账。
1785
1889
  *
@@ -1824,9 +1928,17 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1824
1928
  * whether that cancellation is durably recorded. For replay they are the
1825
1929
  * same; the live `cancelPlan` uses `cancelRecorded` to make a second
1826
1930
  * cancel a no-op instead of appending a duplicate message (N8).
1931
+ *
1932
+ * [1.9.2] 被取代的计划同样有一条已落盘的终态记录(V3 要求先取消才允许
1933
+ * 取代),因此 cancelRecorded 在 superseded 时为 true —— 与 live 记录一致
1934
+ * (`supersedePlanRecord` 保留先前的 cancelRecorded)。`supersedeRecorded`
1935
+ * 是取代信封的写入见证,补齐后普通取消的拒绝体在冷启动/热路径上字段相同。
1827
1936
  */
1828
1937
  cancelled,
1829
- cancelRecorded: cancelled,
1938
+ cancelRecorded: cancelled || superseded,
1939
+ superseded,
1940
+ supersedeRecorded: superseded,
1941
+ supersededBy: superseded ? chosen.supersededBy : undefined,
1830
1942
  }
1831
1943
  }
1832
1944
 
@@ -2225,6 +2337,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2225
2337
  if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2226
2338
  record = adoptRequestedPlan(session, record, args?.planId)
2227
2339
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
2340
+ /*
2341
+ * [1.9.2] superseded 的唯一写入入口(T6)。
2342
+ *
2343
+ * `disposition` 只有两个合法取值:省略/'cancelled' 走既有取消语义(返回体
2344
+ * 与 1.8.19 逐字相同);'superseded' 交给 `supersedePlanRecord`(V1–V8
2345
+ * 复算 + digest + durable 信封)。其他取值一律拒绝:静默忽略一个拼错的
2346
+ * disposition 会把「想取代」写成「取消」,而两者的读侧判定完全不同。
2347
+ */
2348
+ const disposition = args?.disposition
2349
+ if (disposition !== undefined && disposition !== 'cancelled' && disposition !== 'superseded') {
2350
+ throw new PlanError(
2351
+ `disposition 只能是 cancelled 或 superseded(收到 ${String(disposition)})`,
2352
+ 'INVALID_DISPOSITION',
2353
+ )
2354
+ }
2355
+ if (disposition === 'superseded') {
2356
+ const result = supersedePlanRecord(session, record, args, { reconstruct: reconstructFromSession })
2357
+ state.records.set(session.id, record)
2358
+ return result
2359
+ }
2360
+ /*
2361
+ * [1.9.2] 被取代的计划不允许被普通取消静默改回 cancelled。
2362
+ *
2363
+ * 旧路径会追加第二条不带 disposition 的取消信封:live 变 cancelled,
2364
+ * replay 却因同一 planId 先读到 superseded 而仍是 superseded —— 又一种
2365
+ * live/replay 分叉。行政撤销(E6)需要用户明确要求并写入新的处置记录,
2366
+ * 本版本不实现,因此这里 fail-closed 并给出可执行说明。
2367
+ */
2368
+ if (record.phase === 'superseded' || record.superseded === true) {
2369
+ return {
2370
+ ok: false,
2371
+ planId: record.plan.planId,
2372
+ phase: 'superseded',
2373
+ code: 'SUPERSEDED_LOCKED',
2374
+ error: '计划已被取代:不能静默改回 cancelled(行政撤销 E6 需要用户明确要求并写入新的处置记录,本版本未实现)',
2375
+ hint: '被取代不等于完成:不得调用 present、不得声称“已完成”。如需撤销该处置,请先向用户确认,再由主 Agent 走审计流程。',
2376
+ cancelRecorded: record.supersedeRecorded === true,
2377
+ stats: derivePlanSnapshot(record.statuses).stats,
2378
+ }
2379
+ }
2228
2380
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2229
2381
  ? args.reason.trim()
2230
2382
  : '用户取消'
@@ -2503,6 +2655,73 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2503
2655
  }
2504
2656
  }
2505
2657
 
2658
+ /*
2659
+ * [1.9.1] 用户授权的 follow-up 通道。
2660
+ *
2661
+ * 事故背景:三条子会话 a0d5b134 / 031225ef / 7934905a 在 2026-10-31
2662
+ * 23:07–23:23 之间被整轮预算与 900s 子任务上限中止,各自末轮
2663
+ * `turn/end = aborted/parent`;界面据此显示 idle(灰色),而台账侧三条
2664
+ * 都是 done/structured。用户 2026-11-01 明确同意「补发 follow-up,让圈注
2665
+ * 三行真正变绿」——做法是让子会话自己再跑完一个正常回合,而不是伪造
2666
+ * turn/end 或改投影缓存。
2667
+ *
2668
+ * 本工具只做一件事:把一条消息投递到本会话的**直接**子会话。它不写计划
2669
+ * 状态、不触发交付、也不改变 `lastTurnCompleted`——那个字段只会被子会话
2670
+ * 自己真实完成的回合改写。投递成功后子会话开始新一轮;它正常结束,界面
2671
+ * 才可能变绿。失败一律返回 ok:false,不吞错。
2672
+ */
2673
+ async function followupTool(agent: any, args: any, signal: any) {
2674
+ const session = agent?.session
2675
+ if (!session) {
2676
+ return { ok: false, code: 'NO_SESSION', error: '只能在会话内补发 follow-up' }
2677
+ }
2678
+ if (!isRootSession(session)) {
2679
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以补发 follow-up' }
2680
+ }
2681
+ const childId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : ''
2682
+ const message = typeof args?.message === 'string' ? args.message.trim() : ''
2683
+ if (!childId) {
2684
+ return { ok: false, code: 'INVALID_SESSION', error: 'sessionId 必填:必须是本会话的直接子会话 ID' }
2685
+ }
2686
+ if (!message) {
2687
+ return { ok: false, code: 'INVALID_MESSAGE', error: 'message 必填:要发给子会话的说明' }
2688
+ }
2689
+ if (message.length > 4000) {
2690
+ return { ok: false, code: 'MESSAGE_TOO_LONG', error: 'message 过长(上限 4000 字符)' }
2691
+ }
2692
+ if (!spawnedChildIds(session).has(childId)) {
2693
+ return {
2694
+ ok: false,
2695
+ code: 'NOT_DIRECT_CHILD',
2696
+ error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递`,
2697
+ }
2698
+ }
2699
+ const service: any = (ctx as any).subagents
2700
+ if (!service || typeof service.sendMessage !== 'function') {
2701
+ return {
2702
+ ok: false,
2703
+ code: 'NO_SUBAGENT_SERVICE',
2704
+ error: '当前部署没有可用的 subagent 服务,无法投递 follow-up',
2705
+ }
2706
+ }
2707
+ try {
2708
+ const messageId = await service.sendMessage(
2709
+ agent,
2710
+ childId,
2711
+ [{ type: 'text', text: message }],
2712
+ { signal },
2713
+ )
2714
+ return { ok: true, sessionId: childId, messageId: String(messageId ?? '') }
2715
+ } catch (error: any) {
2716
+ return {
2717
+ ok: false,
2718
+ code: 'DELIVERY_FAILED',
2719
+ sessionId: childId,
2720
+ error: truncate(error instanceof Error ? error.message : String(error), 500),
2721
+ }
2722
+ }
2723
+ }
2724
+
2506
2725
  async function dispatchTool(agent: any, args: any, signal: any) {
2507
2726
  const session = agent?.session
2508
2727
  if (!session) throw new PlanError('只能在会话内派发计划', 'NO_SESSION')
@@ -2553,20 +2772,30 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2553
2772
  * is the user's stop signal; the only honest answer is a refusal that says
2554
2773
  * how to continue deliberately (a new plan, or the main Agent takes over).
2555
2774
  */
2556
- if (record.phase === 'cancelled' || record.cancelled === true) {
2775
+ if (isTerminalPhase(record.phase) || record.cancelled === true) {
2776
+ /*
2777
+ * [1.9.0] 终态集合:cancelled(用户撤销)与 superseded(责任已转移)
2778
+ * 都不允许派发、不允许复活。superseded 用独立拒绝码,便于调用方区分
2779
+ * 「用户叫停」与「已被别的计划承接」。cancelled 的返回体与 1.8.19 相同。
2780
+ */
2781
+ const superseded = record.phase === 'superseded'
2557
2782
  const snapshot = derivePlanSnapshot(record.statuses)
2558
2783
  return {
2559
2784
  ok: false,
2560
2785
  planId: record.plan.planId,
2561
- phase: 'cancelled',
2786
+ phase: superseded ? 'superseded' : 'cancelled',
2562
2787
  running: false,
2563
2788
  alreadyRunning: false,
2564
2789
  complete: false,
2565
2790
  remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
2566
2791
  stats: snapshot.stats,
2567
- code: 'PLAN_CANCELLED',
2568
- error: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2569
- hint: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2792
+ code: superseded ? 'PLAN_SUPERSEDED' : 'PLAN_CANCELLED',
2793
+ error: superseded
2794
+ ? '计划已被取代:不会再启动任何部门 Agent'
2795
+ : '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2796
+ hint: superseded
2797
+ ? '不要再次派发。被取代不等于完成:如需交付,请按覆盖链核对承接计划的证据;承接计划未就绪时不得调用 present。'
2798
+ : '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2570
2799
  }
2571
2800
  }
2572
2801
  /*
@@ -2782,9 +3011,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2782
3011
  return deliveryReadiness(snapshot, { phase: record.phase })
2783
3012
  }
2784
3013
 
2785
- function stopGateApplies(record: any) {
3014
+ function stopGateApplies(record: any, session?: any, turn?: number) {
2786
3015
  if (!record?.plan) return false
2787
3016
  if (record.degraded) return false
3017
+ /*
3018
+ * [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
3019
+ * cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
3020
+ * superseded 不 steer:它的判定对象是承接计划,present 的拒绝文案已给出出路。
3021
+ */
3022
+ if (isTerminalPhase(record.phase)) {
3023
+ return record.phase === 'cancelled'
3024
+ && Boolean(session && turn && planIdFromTurn(session, turn) === record.plan.planId)
3025
+ }
2788
3026
  const readiness = recordReadiness(record)
2789
3027
  if (Number(readiness.total ?? 0) === 0) return false
2790
3028
  return !readiness.ready
@@ -2989,7 +3227,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2989
3227
  record = reconstructFromSession(session, planIdFromTurn(session, turn))
2990
3228
  if (record?.plan) state.records.set(session.id, record)
2991
3229
  }
2992
- if (!stopGateApplies(record)) return
3230
+ if (!stopGateApplies(record, session, turn)) return
2993
3231
  if (record.dispatchPromise) {
2994
3232
  try {
2995
3233
  await record.dispatchPromise
@@ -2997,7 +3235,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2997
3235
  /* the failure is already on record.errors; the gate only needs the outcome */
2998
3236
  }
2999
3237
  finishRound(record, session)
3000
- if (!stopGateApplies(record)) return
3238
+ if (!stopGateApplies(record, session, turn)) return
3001
3239
  }
3002
3240
  const book = record.stopSteers && record.stopSteers.turn === turn
3003
3241
  ? record.stopSteers
@@ -3111,7 +3349,79 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3111
3349
  return undefined
3112
3350
  }
3113
3351
 
3114
- function presentDenialReason(agent: any) {
3352
+ /**
3353
+ * [1.9.0] 点名 superseded 时的覆盖链判定(T8 §4.2 第 4 条、§6.3)。
3354
+ *
3355
+ * superseded 只是「责任已转移」,不是完成:本回合点名它时,判的是承接计划
3356
+ * 是否真的就绪。承接计划缺失/已终止/无法复核 ⇒ fail-closed(SUPERSEDED_STALE);
3357
+ * 承接计划未就绪 ⇒ 拒绝;只有承接计划 deliveryReady 才放行(产物来自承接计划)。
3358
+ *
3359
+ * [1.9.2] 返回值带上拒绝码(T8 §4.3 `judgeEffective`):覆盖链无法复核
3360
+ * ⇒ `SUPERSEDED_STALE`;覆盖链有效但承接计划未就绪 ⇒ `ACTIVE_NOT_READY`。
3361
+ * 文案保持逐字不变,码值走 `src/plan.ts` 的同一组常量。
3362
+ */
3363
+ function supersededDenialVerdict(session: any, record: any): PresentDenialVerdict | undefined {
3364
+ const planId = record.plan?.planId ?? record.planId ?? ''
3365
+ const by = record.supersededBy
3366
+ const successorPlanId = typeof by?.successorPlanId === 'string' && by.successorPlanId
3367
+ ? by.successorPlanId
3368
+ : typeof by?.planId === 'string' ? by.planId : ''
3369
+ if (!successorPlanId) {
3370
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3371
+ `计划 ${planId} 已被取代,但缺少可验证的承接计划(supersededBy.successorPlanId):`
3372
+ + '覆盖证据失效(SUPERSEDED_STALE),不得调用 present;请向用户说明覆盖链无法复核并重新确认交付对象。')
3373
+ }
3374
+ /*
3375
+ * [W1] 覆盖摘要:present 复验从 mapping 重算摘要,不读缓存数值(T8 §6.3)。
3376
+ *
3377
+ * 摘要一旦对不上(含 mapping/digest 缺失),覆盖记录就无法复核 —— 无法复核
3378
+ * ≠ 通过,一律 stale。这条检查只证明「存下来的 mapping 没被改动」,不证明
3379
+ * 「两项工作在语义上等价」;后者仍只能由用户确认(V8)承载。
3380
+ */
3381
+ const mapping = by?.mapping
3382
+ if (!Array.isArray(mapping)) {
3383
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3384
+ `计划 ${planId} 已被取代,但缺少可复算的逐项映射(supersededBy.mapping):`
3385
+ + '覆盖证据失效(SUPERSEDED_STALE),不得调用 present,不得声称“已完成/最终版/已交付”;'
3386
+ + '请重新按用户确认的逐项映射做覆盖迁移,并由运行时写入复算后的 digest。')
3387
+ }
3388
+ const computedDigest = computeMappingDigest(mapping)
3389
+ if (!verifyMappingDigest(mapping, by?.digest)) {
3390
+ const stored = typeof by?.digest === 'string' ? by.digest.slice(0, 15) : '缺失'
3391
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3392
+ `计划 ${planId} 已被取代,但覆盖证据摘要与逐项映射不一致(supersededBy.digest=${stored},`
3393
+ + `重算=${computedDigest.slice(0, 15)}):覆盖证据失效(SUPERSEDED_STALE),不得调用 present,`
3394
+ + '不得声称“已完成/最终版/已交付”;请重新按用户确认的逐项映射做覆盖迁移,并由运行时复算 digest。')
3395
+ }
3396
+ const successor = reconstructFromSession(session, successorPlanId)
3397
+ if (!successor?.plan || definedSubtaskCount(successor.plan) === 0 || isTerminalPhase(successor.phase)) {
3398
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3399
+ `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
3400
+ + '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。')
3401
+ }
3402
+ const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase })
3403
+ if (!readiness.ready) {
3404
+ const ids = readiness.remaining.slice(0, 10).join('、')
3405
+ return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
3406
+ `计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
3407
+ + `${ids ? `,剩余 ${readiness.remaining.length} 项(${ids})` : ''}。`
3408
+ + '被取代不等于完成:承接计划通过交付就绪检查之前不得调用 present。')
3409
+ }
3410
+ return undefined
3411
+ }
3412
+
3413
+ /**
3414
+ * [1.9.2] present 拒绝点的唯一出口:码值取常量,拒绝文案保持逐字不变。
3415
+ *
3416
+ * host 的 guard 契约是 `string`(`ctx.tools.checkGuards`),所以工具错误里
3417
+ * 仍只有文案;码值由 `presentDenialVerdict` 一并返回,供断言、日志与后续
3418
+ * UI 使用。所有分支都必须经由这里,不要在分支里手写码值。
3419
+ */
3420
+ function presentDenial(code: PresentDenyCode, message: string): PresentDenialVerdict {
3421
+ return { code, message }
3422
+ }
3423
+
3424
+ function presentDenialVerdict(agent: any): PresentDenialVerdict | undefined {
3115
3425
  const session = agent?.session
3116
3426
  if (!session || !isRootSession(session)) return undefined
3117
3427
  if (isPlanModeActive(ctx, session)) return undefined
@@ -3158,7 +3468,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3158
3468
  * or the last defined plan after a restart) is about: cancel stops
3159
3469
  * execution, it does not make the work deliverable.
3160
3470
  */
3161
- .filter((entry: any) => entry.record.phase !== 'cancelled' && !entry.readiness.ready)
3471
+ .filter((entry: any) => !isTerminalPhase(entry.record.phase) && !entry.readiness.ready)
3162
3472
  if (unresolved.length > 1) {
3163
3473
  const lines = unresolved.slice(0, 6).map((entry: any) => {
3164
3474
  const ids = entry.readiness.remaining.slice(0, 6).join('、')
@@ -3167,10 +3477,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3167
3477
  return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
3168
3478
  + `${gaps ? `;证据缺口:${gaps}` : ''}`
3169
3479
  })
3170
- return `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3480
+ return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
3481
+ `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3171
3482
  + '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
3172
3483
  + '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
3173
- + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。'
3484
+ + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。')
3174
3485
  }
3175
3486
  let record: any
3176
3487
  let readiness: any
@@ -3191,10 +3502,23 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3191
3502
  if (!record?.plan) record = lastGateablePlanRecord(session)
3192
3503
  if (!record?.plan) return undefined
3193
3504
  if (definedSubtaskCount(record.plan) === 0) return undefined
3505
+ /*
3506
+ * [1.9.0] 终态解耦(T8 §4.3 P3):终态计划不再被自动选为判定对象。
3507
+ *
3508
+ * 只有「本回合结构化点名」时才判定;否则不再写回 live、不再拦截其它
3509
+ * 计划的交付。取消 ≠ 完成:记录仍是 cancelled 0/N,只是不再永久挡门。
3510
+ */
3511
+ const namedThisTurn = Boolean(turnPlanId && record.plan.planId === turnPlanId)
3512
+ if (isTerminalPhase(record.phase) && !namedThisTurn) return undefined
3513
+ if (record.phase === 'superseded') {
3514
+ const denial = supersededDenialVerdict(session, record)
3515
+ if (denial) return denial
3516
+ return undefined
3517
+ }
3194
3518
  readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase })
3195
3519
  if (readiness.ready) return undefined
3196
3520
  }
3197
- if (record?.plan) state.records.set(session.id, record)
3521
+ if (record?.plan && !isTerminalPhase(record.phase)) state.records.set(session.id, record)
3198
3522
  const snapshot = derivePlanSnapshot(record.statuses)
3199
3523
  const planId = record.plan?.planId ?? record.planId
3200
3524
  const ids = readiness.remaining.slice(0, 10).join('、')
@@ -3211,26 +3535,44 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3211
3535
  .slice(0, 10)
3212
3536
  .join(';')
3213
3537
  if (readiness.remaining.length === 0) {
3214
- return `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3538
+ return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED,
3539
+ `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3215
3540
  + '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
3216
- + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。'
3541
+ + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。')
3217
3542
  }
3218
- return `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3543
+ return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED,
3544
+ `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3219
3545
  + `${gaps ? `;证据缺口:${gaps}` : ''}。`
3220
3546
  + '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
3221
- + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。'
3547
+ + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。')
3222
3548
  }
3549
+ /*
3550
+ * [1.9.2] P1 的单一映射:`activeDenyCode` 只看就绪结果。
3551
+ * `remaining` 为空但 `blockers` 非空 ⇒ `EVIDENCE_GAP`(T9 C05 的修法);
3552
+ * 还有子任务没做完 ⇒ `ACTIVE_NOT_READY`。两个分支共用同一个码值来源。
3553
+ */
3554
+ const activeCode = activeDenyCode(readiness)
3223
3555
  if (readiness.remaining.length === 0) {
3224
- return `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3556
+ return presentDenial(activeCode,
3557
+ `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3225
3558
  + '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
3226
3559
  + "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
3227
- + '或把对应子任务改回 blocked 并写明原因;不要调用 present。'
3560
+ + '或把对应子任务改回 blocked 并写明原因;不要调用 present。')
3228
3561
  }
3229
- return `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3562
+ return presentDenial(activeCode,
3563
+ `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3230
3564
  + `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
3231
3565
  + '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
3232
3566
  + '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
3233
- + '取消只停止执行,不会改变“未完成”的结论。'
3567
+ + '取消只停止执行,不会改变“未完成”的结论。')
3568
+ }
3569
+
3570
+ /**
3571
+ * 兼容入口:host 的 guard 只接受字符串,所以工具错误仍是原来的文案。
3572
+ * 需要码值时调用 `presentDenialVerdict`。
3573
+ */
3574
+ function presentDenialReason(agent: any) {
3575
+ return presentDenialVerdict(agent)?.message
3234
3576
  }
3235
3577
 
3236
3578
  /*
@@ -3316,7 +3658,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3316
3658
  const unresolved = [...planIds]
3317
3659
  .map((planId) => recordForPlan(session, planId))
3318
3660
  .filter((record: any) => record?.plan
3319
- && record.phase !== 'cancelled'
3661
+ && !isTerminalPhase(record.phase)
3320
3662
  && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready)
3321
3663
  if (unresolved.length === 0) return undefined
3322
3664
  const ids = unresolved.slice(0, 4).map((record: any) => record.plan.planId)
@@ -3414,11 +3756,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3414
3756
  onPreStep,
3415
3757
  onTurnStopping,
3416
3758
  presentDenialReason,
3759
+ presentDenialVerdict,
3760
+ supersededDenialVerdict,
3417
3761
  presentedWriteDenialReason,
3418
3762
  updateStatus,
3419
3763
  cancelPlan,
3420
3764
  dispatchTool,
3421
3765
  statusTool,
3766
+ followupTool,
3422
3767
  plansPayload,
3423
3768
  route,
3424
3769
  dispose,
@@ -3490,7 +3835,13 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
3490
3835
  // A plan committed but not yet dispatched must not be overwritten in the
3491
3836
  // same turn; a later turn may supersede it, otherwise one abandoned plan
3492
3837
  // would lock planning forever.
3493
- if (existing?.plan && !existing.dispatchedAt) {
3838
+ //
3839
+ // [1.9.2] 自动覆盖路径**只允许**写 cancelled,永不写 superseded(规则设计
3840
+ // §7.1:自动路径没有逐项映射与用户确认,满足不了 V4–V8)。它也不得把已经
3841
+ // superseded 的终态记录改回 cancelled:内存写 cancelled、日志里仍是
3842
+ // supersede 信封,会让 live 与 replay 分叉。终态记录由 present 的终态解耦
3843
+ // 处理(不再自动挡门),不需要在这里「取消」。
3844
+ if (existing?.plan && !existing.dispatchedAt && !isTerminalPhase(existing.phase)) {
3494
3845
  if (existing.plan.createdTurn === payload.turn) return downstream
3495
3846
  existing.phase = 'cancelled'
3496
3847
  existing.cancelledAt = Date.now()
@@ -3679,6 +4030,36 @@ export function cancelToolOutputSchema() {
3679
4030
  cancelRecorded: { type: 'boolean' },
3680
4031
  alreadyCancelled: { type: 'boolean' },
3681
4032
  abortedRunning: { type: 'boolean' },
4033
+ /*
4034
+ * [1.9.2] `disposition="superseded"` answers. `supersedeRecorded` is the
4035
+ * durable-write witness for the supersede envelope (the cancelled answer
4036
+ * uses `cancelRecorded`); `alreadySuperseded` is the §7.4 idempotent
4037
+ * re-submission. `code` carries the SUPERSEDE_* refusal; `gaps` /
4038
+ * `missingFrom` / `problems` explain exactly which V-rule failed so a
4039
+ * caller can repair the mapping instead of guessing.
4040
+ */
4041
+ disposition: { type: 'string' },
4042
+ supersededAt: { type: 'number' },
4043
+ supersedeRecorded: { type: 'boolean' },
4044
+ alreadySuperseded: { type: 'boolean' },
4045
+ coverage: { type: 'string' },
4046
+ requiredCount: { type: 'number' },
4047
+ coveredCount: { type: 'number' },
4048
+ successorSeenAtSeq: { type: 'number' },
4049
+ confirmedAtSeq: { type: 'number' },
4050
+ supersededBy: {
4051
+ type: 'object',
4052
+ properties: {
4053
+ planId: { type: 'string' },
4054
+ },
4055
+ additionalProperties: true,
4056
+ },
4057
+ code: { type: 'string' },
4058
+ error: { type: 'string' },
4059
+ hint: { type: 'string' },
4060
+ gaps: { type: 'array', items: { type: 'string' } },
4061
+ missingFrom: { type: 'array', items: { type: 'string' } },
4062
+ problems: { type: 'array', items: { type: 'string' } },
3682
4063
  },
3683
4064
  required: ['ok'],
3684
4065
  additionalProperties: true,