dsh-workplan 1.8.3 → 1.8.18

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
@@ -28,7 +28,9 @@ import {
28
28
  buildPlanMessage,
29
29
  buildPlannerPrompt,
30
30
  buildResultMessage,
31
+ buildStopSteerText,
31
32
  createStatuses,
33
+ deliveryReadiness,
32
34
  derivePlanSnapshot,
33
35
  extractJson,
34
36
  flattenSubtasks,
@@ -36,6 +38,7 @@ import {
36
38
  isSocialMessage,
37
39
  isStatusQuestion,
38
40
  isVagueContinuation,
41
+ makeUserMessage,
39
42
  markDependentsBlocked,
40
43
  messageText,
41
44
  readySubtasks,
@@ -57,6 +60,28 @@ import {
57
60
  } from './plan.js'
58
61
  import { createProgressWatchdog, describeError } from './watchdog.js'
59
62
 
63
+ /**
64
+ * [1.8.18] How many subtasks the plan *defines*.
65
+ *
66
+ * `deliveryReadiness` counts the derived statuses, and `ready` requires
67
+ * `total > 0`, so a plan with `stages: []` can never be ready. Such a plan is
68
+ * not a delivery object at all: normal planning rejects it (`validatePlan`),
69
+ * and it can only reach replay from a malformed historical message. Judging it
70
+ * as "0/0 unfinished forever" was U6 (T5 P13): present was refused with the
71
+ * false copy "0 个子任务虽都已 done".
72
+ *
73
+ * A malformed plan that reaches this function still counts as deliverable
74
+ * (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
75
+ * `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
76
+ */
77
+ function definedSubtaskCount(plan: any): number {
78
+ try {
79
+ return flattenSubtasks(plan).length
80
+ } catch {
81
+ return Number.MAX_SAFE_INTEGER
82
+ }
83
+ }
84
+
60
85
  export const PLANNER_TIMEOUT_MS = 120000
61
86
  /**
62
87
  * Absolute ceiling for one child execution.
@@ -320,7 +345,7 @@ async function disposeActivation(activation: any, record: any, subtaskId: string
320
345
  } catch (error: any) {
321
346
  if (!guard?.timedOut) {
322
347
  record.errors = [
323
- ...record.errors,
348
+ ...(record.errors ?? []),
324
349
  `${subtaskId} dispose: ${truncate(String(error?.message ?? error), 300)}`,
325
350
  ].slice(-20)
326
351
  }
@@ -375,7 +400,7 @@ function writeSubtaskStatus(record: any, subtaskId: any, patch: any, guard: Subt
375
400
 
376
401
  function recordSubtaskError(record: any, subtaskId: any, message: any, guard: SubtaskGuard) {
377
402
  if (guard.timedOut) return
378
- record.errors = [...record.errors, `${subtaskId}: ${truncate(message, 500)}`].slice(-20)
403
+ record.errors = [...(record.errors ?? []), `${subtaskId}: ${truncate(message, 500)}`].slice(-20)
379
404
  }
380
405
 
381
406
  /**
@@ -418,6 +443,76 @@ export function checkArtifacts(artifacts: any, cwd: any, artifactExists: any = e
418
443
  return { artifacts: checked, missingArtifacts }
419
444
  }
420
445
 
446
+ /**
447
+ * [1.8.5] 被中断时,先说清「东西到底写出来没有」。
448
+ *
449
+ * 事故(2026-10-30):一个子 Agent 在 21:34:52 写完了 38KB 交付物,两秒后被
450
+ * 外部中断;插件只留下「结束状态为 aborted」,产物存在与否完全不进判定,主
451
+ * Agent 只能把它当彻底失败,下游 6 个任务跟着停摆。
452
+ *
453
+ * 这里不改变任何判定语义(中断依然记为失败、依然不自动重试),只在报错里
454
+ * 附上一句可核实的事实:该步声明的产物里有哪几个已经在盘上。看到这句话的人
455
+ * 才知道下一步该去核对、改判,而不是白等一次重试。
456
+ */
457
+ export function probeInterruptedArtifacts(output: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
458
+ const candidates = new Set<string>()
459
+ const collect = (text: any) => {
460
+ if (typeof text !== 'string' || !text) return
461
+ // 文件名可能带中文(本次事故就是「T6_人性博弈推演_20261030.md」这种),
462
+ // 所以字符集必须放行 CJK,否则真正的产物会被当成没写。
463
+ for (const hit of text.matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
464
+ const ref = hit[0].replace(/^\.\//, '')
465
+ // 太短的多半是扩展名碎片(如 “.md”),不足以定位文件。
466
+ if (ref.length > 3) candidates.add(ref)
467
+ }
468
+ }
469
+ collect(output)
470
+ for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : []) collect(item)
471
+ const landed: string[] = []
472
+ for (const ref of candidates) {
473
+ const target = resolveArtifactPath(ref, cwd)
474
+ if (!target) continue
475
+ let exists = false
476
+ try {
477
+ exists = artifactExists(target) === true
478
+ } catch {
479
+ exists = false
480
+ }
481
+ if (exists) landed.push(ref)
482
+ if (landed.length >= 6) break
483
+ }
484
+ return landed
485
+ }
486
+
487
+ /**
488
+ * [1.8.6] Turn "the child was interrupted" into evidence the plan can hold.
489
+ *
490
+ * 1.8.5 only put the landed files into the error string. That helped a human
491
+ * read the message, but the plan still recorded `blocked` with no
492
+ * `artifacts` / `missingArtifacts`, so the dispatcher had nothing to check and
493
+ * cascaded every dependent into `blocked`: one interrupted child still killed
494
+ * its whole downstream. This records the same finding in the status fields the
495
+ * scheduler already understands.
496
+ *
497
+ * It deliberately does NOT change the verdict: an interrupted task stays
498
+ * `blocked` (no auto-retry, no auto-adjudication). It only stops the cascade
499
+ * and leaves the main Agent a factual basis to re-adjudicate.
500
+ */
501
+ export function probeInterruptedEvidence(output: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
502
+ const landed = probeInterruptedArtifacts(output, subtask, cwd, artifactExists)
503
+ const declared: string[] = []
504
+ for (const item of Array.isArray(subtask?.outputs) ? subtask.outputs : []) {
505
+ for (const hit of String(item).matchAll(/[\w\u4e00-\u9fff@.\/-]+\.(?:md|csv|json|html|txt|ts|js|py|ya?ml)/g)) {
506
+ const ref = hit[0].replace(/^\.\//, '')
507
+ if (ref.length > 3 && !declared.includes(ref)) declared.push(ref)
508
+ }
509
+ }
510
+ const refs = [...new Set([...declared, ...landed])]
511
+ const artifacts = refs.map((ref) => ({ kind: 'file', ref, exists: landed.includes(ref) }))
512
+ const missingArtifacts = declared.filter((ref) => !landed.includes(ref))
513
+ return { artifacts, missingArtifacts }
514
+ }
515
+
421
516
  /**
422
517
  * Turn one child output into a status verdict.
423
518
  *
@@ -473,6 +568,15 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
473
568
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
474
569
  let lastError: any = null
475
570
  let lastFailure: any = null
571
+ /*
572
+ * [1.8.6] The interrupt has to outlive the thrown error.
573
+ *
574
+ * `interruptedFlag` travels back to the dispatcher (it must not cascade this
575
+ * task's dependents); `interruptedEvidence` is what gets written into the
576
+ * blocked status so the main Agent can re-adjudicate on facts.
577
+ */
578
+ let interruptedFlag = false
579
+ let interruptedEvidence: { artifacts: any[]; missingArtifacts: string[] } | null = null
476
580
  try {
477
581
  if (!writeSubtaskStatus(record, subtask.id, {
478
582
  status: 'in_progress',
@@ -482,6 +586,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
482
586
 
483
587
  for (let attempt = 1; attempt <= 2; attempt += 1) {
484
588
  if (guard.timedOut) return
589
+ interruptedEvidence = null
485
590
  if (parentSignal.aborted) throw abortError()
486
591
  if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
487
592
  let activation: any = null
@@ -576,8 +681,30 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
576
681
  if (guard.timedOut) return
577
682
  const output = resultText(result)
578
683
  if (result.stopReason !== 'completed') {
684
+ /*
685
+ * [1.8.5] 中断必须自己说出「接下来怎么办」。
686
+ *
687
+ * 2026-10-30 事故:T6 在被外部中断前 2 秒已写出 38KB 交付物,插件只留下
688
+ * 「子 Agent 结束状态为 aborted」,主 Agent 无从知道产物其实已经在盘上,
689
+ * 于是把它当彻底失败处理,并把 6 个下游一起判死。中断类失败要显式提示
690
+ * 「先核对已写出的产物」,并给出据实改判与续跑这两条出口。
691
+ */
692
+ const interrupted = result.stopReason === 'aborted'
693
+ const landed = interrupted ? probeInterruptedArtifacts(output, subtask, options.cwd, options.artifactExists) : []
694
+ if (interrupted) {
695
+ interruptedFlag = true
696
+ interruptedEvidence = probeInterruptedEvidence(output, subtask, options.cwd, options.artifactExists)
697
+ }
579
698
  throw new PlanError(
580
- `子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}`,
699
+ `子 Agent 结束状态为 ${result.stopReason}${result.diagnostic ? `:${result.diagnostic}` : ''}${
700
+ interrupted
701
+ ? `(子 Agent 在完成前被中断:先核对该步声明的产物是否已写出${
702
+ landed.length > 0
703
+ ? `——已核到 ${landed.length} 个文件确实在盘上:${landed.join('、')}`
704
+ : ''
705
+ };据实改判,再决定是否续跑)`
706
+ : ''
707
+ }`,
581
708
  'CHILD_NOT_COMPLETED',
582
709
  )
583
710
  }
@@ -615,7 +742,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
615
742
  const retry = !isAbort && shouldRetryAttempt(error, attempt, remaining, idleTimeoutMs)
616
743
  if (retry) {
617
744
  record.errors = [
618
- ...record.errors,
745
+ ...(record.errors ?? []),
619
746
  `${subtask.id}: 第 ${attempt} 次执行失败(${lastFailure.code}),已带上失败原因重试`,
620
747
  ].slice(-20)
621
748
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
@@ -623,7 +750,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
623
750
  }
624
751
  if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
625
752
  record.errors = [
626
- ...record.errors,
753
+ ...(record.errors ?? []),
627
754
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
628
755
  ].slice(-20)
629
756
  }
@@ -643,8 +770,18 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
643
770
  finishedAt: Date.now(),
644
771
  error: truncate(message, 2000),
645
772
  summary: truncate(`未完成:${message}`, 3000),
773
+ // [1.8.6] A blocked status that carries no evidence is what made the
774
+ // dispatcher treat "interrupted, file on disk" exactly like "produced
775
+ // nothing". Record what was actually found.
776
+ ...(interruptedEvidence && interruptedEvidence.artifacts.length > 0
777
+ ? { artifacts: interruptedEvidence.artifacts }
778
+ : {}),
779
+ ...(interruptedEvidence && interruptedEvidence.missingArtifacts.length > 0
780
+ ? { missingArtifacts: interruptedEvidence.missingArtifacts }
781
+ : {}),
646
782
  }, guard)
647
783
  recordSubtaskError(record, subtask.id, message, guard)
784
+ return interruptedFlag ? { interrupted: true } : undefined
648
785
  } catch (error) {
649
786
  const message = describeError(error)
650
787
  try {
@@ -692,11 +829,11 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
692
829
  error: message,
693
830
  summary: truncate(`未完成:${message}`, 3000),
694
831
  })
695
- record.errors = [...record.errors, `${subtask.id}: ${message}`].slice(-20)
832
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${message}`].slice(-20)
696
833
  record.updatedAt = Date.now()
697
834
  } catch (error: any) {
698
835
  record.errors = [
699
- ...record.errors,
836
+ ...(record.errors ?? []),
700
837
  `${subtask.id}: 超时状态写入失败:${truncate(String(error?.message ?? error), 500)}`,
701
838
  ].slice(-20)
702
839
  } finally {
@@ -710,7 +847,9 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
710
847
  timer.unref?.()
711
848
  })
712
849
  try {
713
- await Promise.race([
850
+ // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
851
+ // swallowing it here is why an interrupted child looked like any failure.
852
+ return await Promise.race([
714
853
  executeSubtask(ctx, record, stage, subtask, {
715
854
  ...options,
716
855
  child,
@@ -772,6 +911,15 @@ export function modelStatusLines(statuses: any) {
772
911
  summary: truncate(item.summary ?? item.error ?? '', 2000),
773
912
  error: item.error ?? null,
774
913
  verification: item.verification ?? null,
914
+ // [1.8.13] The model must see *which* acceptance item failed, not just the
915
+ // verdict; it cannot repair a gap it cannot name.
916
+ acceptance: Array.isArray(item.acceptance)
917
+ ? item.acceptance.slice(0, 8).map((entry: any) => ({
918
+ criterion: truncate(String(entry?.criterion ?? ''), 200),
919
+ result: String(entry?.result ?? ''),
920
+ evidence: truncate(String(entry?.evidence ?? ''), 300),
921
+ }))
922
+ : [],
775
923
  revision: Number(item.revision ?? 0),
776
924
  updatedBy: item.updatedBy ?? null,
777
925
  missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
@@ -796,6 +944,42 @@ export function buildRoundResult(record: any, sessionId: any, limits: any) {
796
944
  })
797
945
  }
798
946
 
947
+ /**
948
+ * [1.8.6] Explain why a `pending` task cannot run, instead of calling it blocked.
949
+ *
950
+ * A single generic sentence made three different situations indistinguishable:
951
+ * a budget pause (nothing ran yet), an upstream whose declared file is missing
952
+ * (the work may well be done), and a genuinely failed upstream. The main Agent
953
+ * read all three as "7 卡住了" and had to re-derive the cause by hand.
954
+ */
955
+ function describePendingCause(plan: any, statuses: any[], id: string): string {
956
+ const byId = new Map<string, any>(statuses.map((item: any) => [item.subtaskId, item]))
957
+ const entry = flattenSubtasks(plan).find((candidate: any) => candidate.subtask.id === id)
958
+ if (!entry) return '计划里找不到该步骤'
959
+ const declared: string[] = Array.isArray(entry.subtask.dependsOn) ? entry.subtask.dependsOn : []
960
+ if (declared.length === 0) return '没有上游依赖,但本轮未被调度到'
961
+ const bad = declared.filter((dep: string) => {
962
+ const state = byId.get(dep)
963
+ if (!state || state.status !== 'done') return true
964
+ if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0) return true
965
+ if (state.verification === 'legacy') return true
966
+ return false
967
+ })
968
+ if (bad.length === 0) return '上游都已就绪,但本轮未被调度到'
969
+ return bad.map((dep: string) => {
970
+ const state = byId.get(dep)
971
+ if (!state) return `上游 ${dep} 缺失`
972
+ if (state.status !== 'done') {
973
+ return `上游 ${dep} 状态为 ${state.status}${state.error ? `(${String(state.error).slice(0, 80)})` : ''}`
974
+ }
975
+ if (Array.isArray(state.missingArtifacts) && state.missingArtifacts.length > 0) {
976
+ return `上游 ${dep} 的声明产物缺失:${state.missingArtifacts.join('、')}`
977
+ }
978
+ if (state.verification === 'legacy') return `上游 ${dep} 完成但未提供结构化证据`
979
+ return `上游 ${dep} 不可用`
980
+ }).join(';')
981
+ }
982
+
799
983
  export async function dispatchPlan(ctx: any, record: any, options: any) {
800
984
  const { agent, signal, modelSelection, cwd, conversationContext = '' } = options
801
985
  const deadline = Date.now() + (options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS)
@@ -847,6 +1031,16 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
847
1031
  record.updatedAt = record.dispatchedAt
848
1032
  try {
849
1033
  let guard = 0
1034
+ /*
1035
+ * [1.8.6] Interrupted tasks are not cascaded.
1036
+ *
1037
+ * The 2026-10-30 incident: one child was interrupted after it had already
1038
+ * written its deliverable; the dispatcher blocked its 6 dependents. Those
1039
+ * children were never given a chance, and the plan looked like a 7-task
1040
+ * failure. Keep the interrupted task itself `blocked` (its verdict must not
1041
+ * be rewritten automatically), but leave dependents `pending` and say why.
1042
+ */
1043
+ const interruptedIds = new Set<string>()
850
1044
  while (true) {
851
1045
  guard += 1
852
1046
  if (guard > 200) throw new PlanError('调度次数异常', 'DISPATCH_LOOP')
@@ -865,12 +1059,23 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
865
1059
  }
866
1060
  : {})
867
1061
  if (ready.length === 0) {
1062
+ /*
1063
+ * [1.8.6] "Nothing is ready" is not the same thing as "everything
1064
+ * failed".
1065
+ *
1066
+ * The old code rewrote every remaining `pending` task to `blocked` with
1067
+ * one generic line ("依赖未完成或上游受阻"). A budget pause, a missing
1068
+ * artifact and a genuinely failed upstream all produced that same
1069
+ * status, the plan turned `blocked`, and a resume was billed against
1070
+ * the failure budget. Keep them `pending`, and record the actual cause.
1071
+ */
868
1072
  const pending = record.statuses.filter((item: any) => item.status === 'pending')
869
- for (const item of pending) {
870
- record.statuses = applyStatus(record.statuses, item.subtaskId, {
871
- status: 'blocked',
872
- error: '依赖未完成或上游受阻',
873
- })
1073
+ if (pending.length > 0) {
1074
+ const reasons = pending.map((item: any) =>
1075
+ `${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`)
1076
+ const message = `本轮结束,仍有 ${pending.length} 项保持 pending(不是失败,也未级联成 blocked):${reasons.slice(0, 6).join(';')}`
1077
+ record.error = message
1078
+ record.errors = [...(record.errors ?? []), message].slice(-20)
874
1079
  }
875
1080
  break
876
1081
  }
@@ -881,7 +1086,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
881
1086
  const entry = flattenSubtasks(record.plan)
882
1087
  .find((candidate: any) => candidate.subtask.id === item.id)
883
1088
  if (!entry) return
884
- await runSubtask(ctx, record, entry.stage, entry.subtask, {
1089
+ const outcome: any = await runSubtask(ctx, record, entry.stage, entry.subtask, {
885
1090
  agent,
886
1091
  parentSignal: childController.signal,
887
1092
  deadline,
@@ -893,6 +1098,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
893
1098
  strictEvidence: options.strictEvidence,
894
1099
  artifactExists: options.artifactExists,
895
1100
  })
1101
+ // [1.8.6] Remember which failures were interrupts, so the cascade below
1102
+ // can leave their dependents pending instead of blaming them.
1103
+ if (outcome && outcome.interrupted) interruptedIds.add(item.id)
896
1104
  })
897
1105
  const blocked = record.statuses
898
1106
  .filter((item: any) => item.status === 'blocked')
@@ -904,6 +1112,19 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
904
1112
  * had to re-read the whole plan to guess what to repair.
905
1113
  */
906
1114
  const upstream = record.statuses.find((item: any) => item.subtaskId === id)
1115
+ /*
1116
+ * [1.8.6] An interrupted task blocked itself, not its dependents.
1117
+ *
1118
+ * Recording the interruption in `errors` (instead of silently skipping)
1119
+ * keeps the reason visible in the result message, and `continue` leaves
1120
+ * the dependents `pending` so a re-dispatch can still run them once the
1121
+ * main Agent re-adjudicates the interrupted step.
1122
+ */
1123
+ if (interruptedIds.has(id)) {
1124
+ record.errors = [...(record.errors ?? []),
1125
+ `${id}: 被中断但产物已核对(见 artifacts),未自动级联下游;请据实改判或续跑`].slice(-20)
1126
+ continue
1127
+ }
907
1128
  const cause = upstream
908
1129
  ? {
909
1130
  reason: upstream.error,
@@ -918,7 +1139,17 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
918
1139
  */
919
1140
  record.updatedAt = Date.now()
920
1141
  }
921
- record.phase = planPhase(record.statuses)
1142
+ /*
1143
+ * [1.8.6] Do not let a pending tail masquerade as a failure.
1144
+ *
1145
+ * `planPhase` turns any `blocked` row into `blocked`; with D8's fix a round
1146
+ * can end with real blocked rows *and* untouched pending rows. Keep
1147
+ * `blocked` for real failures, and report `paused` when only pending work
1148
+ * is left, so a resume is not billed against the failure budget.
1149
+ */
1150
+ const hasBlocked = record.statuses.some((item: any) => item.status === 'blocked')
1151
+ const hasPending = record.statuses.some((item: any) => item.status === 'pending')
1152
+ record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses))
922
1153
  } catch (error) {
923
1154
  const message = describeError(error)
924
1155
  pushRecordError(record, error)
@@ -977,7 +1208,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
977
1208
  * report for subtasks that were explicitly *not* failures.
978
1209
  */
979
1210
  record.errors = (record.errors ?? []).filter((line: string) => !/总执行超时/.test(String(line)))
980
- if (!allDoneNow) record.errors = [...record.errors, record.error].slice(-20)
1211
+ if (!allDoneNow) record.errors = [...(record.errors ?? []), record.error].slice(-20)
981
1212
  } else {
982
1213
  /*
983
1214
  * `blocked` is a terminal state, so it always reports progress 100 — the
@@ -1060,8 +1291,49 @@ export function sessionTurnState(session: any) {
1060
1291
  return { state: 'unknown', reason: null, reasonDetail: null, at: null }
1061
1292
  }
1062
1293
 
1294
+ /*
1295
+ * [1.8.4] 回合已经结束 ⇒ 没有任何子任务还可能在跑。
1296
+ *
1297
+ * `turn/end` 之后仍残留 `in_progress` 只有两种来源:派发被进程退出/崩溃打断,
1298
+ * 或者某次状态写入没有配对收尾。无论哪种,把「正在做」原样留在载荷里都会让同一张
1299
+ * 卡片同时说出「已结束」和「正在做」(本次事故截图的第二处矛盾:卡片已经在
1300
+ * 「已结束」组里,第 4 步却写着「正在做」)。这里把这些条目改判为 `blocked`
1301
+ * (=需要人来续跑),保留原进度与已有错误说明,只在没有说明时补一句人话。
1302
+ *
1303
+ * 不引入 `Date.now()`:回放路径必须与实时路径给出同一结论,所以这份载荷
1304
+ * 只依赖输入数组,不依赖当前时间。
1305
+ */
1306
+ const STALE_INFLIGHT_NOTE = '本轮结束时这一步仍未完成,没有拿到结果;可以续跑。'
1307
+ function settleStaleInflight(raw: any): any {
1308
+ const list = Array.isArray(raw) ? raw : []
1309
+ if (!list.some((item: any) => item?.status === 'in_progress')) return raw
1310
+ return list.map((item: any) =>
1311
+ item?.status === 'in_progress'
1312
+ ? {
1313
+ ...item,
1314
+ status: 'blocked',
1315
+ error: typeof item.error === 'string' && item.error.trim() !== '' ? item.error : STALE_INFLIGHT_NOTE,
1316
+ }
1317
+ : item
1318
+ )
1319
+ }
1320
+
1063
1321
  function serialisePlan(record: any, session: any) {
1064
1322
  const plan = record.plan ?? null
1323
+ /*
1324
+ * [1.8.4] 先问「此刻还有没有东西在跑」,再决定这份载荷允不允许宣告结束。
1325
+ *
1326
+ * `record.dispatchPromise` 是插件内部唯一的权威存活信号:派发时赋值,
1327
+ * `.finally()` 里置空(见 dispatchTool)。1.7.0 引入 async 派发后,宿主会在
1328
+ * 派发真正结束**之前**就写下 `turn/end`:事故截图里 20:06:33 卡片已经
1329
+ * 「已结束」,而同一计划的派发一直跑到 20:22:50 才写入结果消息。也就是说
1330
+ * 「回合结束」不等于「没有东西在跑」——把前者当成结束证据,就是本次
1331
+ * 「已结束 ∧ 正在做」的根因。存活信号在这里读一次,下面所有「收敛为 ended」
1332
+ * 的判断都必须经过它。
1333
+ */
1334
+ const liveDispatch = Boolean(record.dispatchPromise)
1335
+ const turn = liveDispatch ? null : sessionTurnState(session)
1336
+ const turnEnded = turn?.state === 'ended'
1065
1337
  /*
1066
1338
  * Counts are derived here, once, from the very array that is shipped.
1067
1339
  *
@@ -1071,13 +1343,13 @@ function serialisePlan(record: any, session: any) {
1071
1343
  * built from `statuses` said otherwise. Deriving both from one normalised
1072
1344
  * snapshot makes that contradiction structurally impossible.
1073
1345
  */
1074
- const snapshot = derivePlanSnapshot(
1346
+ const rawStatuses =
1075
1347
  Array.isArray(record.statuses) && record.statuses.length > 0
1076
1348
  ? record.statuses
1077
1349
  : plan
1078
1350
  ? createStatuses(plan)
1079
1351
  : []
1080
- )
1352
+ const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses)
1081
1353
  const statuses = snapshot.statuses
1082
1354
  const stats = snapshot.stats
1083
1355
  /*
@@ -1107,27 +1379,29 @@ function serialisePlan(record: any, session: any) {
1107
1379
  * 重新开始(日志里出现新的 turn/start),下一份 payload 自然回到原来的
1108
1380
  * 派发状态,不需要任何反向迁移逻辑;
1109
1381
  * - 实时路径与回放路径都经过本函数,因此刷新前后结论必然一致(T4 硬约束)。
1382
+ *
1383
+ * [1.8.4] 前置门:只有 `turnEnded && !liveDispatch` 才准许收敛。存活信号为真时
1384
+ * 「回合已结束」仅仅说明宿主本轮不再收新消息,派发仍在跑,卡片必须继续显示
1385
+ * 真实阶段(正在做 / 预算用完),不许降级成 ended。
1110
1386
  */
1111
1387
  let suspendedPhase: any = null
1112
1388
  let endReason: any = null
1113
1389
  let endReasonDetail: any = null
1114
1390
  let endedAt: any = null
1115
- if (phase !== 'done' && phase !== 'cancelled') {
1116
- const turn = sessionTurnState(session)
1117
- if (turn.state === 'ended') {
1118
- suspendedPhase = phase
1119
- endReason = turn.reason
1120
- endReasonDetail = turn.reasonDetail
1121
- endedAt = turn.at
1122
- phase = 'ended'
1123
- }
1391
+ if (turnEnded && phase !== 'done' && phase !== 'cancelled') {
1392
+ suspendedPhase = phase
1393
+ endReason = turn.reason
1394
+ endReasonDetail = turn.reasonDetail
1395
+ endedAt = turn.at
1396
+ phase = 'ended'
1124
1397
  }
1125
1398
  /*
1126
- * 每次真正下发前跑一遍跨字段不变量(I1–I10)。正常情况下恒为空;一旦某个
1399
+ * 每次真正下发前跑一遍跨字段不变量(I1–I11)。正常情况下恒为空;一旦某个
1127
1400
  * 未来改动重新引入「进度与状态打架」,这里会把它连同具体字段值一起带出去,
1128
1401
  * 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
1129
1402
  */
1130
1403
  const violations = aggregateInvariantViolations(snapshot, phase)
1404
+ const readiness = deliveryReadiness(snapshot, { phase: record.phase })
1131
1405
  return {
1132
1406
  sessionId: session.id,
1133
1407
  planId: record.planId ?? plan?.planId ?? null,
@@ -1144,12 +1418,32 @@ function serialisePlan(record: any, session: any) {
1144
1418
  plan,
1145
1419
  statuses,
1146
1420
  stats,
1421
+ /*
1422
+ * [1.8.13] Delivery readiness travels with the dashboard payload too.
1423
+ *
1424
+ * `phase` alone cannot express "all rows done but evidence missing, or a
1425
+ * cancelled plan is still incomplete"; a green 100% card next to a denied
1426
+ * present is exactly the contradiction this incident exposed. The UI can
1427
+ * now show the same verdict the gate uses.
1428
+ */
1429
+ deliveryReady: readiness.ready,
1430
+ deliveryBlockers: readiness.blockers.slice(0, 12),
1431
+ deliveryRemaining: readiness.remaining.slice(0, 20),
1147
1432
  /*
1148
1433
  * Liveness and resume bookkeeping. Without these the dashboard could not
1149
1434
  * tell a slow-but-alive child from a wedged one, and the model could not
1150
1435
  * tell whether dispatch would actually run anything.
1151
1436
  */
1152
1437
  heartbeatAt: record.heartbeatAt ?? null,
1438
+ /*
1439
+ * [1.8.4] 存活事实跟着载荷一起下发。
1440
+ *
1441
+ * 之前只有模型侧 tool 结果带 `running`,面板拿不到,只能靠 `phase` 猜
1442
+ * 「有没有东西在跑」;而 phase 既可能滞后(派发已结束、状态没回写),
1443
+ * 也可能过早(回合结束、派发还在跑)。把存活信号原样交给展示层,
1444
+ * 「已结束」与「正在做」就不可能再从两条互不知情的数据里各说各话。
1445
+ */
1446
+ running: liveDispatch,
1153
1447
  resumeCount: Number(record.resumeCount ?? 0),
1154
1448
  resumeLimit: Number(record.resumeLimit ?? MAX_PLAN_RESUMES),
1155
1449
  resumeAvailable: record.plan
@@ -1180,30 +1474,135 @@ function readToolArguments(value: any) {
1180
1474
  }
1181
1475
 
1182
1476
  export function reconstructFromSession(session: any, targetPlanId?: string) {
1183
- const start = Math.max(0, session.seq - MAX_HISTORY_EVENTS)
1184
- let plan: any = null
1185
- let statuses: any[] = []
1186
- let degraded: any = null
1187
- let resultSeen = false
1188
- // A round-budget pause must survive a page refresh; otherwise the replayed
1189
- // plan looks “executing” forever (nothing is running) and the card stops
1190
- // telling the user it can simply be dispatched again.
1191
- let resultPhase = ''
1192
- let cancelled = false
1193
- let resumeCount = 0
1194
1477
  /*
1195
- * Older plans stay dispatchable.
1478
+ * [1.8.10] 回放窗口必须包含目标计划的定义。
1479
+ *
1480
+ * 会话事件超过 MAX_HISTORY_EVENTS(2000)后,窗口起点会越过早期的 plan
1481
+ * 消息。此时按 planId 重建旧计划得到 null,dispatch / status 都会退回
1482
+ * 内存里那个更新的计划,旧计划在卡片上消失,也无法再续跑。
1483
+ * 显式指定 planId 时向前扫到该计划的 plan 消息,把窗口起点前移。
1484
+ */
1485
+ let start = Math.max(0, session.seq - MAX_HISTORY_EVENTS)
1486
+ if (targetPlanId) {
1487
+ for (let seq = start - 1; seq >= 0; seq -= 1) {
1488
+ let event
1489
+ try {
1490
+ event = session.eventAt(seq)
1491
+ } catch {
1492
+ continue
1493
+ }
1494
+ if (!event || event.type !== 'user/message') continue
1495
+ const payload = parseWorkplanMessage(event.data)
1496
+ if (payload?.plan?.planId === targetPlanId) {
1497
+ start = seq
1498
+ break
1499
+ }
1500
+ }
1501
+ }
1502
+ /*
1503
+ * [1.8.15] Default replay keeps the "last defined plan" contract, but it
1504
+ * must still find that plan when its message predates the 2000-event window.
1505
+ *
1506
+ * T3 B4 measured the window failure on 1.8.14: on a >2000-event session the
1507
+ * window started after the plan message, the default replay returned null,
1508
+ * and `present` had no plan to judge — the delivery was silently allowed.
1509
+ * The scan reads backwards for the last `workplan` definition and moves the
1510
+ * window start to it.
1511
+ *
1512
+ * The "newest activity" variant was deliberately NOT adopted: the same
1513
+ * default answer also feeds `dispatch`, so an older plan that merely kept
1514
+ * receiving result/update messages would hijack a new task's default
1515
+ * dispatch target (the reason N5 in 1.8.14 left the contract alone). The
1516
+ * turn-scoped fixes (`planIdFromTurn`, the present gate) name the plan
1517
+ * explicitly instead of changing the default.
1518
+ */
1519
+ let defaultPlanId: string | null = null
1520
+ if (!targetPlanId) {
1521
+ for (let seq = session.seq - 1; seq >= 0; seq -= 1) {
1522
+ let event
1523
+ try {
1524
+ event = session.eventAt(seq)
1525
+ } catch {
1526
+ continue
1527
+ }
1528
+ if (!event || event.type !== 'user/message') continue
1529
+ const planMessage = parseWorkplanMessage(event.data)
1530
+ const planId = planMessage?.plan?.planId
1531
+ if (typeof planId !== 'string' || planId === '') continue
1532
+ defaultPlanId = planId
1533
+ let planStart = seq
1534
+ for (let back = seq - 1; back >= 0; back -= 1) {
1535
+ let prior
1536
+ try {
1537
+ prior = session.eventAt(back)
1538
+ } catch {
1539
+ continue
1540
+ }
1541
+ if (!prior || prior.type !== 'user/message') continue
1542
+ if (parseWorkplanMessage(prior.data)?.plan?.planId === planId) planStart = back
1543
+ }
1544
+ if (planStart < start) start = planStart
1545
+ break
1546
+ }
1547
+ }
1548
+ interface ReplaySnapshot {
1549
+ plan: any
1550
+ statuses: any[]
1551
+ resultPhase: string
1552
+ resultSeen: boolean
1553
+ resumeCount: number
1554
+ cancelled: boolean
1555
+ /*
1556
+ * [1.8.17] The durable result message carries the round's failure lines.
1557
+ * Replay used to drop them, and the reconstructed record then had no
1558
+ * `errors` field at all: the next dispatching round spread it
1559
+ * (`[...record.errors, …]`) and died with
1560
+ * `TypeError: record.errors is not iterable`, blocking every remaining
1561
+ * subtask at the budget boundary (wp-40ce5eee, 17:51:37).
1562
+ */
1563
+ errors: string[]
1564
+ }
1565
+ /*
1566
+ * [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
1196
1567
  *
1197
- * The replayed state used to be "whatever the newest plan message says", so a
1198
- * plan paused before a restart became unreachable the moment the next turn
1199
- * generated a new plan: the rebuild answered with the new plan and every
1200
- * dispatch of the old one failed with PLAN_ID_MISMATCH. Keep a snapshot per
1201
- * plan and let the caller ask for a specific one.
1568
+ * 旧实现只有一组 plan/statuses:中途出现第二个计划(这次事故里是「继续」被
1569
+ * 误判后生成的 wp-dd26f206)时,第一个计划的快照被冻结在当时,之后所有属于
1570
+ * 它的结果消息与人工改判都被丢弃——重启后卡片从 13/14 掉回 5/14,而会话
1571
+ * 日志里明明有 7/14 的结果消息和 6 条 done 改判。现在每个计划各一份快照,
1572
+ * 每条 durable 消息只写给 planId 指定的那个计划。
1202
1573
  */
1203
- const finished: any[] = []
1574
+ const snapshots = new Map<string, ReplaySnapshot>()
1575
+ let currentId: string | null = null
1576
+ let degraded: any = null
1577
+ const ensure = (plan: any): ReplaySnapshot => {
1578
+ let snap = snapshots.get(plan.planId)
1579
+ if (!snap) {
1580
+ snap = {
1581
+ plan,
1582
+ statuses: createStatuses(plan),
1583
+ resultPhase: '',
1584
+ resultSeen: false,
1585
+ resumeCount: 0,
1586
+ cancelled: false,
1587
+ errors: [],
1588
+ }
1589
+ snapshots.set(plan.planId, snap)
1590
+ }
1591
+ currentId = plan.planId
1592
+ return snap
1593
+ }
1204
1594
  /** [1.6.0] callId → 待确认的 update 写入;只有配对的 tool/result 才能定案。 */
1205
1595
  const pendingToolCalls = new Map<string, any>()
1206
- const snapshot = () => ({ plan, statuses, resultPhase, resultSeen, resumeCount, cancelled })
1596
+ /**
1597
+ * [1.8.11] 已经由 durable `workplan-update` 消息应用过的人工改判。
1598
+ *
1599
+ * 一次 `dsh_workplan_update` 会写两份记录:一条 durable 用户消息(带
1600
+ * revision 与 updatedBy=agent)和一条 tool/result。回放原来两份都应用,
1601
+ * 第二次以 system 身份把 revision 再抬一级并覆盖 summary——人工改判的
1602
+ * 证据后缀就这么丢了。这里记下消息的 seq,配对的 tool/result 不再重复写。
1603
+ */
1604
+ const appliedUpdates = new Map<string, { seq: number; status: string }>()
1605
+ const updateKey = (planId: string, subtaskId: string) => `${planId}\u0000${subtaskId}`
1207
1606
  for (let seq = start; seq < session.seq; seq += 1) {
1208
1607
  let event
1209
1608
  try {
@@ -1216,34 +1615,40 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1216
1615
  const payload = parseWorkplanMessage(event.data)
1217
1616
  if (payload?.degraded) {
1218
1617
  degraded = payload
1219
- plan = null
1220
- statuses = []
1221
- cancelled = false
1618
+ currentId = null
1222
1619
  } else if (payload?.plan) {
1223
- if (plan) finished.push(snapshot())
1224
- plan = payload.plan
1225
- statuses = createStatuses(plan)
1226
- cancelled = false
1227
- /*
1228
- * A new plan must not inherit the previous plan's round phase.
1229
- *
1230
- * `resultPhase` outlived the old plan, so after a paused plan the next
1231
- * plan in the same session replayed as `paused` before its first
1232
- * dispatch — the card claimed the new plan was out of budget when it had
1233
- * not started. Only a result message for *this* plan may set it.
1234
- */
1235
- resultPhase = ''
1236
- resultSeen = false
1237
- resumeCount = 0
1620
+ ensure(payload.plan)
1238
1621
  }
1622
+ /*
1623
+ * Every result message is routed by its own planId. A result that arrives
1624
+ * after a newer plan was generated must still update the plan it names —
1625
+ * that was the 13/14 → 5/14 replay regression. A plan never inherits
1626
+ * another plan's round phase or resume counter (each snapshot owns them).
1627
+ */
1239
1628
  const result = parseResultMessage(event.data)
1240
- if (result && plan && result.planId === plan.planId) {
1241
- statuses = applyResultStatuses(statuses, result)
1242
- // Resume bookkeeping must survive a page refresh, otherwise the budget
1243
- // silently resets and a never-succeeding subtask can loop forever.
1244
- resumeCount = Number(result.resumeCount ?? resumeCount) || 0
1245
- resultPhase = typeof result.phase === 'string' ? result.phase : ''
1246
- resultSeen = true
1629
+ if (result && typeof result.planId === 'string') {
1630
+ const snap = snapshots.get(result.planId)
1631
+ if (snap) {
1632
+ snap.statuses = applyResultStatuses(snap.statuses, result)
1633
+ // Resume bookkeeping must survive a page refresh, otherwise the budget
1634
+ // silently resets and a never-succeeding subtask can loop forever.
1635
+ snap.resumeCount = Number(result.resumeCount ?? snap.resumeCount) || 0
1636
+ snap.resultPhase = typeof result.phase === 'string' ? result.phase : ''
1637
+ snap.resultSeen = true
1638
+ // [1.8.17] Keep the durable failure lines so a replayed record is
1639
+ // shaped like a live one (never `undefined`).
1640
+ if (Array.isArray(result.errors)) {
1641
+ snap.errors = snap.errors.concat(result.errors.map((line: any) => String(line))).slice(-20)
1642
+ }
1643
+ /*
1644
+ * [1.8.14] A cancel that lands while a dispatch is in flight writes no
1645
+ * separate cancel message (it aborts the dispatch instead), so the
1646
+ * only durable trace of that cancellation is `phase: 'cancelled'` in
1647
+ * the round result. Without this the plan reopens as "executing"
1648
+ * after a restart — the cancel is silently lost.
1649
+ */
1650
+ if (snap.resultPhase === 'cancelled') snap.cancelled = true
1651
+ }
1247
1652
  }
1248
1653
  /*
1249
1654
  * [1.7.0] Manual re-adjudications replay in order.
@@ -1255,24 +1660,37 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1255
1660
  * newer one (see `applyResultStatuses`).
1256
1661
  */
1257
1662
  const update = parseUpdateMessage(event.data)
1258
- if (update && plan && update.planId === plan.planId && typeof update.subtaskId === 'string') {
1259
- try {
1260
- statuses = applyStatus(statuses, update.subtaskId, {
1261
- status: update.status,
1262
- progress: typeof update.progress === 'number' ? update.progress : undefined,
1263
- summary: typeof update.note === 'string' ? update.note : undefined,
1264
- revision: Number.isInteger(update.revision) ? update.revision : undefined,
1265
- updatedBy: 'agent',
1266
- })
1267
- } catch {
1268
- // An invalid historical update is ignored; the rest still replays.
1663
+ if (update && typeof update.planId === 'string' && typeof update.subtaskId === 'string') {
1664
+ const snap = snapshots.get(update.planId)
1665
+ if (snap) {
1666
+ try {
1667
+ snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
1668
+ status: update.status,
1669
+ progress: typeof update.progress === 'number' ? update.progress : undefined,
1670
+ summary: typeof update.note === 'string' ? update.note : undefined,
1671
+ // [1.8.13] Evidence written through the update tool must survive replay.
1672
+ verification: update.verification,
1673
+ acceptance: update.acceptance,
1674
+ artifacts: update.artifacts,
1675
+ missingArtifacts: update.missingArtifacts,
1676
+ revision: Number.isInteger(update.revision) ? update.revision : undefined,
1677
+ updatedBy: 'agent',
1678
+ })
1679
+ appliedUpdates.set(updateKey(update.planId, update.subtaskId), {
1680
+ seq: Number(event.seq ?? 0),
1681
+ status: String(update.status ?? ''),
1682
+ })
1683
+ } catch {
1684
+ // An invalid historical update is ignored; the rest still replays.
1685
+ }
1269
1686
  }
1270
1687
  }
1271
1688
  const cancel = parseCancelMessage(event.data)
1272
- if (cancel && plan && cancel.planId === plan.planId) {
1273
- cancelled = true
1689
+ if (cancel && typeof cancel.planId === 'string') {
1690
+ const snap = snapshots.get(cancel.planId)
1691
+ if (snap) snap.cancelled = true
1274
1692
  }
1275
- } else if (event.type === 'tool/call' && plan) {
1693
+ } else if (event.type === 'tool/call') {
1276
1694
  /*
1277
1695
  * [1.6.0] 只登记,不下结论。
1278
1696
  *
@@ -1286,7 +1704,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1286
1704
  if (data?.name === 'dsh_workplan_update' && typeof data.callId === 'string') {
1287
1705
  const args = readToolArguments(data.arguments)
1288
1706
  if (args && typeof args.subtaskId === 'string' && typeof args.status === 'string') {
1289
- pendingToolCalls.set(data.callId, { args, planId: plan.planId })
1707
+ const planId = typeof args.planId === 'string' ? args.planId : currentId
1708
+ if (planId) pendingToolCalls.set(data.callId, { args, planId, callSeq: Number(event.seq ?? 0) })
1290
1709
  }
1291
1710
  }
1292
1711
  } else if (event.type === 'tool/result') {
@@ -1295,26 +1714,50 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1295
1714
  if (typeof callId !== 'string') continue
1296
1715
  const pending = pendingToolCalls.get(callId)
1297
1716
  pendingToolCalls.delete(callId)
1298
- if (!pending || !plan || pending.planId !== plan.planId) {
1717
+ const snap = pending && typeof pending.planId === 'string' ? snapshots.get(pending.planId) : null
1718
+ if (!snap) {
1299
1719
  // 结果晚于新计划到达:旧计划的写入不污染新计划的状态表。
1300
1720
  } else if (message.isError === true) {
1301
1721
  // 失败的更新不是完成:状态表保持原样。
1302
1722
  } else {
1303
1723
  const args = pending.args
1304
- try {
1305
- statuses = applyStatus(statuses, args.subtaskId, {
1306
- status: args.status,
1307
- progress: typeof args.progress === 'number' ? args.progress : undefined,
1308
- summary: typeof args.note === 'string' ? args.note : undefined,
1309
- })
1310
- } catch {
1311
- // An invalid historical call is ignored; the live cache remains authoritative.
1724
+ /*
1725
+ * [1.8.11] 同一次改判已经由 durable 消息应用过时,配对结果不再写第二遍。
1726
+ * 判据是 seq 与状态都一致:durable 消息在本次调用之后到达且状态相同,
1727
+ * 才说明它是这次调用的记录;更早/更晚的人工改判仍按自己的顺序生效。
1728
+ */
1729
+ const applied = appliedUpdates.get(updateKey(pending.planId, args.subtaskId))
1730
+ const alreadyDurable = Boolean(applied)
1731
+ && applied!.seq > Number(pending.callSeq ?? 0)
1732
+ && applied!.status === String(args.status ?? '')
1733
+ if (!alreadyDurable) {
1734
+ try {
1735
+ snap.statuses = applyStatus(snap.statuses, args.subtaskId, {
1736
+ status: args.status,
1737
+ progress: typeof args.progress === 'number' ? args.progress : undefined,
1738
+ summary: typeof args.note === 'string' ? args.note : undefined,
1739
+ // [1.8.13] A tool/result fallback carries the same evidence fields.
1740
+ verification: args.verification,
1741
+ acceptance: args.acceptance,
1742
+ artifacts: args.artifacts,
1743
+ missingArtifacts: args.missingArtifacts,
1744
+ })
1745
+ } catch {
1746
+ // An invalid historical call is ignored; the live cache remains authoritative.
1747
+ }
1312
1748
  }
1313
1749
  }
1314
1750
  }
1315
1751
  }
1316
- if (!plan && !degraded) return null
1317
- if (degraded) {
1752
+ /*
1753
+ * [1.8.15] Prefer the explicitly named plan, then the plan that owns the
1754
+ * newest activity, then the last definition seen in the replay window.
1755
+ */
1756
+ const chosenId = targetPlanId ?? defaultPlanId ?? currentId
1757
+ let chosen = chosenId ? snapshots.get(chosenId) ?? null : null
1758
+ if (!chosen && currentId) chosen = snapshots.get(currentId) ?? null
1759
+ if (!chosen) {
1760
+ if (!degraded) return null
1318
1761
  return {
1319
1762
  plan: null,
1320
1763
  planId: degraded.planId ?? null,
@@ -1328,12 +1771,12 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1328
1771
  createdTurn: degraded.createdTurn ?? null,
1329
1772
  }
1330
1773
  }
1331
- if (!plan) return null
1332
- if (targetPlanId && plan.planId !== targetPlanId) {
1333
- const hit = finished.find((item: any) => item.plan?.planId === targetPlanId)
1334
- if (!hit) return null
1335
- ;({ plan, statuses, resultPhase, resultSeen, resumeCount, cancelled } = hit)
1336
- }
1774
+ const plan = chosen.plan
1775
+ const statuses = chosen.statuses
1776
+ const resultPhase = chosen.resultPhase
1777
+ const resultSeen = chosen.resultSeen
1778
+ const resumeCount = chosen.resumeCount
1779
+ const cancelled = chosen.cancelled
1337
1780
  let phase = planPhase(statuses, resultSeen)
1338
1781
  if (resultPhase === 'paused' && statuses.some((item: any) => item.status !== 'done')) phase = 'paused'
1339
1782
  if (cancelled) phase = 'cancelled'
@@ -1366,9 +1809,24 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1366
1809
  updatedAt: Date.now(),
1367
1810
  createdTurn: plan.createdTurn,
1368
1811
  resumeCount,
1812
+ /*
1813
+ * [1.8.17] A reconstructed record must carry every field the live dispatch
1814
+ * path spreads/pushes unconditionally. `errors` was the one that was
1815
+ * missing; its absence turned a recoverable child failure into a round
1816
+ * abort that marked the rest of the plan blocked.
1817
+ */
1818
+ errors: (chosen.errors ?? []).slice(-20),
1369
1819
  resumeLimit: MAX_PLAN_RESUMES,
1370
1820
  resumeAvailable: canResumePlan({ phase, statuses, resumeCount }, MAX_PLAN_RESUMES).resume,
1371
1821
  stale: stalePending,
1822
+ /*
1823
+ * [1.8.14] Two facts, one from the log: whether the plan is cancelled and
1824
+ * whether that cancellation is durably recorded. For replay they are the
1825
+ * same; the live `cancelPlan` uses `cancelRecorded` to make a second
1826
+ * cancel a no-op instead of appending a duplicate message (N8).
1827
+ */
1828
+ cancelled,
1829
+ cancelRecorded: cancelled,
1372
1830
  }
1373
1831
  }
1374
1832
 
@@ -1453,14 +1911,78 @@ export type WorkplanRuntimeOptions = {
1453
1911
  totalTimeoutMs?: number
1454
1912
  /** How many times a blocked plan may be resumed. */
1455
1913
  maxResumes?: number
1914
+ /**
1915
+ * [1.8.13] Package version, supplied by the host from its `meta.version`.
1916
+ *
1917
+ * `dsh_workplan_status` used to say nothing about which build answered, so a
1918
+ * stale process (the incident ran 1.8.9 while the workspace had 1.8.11) could
1919
+ * only be detected by inspecting the PID by hand. The version now travels
1920
+ * with every status/dispatch answer.
1921
+ */
1922
+ version?: string
1923
+ /**
1924
+ * [1.8.14] Identity of the modules this process actually loaded.
1925
+ *
1926
+ * 1.8.13 made the *package version* visible, but the incident's N1 stayed
1927
+ * open: a version string cannot distinguish "this build" from "the same
1928
+ * version rebuilt", and after a profile recomposition the in-memory modules
1929
+ * may not be the files on disk. The host therefore hashes the loaded
1930
+ * `lib/host.js` + `lib/runtime.js` + `lib/plan.js` at module-init time and
1931
+ * passes the digest (plus PID and process start time) here. `status` answers
1932
+ * it even when there is no plan, so the "did the restart load the fix"
1933
+ * question needs no PID archaeology.
1934
+ */
1935
+ build?: {
1936
+ pid?: number
1937
+ startedAt?: number
1938
+ entryPath?: string
1939
+ buildHash?: string
1940
+ }
1456
1941
  }
1457
1942
 
1458
1943
  export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions = {}) {
1459
- const state = { records: new Map() }
1944
+ /*
1945
+ * `activeTurns` maps a root session to the turn whose user message carried a
1946
+ * real task; the `agent/turn-stopping` gate only objects on those turns.
1947
+ */
1948
+ const state: any = { records: new Map(), activeTurns: new Map() }
1460
1949
  /*
1461
1950
  * Resolve the tunables once, at construction, so every code path (dispatch,
1462
1951
  * resume, cancel, the host's tool timeout) agrees on the same numbers.
1463
1952
  */
1953
+ const pluginVersion = typeof options.version === 'string' && options.version ? options.version : 'unknown'
1954
+ /*
1955
+ * [1.8.14] Build identity, captured once.
1956
+ *
1957
+ * `startedAt` is derived from `process.uptime()` so it is the real process
1958
+ * start, not the plugin's construction time; `uptimeMs` is computed live.
1959
+ * Tests construct the runtime without a `build` option, so every field is
1960
+ * optional and the answer degrades to `unknown` instead of failing.
1961
+ */
1962
+ const buildInfo = {
1963
+ pid: Number.isInteger(options.build?.pid) && Number(options.build?.pid) > 0
1964
+ ? Number(options.build!.pid)
1965
+ : process.pid,
1966
+ startedAt: Number.isFinite(Number(options.build?.startedAt)) && Number(options.build?.startedAt) > 0
1967
+ ? Number(options.build!.startedAt)
1968
+ : Math.round(Date.now() - process.uptime() * 1000),
1969
+ entryPath: typeof options.build?.entryPath === 'string' && options.build.entryPath
1970
+ ? options.build.entryPath
1971
+ : '',
1972
+ buildHash: typeof options.build?.buildHash === 'string' && options.build.buildHash
1973
+ ? options.build.buildHash
1974
+ : 'unknown',
1975
+ }
1976
+ function runtimeIdentity() {
1977
+ return {
1978
+ version: pluginVersion,
1979
+ pid: buildInfo.pid,
1980
+ startedAt: buildInfo.startedAt,
1981
+ uptimeMs: Math.max(0, Date.now() - buildInfo.startedAt),
1982
+ entryPath: buildInfo.entryPath,
1983
+ buildHash: buildInfo.buildHash,
1984
+ }
1985
+ }
1464
1986
  const limits = {
1465
1987
  childTimeoutMs: normaliseChildTimeout(options.childTimeoutMs),
1466
1988
  idleTimeoutMs: normaliseIdleTimeout(options.idleTimeoutMs),
@@ -1516,15 +2038,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1516
2038
  }
1517
2039
  }
1518
2040
 
1519
- async function updateStatus(agent: any, args: any) {
2041
+ /**
2042
+ * Point an edit or a cancellation at the plan the caller actually named.
2043
+ *
2044
+ * dispatch has always rebuilt an older plan out of the session log
2045
+ * (`needsRebuild` + `reconstructFromSession(session, requestedPlanId)`), but
2046
+ * update and cancel compared the id and threw PLAN_ID_MISMATCH — so the one
2047
+ * repair path for "the child wrote its artifact and was then interrupted"
2048
+ * (re-adjudicating that step) was closed on exactly the plans that needed it.
2049
+ * Align the three tools: a named plan that exists in the session log becomes
2050
+ * the target record. While a *different* plan is dispatching, refuse with a
2051
+ * reason instead of silently swapping the running record out from under it.
2052
+ */
2053
+ function adoptRequestedPlan(session: any, current: any, requestedPlanId: any) {
2054
+ if (!current?.plan || !requestedPlanId || current.plan.planId === requestedPlanId) return current
2055
+ if (current.dispatchPromise) {
2056
+ throw new PlanError(
2057
+ `计划 ${requestedPlanId} 不是当前记录:${current.plan.planId} 正在执行,先等它结束或先取消它`,
2058
+ 'PLAN_ID_MISMATCH',
2059
+ )
2060
+ }
2061
+ const rebuilt = reconstructFromSession(session, requestedPlanId)
2062
+ if (!rebuilt?.plan || rebuilt.plan.planId !== requestedPlanId) {
2063
+ throw new PlanError(
2064
+ `planId 与当前计划不匹配(当前 ${current.plan.planId},会话日志里也没有 ${requestedPlanId})`,
2065
+ 'PLAN_ID_MISMATCH',
2066
+ )
2067
+ }
2068
+ rebuilt.resumeLimit = current.resumeLimit ?? rebuilt.resumeLimit
2069
+ state.records.set(session.id, rebuilt)
2070
+ return rebuilt
2071
+ }
2072
+
2073
+ async function updateStatus(agent: any, args: any): Promise<any> {
1520
2074
  const session = agent?.session
1521
2075
  if (!session) throw new PlanError('只能在会话内更新计划', 'NO_SESSION')
1522
2076
  if (!isRootSession(session)) throw new PlanError('子 Agent 不能更新主计划', 'NOT_ROOT')
1523
- const record = state.records.get(session.id)
2077
+ let record = state.records.get(session.id)
2078
+ if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2079
+ record = adoptRequestedPlan(session, record, args?.planId)
1524
2080
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
1525
- if (args?.planId && record.plan.planId !== args.planId) {
1526
- throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
1527
- }
1528
2081
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : ''
1529
2082
  if (!subtaskId) throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK')
1530
2083
  const status = typeof args?.status === 'string' ? args.status : ''
@@ -1578,11 +2131,27 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1578
2131
  }
1579
2132
  }
1580
2133
  const revision = Number(current?.revision ?? 0) + 1
2134
+ /*
2135
+ * [1.8.13] A manual verdict can carry structured evidence.
2136
+ *
2137
+ * The tool used to accept only `status/progress/note/evidence`, so the
2138
+ * documented escape from the present gate ("先用 dsh_workplan_update 复核
2139
+ * 并补证据") did not exist: a done row stayed `verification: undefined`
2140
+ * and could never become deliverable. These four fields are now accepted,
2141
+ * sanitised by `applyStatus`, persisted in the durable update message and
2142
+ * replayed. Omitted fields keep their previous values.
2143
+ */
2144
+ const evidencePatch: any = {}
2145
+ if (args?.verification !== undefined) evidencePatch.verification = args.verification
2146
+ if (args?.acceptance !== undefined) evidencePatch.acceptance = args.acceptance
2147
+ if (args?.artifacts !== undefined) evidencePatch.artifacts = args.artifacts
2148
+ if (args?.missingArtifacts !== undefined) evidencePatch.missingArtifacts = args.missingArtifacts
1581
2149
  record.statuses = applyStatus(record.statuses, subtaskId, {
1582
2150
  status,
1583
2151
  progress: typeof args?.progress === 'number' ? args.progress : undefined,
1584
2152
  summary: summary || undefined,
1585
2153
  error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
2154
+ ...evidencePatch,
1586
2155
  revision,
1587
2156
  updatedBy: 'agent',
1588
2157
  })
@@ -1597,6 +2166,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1597
2166
  * result. Appending one small message keeps the replay path honest.
1598
2167
  */
1599
2168
  try {
2169
+ const writtenRow = record.statuses.find((item: any) => item.subtaskId === subtaskId)
1600
2170
  session.append('user/message', buildUpdateMessage({
1601
2171
  planId: record.plan.planId,
1602
2172
  subtaskId,
@@ -1604,6 +2174,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1604
2174
  progress: typeof args?.progress === 'number' ? args.progress : undefined,
1605
2175
  note: summary || undefined,
1606
2176
  revision,
2177
+ verification: writtenRow?.verification,
2178
+ acceptance: writtenRow?.acceptance,
2179
+ artifacts: writtenRow?.artifacts,
2180
+ missingArtifacts: writtenRow?.missingArtifacts,
1607
2181
  }), { surfaceOp: 'append' })
1608
2182
  } catch (error) {
1609
2183
  pushRecordError(record, error)
@@ -1621,6 +2195,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1621
2195
  record.updatedAt = Date.now()
1622
2196
  const snapshot = derivePlanSnapshot(record.statuses)
1623
2197
  const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
2198
+ const readiness = deliveryReadiness(snapshot, { phase: record.phase })
1624
2199
  return {
1625
2200
  ok: true,
1626
2201
  planId: record.plan.planId,
@@ -1629,6 +2204,16 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1629
2204
  revision: written?.revision ?? revision,
1630
2205
  updatedBy: written?.updatedBy ?? 'agent',
1631
2206
  stats: snapshot.stats,
2207
+ deliveryReady: readiness.ready,
2208
+ deliveryBlockers: readiness.blockers.slice(0, 12),
2209
+ deliveryRemaining: readiness.remaining.slice(0, 20),
2210
+ ...(readiness.ready
2211
+ ? { hint: '计划已全部 done 且证据通过,可以交付。' }
2212
+ : {
2213
+ hint: written?.status === 'done'
2214
+ ? '该子任务已是 done,但计划尚未通过交付就绪检查;若这项仍有证据缺口,请用 verification/acceptance 补齐或改回 blocked。'
2215
+ : '计划尚未通过交付就绪检查;继续推进剩余项,不要调用 present。',
2216
+ }),
1632
2217
  }
1633
2218
  }
1634
2219
 
@@ -1637,11 +2222,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1637
2222
  if (!session) throw new PlanError('只能在会话内取消计划', 'NO_SESSION')
1638
2223
  if (!isRootSession(session)) throw new PlanError('子 Agent 不能取消主计划', 'NOT_ROOT')
1639
2224
  let record = state.records.get(session.id)
1640
- if (!record?.plan) record = reconstructFromSession(session)
2225
+ if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2226
+ record = adoptRequestedPlan(session, record, args?.planId)
1641
2227
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
1642
- if (args?.planId && record.plan.planId !== args.planId) {
1643
- throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
1644
- }
1645
2228
  const reason = typeof args?.reason === 'string' && args.reason.trim()
1646
2229
  ? args.reason.trim()
1647
2230
  : '用户取消'
@@ -1668,6 +2251,55 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1668
2251
  stats: before.stats,
1669
2252
  }
1670
2253
  }
2254
+ /*
2255
+ * [1.8.14] N8: a second cancel used to append a second cancel message.
2256
+ *
2257
+ * Cancelling is idempotent by definition: once the cancellation is durably
2258
+ * recorded, repeating it must not grow the log — every duplicate is
2259
+ * replayed and shows up as another "取消" line in the transcript, which is
2260
+ * exactly the kind of "did it happen twice?" noise this incident was made
2261
+ * of.
2262
+ *
2263
+ * [1.8.15] The abort path was the exception that still duplicated: while
2264
+ * `dispatchPromise` was in flight the guard fell through every time, so two
2265
+ * cancels during one dispatch appended two messages (T4e F2). Once the
2266
+ * abort has been requested there is nothing left to stop, so the presence
2267
+ * of an in-flight promise is no longer a reason to append again.
2268
+ */
2269
+ if (record.phase === 'cancelled' && record.cancelRecorded === true
2270
+ && (!record.dispatchPromise || record.abortRequested === true)) {
2271
+ state.records.set(session.id, record)
2272
+ return {
2273
+ ok: true,
2274
+ planId: record.plan.planId,
2275
+ phase: 'cancelled',
2276
+ reason: typeof record.cancelReason === 'string' && record.cancelReason ? record.cancelReason : reason,
2277
+ alreadyCancelled: true,
2278
+ abortedRunning: false,
2279
+ cancelRecorded: true,
2280
+ stats: before.stats,
2281
+ }
2282
+ }
2283
+ const cancelMessage = buildCancelMessage(record.plan.planId, reason)
2284
+ /*
2285
+ * [1.8.14] N12: the durable cancel used to be the only append without a
2286
+ * try/catch. A failing append threw out of the tool after the in-memory
2287
+ * phase had already flipped to `cancelled`, leaving the UI saying
2288
+ * "已取消" while the log said nothing — the next restart silently undid it.
2289
+ * Record the failure and report `cancelRecorded: false` instead.
2290
+ */
2291
+ const appendCancelRecord = () => {
2292
+ try {
2293
+ session.append('user/message', cancelMessage, { surfaceOp: 'append' })
2294
+ record.cancelRecorded = true
2295
+ record.cancelReason = reason
2296
+ return true
2297
+ } catch (error: any) {
2298
+ record.cancelRecorded = false
2299
+ pushRecordError(record, `写入取消消息失败:${error instanceof Error ? error.message : String(error)}`)
2300
+ return false
2301
+ }
2302
+ }
1671
2303
  if (record.dispatchPromise) {
1672
2304
  /*
1673
2305
  * Cancel must always work.
@@ -1683,31 +2315,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1683
2315
  record.updatedAt = Date.now()
1684
2316
  let aborted = false
1685
2317
  try {
2318
+ /*
2319
+ * [1.8.15] Mark the abort before asking for it. The idempotency guard
2320
+ * above keys on this flag, so a second cancel that arrives while the
2321
+ * dispatch promise is still settling cannot append a second message.
2322
+ */
2323
+ record.abortRequested = true
1686
2324
  record.abortDispatch?.(reason)
1687
2325
  aborted = true
1688
2326
  } catch (error: any) {
1689
2327
  record.errors = [...(record.errors ?? []), `取消时中止执行失败:${String(error?.message ?? error)}`].slice(-20)
1690
2328
  }
2329
+ /*
2330
+ * [1.8.14] The abort path now writes the cancel durably too. 1.8.13
2331
+ * returned here without touching the log, so a later failed result write
2332
+ * left no trace of the cancellation at all and a restart reopened the
2333
+ * plan as "executing".
2334
+ */
2335
+ const recorded = appendCancelRecord()
2336
+ state.records.set(session.id, record)
1691
2337
  return {
1692
2338
  ok: true,
1693
2339
  planId: record.plan.planId,
1694
2340
  phase: 'cancelled',
1695
2341
  reason,
1696
2342
  abortedRunning: aborted,
2343
+ cancelRecorded: recorded,
1697
2344
  stats: derivePlanSnapshot(record.statuses).stats,
1698
2345
  }
1699
2346
  }
1700
2347
  record.phase = 'cancelled'
1701
2348
  record.error = `计划已取消:${reason}`
1702
2349
  record.updatedAt = Date.now()
1703
- const message = buildCancelMessage(record.plan.planId, reason)
1704
- session.append('user/message', message, { surfaceOp: 'append' })
2350
+ const recorded = appendCancelRecord()
1705
2351
  state.records.set(session.id, record)
1706
2352
  return {
1707
2353
  ok: true,
1708
2354
  planId: record.plan.planId,
1709
2355
  phase: 'cancelled',
1710
2356
  reason,
2357
+ cancelRecorded: recorded,
1711
2358
  stats: derivePlanSnapshot(record.statuses).stats,
1712
2359
  }
1713
2360
  }
@@ -1727,6 +2374,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1727
2374
  record.resultWritten = true
1728
2375
  } catch (error) {
1729
2376
  ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
2377
+ /*
2378
+ * [1.8.14] N13: a failed result write is a real, user-visible failure —
2379
+ * the round summary is absent from the transcript and a restart can
2380
+ * disagree with the live phase. Log it durably, not only in the host log.
2381
+ */
2382
+ pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
1730
2383
  }
1731
2384
  }
1732
2385
  /*
@@ -1740,12 +2393,46 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1740
2393
  return record
1741
2394
  }
1742
2395
 
2396
+ /*
2397
+ * [1.8.7] `ok` alone was read as "the plan is finished".
2398
+ *
2399
+ * The incident's tool result said `ok: true` while 3 of 13 subtasks had never
2400
+ * run; the rendered line added "已加入进行中的派发并等到结果", so the model
2401
+ * had no field telling it the round ended early. `complete`/`remaining` make
2402
+ * that state machine-readable instead of a sentence to interpret.
2403
+ */
2404
+ function completionFields(snapshot: any, phase: any) {
2405
+ const stats = snapshot?.stats ?? {}
2406
+ const total = Number(stats.total ?? 0)
2407
+ const done = Number(stats.done ?? 0)
2408
+ /*
2409
+ * [1.8.13] `complete` and `deliveryReady` are different facts.
2410
+ *
2411
+ * `complete` keeps its old meaning (every subtask done) so existing callers
2412
+ * do not break, but a dispatch answer that only said `complete:true` was
2413
+ * read as "finished" even when every row was legacy/empty-evidence. The
2414
+ * model now also sees whether the plan passed the delivery gate, plus the
2415
+ * exact gaps.
2416
+ */
2417
+ const readiness = deliveryReadiness(snapshot, { phase })
2418
+ return {
2419
+ complete: total > 0 && done >= total,
2420
+ remaining: Math.max(0, total - done),
2421
+ deliveryReady: readiness.ready,
2422
+ deliveryBlockers: readiness.blockers.slice(0, 12),
2423
+ deliveryRemaining: readiness.remaining.slice(0, 20),
2424
+ }
2425
+ }
2426
+
1743
2427
  function dispatchSnapshotOf(record: any, extra: any = {}) {
1744
2428
  const snapshot = derivePlanSnapshot(record.statuses)
1745
2429
  return {
1746
2430
  ok: true,
2431
+ version: pluginVersion,
2432
+ runtime: runtimeIdentity(),
1747
2433
  planId: record.plan.planId,
1748
2434
  alreadyRunning: false,
2435
+ ...completionFields(snapshot, record.phase),
1749
2436
  ...extra,
1750
2437
  phase: record.phase,
1751
2438
  stats: snapshot.stats,
@@ -1771,18 +2458,30 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1771
2458
  if (rebuilt?.plan) record = rebuilt
1772
2459
  }
1773
2460
  if (!record?.plan) {
2461
+ /*
2462
+ * [1.8.14] N1/§14.6 step 2: the identity of the loaded build must be
2463
+ * answerable even before a plan exists. 1.8.13 returned NO_PLAN with no
2464
+ * version here, so the documented restart check ("call status, confirm
2465
+ * the version") failed on a fresh session — the check itself was wrong,
2466
+ * not just the docs.
2467
+ */
1774
2468
  return {
1775
2469
  ok: false,
1776
2470
  code: 'NO_PLAN',
1777
2471
  running: false,
2472
+ version: pluginVersion,
2473
+ runtime: runtimeIdentity(),
1778
2474
  error: '当前会话没有可查看的计划',
1779
2475
  hint: '先让本轮生成计划并调用 dsh_workplan_dispatch。',
1780
2476
  }
1781
2477
  }
1782
2478
  const running = Boolean(record.dispatchPromise)
1783
2479
  const snapshot = derivePlanSnapshot(record.statuses)
2480
+ const readiness = deliveryReadiness(snapshot, { phase: record.phase })
1784
2481
  return {
1785
2482
  ok: true,
2483
+ version: pluginVersion,
2484
+ runtime: runtimeIdentity(),
1786
2485
  planId: record.plan.planId,
1787
2486
  running,
1788
2487
  phase: record.phase,
@@ -1791,9 +2490,16 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1791
2490
  statuses: modelStatusLines(snapshot.statuses),
1792
2491
  errors: (record.errors ?? []).slice(-10),
1793
2492
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
2493
+ deliveryReady: readiness.ready,
2494
+ deliveryBlockers: readiness.blockers.slice(0, 12),
2495
+ deliveryRemaining: readiness.remaining.slice(0, 20),
1794
2496
  ...(running
1795
2497
  ? { hint: '计划仍在执行:先向用户报告进度,不要声称完成;等结果消息出现后再逐项核对证据。' }
1796
- : { hint: '当前没有正在执行的派发。若仍有 pending/blocked,可再次调用 dsh_workplan_dispatch 续跑。' }),
2498
+ : readiness.ready
2499
+ ? { hint: '计划已全部 done 且证据通过,可以交付。' }
2500
+ : readiness.cancelled
2501
+ ? { hint: '计划已取消且未完成:不要 dispatch 或 present;答复按「未完成:剩余 N 项与原因」开头。' }
2502
+ : { hint: '当前没有正在执行的派发。计划尚未通过交付就绪检查:先 dispatch 续跑剩余项;若只剩已 done 项的证据缺口,用 dsh_workplan_update 补 verification/acceptance。不要调用 present。' }),
1797
2503
  }
1798
2504
  }
1799
2505
 
@@ -1838,6 +2544,31 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1838
2544
  if (args?.planId && record.plan.planId !== args.planId) {
1839
2545
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
1840
2546
  }
2547
+ /*
2548
+ * [1.8.15] Cancelled is terminal: dispatch must refuse, not resurrect.
2549
+ *
2550
+ * T4e F1/C16 proved the old path answered `ok: true` and really started
2551
+ * department Agents on a cancelled plan (`activationCalled: true`), and a
2552
+ * 2/2-done cancelled plan was silently rewritten to `phase: done`. Cancel
2553
+ * is the user's stop signal; the only honest answer is a refusal that says
2554
+ * how to continue deliberately (a new plan, or the main Agent takes over).
2555
+ */
2556
+ if (record.phase === 'cancelled' || record.cancelled === true) {
2557
+ const snapshot = derivePlanSnapshot(record.statuses)
2558
+ return {
2559
+ ok: false,
2560
+ planId: record.plan.planId,
2561
+ phase: 'cancelled',
2562
+ running: false,
2563
+ alreadyRunning: false,
2564
+ complete: false,
2565
+ remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
2566
+ stats: snapshot.stats,
2567
+ code: 'PLAN_CANCELLED',
2568
+ error: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2569
+ hint: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2570
+ }
2571
+ }
1841
2572
  /*
1842
2573
  * [1.7.0] Two dispatch modes.
1843
2574
  *
@@ -1995,6 +2726,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1995
2726
  mode: 'async',
1996
2727
  running: true,
1997
2728
  alreadyRunning: false,
2729
+ complete: false,
2730
+ remaining: Math.max(0, Number(live.stats.total ?? 0) - Number(live.stats.done ?? 0)),
1998
2731
  phase: record.phase,
1999
2732
  startedAt,
2000
2733
  stats: live.stats,
@@ -2013,8 +2746,600 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2013
2746
  return dispatchSnapshotOf(record)
2014
2747
  }
2015
2748
 
2749
+ /*
2750
+ * [1.8.7] 回合收尾前的强制闸门——「未完成即输出」的根治点。
2751
+ *
2752
+ * 事故(session-99984ebd…,2026-10-31)里,模型在计划 10/13 时 present 了
2753
+ * 报告并给出收尾答复。插件原来只订阅 `agent/pre-step`,回合结束完全不受
2754
+ * 约束;预算暂停只写了一句「可续跑」,没有任何强制力。
2755
+ *
2756
+ * 官方 harness 为此提供了确切扩展点 `agent/turn-stopping`(@deepseek-ai/dsh-agent
2757
+ * 的 runtime-types 原文:「Awaited before the boundary commits — a listener
2758
+ * that objects steers (agent.steer(...)) and the machine re-reads its inbox:
2759
+ * fresh steering runs another step, none closes the turn.」)。同仓的
2760
+ * dsh-workspace-changes 就注册在插件根 ctx 上,证明该 agent 作用域事件能到
2761
+ * 达根监听器。
2762
+ *
2763
+ * 规则:
2764
+ * - 只看根会话、只看本回合真实任务(state.activeTurns),社交/状态型回合不打扰;
2765
+ * - 降级记录(没有计划)不拦;空计划也不拦(present 仍会拒绝);
2766
+ * - 后台派发仍在跑 ⇒ 先等它结束再判断,绝不让「已结束 ∧ 正在做」复活;
2767
+ * - 计划未通过交付就绪检查(含未完成、证据缺口、已取消但未完成)⇒
2768
+ * `agent.steer()` 一条明确的「禁止收尾」指令,每个回合最多 2 次。
2769
+ *
2770
+ * [1.8.13] 取消不再等于放行。
2771
+ *
2772
+ * 1.8.8 的闸门只问“还有没有 pending/in_progress”,所以全 done 但证据是
2773
+ * legacy/空验收的计划、以及 cancelled 的计划都会安静收尾并声称完成
2774
+ * (T5-B/C/D)。现在闸门与 present 共用 `deliveryReadiness`:凡是能拦住
2775
+ * 交付的缺口,也能拦住“这个回合就这么结束”。取消分支不再要求续跑,
2776
+ * 只要求按未完成口径如实收尾,所以不会空转。
2777
+ */
2778
+ const STOP_STEER_LIMIT = 2
2779
+
2780
+ function recordReadiness(record: any) {
2781
+ const snapshot = derivePlanSnapshot(record.statuses)
2782
+ return deliveryReadiness(snapshot, { phase: record.phase })
2783
+ }
2784
+
2785
+ function stopGateApplies(record: any) {
2786
+ if (!record?.plan) return false
2787
+ if (record.degraded) return false
2788
+ const readiness = recordReadiness(record)
2789
+ if (Number(readiness.total ?? 0) === 0) return false
2790
+ return !readiness.ready
2791
+ }
2792
+
2793
+ function planChildIds(record: any) {
2794
+ const ids = new Set<string>()
2795
+ for (const item of record?.statuses ?? []) {
2796
+ if (typeof item?.childId === 'string' && item.childId) ids.add(item.childId)
2797
+ }
2798
+ for (const stage of record?.plan?.stages ?? []) {
2799
+ for (const subtask of stage?.subtasks ?? []) {
2800
+ if (typeof subtask?.childId === 'string' && subtask.childId) ids.add(subtask.childId)
2801
+ }
2802
+ }
2803
+ return ids
2804
+ }
2805
+
2806
+ const PLAN_CONTINUATION_KINDS = new Set(['subagent-settled', 'workplan-result', 'workplan-continue'])
2807
+
2808
+ /**
2809
+ * [1.8.9] 子会话谱系判定。
2810
+ *
2811
+ * `childId` 在预算重置时会被清空(`applyStatus({status:'pending'})` 走
2812
+ * `normaliseStatusEntry` 强制 childId=null),事故里的 T11 因此不在
2813
+ * planChildIds 中,turn 2 又一次绕过闸门。`header.parentSession` 是子会话
2814
+ * 自身的身份,预算与重启都不会改写它,用它旁证“这条结算来自本计划的执行者”。
2815
+ */
2816
+ function isChildSessionOf(senderId: string, session: any) {
2817
+ if (!senderId) return false
2818
+ try {
2819
+ const child = ctx.sessions?.get?.(senderId)
2820
+ const header = child?.header
2821
+ if (!header) return false
2822
+ return header.parentSession === session.id
2823
+ } catch {
2824
+ return false
2825
+ }
2826
+ }
2827
+
2828
+ /**
2829
+ * [1.8.11] 用父会话自己的 `subagent/catalog` 事件认亲。
2830
+ *
2831
+ * `subagent-settled` 到达时子会话已经被 dispose(dsh-subagent 的
2832
+ * `finishDisposal` 先 `handle.dispose()` 再 `notifySettlement`),
2833
+ * `ctx.sessions.get(senderId)` 必然拿不到 header,1.8.9 的谱系判定因此
2834
+ * 在真实生命周期下恒为 false。spawn 记录却留在父会话的事件流里,重启、
2835
+ * 回放、预算重置都不会改写它,是唯一持久可靠的父链证据。
2836
+ */
2837
+ const spawnedChildCache = new Map<string, { at: number; ids: Set<string> }>()
2838
+ function spawnedChildIds(session: any): Set<string> {
2839
+ const cached = spawnedChildCache.get(session.id)
2840
+ if (cached && cached.at === session.seq) return cached.ids
2841
+ const ids = new Set<string>()
2842
+ if (typeof session?.eventAt === 'function') {
2843
+ for (let i = 0; i < session.seq; i += 1) {
2844
+ let event
2845
+ try {
2846
+ event = session.eventAt(i)
2847
+ } catch {
2848
+ continue
2849
+ }
2850
+ if (event?.type === 'subagent/catalog' && typeof event.data?.childId === 'string') {
2851
+ ids.add(event.data.childId)
2852
+ }
2853
+ }
2854
+ }
2855
+ spawnedChildCache.set(session.id, { at: session.seq, ids })
2856
+ return ids
2857
+ }
2858
+
2859
+ /*
2860
+ * [1.8.14] N5:结算回合要判的是「这条结算对应的计划」,不是「最后生成的计划」。
2861
+ *
2862
+ * 重启后内存为空时,收尾闸门原本走默认回放(最后一个 plan 消息):事故会话在
2863
+ * A 未完成时又生成了 B,A 的结果随后到达,闸门于是按 B 判定。结算输入
2864
+ * (workplan-result)自带 planId;显式传 planId 还能触发 1.8.10 的窗口前移,
2865
+ * 旧计划落在 2000 事件窗口外时也能重建。
2866
+ */
2867
+ function planIdFromTurn(session: any, turn: number): string | undefined {
2868
+ if (typeof session?.eventAt !== 'function' || !(turn >= 1)) return undefined
2869
+ let started = -1
2870
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
2871
+ const event = session.eventAt(i)
2872
+ if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
2873
+ started = i
2874
+ break
2875
+ }
2876
+ }
2877
+ if (started < 0) return undefined
2878
+ for (let i = started + 1; i < session.seq; i += 1) {
2879
+ const event = session.eventAt(i)
2880
+ if (!event) continue
2881
+ if (event.type === 'turn/end' && Number(event.data?.turn) === turn) break
2882
+ if (event.type !== 'user/message') continue
2883
+ const data = event.data?.message ?? event.data
2884
+ if (!data || typeof data !== 'object') continue
2885
+ /*
2886
+ * planId 不在信封上:结果消息的 planId 在正文标记之间的 JSON 里,
2887
+ * plan 消息的 planId 在 plan 对象里。两者都走已有的解析器,避免
2888
+ * 对消息形状再发明一套假设。
2889
+ */
2890
+ const result = parseResultMessage(data)
2891
+ if (result && typeof result.planId === 'string' && result.planId) return result.planId
2892
+ const planMessage = parseWorkplanMessage(data)
2893
+ const planId = planMessage?.plan?.planId
2894
+ if (typeof planId === 'string' && planId) return planId
2895
+ }
2896
+ return undefined
2897
+ }
2898
+
2899
+ /**
2900
+ * [1.8.15] 当前正在进行的回合号;没有打开中的回合时返回 undefined。
2901
+ *
2902
+ * `present` 的闸门需要知道「这一回合在结算哪个计划」。默认回放回答的是
2903
+ * 「最后定义的计划」,在 A 定义、B 后定义、A 的结果在 B 之后到达时会判错
2904
+ * 计划(T3 B5)。这里不新增状态,只从会话尾部回扫 `turn/start`;遇到
2905
+ * `turn/end` 说明当前没有打开中的回合。
2906
+ */
2907
+ function currentTurnOf(session: any): number | undefined {
2908
+ if (typeof session?.eventAt !== 'function') return undefined
2909
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
2910
+ let event
2911
+ try {
2912
+ event = session.eventAt(i)
2913
+ } catch {
2914
+ return undefined
2915
+ }
2916
+ if (!event) continue
2917
+ if (event.type === 'turn/start') {
2918
+ const turn = Number(event.data?.turn)
2919
+ return Number.isFinite(turn) && turn >= 1 ? turn : undefined
2920
+ }
2921
+ if (event.type === 'turn/end') return undefined
2922
+ }
2923
+ return undefined
2924
+ }
2925
+
2926
+ /**
2927
+ * [1.8.8] 结算/结果唤醒的回合也属于“本回合的任务”。
2928
+ *
2929
+ * 事故 turn 2 由 `subagent-settled` 消息唤醒:它不是 human task,
2930
+ * `humanMessages()` 不认,`maybePlan()` 不会写 `state.activeTurns`,
2931
+ * 收尾闸门因此在 turn 2 直接放行,模型又在 11/13 时收尾。
2932
+ * 这里按会话事件判断“这一回合是否装载了本计划的续跑输入”,
2933
+ * 只认三类来源,且子 Agent 结算必须来自本计划派出过的 child,
2934
+ * 避免无关后台任务把闸门误激活。
2935
+ */
2936
+ function turnCarriesPlanWork(session: any, turn: number, record: any) {
2937
+ if (typeof session?.eventAt !== 'function' || !(turn >= 1)) return false
2938
+ const childIds = planChildIds(record)
2939
+ let started = -1
2940
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
2941
+ const event = session.eventAt(i)
2942
+ if (event?.type === 'turn/start' && Number(event.data?.turn) === turn) {
2943
+ started = i
2944
+ break
2945
+ }
2946
+ }
2947
+ if (started < 0) return false
2948
+ for (let i = started + 1; i < session.seq; i += 1) {
2949
+ const event = session.eventAt(i)
2950
+ if (!event) continue
2951
+ if (event.type === 'turn/end' && Number(event.data?.turn) === turn) break
2952
+ if (event.type !== 'user/message') continue
2953
+ const message = event.data?.message ?? event.data
2954
+ const source = message?.source ?? {}
2955
+ const kind = String(source.kind ?? '')
2956
+ if (!PLAN_CONTINUATION_KINDS.has(kind)) continue
2957
+ if (kind === 'subagent-settled') {
2958
+ const sender = String(source.senderSessionId ?? '')
2959
+ /*
2960
+ * 只认“本计划派出过的 child”“本会话的真实子会话”或“父会话 spawn
2961
+ * 记录里出现过的 child”。第三者是 dispose 之后唯一还能取到的证据;
2962
+ * 三者都不命中时,无关后台任务不能把闸门误激活。
2963
+ */
2964
+ if (!childIds.has(sender) && !isChildSessionOf(sender, session) && !spawnedChildIds(session).has(sender)) continue
2965
+ }
2966
+ return true
2967
+ }
2968
+ return false
2969
+ }
2970
+
2971
+ async function onTurnStopping(payload: any) {
2972
+ try {
2973
+ const agent = payload?.agent
2974
+ const session = agent?.session
2975
+ if (!agent || !session || !isRootSession(session)) return
2976
+ if (typeof agent.steer !== 'function') return
2977
+ const turn = Number(payload?.turn ?? 0)
2978
+ const known = state.records.get(session.id)
2979
+ /*
2980
+ * [1.8.8] 不再只认 human task 标记的 activeTurns:结算唤醒的回合
2981
+ * (subagent-settled / workplan-result / workplan-continue)同样装载
2982
+ * 了本计划的续跑输入,必须受同一道收尾闸门约束。
2983
+ */
2984
+ if (state.activeTurns?.get?.(session.id) !== turn && !turnCarriesPlanWork(session, turn, known)) return
2985
+ if (isPlanModeActive(ctx, session)) return
2986
+ let record = known
2987
+ if (!record?.plan) {
2988
+ // [1.8.14] N5:优先按本回合结算消息里点名的计划重建,而不是最后生成的计划。
2989
+ record = reconstructFromSession(session, planIdFromTurn(session, turn))
2990
+ if (record?.plan) state.records.set(session.id, record)
2991
+ }
2992
+ if (!stopGateApplies(record)) return
2993
+ if (record.dispatchPromise) {
2994
+ try {
2995
+ await record.dispatchPromise
2996
+ } catch {
2997
+ /* the failure is already on record.errors; the gate only needs the outcome */
2998
+ }
2999
+ finishRound(record, session)
3000
+ if (!stopGateApplies(record)) return
3001
+ }
3002
+ const book = record.stopSteers && record.stopSteers.turn === turn
3003
+ ? record.stopSteers
3004
+ : { turn, count: 0 }
3005
+ if (book.count >= STOP_STEER_LIMIT) return
3006
+ book.count += 1
3007
+ record.stopSteers = book
3008
+ const snapshot = derivePlanSnapshot(record.statuses)
3009
+ agent.steer(makeUserMessage(
3010
+ buildStopSteerText({
3011
+ planId: record.plan.planId,
3012
+ phase: record.phase,
3013
+ stats: snapshot.stats,
3014
+ statuses: snapshot.statuses,
3015
+ attempt: book.count,
3016
+ }),
3017
+ {
3018
+ kind: 'workplan-continue',
3019
+ form: 'notice',
3020
+ summary: `【计划未就绪】${snapshot.stats.done}/${snapshot.stats.total},本回合被要求按未完成口径收尾或继续`,
3021
+ },
3022
+ ))
3023
+ ctx.logger?.warn?.(
3024
+ `dsh-workplan: 计划 ${record.plan.planId} 未通过交付就绪检查(${snapshot.stats.done}/${snapshot.stats.total}),`
3025
+ + `已在回合收尾前要求继续/如实收尾(第 ${book.count} 次)`,
3026
+ )
3027
+ } catch (error) {
3028
+ ctx.logger?.warn?.(`dsh-workplan: 回合收尾检查失败:${error instanceof Error ? error.message : String(error)}`)
3029
+ }
3030
+ }
3031
+
3032
+ /**
3033
+ * [1.8.8] present 的硬闸门:计划未完成时不允许把产物作为成品交付。
3034
+ *
3035
+ * 1.8.7 只把这条规则写进提示词;事故里模型在回合中途直接 present,
3036
+ * 交付卡片先出现、收尾闸门后到,卡片无法撤回。这里在工具执行前拒绝,
3037
+ * 与回合闸门形成前后两道防线。
3038
+ *
3039
+ * [1.8.13] 判据换成与回合闸门同一个 `deliveryReadiness`。
3040
+ *
3041
+ * 1.8.9 只拦三类硬缺口(自检失败/验收失败/产物缺失),而把 legacy、
3042
+ * unverified、空 acceptance、undefined verification 当作“软缺口”放行;
3043
+ * 同时 `planIncomplete` 对 cancelled 直接返回 false,于是“取消 1/3 再
3044
+ * present”也能过(T5-C)。这两条都被本会话的行为探针证实。现在:
3045
+ * - 只有 `deliveryReady === true` 才能 present;
3046
+ * - 取消、降级(有 plan 时)、全 blocked、全 done 但无结构化证据一律拒绝;
3047
+ * - 拒绝文案必须给出可执行的出路(dispatch / update 补证 / 改 blocked),
3048
+ * cancel 不再被写成交付许可。
3049
+ */
3050
+ /**
3051
+ * [1.8.16] 会话里所有「定义过」的计划。
3052
+ *
3053
+ * `reconstructFromSession(session)` 只回答「默认该看哪个计划」,而 `present`
3054
+ * 需要回答「会话里还有没有没交付完的计划」。1.8.15 的活体 E2E 暴露了这个差
3055
+ * 距:wp-6753e19f 停在 13/14,但最后定义的计划已就绪,`present` 仍然交付了
3056
+ * 报告。这里按日志里出现的 planId 逐个重建;数量极少(本会话只有 4 个),
3057
+ * 每个重建各自带回扫窗口,因此旧计划不会因为超过 2000 事件而消失。
3058
+ */
3059
+ function sessionPlanRecords(session: any): any[] {
3060
+ if (typeof session?.eventAt !== 'function') return []
3061
+ const ids = new Set<string>()
3062
+ for (let i = 0; i < session.seq; i += 1) {
3063
+ let event
3064
+ try {
3065
+ event = session.eventAt(i)
3066
+ } catch {
3067
+ continue
3068
+ }
3069
+ if (!event || event.type !== 'user/message') continue
3070
+ const planId = parseWorkplanMessage(event.data)?.plan?.planId
3071
+ if (typeof planId === 'string' && planId) ids.add(planId)
3072
+ }
3073
+ const records: any[] = []
3074
+ for (const planId of ids) {
3075
+ const record = reconstructFromSession(session, planId)
3076
+ if (record?.plan) records.push(record)
3077
+ }
3078
+ return records
3079
+ }
3080
+
3081
+ /**
3082
+ * [1.8.18] The last plan that actually defines work, for the restart replay.
3083
+ *
3084
+ * The gate used to fall back only to the live record or the turn's plan. After
3085
+ * a restart both are gone, so a session whose last action was cancelling an
3086
+ * unfinished plan allowed `present` — contradicting the cancel tool's own
3087
+ * contract ("取消后如仍有未完成项或证据缺口,present 仍会被拒绝"). T5 E1/E6
3088
+ * pinned that hole.
3089
+ *
3090
+ * Empty plans are skipped: they are not delivery objects (U6), and accepting
3091
+ * one as "the last plan" would let a builder cancel real work and define an
3092
+ * empty plan as a shield. Older cancelled plans still do not block a newer
3093
+ * plan, so cancelling a stale plan does not deadlock the session.
3094
+ */
3095
+ function lastGateablePlanRecord(session: any): any {
3096
+ if (typeof session?.eventAt !== 'function') return undefined
3097
+ for (let i = session.seq - 1; i >= 0; i -= 1) {
3098
+ let event
3099
+ try {
3100
+ event = session.eventAt(i)
3101
+ } catch {
3102
+ continue
3103
+ }
3104
+ if (!event || event.type !== 'user/message') continue
3105
+ const plan = parseWorkplanMessage(event.data)?.plan
3106
+ if (!plan || typeof plan.planId !== 'string' || plan.planId === '') continue
3107
+ if (definedSubtaskCount(plan) === 0) continue
3108
+ const record = reconstructFromSession(session, plan.planId)
3109
+ if (record?.plan && definedSubtaskCount(record.plan) > 0) return record
3110
+ }
3111
+ return undefined
3112
+ }
3113
+
3114
+ function presentDenialReason(agent: any) {
3115
+ const session = agent?.session
3116
+ if (!session || !isRootSession(session)) return undefined
3117
+ if (isPlanModeActive(ctx, session)) return undefined
3118
+ /*
3119
+ * [1.8.16] Every plan in the session matters, not just the turn's plan.
3120
+ *
3121
+ * 1.8.15 taught this gate to prefer the plan named by the current turn's
3122
+ * messages, but a session can hold several plans at once (the incident
3123
+ * session itself ended with four). A live E2E on 1.8.15 showed the hole:
3124
+ * wp-6753e19f was still 13/14, the last defined plan was ready, and
3125
+ * `present` delivered the report. The gate now asks every plan in the log;
3126
+ * `dsh_workplan_cancel` is the documented escape hatch for a plan that
3127
+ * will not be finished.
3128
+ */
3129
+ const turn = currentTurnOf(session)
3130
+ const turnPlanId = turn ? planIdFromTurn(session, turn) : undefined
3131
+ const candidates = sessionPlanRecords(session)
3132
+ const live = state.records.get(session.id)
3133
+ if (live?.plan && !candidates.some((item: any) => item.plan.planId === live.plan.planId)) candidates.push(live)
3134
+ if (turnPlanId && !candidates.some((item: any) => item.plan.planId === turnPlanId)) {
3135
+ const named = reconstructFromSession(session, turnPlanId)
3136
+ if (named?.plan) candidates.push(named)
3137
+ }
3138
+ if (candidates.length === 0) return undefined
3139
+ /*
3140
+ * [U6] a plan with zero defined subtasks is not a delivery object.
3141
+ * `deliveryReadiness` can never call it ready (`total > 0`), so judging it
3142
+ * only produced the false refusal "0 个子任务虽都已 done". Filter by the
3143
+ * definition itself — not by `statuses.length` — so a real plan whose
3144
+ * statuses failed to derive is still judged (and stays closed).
3145
+ */
3146
+ const gateable = candidates.filter((item: any) => definedSubtaskCount(item.plan) > 0)
3147
+ if (gateable.length === 0) return undefined
3148
+ const unresolved = gateable
3149
+ .map((item: any) => ({
3150
+ record: item,
3151
+ readiness: deliveryReadiness(derivePlanSnapshot(item.statuses), { phase: item.phase }),
3152
+ }))
3153
+ /*
3154
+ * A cancelled plan is not a delivery blocker for *other* plans — the
3155
+ * incident session accumulates cancelled plans that will never be
3156
+ * finished, and blocking on them forever would deadlock delivery. It is
3157
+ * still checked below when it is the plan this turn (or the live record,
3158
+ * or the last defined plan after a restart) is about: cancel stops
3159
+ * execution, it does not make the work deliverable.
3160
+ */
3161
+ .filter((entry: any) => entry.record.phase !== 'cancelled' && !entry.readiness.ready)
3162
+ if (unresolved.length > 1) {
3163
+ const lines = unresolved.slice(0, 6).map((entry: any) => {
3164
+ const ids = entry.readiness.remaining.slice(0, 6).join('、')
3165
+ const suffix = ids ? `(${ids}${entry.readiness.remaining.length > 6 ? '…' : ''})` : ''
3166
+ const gaps = entry.readiness.blockers.slice(0, 4).join(';')
3167
+ return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
3168
+ + `${gaps ? `;证据缺口:${gaps}` : ''}`
3169
+ })
3170
+ return `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3171
+ + '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
3172
+ + '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
3173
+ + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。'
3174
+ }
3175
+ let record: any
3176
+ let readiness: any
3177
+ if (unresolved.length === 1) {
3178
+ record = unresolved[0].record
3179
+ readiness = unresolved[0].readiness
3180
+ } else {
3181
+ /*
3182
+ * No unfinished active plan. The plan this turn is about (or the live
3183
+ * record) may still be a cancelled one that never finished — T5-C pins
3184
+ * that `present` must be refused for it. After a restart neither exists,
3185
+ * so fall back to the last plan that defines work; otherwise the
3186
+ * sequence "cancel an unfinished plan, restart, present" silently
3187
+ * bypasses the cancel tool's own contract (T5 E1/E6).
3188
+ */
3189
+ record = state.records.get(session.id)
3190
+ if (turnPlanId) record = reconstructFromSession(session, turnPlanId) ?? record
3191
+ if (!record?.plan) record = lastGateablePlanRecord(session)
3192
+ if (!record?.plan) return undefined
3193
+ if (definedSubtaskCount(record.plan) === 0) return undefined
3194
+ readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase })
3195
+ if (readiness.ready) return undefined
3196
+ }
3197
+ if (record?.plan) state.records.set(session.id, record)
3198
+ const snapshot = derivePlanSnapshot(record.statuses)
3199
+ const planId = record.plan?.planId ?? record.planId
3200
+ const ids = readiness.remaining.slice(0, 10).join('、')
3201
+ const idSuffix = ids ? `(${ids}${readiness.remaining.length > 10 ? '…' : ''})` : ''
3202
+ const blockers = readiness.blockers.slice(0, 10).join(';')
3203
+ if (readiness.cancelled) {
3204
+ /*
3205
+ * [1.8.13] `deliveryReadiness` already puts the cancellation fact at the
3206
+ * head of `blockers`; repeating it here produced the T6b/C0 copy with the
3207
+ * same sentence twice. Only the *evidence* gaps belong in this suffix.
3208
+ */
3209
+ const gaps = readiness.blockers
3210
+ .filter((line: string) => !line.startsWith('计划已取消但只完成'))
3211
+ .slice(0, 10)
3212
+ .join(';')
3213
+ if (readiness.remaining.length === 0) {
3214
+ return `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3215
+ + '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
3216
+ + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。'
3217
+ }
3218
+ return `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3219
+ + `${gaps ? `;证据缺口:${gaps}` : ''}。`
3220
+ + '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
3221
+ + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。'
3222
+ }
3223
+ if (readiness.remaining.length === 0) {
3224
+ return `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3225
+ + '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
3226
+ + "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
3227
+ + '或把对应子任务改回 blocked 并写明原因;不要调用 present。'
3228
+ }
3229
+ return `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3230
+ + `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
3231
+ + '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
3232
+ + '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
3233
+ + '取消只停止执行,不会改变“未完成”的结论。'
3234
+ }
3235
+
3236
+ /*
3237
+ * [1.8.18] 已交付文件的写保护(T7-N2)。
3238
+ *
3239
+ * `present` 不复制内容(工具描述原文:the user opens the current files),
3240
+ * write/edit 也不校验路径是否已经交付。事故的迟到回合在 12:13 两次原地改写
3241
+ * 12:04 已 present 的报告,卡片背后的文件因此变了。这里把「present 时点
3242
+ * 已经定义过的计划」记到路径上:只要这些计划至今仍未通过交付就绪检查,
3243
+ * 根会话对同一路径的 write/edit 就被拒绝。present 之后才定义的新计划不在
3244
+ * 集合里,所以“用户要求改版 → 新计划”不会被写保护卡死;cancel 仍是显式出路。
3245
+ */
3246
+ const presentedPaths = new Map<string, {
3247
+ scannedTo: number
3248
+ planIds: Set<string>
3249
+ entries: Array<{ raw: string; canonical?: string; planIds: string[] }>
3250
+ }>()
3251
+
3252
+ function canonicalPath(session: any, value: any) {
3253
+ if (typeof value !== 'string' || value.trim() === '') return undefined
3254
+ if (isAbsolute(value)) return resolve(value)
3255
+ const cwd = session?.header?.cwd ?? options.cwd
3256
+ return typeof cwd === 'string' && cwd ? resolve(cwd, value) : undefined
3257
+ }
3258
+
3259
+ function presentedEntries(session: any) {
3260
+ if (typeof session?.eventAt !== 'function' || !(Number(session.seq) >= 0)) return []
3261
+ const cache = presentedPaths.get(session.id)
3262
+ const reusable = cache !== undefined && cache.scannedTo <= Number(session.seq)
3263
+ const from = reusable ? cache.scannedTo : 0
3264
+ const seen = new Set<string>(reusable ? cache.planIds : [])
3265
+ const entries = reusable ? cache.entries.slice() : []
3266
+ for (let i = from; i < Number(session.seq); i += 1) {
3267
+ let event
3268
+ try {
3269
+ event = session.eventAt(i)
3270
+ } catch {
3271
+ continue
3272
+ }
3273
+ if (!event) continue
3274
+ if (event.type === 'user/message') {
3275
+ const planId = parseWorkplanMessage(event.data)?.plan?.planId
3276
+ if (typeof planId === 'string' && planId) seen.add(planId)
3277
+ continue
3278
+ }
3279
+ if (event.type !== 'deliverables/presented') continue
3280
+ const planIds = [...seen]
3281
+ for (const file of event.data?.files ?? []) {
3282
+ if (typeof file?.path !== 'string' || file.path.trim() === '') continue
3283
+ entries.push({ raw: file.path, canonical: canonicalPath(session, file.path), planIds })
3284
+ }
3285
+ }
3286
+ presentedPaths.set(session.id, {
3287
+ scannedTo: Number(session.seq),
3288
+ planIds: seen,
3289
+ entries,
3290
+ })
3291
+ return entries
3292
+ }
3293
+
3294
+ function recordForPlan(session: any, planId: string) {
3295
+ const live = state.records.get(session.id)
3296
+ if (live?.plan?.planId === planId) return live
3297
+ return reconstructFromSession(session, planId)
3298
+ }
3299
+
3300
+ function presentedWriteDenialReason(agent: any, args: any) {
3301
+ const session = agent?.session
3302
+ if (!session || !isRootSession(session)) return undefined
3303
+ if (isPlanModeActive(ctx, session)) return undefined
3304
+ const entries = presentedEntries(session)
3305
+ if (entries.length === 0) return undefined
3306
+ const requested = args?.file_path ?? args?.path
3307
+ if (typeof requested !== 'string' || requested.trim() === '') return undefined
3308
+ const canonical = canonicalPath(session, requested)
3309
+ const matched = entries.filter((entry: any) =>
3310
+ entry.raw === requested
3311
+ || (canonical !== undefined && entry.canonical !== undefined && entry.canonical === canonical))
3312
+ if (matched.length === 0) return undefined
3313
+ const planIds = new Set<string>()
3314
+ for (const entry of matched) for (const planId of entry.planIds) planIds.add(planId)
3315
+ if (planIds.size === 0) return undefined
3316
+ const unresolved = [...planIds]
3317
+ .map((planId) => recordForPlan(session, planId))
3318
+ .filter((record: any) => record?.plan
3319
+ && record.phase !== 'cancelled'
3320
+ && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready)
3321
+ if (unresolved.length === 0) return undefined
3322
+ const ids = unresolved.slice(0, 4).map((record: any) => record.plan.planId)
3323
+ return `文件 ${requested} 已通过 present 交付给用户,而交付时点已存在的计划`
3324
+ + `${ids.length ? ` ${ids.join('、')}` : ''} 仍未通过交付就绪检查。`
3325
+ + '计划未就绪期间不得原地改写已交付文件:先调用 dsh_workplan_dispatch 续跑剩余项,'
3326
+ + '完成后重新 present 新版本;确实不做的计划用 dsh_workplan_cancel 显式取消。'
3327
+ + '(present 之后新建的计划不受此限制。)'
3328
+ }
3329
+
2016
3330
  function plansPayload(sessionId: any) {
2017
- return buildPlansPayload(ctx, state, sessionId)
3331
+ /*
3332
+ * [1.8.15] The feed must carry build identity too.
3333
+ *
3334
+ * `status` learned version/runtime in 1.8.14, but the Web UI reads this
3335
+ * feed only — so after a rebuild the card could not tell "the process is
3336
+ * still running yesterday's bytes" (T5c §6.2). Same helpers, one source.
3337
+ */
3338
+ return {
3339
+ ...buildPlansPayload(ctx, state, sessionId),
3340
+ version: pluginVersion,
3341
+ runtime: runtimeIdentity(),
3342
+ }
2018
3343
  }
2019
3344
 
2020
3345
  async function route(req: any, res: any, connectionCtx: any = ctx) {
@@ -2087,6 +3412,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2087
3412
  state,
2088
3413
  limits,
2089
3414
  onPreStep,
3415
+ onTurnStopping,
3416
+ presentDenialReason,
3417
+ presentedWriteDenialReason,
2090
3418
  updateStatus,
2091
3419
  cancelPlan,
2092
3420
  dispatchTool,
@@ -2142,6 +3470,16 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
2142
3470
  if (isSocialMessage(taskText)) return downstream
2143
3471
  if (isVagueContinuation(taskText)) return downstream
2144
3472
  if (isStatusQuestion(taskText)) return downstream
3473
+ /*
3474
+ * [1.8.7] Remember that this turn carries a real task.
3475
+ *
3476
+ * `agent/turn-stopping` must only object on turns whose plan belongs to the
3477
+ * user's actual request. A plan left paused in an earlier turn must not turn
3478
+ * every later "谢谢/进度如何" turn into a forced 20-minute dispatch, so the
3479
+ * stop gate reads this marker and stays silent on social or status turns.
3480
+ */
3481
+ if (!state.activeTurns) state.activeTurns = new Map()
3482
+ state.activeTurns.set(session.id, Number(payload.turn ?? 0))
2145
3483
  const conversationContext = recentConversation(session)
2146
3484
  const existing = state.records.get(session.id)
2147
3485
  if (existing?.plan?.createdTurn === payload.turn) return downstream
@@ -2315,6 +3653,10 @@ export function updateToolOutputSchema() {
2315
3653
  subtaskId: { type: 'string' },
2316
3654
  status: { type: 'string' },
2317
3655
  stats: { type: 'object' },
3656
+ deliveryReady: { type: 'boolean' },
3657
+ deliveryBlockers: { type: 'array' },
3658
+ deliveryRemaining: { type: 'array' },
3659
+ hint: { type: 'string' },
2318
3660
  },
2319
3661
  required: ['ok'],
2320
3662
  additionalProperties: true,
@@ -2329,6 +3671,14 @@ export function cancelToolOutputSchema() {
2329
3671
  planId: { type: 'string' },
2330
3672
  phase: { type: 'string' },
2331
3673
  reason: { type: 'string' },
3674
+ /*
3675
+ * [1.8.14] `cancelRecorded` is the difference between "the UI says
3676
+ * cancelled" and "a restart will still say cancelled". A cancel whose
3677
+ * durable append failed reports false so the caller does not build on it.
3678
+ */
3679
+ cancelRecorded: { type: 'boolean' },
3680
+ alreadyCancelled: { type: 'boolean' },
3681
+ abortedRunning: { type: 'boolean' },
2332
3682
  },
2333
3683
  required: ['ok'],
2334
3684
  additionalProperties: true,
@@ -2350,6 +3700,13 @@ export function statusToolOutputSchema() {
2350
3700
  statuses: { type: 'array' },
2351
3701
  errors: { type: 'array' },
2352
3702
  resumeLimit: { type: 'number' },
3703
+ version: { type: 'string' },
3704
+ // [1.8.14] Loaded-build identity: version alone cannot prove which bytes
3705
+ // the process is running after a rebuild or a profile recomposition.
3706
+ runtime: { type: 'object' },
3707
+ deliveryReady: { type: 'boolean' },
3708
+ deliveryBlockers: { type: 'array' },
3709
+ deliveryRemaining: { type: 'array' },
2353
3710
  hint: { type: 'string' },
2354
3711
  error: { type: 'string' },
2355
3712
  code: { type: 'string' },
@@ -2370,6 +3727,18 @@ export function dispatchToolOutputSchema() {
2370
3727
  running: { type: 'boolean' },
2371
3728
  joined: { type: 'boolean' },
2372
3729
  mode: { type: 'string' },
3730
+ /*
3731
+ * [1.8.7] `ok:true` used to be the only success signal, so a budget pause
3732
+ * (10/13) read as a finished dispatch. `complete` is the field the model
3733
+ * must test before it presents anything.
3734
+ */
3735
+ complete: { type: 'boolean' },
3736
+ remaining: { type: 'integer' },
3737
+ deliveryReady: { type: 'boolean' },
3738
+ deliveryBlockers: { type: 'array' },
3739
+ deliveryRemaining: { type: 'array' },
3740
+ version: { type: 'string' },
3741
+ runtime: { type: 'object' },
2373
3742
  elapsedMs: { type: 'number' },
2374
3743
  statuses: { type: 'array' },
2375
3744
  phase: { type: 'string' },