dsh-workplan 1.9.1 → 1.11.0

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 {
@@ -22,6 +22,7 @@ import {
22
22
  aggregateInvariantViolations,
23
23
  applyStatus,
24
24
  attachPlanMeta,
25
+ blockCancelledDependents,
25
26
  buildChildPrompt,
26
27
  buildCancelMessage,
27
28
  buildDegradedMessage,
@@ -58,13 +59,30 @@ import {
58
59
  adjudicateResult,
59
60
  activeDenyCode,
60
61
  MAX_CONVERSATION_CHARS,
62
+ MAX_ESCALATION_OPTIONS,
63
+ MAX_INSTRUCTION_CHARS,
64
+ MAX_QUESTION_CHARS,
61
65
  parseUpdateMessage,
62
66
  buildUpdateMessage,
67
+ normaliseHandoffs,
68
+ openHandoffs,
69
+ DEPARTMENTS,
70
+ DEPARTMENT_IDS,
71
+ MAX_HANDOFF_RESPONSE_CHARS,
63
72
  } from './plan.js'
64
73
  import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
65
74
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
66
75
  import { supersedePlanRecord } from './supersede.js'
67
76
  import { createProgressWatchdog, describeError } from './watchdog.js'
77
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js'
78
+ import {
79
+ applyReplanStatuses,
80
+ buildChangeRequestMessage,
81
+ buildReplanMessage,
82
+ parseChangeRequestMessage,
83
+ parseReplanMessage,
84
+ planReplan,
85
+ } from './replan.js'
68
86
 
69
87
  /**
70
88
  * [1.8.18] How many subtasks the plan *defines*.
@@ -80,14 +98,68 @@ import { createProgressWatchdog, describeError } from './watchdog.js'
80
98
  * (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
81
99
  * `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
82
100
  */
101
+ function expectedAcceptanceOf(plan: any): Record<string, any[]> {
102
+ const out: Record<string, any[]> = {}
103
+ for (const entry of flattenSubtasks(plan)) {
104
+ const id = String(entry?.subtask?.id ?? '')
105
+ if (!id) continue
106
+ out[id] = Array.isArray(entry.subtask.acceptance) ? entry.subtask.acceptance : []
107
+ }
108
+ return out
109
+ }
110
+
83
111
  function definedSubtaskCount(plan: any): number {
84
112
  try {
85
- return flattenSubtasks(plan).length
113
+ /*
114
+ * [1.11.0] 被重规划替换/撤销的旧行不占分母。
115
+ *
116
+ * 契约 §7.2 硬规则 2:`cancel` 掉的工作如果仍然计入定义条数,计划就永远
117
+ * 差一项、永远无法交付。标记由 `replan.ts` 写在计划定义上(supersededAt),
118
+ * 与状态条目的 `closure:'replanned'` 是同一次写入的两个镜像。
119
+ */
120
+ return flattenSubtasks(plan).filter((entry: any) => !entry.subtask?.supersededAt).length
86
121
  } catch {
87
122
  return Number.MAX_SAFE_INTEGER
88
123
  }
89
124
  }
90
125
 
126
+ /**
127
+ * [1.11.0] 可调度/可计数的状态行:排除已被重规划替换或撤销的旧行。
128
+ *
129
+ * `closure` 仍是唯一标记。这里不复制状态的其它字段,只做视图过滤,因此
130
+ * 左侧栏、调度器、交付门禁读到的仍是同一个 `record.statuses` 数组。
131
+ */
132
+ function liveStatuses(statuses: any) {
133
+ return Array.isArray(statuses)
134
+ ? statuses.filter((item: any) => item?.closure !== 'replanned')
135
+ : []
136
+ }
137
+
138
+ /**
139
+ * [1.11.0] C-17:交付门禁的唯一读取助手——左侧栏、present、收尾闸门、dispatch
140
+ * 返回体都从这里拿 `deliveryReady`,不再各自决定“要不要把记录级事实算进去”。
141
+ *
142
+ * `changeRequest.pending`(执行中收到、尚未重规划的变更)与 `reportPending`
143
+ * (完成结果还没写进会话)只存在于 `record` 而不是 `statuses`,所以必须在
144
+ * 这一层显式传入;`plan.ts` 的 `deliveryReadiness` 因此仍是纯函数。
145
+ */
146
+ function readinessOf(record: any, snapshot?: any) {
147
+ const snap = snapshot ?? derivePlanSnapshot(
148
+ record?.plan ? blockCancelledDependents(record.plan, record?.statuses) : record?.statuses,
149
+ record?.plan ? definedSubtaskCount(record.plan) : undefined,
150
+ )
151
+ return deliveryReadiness(snap, {
152
+ phase: record?.phase,
153
+ changePending: record?.changeRequest?.status === 'pending',
154
+ reportPending: record?.reportPending === true,
155
+ /*
156
+ * 计划定义的验收标准是交付门的另一半:状态行只回答「子 Agent 说通过
157
+ * 了几条」,这里回答「计划要求的几条有没有被逐条回应」。
158
+ */
159
+ expectedAcceptance: record?.plan ? expectedAcceptanceOf(record.plan) : undefined,
160
+ })
161
+ }
162
+
91
163
  export const PLANNER_TIMEOUT_MS = 120000
92
164
  /**
93
165
  * Absolute ceiling for one child execution.
@@ -113,6 +185,30 @@ export const MAX_CHILD_TIMEOUT_MS = 1800000
113
185
  export const MIN_CHILD_IDLE_MS = 1000
114
186
  export const MAX_CHILD_IDLE_MS = 900000
115
187
  export const CHILD_POLL_MS = 2000
188
+ /*
189
+ * [1.11.0] 派发回执的两个窗口(T4 B1/B2)。
190
+ *
191
+ * `assigned` 只是「已交给子会话」,不等于「子会话已经动了」。收不到回执时
192
+ * 静默等到空闲窗口(默认 300s)会把「根本没启动」和「在慢慢想」混为一谈:
193
+ * 90s 先标记 ackOverdue 让看板可见,180s 仍无任何新事件就按 no-ack 收束,
194
+ * 不再无限等待。
195
+ */
196
+ export const ASSIGN_ACK_NOTICE_MS = 90000
197
+ export const ASSIGN_ACK_DEADLINE_MS = 180000
198
+ /*
199
+ * [1.11.0] 指示回执的两个窗口(T4 B5)。
200
+ *
201
+ * `instructed` 只表示「指示已经写进状态行并投递」,不表示子 Agent 已经照做。
202
+ * 60s 没有新事件先标 `instructionOverdue`(看板可见、主 Agent 可催),
203
+ * 180s 仍无增长就按 no-ack 收束,避免「指示已下、那边根本没跑」无限挂起。
204
+ */
205
+ export const INSTRUCTION_ACK_NOTICE_MS = 60000
206
+ export const INSTRUCTION_ACK_DEADLINE_MS = 180000
207
+ /*
208
+ * 正向回执的观察频率。5s 足以在 60s 提醒前发现「子会话已在动」,同时把
209
+ * 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
210
+ */
211
+ export const INSTRUCTION_POLL_MS = 5000
116
212
  export const TOTAL_TIMEOUT_MS = 1200000
117
213
  export const DISPOSE_TIMEOUT_MS = 5000
118
214
  export const STALE_PENDING_MS = 10 * 60 * 1000
@@ -519,6 +615,61 @@ export function probeInterruptedEvidence(output: any, subtask: any, cwd: any, ar
519
615
  return { artifacts, missingArtifacts }
520
616
  }
521
617
 
618
+ /**
619
+ * [1.10.6] Fingerprint the files a timed-out attempt already wrote.
620
+ *
621
+ * T6 (G3) found that the retry decision never looked at the disk: a second
622
+ * attempt could silently overwrite a deliverable the first attempt had already
623
+ * produced, turning "the child stopped early" into "the deliverable was
624
+ * rewritten". This snapshot (path + size + mtime) is the record the retry is
625
+ * compared against.
626
+ *
627
+ * A missing file is not a conflict — it simply has no fingerprint. `stat` is
628
+ * injectable so the check can be tested without touching the real filesystem.
629
+ */
630
+ export function fingerprintArtifacts(refs: any, cwd: any, stat: any = statSync) {
631
+ const list = Array.isArray(refs) ? refs : []
632
+ const out: { ref: string; size: number; mtimeMs: number }[] = []
633
+ const seen = new Set<string>()
634
+ for (const item of list) {
635
+ const ref = typeof item === 'string' ? item.trim() : ''
636
+ if (!ref || seen.has(ref)) continue
637
+ seen.add(ref)
638
+ const target = resolveArtifactPath(ref, cwd)
639
+ if (!target) continue
640
+ try {
641
+ const info = stat(target)
642
+ if (!info) continue
643
+ out.push({ ref, size: Number(info.size), mtimeMs: Number(info.mtimeMs) })
644
+ } catch {
645
+ // Missing or unreadable: nothing to protect, and not a conflict.
646
+ }
647
+ }
648
+ return out
649
+ }
650
+
651
+ /**
652
+ * [1.10.6] Which landed artifacts changed since the snapshot was taken.
653
+ *
654
+ * Size or mtime differing is enough to call it a conflict: the file the first
655
+ * attempt produced is no longer the file on disk, so a retry that rewrites it
656
+ * would destroy work rather than finish it.
657
+ */
658
+ export function diffArtifactFingerprints(before: any, after: any) {
659
+ const previous = new Map<string, any>()
660
+ for (const item of Array.isArray(before) ? before : []) {
661
+ if (item && typeof item.ref === 'string') previous.set(item.ref, item)
662
+ }
663
+ const conflicts: string[] = []
664
+ for (const item of Array.isArray(after) ? after : []) {
665
+ if (!item || typeof item.ref !== 'string') continue
666
+ const recorded = previous.get(item.ref)
667
+ if (!recorded) continue
668
+ if (recorded.size !== item.size || recorded.mtimeMs !== item.mtimeMs) conflicts.push(item.ref)
669
+ }
670
+ return conflicts
671
+ }
672
+
522
673
  /**
523
674
  * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
524
675
  */
@@ -551,6 +702,8 @@ export function timeoutBlockedPatch(subtask: any, cwd: any, message: string, art
551
702
  return {
552
703
  patch: {
553
704
  status: 'blocked',
705
+ closure: 'blocked',
706
+ blockedKind: 'timeout',
554
707
  progress: 100,
555
708
  finishedAt: Date.now(),
556
709
  error: message + artifactNote,
@@ -592,8 +745,31 @@ export function budgetResetError(item: any, subtask: any, cwd: any, artifactExis
592
745
  * that need the environment: the strict/legacy switch and the file check.
593
746
  */
594
747
  function settleFromOutput(record: any, subtask: any, output: any, guard: SubtaskGuard, options: any) {
595
- const verdict = adjudicateResult({ output, strict: options.strictEvidence !== false })
748
+ /*
749
+ * [1.11.0] 已经升级的请示不能被收尾正文覆盖。
750
+ *
751
+ * `dsh_workplan_escalate` 在子会话中途就写下了 blocked + escalated。子 Agent
752
+ * 随后仍可能补一段结果块(甚至写 done),如果这里照常 adjudicate,就会把
753
+ * 「等人拍板」洗成「完成/普通失败」,提问也随之丢失。升级一旦写入,本轮
754
+ * 的最终判定只能保留它。
755
+ */
756
+ const current = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
757
+ if (current?.closure === 'escalated') return { status: 'blocked', escalated: true }
758
+ const verdict = adjudicateResult({
759
+ output,
760
+ strict: options.strictEvidence !== false,
761
+ /*
762
+ * [1.11.0] 计划验收进入裁决(T5 C4 / T10 D-01)。
763
+ *
764
+ * 不传这一项时,子 Agent 可以用一条自创验收项绕过整张验收表;传了之后
765
+ * 「5 条只回 1 条」会在收尾时直接变成 blocked/unverified,而不是等到
766
+ * 交付才被用户发现。
767
+ */
768
+ expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
769
+ })
596
770
  const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists)
771
+ const escalated = verdict.status === 'blocked'
772
+ && typeof verdict.question === 'string' && verdict.question.trim() !== ''
597
773
  writeSubtaskStatus(record, subtask.id, {
598
774
  status: verdict.status,
599
775
  progress: 100,
@@ -605,28 +781,77 @@ function settleFromOutput(record: any, subtask: any, output: any, guard: Subtask
605
781
  artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
606
782
  missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
607
783
  needs: verdict.needs.length > 0 ? verdict.needs : undefined,
784
+ /*
785
+ * [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
786
+ * `question` 就是同一条请示。它仍然写成 blocked 投影,但 closure 是
787
+ * escalated,看板与主 Agent 看到的都是「等指示」而不是普通失败。
788
+ */
789
+ ...(escalated
790
+ ? {
791
+ closure: 'escalated',
792
+ blockedKind: 'escalated',
793
+ question: verdict.question,
794
+ options: verdict.options,
795
+ escalatedAt: Date.now(),
796
+ escalationSeq: Number(current?.revision ?? 0) + 1,
797
+ }
798
+ : verdict.status === 'done'
799
+ /*
800
+ * [1.11.0] 完成必须落到 `closure:'done'`,不是 `blocked`。
801
+ *
802
+ * T9 的 P1 探针抓到过这里:完成路径固定写 `blocked/failed`,于是
803
+ * `done` 在执行路径不可达,「完成未回报」门禁与 `reportPending` 全部
804
+ * 恒不成立,进度栏也只能显示「失败」。完成与受阻是两种语义,必须分开。
805
+ */
806
+ ? { closure: 'done', blockedKind: null }
807
+ : {
808
+ closure: 'blocked',
809
+ blockedKind: 'failed',
810
+ }),
608
811
  }, guard)
609
812
  if (verdict.status === 'blocked') {
610
- recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard)
813
+ recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (verdict.error ?? '未完成'), guard)
611
814
  } else if (checked.missingArtifacts.length > 0) {
612
815
  recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard)
613
816
  }
614
- return verdict
817
+ return { ...verdict, escalated }
615
818
  }
616
819
 
617
820
  /**
618
821
  * Retry policy for one child attempt.
619
822
  *
620
823
  * A wedged child (no event for the whole idle window) is worth one fresh
621
- * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
622
- * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
623
- * more than one idle window left, otherwise the retry itself would just be
624
- * killed by the same watchdog.
824
+ * attempt. `CHILD_NOT_COMPLETED` is retried only while there is more than one
825
+ * idle window left, otherwise the retry itself would just be killed by the same
826
+ * watchdog.
827
+ *
828
+ * [1.10.3] 单个子任务撞上 900 秒硬上限时,只要整轮预算还够再跑一轮,就自动重试
829
+ * 一次。用户 2026-11-01 的质疑是对的:此前这一支被无条件 `return false`,
830
+ * 于是「预算没花完、只是这一步慢了」也被判成阻塞,必须等主 Agent 人工改判或
831
+ * 重新派发——而 `attempt` 已经是 1、产物又都在盘上,重跑一次往往就能过。
832
+ *
833
+ * 仍然**不自动重试**的两种情况,理由不变:
834
+ * - `TOTAL_TIMEOUT`:整轮预算已经用光,重试必然再被同一把闸刀砍掉,只会空耗;
835
+ * - `ABORTED`:那是「有人决定停」而不是「跑不完」,自动重来等于违背决定。
625
836
  */
626
837
  export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, idleTimeoutMs: any) {
627
838
  if (attempt >= 2) return false
628
839
  const code = error?.code
629
- if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
840
+ if (code === 'CHILD_TIMEOUT') {
841
+ /*
842
+ * 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
843
+ *
844
+ * [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
845
+ * 出厂配置是 ceiling=900s / idle=300s / round=1200s,撞上限后剩下约
846
+ * 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
847
+ * 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
848
+ * 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
849
+ * `tests/workplan-retry-feedback.test.ts` 的 60s 反例与 600s 正例都仍然成立。
850
+ */
851
+ const floor = 120000
852
+ return Number(remainingMs) > floor
853
+ }
854
+ if (code === 'ABORTED' || code === 'TOTAL_TIMEOUT') return false
630
855
  if (/aborted|refusal/i.test(String(error?.message ?? ''))) return false
631
856
  if (code === 'CHILD_STALLED') return true
632
857
  if (code === 'CHILD_NOT_COMPLETED') {
@@ -638,7 +863,17 @@ export function shouldRetryAttempt(error: any, attempt: any, remainingMs: any, i
638
863
  async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
639
864
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options
640
865
  let lastError: any = null
641
- let lastFailure: any = null
866
+ /*
867
+ * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
868
+ * even though this function is entered afresh. `attemptOffset` keeps the
869
+ * numbering honest (`第 2 次尝试`) and, with the loop condition below, keeps
870
+ * the cap at two real activations instead of letting the new call spend its
871
+ * own two.
872
+ */
873
+ const firstAttempt = Number.isInteger(options.attemptOffset) && options.attemptOffset > 1
874
+ ? options.attemptOffset
875
+ : 1
876
+ let lastFailure: any = options.priorFailure ?? null
642
877
  /*
643
878
  * [1.8.6] The interrupt has to outlive the thrown error.
644
879
  *
@@ -655,12 +890,15 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
655
890
  startedAt: Date.now(),
656
891
  }, guard)) return
657
892
 
658
- for (let attempt = 1; attempt <= 2; attempt += 1) {
893
+ for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
659
894
  if (guard.timedOut) return
660
895
  interruptedEvidence = null
661
896
  if (parentSignal.aborted) throw abortError()
662
897
  if (Date.now() >= deadline) throw new PlanError('总执行超时', 'TOTAL_TIMEOUT')
663
898
  let activation: any = null
899
+ // Declared outside the try so the per-attempt finally can always cancel
900
+ // the receipt timers, even when activation itself failed.
901
+ let clearAckTimers: () => void = () => {}
664
902
  try {
665
903
  if (child.controller.signal.aborted) {
666
904
  throw child.controller.signal.reason ?? abortError()
@@ -682,6 +920,16 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
682
920
  title: item.title,
683
921
  status: item.status,
684
922
  summary: item.summary,
923
+ /*
924
+ * [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
925
+ *
926
+ * 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
927
+ * 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
928
+ * 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
929
+ */
930
+ artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
931
+ .filter((artifact: any) => artifact?.exists === true && typeof artifact?.ref === 'string')
932
+ .map((artifact: any) => String(artifact.ref)),
685
933
  })),
686
934
  cwd: options.cwd,
687
935
  conversationContext,
@@ -703,10 +951,80 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
703
951
  if (!activation || typeof activation.result?.then !== 'function') {
704
952
  throw new PlanError('子 Agent 没有返回可等待的结果', 'NO_ACTIVATION')
705
953
  }
706
- writeSubtaskStatus(record, subtask.id, {
954
+ /*
955
+ * [1.11.0] `assigned` 是「已交给子会话」,不是「子会话已确认」。
956
+ *
957
+ * 旧代码只写 childId + 10%,从这一刻起到子 Agent 真正产出第一个事件
958
+ * 之间没有任何可观察状态:用户看到 10% 长时间不动,也无法区分
959
+ * 「没启动」「启动失败」「在跑一个很长的工具」。这里把派发序号和
960
+ * 回执窗口一起写进状态,后面的 onProgress/定时器才有据可依。
961
+ */
962
+ const assignedAt = Date.now()
963
+ const dispatchSeq = Number(record.dispatchSeq ?? 0) + 1
964
+ record.dispatchSeq = dispatchSeq
965
+ const assigned = writeSubtaskStatus(record, subtask.id, {
707
966
  childId: activation.childId,
708
967
  progress: 10,
968
+ closure: 'assigned',
969
+ assignedAt,
970
+ dispatchSeq,
971
+ // A retry is a fresh attempt: no stale receipt or escalation survives it.
972
+ ackedAt: null,
973
+ ackEvidence: undefined,
974
+ ackOverdue: false,
975
+ escalatedAt: null,
976
+ escalationSeq: null,
977
+ question: null,
978
+ options: [],
979
+ blockedKind: null,
709
980
  }, guard)
981
+ if (!assigned) return
982
+ const ackTimers: Array<ReturnType<typeof setTimeout>> = []
983
+ clearAckTimers = () => {
984
+ while (ackTimers.length > 0) {
985
+ const timer = ackTimers.pop()
986
+ if (timer) clearTimeout(timer)
987
+ }
988
+ }
989
+ const attemptRow = () => record.statuses.find((item: any) => item?.subtaskId === subtask.id)
990
+ const noticeTimer = setTimeout(() => {
991
+ if (guard.timedOut) return
992
+ const row = attemptRow()
993
+ if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
994
+ writeSubtaskStatus(record, subtask.id, { ackOverdue: true }, guard)
995
+ }, ASSIGN_ACK_NOTICE_MS)
996
+ noticeTimer.unref?.()
997
+ ackTimers.push(noticeTimer)
998
+ /*
999
+ * [1.11.0] 180s 仍无回执 → 明确收束为 no-ack,而不是继续静默等待。
1000
+ *
1001
+ * 看门狗默认空闲窗口是 300s,而「根本没启动」和「在慢慢想」在日志上
1002
+ * 都表现为没有新事件。先把状态写成 blocked + blockedKind:'no-ack',
1003
+ * 再中止子会话;主 Agent 因此能立刻看到原因,也能选择续跑。
1004
+ */
1005
+ const deadlineTimer = setTimeout(() => {
1006
+ if (guard.timedOut) return
1007
+ const row = attemptRow()
1008
+ if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
1009
+ const seconds = Math.round(ASSIGN_ACK_DEADLINE_MS / 1000)
1010
+ const message = `派发后 ${seconds}s 未收到子 Agent 任何新事件(no-ack)`
1011
+ writeSubtaskStatus(record, subtask.id, {
1012
+ status: 'blocked',
1013
+ closure: 'blocked',
1014
+ blockedKind: 'no-ack',
1015
+ progress: 100,
1016
+ finishedAt: Date.now(),
1017
+ ackOverdue: true,
1018
+ error: message,
1019
+ summary: `未完成:${message}`,
1020
+ }, guard)
1021
+ recordSubtaskError(record, subtask.id, message, guard)
1022
+ if (!child.controller.signal.aborted) {
1023
+ child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }))
1024
+ }
1025
+ }, ASSIGN_ACK_DEADLINE_MS)
1026
+ deadlineTimer.unref?.()
1027
+ ackTimers.push(deadlineTimer)
710
1028
  const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
711
1029
  const hardTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
712
1030
  const watchdog = createProgressWatchdog({
@@ -724,12 +1042,29 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
724
1042
  // Poll often enough to notice growth inside a short idle window, but
725
1043
  // never more than four times per window.
726
1044
  pollMs: Math.min(CHILD_POLL_MS, Math.max(20, Math.floor(idleTimeoutMs / 4))),
727
- onProgress: ({ now }: any) => {
1045
+ onProgress: ({ now, seq, elapsedMs }: any) => {
728
1046
  if (guard.timedOut) return
729
1047
  // Visible liveness: the dashboard can show that a slow subtask is
730
1048
  // still producing events instead of looking frozen.
731
1049
  record.heartbeatAt = now
732
1050
  record.updatedAt = now
1051
+ /*
1052
+ * [1.11.0] 第一次观察到子会话日志增长 = 回执。
1053
+ *
1054
+ * 这是唯一能证明「子 Agent 已经在动」的廉价事实:不用它自己的
1055
+ * 汇报(可能永远等不到),只看它有没有产生新事件。回执写入后
1056
+ * 两个 no-ack 定时器立即撤销,正常的长任务不会被误判。
1057
+ */
1058
+ const row = attemptRow()
1059
+ if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq) return
1060
+ const acked = writeSubtaskStatus(record, subtask.id, {
1061
+ closure: 'acknowledged',
1062
+ ackedAt: now,
1063
+ ackEvidence: { seq, elapsedMs },
1064
+ ackOverdue: false,
1065
+ progress: Math.max(Number(row.progress ?? 10), 15),
1066
+ }, guard)
1067
+ if (acked) clearAckTimers()
733
1068
  },
734
1069
  makeError: (reason: any) => new PlanError(
735
1070
  reason === 'stalled'
@@ -819,7 +1154,8 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
819
1154
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard)
820
1155
  continue
821
1156
  }
822
- if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
1157
+ /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
1158
+ if (!isAbort && remaining <= idleTimeoutMs) {
823
1159
  record.errors = [
824
1160
  ...(record.errors ?? []),
825
1161
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
@@ -827,6 +1163,7 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
827
1163
  }
828
1164
  break
829
1165
  } finally {
1166
+ clearAckTimers()
830
1167
  if (activation) {
831
1168
  await disposeActivation(activation, record, subtask.id, guard)
832
1169
  activation = null
@@ -834,9 +1171,21 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
834
1171
  }
835
1172
  }
836
1173
 
1174
+ /*
1175
+ * [1.11.0] 已升级的请示不被最终的失败收束覆盖。
1176
+ *
1177
+ * 子 Agent 可能先调用 escalate,再因为中断/超时走到这里;此时问题已经
1178
+ * 写入状态,把它改成普通 blocked 会让主 Agent 永远看不到要回答什么。
1179
+ */
1180
+ const finalRow = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
1181
+ if (finalRow?.closure === 'escalated') {
1182
+ return interruptedFlag ? { interrupted: true } : undefined
1183
+ }
837
1184
  const message = describeError(lastError ?? new Error('未知失败'))
838
1185
  writeSubtaskStatus(record, subtask.id, {
839
1186
  status: 'blocked',
1187
+ closure: 'blocked',
1188
+ blockedKind: 'failed',
840
1189
  progress: 100,
841
1190
  finishedAt: Date.now(),
842
1191
  error: truncate(message, 2000),
@@ -856,8 +1205,15 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
856
1205
  } catch (error) {
857
1206
  const message = describeError(error)
858
1207
  try {
1208
+ const row = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
1209
+ if (row?.closure === 'escalated') {
1210
+ recordSubtaskError(record, subtask.id, `升级后发生异常,保留待指示状态:${message}`, guard)
1211
+ return
1212
+ }
859
1213
  writeSubtaskStatus(record, subtask.id, {
860
1214
  status: 'blocked',
1215
+ closure: 'blocked',
1216
+ blockedKind: 'failed',
861
1217
  progress: 100,
862
1218
  finishedAt: Date.now(),
863
1219
  error: truncate(message, 2000),
@@ -871,32 +1227,75 @@ async function executeSubtask(ctx: any, record: any, stage: any, subtask: any, o
871
1227
  }
872
1228
 
873
1229
  /*
874
- * Runs one subtask under a deadline that belongs to that subtask alone.
1230
+ * One attempt under a deadline that belongs to that attempt alone.
1231
+ *
1232
+ * [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
1233
+ * *fresh* timer. The old code armed a single timer for the whole subtask (shared
1234
+ * by both attempts), so even once the retry decision became reachable the second
1235
+ * attempt would have had no time left — a patch that changes nothing.
875
1236
  *
876
- * The subtask timer is a full settlement guarantee, not just an abort hint: if
877
- * the child activation ignores its abort signal, or never settles at all, the
878
- * race below still resolves, that subtask is recorded as blocked, and the
879
- * dispatcher keeps scheduling the rest of the DAG. This function never throws
880
- * on a per-subtask timeout, so one slow child can no longer blanket-block the
881
- * whole plan — only that subtask (and its real dependents) is affected.
1237
+ * The timer remains a full settlement guarantee, not just an abort hint: if the
1238
+ * child activation ignores its abort signal, or never settles at all, the race
1239
+ * below still resolves, the subtask is recorded as blocked, and the dispatcher
1240
+ * keeps scheduling the rest of the DAG.
882
1241
  */
883
- async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
884
- const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
1242
+ async function runSubtaskAttempt(
1243
+ ctx: any,
1244
+ record: any,
1245
+ stage: any,
1246
+ subtask: any,
1247
+ options: any,
1248
+ timeoutMs: number,
1249
+ ) {
885
1250
  const child = createChildController(options.parentSignal)
886
1251
  const guard: SubtaskGuard = { timedOut: false }
887
1252
  let timer: ReturnType<typeof setTimeout> | null = null
1253
+ let ceilingFired = false
1254
+ // [1.10.6] What the ceiling left on disk, in the words of the same probe the
1255
+ // blocked row records. The retry is compared against exactly this list.
1256
+ let ceilingLanded: string[] = []
1257
+ /*
1258
+ * [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
1259
+ *
1260
+ * The first cut of this check fingerprinted the same refs twice, back to back,
1261
+ * immediately before the retry. Two reads of the same instant can never
1262
+ * differ, so the conflict branch was unreachable in production (only a test
1263
+ * injecting a mutating `stat` could reach it). The record must be taken while
1264
+ * the timeout is being recorded; the pre-retry read is compared against it.
1265
+ */
1266
+ let ceilingFingerprint: any[] = []
1267
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
888
1268
  const deadlinePromise = new Promise<void>((resolve) => {
889
1269
  timer = setTimeout(() => {
1270
+ ceilingFired = true
890
1271
  guard.timedOut = true
891
1272
  // Reached only when the child ignored both its idle window and its
892
1273
  // abort signal; the message says so, otherwise the cause looks like a
893
1274
  // plain "too slow" and the next investigation goes down the wrong path.
894
- const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`
1275
+ const message = `子任务 ${subtask.id} 达到执行上限(${timeoutMs}ms),已强制结束`
895
1276
  try {
896
1277
  // [1.8.19] Keep the evidence of what already landed on disk.
897
- const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
898
- record.statuses = applyStatus(record.statuses, subtask.id, patch)
899
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
1278
+ const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists)
1279
+ ceilingLanded = Array.isArray(landed) ? landed : []
1280
+ ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat)
1281
+ /*
1282
+ * [1.11.0] An escalation outranks the ceiling.
1283
+ *
1284
+ * The child may have written `escalated` seconds before this timer fired;
1285
+ * turning that into a plain timeout would erase the question the main
1286
+ * Agent has to answer. The activation is still aborted, but the row keeps
1287
+ * its pending-decision state.
1288
+ */
1289
+ const existing = record.statuses.find((item: any) => item?.subtaskId === subtask.id)
1290
+ if (existing?.closure === 'escalated') {
1291
+ record.errors = [
1292
+ ...(record.errors ?? []),
1293
+ `${subtask.id}: 已达执行上限,但该子任务已在等待指示,保留 escalated 状态`,
1294
+ ].slice(-20)
1295
+ } else {
1296
+ record.statuses = applyStatus(record.statuses, subtask.id, patch)
1297
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20)
1298
+ }
900
1299
  record.updatedAt = Date.now()
901
1300
  } catch (error: any) {
902
1301
  record.errors = [
@@ -910,13 +1309,13 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
910
1309
  child.disposeListener()
911
1310
  resolve()
912
1311
  }
913
- }, childTimeoutMs)
1312
+ }, timeoutMs)
914
1313
  timer.unref?.()
915
1314
  })
916
1315
  try {
917
1316
  // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
918
1317
  // swallowing it here is why an interrupted child looked like any failure.
919
- return await Promise.race([
1318
+ const outcome = await Promise.race([
920
1319
  executeSubtask(ctx, record, stage, subtask, {
921
1320
  ...options,
922
1321
  child,
@@ -924,6 +1323,7 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
924
1323
  }),
925
1324
  deadlinePromise,
926
1325
  ])
1326
+ return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint }
927
1327
  } finally {
928
1328
  if (timer) {
929
1329
  clearTimeout(timer)
@@ -934,6 +1334,88 @@ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, optio
934
1334
  }
935
1335
  }
936
1336
 
1337
+ /*
1338
+ * Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
1339
+ * round budget can still pay for a second attempt (T6 G1/G3/G4).
1340
+ *
1341
+ * The retry is deliberately narrow:
1342
+ * - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
1343
+ * budget timeout stay non-retryable, because retrying them would be killed by
1344
+ * the same guillotine;
1345
+ * - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
1346
+ * - before it starts, the artifacts the first attempt landed are fingerprinted
1347
+ * (path + size + mtime) and re-checked. If any of them changed since the
1348
+ * timeout was recorded, something else owns that file now: the retry is
1349
+ * skipped and the row is marked `artifactConflict` instead of overwriting it.
1350
+ */
1351
+ async function runSubtask(ctx: any, record: any, stage: any, subtask: any, options: any) {
1352
+ const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs)
1353
+ const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs)
1354
+ if (!first.ceilingFired) return first.outcome
1355
+
1356
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs)
1357
+ const now = Date.now()
1358
+ const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs
1359
+ const remaining = deadline - now
1360
+ const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms)`
1361
+ /*
1362
+ * [1.8.6] A parent abort outranks a retry: the round is being stopped on
1363
+ * purpose, and a second child would only be aborted on arrival.
1364
+ */
1365
+ if (options.parentSignal?.aborted) return first.outcome
1366
+ if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
1367
+ record.errors = [
1368
+ ...(record.errors ?? []),
1369
+ `${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
1370
+ ].slice(-20)
1371
+ return first.outcome
1372
+ }
1373
+ /*
1374
+ * [1.10.6] T6 G3: never retry over work that already exists.
1375
+ *
1376
+ * `ceilingFingerprint` was taken the moment the ceiling fired (inside the
1377
+ * timeout callback); the same refs are re-read right before the retry starts.
1378
+ * A size or mtime difference means the file was written by somebody else in
1379
+ * between, so a retry would overwrite it rather than finish it.
1380
+ */
1381
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync
1382
+ const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat)
1383
+ const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current)
1384
+ const row: any = Array.isArray(record.statuses)
1385
+ ? record.statuses.find((item: any) => item.subtaskId === subtask.id)
1386
+ : null
1387
+ if (conflicts.length > 0) {
1388
+ const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`
1389
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1390
+ artifactConflict: conflicts,
1391
+ error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
1392
+ })
1393
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20)
1394
+ record.updatedAt = Date.now()
1395
+ return first.outcome
1396
+ }
1397
+
1398
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1399
+ status: 'in_progress',
1400
+ progress: 15,
1401
+ // Clearing `error` moves the timeout text to `lastError` (applyStatus does
1402
+ // that move), so the row no longer claims "blocked" while it is retrying.
1403
+ error: null,
1404
+ })
1405
+ record.errors = [
1406
+ ...(record.errors ?? []),
1407
+ `${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
1408
+ ].slice(-20)
1409
+ record.updatedAt = Date.now()
1410
+ const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining))
1411
+ const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
1412
+ ...options,
1413
+ attemptOffset: 2,
1414
+ priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已强制结束` },
1415
+ }, retryTimeoutMs)
1416
+ return second.outcome
1417
+ }
1418
+
937
1419
  async function runWithConcurrency(items: any, limit: any, worker: any) {
938
1420
  let cursor = 0
939
1421
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
@@ -991,6 +1473,29 @@ export function modelStatusLines(statuses: any) {
991
1473
  updatedBy: item.updatedBy ?? null,
992
1474
  missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
993
1475
  needs: Array.isArray(item.needs) ? item.needs : [],
1476
+ // [1.11.0] 闭环阶段必须进入模型可读面:只暴露四值 status 时,
1477
+ // 「在等指示」和「做失败了」在工具输出里长得一模一样。
1478
+ closure: item.closure ?? null,
1479
+ blockedKind: item.blockedKind ?? null,
1480
+ question: item.question ?? null,
1481
+ options: Array.isArray(item.options) ? item.options : [],
1482
+ ackOverdue: item.ackOverdue === true,
1483
+ escalatedAt: item.escalatedAt ?? null,
1484
+ instruction: item.instruction?.text ? truncate(item.instruction.text, 500) : null,
1485
+ /*
1486
+ * [1.11.0] 跨部门需求的待处理项必须出现在模型可读面(用户 m00687)。
1487
+ *
1488
+ * 只放在结果消息里时,主 Agent 一旦错过那一轮就再也看不到「还有一条
1489
+ * 需求没处置」,而交付门禁却一直拦着。status 工具是与进度同源的读取口,
1490
+ * 这里只暴露未处置项,避免把已答复的历史反复塞进上下文。
1491
+ */
1492
+ openHandoffs: openHandoffs(item).map((handoff: any) => ({
1493
+ id: handoff.id,
1494
+ request: truncate(String(handoff.request ?? ''), 300),
1495
+ department: handoff.department ?? null,
1496
+ status: handoff.status,
1497
+ })),
1498
+ reportedAt: item.reportedAt ?? null,
994
1499
  }))
995
1500
  }
996
1501
 
@@ -1008,6 +1513,14 @@ export function buildRoundResult(record: any, sessionId: any, limits: any) {
1008
1513
  phase: record.phase,
1009
1514
  resumeCount: Number(record.resumeCount ?? 0),
1010
1515
  resumeAvailable: canResumePlan(record, limits.maxResumes).resume,
1516
+ // [1.11.0] 结果消息也带上修订号,回放时才知道这份结果属于哪一版计划。
1517
+ planRevision: Number(record.planRevision ?? 0),
1518
+ /*
1519
+ * [1.11.0] C-17:记录级闭环事实随结果消息下发,让摘要里的判定与
1520
+ * `deliveryReady` 门禁读同一组输入(否则「结果说完成、present 被拒」)。
1521
+ */
1522
+ changePending: record.changeRequest?.status === 'pending',
1523
+ reportPending: record.reportPending === true,
1011
1524
  })
1012
1525
  }
1013
1526
 
@@ -1059,6 +1572,11 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1059
1572
  * its side effects) while giving the rest a second chance, and the resume
1060
1573
  * budget stops a subtask that always fails from looping forever.
1061
1574
  */
1575
+ /*
1576
+ * [1.11.0] 重规划 cancel 留下的悬挂下游,在派发前显式收束成 blocked
1577
+ * (T4 D-T4-02)。否则它们永远 pending,既不报错也不进入交付阻塞。
1578
+ */
1579
+ record.statuses = blockCancelledDependents(record.plan, record.statuses)
1062
1580
  const resume = canResumePlan(record, options.maxResumes ?? MAX_PLAN_RESUMES)
1063
1581
  if (resume.resume) {
1064
1582
  /*
@@ -1081,7 +1599,13 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1081
1599
  `第 ${record.resumeCount} 次续跑:已重置 ${resume.failed} 个受阻子任务(已完成的不重跑)`,
1082
1600
  ].slice(-20)
1083
1601
  } else {
1084
- record.errors = (record.errors ?? []).filter((line: string) => !/预算|续跑/.test(String(line))).slice(-20)
1602
+ /*
1603
+ * [1.10.4] 保留自动续跑的审计行:它们必然含「续跑/预算」字样,旧过滤器
1604
+ * 会把「为什么自动续跑、停在哪个判定码」一起擦掉,正好毁掉事后取证。
1605
+ */
1606
+ record.errors = (record.errors ?? [])
1607
+ .filter((line: string) => !/预算|续跑/.test(String(line)) || String(line).includes('[auto-resume]'))
1608
+ .slice(-20)
1085
1609
  }
1086
1610
  }
1087
1611
  const parentSignal = signal
@@ -1119,9 +1643,19 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1119
1643
  * an older plan or a debugging session can keep plain status semantics.
1120
1644
  */
1121
1645
  const gate = options.artifactGate !== false
1122
- const ready = readySubtasks(record.plan, record.statuses, gate
1646
+ const ready = readySubtasks(record.plan, liveStatuses(record.statuses), gate
1123
1647
  ? {
1648
+ /*
1649
+ * [1.11.0] 未验收的 done 不再解锁下游(T5 C5 / T8 S1-05)。
1650
+ *
1651
+ * `done` 只说明子 Agent 交了东西;`unverified`/`failed` 说明
1652
+ * 交付内容没有通过验收。让下游在这时开跑,等于把未验证的结论
1653
+ * 当上游契约使用——跨部门链条会一路放大错误。legacy(旧日志)
1654
+ * 与 structured 仍放行,避免历史计划整体卡死。
1655
+ */
1124
1656
  dependencyOk: (dependency: any) => dependency?.status === 'done'
1657
+ && dependency?.verification !== 'unverified'
1658
+ && dependency?.verification !== 'failed'
1125
1659
  && !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
1126
1660
  }
1127
1661
  : {})
@@ -1136,7 +1670,7 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1136
1670
  * status, the plan turned `blocked`, and a resume was billed against
1137
1671
  * the failure budget. Keep them `pending`, and record the actual cause.
1138
1672
  */
1139
- const pending = record.statuses.filter((item: any) => item.status === 'pending')
1673
+ const pending = liveStatuses(record.statuses).filter((item: any) => item.status === 'pending')
1140
1674
  if (pending.length > 0) {
1141
1675
  const reasons = pending.map((item: any) =>
1142
1676
  `${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`)
@@ -1164,6 +1698,9 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1164
1698
  conversationContext,
1165
1699
  strictEvidence: options.strictEvidence,
1166
1700
  artifactExists: options.artifactExists,
1701
+ // [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
1702
+ // use it so the conflict branch is provable without real files.
1703
+ artifactStat: options.artifactStat,
1167
1704
  })
1168
1705
  // [1.8.6] Remember which failures were interrupts, so the cascade below
1169
1706
  // can leave their dependents pending instead of blaming them.
@@ -1214,8 +1751,8 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1214
1751
  * `blocked` for real failures, and report `paused` when only pending work
1215
1752
  * is left, so a resume is not billed against the failure budget.
1216
1753
  */
1217
- const hasBlocked = record.statuses.some((item: any) => item.status === 'blocked')
1218
- const hasPending = record.statuses.some((item: any) => item.status === 'pending')
1754
+ const hasBlocked = liveStatuses(record.statuses).some((item: any) => item.status === 'blocked')
1755
+ const hasPending = liveStatuses(record.statuses).some((item: any) => item.status === 'pending')
1219
1756
  record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses))
1220
1757
  } catch (error) {
1221
1758
  const message = describeError(error)
@@ -1287,6 +1824,8 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1287
1824
  * or 100 % depending on which branch happened to write it.
1288
1825
  */
1289
1826
  record.statuses = record.statuses.map((item: any) => {
1827
+ // [1.11.0] 被重规划的行不参与「失败收敛」:它们本来就是闭态旧行。
1828
+ if (item.closure === 'replanned') return item
1290
1829
  if (item.status === 'pending' || item.status === 'in_progress') {
1291
1830
  return {
1292
1831
  ...item,
@@ -1419,7 +1958,19 @@ function serialisePlan(record: any, session: any) {
1419
1958
  : plan
1420
1959
  ? createStatuses(plan)
1421
1960
  : []
1422
- const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses)
1961
+ /*
1962
+ * [1.10.0] 分母来自计划定义,并允许「明细行少于定义」时按 pending 补齐。
1963
+ * `definedSubtaskCount` 对畸形计划返回 MAX_SAFE_INTEGER,那种情况下退回
1964
+ * 「只数明细行」,避免把一个坏计划直接判成 0/天文数字。
1965
+ */
1966
+ const defined = plan ? definedSubtaskCount(plan) : 0
1967
+ const expectedTotal = Number.isFinite(defined) && defined > 0 && defined < Number.MAX_SAFE_INTEGER
1968
+ ? defined
1969
+ : undefined
1970
+ const snapshot = derivePlanSnapshot(
1971
+ turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses,
1972
+ expectedTotal,
1973
+ )
1423
1974
  const statuses = snapshot.statuses
1424
1975
  const stats = snapshot.stats
1425
1976
  /*
@@ -1471,7 +2022,7 @@ function serialisePlan(record: any, session: any) {
1471
2022
  * 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
1472
2023
  */
1473
2024
  const violations = aggregateInvariantViolations(snapshot, phase)
1474
- const readiness = deliveryReadiness(snapshot, { phase: record.phase })
2025
+ const readiness = readinessOf(record, snapshot)
1475
2026
  return {
1476
2027
  sessionId: session.id,
1477
2028
  planId: record.planId ?? plan?.planId ?? null,
@@ -1481,7 +2032,18 @@ function serialisePlan(record: any, session: any) {
1481
2032
  ...(violations.length ? { violations } : {}),
1482
2033
  degraded: record.degraded === true,
1483
2034
  error: record.error ? truncate(record.error, 2000) : null,
1484
- errors: (record.errors ?? []).slice(-20),
2035
+ /*
2036
+ * [1.10.0] C-18:「已结束 / 已完成」的计划不再把上一轮的失败文本摆在首页。
2037
+ *
2038
+ * 1.9.1 把 `record.errors`("本轮执行预算已到:已完成 9/13…" 之类)无条件
2039
+ * 下发,界面又无条件渲染,于是 13/13 完成的那一帧下面还挂着一句「这件事没有
2040
+ * 做完」。现在:计划已 done 或 cancelled 时,这批文本改挂 `archivedErrors`,
2041
+ * 供折叠区/审计使用;`errors` 只在计划仍需处理时下发。
2042
+ */
2043
+ errors: phase === 'done' || phase === 'cancelled' ? [] : (record.errors ?? []).slice(-20),
2044
+ ...(phase === 'done' || phase === 'cancelled'
2045
+ ? { archivedErrors: (record.errors ?? []).slice(-20) }
2046
+ : {}),
1485
2047
  createdAt: record.createdAt ?? plan?.createdAt ?? session.header.createdAt,
1486
2048
  updatedAt: record.updatedAt ?? Date.now(),
1487
2049
  createdTurn: plan?.createdTurn ?? record.createdTurn ?? null,
@@ -1499,6 +2061,16 @@ function serialisePlan(record: any, session: any) {
1499
2061
  deliveryReady: readiness.ready,
1500
2062
  deliveryBlockers: readiness.blockers.slice(0, 12),
1501
2063
  deliveryRemaining: readiness.remaining.slice(0, 20),
2064
+ /*
2065
+ * [1.11.0] 重规划与回报状态随载荷下发(T7 C-15)。
2066
+ *
2067
+ * `planRevision` 让界面能显示「第 N 次修订」;`changeRequest` 是执行中
2068
+ * 收到、尚未重规划的用户变更;`reportPending` 表示完成结果还没成功回报。
2069
+ * 三者都来自 record 的同一份事实,不另建缓存。
2070
+ */
2071
+ planRevision: Number(record.planRevision ?? 0),
2072
+ changeRequest: record.changeRequest ?? null,
2073
+ reportPending: record.reportPending === true,
1502
2074
  /*
1503
2075
  * Liveness and resume bookkeeping. Without these the dashboard could not
1504
2076
  * tell a slow-but-alive child from a wedged one, and the model could not
@@ -1637,6 +2209,9 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1637
2209
  * subtask at the budget boundary (wp-40ce5eee, 17:51:37).
1638
2210
  */
1639
2211
  errors: string[]
2212
+ /* [1.11.0] 重规划修订号与未处理的变更请求,随 durable 消息回放。 */
2213
+ planRevision: number
2214
+ changeRequest: any
1640
2215
  }
1641
2216
  /*
1642
2217
  * [1.8.9] 回放按 planId 分账,不按会话「最后一个计划」分账。
@@ -1663,6 +2238,8 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1663
2238
  superseded: false,
1664
2239
  supersededBy: undefined,
1665
2240
  errors: [],
2241
+ planRevision: Number(plan?.planRevision ?? 0) || 0,
2242
+ changeRequest: null,
1666
2243
  }
1667
2244
  snapshots.set(plan.planId, snap)
1668
2245
  }
@@ -1703,6 +2280,44 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1703
2280
  * that was the 13/14 → 5/14 replay regression. A plan never inherits
1704
2281
  * another plan's round phase or resume counter (each snapshot owns them).
1705
2282
  */
2283
+ /*
2284
+ * [1.11.0] 重规划记录:采用 durable 消息里的完整修订计划,不重新推导。
2285
+ * 旧行在同一份 plan 里带 supersededAt,状态条目同步标 closure='replanned'。
2286
+ */
2287
+ const replan = parseReplanMessage(event.data)
2288
+ if (replan && typeof replan.planId === 'string') {
2289
+ const snap = snapshots.get(replan.planId)
2290
+ if (snap) {
2291
+ snap.plan = replan.plan
2292
+ snap.planRevision = Number(replan.revision) || snap.planRevision
2293
+ snap.statuses = applyReplanStatuses(snap.statuses, replan)
2294
+ if (snap.changeRequest && snap.changeRequest.status !== 'replanned') {
2295
+ snap.changeRequest = {
2296
+ ...snap.changeRequest,
2297
+ status: 'replanned',
2298
+ replannedAt: replan.at,
2299
+ planRevision: snap.planRevision,
2300
+ }
2301
+ }
2302
+ }
2303
+ }
2304
+ /*
2305
+ * [1.11.0] 执行中收到的变更:恢复成 changeRequest,刷新后仍然可见、
2306
+ * 仍然阻止“静默收尾”。
2307
+ */
2308
+ const change = parseChangeRequestMessage(event.data)
2309
+ if (change && typeof change.planId === 'string') {
2310
+ const snap = snapshots.get(change.planId)
2311
+ if (snap) {
2312
+ snap.changeRequest = {
2313
+ seq: change.seq,
2314
+ text: change.text,
2315
+ at: change.at,
2316
+ turn: change.turn,
2317
+ status: 'pending',
2318
+ }
2319
+ }
2320
+ }
1706
2321
  const result = parseResultMessage(event.data)
1707
2322
  if (result && typeof result.planId === 'string') {
1708
2323
  const snap = snapshots.get(result.planId)
@@ -1939,6 +2554,20 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
1939
2554
  superseded,
1940
2555
  supersedeRecorded: superseded,
1941
2556
  supersededBy: superseded ? chosen.supersededBy : undefined,
2557
+ /*
2558
+ * [1.11.0] 回放也恢复修订号与未处理变更。`reportPending` 由状态本身派生:
2559
+ * 存在 done 行却没到 reported,说明当时的结果消息没有成功写进会话。
2560
+ */
2561
+ planRevision: chosen.planRevision,
2562
+ changeRequest: chosen.changeRequest,
2563
+ /*
2564
+ * [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
2565
+ * 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
2566
+ * 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
2567
+ * 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
2568
+ */
2569
+ reportPending: statuses.some((item: any) =>
2570
+ item?.status === 'done' && item?.closure === 'done'),
1942
2571
  }
1943
2572
  }
1944
2573
 
@@ -2023,6 +2652,24 @@ export type WorkplanRuntimeOptions = {
2023
2652
  totalTimeoutMs?: number
2024
2653
  /** How many times a blocked plan may be resumed. */
2025
2654
  maxResumes?: number
2655
+ /**
2656
+ * [1.10.4] 整轮预算到点后自动开始下一轮。**默认关闭**:默认值来自
2657
+ * `AUTO_RESUME_DEFAULTS.enabled=false`,必须由宿主显式打开。
2658
+ *
2659
+ * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败),
2660
+ * 也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2661
+ */
2662
+ autoResume?: boolean
2663
+ /** 自动续跑轮次上限(0–4,默认 2)。 */
2664
+ autoResumeMaxAttempts?: number
2665
+ /**
2666
+ * [1.11.0] 完成必回报开关(C-05 / M3)。
2667
+ *
2668
+ * `undefined`/`true` = 严格:子任务没有结构化证据块时判 `blocked/unverified`;
2669
+ * `false` = 兼容 1.10.6 的 `done/legacy`。宿主从 `WorkplanConfig.strictCompletion`
2670
+ * 或 `DSH_WORKPLAN_STRICT_COMPLETION` 解析后传入。
2671
+ */
2672
+ strictEvidence?: boolean
2026
2673
  /**
2027
2674
  * [1.8.13] Package version, supplied by the host from its `meta.version`.
2028
2675
  *
@@ -2104,6 +2751,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2104
2751
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
2105
2752
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
2106
2753
  : MAX_PLAN_RESUMES,
2754
+ autoResume: {
2755
+ enabled: options.autoResume === true,
2756
+ maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2757
+ },
2107
2758
  }
2108
2759
 
2109
2760
  async function onPreStep(payload: any, next: any) {
@@ -2115,6 +2766,19 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2115
2766
  }
2116
2767
  if (downstream?.kind !== 'enter') return downstream
2117
2768
  try {
2769
+ /*
2770
+ * [1.11.0] 回报自愈(契约 §7.3 B4):上一轮结果消息已写入,但回报标记
2771
+ * 写失败/进程中断时,下一步 pre-step 幂等补齐,不重复追加上下文。
2772
+ */
2773
+ const session = payload.agent?.session
2774
+ const known = session ? state.records.get(session.id) : null
2775
+ if (known?.plan && known.reportPending === true && known.resultWritten === true) {
2776
+ const changed = markReported(known, session, `${known.plan.planId}:${known.dispatchedAt ?? 0}`)
2777
+ if (changed > 0) {
2778
+ known.reportPending = (known.statuses ?? []).some((item: any) =>
2779
+ item?.status === 'done' && item?.closure === 'done')
2780
+ }
2781
+ }
2118
2782
  return await maybePlan(ctx, state, payload, downstream, { ...options, limits })
2119
2783
  } catch (error) {
2120
2784
  try {
@@ -2190,6 +2854,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2190
2854
  if (!record?.plan) record = reconstructFromSession(session, args?.planId)
2191
2855
  record = adoptRequestedPlan(session, record, args?.planId)
2192
2856
  if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
2857
+ // [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
2858
+ clearAutoResumeTimer(record, 'manual-update')
2193
2859
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : ''
2194
2860
  if (!subtaskId) throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK')
2195
2861
  const status = typeof args?.status === 'string' ? args.status : ''
@@ -2242,6 +2908,59 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2242
2908
  hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
2243
2909
  }
2244
2910
  }
2911
+ /*
2912
+ * [1.11.0] 待指示行的两条合法出口(T4 S4→S5 / S4→S6)。
2913
+ *
2914
+ * `dsh_workplan_update` 也是 `instruct` 的等价入口:带 instruction 即恢复
2915
+ * 推进,不带 instruction 直接 in_progress/done 会把一条未回答的请示洗成
2916
+ * 「在做/做完」,所以显式拒绝,并告诉主 Agent 该用哪个字段。
2917
+ */
2918
+ const instruction = typeof args?.instruction === 'string' ? args.instruction.trim() : ''
2919
+ if (instruction) {
2920
+ if (current?.closure !== 'escalated') {
2921
+ return {
2922
+ ok: false,
2923
+ code: 'NOT_ESCALATED',
2924
+ planId: record.plan.planId,
2925
+ subtaskId,
2926
+ error: '该子任务不在待指示状态,不需要 instruction;普通受阻请直接改判。',
2927
+ }
2928
+ }
2929
+ if (status !== 'in_progress') {
2930
+ return {
2931
+ ok: false,
2932
+ code: 'INSTRUCTION_REQUIRES_IN_PROGRESS',
2933
+ planId: record.plan.planId,
2934
+ subtaskId,
2935
+ error: '下发 instruction 时 status 必须是 in_progress(或改用 dsh_workplan_instruct)。',
2936
+ }
2937
+ }
2938
+ return instructSubtask(agent, {
2939
+ planId: args?.planId,
2940
+ subtaskId,
2941
+ instruction,
2942
+ }, undefined, record)
2943
+ }
2944
+ if (current?.closure === 'escalated') {
2945
+ if (status === 'done') {
2946
+ return {
2947
+ ok: false,
2948
+ code: 'ESCALATION_OPEN',
2949
+ planId: record.plan.planId,
2950
+ subtaskId,
2951
+ error: '该子任务仍在等待指示,不能直接改判 done:请先给出 instruction,或明确改判 blocked 放弃。',
2952
+ }
2953
+ }
2954
+ if (status === 'in_progress') {
2955
+ return {
2956
+ ok: false,
2957
+ code: 'INSTRUCTION_REQUIRED',
2958
+ planId: record.plan.planId,
2959
+ subtaskId,
2960
+ error: '该子任务正在等待指示:恢复推进必须传 instruction(或调用 dsh_workplan_instruct),不能只改 status。',
2961
+ }
2962
+ }
2963
+ }
2245
2964
  const revision = Number(current?.revision ?? 0) + 1
2246
2965
  /*
2247
2966
  * [1.8.13] A manual verdict can carry structured evidence.
@@ -2264,6 +2983,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2264
2983
  summary: summary || undefined,
2265
2984
  error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
2266
2985
  ...evidencePatch,
2986
+ /*
2987
+ * [1.11.0] 明确放弃(blocked)必须同时关掉 escalated,否则
2988
+ * applyStatus 会保留「等指示」投影,主 Agent 的放弃写了个寂寞。
2989
+ */
2990
+ ...(current?.closure === 'escalated' && status === 'blocked'
2991
+ ? { closure: 'blocked', blockedKind: 'failed', question: null, options: [] }
2992
+ : {}),
2267
2993
  revision,
2268
2994
  updatedBy: 'agent',
2269
2995
  })
@@ -2290,6 +3016,12 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2290
3016
  acceptance: writtenRow?.acceptance,
2291
3017
  artifacts: writtenRow?.artifacts,
2292
3018
  missingArtifacts: writtenRow?.missingArtifacts,
3019
+ closure: writtenRow?.closure,
3020
+ blockedKind: writtenRow?.blockedKind,
3021
+ question: writtenRow?.question,
3022
+ options: writtenRow?.options,
3023
+ instruction: writtenRow?.instruction,
3024
+ instructionSeq: writtenRow?.instructionSeq,
2293
3025
  }), { surfaceOp: 'append' })
2294
3026
  } catch (error) {
2295
3027
  pushRecordError(record, error)
@@ -2307,7 +3039,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2307
3039
  record.updatedAt = Date.now()
2308
3040
  const snapshot = derivePlanSnapshot(record.statuses)
2309
3041
  const written = snapshot.statuses.find((item: any) => item.subtaskId === subtaskId)
2310
- const readiness = deliveryReadiness(snapshot, { phase: record.phase })
3042
+ const readiness = readinessOf(record, snapshot)
2311
3043
  return {
2312
3044
  ok: true,
2313
3045
  planId: record.plan.planId,
@@ -2329,6 +3061,121 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2329
3061
  }
2330
3062
  }
2331
3063
 
3064
+ /**
3065
+ * [1.11.0] C-11:需求变更的唯一写入入口(dsh_workplan_replan)。
3066
+ *
3067
+ * 为什么必须单独一个工具,而不是让模型直接改计划消息:
3068
+ * 1. 旧行的 `supersededAt` 与状态条的 `closure:'replanned'` 必须同一次写入,
3069
+ * 否则调度器会继续跑「已撤销」的工作;
3070
+ * 2. durable `workplan-replan` 带上完整修订计划,刷新后才能得到同一份定义;
3071
+ * 3. 执行中收到变更时,工具返回 `REPLAN_PLAN_RUNNING` 并保留 changeRequest,
3072
+ * 让模型等待而不是静默丢弃或强行中断正在跑的子任务。
3073
+ */
3074
+ async function replanPlan(agent: any, args: any) {
3075
+ const session = agent?.session
3076
+ if (!session) throw new PlanError('只能在会话内重规划', 'NO_SESSION')
3077
+ if (!isRootSession(session)) throw new PlanError('子 Agent 不能重规划主计划', 'NOT_ROOT')
3078
+ let record = state.records.get(session.id)
3079
+ if (!record?.plan) record = reconstructFromSession(session, args?.planId)
3080
+ record = adoptRequestedPlan(session, record, args?.planId)
3081
+ if (!record?.plan) throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN')
3082
+ const planId = record.plan.planId
3083
+ const revisionNow = Number(record.planRevision ?? record.plan?.planRevision ?? 0)
3084
+ const base = {
3085
+ ok: false,
3086
+ planId,
3087
+ planRevision: revisionNow,
3088
+ stats: derivePlanSnapshot(record.statuses).stats,
3089
+ }
3090
+ if (record.phase === 'cancelled' || record.phase === 'superseded' || record.superseded === true) {
3091
+ return {
3092
+ ...base,
3093
+ code: 'REPLAN_TERMINAL',
3094
+ error: '计划已是终态(已取消/已被取代),不能重规划',
3095
+ hint: '终态计划不会复活:如需继续这项工作,请让主 Agent 生成新计划。',
3096
+ }
3097
+ }
3098
+ if (record.dispatchPromise) {
3099
+ /*
3100
+ * 执行中拒绝改写定义,但把变更原文记下来。旧行为(maybePlan 直接
3101
+ * return downstream)会让用户在派发期间说的新需求彻底消失。
3102
+ */
3103
+ const change = typeof args?.changeText === 'string' ? truncate(args.changeText.trim(), 4000) : ''
3104
+ if (change) {
3105
+ const seq = Number(record.changeRequestSeq ?? 0) + 1
3106
+ record.changeRequestSeq = seq
3107
+ record.changeRequest = {
3108
+ seq,
3109
+ text: change,
3110
+ at: Date.now(),
3111
+ turn: Number(state.activeTurns?.get?.(session.id) ?? NaN) || null,
3112
+ status: 'pending',
3113
+ }
3114
+ record.updatedAt = Date.now()
3115
+ }
3116
+ state.records.set(session.id, record)
3117
+ return {
3118
+ ...base,
3119
+ code: 'REPLAN_PLAN_RUNNING',
3120
+ error: '本轮派发仍在执行:重规划不会中途改写正在跑的子任务',
3121
+ hint: '先轮询 dsh_workplan_status 等本轮结束(或先 cancel 并等它收敛),再提交同一组 changes;变更已记录为 changeRequest,不会丢失。',
3122
+ running: true,
3123
+ changeRequest: record.changeRequest ?? null,
3124
+ }
3125
+ }
3126
+ const revision = revisionNow + 1
3127
+ const at = Date.now()
3128
+ const result = planReplan(record.plan, args?.changes, {
3129
+ planId,
3130
+ reason: args?.reason,
3131
+ revision,
3132
+ at,
3133
+ })
3134
+ if (!result.ok) return { ...base, code: result.code, error: result.error }
3135
+ /*
3136
+ * 先落 durable 记录,再改内存:写失败时计划保持原样,不会出现
3137
+ * 「内存里已经改了、刷新后又退回去」的分叉。
3138
+ */
3139
+ try {
3140
+ session.append('user/message', buildReplanMessage(result.payload), { surfaceOp: 'append' })
3141
+ } catch (error) {
3142
+ return {
3143
+ ...base,
3144
+ code: 'REPLAN_WRITE_FAILED',
3145
+ error: `写入重规划记录失败:${error instanceof Error ? error.message : String(error)}`,
3146
+ hint: '计划未被改动;修复会话写入问题后重试同一组 changes。',
3147
+ }
3148
+ }
3149
+ record.plan = result.payload.plan
3150
+ record.planRevision = revision
3151
+ record.statuses = applyReplanStatuses(record.statuses, result.payload)
3152
+ record.phase = planPhase(record.statuses)
3153
+ record.error = null
3154
+ record.updatedAt = at
3155
+ if (record.changeRequest && record.changeRequest.status !== 'replanned') {
3156
+ record.changeRequest = {
3157
+ ...record.changeRequest,
3158
+ status: 'replanned',
3159
+ replannedAt: at,
3160
+ planRevision: revision,
3161
+ }
3162
+ }
3163
+ state.records.set(session.id, record)
3164
+ const snapshot = derivePlanSnapshot(record.statuses, definedSubtaskCount(record.plan))
3165
+ return {
3166
+ ok: true,
3167
+ planId,
3168
+ planRevision: revision,
3169
+ reason: result.payload.reason,
3170
+ marks: result.payload.marks,
3171
+ added: result.payload.added,
3172
+ phase: record.phase,
3173
+ stats: snapshot.stats,
3174
+ statuses: modelStatusLines(snapshot.statuses),
3175
+ hint: '旧行保留为 closure=replanned(可追溯、不计入剩余项、不再调度);修订后的新行是 pending,调用 dsh_workplan_dispatch 才会执行。',
3176
+ }
3177
+ }
3178
+
2332
3179
  async function cancelPlan(agent: any, args: any) {
2333
3180
  const session = agent?.session
2334
3181
  if (!session) throw new PlanError('只能在会话内取消计划', 'NO_SESSION')
@@ -2380,6 +3227,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2380
3227
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2381
3228
  ? args.reason.trim()
2382
3229
  : '用户取消'
3230
+ // [1.10.4] 取消是终态:必须撤销已排期的自动续跑,否则定时器会在取消之后复活计划。
3231
+ clearAutoResumeTimer(record, 'cancelled')
2383
3232
  /*
2384
3233
  * [1.5.2] 已完成即终态:取消不再把 100% 的计划改写成「已取消」。
2385
3234
  *
@@ -2511,20 +3360,281 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2511
3360
  }
2512
3361
  }
2513
3362
 
2514
- /**
2515
- * Persist the round result and settle the phase.
3363
+ /*
3364
+ * [1.10.4][auto-resume] 自动续跑的记账与排期。
2516
3365
  *
2517
- * Extracted from the wait path so an async dispatch reaches exactly the same
2518
- * end state: a durable result message plus a reconciled phase. Anything less
3366
+ * 为什么在工具层而不是 `dispatchPlan` 里:被整轮预算中止时,这一轮已经没有
3367
+ * 预算可用,轮内重试必然再被同一把闸刀砍掉(`shouldRetryAttempt` 对
3368
+ * `TOTAL_TIMEOUT` / `ABORTED` 恒为 false 是正确的)。能重试的只有「下一轮」:
3369
+ * 新预算、新截止时间,未完成项由 `resetBlockedStatuses` 放回 pending,
3370
+ * done 项永不重跑。所以调度点属于「谁结束了一轮」,也就是这里。
3371
+ *
3372
+ * 所有停止分支都由纯函数 `decideAutoResume` 判定,本层只负责:
3373
+ * - 记录 done 水位与连续无进展轮数(防止空转);
3374
+ * - 用 unref 的定时器排期,并在取消/人工派发/进程销毁时撤销;
3375
+ * - 起跑前再核对一次记录身份与阶段(定时器期间状态可能已变)。
3376
+ */
3377
+ function autoResumeBook(record: any) {
3378
+ if (!record.autoResume || typeof record.autoResume !== 'object') {
3379
+ record.autoResume = {
3380
+ attempt: 0,
3381
+ noProgressRounds: 0,
3382
+ doneBefore: null,
3383
+ nextAt: null,
3384
+ timer: null,
3385
+ lastDecision: null,
3386
+ history: [],
3387
+ }
3388
+ }
3389
+ return record.autoResume
3390
+ }
3391
+
3392
+ function clearAutoResumeTimer(record: any, reason: string) {
3393
+ const book = record?.autoResume
3394
+ if (!book) return false
3395
+ book.nextAt = null
3396
+ if (!book.timer) return false
3397
+ clearTimeout(book.timer)
3398
+ book.timer = null
3399
+ book.lastStopReason = reason
3400
+ return true
3401
+ }
3402
+
3403
+ function autoResumeView(record: any) {
3404
+ const book = record?.autoResume
3405
+ return {
3406
+ enabled: limits.autoResume.enabled,
3407
+ attempt: Number(book?.attempt ?? 0),
3408
+ maxAttempts: limits.autoResume.maxAttempts,
3409
+ armed: Boolean(book?.timer),
3410
+ nextInMs: book?.nextAt ? Math.max(0, Number(book.nextAt) - Date.now()) : null,
3411
+ lastCode: book?.lastDecision?.code ?? null,
3412
+ lastReason: book?.lastDecision?.reason ?? null,
3413
+ lastStopReason: book?.lastStopReason ?? null,
3414
+ }
3415
+ }
3416
+
3417
+ /**
3418
+ * 在一轮结束后决定是否再开一轮。
3419
+ *
3420
+ * @param record - 当前计划记录。
3421
+ * @param session - 根会话(结果消息与子 Agent 都归属它)。
3422
+ * @param base - 本轮派发的可复用参数(agent / modelSelection / cwd / conversationContext)。
3423
+ */
3424
+ function armAutoResume(record: any, session: any, base: any) {
3425
+ const book = autoResumeBook(record)
3426
+ clearAutoResumeTimer(record, 'rearmed')
3427
+ const snapshot = derivePlanSnapshot(record.statuses)
3428
+ const stats: any = snapshot.stats ?? {}
3429
+ const statuses: any[] = Array.isArray(record.statuses) ? record.statuses : []
3430
+ const done = Number(stats.done ?? 0)
3431
+ const doneBefore = Number.isFinite(Number(book.doneBefore)) ? Number(book.doneBefore) : done
3432
+ /*
3433
+ * 「有进展」只认新增的 done 行。被预算中止的子任务会把 error 从 pending
3434
+ * 一路写到重置,只有真正完成才会抬高 done;用 done 作水位既不会把
3435
+ * 「重跑一次又失败」误判成进展,也不会因错误文案变化而空转。
3436
+ */
3437
+ if (done > doneBefore) book.noProgressRounds = 0
3438
+ else if (Number(book.attempt ?? 0) > 0) book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1
3439
+ book.doneBefore = done
3440
+ const pending = statuses.filter((item: any) => item?.status === 'pending').length
3441
+ const blocked = statuses.filter((item: any) => item?.status === 'blocked').length
3442
+ /*
3443
+ * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
3444
+ *
3445
+ * T7 实测:`armAutoResume` 在每一轮结束后都会被调用,正常完成的轮也会走到
3446
+ * `PHASE_NOT_PAUSED` 分支,于是每个顺利结束的计划都在 `record.errors` 里多一条
3447
+ * 「[auto-resume] 停止」——把真正需要看的中止信息埋掉。全部 done 且没有
3448
+ * pending/blocked 时,直接静默收尾,不写台账。
3449
+ */
3450
+ if (Number(stats.total ?? 0) > 0 && pending === 0 && blocked === 0 && done === Number(stats.total ?? 0)) {
3451
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code: 'NOTHING_PENDING', reason: '全部子任务已 done,无需自动续跑' }
3452
+ return book.lastDecision
3453
+ }
3454
+ const decision = decideAutoResume({
3455
+ enabled: limits.autoResume.enabled,
3456
+ phase: record.phase,
3457
+ cancelled: record.cancelled === true,
3458
+ degraded: record.degraded === true,
3459
+ planMode: isPlanModeActive(ctx, session),
3460
+ running: Boolean(record.dispatchPromise),
3461
+ total: Number(stats.total ?? 0),
3462
+ done,
3463
+ pending,
3464
+ blocked,
3465
+ attempt: Number(book.attempt ?? 0),
3466
+ maxAttempts: limits.autoResume.maxAttempts,
3467
+ noProgressRounds: Number(book.noProgressRounds ?? 0),
3468
+ stallLimit: AUTO_RESUME_DEFAULTS.stallLimit,
3469
+ baseDelayMs: AUTO_RESUME_DEFAULTS.baseDelayMs,
3470
+ maxDelayMs: AUTO_RESUME_DEFAULTS.maxDelayMs,
3471
+ })
3472
+ book.lastDecision = { at: Date.now(), phase: record.phase, ...decision }
3473
+ book.history = [...(book.history ?? []), {
3474
+ at: Date.now(),
3475
+ phase: record.phase,
3476
+ done,
3477
+ pending,
3478
+ blocked,
3479
+ attempt: Number(book.attempt ?? 0),
3480
+ action: decision.action,
3481
+ code: decision.code,
3482
+ }].slice(-10)
3483
+ if (decision.action !== 'schedule') {
3484
+ /*
3485
+ * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
3486
+ * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
3487
+ */
3488
+ if (decision.code !== 'AUTO_RESUME_DISABLED') {
3489
+ record.errors = [...(record.errors ?? []),
3490
+ `[auto-resume] 停止(${decision.code}):${decision.reason}`].slice(-20)
3491
+ }
3492
+ return decision
3493
+ }
3494
+ const attempt = Number(book.attempt ?? 0) + 1
3495
+ book.attempt = attempt
3496
+ book.nextAt = Date.now() + decision.delayMs
3497
+ record.errors = [...(record.errors ?? []),
3498
+ `[auto-resume] 已排期第 ${attempt}/${limits.autoResume.maxAttempts} 次自动续跑:`
3499
+ + `${Math.round(decision.delayMs / 1000)}s 后开始(本轮预算到点,仍有 ${pending} 项 pending;done 项不重跑)`].slice(-20)
3500
+ const timer = setTimeout(() => {
3501
+ book.timer = null
3502
+ book.nextAt = null
3503
+ try {
3504
+ /*
3505
+ * 排期到点后逐项复核,任何一项不成立都安静退出:定时器活过了一个
3506
+ * 回合,期间用户可能已经取消、主 Agent 可能已经手动派发、页面可能
3507
+ * 已经换了一份计划记录。
3508
+ */
3509
+ /*
3510
+ * [1.10.4 / D1] 复核失败必须留下停止码。
3511
+ *
3512
+ * T5 的 I9:任何一次「本应自动续跑却没有发生」都要可解释。原先这里五个
3513
+ * 分支全是裸 `return`,计划停在 paused 而台账里没有任何痕迹,用户只能再
3514
+ * 做一次考古。现在每个分支都写 `lastStopReason`,并把原因追加到 history。
3515
+ */
3516
+ const stopTimer = (code: string) => {
3517
+ book.lastStopReason = code
3518
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code, reason: '定时器复核未通过' }
3519
+ book.history = [...(book.history ?? []), {
3520
+ at: Date.now(), phase: record.phase, action: 'stop', code,
3521
+ }].slice(-10)
3522
+ return
3523
+ }
3524
+ if (state.records.get(session.id) !== record) return stopTimer('SCHEDULE_REVOKED_RECORD_REPLACED')
3525
+ if (record.dispatchPromise) return stopTimer('SCHEDULE_REVOKED_ALREADY_RUNNING')
3526
+ if (record.cancelled === true) return stopTimer('CANCELLED')
3527
+ if (isTerminalPhase(record.phase)) return stopTimer('PHASE_TERMINAL')
3528
+ if (isPlanModeActive(ctx, session)) return stopTimer('PLAN_MODE')
3529
+ if (record.phase !== 'paused') return stopTimer('PHASE_NOT_PAUSED')
3530
+ const live = derivePlanSnapshot(record.statuses)
3531
+ const livePending = (record.statuses ?? []).filter((item: any) => item?.status === 'pending').length
3532
+ if (Number(live.stats?.total ?? 0) === 0 || livePending === 0) return stopTimer('NOTHING_PENDING')
3533
+ const controller = new AbortController()
3534
+ record.abortRequested = false
3535
+ record.abortDispatch = (reason: string) => {
3536
+ if (!controller.signal.aborted) controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
3537
+ }
3538
+ record.dispatchStartedAt = Date.now()
3539
+ // 新一轮必须写一条新的结果消息,否则主 Agent 永远看不到自动续跑的结局。
3540
+ record.resultWritten = false
3541
+ book.doneBefore = Number(live.stats?.done ?? 0)
3542
+ record.dispatchPromise = dispatchPlan(ctx, record, {
3543
+ ...base,
3544
+ signal: controller.signal,
3545
+ childTimeoutMs: limits.childTimeoutMs,
3546
+ idleTimeoutMs: limits.idleTimeoutMs,
3547
+ totalTimeoutMs: limits.totalTimeoutMs,
3548
+ maxResumes: limits.maxResumes,
3549
+ strictEvidence: options.strictEvidence,
3550
+ })
3551
+ .then(() => finishRound(record, session))
3552
+ .catch((error: any) => {
3553
+ pushRecordError(record, error)
3554
+ finishRound(record, session)
3555
+ })
3556
+ .finally(() => {
3557
+ record.dispatchPromise = null
3558
+ record.dispatchStartedAt = null
3559
+ record.abortDispatch = null
3560
+ armAutoResume(record, session, base)
3561
+ })
3562
+ ctx.logger?.warn?.(
3563
+ `dsh-workplan: 计划 ${record.plan?.planId ?? '?'} 自动续跑第 ${attempt}/${limits.autoResume.maxAttempts} 轮已开始`
3564
+ + `(remaining ${Number(live.stats?.total ?? 0) - Number(live.stats?.done ?? 0)})`,
3565
+ )
3566
+ } catch (error) {
3567
+ pushRecordError(record, error)
3568
+ ctx.logger?.warn?.(`dsh-workplan: 自动续跑失败:${error instanceof Error ? error.message : String(error)}`)
3569
+ }
3570
+ }, decision.delayMs)
3571
+ timer.unref?.()
3572
+ book.timer = timer
3573
+ return decision
3574
+ }
3575
+
3576
+ /**
3577
+ * Persist the round result and settle the phase.
3578
+ *
3579
+ * Extracted from the wait path so an async dispatch reaches exactly the same
3580
+ * end state: a durable result message plus a reconciled phase. Anything less
2519
3581
  * would make "start now, read later" a second, divergent code path.
2520
3582
  */
3583
+ /**
3584
+ * [1.11.0] 完成必回报的写入点(T7 C-06;契约 S7 done → S8 reported)。
3585
+ *
3586
+ * 只有在「结果消息确实写进会话」之后才调用:没有证据的“已回报”比不回报
3587
+ * 更危险。写入走 applyStatus(唯一写入口),读到的是同一条状态条目上的
3588
+ * `closure:'reported'` + `report{state,at,ref,turn}`,与左侧栏 chip 同源。
3589
+ * 返回本次新标记的条数;已是 reported 的行不重复写,避免每轮刷新 revision。
3590
+ */
3591
+ function markReported(record: any, session: any, ref: string) {
3592
+ const at = Date.now()
3593
+ const rawTurn = Number(state.activeTurns?.get?.(session?.id) ?? NaN)
3594
+ const turn = Number.isFinite(rawTurn) ? rawTurn : null
3595
+ let changed = 0
3596
+ for (const item of Array.isArray(record?.statuses) ? record.statuses : []) {
3597
+ if (item?.status !== 'done') continue
3598
+ if (item?.closure === 'reported' && item?.report?.state === 'sent') continue
3599
+ try {
3600
+ record.statuses = applyStatus(record.statuses, item.subtaskId, {
3601
+ closure: 'reported',
3602
+ reportedAt: at,
3603
+ report: { state: 'sent', at, ref, turn },
3604
+ revision: Number(item.revision ?? 0) + 1,
3605
+ updatedBy: 'system',
3606
+ })
3607
+ changed += 1
3608
+ } catch (error) {
3609
+ ctx.logger?.warn?.(`dsh-workplan: 回报标记失败 ${String(item?.subtaskId)}:${error instanceof Error ? error.message : String(error)}`)
3610
+ record.reportPending = true
3611
+ }
3612
+ }
3613
+ return changed
3614
+ }
3615
+
2521
3616
  function finishRound(record: any, session: any) {
3617
+ const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`
2522
3618
  if (!record.resultWritten) {
3619
+ /*
3620
+ * [1.11.0] 完成必回报的顺序:先标记 reported,再构建并落盘结果消息。
3621
+ *
3622
+ * 这样结果消息里的 statuses 就带着 `closure:'reported'`,刷新/重启后
3623
+ * 回放得到同一个结论;而“标记了但消息没写成功”会在 catch 里回滚,
3624
+ * 绝不留下没有证据的 reported。
3625
+ */
3626
+ const before = (record.statuses ?? []).map((item: any) => ({ ...item }))
3627
+ const needReport = before.filter((item: any) => item?.status === 'done' && item?.closure !== 'reported').length
3628
+ // ^ 本轮结算:done 且未到 reported 的行(含旧日志的 null)都算待回报。
3629
+ const reported = markReported(record, session, ref)
2523
3630
  const resultMessage = buildRoundResult(record, session.id, limits)
2524
3631
  try {
2525
3632
  session.append('user/message', resultMessage, { surfaceOp: 'append' })
2526
3633
  record.resultWritten = true
3634
+ record.reportPending = needReport > 0 && reported < needReport
2527
3635
  } catch (error) {
3636
+ // 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
3637
+ record.statuses = before
2528
3638
  ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
2529
3639
  /*
2530
3640
  * [1.8.14] N13: a failed result write is a real, user-visible failure —
@@ -2532,6 +3642,22 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2532
3642
  * disagree with the live phase. Log it durably, not only in the host log.
2533
3643
  */
2534
3644
  pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`)
3645
+ /*
3646
+ * [1.11.0] 写失败时不能假装回报过。保留 reportPending,让下一次
3647
+ * pre-step 或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
3648
+ */
3649
+ record.reportPending = true
3650
+ }
3651
+ } else {
3652
+ /*
3653
+ * 旧日志 / 上一次写失败的重试:结果消息已在,但仍有 done 行没到
3654
+ * reported。幂等补齐,不重复追加消息。
3655
+ */
3656
+ const pending = (record.statuses ?? []).some((item: any) =>
3657
+ item?.status === 'done' && item?.closure !== 'reported')
3658
+ if (pending) {
3659
+ const changed = markReported(record, session, ref)
3660
+ if (changed > 0) record.reportPending = false
2535
3661
  }
2536
3662
  }
2537
3663
  /*
@@ -2553,7 +3679,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2553
3679
  * had no field telling it the round ended early. `complete`/`remaining` make
2554
3680
  * that state machine-readable instead of a sentence to interpret.
2555
3681
  */
2556
- function completionFields(snapshot: any, phase: any) {
3682
+ function completionFields(snapshot: any, phase: any, record?: any) {
2557
3683
  const stats = snapshot?.stats ?? {}
2558
3684
  const total = Number(stats.total ?? 0)
2559
3685
  const done = Number(stats.done ?? 0)
@@ -2566,7 +3692,9 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2566
3692
  * model now also sees whether the plan passed the delivery gate, plus the
2567
3693
  * exact gaps.
2568
3694
  */
2569
- const readiness = deliveryReadiness(snapshot, { phase })
3695
+ const readiness = record
3696
+ ? readinessOf(record, snapshot)
3697
+ : deliveryReadiness(snapshot, { phase })
2570
3698
  return {
2571
3699
  complete: total > 0 && done >= total,
2572
3700
  remaining: Math.max(0, total - done),
@@ -2584,7 +3712,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2584
3712
  runtime: runtimeIdentity(),
2585
3713
  planId: record.plan.planId,
2586
3714
  alreadyRunning: false,
2587
- ...completionFields(snapshot, record.phase),
3715
+ ...completionFields(snapshot, record.phase, record),
2588
3716
  ...extra,
2589
3717
  phase: record.phase,
2590
3718
  stats: snapshot.stats,
@@ -2629,7 +3757,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2629
3757
  }
2630
3758
  const running = Boolean(record.dispatchPromise)
2631
3759
  const snapshot = derivePlanSnapshot(record.statuses)
2632
- const readiness = deliveryReadiness(snapshot, { phase: record.phase })
3760
+ const readiness = readinessOf(record, snapshot)
2633
3761
  return {
2634
3762
  ok: true,
2635
3763
  version: pluginVersion,
@@ -2642,6 +3770,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2642
3770
  statuses: modelStatusLines(snapshot.statuses),
2643
3771
  errors: (record.errors ?? []).slice(-10),
2644
3772
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
3773
+ // [1.10.4] 自动续跑的可观测面:开关、已用轮次、是否已排期、上一次判定码。
3774
+ autoResume: autoResumeView(record),
2645
3775
  deliveryReady: readiness.ready,
2646
3776
  deliveryBlockers: readiness.blockers.slice(0, 12),
2647
3777
  deliveryRemaining: readiness.remaining.slice(0, 20),
@@ -2722,6 +3852,490 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2722
3852
  }
2723
3853
  }
2724
3854
 
3855
+ /**
3856
+ * [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
3857
+ *
3858
+ * 子会话只知道自己的 `session.id` 和父会话 id。这里用父链 + `childId` 反查
3859
+ * 子任务,而不是相信子 Agent 自报的 subtaskId:自报值可以写错,父链不会。
3860
+ * 写入仍是 `applyStatus`(唯一写入口),并同步落一条 durable update,刷新后
3861
+ * 「有一条请示在等指示」不会退回 pending。
3862
+ */
3863
+ async function escalateSubtask(agent: any, args: any) {
3864
+ const childSession = agent?.session
3865
+ if (!childSession?.id) {
3866
+ return { ok: false, code: 'NO_SESSION', error: '只能在子会话内上报遇阻' }
3867
+ }
3868
+ const parentId = childSession.header?.parentSession
3869
+ if (!parentId) {
3870
+ return {
3871
+ ok: false,
3872
+ code: 'NOT_CHILD_SESSION',
3873
+ error: '当前不是子会话,无法反查父计划;请直接在结果块写 status=blocked + question',
3874
+ }
3875
+ }
3876
+ let record = state.records.get(parentId)
3877
+ if (!record?.plan) {
3878
+ const parent = (ctx as any).sessions?.get?.(parentId)
3879
+ if (parent) {
3880
+ try {
3881
+ record = reconstructFromSession(parent)
3882
+ } catch (error) {
3883
+ pushRecordError({ errors: [] } as any, error)
3884
+ }
3885
+ }
3886
+ }
3887
+ if (!record?.plan) {
3888
+ return {
3889
+ ok: false,
3890
+ code: 'NO_PLAN',
3891
+ error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
3892
+ }
3893
+ }
3894
+ const row = (record.statuses ?? []).find((item: any) => item?.childId === childSession.id)
3895
+ if (!row) {
3896
+ return {
3897
+ ok: false,
3898
+ code: 'NO_SUBTASK',
3899
+ error: '计划里找不到与本子会话关联的子任务(childId 未登记);请在结果块写 status=blocked + question',
3900
+ }
3901
+ }
3902
+ if (row.status === 'done') {
3903
+ return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已标记完成,不能再提交请示' }
3904
+ }
3905
+ const question = truncate(String(args?.question ?? '').trim(), MAX_QUESTION_CHARS)
3906
+ if (!question) {
3907
+ return { ok: false, code: 'INVALID_QUESTION', subtaskId: row.subtaskId, error: 'question 必填:写清需要主 Agent 决定的单个问题' }
3908
+ }
3909
+ if (row.closure === 'escalated') {
3910
+ return {
3911
+ ok: true,
3912
+ alreadyEscalated: true,
3913
+ planId: record.plan.planId,
3914
+ subtaskId: row.subtaskId,
3915
+ status: 'blocked',
3916
+ closure: 'escalated',
3917
+ question: row.question ?? question,
3918
+ message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待主 Agent 指示。',
3919
+ }
3920
+ }
3921
+ const options = (Array.isArray(args?.options) ? args.options : [])
3922
+ .slice(0, MAX_ESCALATION_OPTIONS)
3923
+ .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
3924
+ .filter(Boolean)
3925
+ const needs = (Array.isArray(args?.needs) ? args.needs : [])
3926
+ .slice(0, 10)
3927
+ .map((item: any) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
3928
+ .filter(Boolean)
3929
+ const now = Date.now()
3930
+ const revision = Number(row.revision ?? 0) + 1
3931
+ record.statuses = applyStatus(record.statuses, row.subtaskId, {
3932
+ status: 'blocked',
3933
+ closure: 'escalated',
3934
+ blockedKind: 'escalated',
3935
+ question,
3936
+ options,
3937
+ needs: [...(Array.isArray(row.needs) ? row.needs : []), ...needs],
3938
+ progress: 100,
3939
+ finishedAt: now,
3940
+ error: question,
3941
+ summary: `待指示:${question}`,
3942
+ escalatedAt: now,
3943
+ escalationSeq: revision,
3944
+ revision,
3945
+ updatedBy: 'child',
3946
+ })
3947
+ record.updatedAt = now
3948
+ try {
3949
+ const parent = (ctx as any).sessions?.get?.(parentId)
3950
+ const written = record.statuses.find((item: any) => item?.subtaskId === row.subtaskId)
3951
+ parent?.append?.('user/message', buildUpdateMessage({
3952
+ planId: record.plan.planId,
3953
+ subtaskId: row.subtaskId,
3954
+ status: 'blocked',
3955
+ closure: 'escalated',
3956
+ blockedKind: 'escalated',
3957
+ question,
3958
+ options,
3959
+ needs: written?.needs,
3960
+ escalatedAt: now,
3961
+ escalationSeq: revision,
3962
+ revision,
3963
+ }), { surfaceOp: 'append' })
3964
+ } catch (error) {
3965
+ pushRecordError(record, error)
3966
+ }
3967
+ return {
3968
+ ok: true,
3969
+ planId: record.plan.planId,
3970
+ subtaskId: row.subtaskId,
3971
+ status: 'blocked',
3972
+ closure: 'escalated',
3973
+ question,
3974
+ revision,
3975
+ message: '已上报主 Agent。请立即停止推进,只允许做只读核对;等待指示期间不要开始新的写入或大改。',
3976
+ }
3977
+ }
3978
+
3979
+ /**
3980
+ * [1.11.0] 指示回执(T4 B5 / M6,T10 N4)。
3981
+ *
3982
+ * 指示投递成功只证明消息进了收件箱,不证明子会话真的开始执行。三个观察点
3983
+ * 都以「该行仍是 instructed 且 instructionSeq 未变」为前提:
3984
+ * - 轮询:子会话 seq 增长 = 已开始执行 → 写 acknowledged(唯一正向回执);
3985
+ * - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催);
3986
+ * - 180s:仍无增长 → 收束为 blocked/no-ack(不再无限等待)。
3987
+ * 主 Agent 再次改判或子会话产出结果都会让这三个观察点自然作废。
3988
+ */
3989
+ function scheduleInstructionAck(record: any, subtaskId: string, childId: string, revision: number) {
3990
+ const rowOf = () => record.statuses.find((item: any) => item?.subtaskId === subtaskId)
3991
+ const readSeq = () => {
3992
+ try {
3993
+ const seq = Number((ctx as any).sessions?.get?.(childId)?.seq)
3994
+ return Number.isFinite(seq) ? seq : undefined
3995
+ } catch {
3996
+ return undefined
3997
+ }
3998
+ }
3999
+ const baseline = readSeq()
4000
+ let stopped = false
4001
+ const timers: Array<ReturnType<typeof setTimeout> | ReturnType<typeof setInterval>> = []
4002
+ const stop = () => {
4003
+ if (stopped) return
4004
+ stopped = true
4005
+ for (const timer of timers) {
4006
+ clearTimeout(timer as any)
4007
+ clearInterval(timer as any)
4008
+ }
4009
+ }
4010
+ const sameAttempt = (row: any) => {
4011
+ if (stopped) return false
4012
+ if (!row || row.closure !== 'instructed') return false
4013
+ return Number(row.instructionSeq ?? 0) === Number(revision)
4014
+ }
4015
+ const unchanged = (row: any) => {
4016
+ if (!sameAttempt(row)) return false
4017
+ const seq = readSeq()
4018
+ if (seq === undefined || baseline === undefined) return true
4019
+ return seq <= baseline
4020
+ }
4021
+ /*
4022
+ * 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会在 180s 被
4023
+ * 误判成 no-ack 并阻断,而它其实早就在产出事件了。
4024
+ */
4025
+ const poll = setInterval(() => {
4026
+ const row = rowOf()
4027
+ if (!sameAttempt(row)) { stop(); return }
4028
+ const seq = readSeq()
4029
+ if (seq === undefined || baseline === undefined || seq <= baseline) return
4030
+ try {
4031
+ writeSubtaskStatus(record, subtaskId, {
4032
+ closure: 'acknowledged',
4033
+ ackedAt: Date.now(),
4034
+ ackEvidence: { seq, elapsedMs: Date.now() - Number(row.instruction?.at ?? Date.now()) },
4035
+ instructionOverdue: false,
4036
+ progress: Math.max(Number(row.progress ?? 0), 15),
4037
+ }, { timedOut: false })
4038
+ } catch {
4039
+ // Row moved on between read and write; the next tick re-evaluates.
4040
+ return
4041
+ }
4042
+ stop()
4043
+ }, INSTRUCTION_POLL_MS)
4044
+ poll.unref?.()
4045
+ timers.push(poll)
4046
+ const notice = setTimeout(() => {
4047
+ if (!unchanged(rowOf())) return
4048
+ try {
4049
+ writeSubtaskStatus(record, subtaskId, { instructionOverdue: true }, { timedOut: false })
4050
+ } catch {
4051
+ // The row moved on between the read and the write; nothing to report.
4052
+ }
4053
+ }, INSTRUCTION_ACK_NOTICE_MS)
4054
+ notice.unref?.()
4055
+ timers.push(notice)
4056
+ const deadline = setTimeout(() => {
4057
+ if (!unchanged(rowOf())) { stop(); return }
4058
+ const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000)
4059
+ const message = `指示下发后 ${seconds}s 子会话仍无任何新事件(no-ack):指示没有被执行`
4060
+ try {
4061
+ writeSubtaskStatus(record, subtaskId, {
4062
+ status: 'blocked',
4063
+ closure: 'blocked',
4064
+ blockedKind: 'no-ack',
4065
+ progress: 100,
4066
+ finishedAt: Date.now(),
4067
+ instructionOverdue: true,
4068
+ error: message,
4069
+ summary: `未完成:${message}`,
4070
+ }, { timedOut: false })
4071
+ recordSubtaskError(record, subtaskId, message, { timedOut: false })
4072
+ } catch {
4073
+ // Same race as above: the row already left instructed.
4074
+ }
4075
+ stop()
4076
+ }, INSTRUCTION_ACK_DEADLINE_MS)
4077
+ deadline.unref?.()
4078
+ timers.push(deadline)
4079
+ }
4080
+
4081
+ /**
4082
+ * [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
4083
+ *
4084
+ * 只有根会话能调用;只接受 `closure:'escalated'` 的行;只投递给本会话直接
4085
+ * 子会话。投递失败时不改状态(不伪造成「已指示」),把错误原样交给主 Agent。
4086
+ */
4087
+ async function instructSubtask(agent: any, args: any, signal?: any, existingRecord?: any) {
4088
+ const session = agent?.session
4089
+ if (!session) return { ok: false, code: 'NO_SESSION', error: '只能在会话内下发指示' }
4090
+ if (!isRootSession(session)) return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' }
4091
+ let record = existingRecord ?? state.records.get(session.id)
4092
+ if (!record?.plan) record = reconstructFromSession(session, args?.planId)
4093
+ record = adoptRequestedPlan(session, record, args?.planId)
4094
+ if (!record?.plan) return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' }
4095
+ clearAutoResumeTimer(record, 'manual-instruct')
4096
+ const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : ''
4097
+ if (!subtaskId) return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' }
4098
+ const current = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
4099
+ if (!current) return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` }
4100
+ if (current.closure !== 'escalated') {
4101
+ return {
4102
+ ok: false,
4103
+ code: 'NOT_ESCALATED',
4104
+ subtaskId,
4105
+ error: '该子任务不在待指示状态;普通受阻请用 dsh_workplan_update 改判',
4106
+ }
4107
+ }
4108
+ const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS)
4109
+ if (!instruction) return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要子 Agent 执行的决定' }
4110
+ const childId = typeof current.childId === 'string' ? current.childId : ''
4111
+ if (!childId) return { ok: false, code: 'NO_CHILD', subtaskId, error: '该行没有关联子会话,无法投递指示' }
4112
+ if (!spawnedChildIds(session).has(childId)) {
4113
+ return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话,拒绝投递` }
4114
+ }
4115
+ const service: any = (ctx as any).subagents
4116
+ if (!service || typeof service.sendMessage !== 'function') {
4117
+ return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId, error: '当前部署没有可用的 subagent 服务,无法投递指示' }
4118
+ }
4119
+ let messageId = ''
4120
+ try {
4121
+ messageId = String(await service.sendMessage(
4122
+ agent,
4123
+ childId,
4124
+ [{
4125
+ type: 'text',
4126
+ text: [
4127
+ '【主 Agent 指示(对应你此前提交的请示)】',
4128
+ instruction,
4129
+ '',
4130
+ '请按上述指示继续原任务。若仍受阻,先调用 dsh_workplan_escalate 再次上报,然后停止推进等待指示;不要自行猜测未被回答的部分。',
4131
+ ].join('\n'),
4132
+ }],
4133
+ { signal },
4134
+ ) ?? '')
4135
+ } catch (error: any) {
4136
+ return {
4137
+ ok: false,
4138
+ code: 'DELIVERY_FAILED',
4139
+ subtaskId,
4140
+ error: truncate(error instanceof Error ? error.message : String(error), 500),
4141
+ hint: '状态未改变,该行仍是待指示;可重试,或用 dsh_workplan_followup 直接投递同一段指示。',
4142
+ }
4143
+ }
4144
+ const now = Date.now()
4145
+ const revision = Number(current.revision ?? 0) + 1
4146
+ record.statuses = applyStatus(record.statuses, subtaskId, {
4147
+ status: 'in_progress',
4148
+ closure: 'instructed',
4149
+ instruction: { text: instruction, at: now, by: 'agent', messageId, delivery: 'sent' },
4150
+ instructionSeq: revision,
4151
+ progress: Math.max(Number(current.progress ?? 0), 15),
4152
+ finishedAt: null,
4153
+ error: null,
4154
+ question: null,
4155
+ options: [],
4156
+ blockedKind: null,
4157
+ ackOverdue: false,
4158
+ ackedAt: null,
4159
+ ackEvidence: undefined,
4160
+ revision,
4161
+ updatedBy: 'agent',
4162
+ })
4163
+ /*
4164
+ * [1.11.0] 指示会解除「受阻」(T10 N3)。
4165
+ *
4166
+ * 行从 blocked/escalated 变成 in_progress/instructed 后,缓存的
4167
+ * `record.phase` 仍是 blocked;`reconcilePhase` 现在允许 blocked 在有
4168
+ * 活跃行时让位给 executing,这里必须重新对账,否则卡片继续显示
4169
+ * 「卡住了」,与事实相反。
4170
+ */
4171
+ record.phase = reconcilePhase(record.phase, record.statuses)
4172
+ record.updatedAt = now
4173
+ try {
4174
+ const written = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
4175
+ session.append('user/message', buildUpdateMessage({
4176
+ planId: record.plan.planId,
4177
+ subtaskId,
4178
+ status: 'in_progress',
4179
+ closure: 'instructed',
4180
+ instruction: written?.instruction,
4181
+ instructionSeq: revision,
4182
+ revision,
4183
+ }), { surfaceOp: 'append' })
4184
+ } catch (error) {
4185
+ pushRecordError(record, error)
4186
+ }
4187
+ scheduleInstructionAck(record, subtaskId, childId, revision)
4188
+ const snapshot = derivePlanSnapshot(record.statuses)
4189
+ const readiness = readinessOf(record, snapshot)
4190
+ return {
4191
+ ok: true,
4192
+ planId: record.plan.planId,
4193
+ subtaskId,
4194
+ status: 'in_progress',
4195
+ closure: 'instructed',
4196
+ revision,
4197
+ messageId,
4198
+ stats: snapshot.stats,
4199
+ deliveryReady: readiness.ready,
4200
+ hint: '指示已投递,该行已变为「已收到指示」。子 Agent 会开启新一轮;完成前仍不得交付。',
4201
+ }
4202
+ }
4203
+
4204
+ /**
4205
+ * [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
4206
+ *
4207
+ * 单独一层包装而不是让 host 直接调内部函数:`escalateSubtask` 需要
4208
+ * `record`/`ctx` 闭包,host 侧只拿得到 runtime 的公开面;这一层也是
4209
+ * 唯一被 `dsh_workplan_escalate` 触发的地方,便于测试替身注入。
4210
+ */
4211
+ async function escalateTool(agent: any, args: any) {
4212
+ return escalateSubtask(agent, args)
4213
+ }
4214
+
4215
+ /**
4216
+ * [1.11.0] 工具层入口:主 Agent 下发指示(T4 C-10 / T6 M6)。
4217
+ *
4218
+ * 前置校验(根会话、escalated、直接子会话、非空 instruction)全部在
4219
+ * `instructSubtask` 里,这一层只转发 —— 校验留在唯一实现处,两个入口
4220
+ * (工具与 `dsh_workplan_update` 的 instruction 字段)才不会分叉。
4221
+ */
4222
+ async function instructTool(agent: any, args: any, signal?: any) {
4223
+ return instructSubtask(agent, args, signal)
4224
+ }
4225
+
4226
+ /**
4227
+ * [1.11.0] 跨部门需求的唯一处置入口(用户 m00687)。
4228
+ *
4229
+ * 子 Agent 只能「提出」需求(needs → open handoff),不能宣称需求已解决;
4230
+ * 只有根会话的主 Agent 能把一条需求指派给部门(routed)、写入书面答复
4231
+ * (answered)或判定无需动作(closed)。处置结果写回同一条状态行并追加
4232
+ * 一条可回放的人工改判消息,刷新后仍然有效。
4233
+ */
4234
+ async function handoffTool(agent: any, args: any, signal?: any) {
4235
+ const session = agent?.session
4236
+ if (!session) return { ok: false, code: 'NO_SESSION', error: '只能在会话内处置跨部门需求' }
4237
+ if (!isRootSession(session)) return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以处置跨部门需求' }
4238
+ let record = state.records.get(session.id)
4239
+ if (!record?.plan) record = reconstructFromSession(session, args?.planId)
4240
+ record = adoptRequestedPlan(session, record, args?.planId)
4241
+ if (!record?.plan) return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' }
4242
+ const action = ['list', 'assign', 'resolve', 'close'].includes(args?.action) ? args.action : ''
4243
+ if (!action) return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 list / assign / resolve / close' }
4244
+ if (action === 'list') {
4245
+ const rows = (record.statuses ?? []).flatMap((row: any) =>
4246
+ openHandoffs(row).map((handoff: any) => ({
4247
+ subtaskId: row.subtaskId,
4248
+ id: handoff.id,
4249
+ department: handoff.department,
4250
+ status: handoff.status,
4251
+ request: handoff.request,
4252
+ })))
4253
+ return { ok: true, planId: record.plan.planId, handoffs: rows, count: rows.length }
4254
+ }
4255
+ const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : ''
4256
+ if (!subtaskId) return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' }
4257
+ const row = record.statuses.find((item: any) => item?.subtaskId === subtaskId)
4258
+ if (!row) return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` }
4259
+ const handoffs = normaliseHandoffs(row.handoffs)
4260
+ const wanted = typeof args?.handoffId === 'string' ? args.handoffId.trim() : ''
4261
+ const index = wanted
4262
+ ? handoffs.findIndex((item: any) => item.id === wanted)
4263
+ : handoffs.findIndex((item: any) => item.status === 'open' || item.status === 'routed')
4264
+ if (index < 0) {
4265
+ return {
4266
+ ok: false,
4267
+ code: wanted ? 'UNKNOWN_HANDOFF' : 'NO_OPEN_HANDOFF',
4268
+ subtaskId,
4269
+ error: wanted ? `未知跨部门需求:${wanted}` : '该行没有待处理的跨部门需求',
4270
+ }
4271
+ }
4272
+ const handoff = handoffs[index]
4273
+ if (action === 'assign') {
4274
+ const department = typeof args?.department === 'string' ? args.department.trim() : ''
4275
+ if (!DEPARTMENTS[department as keyof typeof DEPARTMENTS]) {
4276
+ return { ok: false, code: 'INVALID_DEPARTMENT', error: `department 必须是 ${DEPARTMENT_IDS.join(' / ')} 之一` }
4277
+ }
4278
+ handoffs[index] = { ...handoff, department, status: 'routed', updatedAt: Date.now(), by: 'agent' }
4279
+ } else if (action === 'resolve') {
4280
+ const response = truncate(String(args?.response ?? '').trim(), MAX_HANDOFF_RESPONSE_CHARS)
4281
+ if (!response) return { ok: false, code: 'INVALID_RESPONSE', error: 'resolve 必须写清答复或已由哪项产物满足该需求' }
4282
+ handoffs[index] = { ...handoff, status: 'answered', response, updatedAt: Date.now(), by: 'agent' }
4283
+ } else {
4284
+ handoffs[index] = { ...handoff, status: 'closed', response: handoff.response ?? null, updatedAt: Date.now(), by: 'agent' }
4285
+ }
4286
+ const revision = Number(row.revision ?? 0) + 1
4287
+ record.statuses = applyStatus(record.statuses, subtaskId, {
4288
+ handoffs,
4289
+ revision,
4290
+ updatedBy: 'agent',
4291
+ })
4292
+ record.updatedAt = Date.now()
4293
+ try {
4294
+ session.append('user/message', buildUpdateMessage({
4295
+ planId: record.plan.planId,
4296
+ subtaskId,
4297
+ status: row.status,
4298
+ handoffs,
4299
+ revision,
4300
+ }), { surfaceOp: 'append' })
4301
+ } catch (error) {
4302
+ pushRecordError(record, error)
4303
+ }
4304
+ /*
4305
+ * [1.11.0] 答复必须真的送到还在等它的子会话(用户 m00687)。
4306
+ *
4307
+ * 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
4308
+ * handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
4309
+ * 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
4310
+ * 60s/180s 回执、下次激活注入),不另造第二条消息通道。
4311
+ * 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
4312
+ */
4313
+ let instruction: any = null
4314
+ if (action === 'resolve' && row.closure === 'escalated' && handoffs[index]?.response) {
4315
+ const answer = handoffs[index]
4316
+ instruction = await instructSubtask(agent, {
4317
+ planId: record.plan.planId,
4318
+ subtaskId,
4319
+ instruction: `跨部门需求 ${answer.id} 已答复${answer.department ? `(${answer.department})` : ''}:${answer.response}。按此答复继续原任务。`,
4320
+ }, signal)
4321
+ }
4322
+ const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses))
4323
+ return {
4324
+ ok: true,
4325
+ planId: record.plan.planId,
4326
+ subtaskId,
4327
+ handoff: record.statuses.find((item: any) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
4328
+ deliveryReady: finalReadiness.ready,
4329
+ deliveryBlockers: finalReadiness.blockers,
4330
+ ...(instruction ? { instruction } : {}),
4331
+ hint: action === 'assign'
4332
+ ? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
4333
+ : instruction && instruction.ok !== true
4334
+ ? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
4335
+ : '已记录处置结果;交付阻塞按最新状态重新计算。',
4336
+ }
4337
+ }
4338
+
2725
4339
  async function dispatchTool(agent: any, args: any, signal: any) {
2726
4340
  const session = agent?.session
2727
4341
  if (!session) throw new PlanError('只能在会话内派发计划', 'NO_SESSION')
@@ -2760,6 +4374,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2760
4374
  }
2761
4375
  }
2762
4376
  if (!record?.plan) throw new PlanError('当前会话没有可派发的计划', 'NO_PLAN')
4377
+ /*
4378
+ * [1.10.4] 人工/工具派发优先于自动续跑:撤销待触发的定时器,并把自动
4379
+ * 轮次计数归零(这一次是外部授权的新起点)。done 水位取当前值,下一轮
4380
+ * 结束后才能正确判断「有没有新增完成项」。
4381
+ */
4382
+ clearAutoResumeTimer(record, 'manual-dispatch')
4383
+ {
4384
+ const book = autoResumeBook(record)
4385
+ book.attempt = 0
4386
+ book.noProgressRounds = 0
4387
+ book.doneBefore = Number(derivePlanSnapshot(record.statuses).stats?.done ?? 0)
4388
+ }
2763
4389
  if (args?.planId && record.plan.planId !== args.planId) {
2764
4390
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH')
2765
4391
  }
@@ -2914,16 +4540,24 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2914
4540
  dispatchController.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2915
4541
  }
2916
4542
  }
2917
- record.dispatchPromise = dispatchPlan(ctx, record, {
4543
+ const roundOptions = {
2918
4544
  agent,
2919
- signal: dispatchController.signal,
2920
4545
  modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
2921
4546
  cwd: session.header?.cwd ?? options.cwd,
2922
4547
  conversationContext: record.conversationContext ?? '',
4548
+ }
4549
+ record.dispatchPromise = dispatchPlan(ctx, record, {
4550
+ ...roundOptions,
4551
+ signal: dispatchController.signal,
2923
4552
  childTimeoutMs: limits.childTimeoutMs,
2924
4553
  idleTimeoutMs: limits.idleTimeoutMs,
2925
4554
  totalTimeoutMs: limits.totalTimeoutMs,
2926
4555
  maxResumes: limits.maxResumes,
4556
+ /*
4557
+ * [1.11.0] 严格完成是运行时级配置,不是每个调用点各传一份。
4558
+ * 漏传会让 `strictCompletion:false` 的部署读到默认 true,行为无法预期。
4559
+ */
4560
+ strictEvidence: options.strictEvidence,
2927
4561
  }).finally(() => {
2928
4562
  record.dispatchPromise = null
2929
4563
  record.dispatchStartedAt = null
@@ -2942,11 +4576,13 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2942
4576
  .then(() => {
2943
4577
  finishRound(record, session)
2944
4578
  state.records.set(session.id, record)
4579
+ armAutoResume(record, session, roundOptions)
2945
4580
  })
2946
4581
  .catch((error: any) => {
2947
4582
  pushRecordError(record, error)
2948
4583
  finishRound(record, session)
2949
4584
  state.records.set(session.id, record)
4585
+ armAutoResume(record, session, roundOptions)
2950
4586
  })
2951
4587
  const live = derivePlanSnapshot(record.statuses)
2952
4588
  return {
@@ -2967,6 +4603,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2967
4603
  }
2968
4604
  await record.dispatchPromise
2969
4605
  finishRound(record, session)
4606
+ armAutoResume(record, session, roundOptions)
2970
4607
  /*
2971
4608
  * The model's dispatch result reports the same snapshot the dashboard will
2972
4609
  * show. It used to send `record.stats` while the status list below was read
@@ -3007,8 +4644,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3007
4644
  const STOP_STEER_LIMIT = 2
3008
4645
 
3009
4646
  function recordReadiness(record: any) {
3010
- const snapshot = derivePlanSnapshot(record.statuses)
3011
- return deliveryReadiness(snapshot, { phase: record.phase })
4647
+ return readinessOf(record)
3012
4648
  }
3013
4649
 
3014
4650
  function stopGateApplies(record: any, session?: any, turn?: number) {
@@ -3251,6 +4887,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3251
4887
  stats: snapshot.stats,
3252
4888
  statuses: snapshot.statuses,
3253
4889
  attempt: book.count,
4890
+ changePending: record.changeRequest?.status === 'pending',
4891
+ reportPending: record.reportPending === true,
3254
4892
  }),
3255
4893
  {
3256
4894
  kind: 'workplan-continue',
@@ -3399,7 +5037,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3399
5037
  `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
3400
5038
  + '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。')
3401
5039
  }
3402
- const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase })
5040
+ const readiness = readinessOf(successor)
3403
5041
  if (!readiness.ready) {
3404
5042
  const ids = readiness.remaining.slice(0, 10).join('、')
3405
5043
  return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY,
@@ -3423,7 +5061,18 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3423
5061
 
3424
5062
  function presentDenialVerdict(agent: any): PresentDenialVerdict | undefined {
3425
5063
  const session = agent?.session
3426
- if (!session || !isRootSession(session)) return undefined
5064
+ if (!session) return undefined
5065
+ /*
5066
+ * [1.11.0] 子会话不得直接交付(T7 P9 / R3)。
5067
+ *
5068
+ * 1.10.6 对非根会话直接返回 undefined,等于让子 Agent 绕过根交付门禁
5069
+ * 调用 present:中间产物会被当成最终交付展示给用户。交付只属于根会话;
5070
+ * 子会话的产物应写进工作区并由主 Agent 统一 present。
5071
+ */
5072
+ if (!isRootSession(session)) {
5073
+ return presentDenial(PRESENT_DENY_CODES.NOT_ROOT,
5074
+ '子 Agent 不能直接交付:请把产物写入工作区并在结论里给出路径,由主 Agent 统一核对后调用 present。')
5075
+ }
3427
5076
  if (isPlanModeActive(ctx, session)) return undefined
3428
5077
  /*
3429
5078
  * [1.8.16] Every plan in the session matters, not just the turn's plan.
@@ -3458,7 +5107,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3458
5107
  const unresolved = gateable
3459
5108
  .map((item: any) => ({
3460
5109
  record: item,
3461
- readiness: deliveryReadiness(derivePlanSnapshot(item.statuses), { phase: item.phase }),
5110
+ readiness: readinessOf(item),
3462
5111
  }))
3463
5112
  /*
3464
5113
  * A cancelled plan is not a delivery blocker for *other* plans — the
@@ -3515,7 +5164,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3515
5164
  if (denial) return denial
3516
5165
  return undefined
3517
5166
  }
3518
- readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase })
5167
+ readiness = readinessOf(record)
3519
5168
  if (readiness.ready) return undefined
3520
5169
  }
3521
5170
  if (record?.plan && !isTerminalPhase(record.phase)) state.records.set(session.id, record)
@@ -3659,7 +5308,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3659
5308
  .map((planId) => recordForPlan(session, planId))
3660
5309
  .filter((record: any) => record?.plan
3661
5310
  && !isTerminalPhase(record.phase)
3662
- && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready)
5311
+ && !readinessOf(record).ready)
3663
5312
  if (unresolved.length === 0) return undefined
3664
5313
  const ids = unresolved.slice(0, 4).map((record: any) => record.plan.planId)
3665
5314
  return `文件 ${requested} 已通过 present 交付给用户,而交付时点已存在的计划`
@@ -3747,6 +5396,8 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3747
5396
  }
3748
5397
 
3749
5398
  function dispose() {
5399
+ // [1.10.4] 定时器不能吊住进程,也不能在记录清空后复活一个已销毁的计划。
5400
+ for (const record of state.records.values()) clearAutoResumeTimer(record, 'dispose')
3750
5401
  state.records.clear()
3751
5402
  }
3752
5403
 
@@ -3764,6 +5415,10 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3764
5415
  dispatchTool,
3765
5416
  statusTool,
3766
5417
  followupTool,
5418
+ escalateTool,
5419
+ instructTool,
5420
+ handoffTool,
5421
+ replanPlan,
3767
5422
  plansPayload,
3768
5423
  route,
3769
5424
  dispose,
@@ -3828,6 +5483,25 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
3828
5483
  const conversationContext = recentConversation(session)
3829
5484
  const existing = state.records.get(session.id)
3830
5485
  if (existing?.plan?.createdTurn === payload.turn) return downstream
5486
+ /*
5487
+ * [1.11.0] 执行中记录的变更,在本轮结束后仍然没有被 replan 落实时,必须
5488
+ * 在下一步拦住“直接开始新一轮计划/直接收尾”:提醒模型先处理变更。每个
5489
+ * 变更序号只提醒一次(notifiedSeq),不会每步重复注入。
5490
+ */
5491
+ if (existing?.plan && !existing.dispatchPromise
5492
+ && existing.changeRequest?.status === 'pending'
5493
+ && existing.changeRequest.notifiedSeq !== existing.changeRequest.seq) {
5494
+ existing.changeRequest.notifiedSeq = existing.changeRequest.seq
5495
+ const change = existing.changeRequest
5496
+ return enterDecision(downstream, [buildChangeRequestMessage({
5497
+ kind: 'workplan-change',
5498
+ planId: String(existing.plan.planId ?? ''),
5499
+ seq: Number(change.seq) || 1,
5500
+ at: Number(change.at) || Date.now(),
5501
+ turn: Number(change.turn) || null,
5502
+ text: String(change.text ?? ''),
5503
+ }, { afterRound: true })])
5504
+ }
3831
5505
  // A plan generated in plan mode is intentionally deferred: keep it intact
3832
5506
  // until the user leaves plan mode and dispatches it. Cancelling it here
3833
5507
  // would make the plan disappear before the main Agent can act on approval.
@@ -3849,7 +5523,46 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
3849
5523
  existing.errors = Array.isArray(existing.errors) ? existing.errors : []
3850
5524
  existing.errors.push('计划已取消:上一轮未派发')
3851
5525
  }
3852
- if (existing?.dispatchPromise || existing?.phase === 'executing') return downstream
5526
+ if (existing?.dispatchPromise || existing?.phase === 'executing') {
5527
+ /*
5528
+ * [1.11.0] C-12:执行中收到的新需求不能静默丢弃。
5529
+ *
5530
+ * 旧代码在这里直接 `return downstream`,用户在看到「正在做」之后补充的要求
5531
+ * 既没写进状态、也没出现在会话里,下一轮计划更不会包含它们。现在:
5532
+ * - 原文落进 `record.changeRequest`(带序号/回合/时间),刷新后可恢复;
5533
+ * - 一条 notice 消息进入本轮上下文,明确告诉模型「先别打断、结束后用
5534
+ * dsh_workplan_replan 落实」;
5535
+ * - 同一段文本只记一次,避免每步重复注入。
5536
+ */
5537
+ const text = truncate(taskText, 4000)
5538
+ const previous = typeof existing.changeRequest?.text === 'string' ? existing.changeRequest.text : ''
5539
+ if (previous !== text) {
5540
+ const seq = Number(existing.changeRequestSeq ?? 0) + 1
5541
+ const at = Date.now()
5542
+ existing.changeRequestSeq = seq
5543
+ existing.changeRequest = {
5544
+ seq,
5545
+ text,
5546
+ at,
5547
+ turn: Number(payload.turn ?? 0),
5548
+ status: 'pending',
5549
+ notifiedSeq: seq,
5550
+ }
5551
+ existing.updatedAt = at
5552
+ const active = (existing.statuses ?? [])
5553
+ .filter((item: any) => item?.status === 'in_progress')
5554
+ .map((item: any) => `${String(item.subtaskId)}「${String(item.title ?? '')}」`)
5555
+ return enterDecision(downstream, [buildChangeRequestMessage({
5556
+ kind: 'workplan-change',
5557
+ planId: String(existing.plan?.planId ?? ''),
5558
+ seq,
5559
+ at,
5560
+ turn: Number(payload.turn ?? 0),
5561
+ text,
5562
+ }, { activeSubtasks: active })])
5563
+ }
5564
+ return downstream
5565
+ }
3853
5566
  const modelSelection = resolveModelSelection(ctx, payload)
3854
5567
  if (!modelSelection?.provider || !modelSelection?.model) {
3855
5568
  const message = buildDegradedMessage({
@@ -4097,6 +5810,55 @@ export function statusToolOutputSchema() {
4097
5810
  }
4098
5811
  }
4099
5812
 
5813
+ export function replanToolOutputSchema() {
5814
+ return {
5815
+ type: 'object',
5816
+ properties: {
5817
+ ok: { type: 'boolean' },
5818
+ planId: { type: 'string' },
5819
+ planRevision: { type: 'number' },
5820
+ reason: { type: 'string' },
5821
+ phase: { type: 'string' },
5822
+ stats: { type: 'object' },
5823
+ statuses: { type: 'array' },
5824
+ marks: {
5825
+ type: 'array',
5826
+ items: {
5827
+ type: 'object',
5828
+ properties: {
5829
+ subtaskId: { type: 'string' },
5830
+ action: { type: 'string' },
5831
+ replacedBy: { type: 'array', items: { type: 'string' } },
5832
+ reason: { type: 'string' },
5833
+ },
5834
+ additionalProperties: true,
5835
+ },
5836
+ },
5837
+ added: {
5838
+ type: 'array',
5839
+ items: {
5840
+ type: 'object',
5841
+ properties: {
5842
+ subtaskId: { type: 'string' },
5843
+ stageId: { type: 'string' },
5844
+ title: { type: 'string' },
5845
+ replaces: { oneOf: [{ type: 'string' }, { type: 'null' }] },
5846
+ },
5847
+ additionalProperties: true,
5848
+ },
5849
+ },
5850
+ // 执行中拒绝改计划时:变更已记录、本轮仍在跑(REPLAN_PLAN_RUNNING)。
5851
+ running: { type: 'boolean' },
5852
+ changeRequest: { oneOf: [{ type: 'object' }, { type: 'null' }] },
5853
+ code: { type: 'string' },
5854
+ error: { type: 'string' },
5855
+ hint: { type: 'string' },
5856
+ },
5857
+ required: ['ok'],
5858
+ additionalProperties: true,
5859
+ }
5860
+ }
5861
+
4100
5862
  export function dispatchToolOutputSchema() {
4101
5863
  return {
4102
5864
  type: 'object',