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/lib/runtime.js CHANGED
@@ -14,7 +14,9 @@
14
14
  import { randomUUID } from 'node:crypto';
15
15
  import { existsSync } from 'node:fs';
16
16
  import { isAbsolute, resolve } from 'node:path';
17
- import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
17
+ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
18
+ import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
19
+ import { supersedePlanRecord } from './supersede.js';
18
20
  import { createProgressWatchdog, describeError } from './watchdog.js';
19
21
  /**
20
22
  * [1.8.18] How many subtasks the plan *defines*.
@@ -481,6 +483,71 @@ export function probeInterruptedEvidence(output, subtask, cwd, artifactExists =
481
483
  const missingArtifacts = declared.filter((ref) => !landed.includes(ref));
482
484
  return { artifacts, missingArtifacts };
483
485
  }
486
+ /**
487
+ * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
488
+ */
489
+ export function findSubtaskById(plan, subtaskId) {
490
+ for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
491
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
492
+ if (subtask?.id === subtaskId)
493
+ return subtask;
494
+ }
495
+ }
496
+ return null;
497
+ }
498
+ /**
499
+ * [1.8.19] A hard per-subtask timeout must not erase what the child already wrote.
500
+ *
501
+ * Real incident (2026-10-31 23:23:38): T11/T12 were aborted by the 900 s
502
+ * per-subtask ceiling four seconds after their deliverables had landed
503
+ * (T11 32,996 B report + 140-row index; T12 51,547 B report). The parent only
504
+ * saw `blocked / 达到执行上限`, with no hint that the files existed, so the same
505
+ * work would be redone from scratch. This probe records the landed declared
506
+ * outputs in the status row and in the error text — it does not change the
507
+ * verdict (a timeout is still `blocked`), it only stops the evidence loss.
508
+ */
509
+ export function timeoutBlockedPatch(subtask, cwd, message, artifactExists = existsSync) {
510
+ const evidence = probeInterruptedEvidence(null, subtask, cwd, artifactExists);
511
+ const landed = evidence.artifacts.filter((item) => item?.exists === true).map((item) => String(item.ref));
512
+ const artifactNote = landed.length > 0
513
+ ? `;该步声明的产物已在盘上:${landed.slice(0, 6).join('、')}(先核对,不要当作从未运行)`
514
+ : '';
515
+ return {
516
+ patch: {
517
+ status: 'blocked',
518
+ progress: 100,
519
+ finishedAt: Date.now(),
520
+ error: message + artifactNote,
521
+ summary: truncate(`未完成:${message}${artifactNote}`, 3000),
522
+ ...(evidence.artifacts.length > 0 ? { artifacts: evidence.artifacts } : {}),
523
+ ...(evidence.missingArtifacts.length > 0 ? { missingArtifacts: evidence.missingArtifacts } : {}),
524
+ },
525
+ landed,
526
+ };
527
+ }
528
+ /**
529
+ * [1.8.19] The round budget reset used to erase every trace of the attempt.
530
+ *
531
+ * The 20-minute `TOTAL_TIMEOUT` branch resets unfinished rows to `pending`, and
532
+ * `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
533
+ * 2026-10-31 incident T10 had run for ~19 minutes and had already written its
534
+ * coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
535
+ * said "not started" and the user asked "why did T10 stop by itself". The
536
+ * attempt provenance and any landed declared outputs now travel in the error
537
+ * text, so the reset stays a pause but stops being an erasure.
538
+ */
539
+ export function budgetResetError(item, subtask, cwd, artifactExists = existsSync) {
540
+ const landed = probeInterruptedArtifacts(null, subtask, cwd, artifactExists);
541
+ const parts = ['本轮预算用尽,等待续跑'];
542
+ if (item?.childId)
543
+ parts.push(`上一轮子会话 ${String(item.childId).slice(0, 8)}`);
544
+ if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
545
+ parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`);
546
+ }
547
+ if (landed.length > 0)
548
+ parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`);
549
+ return parts.join(';');
550
+ }
484
551
  /**
485
552
  * Turn one child output into a status verdict.
486
553
  *
@@ -794,14 +861,10 @@ async function runSubtask(ctx, record, stage, subtask, options) {
794
861
  // plain "too slow" and the next investigation goes down the wrong path.
795
862
  const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`;
796
863
  try {
797
- record.statuses = applyStatus(record.statuses, subtask.id, {
798
- status: 'blocked',
799
- progress: 100,
800
- finishedAt: Date.now(),
801
- error: message,
802
- summary: truncate(`未完成:${message}`, 3000),
803
- });
804
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${message}`].slice(-20);
864
+ // [1.8.19] Keep the evidence of what already landed on disk.
865
+ const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
866
+ record.statuses = applyStatus(record.statuses, subtask.id, patch);
867
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
805
868
  record.updatedAt = Date.now();
806
869
  }
807
870
  catch (error) {
@@ -1169,9 +1232,12 @@ export async function dispatchPlan(ctx, record, options) {
1169
1232
  for (const item of record.statuses) {
1170
1233
  if (item.status === 'done')
1171
1234
  continue;
1235
+ // [1.8.19] Carry the aborted attempt's provenance and landed files into
1236
+ // the pause reason instead of silently erasing them.
1237
+ const definition = findSubtaskById(record.plan, item.subtaskId);
1172
1238
  reset = applyStatus(reset, item.subtaskId, {
1173
1239
  status: 'pending',
1174
- error: '本轮预算用尽,等待续跑',
1240
+ error: budgetResetError(item, definition, options.cwd, options.artifactExists),
1175
1241
  });
1176
1242
  }
1177
1243
  record.statuses = reset;
@@ -1567,6 +1633,8 @@ export function reconstructFromSession(session, targetPlanId) {
1567
1633
  resultSeen: false,
1568
1634
  resumeCount: 0,
1569
1635
  cancelled: false,
1636
+ superseded: false,
1637
+ supersededBy: undefined,
1570
1638
  errors: [],
1571
1639
  };
1572
1640
  snapshots.set(plan.planId, snap);
@@ -1676,8 +1744,27 @@ export function reconstructFromSession(session, targetPlanId) {
1676
1744
  const cancel = parseCancelMessage(event.data);
1677
1745
  if (cancel && typeof cancel.planId === 'string') {
1678
1746
  const snap = snapshots.get(cancel.planId);
1679
- if (snap)
1680
- snap.cancelled = true;
1747
+ if (snap) {
1748
+ /*
1749
+ * [1.9.0] disposition='superseded' 的信封表示「责任已转移」,不是
1750
+ * 用户撤销。旧解析器只校验 kind,因此该字段对新旧版本都安全:旧版
1751
+ * 按 cancelled 读(不可派发、不可交付),不会复活成 active。
1752
+ */
1753
+ if (cancel.disposition === 'superseded') {
1754
+ snap.superseded = true;
1755
+ snap.supersededBy = cancel.supersededBy;
1756
+ /*
1757
+ * [1.9.2] 互斥(T6):取代永远发生在取消之后,所以日志里两条信封
1758
+ * 都在。只加 superseded 不清 cancelled,冷启动记录就会变成「既已
1759
+ * 取消、又被取代」,与 live 记录(`supersedePlanRecord` 写入时
1760
+ * 把 cancelled 置 false)分叉 —— 这正是写侧收敛要杜绝的那类分叉。
1761
+ */
1762
+ snap.cancelled = false;
1763
+ }
1764
+ else {
1765
+ snap.cancelled = true;
1766
+ }
1767
+ }
1681
1768
  }
1682
1769
  }
1683
1770
  else if (event.type === 'tool/call') {
@@ -1774,12 +1861,20 @@ export function reconstructFromSession(session, targetPlanId) {
1774
1861
  const resultPhase = chosen.resultPhase;
1775
1862
  const resultSeen = chosen.resultSeen;
1776
1863
  const resumeCount = chosen.resumeCount;
1777
- const cancelled = chosen.cancelled;
1864
+ const superseded = chosen.superseded;
1865
+ /*
1866
+ * [1.9.2] 终态互斥(T6):superseded 与 cancelled 不会同时成立。手写/旧版
1867
+ * 日志里可能出现「supersede 信封之后又有一条取消信封」,此时按终态优先级
1868
+ * 只认 superseded(fail-closed:被取代依然不可派发、不可交付)。
1869
+ */
1870
+ const cancelled = chosen.cancelled && !superseded;
1778
1871
  let phase = planPhase(statuses, resultSeen);
1779
1872
  if (resultPhase === 'paused' && statuses.some((item) => item.status !== 'done'))
1780
1873
  phase = 'paused';
1781
1874
  if (cancelled)
1782
1875
  phase = 'cancelled';
1876
+ if (superseded)
1877
+ phase = 'superseded';
1783
1878
  /*
1784
1879
  * [1.5.2] 回放也必须走同一套对账。
1785
1880
  *
@@ -1824,9 +1919,17 @@ export function reconstructFromSession(session, targetPlanId) {
1824
1919
  * whether that cancellation is durably recorded. For replay they are the
1825
1920
  * same; the live `cancelPlan` uses `cancelRecorded` to make a second
1826
1921
  * cancel a no-op instead of appending a duplicate message (N8).
1922
+ *
1923
+ * [1.9.2] 被取代的计划同样有一条已落盘的终态记录(V3 要求先取消才允许
1924
+ * 取代),因此 cancelRecorded 在 superseded 时为 true —— 与 live 记录一致
1925
+ * (`supersedePlanRecord` 保留先前的 cancelRecorded)。`supersedeRecorded`
1926
+ * 是取代信封的写入见证,补齐后普通取消的拒绝体在冷启动/热路径上字段相同。
1827
1927
  */
1828
1928
  cancelled,
1829
- cancelRecorded: cancelled,
1929
+ cancelRecorded: cancelled || superseded,
1930
+ superseded,
1931
+ supersedeRecorded: superseded,
1932
+ supersededBy: superseded ? chosen.supersededBy : undefined,
1830
1933
  };
1831
1934
  }
1832
1935
  function liveSessions(ctx) {
@@ -2193,6 +2296,43 @@ export function createWorkplanRuntime(ctx, options = {}) {
2193
2296
  record = adoptRequestedPlan(session, record, args?.planId);
2194
2297
  if (!record?.plan)
2195
2298
  throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
2299
+ /*
2300
+ * [1.9.2] superseded 的唯一写入入口(T6)。
2301
+ *
2302
+ * `disposition` 只有两个合法取值:省略/'cancelled' 走既有取消语义(返回体
2303
+ * 与 1.8.19 逐字相同);'superseded' 交给 `supersedePlanRecord`(V1–V8
2304
+ * 复算 + digest + durable 信封)。其他取值一律拒绝:静默忽略一个拼错的
2305
+ * disposition 会把「想取代」写成「取消」,而两者的读侧判定完全不同。
2306
+ */
2307
+ const disposition = args?.disposition;
2308
+ if (disposition !== undefined && disposition !== 'cancelled' && disposition !== 'superseded') {
2309
+ throw new PlanError(`disposition 只能是 cancelled 或 superseded(收到 ${String(disposition)})`, 'INVALID_DISPOSITION');
2310
+ }
2311
+ if (disposition === 'superseded') {
2312
+ const result = supersedePlanRecord(session, record, args, { reconstruct: reconstructFromSession });
2313
+ state.records.set(session.id, record);
2314
+ return result;
2315
+ }
2316
+ /*
2317
+ * [1.9.2] 被取代的计划不允许被普通取消静默改回 cancelled。
2318
+ *
2319
+ * 旧路径会追加第二条不带 disposition 的取消信封:live 变 cancelled,
2320
+ * replay 却因同一 planId 先读到 superseded 而仍是 superseded —— 又一种
2321
+ * live/replay 分叉。行政撤销(E6)需要用户明确要求并写入新的处置记录,
2322
+ * 本版本不实现,因此这里 fail-closed 并给出可执行说明。
2323
+ */
2324
+ if (record.phase === 'superseded' || record.superseded === true) {
2325
+ return {
2326
+ ok: false,
2327
+ planId: record.plan.planId,
2328
+ phase: 'superseded',
2329
+ code: 'SUPERSEDED_LOCKED',
2330
+ error: '计划已被取代:不能静默改回 cancelled(行政撤销 E6 需要用户明确要求并写入新的处置记录,本版本未实现)',
2331
+ hint: '被取代不等于完成:不得调用 present、不得声称“已完成”。如需撤销该处置,请先向用户确认,再由主 Agent 走审计流程。',
2332
+ cancelRecorded: record.supersedeRecorded === true,
2333
+ stats: derivePlanSnapshot(record.statuses).stats,
2334
+ };
2335
+ }
2196
2336
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2197
2337
  ? args.reason.trim()
2198
2338
  : '用户取消';
@@ -2471,6 +2611,68 @@ export function createWorkplanRuntime(ctx, options = {}) {
2471
2611
  : { hint: '当前没有正在执行的派发。计划尚未通过交付就绪检查:先 dispatch 续跑剩余项;若只剩已 done 项的证据缺口,用 dsh_workplan_update 补 verification/acceptance。不要调用 present。' }),
2472
2612
  };
2473
2613
  }
2614
+ /*
2615
+ * [1.9.1] 用户授权的 follow-up 通道。
2616
+ *
2617
+ * 事故背景:三条子会话 a0d5b134 / 031225ef / 7934905a 在 2026-10-31
2618
+ * 23:07–23:23 之间被整轮预算与 900s 子任务上限中止,各自末轮
2619
+ * `turn/end = aborted/parent`;界面据此显示 idle(灰色),而台账侧三条
2620
+ * 都是 done/structured。用户 2026-11-01 明确同意「补发 follow-up,让圈注
2621
+ * 三行真正变绿」——做法是让子会话自己再跑完一个正常回合,而不是伪造
2622
+ * turn/end 或改投影缓存。
2623
+ *
2624
+ * 本工具只做一件事:把一条消息投递到本会话的**直接**子会话。它不写计划
2625
+ * 状态、不触发交付、也不改变 `lastTurnCompleted`——那个字段只会被子会话
2626
+ * 自己真实完成的回合改写。投递成功后子会话开始新一轮;它正常结束,界面
2627
+ * 才可能变绿。失败一律返回 ok:false,不吞错。
2628
+ */
2629
+ async function followupTool(agent, args, signal) {
2630
+ const session = agent?.session;
2631
+ if (!session) {
2632
+ return { ok: false, code: 'NO_SESSION', error: '只能在会话内补发 follow-up' };
2633
+ }
2634
+ if (!isRootSession(session)) {
2635
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以补发 follow-up' };
2636
+ }
2637
+ const childId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : '';
2638
+ const message = typeof args?.message === 'string' ? args.message.trim() : '';
2639
+ if (!childId) {
2640
+ return { ok: false, code: 'INVALID_SESSION', error: 'sessionId 必填:必须是本会话的直接子会话 ID' };
2641
+ }
2642
+ if (!message) {
2643
+ return { ok: false, code: 'INVALID_MESSAGE', error: 'message 必填:要发给子会话的说明' };
2644
+ }
2645
+ if (message.length > 4000) {
2646
+ return { ok: false, code: 'MESSAGE_TOO_LONG', error: 'message 过长(上限 4000 字符)' };
2647
+ }
2648
+ if (!spawnedChildIds(session).has(childId)) {
2649
+ return {
2650
+ ok: false,
2651
+ code: 'NOT_DIRECT_CHILD',
2652
+ error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递`,
2653
+ };
2654
+ }
2655
+ const service = ctx.subagents;
2656
+ if (!service || typeof service.sendMessage !== 'function') {
2657
+ return {
2658
+ ok: false,
2659
+ code: 'NO_SUBAGENT_SERVICE',
2660
+ error: '当前部署没有可用的 subagent 服务,无法投递 follow-up',
2661
+ };
2662
+ }
2663
+ try {
2664
+ const messageId = await service.sendMessage(agent, childId, [{ type: 'text', text: message }], { signal });
2665
+ return { ok: true, sessionId: childId, messageId: String(messageId ?? '') };
2666
+ }
2667
+ catch (error) {
2668
+ return {
2669
+ ok: false,
2670
+ code: 'DELIVERY_FAILED',
2671
+ sessionId: childId,
2672
+ error: truncate(error instanceof Error ? error.message : String(error), 500),
2673
+ };
2674
+ }
2675
+ }
2474
2676
  async function dispatchTool(agent, args, signal) {
2475
2677
  const session = agent?.session;
2476
2678
  if (!session)
@@ -2524,20 +2726,30 @@ export function createWorkplanRuntime(ctx, options = {}) {
2524
2726
  * is the user's stop signal; the only honest answer is a refusal that says
2525
2727
  * how to continue deliberately (a new plan, or the main Agent takes over).
2526
2728
  */
2527
- if (record.phase === 'cancelled' || record.cancelled === true) {
2729
+ if (isTerminalPhase(record.phase) || record.cancelled === true) {
2730
+ /*
2731
+ * [1.9.0] 终态集合:cancelled(用户撤销)与 superseded(责任已转移)
2732
+ * 都不允许派发、不允许复活。superseded 用独立拒绝码,便于调用方区分
2733
+ * 「用户叫停」与「已被别的计划承接」。cancelled 的返回体与 1.8.19 相同。
2734
+ */
2735
+ const superseded = record.phase === 'superseded';
2528
2736
  const snapshot = derivePlanSnapshot(record.statuses);
2529
2737
  return {
2530
2738
  ok: false,
2531
2739
  planId: record.plan.planId,
2532
- phase: 'cancelled',
2740
+ phase: superseded ? 'superseded' : 'cancelled',
2533
2741
  running: false,
2534
2742
  alreadyRunning: false,
2535
2743
  complete: false,
2536
2744
  remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
2537
2745
  stats: snapshot.stats,
2538
- code: 'PLAN_CANCELLED',
2539
- error: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2540
- hint: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2746
+ code: superseded ? 'PLAN_SUPERSEDED' : 'PLAN_CANCELLED',
2747
+ error: superseded
2748
+ ? '计划已被取代:不会再启动任何部门 Agent'
2749
+ : '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2750
+ hint: superseded
2751
+ ? '不要再次派发。被取代不等于完成:如需交付,请按覆盖链核对承接计划的证据;承接计划未就绪时不得调用 present。'
2752
+ : '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2541
2753
  };
2542
2754
  }
2543
2755
  /*
@@ -2753,11 +2965,20 @@ export function createWorkplanRuntime(ctx, options = {}) {
2753
2965
  const snapshot = derivePlanSnapshot(record.statuses);
2754
2966
  return deliveryReadiness(snapshot, { phase: record.phase });
2755
2967
  }
2756
- function stopGateApplies(record) {
2968
+ function stopGateApplies(record, session, turn) {
2757
2969
  if (!record?.plan)
2758
2970
  return false;
2759
2971
  if (record.degraded)
2760
2972
  return false;
2973
+ /*
2974
+ * [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
2975
+ * cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
2976
+ * superseded 不 steer:它的判定对象是承接计划,present 的拒绝文案已给出出路。
2977
+ */
2978
+ if (isTerminalPhase(record.phase)) {
2979
+ return record.phase === 'cancelled'
2980
+ && Boolean(session && turn && planIdFromTurn(session, turn) === record.plan.planId);
2981
+ }
2761
2982
  const readiness = recordReadiness(record);
2762
2983
  if (Number(readiness.total ?? 0) === 0)
2763
2984
  return false;
@@ -2986,7 +3207,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2986
3207
  if (record?.plan)
2987
3208
  state.records.set(session.id, record);
2988
3209
  }
2989
- if (!stopGateApplies(record))
3210
+ if (!stopGateApplies(record, session, turn))
2990
3211
  return;
2991
3212
  if (record.dispatchPromise) {
2992
3213
  try {
@@ -2996,7 +3217,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2996
3217
  /* the failure is already on record.errors; the gate only needs the outcome */
2997
3218
  }
2998
3219
  finishRound(record, session);
2999
- if (!stopGateApplies(record))
3220
+ if (!stopGateApplies(record, session, turn))
3000
3221
  return;
3001
3222
  }
3002
3223
  const book = record.stopSteers && record.stopSteers.turn === turn
@@ -3116,7 +3337,72 @@ export function createWorkplanRuntime(ctx, options = {}) {
3116
3337
  }
3117
3338
  return undefined;
3118
3339
  }
3119
- function presentDenialReason(agent) {
3340
+ /**
3341
+ * [1.9.0] 点名 superseded 时的覆盖链判定(T8 §4.2 第 4 条、§6.3)。
3342
+ *
3343
+ * superseded 只是「责任已转移」,不是完成:本回合点名它时,判的是承接计划
3344
+ * 是否真的就绪。承接计划缺失/已终止/无法复核 ⇒ fail-closed(SUPERSEDED_STALE);
3345
+ * 承接计划未就绪 ⇒ 拒绝;只有承接计划 deliveryReady 才放行(产物来自承接计划)。
3346
+ *
3347
+ * [1.9.2] 返回值带上拒绝码(T8 §4.3 `judgeEffective`):覆盖链无法复核
3348
+ * ⇒ `SUPERSEDED_STALE`;覆盖链有效但承接计划未就绪 ⇒ `ACTIVE_NOT_READY`。
3349
+ * 文案保持逐字不变,码值走 `src/plan.ts` 的同一组常量。
3350
+ */
3351
+ function supersededDenialVerdict(session, record) {
3352
+ const planId = record.plan?.planId ?? record.planId ?? '';
3353
+ const by = record.supersededBy;
3354
+ const successorPlanId = typeof by?.successorPlanId === 'string' && by.successorPlanId
3355
+ ? by.successorPlanId
3356
+ : typeof by?.planId === 'string' ? by.planId : '';
3357
+ if (!successorPlanId) {
3358
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但缺少可验证的承接计划(supersededBy.successorPlanId):`
3359
+ + '覆盖证据失效(SUPERSEDED_STALE),不得调用 present;请向用户说明覆盖链无法复核并重新确认交付对象。');
3360
+ }
3361
+ /*
3362
+ * [W1] 覆盖摘要:present 复验从 mapping 重算摘要,不读缓存数值(T8 §6.3)。
3363
+ *
3364
+ * 摘要一旦对不上(含 mapping/digest 缺失),覆盖记录就无法复核 —— 无法复核
3365
+ * ≠ 通过,一律 stale。这条检查只证明「存下来的 mapping 没被改动」,不证明
3366
+ * 「两项工作在语义上等价」;后者仍只能由用户确认(V8)承载。
3367
+ */
3368
+ const mapping = by?.mapping;
3369
+ if (!Array.isArray(mapping)) {
3370
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但缺少可复算的逐项映射(supersededBy.mapping):`
3371
+ + '覆盖证据失效(SUPERSEDED_STALE),不得调用 present,不得声称“已完成/最终版/已交付”;'
3372
+ + '请重新按用户确认的逐项映射做覆盖迁移,并由运行时写入复算后的 digest。');
3373
+ }
3374
+ const computedDigest = computeMappingDigest(mapping);
3375
+ if (!verifyMappingDigest(mapping, by?.digest)) {
3376
+ const stored = typeof by?.digest === 'string' ? by.digest.slice(0, 15) : '缺失';
3377
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但覆盖证据摘要与逐项映射不一致(supersededBy.digest=${stored},`
3378
+ + `重算=${computedDigest.slice(0, 15)}):覆盖证据失效(SUPERSEDED_STALE),不得调用 present,`
3379
+ + '不得声称“已完成/最终版/已交付”;请重新按用户确认的逐项映射做覆盖迁移,并由运行时复算 digest。');
3380
+ }
3381
+ const successor = reconstructFromSession(session, successorPlanId);
3382
+ if (!successor?.plan || definedSubtaskCount(successor.plan) === 0 || isTerminalPhase(successor.phase)) {
3383
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
3384
+ + '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。');
3385
+ }
3386
+ const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase });
3387
+ if (!readiness.ready) {
3388
+ const ids = readiness.remaining.slice(0, 10).join('、');
3389
+ return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY, `计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
3390
+ + `${ids ? `,剩余 ${readiness.remaining.length} 项(${ids})` : ''}。`
3391
+ + '被取代不等于完成:承接计划通过交付就绪检查之前不得调用 present。');
3392
+ }
3393
+ return undefined;
3394
+ }
3395
+ /**
3396
+ * [1.9.2] present 拒绝点的唯一出口:码值取常量,拒绝文案保持逐字不变。
3397
+ *
3398
+ * host 的 guard 契约是 `string`(`ctx.tools.checkGuards`),所以工具错误里
3399
+ * 仍只有文案;码值由 `presentDenialVerdict` 一并返回,供断言、日志与后续
3400
+ * UI 使用。所有分支都必须经由这里,不要在分支里手写码值。
3401
+ */
3402
+ function presentDenial(code, message) {
3403
+ return { code, message };
3404
+ }
3405
+ function presentDenialVerdict(agent) {
3120
3406
  const session = agent?.session;
3121
3407
  if (!session || !isRootSession(session))
3122
3408
  return undefined;
@@ -3169,7 +3455,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3169
3455
  * or the last defined plan after a restart) is about: cancel stops
3170
3456
  * execution, it does not make the work deliverable.
3171
3457
  */
3172
- .filter((entry) => entry.record.phase !== 'cancelled' && !entry.readiness.ready);
3458
+ .filter((entry) => !isTerminalPhase(entry.record.phase) && !entry.readiness.ready);
3173
3459
  if (unresolved.length > 1) {
3174
3460
  const lines = unresolved.slice(0, 6).map((entry) => {
3175
3461
  const ids = entry.readiness.remaining.slice(0, 6).join('、');
@@ -3178,10 +3464,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
3178
3464
  return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
3179
3465
  + `${gaps ? `;证据缺口:${gaps}` : ''}`;
3180
3466
  });
3181
- return `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3467
+ return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY, `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3182
3468
  + '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
3183
3469
  + '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
3184
- + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。';
3470
+ + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。');
3185
3471
  }
3186
3472
  let record;
3187
3473
  let readiness;
@@ -3207,11 +3493,26 @@ export function createWorkplanRuntime(ctx, options = {}) {
3207
3493
  return undefined;
3208
3494
  if (definedSubtaskCount(record.plan) === 0)
3209
3495
  return undefined;
3496
+ /*
3497
+ * [1.9.0] 终态解耦(T8 §4.3 P3):终态计划不再被自动选为判定对象。
3498
+ *
3499
+ * 只有「本回合结构化点名」时才判定;否则不再写回 live、不再拦截其它
3500
+ * 计划的交付。取消 ≠ 完成:记录仍是 cancelled 0/N,只是不再永久挡门。
3501
+ */
3502
+ const namedThisTurn = Boolean(turnPlanId && record.plan.planId === turnPlanId);
3503
+ if (isTerminalPhase(record.phase) && !namedThisTurn)
3504
+ return undefined;
3505
+ if (record.phase === 'superseded') {
3506
+ const denial = supersededDenialVerdict(session, record);
3507
+ if (denial)
3508
+ return denial;
3509
+ return undefined;
3510
+ }
3210
3511
  readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase });
3211
3512
  if (readiness.ready)
3212
3513
  return undefined;
3213
3514
  }
3214
- if (record?.plan)
3515
+ if (record?.plan && !isTerminalPhase(record.phase))
3215
3516
  state.records.set(session.id, record);
3216
3517
  const snapshot = derivePlanSnapshot(record.statuses);
3217
3518
  const planId = record.plan?.planId ?? record.planId;
@@ -3229,26 +3530,39 @@ export function createWorkplanRuntime(ctx, options = {}) {
3229
3530
  .slice(0, 10)
3230
3531
  .join(';');
3231
3532
  if (readiness.remaining.length === 0) {
3232
- return `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3533
+ return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED, `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3233
3534
  + '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
3234
- + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。';
3535
+ + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。');
3235
3536
  }
3236
- return `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3537
+ return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED, `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3237
3538
  + `${gaps ? `;证据缺口:${gaps}` : ''}。`
3238
3539
  + '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
3239
- + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。';
3540
+ + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。');
3240
3541
  }
3542
+ /*
3543
+ * [1.9.2] P1 的单一映射:`activeDenyCode` 只看就绪结果。
3544
+ * `remaining` 为空但 `blockers` 非空 ⇒ `EVIDENCE_GAP`(T9 C05 的修法);
3545
+ * 还有子任务没做完 ⇒ `ACTIVE_NOT_READY`。两个分支共用同一个码值来源。
3546
+ */
3547
+ const activeCode = activeDenyCode(readiness);
3241
3548
  if (readiness.remaining.length === 0) {
3242
- return `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3549
+ return presentDenial(activeCode, `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3243
3550
  + '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
3244
3551
  + "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
3245
- + '或把对应子任务改回 blocked 并写明原因;不要调用 present。';
3552
+ + '或把对应子任务改回 blocked 并写明原因;不要调用 present。');
3246
3553
  }
3247
- return `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3554
+ return presentDenial(activeCode, `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3248
3555
  + `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
3249
3556
  + '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
3250
3557
  + '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
3251
- + '取消只停止执行,不会改变“未完成”的结论。';
3558
+ + '取消只停止执行,不会改变“未完成”的结论。');
3559
+ }
3560
+ /**
3561
+ * 兼容入口:host 的 guard 只接受字符串,所以工具错误仍是原来的文案。
3562
+ * 需要码值时调用 `presentDenialVerdict`。
3563
+ */
3564
+ function presentDenialReason(agent) {
3565
+ return presentDenialVerdict(agent)?.message;
3252
3566
  }
3253
3567
  /*
3254
3568
  * [1.8.18] 已交付文件的写保护(T7-N2)。
@@ -3341,7 +3655,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3341
3655
  const unresolved = [...planIds]
3342
3656
  .map((planId) => recordForPlan(session, planId))
3343
3657
  .filter((record) => record?.plan
3344
- && record.phase !== 'cancelled'
3658
+ && !isTerminalPhase(record.phase)
3345
3659
  && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready);
3346
3660
  if (unresolved.length === 0)
3347
3661
  return undefined;
@@ -3439,11 +3753,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
3439
3753
  onPreStep,
3440
3754
  onTurnStopping,
3441
3755
  presentDenialReason,
3756
+ presentDenialVerdict,
3757
+ supersededDenialVerdict,
3442
3758
  presentedWriteDenialReason,
3443
3759
  updateStatus,
3444
3760
  cancelPlan,
3445
3761
  dispatchTool,
3446
3762
  statusTool,
3763
+ followupTool,
3447
3764
  plansPayload,
3448
3765
  route,
3449
3766
  dispose,
@@ -3524,7 +3841,13 @@ async function maybePlan(ctx, state, payload, downstream, options) {
3524
3841
  // A plan committed but not yet dispatched must not be overwritten in the
3525
3842
  // same turn; a later turn may supersede it, otherwise one abandoned plan
3526
3843
  // would lock planning forever.
3527
- if (existing?.plan && !existing.dispatchedAt) {
3844
+ //
3845
+ // [1.9.2] 自动覆盖路径**只允许**写 cancelled,永不写 superseded(规则设计
3846
+ // §7.1:自动路径没有逐项映射与用户确认,满足不了 V4–V8)。它也不得把已经
3847
+ // superseded 的终态记录改回 cancelled:内存写 cancelled、日志里仍是
3848
+ // supersede 信封,会让 live 与 replay 分叉。终态记录由 present 的终态解耦
3849
+ // 处理(不再自动挡门),不需要在这里「取消」。
3850
+ if (existing?.plan && !existing.dispatchedAt && !isTerminalPhase(existing.phase)) {
3528
3851
  if (existing.plan.createdTurn === payload.turn)
3529
3852
  return downstream;
3530
3853
  existing.phase = 'cancelled';
@@ -3714,6 +4037,36 @@ export function cancelToolOutputSchema() {
3714
4037
  cancelRecorded: { type: 'boolean' },
3715
4038
  alreadyCancelled: { type: 'boolean' },
3716
4039
  abortedRunning: { type: 'boolean' },
4040
+ /*
4041
+ * [1.9.2] `disposition="superseded"` answers. `supersedeRecorded` is the
4042
+ * durable-write witness for the supersede envelope (the cancelled answer
4043
+ * uses `cancelRecorded`); `alreadySuperseded` is the §7.4 idempotent
4044
+ * re-submission. `code` carries the SUPERSEDE_* refusal; `gaps` /
4045
+ * `missingFrom` / `problems` explain exactly which V-rule failed so a
4046
+ * caller can repair the mapping instead of guessing.
4047
+ */
4048
+ disposition: { type: 'string' },
4049
+ supersededAt: { type: 'number' },
4050
+ supersedeRecorded: { type: 'boolean' },
4051
+ alreadySuperseded: { type: 'boolean' },
4052
+ coverage: { type: 'string' },
4053
+ requiredCount: { type: 'number' },
4054
+ coveredCount: { type: 'number' },
4055
+ successorSeenAtSeq: { type: 'number' },
4056
+ confirmedAtSeq: { type: 'number' },
4057
+ supersededBy: {
4058
+ type: 'object',
4059
+ properties: {
4060
+ planId: { type: 'string' },
4061
+ },
4062
+ additionalProperties: true,
4063
+ },
4064
+ code: { type: 'string' },
4065
+ error: { type: 'string' },
4066
+ hint: { type: 'string' },
4067
+ gaps: { type: 'array', items: { type: 'string' } },
4068
+ missingFrom: { type: 'array', items: { type: 'string' } },
4069
+ problems: { type: 'array', items: { type: 'string' } },
3717
4070
  },
3718
4071
  required: ['ok'],
3719
4072
  additionalProperties: true,