dsh-workplan 1.8.18 → 1.10.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  */
14
14
 
15
15
  import { randomUUID } from 'node:crypto'
16
- import { existsSync } from 'node:fs'
16
+ import { existsSync, statSync } from 'node:fs'
17
17
  import { isAbsolute, resolve } from 'node:path'
18
18
 
19
19
  import {
@@ -36,6 +36,7 @@ import {
36
36
  flattenSubtasks,
37
37
  isRecord,
38
38
  isSocialMessage,
39
+ isTerminalPhase,
39
40
  isStatusQuestion,
40
41
  isVagueContinuation,
41
42
  makeUserMessage,
@@ -43,6 +44,7 @@ import {
43
44
  messageText,
44
45
  readySubtasks,
45
46
  MAX_PLAN_RESUMES,
47
+ PRESENT_DENY_CODES,
46
48
  canResumePlan,
47
49
  resetBlockedStatuses,
48
50
  parseCancelMessage,
@@ -54,11 +56,16 @@ import {
54
56
  validatePlan,
55
57
  applyResultStatuses,
56
58
  adjudicateResult,
59
+ activeDenyCode,
57
60
  MAX_CONVERSATION_CHARS,
58
61
  parseUpdateMessage,
59
62
  buildUpdateMessage,
60
63
  } from './plan.js'
64
+ import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
65
+ import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
66
+ import { supersedePlanRecord } from './supersede.js'
61
67
  import { createProgressWatchdog, describeError } from './watchdog.js'
68
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js'
62
69
 
63
70
  /**
64
71
  * [1.8.18] How many subtasks the plan *defines*.
@@ -513,6 +520,126 @@ export function probeInterruptedEvidence(output: any, subtask: any, cwd: any, ar
513
520
  return { artifacts, missingArtifacts }
514
521
  }
515
522
 
523
+ /**
524
+ * [1.10.6] Fingerprint the files a timed-out attempt already wrote.
525
+ *
526
+ * T6 (G3) found that the retry decision never looked at the disk: a second
527
+ * attempt could silently overwrite a deliverable the first attempt had already
528
+ * produced, turning "the child stopped early" into "the deliverable was
529
+ * rewritten". This snapshot (path + size + mtime) is the record the retry is
530
+ * compared against.
531
+ *
532
+ * A missing file is not a conflict — it simply has no fingerprint. `stat` is
533
+ * injectable so the check can be tested without touching the real filesystem.
534
+ */
535
+ export function fingerprintArtifacts(refs: any, cwd: any, stat: any = statSync) {
536
+ const list = Array.isArray(refs) ? refs : []
537
+ const out: { ref: string; size: number; mtimeMs: number }[] = []
538
+ const seen = new Set<string>()
539
+ for (const item of list) {
540
+ const ref = typeof item === 'string' ? item.trim() : ''
541
+ if (!ref || seen.has(ref)) continue
542
+ seen.add(ref)
543
+ const target = resolveArtifactPath(ref, cwd)
544
+ if (!target) continue
545
+ try {
546
+ const info = stat(target)
547
+ if (!info) continue
548
+ out.push({ ref, size: Number(info.size), mtimeMs: Number(info.mtimeMs) })
549
+ } catch {
550
+ // Missing or unreadable: nothing to protect, and not a conflict.
551
+ }
552
+ }
553
+ return out
554
+ }
555
+
556
+ /**
557
+ * [1.10.6] Which landed artifacts changed since the snapshot was taken.
558
+ *
559
+ * Size or mtime differing is enough to call it a conflict: the file the first
560
+ * attempt produced is no longer the file on disk, so a retry that rewrites it
561
+ * would destroy work rather than finish it.
562
+ */
563
+ export function diffArtifactFingerprints(before: any, after: any) {
564
+ const previous = new Map<string, any>()
565
+ for (const item of Array.isArray(before) ? before : []) {
566
+ if (item && typeof item.ref === 'string') previous.set(item.ref, item)
567
+ }
568
+ const conflicts: string[] = []
569
+ for (const item of Array.isArray(after) ? after : []) {
570
+ if (!item || typeof item.ref !== 'string') continue
571
+ const recorded = previous.get(item.ref)
572
+ if (!recorded) continue
573
+ if (recorded.size !== item.size || recorded.mtimeMs !== item.mtimeMs) conflicts.push(item.ref)
574
+ }
575
+ return conflicts
576
+ }
577
+
578
+ /**
579
+ * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
580
+ */
581
+ export function findSubtaskById(plan: any, subtaskId: string) {
582
+ for (const stage of Array.isArray(plan?.stages) ? plan.stages : []) {
583
+ for (const subtask of Array.isArray(stage?.subtasks) ? stage.subtasks : []) {
584
+ if (subtask?.id === subtaskId) return subtask
585
+ }
586
+ }
587
+ return null
588
+ }
589
+
590
+ /**
591
+ * [1.8.19] A hard per-subtask timeout must not erase what the child already wrote.
592
+ *
593
+ * Real incident (2026-10-31 23:23:38): T11/T12 were aborted by the 900 s
594
+ * per-subtask ceiling four seconds after their deliverables had landed
595
+ * (T11 32,996 B report + 140-row index; T12 51,547 B report). The parent only
596
+ * saw `blocked / 达到执行上限`, with no hint that the files existed, so the same
597
+ * work would be redone from scratch. This probe records the landed declared
598
+ * outputs in the status row and in the error text — it does not change the
599
+ * verdict (a timeout is still `blocked`), it only stops the evidence loss.
600
+ */
601
+ export function timeoutBlockedPatch(subtask: any, cwd: any, message: string, artifactExists: any = existsSync) {
602
+ const evidence = probeInterruptedEvidence(null, subtask, cwd, artifactExists)
603
+ const landed = evidence.artifacts.filter((item: any) => item?.exists === true).map((item: any) => String(item.ref))
604
+ const artifactNote = landed.length > 0
605
+ ? `;该步声明的产物已在盘上:${landed.slice(0, 6).join('、')}(先核对,不要当作从未运行)`
606
+ : ''
607
+ return {
608
+ patch: {
609
+ status: 'blocked',
610
+ progress: 100,
611
+ finishedAt: Date.now(),
612
+ error: message + artifactNote,
613
+ summary: truncate(`未完成:${message}${artifactNote}`, 3000),
614
+ ...(evidence.artifacts.length > 0 ? { artifacts: evidence.artifacts } : {}),
615
+ ...(evidence.missingArtifacts.length > 0 ? { missingArtifacts: evidence.missingArtifacts } : {}),
616
+ },
617
+ landed,
618
+ }
619
+ }
620
+
621
+ /**
622
+ * [1.8.19] The round budget reset used to erase every trace of the attempt.
623
+ *
624
+ * The 20-minute `TOTAL_TIMEOUT` branch resets unfinished rows to `pending`, and
625
+ * `applyStatus` (by design) clears `childId / startedAt / finishedAt`. In the
626
+ * 2026-10-31 incident T10 had run for ~19 minutes and had already written its
627
+ * coverage report at 23:06:26 when the budget fired at 23:07:25; the card then
628
+ * said "not started" and the user asked "why did T10 stop by itself". The
629
+ * attempt provenance and any landed declared outputs now travel in the error
630
+ * text, so the reset stays a pause but stops being an erasure.
631
+ */
632
+ export function budgetResetError(item: any, subtask: any, cwd: any, artifactExists: any = existsSync) {
633
+ const landed = probeInterruptedArtifacts(null, subtask, cwd, artifactExists)
634
+ const parts = ['本轮预算用尽,等待续跑']
635
+ if (item?.childId) parts.push(`上一轮子会话 ${String(item.childId).slice(0, 8)}`)
636
+ if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
637
+ parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`)
638
+ }
639
+ if (landed.length > 0) parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`)
640
+ return parts.join(';')
641
+ }
642
+
516
643
  /**
517
644
  * Turn one child output into a status verdict.
518
645
  *
@@ -547,15 +674,37 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
547
674
  * Retry policy for one child attempt.
548
675
  *
549
676
  * A wedged child (no event for the whole idle window) is worth one fresh
550
- * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
551
- * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
552
- * more than one idle window left, otherwise the retry itself would just be
553
- * killed by the same watchdog.
677
+ * attempt. `CHILD_NOT_COMPLETED` is retried only while there is more than one
678
+ * idle window left, otherwise the retry itself would just be killed by the same
679
+ * watchdog.
680
+ *
681
+ * [1.10.3] 单个子任务撞上 900 秒硬上限时,只要整轮预算还够再跑一轮,就自动重试
682
+ * 一次。用户 2026-11-01 的质疑是对的:此前这一支被无条件 `return false`,
683
+ * 于是「预算没花完、只是这一步慢了」也被判成阻塞,必须等主 Agent 人工改判或
684
+ * 重新派发——而 `attempt` 已经是 1、产物又都在盘上,重跑一次往往就能过。
685
+ *
686
+ * 仍然**不自动重试**的两种情况,理由不变:
687
+ * - `TOTAL_TIMEOUT`:整轮预算已经用光,重试必然再被同一把闸刀砍掉,只会空耗;
688
+ * - `ABORTED`:那是「有人决定停」而不是「跑不完」,自动重来等于违背决定。
554
689
  */
555
690
  export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, idleTimeoutMs: any) {
556
691
  if (attempt >= 2) return false
557
692
  const code = error?.code
558
- if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
693
+ if (code === 'CHILD_TIMEOUT') {
694
+ /*
695
+ * 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
696
+ *
697
+ * [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
698
+ * 出厂配置是 ceiling=900s / idle=300s / round=1200s,撞上限后剩下约
699
+ * 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
700
+ * 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
701
+ * 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
702
+ * `tests/workplan-retry-feedback.test.ts` 的 60s 反例与 600s 正例都仍然成立。
703
+ */
704
+ const floor = 120000
705
+ return Number(remainingMs) > floor
706
+ }
707
+ if (code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
559
708
  if (/aborted|refusal/i.test(String(error?.message ?? ''))) return false
560
709
  if (code === 'CHILD_STALLED') return true
561
710
  if (code === 'CHILD_NOT_COMPLETED') {
@@ -567,7 +716,17 @@ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, i
567
716
  async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
568
717
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
569
718
  let lastError: any = null
570
- let lastFailure: any = null
719
+ /*
720
+ * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
721
+ * even though this function is entered afresh. `attemptOffset` keeps the
722
+ * numbering honest (`第 2 次尝试`) and, with the loop condition below, keeps
723
+ * the cap at two real activations instead of letting the new call spend its
724
+ * own two.
725
+ */
726
+ const firstAttempt = Number.isInteger(options.attemptOffset) && options.attemptOffset > 1
727
+ ? options.attemptOffset
728
+ : 1
729
+ let lastFailure: any = options.priorFailure ?? null
571
730
  /*
572
731
  * [1.8.6] The interrupt has to outlive the thrown error.
573
732
  *
@@ -584,7 +743,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
584
743
  startedAt: Date.now(),
585
744
  }, guard)) return
586
745
 
587
- for (let attempt = 1; attempt <= 2; attempt += 1) {
746
+ for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
588
747
  if (guard.timedOut) return
589
748
  interruptedEvidence = null
590
749
  if (parentSignal.aborted) throw abortError()
@@ -748,7 +907,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
748
907
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
749
908
  continue
750
909
  }
751
- if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
910
+ /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
911
+ if (!isAbort && remaining <= idleTimeoutMs) {
752
912
  record.errors = [
753
913
  ...(record.errors ?? []),
754
914
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
@@ -800,36 +960,59 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
800
960
  }
801
961
 
802
962
  /*
803
- * Runs one subtask under a deadline that belongs to that subtask alone.
963
+ * One attempt under a deadline that belongs to that attempt alone.
964
+ *
965
+ * [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
966
+ * *fresh* timer. The old code armed a single timer for the whole subtask (shared
967
+ * by both attempts), so even once the retry decision became reachable the second
968
+ * attempt would have had no time left — a patch that changes nothing.
804
969
  *
805
- * The subtask timer is a full settlement guarantee, not just an abort hint: if
806
- * the child activation ignores its abort signal, or never settles at all, the
807
- * race below still resolves, that subtask is recorded as blocked, and the
808
- * dispatcher keeps scheduling the rest of the DAG. This function never throws
809
- * on a per-subtask timeout, so one slow child can no longer blanket-block the
810
- * whole plan — only that subtask (and its real dependents) is affected.
970
+ * The timer remains a full settlement guarantee, not just an abort hint: if the
971
+ * child activation ignores its abort signal, or never settles at all, the race
972
+ * below still resolves, the subtask is recorded as blocked, and the dispatcher
973
+ * keeps scheduling the rest of the DAG.
811
974
  */
812
- async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
813
- const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
975
+ async function runSubtaskAttempt(
976
+ ctx: any,
977
+ record: any,
978
+ stage: any,
979
+ subtask: any,
980
+ options: any,
981
+ timeoutMs: number,
982
+ ) {
814
983
  const child = createChildController(options.parentSignal)
815
984
  const guard: SubtaskGuard = { timedOut: false }
816
985
  let timer: ReturnType<typeof setTimeout> | null = null
986
+ let ceilingFired = false
987
+ // [1.10.6] What the ceiling left on disk, in the words of the same probe the
988
+ // blocked row records. The retry is compared against exactly this list.
989
+ let ceilingLanded: string[] = []
990
+ /*
991
+ * [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
992
+ *
993
+ * The first cut of this check fingerprinted the same refs twice, back to back,
994
+ * immediately before the retry. Two reads of the same instant can never
995
+ * differ, so the conflict branch was unreachable in production (only a test
996
+ * injecting a mutating `stat` could reach it). The record must be taken while
997
+ * the timeout is being recorded; the pre-retry read is compared against it.
998
+ */
999
+ let ceilingFingerprint: any[] = []
1000
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
817
1001
  const deadlinePromise = new Promise<void>((resolve) => {
818
1002
  timer = setTimeout(() => {
1003
+ ceilingFired = true
819
1004
  guard.timedOut = true
820
1005
  // Reached only when the child ignored both its idle window and its
821
1006
  // abort signal; the message says so, otherwise the cause looks like a
822
1007
  // plain "too slow" and the next investigation goes down the wrong path.
823
- const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`
1008
+ const message = `子任务 ${subtask.id} 达到执行上限(${timeoutMs}ms),已强制结束`
824
1009
  try {
825
- record.statuses = applyStatus(record.statuses, subtask.id, {
826
- status: 'blocked',
827
- progress: 100,
828
- finishedAt: Date.now(),
829
- error: message,
830
- summary: truncate(`未完成:${message}`, 3000),
831
- })
832
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${message}`].slice(-20)
1010
+ // [1.8.19] Keep the evidence of what already landed on disk.
1011
+ const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
1012
+ ceilingLanded = Array.isArray(landed) ? landed : []
1013
+ ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat)
1014
+ record.statuses = applyStatus(record.statuses, subtask.id, patch)
1015
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
833
1016
  record.updatedAt = Date.now()
834
1017
  } catch (error: any) {
835
1018
  record.errors = [
@@ -843,13 +1026,13 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
843
1026
  child.disposeListener()
844
1027
  resolve()
845
1028
  }
846
- }, childTimeoutMs)
1029
+ }, timeoutMs)
847
1030
  timer.unref?.()
848
1031
  })
849
1032
  try {
850
1033
  // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
851
1034
  // swallowing it here is why an interrupted child looked like any failure.
852
- return await Promise.race([
1035
+ const outcome = await Promise.race([
853
1036
  executeSubtask(ctx, record, stage, subtask, {
854
1037
  ...options,
855
1038
  child,
@@ -857,6 +1040,7 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
857
1040
  }),
858
1041
  deadlinePromise,
859
1042
  ])
1043
+ return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint }
860
1044
  } finally {
861
1045
  if (timer) {
862
1046
  clearTimeout(timer)
@@ -867,6 +1051,88 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
867
1051
  }
868
1052
  }
869
1053
 
1054
+ /*
1055
+ * Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
1056
+ * round budget can still pay for a second attempt (T6 G1/G3/G4).
1057
+ *
1058
+ * The retry is deliberately narrow:
1059
+ * - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
1060
+ * budget timeout stay non-retryable, because retrying them would be killed by
1061
+ * the same guillotine;
1062
+ * - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
1063
+ * - before it starts, the artifacts the first attempt landed are fingerprinted
1064
+ * (path + size + mtime) and re-checked. If any of them changed since the
1065
+ * timeout was recorded, something else owns that file now: the retry is
1066
+ * skipped and the row is marked `artifactConflict` instead of overwriting it.
1067
+ */
1068
+ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
1069
+ const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
1070
+ const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs)
1071
+ if (!first.ceilingFired) return first.outcome
1072
+
1073
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
1074
+ const now = Date.now()
1075
+ const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs
1076
+ const remaining = deadline - now
1077
+ const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms)`
1078
+ /*
1079
+ * [1.8.6] A parent abort outranks a retry: the round is being stopped on
1080
+ * purpose, and a second child would only be aborted on arrival.
1081
+ */
1082
+ if (options.parentSignal?.aborted) return first.outcome
1083
+ if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
1084
+ record.errors = [
1085
+ ...(record.errors ?? []),
1086
+ `${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
1087
+ ].slice(-20)
1088
+ return first.outcome
1089
+ }
1090
+ /*
1091
+ * [1.10.6] T6 G3: never retry over work that already exists.
1092
+ *
1093
+ * `ceilingFingerprint` was taken the moment the ceiling fired (inside the
1094
+ * timeout callback); the same refs are re-read right before the retry starts.
1095
+ * A size or mtime difference means the file was written by somebody else in
1096
+ * between, so a retry would overwrite it rather than finish it.
1097
+ */
1098
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
1099
+ const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat)
1100
+ const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current)
1101
+ const row: any = Array.isArray(record.statuses)
1102
+ ? record.statuses.find((item: any) => item.subtaskId === subtask.id)
1103
+ : null
1104
+ if (conflicts.length > 0) {
1105
+ const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`
1106
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1107
+ artifactConflict: conflicts,
1108
+ error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
1109
+ })
1110
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20)
1111
+ record.updatedAt = Date.now()
1112
+ return first.outcome
1113
+ }
1114
+
1115
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1116
+ status: 'in_progress',
1117
+ progress: 15,
1118
+ // Clearing `error` moves the timeout text to `lastError` (applyStatus does
1119
+ // that move), so the row no longer claims "blocked" while it is retrying.
1120
+ error: null,
1121
+ })
1122
+ record.errors = [
1123
+ ...(record.errors ?? []),
1124
+ `${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
1125
+ ].slice(-20)
1126
+ record.updatedAt = Date.now()
1127
+ const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining))
1128
+ const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
1129
+ ...options,
1130
+ attemptOffset: 2,
1131
+ priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已强制结束` },
1132
+ }, retryTimeoutMs)
1133
+ return second.outcome
1134
+ }
1135
+
870
1136
  async function runWithConcurrency(items: any, limit: any, worker: any) {
871
1137
  let cursor = 0
872
1138
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
@@ -1014,7 +1280,13 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1014
1280
  `第 ${record.resumeCount} 次续跑:已重置 ${resume.failed} 个受阻子任务(已完成的不重跑)`,
1015
1281
  ].slice(-20)
1016
1282
  } else {
1017
- record.errors = (record.errors ?? []).filter((line: string) => !/预算|续跑/.test(String(line))).slice(-20)
1283
+ /*
1284
+ * [1.10.4] 保留自动续跑的审计行:它们必然含「续跑/预算」字样,旧过滤器
1285
+ * 会把「为什么自动续跑、停在哪个判定码」一起擦掉,正好毁掉事后取证。
1286
+ */
1287
+ record.errors = (record.errors ?? [])
1288
+ .filter((line: string) => !/预算|续跑/.test(String(line)) || String(line).includes('[auto-resume]'))
1289
+ .slice(-20)
1018
1290
  }
1019
1291
  }
1020
1292
  const parentSignal = signal
@@ -1097,6 +1369,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1097
1369
  conversationContext,
1098
1370
  strictEvidence: options.strictEvidence,
1099
1371
  artifactExists: options.artifactExists,
1372
+ // [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
1373
+ // use it so the conflict branch is provable without real files.
1374
+ artifactStat: options.artifactStat,
1100
1375
  })
1101
1376
  // [1.8.6] Remember which failures were interrupts, so the cascade below
1102
1377
  // can leave their dependents pending instead of blaming them.
@@ -1179,9 +1454,12 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1179
1454
  let reset = record.statuses
1180
1455
  for (const item of record.statuses) {
1181
1456
  if (item.status === 'done') continue
1457
+ // [1.8.19] Carry the aborted attempt's provenance and landed files into
1458
+ // the pause reason instead of silently erasing them.
1459
+ const definition = findSubtaskById(record.plan, item.subtaskId)
1182
1460
  reset = applyStatus(reset, item.subtaskId, {
1183
1461
  status: 'pending',
1184
- error: '本轮预算用尽,等待续跑',
1462
+ error: budgetResetError(item, definition, options.cwd, options.artifactExists),
1185
1463
  })
1186
1464
  }
1187
1465
  record.statuses = reset
@@ -1349,7 +1627,19 @@ function serialisePlan(record: any, session: any) {
1349
1627
  : plan
1350
1628
  ? createStatuses(plan)
1351
1629
  : []
1352
- const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses)
1630
+ /*
1631
+ * [1.10.0] 分母来自计划定义,并允许「明细行少于定义」时按 pending 补齐。
1632
+ * `definedSubtaskCount` 对畸形计划返回 MAX_SAFE_INTEGER,那种情况下退回
1633
+ * 「只数明细行」,避免把一个坏计划直接判成 0/天文数字。
1634
+ */
1635
+ const defined = plan ? definedSubtaskCount(plan) : 0
1636
+ const expectedTotal = Number.isFinite(defined) && defined > 0 && defined < Number.MAX_SAFE_INTEGER
1637
+ ? defined
1638
+ : undefined
1639
+ const snapshot = derivePlanSnapshot(
1640
+ turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses,
1641
+ expectedTotal,
1642
+ )
1353
1643
  const statuses = snapshot.statuses
1354
1644
  const stats = snapshot.stats
1355
1645
  /*
@@ -1411,7 +1701,18 @@ function serialisePlan(record: any, session: any) {
1411
1701
  ...(violations.length ? { violations } : {}),
1412
1702
  degraded: record.degraded === true,
1413
1703
  error: record.error ? truncate(record.error, 2000) : null,
1414
- errors: (record.errors ?? []).slice(-20),
1704
+ /*
1705
+ * [1.10.0] C-18:「已结束 / 已完成」的计划不再把上一轮的失败文本摆在首页。
1706
+ *
1707
+ * 1.9.1 把 `record.errors`("本轮执行预算已到:已完成 9/13…" 之类)无条件
1708
+ * 下发,界面又无条件渲染,于是 13/13 完成的那一帧下面还挂着一句「这件事没有
1709
+ * 做完」。现在:计划已 done 或 cancelled 时,这批文本改挂 `archivedErrors`,
1710
+ * 供折叠区/审计使用;`errors` 只在计划仍需处理时下发。
1711
+ */
1712
+ errors: phase === 'done' || phase === 'cancelled' ? [] : (record.errors ?? []).slice(-20),
1713
+ ...(phase === 'done' || phase === 'cancelled'
1714
+ ? { archivedErrors: (record.errors ?? []).slice(-20) }
1715
+ : {}),
1415
1716
  createdAt: record.createdAt ?? plan?.createdAt ?? session.header.createdAt,
1416
1717
  updatedAt: record.updatedAt ?? Date.now(),
1417
1718
  createdTurn: plan?.createdTurn ?? record.createdTurn ?? null,
@@ -1552,6 +1853,12 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1552
1853
  resultSeen: boolean
1553
1854
  resumeCount: number
1554
1855
  cancelled: boolean
1856
+ /*
1857
+ * [1.9.0] 被取代(责任已转移)。与 cancelled 互斥。本补丁只做读取、
1858
+ * 判定与拒绝;写入路径(V1–V8 核验 + 用户确认)见规则文档 §6,属下一批。
1859
+ */
1860
+ superseded: boolean
1861
+ supersededBy: any
1555
1862
  /*
1556
1863
  * [1.8.17] The durable result message carries the round's failure lines.
1557
1864
  * Replay used to drop them, and the reconstructed record then had no
@@ -1584,6 +1891,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1584
1891
  resultSeen: false,
1585
1892
  resumeCount: 0,
1586
1893
  cancelled: false,
1894
+ superseded: false,
1895
+ supersededBy: undefined,
1587
1896
  errors: [],
1588
1897
  }
1589
1898
  snapshots.set(plan.planId, snap)
@@ -1688,7 +1997,26 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1688
1997
  const cancel = parseCancelMessage(event.data)
1689
1998
  if (cancel && typeof cancel.planId === 'string') {
1690
1999
  const snap = snapshots.get(cancel.planId)
1691
- if (snap) snap.cancelled = true
2000
+ if (snap) {
2001
+ /*
2002
+ * [1.9.0] disposition='superseded' 的信封表示「责任已转移」,不是
2003
+ * 用户撤销。旧解析器只校验 kind,因此该字段对新旧版本都安全:旧版
2004
+ * 按 cancelled 读(不可派发、不可交付),不会复活成 active。
2005
+ */
2006
+ if (cancel.disposition === 'superseded') {
2007
+ snap.superseded = true
2008
+ snap.supersededBy = cancel.supersededBy
2009
+ /*
2010
+ * [1.9.2] 互斥(T6):取代永远发生在取消之后,所以日志里两条信封
2011
+ * 都在。只加 superseded 不清 cancelled,冷启动记录就会变成「既已
2012
+ * 取消、又被取代」,与 live 记录(`supersedePlanRecord` 写入时
2013
+ * 把 cancelled 置 false)分叉 —— 这正是写侧收敛要杜绝的那类分叉。
2014
+ */
2015
+ snap.cancelled = false
2016
+ } else {
2017
+ snap.cancelled = true
2018
+ }
2019
+ }
1692
2020
  }
1693
2021
  } else if (event.type === 'tool/call') {
1694
2022
  /*
@@ -1776,10 +2104,17 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1776
2104
  const resultPhase = chosen.resultPhase
1777
2105
  const resultSeen = chosen.resultSeen
1778
2106
  const resumeCount = chosen.resumeCount
1779
- const cancelled = chosen.cancelled
2107
+ const superseded = chosen.superseded
2108
+ /*
2109
+ * [1.9.2] 终态互斥(T6):superseded 与 cancelled 不会同时成立。手写/旧版
2110
+ * 日志里可能出现「supersede 信封之后又有一条取消信封」,此时按终态优先级
2111
+ * 只认 superseded(fail-closed:被取代依然不可派发、不可交付)。
2112
+ */
2113
+ const cancelled = chosen.cancelled && !superseded
1780
2114
  let phase = planPhase(statuses, resultSeen)
1781
2115
  if (resultPhase === 'paused' && statuses.some((item: any) => item.status !== 'done')) phase = 'paused'
1782
2116
  if (cancelled) phase = 'cancelled'
2117
+ if (superseded) phase = 'superseded'
1783
2118
  /*
1784
2119
  * [1.5.2] 回放也必须走同一套对账。
1785
2120
  *
@@ -1824,9 +2159,17 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1824
2159
  * whether that cancellation is durably recorded. For replay they are the
1825
2160
  * same; the live `cancelPlan` uses `cancelRecorded` to make a second
1826
2161
  * cancel a no-op instead of appending a duplicate message (N8).
2162
+ *
2163
+ * [1.9.2] 被取代的计划同样有一条已落盘的终态记录(V3 要求先取消才允许
2164
+ * 取代),因此 cancelRecorded 在 superseded 时为 true —— 与 live 记录一致
2165
+ * (`supersedePlanRecord` 保留先前的 cancelRecorded)。`supersedeRecorded`
2166
+ * 是取代信封的写入见证,补齐后普通取消的拒绝体在冷启动/热路径上字段相同。
1827
2167
  */
1828
2168
  cancelled,
1829
- cancelRecorded: cancelled,
2169
+ cancelRecorded: cancelled || superseded,
2170
+ superseded,
2171
+ supersedeRecorded: superseded,
2172
+ supersededBy: superseded ? chosen.supersededBy : undefined,
1830
2173
  }
1831
2174
  }
1832
2175
 
@@ -1911,6 +2254,16 @@ export type WorkplanRuntimeOptions = {
1911
2254
  totalTimeoutMs?: number
1912
2255
  /** How many times a blocked plan may be resumed. */
1913
2256
  maxResumes?: number
2257
+ /**
2258
+ * [1.10.4] 整轮预算到点后自动开始下一轮。**默认关闭**:默认值来自
2259
+ * `AUTO_RESUME_DEFAULTS.enabled=false`,必须由宿主显式打开。
2260
+ *
2261
+ * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败),
2262
+ * 也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2263
+ */
2264
+ autoResume?: boolean
2265
+ /** 自动续跑轮次上限(0–4,默认 2)。 */
2266
+ autoResumeMaxAttempts?: number
1914
2267
  /**
1915
2268
  * [1.8.13] Package version, supplied by the host from its `meta.version`.
1916
2269
  *
@@ -1992,6 +2345,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
1992
2345
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
1993
2346
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
1994
2347
  : MAX_PLAN_RESUMES,
2348
+ autoResume: {
2349
+ enabled: options.autoResume === true,
2350
+ maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2351
+ },
1995
2352
  }
1996
2353
 
1997
2354
  async function onPreStep(payload: any, next: any) {
@@ -2078,6 +2435,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2078
2435
  if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2079
2436
  record = adoptRequestedPlan(session, record, args?.planId)
2080
2437
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
2438
+ // [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
2439
+ clearAutoResumeTimer(record, 'manual-update')
2081
2440
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : ''
2082
2441
  if (!subtaskId) throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK')
2083
2442
  const status = typeof args?.status === 'string' ? args.status : ''
@@ -2225,9 +2584,51 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2225
2584
  if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2226
2585
  record = adoptRequestedPlan(session, record, args?.planId)
2227
2586
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
2587
+ /*
2588
+ * [1.9.2] superseded 的唯一写入入口(T6)。
2589
+ *
2590
+ * `disposition` 只有两个合法取值:省略/'cancelled' 走既有取消语义(返回体
2591
+ * 与 1.8.19 逐字相同);'superseded' 交给 `supersedePlanRecord`(V1–V8
2592
+ * 复算 + digest + durable 信封)。其他取值一律拒绝:静默忽略一个拼错的
2593
+ * disposition 会把「想取代」写成「取消」,而两者的读侧判定完全不同。
2594
+ */
2595
+ const disposition = args?.disposition
2596
+ if (disposition !== undefined && disposition !== 'cancelled' && disposition !== 'superseded') {
2597
+ throw new PlanError(
2598
+ `disposition 只能是 cancelled 或 superseded(收到 ${String(disposition)})`,
2599
+ 'INVALID_DISPOSITION',
2600
+ )
2601
+ }
2602
+ if (disposition === 'superseded') {
2603
+ const result = supersedePlanRecord(session, record, args, { reconstruct: reconstructFromSession })
2604
+ state.records.set(session.id, record)
2605
+ return result
2606
+ }
2607
+ /*
2608
+ * [1.9.2] 被取代的计划不允许被普通取消静默改回 cancelled。
2609
+ *
2610
+ * 旧路径会追加第二条不带 disposition 的取消信封:live 变 cancelled,
2611
+ * replay 却因同一 planId 先读到 superseded 而仍是 superseded —— 又一种
2612
+ * live/replay 分叉。行政撤销(E6)需要用户明确要求并写入新的处置记录,
2613
+ * 本版本不实现,因此这里 fail-closed 并给出可执行说明。
2614
+ */
2615
+ if (record.phase === 'superseded' || record.superseded === true) {
2616
+ return {
2617
+ ok: false,
2618
+ planId: record.plan.planId,
2619
+ phase: 'superseded',
2620
+ code: 'SUPERSEDED_LOCKED',
2621
+ error: '计划已被取代:不能静默改回 cancelled(行政撤销 E6 需要用户明确要求并写入新的处置记录,本版本未实现)',
2622
+ hint: '被取代不等于完成:不得调用 present、不得声称“已完成”。如需撤销该处置,请先向用户确认,再由主 Agent 走审计流程。',
2623
+ cancelRecorded: record.supersedeRecorded === true,
2624
+ stats: derivePlanSnapshot(record.statuses).stats,
2625
+ }
2626
+ }
2228
2627
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2229
2628
  ? args.reason.trim()
2230
2629
  : '用户取消'
2630
+ // [1.10.4] 取消是终态:必须撤销已排期的自动续跑,否则定时器会在取消之后复活计划。
2631
+ clearAutoResumeTimer(record, 'cancelled')
2231
2632
  /*
2232
2633
  * [1.5.2] 已完成即终态:取消不再把 100% 的计划改写成「已取消」。
2233
2634
  *
@@ -2359,6 +2760,218 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2359
2760
  }
2360
2761
  }
2361
2762
 
2763
+ /*
2764
+ * [1.10.4][auto-resume] 自动续跑的记账与排期。
2765
+ *
2766
+ * 为什么在工具层而不是 `dispatchPlan` 里:被整轮预算中止时,这一轮已经没有
2767
+ * 预算可用,轮内重试必然再被同一把闸刀砍掉(`shouldRetryAttempt` 对
2768
+ * `TOTAL_TIMEOUT` / `ABORTED` 恒为 false 是正确的)。能重试的只有「下一轮」:
2769
+ * 新预算、新截止时间,未完成项由 `resetBlockedStatuses` 放回 pending,
2770
+ * done 项永不重跑。所以调度点属于「谁结束了一轮」,也就是这里。
2771
+ *
2772
+ * 所有停止分支都由纯函数 `decideAutoResume` 判定,本层只负责:
2773
+ * - 记录 done 水位与连续无进展轮数(防止空转);
2774
+ * - 用 unref 的定时器排期,并在取消/人工派发/进程销毁时撤销;
2775
+ * - 起跑前再核对一次记录身份与阶段(定时器期间状态可能已变)。
2776
+ */
2777
+ function autoResumeBook(record: any) {
2778
+ if (!record.autoResume || typeof record.autoResume !== 'object') {
2779
+ record.autoResume = {
2780
+ attempt: 0,
2781
+ noProgressRounds: 0,
2782
+ doneBefore: null,
2783
+ nextAt: null,
2784
+ timer: null,
2785
+ lastDecision: null,
2786
+ history: [],
2787
+ }
2788
+ }
2789
+ return record.autoResume
2790
+ }
2791
+
2792
+ function clearAutoResumeTimer(record: any, reason: string) {
2793
+ const book = record?.autoResume
2794
+ if (!book) return false
2795
+ book.nextAt = null
2796
+ if (!book.timer) return false
2797
+ clearTimeout(book.timer)
2798
+ book.timer = null
2799
+ book.lastStopReason = reason
2800
+ return true
2801
+ }
2802
+
2803
+ function autoResumeView(record: any) {
2804
+ const book = record?.autoResume
2805
+ return {
2806
+ enabled: limits.autoResume.enabled,
2807
+ attempt: Number(book?.attempt ?? 0),
2808
+ maxAttempts: limits.autoResume.maxAttempts,
2809
+ armed: Boolean(book?.timer),
2810
+ nextInMs: book?.nextAt ? Math.max(0, Number(book.nextAt) - Date.now()) : null,
2811
+ lastCode: book?.lastDecision?.code ?? null,
2812
+ lastReason: book?.lastDecision?.reason ?? null,
2813
+ lastStopReason: book?.lastStopReason ?? null,
2814
+ }
2815
+ }
2816
+
2817
+ /**
2818
+ * 在一轮结束后决定是否再开一轮。
2819
+ *
2820
+ * @param record - 当前计划记录。
2821
+ * @param session - 根会话(结果消息与子 Agent 都归属它)。
2822
+ * @param base - 本轮派发的可复用参数(agent / modelSelection / cwd / conversationContext)。
2823
+ */
2824
+ function armAutoResume(record: any, session: any, base: any) {
2825
+ const book = autoResumeBook(record)
2826
+ clearAutoResumeTimer(record, 'rearmed')
2827
+ const snapshot = derivePlanSnapshot(record.statuses)
2828
+ const stats: any = snapshot.stats ?? {}
2829
+ const statuses: any[] = Array.isArray(record.statuses) ? record.statuses : []
2830
+ const done = Number(stats.done ?? 0)
2831
+ const doneBefore = Number.isFinite(Number(book.doneBefore)) ? Number(book.doneBefore) : done
2832
+ /*
2833
+ * 「有进展」只认新增的 done 行。被预算中止的子任务会把 error 从 pending
2834
+ * 一路写到重置,只有真正完成才会抬高 done;用 done 作水位既不会把
2835
+ * 「重跑一次又失败」误判成进展,也不会因错误文案变化而空转。
2836
+ */
2837
+ if (done > doneBefore) book.noProgressRounds = 0
2838
+ else if (Number(book.attempt ?? 0) > 0) book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1
2839
+ book.doneBefore = done
2840
+ const pending = statuses.filter((item: any) => item?.status === 'pending').length
2841
+ const blocked = statuses.filter((item: any) => item?.status === 'blocked').length
2842
+ /*
2843
+ * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
2844
+ *
2845
+ * T7 实测:`armAutoResume` 在每一轮结束后都会被调用,正常完成的轮也会走到
2846
+ * `PHASE_NOT_PAUSED` 分支,于是每个顺利结束的计划都在 `record.errors` 里多一条
2847
+ * 「[auto-resume] 停止」——把真正需要看的中止信息埋掉。全部 done 且没有
2848
+ * pending/blocked 时,直接静默收尾,不写台账。
2849
+ */
2850
+ if (Number(stats.total ?? 0) > 0 && pending === 0 && blocked === 0 && done === Number(stats.total ?? 0)) {
2851
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code: 'NOTHING_PENDING', reason: '全部子任务已 done,无需自动续跑' }
2852
+ return book.lastDecision
2853
+ }
2854
+ const decision = decideAutoResume({
2855
+ enabled: limits.autoResume.enabled,
2856
+ phase: record.phase,
2857
+ cancelled: record.cancelled === true,
2858
+ degraded: record.degraded === true,
2859
+ planMode: isPlanModeActive(ctx, session),
2860
+ running: Boolean(record.dispatchPromise),
2861
+ total: Number(stats.total ?? 0),
2862
+ done,
2863
+ pending,
2864
+ blocked,
2865
+ attempt: Number(book.attempt ?? 0),
2866
+ maxAttempts: limits.autoResume.maxAttempts,
2867
+ noProgressRounds: Number(book.noProgressRounds ?? 0),
2868
+ stallLimit: AUTO_RESUME_DEFAULTS.stallLimit,
2869
+ baseDelayMs: AUTO_RESUME_DEFAULTS.baseDelayMs,
2870
+ maxDelayMs: AUTO_RESUME_DEFAULTS.maxDelayMs,
2871
+ })
2872
+ book.lastDecision = { at: Date.now(), phase: record.phase, ...decision }
2873
+ book.history = [...(book.history ?? []), {
2874
+ at: Date.now(),
2875
+ phase: record.phase,
2876
+ done,
2877
+ pending,
2878
+ blocked,
2879
+ attempt: Number(book.attempt ?? 0),
2880
+ action: decision.action,
2881
+ code: decision.code,
2882
+ }].slice(-10)
2883
+ if (decision.action !== 'schedule') {
2884
+ /*
2885
+ * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
2886
+ * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
2887
+ */
2888
+ if (decision.code !== 'AUTO_RESUME_DISABLED') {
2889
+ record.errors = [...(record.errors ?? []),
2890
+ `[auto-resume] 停止(${decision.code}):${decision.reason}`].slice(-20)
2891
+ }
2892
+ return decision
2893
+ }
2894
+ const attempt = Number(book.attempt ?? 0) + 1
2895
+ book.attempt = attempt
2896
+ book.nextAt = Date.now() + decision.delayMs
2897
+ record.errors = [...(record.errors ?? []),
2898
+ `[auto-resume] 已排期第 ${attempt}/${limits.autoResume.maxAttempts} 次自动续跑:`
2899
+ + `${Math.round(decision.delayMs / 1000)}s 后开始(本轮预算到点,仍有 ${pending} 项 pending;done 项不重跑)`].slice(-20)
2900
+ const timer = setTimeout(() => {
2901
+ book.timer = null
2902
+ book.nextAt = null
2903
+ try {
2904
+ /*
2905
+ * 排期到点后逐项复核,任何一项不成立都安静退出:定时器活过了一个
2906
+ * 回合,期间用户可能已经取消、主 Agent 可能已经手动派发、页面可能
2907
+ * 已经换了一份计划记录。
2908
+ */
2909
+ /*
2910
+ * [1.10.4 / D1] 复核失败必须留下停止码。
2911
+ *
2912
+ * T5 的 I9:任何一次「本应自动续跑却没有发生」都要可解释。原先这里五个
2913
+ * 分支全是裸 `return`,计划停在 paused 而台账里没有任何痕迹,用户只能再
2914
+ * 做一次考古。现在每个分支都写 `lastStopReason`,并把原因追加到 history。
2915
+ */
2916
+ const stopTimer = (code: string) => {
2917
+ book.lastStopReason = code
2918
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code, reason: '定时器复核未通过' }
2919
+ book.history = [...(book.history ?? []), {
2920
+ at: Date.now(), phase: record.phase, action: 'stop', code,
2921
+ }].slice(-10)
2922
+ return
2923
+ }
2924
+ if (state.records.get(session.id) !== record) return stopTimer('SCHEDULE_REVOKED_RECORD_REPLACED')
2925
+ if (record.dispatchPromise) return stopTimer('SCHEDULE_REVOKED_ALREADY_RUNNING')
2926
+ if (record.cancelled === true) return stopTimer('CANCELLED')
2927
+ if (isTerminalPhase(record.phase)) return stopTimer('PHASE_TERMINAL')
2928
+ if (isPlanModeActive(ctx, session)) return stopTimer('PLAN_MODE')
2929
+ if (record.phase !== 'paused') return stopTimer('PHASE_NOT_PAUSED')
2930
+ const live = derivePlanSnapshot(record.statuses)
2931
+ const livePending = (record.statuses ?? []).filter((item: any) => item?.status === 'pending').length
2932
+ if (Number(live.stats?.total ?? 0) === 0 || livePending === 0) return stopTimer('NOTHING_PENDING')
2933
+ const controller = new AbortController()
2934
+ record.abortRequested = false
2935
+ record.abortDispatch = (reason: string) => {
2936
+ if (!controller.signal.aborted) controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2937
+ }
2938
+ record.dispatchStartedAt = Date.now()
2939
+ // 新一轮必须写一条新的结果消息,否则主 Agent 永远看不到自动续跑的结局。
2940
+ record.resultWritten = false
2941
+ book.doneBefore = Number(live.stats?.done ?? 0)
2942
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2943
+ ...base,
2944
+ signal: controller.signal,
2945
+ childTimeoutMs: limits.childTimeoutMs,
2946
+ idleTimeoutMs: limits.idleTimeoutMs,
2947
+ totalTimeoutMs: limits.totalTimeoutMs,
2948
+ maxResumes: limits.maxResumes,
2949
+ })
2950
+ .then(() => finishRound(record, session))
2951
+ .catch((error: any) => {
2952
+ pushRecordError(record, error)
2953
+ finishRound(record, session)
2954
+ })
2955
+ .finally(() => {
2956
+ record.dispatchPromise = null
2957
+ record.dispatchStartedAt = null
2958
+ record.abortDispatch = null
2959
+ armAutoResume(record, session, base)
2960
+ })
2961
+ ctx.logger?.warn?.(
2962
+ `dsh-workplan: 计划 ${record.plan?.planId ?? '?'} 自动续跑第 ${attempt}/${limits.autoResume.maxAttempts} 轮已开始`
2963
+ + `(remaining ${Number(live.stats?.total ?? 0) - Number(live.stats?.done ?? 0)})`,
2964
+ )
2965
+ } catch (error) {
2966
+ pushRecordError(record, error)
2967
+ ctx.logger?.warn?.(`dsh-workplan: 自动续跑失败:${error instanceof Error ? error.message : String(error)}`)
2968
+ }
2969
+ }, decision.delayMs)
2970
+ timer.unref?.()
2971
+ book.timer = timer
2972
+ return decision
2973
+ }
2974
+
2362
2975
  /**
2363
2976
  * Persist the round result and settle the phase.
2364
2977
  *
@@ -2490,6 +3103,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2490
3103
  statuses: modelStatusLines(snapshot.statuses),
2491
3104
  errors: (record.errors ?? []).slice(-10),
2492
3105
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
3106
+ // [1.10.4] 自动续跑的可观测面:开关、已用轮次、是否已排期、上一次判定码。
3107
+ autoResume: autoResumeView(record),
2493
3108
  deliveryReady: readiness.ready,
2494
3109
  deliveryBlockers: readiness.blockers.slice(0, 12),
2495
3110
  deliveryRemaining: readiness.remaining.slice(0, 20),
@@ -2503,6 +3118,73 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2503
3118
  }
2504
3119
  }
2505
3120
 
3121
+ /*
3122
+ * [1.9.1] 用户授权的 follow-up 通道。
3123
+ *
3124
+ * 事故背景:三条子会话 a0d5b134 / 031225ef / 7934905a 在 2026-10-31
3125
+ * 23:07–23:23 之间被整轮预算与 900s 子任务上限中止,各自末轮
3126
+ * `turn/end = aborted/parent`;界面据此显示 idle(灰色),而台账侧三条
3127
+ * 都是 done/structured。用户 2026-11-01 明确同意「补发 follow-up,让圈注
3128
+ * 三行真正变绿」——做法是让子会话自己再跑完一个正常回合,而不是伪造
3129
+ * turn/end 或改投影缓存。
3130
+ *
3131
+ * 本工具只做一件事:把一条消息投递到本会话的**直接**子会话。它不写计划
3132
+ * 状态、不触发交付、也不改变 `lastTurnCompleted`——那个字段只会被子会话
3133
+ * 自己真实完成的回合改写。投递成功后子会话开始新一轮;它正常结束,界面
3134
+ * 才可能变绿。失败一律返回 ok:false,不吞错。
3135
+ */
3136
+ async function followupTool(agent: any, args: any, signal: any) {
3137
+ const session = agent?.session
3138
+ if (!session) {
3139
+ return { ok: false, code: 'NO_SESSION', error: '只能在会话内补发 follow-up' }
3140
+ }
3141
+ if (!isRootSession(session)) {
3142
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以补发 follow-up' }
3143
+ }
3144
+ const childId = typeof args?.sessionId === 'string' ? args.sessionId.trim() : ''
3145
+ const message = typeof args?.message === 'string' ? args.message.trim() : ''
3146
+ if (!childId) {
3147
+ return { ok: false, code: 'INVALID_SESSION', error: 'sessionId 必填:必须是本会话的直接子会话 ID' }
3148
+ }
3149
+ if (!message) {
3150
+ return { ok: false, code: 'INVALID_MESSAGE', error: 'message 必填:要发给子会话的说明' }
3151
+ }
3152
+ if (message.length > 4000) {
3153
+ return { ok: false, code: 'MESSAGE_TOO_LONG', error: 'message 过长(上限 4000 字符)' }
3154
+ }
3155
+ if (!spawnedChildIds(session).has(childId)) {
3156
+ return {
3157
+ ok: false,
3158
+ code: 'NOT_DIRECT_CHILD',
3159
+ error: `${childId} 不是本会话的直接子会话(父会话 catalog 未登记),拒绝投递`,
3160
+ }
3161
+ }
3162
+ const service: any = (ctx as any).subagents
3163
+ if (!service || typeof service.sendMessage !== 'function') {
3164
+ return {
3165
+ ok: false,
3166
+ code: 'NO_SUBAGENT_SERVICE',
3167
+ error: '当前部署没有可用的 subagent 服务,无法投递 follow-up',
3168
+ }
3169
+ }
3170
+ try {
3171
+ const messageId = await service.sendMessage(
3172
+ agent,
3173
+ childId,
3174
+ [{ type: 'text', text: message }],
3175
+ { signal },
3176
+ )
3177
+ return { ok: true, sessionId: childId, messageId: String(messageId ?? '') }
3178
+ } catch (error: any) {
3179
+ return {
3180
+ ok: false,
3181
+ code: 'DELIVERY_FAILED',
3182
+ sessionId: childId,
3183
+ error: truncate(error instanceof Error ? error.message : String(error), 500),
3184
+ }
3185
+ }
3186
+ }
3187
+
2506
3188
  async function dispatchTool(agent: any, args: any, signal: any) {
2507
3189
  const session = agent?.session
2508
3190
  if (!session) throw new PlanError('只能在会话内派发计划', 'NO_SESSION')
@@ -2541,6 +3223,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2541
3223
  }
2542
3224
  }
2543
3225
  if (!record?.plan) throw new PlanError('当前会话没有可派发的计划', 'NO_PLAN')
3226
+ /*
3227
+ * [1.10.4] 人工/工具派发优先于自动续跑:撤销待触发的定时器,并把自动
3228
+ * 轮次计数归零(这一次是外部授权的新起点)。done 水位取当前值,下一轮
3229
+ * 结束后才能正确判断「有没有新增完成项」。
3230
+ */
3231
+ clearAutoResumeTimer(record, 'manual-dispatch')
3232
+ {
3233
+ const book = autoResumeBook(record)
3234
+ book.attempt = 0
3235
+ book.noProgressRounds = 0
3236
+ book.doneBefore = Number(derivePlanSnapshot(record.statuses).stats?.done ?? 0)
3237
+ }
2544
3238
  if (args?.planId && record.plan.planId !== args.planId) {
2545
3239
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
2546
3240
  }
@@ -2553,20 +3247,30 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2553
3247
  * is the user's stop signal; the only honest answer is a refusal that says
2554
3248
  * how to continue deliberately (a new plan, or the main Agent takes over).
2555
3249
  */
2556
- if (record.phase === 'cancelled' || record.cancelled === true) {
3250
+ if (isTerminalPhase(record.phase) || record.cancelled === true) {
3251
+ /*
3252
+ * [1.9.0] 终态集合:cancelled(用户撤销)与 superseded(责任已转移)
3253
+ * 都不允许派发、不允许复活。superseded 用独立拒绝码,便于调用方区分
3254
+ * 「用户叫停」与「已被别的计划承接」。cancelled 的返回体与 1.8.19 相同。
3255
+ */
3256
+ const superseded = record.phase === 'superseded'
2557
3257
  const snapshot = derivePlanSnapshot(record.statuses)
2558
3258
  return {
2559
3259
  ok: false,
2560
3260
  planId: record.plan.planId,
2561
- phase: 'cancelled',
3261
+ phase: superseded ? 'superseded' : 'cancelled',
2562
3262
  running: false,
2563
3263
  alreadyRunning: false,
2564
3264
  complete: false,
2565
3265
  remaining: Math.max(0, Number(snapshot.stats.total ?? 0) - Number(snapshot.stats.done ?? 0)),
2566
3266
  stats: snapshot.stats,
2567
- code: 'PLAN_CANCELLED',
2568
- error: '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
2569
- hint: '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
3267
+ code: superseded ? 'PLAN_SUPERSEDED' : 'PLAN_CANCELLED',
3268
+ error: superseded
3269
+ ? '计划已被取代:不会再启动任何部门 Agent'
3270
+ : '计划已取消:取消只停止执行,不会再启动任何部门 Agent',
3271
+ hint: superseded
3272
+ ? '不要再次派发。被取代不等于完成:如需交付,请按覆盖链核对承接计划的证据;承接计划未就绪时不得调用 present。'
3273
+ : '不要再次派发。如需继续这项工作,请向用户确认后重新生成计划;或由主 Agent 直接接手剩余项,并在答复中说明这是直接执行而非派发。',
2570
3274
  }
2571
3275
  }
2572
3276
  /*
@@ -2685,12 +3389,15 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2685
3389
  dispatchController.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2686
3390
  }
2687
3391
  }
2688
- record.dispatchPromise = dispatchPlan(ctx, record, {
3392
+ const roundOptions = {
2689
3393
  agent,
2690
- signal: dispatchController.signal,
2691
3394
  modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
2692
3395
  cwd: session.header?.cwd ?? options.cwd,
2693
3396
  conversationContext: record.conversationContext ?? '',
3397
+ }
3398
+ record.dispatchPromise = dispatchPlan(ctx, record, {
3399
+ ...roundOptions,
3400
+ signal: dispatchController.signal,
2694
3401
  childTimeoutMs: limits.childTimeoutMs,
2695
3402
  idleTimeoutMs: limits.idleTimeoutMs,
2696
3403
  totalTimeoutMs: limits.totalTimeoutMs,
@@ -2713,11 +3420,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2713
3420
  .then(() => {
2714
3421
  finishRound(record, session)
2715
3422
  state.records.set(session.id, record)
3423
+ armAutoResume(record, session, roundOptions)
2716
3424
  })
2717
3425
  .catch((error: any) => {
2718
3426
  pushRecordError(record, error)
2719
3427
  finishRound(record, session)
2720
3428
  state.records.set(session.id, record)
3429
+ armAutoResume(record, session, roundOptions)
2721
3430
  })
2722
3431
  const live = derivePlanSnapshot(record.statuses)
2723
3432
  return {
@@ -2738,6 +3447,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2738
3447
  }
2739
3448
  await record.dispatchPromise
2740
3449
  finishRound(record, session)
3450
+ armAutoResume(record, session, roundOptions)
2741
3451
  /*
2742
3452
  * The model's dispatch result reports the same snapshot the dashboard will
2743
3453
  * show. It used to send `record.stats` while the status list below was read
@@ -2782,9 +3492,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2782
3492
  return deliveryReadiness(snapshot, { phase: record.phase })
2783
3493
  }
2784
3494
 
2785
- function stopGateApplies(record: any) {
3495
+ function stopGateApplies(record: any, session?: any, turn?: number) {
2786
3496
  if (!record?.plan) return false
2787
3497
  if (record.degraded) return false
3498
+ /*
3499
+ * [1.9.0] 终态不再触发收尾 steer —— 这正是死锁的第二个出口(T8 I7)。
3500
+ * cancelled 只有在本回合被结构化点名时才提醒一次(present 仍会硬拦);
3501
+ * superseded 不 steer:它的判定对象是承接计划,present 的拒绝文案已给出出路。
3502
+ */
3503
+ if (isTerminalPhase(record.phase)) {
3504
+ return record.phase === 'cancelled'
3505
+ && Boolean(session && turn && planIdFromTurn(session, turn) === record.plan.planId)
3506
+ }
2788
3507
  const readiness = recordReadiness(record)
2789
3508
  if (Number(readiness.total ?? 0) === 0) return false
2790
3509
  return !readiness.ready
@@ -2989,7 +3708,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2989
3708
  record = reconstructFromSession(session, planIdFromTurn(session, turn))
2990
3709
  if (record?.plan) state.records.set(session.id, record)
2991
3710
  }
2992
- if (!stopGateApplies(record)) return
3711
+ if (!stopGateApplies(record, session, turn)) return
2993
3712
  if (record.dispatchPromise) {
2994
3713
  try {
2995
3714
  await record.dispatchPromise
@@ -2997,7 +3716,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2997
3716
  /* the failure is already on record.errors; the gate only needs the outcome */
2998
3717
  }
2999
3718
  finishRound(record, session)
3000
- if (!stopGateApplies(record)) return
3719
+ if (!stopGateApplies(record, session, turn)) return
3001
3720
  }
3002
3721
  const book = record.stopSteers && record.stopSteers.turn === turn
3003
3722
  ? record.stopSteers
@@ -3111,7 +3830,79 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3111
3830
  return undefined
3112
3831
  }
3113
3832
 
3114
- function presentDenialReason(agent: any) {
3833
+ /**
3834
+ * [1.9.0] 点名 superseded 时的覆盖链判定(T8 §4.2 第 4 条、§6.3)。
3835
+ *
3836
+ * superseded 只是「责任已转移」,不是完成:本回合点名它时,判的是承接计划
3837
+ * 是否真的就绪。承接计划缺失/已终止/无法复核 ⇒ fail-closed(SUPERSEDED_STALE);
3838
+ * 承接计划未就绪 ⇒ 拒绝;只有承接计划 deliveryReady 才放行(产物来自承接计划)。
3839
+ *
3840
+ * [1.9.2] 返回值带上拒绝码(T8 §4.3 `judgeEffective`):覆盖链无法复核
3841
+ * ⇒ `SUPERSEDED_STALE`;覆盖链有效但承接计划未就绪 ⇒ `ACTIVE_NOT_READY`。
3842
+ * 文案保持逐字不变,码值走 `src/plan.ts` 的同一组常量。
3843
+ */
3844
+ function supersededDenialVerdict(session: any, record: any): PresentDenialVerdict | undefined {
3845
+ const planId = record.plan?.planId ?? record.planId ?? ''
3846
+ const by = record.supersededBy
3847
+ const successorPlanId = typeof by?.successorPlanId === 'string' && by.successorPlanId
3848
+ ? by.successorPlanId
3849
+ : typeof by?.planId === 'string' ? by.planId : ''
3850
+ if (!successorPlanId) {
3851
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3852
+ `计划 ${planId} 已被取代,但缺少可验证的承接计划(supersededBy.successorPlanId):`
3853
+ + '覆盖证据失效(SUPERSEDED_STALE),不得调用 present;请向用户说明覆盖链无法复核并重新确认交付对象。')
3854
+ }
3855
+ /*
3856
+ * [W1] 覆盖摘要:present 复验从 mapping 重算摘要,不读缓存数值(T8 §6.3)。
3857
+ *
3858
+ * 摘要一旦对不上(含 mapping/digest 缺失),覆盖记录就无法复核 —— 无法复核
3859
+ * ≠ 通过,一律 stale。这条检查只证明「存下来的 mapping 没被改动」,不证明
3860
+ * 「两项工作在语义上等价」;后者仍只能由用户确认(V8)承载。
3861
+ */
3862
+ const mapping = by?.mapping
3863
+ if (!Array.isArray(mapping)) {
3864
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3865
+ `计划 ${planId} 已被取代,但缺少可复算的逐项映射(supersededBy.mapping):`
3866
+ + '覆盖证据失效(SUPERSEDED_STALE),不得调用 present,不得声称“已完成/最终版/已交付”;'
3867
+ + '请重新按用户确认的逐项映射做覆盖迁移,并由运行时写入复算后的 digest。')
3868
+ }
3869
+ const computedDigest = computeMappingDigest(mapping)
3870
+ if (!verifyMappingDigest(mapping, by?.digest)) {
3871
+ const stored = typeof by?.digest === 'string' ? by.digest.slice(0, 15) : '缺失'
3872
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3873
+ `计划 ${planId} 已被取代,但覆盖证据摘要与逐项映射不一致(supersededBy.digest=${stored},`
3874
+ + `重算=${computedDigest.slice(0, 15)}):覆盖证据失效(SUPERSEDED_STALE),不得调用 present,`
3875
+ + '不得声称“已完成/最终版/已交付”;请重新按用户确认的逐项映射做覆盖迁移,并由运行时复算 digest。')
3876
+ }
3877
+ const successor = reconstructFromSession(session, successorPlanId)
3878
+ if (!successor?.plan || definedSubtaskCount(successor.plan) === 0 || isTerminalPhase(successor.phase)) {
3879
+ return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE,
3880
+ `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
3881
+ + '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。')
3882
+ }
3883
+ const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase })
3884
+ if (!readiness.ready) {
3885
+ const ids = readiness.remaining.slice(0, 10).join('、')
3886
+ return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
3887
+ `计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
3888
+ + `${ids ? `,剩余 ${readiness.remaining.length} 项(${ids})` : ''}。`
3889
+ + '被取代不等于完成:承接计划通过交付就绪检查之前不得调用 present。')
3890
+ }
3891
+ return undefined
3892
+ }
3893
+
3894
+ /**
3895
+ * [1.9.2] present 拒绝点的唯一出口:码值取常量,拒绝文案保持逐字不变。
3896
+ *
3897
+ * host 的 guard 契约是 `string`(`ctx.tools.checkGuards`),所以工具错误里
3898
+ * 仍只有文案;码值由 `presentDenialVerdict` 一并返回,供断言、日志与后续
3899
+ * UI 使用。所有分支都必须经由这里,不要在分支里手写码值。
3900
+ */
3901
+ function presentDenial(code: PresentDenyCode, message: string): PresentDenialVerdict {
3902
+ return { code, message }
3903
+ }
3904
+
3905
+ function presentDenialVerdict(agent: any): PresentDenialVerdict | undefined {
3115
3906
  const session = agent?.session
3116
3907
  if (!session || !isRootSession(session)) return undefined
3117
3908
  if (isPlanModeActive(ctx, session)) return undefined
@@ -3158,7 +3949,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3158
3949
  * or the last defined plan after a restart) is about: cancel stops
3159
3950
  * execution, it does not make the work deliverable.
3160
3951
  */
3161
- .filter((entry: any) => entry.record.phase !== 'cancelled' && !entry.readiness.ready)
3952
+ .filter((entry: any) => !isTerminalPhase(entry.record.phase) && !entry.readiness.ready)
3162
3953
  if (unresolved.length > 1) {
3163
3954
  const lines = unresolved.slice(0, 6).map((entry: any) => {
3164
3955
  const ids = entry.readiness.remaining.slice(0, 6).join('、')
@@ -3167,10 +3958,11 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3167
3958
  return `- 计划 ${entry.record.plan.planId}:完成 ${entry.readiness.done}/${entry.readiness.total}${suffix}`
3168
3959
  + `${gaps ? `;证据缺口:${gaps}` : ''}`
3169
3960
  })
3170
- return `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3961
+ return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
3962
+ `本会话还有 ${unresolved.length} 个计划未通过交付就绪检查:\n${lines.join('\n')}\n`
3171
3963
  + '在它们全部通过交付就绪检查之前,不得调用 present 交付任何产物:'
3172
3964
  + '先调用 dsh_workplan_dispatch 续跑,证据缺口用 dsh_workplan_update 补齐。'
3173
- + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。'
3965
+ + '取消只停止执行,不会让未完成的计划变成可交付,也不能用来绕过这道检查。')
3174
3966
  }
3175
3967
  let record: any
3176
3968
  let readiness: any
@@ -3191,10 +3983,23 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3191
3983
  if (!record?.plan) record = lastGateablePlanRecord(session)
3192
3984
  if (!record?.plan) return undefined
3193
3985
  if (definedSubtaskCount(record.plan) === 0) return undefined
3986
+ /*
3987
+ * [1.9.0] 终态解耦(T8 §4.3 P3):终态计划不再被自动选为判定对象。
3988
+ *
3989
+ * 只有「本回合结构化点名」时才判定;否则不再写回 live、不再拦截其它
3990
+ * 计划的交付。取消 ≠ 完成:记录仍是 cancelled 0/N,只是不再永久挡门。
3991
+ */
3992
+ const namedThisTurn = Boolean(turnPlanId && record.plan.planId === turnPlanId)
3993
+ if (isTerminalPhase(record.phase) && !namedThisTurn) return undefined
3994
+ if (record.phase === 'superseded') {
3995
+ const denial = supersededDenialVerdict(session, record)
3996
+ if (denial) return denial
3997
+ return undefined
3998
+ }
3194
3999
  readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase })
3195
4000
  if (readiness.ready) return undefined
3196
4001
  }
3197
- if (record?.plan) state.records.set(session.id, record)
4002
+ if (record?.plan && !isTerminalPhase(record.phase)) state.records.set(session.id, record)
3198
4003
  const snapshot = derivePlanSnapshot(record.statuses)
3199
4004
  const planId = record.plan?.planId ?? record.planId
3200
4005
  const ids = readiness.remaining.slice(0, 10).join('、')
@@ -3211,26 +4016,44 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3211
4016
  .slice(0, 10)
3212
4017
  .join(';')
3213
4018
  if (readiness.remaining.length === 0) {
3214
- return `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
4019
+ return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED,
4020
+ `计划 ${planId} 已取消,${readiness.total} 个子任务虽已 done,但证据未通过:${gaps || '缺少结构化证据'}。`
3215
4021
  + '取消只停止执行,不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”;'
3216
- + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。'
4022
+ + '答复必须说明取消状态与证据缺口,不能写成“全部完成”。')
3217
4023
  }
3218
- return `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
4024
+ return presentDenial(PRESENT_DENY_CODES.CANCELLED_NAMED,
4025
+ `计划 ${planId} 已取消,但只完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3219
4026
  + `${gaps ? `;证据缺口:${gaps}` : ''}。`
3220
4027
  + '取消只停止执行,不等于完成,也不会让未完成项变成可交付:不得调用 present,不得声称“已完成/最终版/已交付”;'
3221
- + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。'
4028
+ + '答复开头必须写「未完成:剩余 N 项(列出 ID)与原因」。')
3222
4029
  }
4030
+ /*
4031
+ * [1.9.2] P1 的单一映射:`activeDenyCode` 只看就绪结果。
4032
+ * `remaining` 为空但 `blockers` 非空 ⇒ `EVIDENCE_GAP`(T9 C05 的修法);
4033
+ * 还有子任务没做完 ⇒ `ACTIVE_NOT_READY`。两个分支共用同一个码值来源。
4034
+ */
4035
+ const activeCode = activeDenyCode(readiness)
3223
4036
  if (readiness.remaining.length === 0) {
3224
- return `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
4037
+ return presentDenial(activeCode,
4038
+ `计划 ${planId} 的 ${readiness.total} 个子任务虽都已 done,但证据未通过:${blockers || '缺少结构化证据'}。`
3225
4039
  + '在 deliveryReady 变为 true 之前,产物不得作为成品交付:'
3226
4040
  + "用 dsh_workplan_update 为这些子任务补 verification='structured' 与 acceptance(每项 result='pass' 并附证据),"
3227
- + '或把对应子任务改回 blocked 并写明原因;不要调用 present。'
4041
+ + '或把对应子任务改回 blocked 并写明原因;不要调用 present。')
3228
4042
  }
3229
- return `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
4043
+ return presentDenial(activeCode,
4044
+ `计划 ${planId} 未完成:完成 ${readiness.done}/${readiness.total},剩余 ${readiness.remaining.length} 项${idSuffix}`
3230
4045
  + `${blockers ? `;另有证据缺口:${blockers}` : ''}。`
3231
4046
  + '在计划通过交付就绪检查之前不得调用 present 交付产物:先调用 dsh_workplan_dispatch 续跑剩余项;'
3232
4047
  + '证据缺口用 dsh_workplan_update 补齐;确实无法继续时,把答复写成「未完成:剩余 N 项与原因」。'
3233
- + '取消只停止执行,不会改变“未完成”的结论。'
4048
+ + '取消只停止执行,不会改变“未完成”的结论。')
4049
+ }
4050
+
4051
+ /**
4052
+ * 兼容入口:host 的 guard 只接受字符串,所以工具错误仍是原来的文案。
4053
+ * 需要码值时调用 `presentDenialVerdict`。
4054
+ */
4055
+ function presentDenialReason(agent: any) {
4056
+ return presentDenialVerdict(agent)?.message
3234
4057
  }
3235
4058
 
3236
4059
  /*
@@ -3316,7 +4139,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3316
4139
  const unresolved = [...planIds]
3317
4140
  .map((planId) => recordForPlan(session, planId))
3318
4141
  .filter((record: any) => record?.plan
3319
- && record.phase !== 'cancelled'
4142
+ && !isTerminalPhase(record.phase)
3320
4143
  && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready)
3321
4144
  if (unresolved.length === 0) return undefined
3322
4145
  const ids = unresolved.slice(0, 4).map((record: any) => record.plan.planId)
@@ -3405,6 +4228,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3405
4228
  }
3406
4229
 
3407
4230
  function dispose() {
4231
+ // [1.10.4] 定时器不能吊住进程,也不能在记录清空后复活一个已销毁的计划。
4232
+ for (const record of state.records.values()) clearAutoResumeTimer(record, 'dispose')
3408
4233
  state.records.clear()
3409
4234
  }
3410
4235
 
@@ -3414,11 +4239,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3414
4239
  onPreStep,
3415
4240
  onTurnStopping,
3416
4241
  presentDenialReason,
4242
+ presentDenialVerdict,
4243
+ supersededDenialVerdict,
3417
4244
  presentedWriteDenialReason,
3418
4245
  updateStatus,
3419
4246
  cancelPlan,
3420
4247
  dispatchTool,
3421
4248
  statusTool,
4249
+ followupTool,
3422
4250
  plansPayload,
3423
4251
  route,
3424
4252
  dispose,
@@ -3490,7 +4318,13 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
3490
4318
  // A plan committed but not yet dispatched must not be overwritten in the
3491
4319
  // same turn; a later turn may supersede it, otherwise one abandoned plan
3492
4320
  // would lock planning forever.
3493
- if (existing?.plan && !existing.dispatchedAt) {
4321
+ //
4322
+ // [1.9.2] 自动覆盖路径**只允许**写 cancelled,永不写 superseded(规则设计
4323
+ // §7.1:自动路径没有逐项映射与用户确认,满足不了 V4–V8)。它也不得把已经
4324
+ // superseded 的终态记录改回 cancelled:内存写 cancelled、日志里仍是
4325
+ // supersede 信封,会让 live 与 replay 分叉。终态记录由 present 的终态解耦
4326
+ // 处理(不再自动挡门),不需要在这里「取消」。
4327
+ if (existing?.plan && !existing.dispatchedAt && !isTerminalPhase(existing.phase)) {
3494
4328
  if (existing.plan.createdTurn === payload.turn) return downstream
3495
4329
  existing.phase = 'cancelled'
3496
4330
  existing.cancelledAt = Date.now()
@@ -3679,6 +4513,36 @@ export function cancelToolOutputSchema() {
3679
4513
  cancelRecorded: { type: 'boolean' },
3680
4514
  alreadyCancelled: { type: 'boolean' },
3681
4515
  abortedRunning: { type: 'boolean' },
4516
+ /*
4517
+ * [1.9.2] `disposition="superseded"` answers. `supersedeRecorded` is the
4518
+ * durable-write witness for the supersede envelope (the cancelled answer
4519
+ * uses `cancelRecorded`); `alreadySuperseded` is the §7.4 idempotent
4520
+ * re-submission. `code` carries the SUPERSEDE_* refusal; `gaps` /
4521
+ * `missingFrom` / `problems` explain exactly which V-rule failed so a
4522
+ * caller can repair the mapping instead of guessing.
4523
+ */
4524
+ disposition: { type: 'string' },
4525
+ supersededAt: { type: 'number' },
4526
+ supersedeRecorded: { type: 'boolean' },
4527
+ alreadySuperseded: { type: 'boolean' },
4528
+ coverage: { type: 'string' },
4529
+ requiredCount: { type: 'number' },
4530
+ coveredCount: { type: 'number' },
4531
+ successorSeenAtSeq: { type: 'number' },
4532
+ confirmedAtSeq: { type: 'number' },
4533
+ supersededBy: {
4534
+ type: 'object',
4535
+ properties: {
4536
+ planId: { type: 'string' },
4537
+ },
4538
+ additionalProperties: true,
4539
+ },
4540
+ code: { type: 'string' },
4541
+ error: { type: 'string' },
4542
+ hint: { type: 'string' },
4543
+ gaps: { type: 'array', items: { type: 'string' } },
4544
+ missingFrom: { type: 'array', items: { type: 'string' } },
4545
+ problems: { type: 'array', items: { type: 'string' } },
3682
4546
  },
3683
4547
  required: ['ok'],
3684
4548
  additionalProperties: true,