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/lib/runtime.js CHANGED
@@ -12,12 +12,14 @@
12
12
  * in this file is allowed to escape as an unhandled rejection from a listener.
13
13
  */
14
14
  import { randomUUID } from 'node:crypto';
15
- import { existsSync } from 'node:fs';
15
+ import { existsSync, statSync } from 'node:fs';
16
16
  import { isAbsolute, resolve } from 'node:path';
17
- import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, parseUpdateMessage, buildUpdateMessage, } from './plan.js';
17
+ import { MAX_CONCURRENT, PlanError, aggregateInvariantViolations, applyStatus, attachPlanMeta, blockCancelledDependents, buildChildPrompt, buildCancelMessage, buildDegradedMessage, buildPlanMessage, buildPlannerPrompt, buildResultMessage, buildStopSteerText, createStatuses, deliveryReadiness, derivePlanSnapshot, extractJson, flattenSubtasks, isRecord, isSocialMessage, isTerminalPhase, isStatusQuestion, isVagueContinuation, makeUserMessage, markDependentsBlocked, messageText, readySubtasks, MAX_PLAN_RESUMES, PRESENT_DENY_CODES, canResumePlan, resetBlockedStatuses, parseCancelMessage, parseResultMessage, parseWorkplanMessage, planPhase, reconcilePhase, truncate, validatePlan, applyResultStatuses, adjudicateResult, activeDenyCode, MAX_CONVERSATION_CHARS, MAX_ESCALATION_OPTIONS, MAX_INSTRUCTION_CHARS, MAX_QUESTION_CHARS, parseUpdateMessage, buildUpdateMessage, normaliseHandoffs, openHandoffs, DEPARTMENTS, DEPARTMENT_IDS, MAX_HANDOFF_RESPONSE_CHARS, } from './plan.js';
18
18
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
19
19
  import { supersedePlanRecord } from './supersede.js';
20
20
  import { createProgressWatchdog, describeError } from './watchdog.js';
21
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js';
22
+ import { applyReplanStatuses, buildChangeRequestMessage, buildReplanMessage, parseChangeRequestMessage, parseReplanMessage, planReplan, } from './replan.js';
21
23
  /**
22
24
  * [1.8.18] How many subtasks the plan *defines*.
23
25
  *
@@ -32,14 +34,63 @@ import { createProgressWatchdog, describeError } from './watchdog.js';
32
34
  * (`MAX_SAFE_INTEGER`); plans failing reconstruction earlier are dropped by
33
35
  * `sessionPlanRecords` — a known fail-open boundary (T5 A9), not closed here.
34
36
  */
37
+ function expectedAcceptanceOf(plan) {
38
+ const out = {};
39
+ for (const entry of flattenSubtasks(plan)) {
40
+ const id = String(entry?.subtask?.id ?? '');
41
+ if (!id)
42
+ continue;
43
+ out[id] = Array.isArray(entry.subtask.acceptance) ? entry.subtask.acceptance : [];
44
+ }
45
+ return out;
46
+ }
35
47
  function definedSubtaskCount(plan) {
36
48
  try {
37
- return flattenSubtasks(plan).length;
49
+ /*
50
+ * [1.11.0] 被重规划替换/撤销的旧行不占分母。
51
+ *
52
+ * 契约 §7.2 硬规则 2:`cancel` 掉的工作如果仍然计入定义条数,计划就永远
53
+ * 差一项、永远无法交付。标记由 `replan.ts` 写在计划定义上(supersededAt),
54
+ * 与状态条目的 `closure:'replanned'` 是同一次写入的两个镜像。
55
+ */
56
+ return flattenSubtasks(plan).filter((entry) => !entry.subtask?.supersededAt).length;
38
57
  }
39
58
  catch {
40
59
  return Number.MAX_SAFE_INTEGER;
41
60
  }
42
61
  }
62
+ /**
63
+ * [1.11.0] 可调度/可计数的状态行:排除已被重规划替换或撤销的旧行。
64
+ *
65
+ * `closure` 仍是唯一标记。这里不复制状态的其它字段,只做视图过滤,因此
66
+ * 左侧栏、调度器、交付门禁读到的仍是同一个 `record.statuses` 数组。
67
+ */
68
+ function liveStatuses(statuses) {
69
+ return Array.isArray(statuses)
70
+ ? statuses.filter((item) => item?.closure !== 'replanned')
71
+ : [];
72
+ }
73
+ /**
74
+ * [1.11.0] C-17:交付门禁的唯一读取助手——左侧栏、present、收尾闸门、dispatch
75
+ * 返回体都从这里拿 `deliveryReady`,不再各自决定“要不要把记录级事实算进去”。
76
+ *
77
+ * `changeRequest.pending`(执行中收到、尚未重规划的变更)与 `reportPending`
78
+ * (完成结果还没写进会话)只存在于 `record` 而不是 `statuses`,所以必须在
79
+ * 这一层显式传入;`plan.ts` 的 `deliveryReadiness` 因此仍是纯函数。
80
+ */
81
+ function readinessOf(record, snapshot) {
82
+ const snap = snapshot ?? derivePlanSnapshot(record?.plan ? blockCancelledDependents(record.plan, record?.statuses) : record?.statuses, record?.plan ? definedSubtaskCount(record.plan) : undefined);
83
+ return deliveryReadiness(snap, {
84
+ phase: record?.phase,
85
+ changePending: record?.changeRequest?.status === 'pending',
86
+ reportPending: record?.reportPending === true,
87
+ /*
88
+ * 计划定义的验收标准是交付门的另一半:状态行只回答「子 Agent 说通过
89
+ * 了几条」,这里回答「计划要求的几条有没有被逐条回应」。
90
+ */
91
+ expectedAcceptance: record?.plan ? expectedAcceptanceOf(record.plan) : undefined,
92
+ });
93
+ }
43
94
  export const PLANNER_TIMEOUT_MS = 120000;
44
95
  /**
45
96
  * Absolute ceiling for one child execution.
@@ -65,6 +116,30 @@ export const MAX_CHILD_TIMEOUT_MS = 1800000;
65
116
  export const MIN_CHILD_IDLE_MS = 1000;
66
117
  export const MAX_CHILD_IDLE_MS = 900000;
67
118
  export const CHILD_POLL_MS = 2000;
119
+ /*
120
+ * [1.11.0] 派发回执的两个窗口(T4 B1/B2)。
121
+ *
122
+ * `assigned` 只是「已交给子会话」,不等于「子会话已经动了」。收不到回执时
123
+ * 静默等到空闲窗口(默认 300s)会把「根本没启动」和「在慢慢想」混为一谈:
124
+ * 90s 先标记 ackOverdue 让看板可见,180s 仍无任何新事件就按 no-ack 收束,
125
+ * 不再无限等待。
126
+ */
127
+ export const ASSIGN_ACK_NOTICE_MS = 90000;
128
+ export const ASSIGN_ACK_DEADLINE_MS = 180000;
129
+ /*
130
+ * [1.11.0] 指示回执的两个窗口(T4 B5)。
131
+ *
132
+ * `instructed` 只表示「指示已经写进状态行并投递」,不表示子 Agent 已经照做。
133
+ * 60s 没有新事件先标 `instructionOverdue`(看板可见、主 Agent 可催),
134
+ * 180s 仍无增长就按 no-ack 收束,避免「指示已下、那边根本没跑」无限挂起。
135
+ */
136
+ export const INSTRUCTION_ACK_NOTICE_MS = 60000;
137
+ export const INSTRUCTION_ACK_DEADLINE_MS = 180000;
138
+ /*
139
+ * 正向回执的观察频率。5s 足以在 60s 提醒前发现「子会话已在动」,同时把
140
+ * 会话读取次数控制在可接受范围(每个等指示的行每 5s 一次只读查询)。
141
+ */
142
+ export const INSTRUCTION_POLL_MS = 5000;
68
143
  export const TOTAL_TIMEOUT_MS = 1200000;
69
144
  export const DISPOSE_TIMEOUT_MS = 5000;
70
145
  export const STALE_PENDING_MS = 10 * 60 * 1000;
@@ -483,6 +558,67 @@ export function probeInterruptedEvidence(output, subtask, cwd, artifactExists =
483
558
  const missingArtifacts = declared.filter((ref) => !landed.includes(ref));
484
559
  return { artifacts, missingArtifacts };
485
560
  }
561
+ /**
562
+ * [1.10.6] Fingerprint the files a timed-out attempt already wrote.
563
+ *
564
+ * T6 (G3) found that the retry decision never looked at the disk: a second
565
+ * attempt could silently overwrite a deliverable the first attempt had already
566
+ * produced, turning "the child stopped early" into "the deliverable was
567
+ * rewritten". This snapshot (path + size + mtime) is the record the retry is
568
+ * compared against.
569
+ *
570
+ * A missing file is not a conflict — it simply has no fingerprint. `stat` is
571
+ * injectable so the check can be tested without touching the real filesystem.
572
+ */
573
+ export function fingerprintArtifacts(refs, cwd, stat = statSync) {
574
+ const list = Array.isArray(refs) ? refs : [];
575
+ const out = [];
576
+ const seen = new Set();
577
+ for (const item of list) {
578
+ const ref = typeof item === 'string' ? item.trim() : '';
579
+ if (!ref || seen.has(ref))
580
+ continue;
581
+ seen.add(ref);
582
+ const target = resolveArtifactPath(ref, cwd);
583
+ if (!target)
584
+ continue;
585
+ try {
586
+ const info = stat(target);
587
+ if (!info)
588
+ continue;
589
+ out.push({ ref, size: Number(info.size), mtimeMs: Number(info.mtimeMs) });
590
+ }
591
+ catch {
592
+ // Missing or unreadable: nothing to protect, and not a conflict.
593
+ }
594
+ }
595
+ return out;
596
+ }
597
+ /**
598
+ * [1.10.6] Which landed artifacts changed since the snapshot was taken.
599
+ *
600
+ * Size or mtime differing is enough to call it a conflict: the file the first
601
+ * attempt produced is no longer the file on disk, so a retry that rewrites it
602
+ * would destroy work rather than finish it.
603
+ */
604
+ export function diffArtifactFingerprints(before, after) {
605
+ const previous = new Map();
606
+ for (const item of Array.isArray(before) ? before : []) {
607
+ if (item && typeof item.ref === 'string')
608
+ previous.set(item.ref, item);
609
+ }
610
+ const conflicts = [];
611
+ for (const item of Array.isArray(after) ? after : []) {
612
+ if (!item || typeof item.ref !== 'string')
613
+ continue;
614
+ const recorded = previous.get(item.ref);
615
+ if (!recorded)
616
+ continue;
617
+ if (recorded.size !== item.size || recorded.mtimeMs !== item.mtimeMs)
618
+ conflicts.push(item.ref);
619
+ }
620
+ return conflicts;
621
+ }
486
622
  /**
487
623
  * [1.8.19] Find a subtask definition by id, without assuming the plan is valid.
488
624
  */
@@ -515,6 +651,8 @@ export function timeoutBlockedPatch(subtask, cwd, message, artifactExists = exis
515
651
  return {
516
652
  patch: {
517
653
  status: 'blocked',
654
+ closure: 'blocked',
655
+ blockedKind: 'timeout',
518
656
  progress: 100,
519
657
  finishedAt: Date.now(),
520
658
  error: message + artifactNote,
@@ -556,8 +694,32 @@ export function budgetResetError(item, subtask, cwd, artifactExists = existsSync
556
694
  * that need the environment: the strict/legacy switch and the file check.
557
695
  */
558
696
  function settleFromOutput(record, subtask, output, guard, options) {
559
- const verdict = adjudicateResult({ output, strict: options.strictEvidence !== false });
697
+ /*
698
+ * [1.11.0] 已经升级的请示不能被收尾正文覆盖。
699
+ *
700
+ * `dsh_workplan_escalate` 在子会话中途就写下了 blocked + escalated。子 Agent
701
+ * 随后仍可能补一段结果块(甚至写 done),如果这里照常 adjudicate,就会把
702
+ * 「等人拍板」洗成「完成/普通失败」,提问也随之丢失。升级一旦写入,本轮
703
+ * 的最终判定只能保留它。
704
+ */
705
+ const current = record.statuses.find((item) => item?.subtaskId === subtask.id);
706
+ if (current?.closure === 'escalated')
707
+ return { status: 'blocked', escalated: true };
708
+ const verdict = adjudicateResult({
709
+ output,
710
+ strict: options.strictEvidence !== false,
711
+ /*
712
+ * [1.11.0] 计划验收进入裁决(T5 C4 / T10 D-01)。
713
+ *
714
+ * 不传这一项时,子 Agent 可以用一条自创验收项绕过整张验收表;传了之后
715
+ * 「5 条只回 1 条」会在收尾时直接变成 blocked/unverified,而不是等到
716
+ * 交付才被用户发现。
717
+ */
718
+ expectedAcceptance: Array.isArray(subtask?.acceptance) ? subtask.acceptance : [],
719
+ });
560
720
  const checked = checkArtifacts(verdict.artifacts, options.cwd, options.artifactExists);
721
+ const escalated = verdict.status === 'blocked'
722
+ && typeof verdict.question === 'string' && verdict.question.trim() !== '';
561
723
  writeSubtaskStatus(record, subtask.id, {
562
724
  status: verdict.status,
563
725
  progress: 100,
@@ -569,29 +731,78 @@ function settleFromOutput(record, subtask, output, guard, options) {
569
731
  artifacts: checked.artifacts.length > 0 ? checked.artifacts : undefined,
570
732
  missingArtifacts: checked.missingArtifacts.length > 0 ? checked.missingArtifacts : undefined,
571
733
  needs: verdict.needs.length > 0 ? verdict.needs : undefined,
734
+ /*
735
+ * [1.11.0] 文本兜底:子会话拿不到 escalate 工具时,结果块里的
736
+ * `question` 就是同一条请示。它仍然写成 blocked 投影,但 closure 是
737
+ * escalated,看板与主 Agent 看到的都是「等指示」而不是普通失败。
738
+ */
739
+ ...(escalated
740
+ ? {
741
+ closure: 'escalated',
742
+ blockedKind: 'escalated',
743
+ question: verdict.question,
744
+ options: verdict.options,
745
+ escalatedAt: Date.now(),
746
+ escalationSeq: Number(current?.revision ?? 0) + 1,
747
+ }
748
+ : verdict.status === 'done'
749
+ /*
750
+ * [1.11.0] 完成必须落到 `closure:'done'`,不是 `blocked`。
751
+ *
752
+ * T9 的 P1 探针抓到过这里:完成路径固定写 `blocked/failed`,于是
753
+ * `done` 在执行路径不可达,「完成未回报」门禁与 `reportPending` 全部
754
+ * 恒不成立,进度栏也只能显示「失败」。完成与受阻是两种语义,必须分开。
755
+ */
756
+ ? { closure: 'done', blockedKind: null }
757
+ : {
758
+ closure: 'blocked',
759
+ blockedKind: 'failed',
760
+ }),
572
761
  }, guard);
573
762
  if (verdict.status === 'blocked') {
574
- recordSubtaskError(record, subtask.id, verdict.error ?? '未完成', guard);
763
+ recordSubtaskError(record, subtask.id, escalated ? `待指示:${verdict.question}` : (verdict.error ?? '未完成'), guard);
575
764
  }
576
765
  else if (checked.missingArtifacts.length > 0) {
577
766
  recordSubtaskError(record, subtask.id, `声明产物缺失:${checked.missingArtifacts.join('、')}`, guard);
578
767
  }
579
- return verdict;
768
+ return { ...verdict, escalated };
580
769
  }
581
770
  /**
582
771
  * Retry policy for one child attempt.
583
772
  *
584
773
  * A wedged child (no event for the whole idle window) is worth one fresh
585
- * attempt. A hard ceiling means the budget is gone, and an abort is a decision,
586
- * so neither is retried. `CHILD_NOT_COMPLETED` is retried only while there is
587
- * more than one idle window left, otherwise the retry itself would just be
588
- * killed by the same watchdog.
774
+ * attempt. `CHILD_NOT_COMPLETED` is retried only while there is more than one
775
+ * idle window left, otherwise the retry itself would just be killed by the same
776
+ * watchdog.
777
+ *
778
+ * [1.10.3] 单个子任务撞上 900 秒硬上限时,只要整轮预算还够再跑一轮,就自动重试
779
+ * 一次。用户 2026-11-01 的质疑是对的:此前这一支被无条件 `return false`,
780
+ * 于是「预算没花完、只是这一步慢了」也被判成阻塞,必须等主 Agent 人工改判或
781
+ * 重新派发——而 `attempt` 已经是 1、产物又都在盘上,重跑一次往往就能过。
782
+ *
783
+ * 仍然**不自动重试**的两种情况,理由不变:
784
+ * - `TOTAL_TIMEOUT`:整轮预算已经用光,重试必然再被同一把闸刀砍掉,只会空耗;
785
+ * - `ABORTED`:那是「有人决定停」而不是「跑不完」,自动重来等于违背决定。
589
786
  */
590
787
  export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
591
788
  if (attempt >= 2)
592
789
  return false;
593
790
  const code = error?.code;
594
- if (code === 'CHILD_TIMEOUT' || code === 'ABORTED' || code === 'TOTAL_TIMEOUT')
791
+ if (code === 'CHILD_TIMEOUT') {
792
+ /*
793
+ * 重试要有意义,必须给它留够「至少再跑一次短任务」的时间。
794
+ *
795
+ * [1.10.6] 这里**不能**再拿空闲窗口当门槛(旧式 `max(idle, 120s)`):
796
+ * 出厂配置是 ceiling=900s / idle=300s / round=1200s,撞上限后剩下约
797
+ * 300s,而 `remaining > 300s` 恒为假——用户要的「有预算就自动重试一次」
798
+ * 会在默认配置下永远不触发,正是 T6 记录的那类「策略说会、链路不会」。
799
+ * 固定 120s 是「够跑一次短任务」的下限,同时保证不会刚重试就被砍掉。
800
+ * `tests/workplan-retry-feedback.test.ts` 的 60s 反例与 600s 正例都仍然成立。
801
+ */
802
+ const floor = 120000;
803
+ return Number(remainingMs) > floor;
804
+ }
805
+ if (code === 'ABORTED' || code === 'TOTAL_TIMEOUT')
595
806
  return false;
596
807
  if (/aborted|refusal/i.test(String(error?.message ?? '')))
597
808
  return false;
@@ -605,7 +816,17 @@ export function shouldRetryAttempt(error, attempt, remainingMs, idleTimeoutMs) {
605
816
  async function executeSubtask(ctx, record, stage, subtask, options) {
606
817
  const { parentSignal, deadline, modelSelection, conversationContext = '', child, guard } = options;
607
818
  let lastError = null;
608
- let lastFailure = null;
819
+ /*
820
+ * [1.10.6] A retry that starts after a *ceiling* timeout is a second attempt
821
+ * even though this function is entered afresh. `attemptOffset` keeps the
822
+ * numbering honest (`第 2 次尝试`) and, with the loop condition below, keeps
823
+ * the cap at two real activations instead of letting the new call spend its
824
+ * own two.
825
+ */
826
+ const firstAttempt = Number.isInteger(options.attemptOffset) && options.attemptOffset > 1
827
+ ? options.attemptOffset
828
+ : 1;
829
+ let lastFailure = options.priorFailure ?? null;
609
830
  /*
610
831
  * [1.8.6] The interrupt has to outlive the thrown error.
611
832
  *
@@ -622,7 +843,7 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
622
843
  startedAt: Date.now(),
623
844
  }, guard))
624
845
  return;
625
- for (let attempt = 1; attempt <= 2; attempt += 1) {
846
+ for (let attempt = firstAttempt; attempt <= 2; attempt += 1) {
626
847
  if (guard.timedOut)
627
848
  return;
628
849
  interruptedEvidence = null;
@@ -631,6 +852,9 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
631
852
  if (Date.now() >= deadline)
632
853
  throw new PlanError('总执行超时', 'TOTAL_TIMEOUT');
633
854
  let activation = null;
855
+ // Declared outside the try so the per-attempt finally can always cancel
856
+ // the receipt timers, even when activation itself failed.
857
+ let clearAckTimers = () => { };
634
858
  try {
635
859
  if (child.controller.signal.aborted) {
636
860
  throw child.controller.signal.reason ?? abortError();
@@ -652,6 +876,16 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
652
876
  title: item.title,
653
877
  status: item.status,
654
878
  summary: item.summary,
879
+ /*
880
+ * [1.11.0] 跨部门交接物必须能被下游直接消费(用户 m00687)。
881
+ *
882
+ * 只传状态和摘要时,下游部门知道「上游做完了」,却不知道
883
+ * 产物在哪,只能重做或向主 Agent 再提一次需求。这里把上游
884
+ * 已核验存在的产物引用一并带进子提示词,交接物才算真正交接。
885
+ */
886
+ artifacts: (Array.isArray(item.artifacts) ? item.artifacts : [])
887
+ .filter((artifact) => artifact?.exists === true && typeof artifact?.ref === 'string')
888
+ .map((artifact) => String(artifact.ref)),
655
889
  })),
656
890
  cwd: options.cwd,
657
891
  conversationContext,
@@ -674,10 +908,86 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
674
908
  if (!activation || typeof activation.result?.then !== 'function') {
675
909
  throw new PlanError('子 Agent 没有返回可等待的结果', 'NO_ACTIVATION');
676
910
  }
677
- writeSubtaskStatus(record, subtask.id, {
911
+ /*
912
+ * [1.11.0] `assigned` 是「已交给子会话」,不是「子会话已确认」。
913
+ *
914
+ * 旧代码只写 childId + 10%,从这一刻起到子 Agent 真正产出第一个事件
915
+ * 之间没有任何可观察状态:用户看到 10% 长时间不动,也无法区分
916
+ * 「没启动」「启动失败」「在跑一个很长的工具」。这里把派发序号和
917
+ * 回执窗口一起写进状态,后面的 onProgress/定时器才有据可依。
918
+ */
919
+ const assignedAt = Date.now();
920
+ const dispatchSeq = Number(record.dispatchSeq ?? 0) + 1;
921
+ record.dispatchSeq = dispatchSeq;
922
+ const assigned = writeSubtaskStatus(record, subtask.id, {
678
923
  childId: activation.childId,
679
924
  progress: 10,
925
+ closure: 'assigned',
926
+ assignedAt,
927
+ dispatchSeq,
928
+ // A retry is a fresh attempt: no stale receipt or escalation survives it.
929
+ ackedAt: null,
930
+ ackEvidence: undefined,
931
+ ackOverdue: false,
932
+ escalatedAt: null,
933
+ escalationSeq: null,
934
+ question: null,
935
+ options: [],
936
+ blockedKind: null,
680
937
  }, guard);
938
+ if (!assigned)
939
+ return;
940
+ const ackTimers = [];
941
+ clearAckTimers = () => {
942
+ while (ackTimers.length > 0) {
943
+ const timer = ackTimers.pop();
944
+ if (timer)
945
+ clearTimeout(timer);
946
+ }
947
+ };
948
+ const attemptRow = () => record.statuses.find((item) => item?.subtaskId === subtask.id);
949
+ const noticeTimer = setTimeout(() => {
950
+ if (guard.timedOut)
951
+ return;
952
+ const row = attemptRow();
953
+ if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
954
+ return;
955
+ writeSubtaskStatus(record, subtask.id, { ackOverdue: true }, guard);
956
+ }, ASSIGN_ACK_NOTICE_MS);
957
+ noticeTimer.unref?.();
958
+ ackTimers.push(noticeTimer);
959
+ /*
960
+ * [1.11.0] 180s 仍无回执 → 明确收束为 no-ack,而不是继续静默等待。
961
+ *
962
+ * 看门狗默认空闲窗口是 300s,而「根本没启动」和「在慢慢想」在日志上
963
+ * 都表现为没有新事件。先把状态写成 blocked + blockedKind:'no-ack',
964
+ * 再中止子会话;主 Agent 因此能立刻看到原因,也能选择续跑。
965
+ */
966
+ const deadlineTimer = setTimeout(() => {
967
+ if (guard.timedOut)
968
+ return;
969
+ const row = attemptRow();
970
+ if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
971
+ return;
972
+ const seconds = Math.round(ASSIGN_ACK_DEADLINE_MS / 1000);
973
+ const message = `派发后 ${seconds}s 未收到子 Agent 任何新事件(no-ack)`;
974
+ writeSubtaskStatus(record, subtask.id, {
975
+ status: 'blocked',
976
+ closure: 'blocked',
977
+ blockedKind: 'no-ack',
978
+ progress: 100,
979
+ finishedAt: Date.now(),
980
+ ackOverdue: true,
981
+ error: message,
982
+ summary: `未完成:${message}`,
983
+ }, guard);
984
+ recordSubtaskError(record, subtask.id, message, guard);
985
+ if (!child.controller.signal.aborted) {
986
+ child.controller.abort(new PlanError(message, 'CHILD_NO_ACK', { subtaskId: subtask.id }));
987
+ }
988
+ }, ASSIGN_ACK_DEADLINE_MS);
989
+ deadlineTimer.unref?.();
990
+ ackTimers.push(deadlineTimer);
681
991
  const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
682
992
  const hardTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
683
993
  const watchdog = createProgressWatchdog({
@@ -696,13 +1006,32 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
696
1006
  // Poll often enough to notice growth inside a short idle window, but
697
1007
  // never more than four times per window.
698
1008
  pollMs: Math.min(CHILD_POLL_MS, Math.max(20, Math.floor(idleTimeoutMs / 4))),
699
- onProgress: ({ now }) => {
1009
+ onProgress: ({ now, seq, elapsedMs }) => {
700
1010
  if (guard.timedOut)
701
1011
  return;
702
1012
  // Visible liveness: the dashboard can show that a slow subtask is
703
1013
  // still producing events instead of looking frozen.
704
1014
  record.heartbeatAt = now;
705
1015
  record.updatedAt = now;
1016
+ /*
1017
+ * [1.11.0] 第一次观察到子会话日志增长 = 回执。
1018
+ *
1019
+ * 这是唯一能证明「子 Agent 已经在动」的廉价事实:不用它自己的
1020
+ * 汇报(可能永远等不到),只看它有没有产生新事件。回执写入后
1021
+ * 两个 no-ack 定时器立即撤销,正常的长任务不会被误判。
1022
+ */
1023
+ const row = attemptRow();
1024
+ if (row?.closure !== 'assigned' || row?.dispatchSeq !== dispatchSeq)
1025
+ return;
1026
+ const acked = writeSubtaskStatus(record, subtask.id, {
1027
+ closure: 'acknowledged',
1028
+ ackedAt: now,
1029
+ ackEvidence: { seq, elapsedMs },
1030
+ ackOverdue: false,
1031
+ progress: Math.max(Number(row.progress ?? 10), 15),
1032
+ }, guard);
1033
+ if (acked)
1034
+ clearAckTimers();
706
1035
  },
707
1036
  makeError: (reason) => new PlanError(reason === 'stalled'
708
1037
  ? `子任务 ${subtask.id} 无进展超时(${idleTimeoutMs}ms 内子 Agent 没有产生任何新事件)`
@@ -786,7 +1115,8 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
786
1115
  writeSubtaskStatus(record, subtask.id, { progress: 15 }, guard);
787
1116
  continue;
788
1117
  }
789
- if (!isAbort && remaining <= idleTimeoutMs && error?.code !== 'CHILD_TIMEOUT') {
1118
+ /* [1.10.3] CHILD_TIMEOUT 现在也会在预算充足时重试,所以「预算不足未重试」这条说明对它同样成立。 */
1119
+ if (!isAbort && remaining <= idleTimeoutMs) {
790
1120
  record.errors = [
791
1121
  ...(record.errors ?? []),
792
1122
  `${subtask.id}: 剩余预算不足(${Math.max(0, Math.round(remaining / 1000))}s),未重试`,
@@ -795,15 +1125,28 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
795
1125
  break;
796
1126
  }
797
1127
  finally {
1128
+ clearAckTimers();
798
1129
  if (activation) {
799
1130
  await disposeActivation(activation, record, subtask.id, guard);
800
1131
  activation = null;
801
1132
  }
802
1133
  }
803
1134
  }
1135
+ /*
1136
+ * [1.11.0] 已升级的请示不被最终的失败收束覆盖。
1137
+ *
1138
+ * 子 Agent 可能先调用 escalate,再因为中断/超时走到这里;此时问题已经
1139
+ * 写入状态,把它改成普通 blocked 会让主 Agent 永远看不到要回答什么。
1140
+ */
1141
+ const finalRow = record.statuses.find((item) => item?.subtaskId === subtask.id);
1142
+ if (finalRow?.closure === 'escalated') {
1143
+ return interruptedFlag ? { interrupted: true } : undefined;
1144
+ }
804
1145
  const message = describeError(lastError ?? new Error('未知失败'));
805
1146
  writeSubtaskStatus(record, subtask.id, {
806
1147
  status: 'blocked',
1148
+ closure: 'blocked',
1149
+ blockedKind: 'failed',
807
1150
  progress: 100,
808
1151
  finishedAt: Date.now(),
809
1152
  error: truncate(message, 2000),
@@ -824,8 +1167,15 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
824
1167
  catch (error) {
825
1168
  const message = describeError(error);
826
1169
  try {
1170
+ const row = record.statuses.find((item) => item?.subtaskId === subtask.id);
1171
+ if (row?.closure === 'escalated') {
1172
+ recordSubtaskError(record, subtask.id, `升级后发生异常,保留待指示状态:${message}`, guard);
1173
+ return;
1174
+ }
827
1175
  writeSubtaskStatus(record, subtask.id, {
828
1176
  status: 'blocked',
1177
+ closure: 'blocked',
1178
+ blockedKind: 'failed',
829
1179
  progress: 100,
830
1180
  finishedAt: Date.now(),
831
1181
  error: truncate(message, 2000),
@@ -839,32 +1189,69 @@ async function executeSubtask(ctx, record, stage, subtask, options) {
839
1189
  }
840
1190
  }
841
1191
  /*
842
- * Runs one subtask under a deadline that belongs to that subtask alone.
1192
+ * One attempt under a deadline that belongs to that attempt alone.
843
1193
  *
844
- * The subtask timer is a full settlement guarantee, not just an abort hint: if
845
- * the child activation ignores its abort signal, or never settles at all, the
846
- * race below still resolves, that subtask is recorded as blocked, and the
847
- * dispatcher keeps scheduling the rest of the DAG. This function never throws
848
- * on a per-subtask timeout, so one slow child can no longer blanket-block the
849
- * whole plan — only that subtask (and its real dependents) is affected.
1194
+ * [1.10.6] Split out of `runSubtask` so a ceiling timeout can be retried with a
1195
+ * *fresh* timer. The old code armed a single timer for the whole subtask (shared
1196
+ * by both attempts), so even once the retry decision became reachable the second
1197
+ * attempt would have had no time left — a patch that changes nothing.
1198
+ *
1199
+ * The timer remains a full settlement guarantee, not just an abort hint: if the
1200
+ * child activation ignores its abort signal, or never settles at all, the race
1201
+ * below still resolves, the subtask is recorded as blocked, and the dispatcher
1202
+ * keeps scheduling the rest of the DAG.
850
1203
  */
851
- async function runSubtask(ctx, record, stage, subtask, options) {
852
- const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
1204
+ async function runSubtaskAttempt(ctx, record, stage, subtask, options, timeoutMs) {
853
1205
  const child = createChildController(options.parentSignal);
854
1206
  const guard = { timedOut: false };
855
1207
  let timer = null;
1208
+ let ceilingFired = false;
1209
+ // [1.10.6] What the ceiling left on disk, in the words of the same probe the
1210
+ // blocked row records. The retry is compared against exactly this list.
1211
+ let ceilingLanded = [];
1212
+ /*
1213
+ * [1.10.6] Snapshot taken *at the moment the ceiling fires*, not later.
1214
+ *
1215
+ * The first cut of this check fingerprinted the same refs twice, back to back,
1216
+ * immediately before the retry. Two reads of the same instant can never
1217
+ * differ, so the conflict branch was unreachable in production (only a test
1218
+ * injecting a mutating `stat` could reach it). The record must be taken while
1219
+ * the timeout is being recorded; the pre-retry read is compared against it.
1220
+ */
1221
+ let ceilingFingerprint = [];
1222
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
856
1223
  const deadlinePromise = new Promise((resolve) => {
857
1224
  timer = setTimeout(() => {
1225
+ ceilingFired = true;
858
1226
  guard.timedOut = true;
859
1227
  // Reached only when the child ignored both its idle window and its
860
1228
  // abort signal; the message says so, otherwise the cause looks like a
861
1229
  // plain "too slow" and the next investigation goes down the wrong path.
862
- const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms),已强制结束`;
1230
+ const message = `子任务 ${subtask.id} 达到执行上限(${timeoutMs}ms),已强制结束`;
863
1231
  try {
864
1232
  // [1.8.19] Keep the evidence of what already landed on disk.
865
- const { patch } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
866
- record.statuses = applyStatus(record.statuses, subtask.id, patch);
867
- record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
1233
+ const { patch, landed } = timeoutBlockedPatch(subtask, options.cwd, message, options.artifactExists);
1234
+ ceilingLanded = Array.isArray(landed) ? landed : [];
1235
+ ceilingFingerprint = fingerprintArtifacts(ceilingLanded, options.cwd, stat);
1236
+ /*
1237
+ * [1.11.0] An escalation outranks the ceiling.
1238
+ *
1239
+ * The child may have written `escalated` seconds before this timer fired;
1240
+ * turning that into a plain timeout would erase the question the main
1241
+ * Agent has to answer. The activation is still aborted, but the row keeps
1242
+ * its pending-decision state.
1243
+ */
1244
+ const existing = record.statuses.find((item) => item?.subtaskId === subtask.id);
1245
+ if (existing?.closure === 'escalated') {
1246
+ record.errors = [
1247
+ ...(record.errors ?? []),
1248
+ `${subtask.id}: 已达执行上限,但该子任务已在等待指示,保留 escalated 状态`,
1249
+ ].slice(-20);
1250
+ }
1251
+ else {
1252
+ record.statuses = applyStatus(record.statuses, subtask.id, patch);
1253
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${patch.error}`].slice(-20);
1254
+ }
868
1255
  record.updatedAt = Date.now();
869
1256
  }
870
1257
  catch (error) {
@@ -880,13 +1267,13 @@ async function runSubtask(ctx, record, stage, subtask, options) {
880
1267
  child.disposeListener();
881
1268
  resolve();
882
1269
  }
883
- }, childTimeoutMs);
1270
+ }, timeoutMs);
884
1271
  timer.unref?.();
885
1272
  });
886
1273
  try {
887
1274
  // [1.8.6] The outcome (`{interrupted:true}`) has to reach the dispatcher;
888
1275
  // swallowing it here is why an interrupted child looked like any failure.
889
- return await Promise.race([
1276
+ const outcome = await Promise.race([
890
1277
  executeSubtask(ctx, record, stage, subtask, {
891
1278
  ...options,
892
1279
  child,
@@ -894,6 +1281,7 @@ async function runSubtask(ctx, record, stage, subtask, options) {
894
1281
  }),
895
1282
  deadlinePromise,
896
1283
  ]);
1284
+ return { outcome, ceilingFired, ceilingLanded, ceilingFingerprint };
897
1285
  }
898
1286
  finally {
899
1287
  if (timer) {
@@ -905,6 +1293,87 @@ async function runSubtask(ctx, record, stage, subtask, options) {
905
1293
  child.controller.abort();
906
1294
  }
907
1295
  }
1296
+ /*
1297
+ * Runs one subtask, retrying **once** when the per-subtask ceiling fired and the
1298
+ * round budget can still pay for a second attempt (T6 G1/G3/G4).
1299
+ *
1300
+ * The retry is deliberately narrow:
1301
+ * - only the ceiling (`CHILD_TIMEOUT`) qualifies; a user abort and a round
1302
+ * budget timeout stay non-retryable, because retrying them would be killed by
1303
+ * the same guillotine;
1304
+ * - at most one retry (`attemptOffset: 2` caps the inner loop at a single run);
1305
+ * - before it starts, the artifacts the first attempt landed are fingerprinted
1306
+ * (path + size + mtime) and re-checked. If any of them changed since the
1307
+ * timeout was recorded, something else owns that file now: the retry is
1308
+ * skipped and the row is marked `artifactConflict` instead of overwriting it.
1309
+ */
1310
+ async function runSubtask(ctx, record, stage, subtask, options) {
1311
+ const childTimeoutMs = normaliseChildTimeout(options.childTimeoutMs);
1312
+ const first = await runSubtaskAttempt(ctx, record, stage, subtask, options, childTimeoutMs);
1313
+ if (!first.ceilingFired)
1314
+ return first.outcome;
1315
+ const idleTimeoutMs = normaliseIdleTimeout(options.idleTimeoutMs);
1316
+ const now = Date.now();
1317
+ const deadline = Number.isFinite(options.deadline) ? Number(options.deadline) : now + childTimeoutMs;
1318
+ const remaining = deadline - now;
1319
+ const message = `子任务 ${subtask.id} 达到执行上限(${childTimeoutMs}ms)`;
1320
+ /*
1321
+ * [1.8.6] A parent abort outranks a retry: the round is being stopped on
1322
+ * purpose, and a second child would only be aborted on arrival.
1323
+ */
1324
+ if (options.parentSignal?.aborted)
1325
+ return first.outcome;
1326
+ if (!shouldRetryAttempt({ code: 'CHILD_TIMEOUT', message }, 1, remaining, idleTimeoutMs)) {
1327
+ record.errors = [
1328
+ ...(record.errors ?? []),
1329
+ `${subtask.id}: 达到执行上限,剩余预算 ${Math.max(0, Math.round(remaining / 1000))}s 不足,未重试`,
1330
+ ].slice(-20);
1331
+ return first.outcome;
1332
+ }
1333
+ /*
1334
+ * [1.10.6] T6 G3: never retry over work that already exists.
1335
+ *
1336
+ * `ceilingFingerprint` was taken the moment the ceiling fired (inside the
1337
+ * timeout callback); the same refs are re-read right before the retry starts.
1338
+ * A size or mtime difference means the file was written by somebody else in
1339
+ * between, so a retry would overwrite it rather than finish it.
1340
+ */
1341
+ const stat = typeof options.artifactStat === 'function' ? options.artifactStat : statSync;
1342
+ const current = fingerprintArtifacts(first.ceilingLanded, options.cwd, stat);
1343
+ const conflicts = diffArtifactFingerprints(first.ceilingFingerprint, current);
1344
+ const row = Array.isArray(record.statuses)
1345
+ ? record.statuses.find((item) => item.subtaskId === subtask.id)
1346
+ : null;
1347
+ if (conflicts.length > 0) {
1348
+ const note = `重试前核对发现已落盘产物在超时后被改动(${conflicts.join('、')}),为避免覆盖已跳过自动重试,请人工核对`;
1349
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1350
+ artifactConflict: conflicts,
1351
+ error: truncate(`${truncate(String(row?.error ?? message), 1500)};${note}`, 2000),
1352
+ });
1353
+ record.errors = [...(record.errors ?? []), `${subtask.id}: ${note}`].slice(-20);
1354
+ record.updatedAt = Date.now();
1355
+ return first.outcome;
1356
+ }
1357
+ record.statuses = applyStatus(record.statuses, subtask.id, {
1358
+ status: 'in_progress',
1359
+ progress: 15,
1360
+ // Clearing `error` moves the timeout text to `lastError` (applyStatus does
1361
+ // that move), so the row no longer claims "blocked" while it is retrying.
1362
+ error: null,
1363
+ });
1364
+ record.errors = [
1365
+ ...(record.errors ?? []),
1366
+ `${subtask.id}: 第 1 次执行达到上限(CHILD_TIMEOUT),已核对产物无冲突,自动重试一次`,
1367
+ ].slice(-20);
1368
+ record.updatedAt = Date.now();
1369
+ const retryTimeoutMs = Math.max(MIN_CHILD_TIMEOUT_MS, Math.min(childTimeoutMs, remaining));
1370
+ const second = await runSubtaskAttempt(ctx, record, stage, subtask, {
1371
+ ...options,
1372
+ attemptOffset: 2,
1373
+ priorFailure: { attempt: 1, code: 'CHILD_TIMEOUT', message: `${message},已强制结束` },
1374
+ }, retryTimeoutMs);
1375
+ return second.outcome;
1376
+ }
908
1377
  async function runWithConcurrency(items, limit, worker) {
909
1378
  let cursor = 0;
910
1379
  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
@@ -962,6 +1431,29 @@ export function modelStatusLines(statuses) {
962
1431
  updatedBy: item.updatedBy ?? null,
963
1432
  missingArtifacts: Array.isArray(item.missingArtifacts) ? item.missingArtifacts : [],
964
1433
  needs: Array.isArray(item.needs) ? item.needs : [],
1434
+ // [1.11.0] 闭环阶段必须进入模型可读面:只暴露四值 status 时,
1435
+ // 「在等指示」和「做失败了」在工具输出里长得一模一样。
1436
+ closure: item.closure ?? null,
1437
+ blockedKind: item.blockedKind ?? null,
1438
+ question: item.question ?? null,
1439
+ options: Array.isArray(item.options) ? item.options : [],
1440
+ ackOverdue: item.ackOverdue === true,
1441
+ escalatedAt: item.escalatedAt ?? null,
1442
+ instruction: item.instruction?.text ? truncate(item.instruction.text, 500) : null,
1443
+ /*
1444
+ * [1.11.0] 跨部门需求的待处理项必须出现在模型可读面(用户 m00687)。
1445
+ *
1446
+ * 只放在结果消息里时,主 Agent 一旦错过那一轮就再也看不到「还有一条
1447
+ * 需求没处置」,而交付门禁却一直拦着。status 工具是与进度同源的读取口,
1448
+ * 这里只暴露未处置项,避免把已答复的历史反复塞进上下文。
1449
+ */
1450
+ openHandoffs: openHandoffs(item).map((handoff) => ({
1451
+ id: handoff.id,
1452
+ request: truncate(String(handoff.request ?? ''), 300),
1453
+ department: handoff.department ?? null,
1454
+ status: handoff.status,
1455
+ })),
1456
+ reportedAt: item.reportedAt ?? null,
965
1457
  }));
966
1458
  }
967
1459
  export function buildRoundResult(record, sessionId, limits) {
@@ -978,6 +1470,14 @@ export function buildRoundResult(record, sessionId, limits) {
978
1470
  phase: record.phase,
979
1471
  resumeCount: Number(record.resumeCount ?? 0),
980
1472
  resumeAvailable: canResumePlan(record, limits.maxResumes).resume,
1473
+ // [1.11.0] 结果消息也带上修订号,回放时才知道这份结果属于哪一版计划。
1474
+ planRevision: Number(record.planRevision ?? 0),
1475
+ /*
1476
+ * [1.11.0] C-17:记录级闭环事实随结果消息下发,让摘要里的判定与
1477
+ * `deliveryReady` 门禁读同一组输入(否则「结果说完成、present 被拒」)。
1478
+ */
1479
+ changePending: record.changeRequest?.status === 'pending',
1480
+ reportPending: record.reportPending === true,
981
1481
  });
982
1482
  }
983
1483
  /**
@@ -1035,6 +1535,11 @@ export async function dispatchPlan(ctx, record, options) {
1035
1535
  * its side effects) while giving the rest a second chance, and the resume
1036
1536
  * budget stops a subtask that always fails from looping forever.
1037
1537
  */
1538
+ /*
1539
+ * [1.11.0] 重规划 cancel 留下的悬挂下游,在派发前显式收束成 blocked
1540
+ * (T4 D-T4-02)。否则它们永远 pending,既不报错也不进入交付阻塞。
1541
+ */
1542
+ record.statuses = blockCancelledDependents(record.plan, record.statuses);
1038
1543
  const resume = canResumePlan(record, options.maxResumes ?? MAX_PLAN_RESUMES);
1039
1544
  if (resume.resume) {
1040
1545
  /*
@@ -1059,7 +1564,13 @@ export async function dispatchPlan(ctx, record, options) {
1059
1564
  ].slice(-20);
1060
1565
  }
1061
1566
  else {
1062
- record.errors = (record.errors ?? []).filter((line) => !/预算|续跑/.test(String(line))).slice(-20);
1567
+ /*
1568
+ * [1.10.4] 保留自动续跑的审计行:它们必然含「续跑/预算」字样,旧过滤器
1569
+ * 会把「为什么自动续跑、停在哪个判定码」一起擦掉,正好毁掉事后取证。
1570
+ */
1571
+ record.errors = (record.errors ?? [])
1572
+ .filter((line) => !/预算|续跑/.test(String(line)) || String(line).includes('[auto-resume]'))
1573
+ .slice(-20);
1063
1574
  }
1064
1575
  }
1065
1576
  const parentSignal = signal;
@@ -1102,9 +1613,19 @@ export async function dispatchPlan(ctx, record, options) {
1102
1613
  * an older plan or a debugging session can keep plain status semantics.
1103
1614
  */
1104
1615
  const gate = options.artifactGate !== false;
1105
- const ready = readySubtasks(record.plan, record.statuses, gate
1616
+ const ready = readySubtasks(record.plan, liveStatuses(record.statuses), gate
1106
1617
  ? {
1618
+ /*
1619
+ * [1.11.0] 未验收的 done 不再解锁下游(T5 C5 / T8 S1-05)。
1620
+ *
1621
+ * `done` 只说明子 Agent 交了东西;`unverified`/`failed` 说明
1622
+ * 交付内容没有通过验收。让下游在这时开跑,等于把未验证的结论
1623
+ * 当上游契约使用——跨部门链条会一路放大错误。legacy(旧日志)
1624
+ * 与 structured 仍放行,避免历史计划整体卡死。
1625
+ */
1107
1626
  dependencyOk: (dependency) => dependency?.status === 'done'
1627
+ && dependency?.verification !== 'unverified'
1628
+ && dependency?.verification !== 'failed'
1108
1629
  && !(Array.isArray(dependency?.missingArtifacts) && dependency.missingArtifacts.length > 0),
1109
1630
  }
1110
1631
  : {});
@@ -1119,7 +1640,7 @@ export async function dispatchPlan(ctx, record, options) {
1119
1640
  * status, the plan turned `blocked`, and a resume was billed against
1120
1641
  * the failure budget. Keep them `pending`, and record the actual cause.
1121
1642
  */
1122
- const pending = record.statuses.filter((item) => item.status === 'pending');
1643
+ const pending = liveStatuses(record.statuses).filter((item) => item.status === 'pending');
1123
1644
  if (pending.length > 0) {
1124
1645
  const reasons = pending.map((item) => `${item.subtaskId}:${describePendingCause(record.plan, record.statuses, item.subtaskId)}`);
1125
1646
  const message = `本轮结束,仍有 ${pending.length} 项保持 pending(不是失败,也未级联成 blocked):${reasons.slice(0, 6).join(';')}`;
@@ -1147,6 +1668,9 @@ export async function dispatchPlan(ctx, record, options) {
1147
1668
  conversationContext,
1148
1669
  strictEvidence: options.strictEvidence,
1149
1670
  artifactExists: options.artifactExists,
1671
+ // [1.10.6] Injectable stat for the pre-retry fingerprint check; tests
1672
+ // use it so the conflict branch is provable without real files.
1673
+ artifactStat: options.artifactStat,
1150
1674
  });
1151
1675
  // [1.8.6] Remember which failures were interrupts, so the cascade below
1152
1676
  // can leave their dependents pending instead of blaming them.
@@ -1198,8 +1722,8 @@ export async function dispatchPlan(ctx, record, options) {
1198
1722
  * `blocked` for real failures, and report `paused` when only pending work
1199
1723
  * is left, so a resume is not billed against the failure budget.
1200
1724
  */
1201
- const hasBlocked = record.statuses.some((item) => item.status === 'blocked');
1202
- const hasPending = record.statuses.some((item) => item.status === 'pending');
1725
+ const hasBlocked = liveStatuses(record.statuses).some((item) => item.status === 'blocked');
1726
+ const hasPending = liveStatuses(record.statuses).some((item) => item.status === 'pending');
1203
1727
  record.phase = hasBlocked ? 'blocked' : (hasPending ? 'paused' : planPhase(record.statuses));
1204
1728
  }
1205
1729
  catch (error) {
@@ -1275,6 +1799,9 @@ export async function dispatchPlan(ctx, record, options) {
1275
1799
  * or 100 % depending on which branch happened to write it.
1276
1800
  */
1277
1801
  record.statuses = record.statuses.map((item) => {
1802
+ // [1.11.0] 被重规划的行不参与「失败收敛」:它们本来就是闭态旧行。
1803
+ if (item.closure === 'replanned')
1804
+ return item;
1278
1805
  if (item.status === 'pending' || item.status === 'in_progress') {
1279
1806
  return {
1280
1807
  ...item,
@@ -1406,7 +1933,16 @@ function serialisePlan(record, session) {
1406
1933
  : plan
1407
1934
  ? createStatuses(plan)
1408
1935
  : [];
1409
- const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses);
1936
+ /*
1937
+ * [1.10.0] 分母来自计划定义,并允许「明细行少于定义」时按 pending 补齐。
1938
+ * `definedSubtaskCount` 对畸形计划返回 MAX_SAFE_INTEGER,那种情况下退回
1939
+ * 「只数明细行」,避免把一个坏计划直接判成 0/天文数字。
1940
+ */
1941
+ const defined = plan ? definedSubtaskCount(plan) : 0;
1942
+ const expectedTotal = Number.isFinite(defined) && defined > 0 && defined < Number.MAX_SAFE_INTEGER
1943
+ ? defined
1944
+ : undefined;
1945
+ const snapshot = derivePlanSnapshot(turnEnded ? settleStaleInflight(rawStatuses) : rawStatuses, expectedTotal);
1410
1946
  const statuses = snapshot.statuses;
1411
1947
  const stats = snapshot.stats;
1412
1948
  /*
@@ -1458,7 +1994,7 @@ function serialisePlan(record, session) {
1458
1994
  * 而不是等用户截图发现。附在 payload 上而不是抛错:展示层不应因自检而白屏。
1459
1995
  */
1460
1996
  const violations = aggregateInvariantViolations(snapshot, phase);
1461
- const readiness = deliveryReadiness(snapshot, { phase: record.phase });
1997
+ const readiness = readinessOf(record, snapshot);
1462
1998
  return {
1463
1999
  sessionId: session.id,
1464
2000
  planId: record.planId ?? plan?.planId ?? null,
@@ -1468,7 +2004,18 @@ function serialisePlan(record, session) {
1468
2004
  ...(violations.length ? { violations } : {}),
1469
2005
  degraded: record.degraded === true,
1470
2006
  error: record.error ? truncate(record.error, 2000) : null,
1471
- errors: (record.errors ?? []).slice(-20),
2007
+ /*
2008
+ * [1.10.0] C-18:「已结束 / 已完成」的计划不再把上一轮的失败文本摆在首页。
2009
+ *
2010
+ * 1.9.1 把 `record.errors`("本轮执行预算已到:已完成 9/13…" 之类)无条件
2011
+ * 下发,界面又无条件渲染,于是 13/13 完成的那一帧下面还挂着一句「这件事没有
2012
+ * 做完」。现在:计划已 done 或 cancelled 时,这批文本改挂 `archivedErrors`,
2013
+ * 供折叠区/审计使用;`errors` 只在计划仍需处理时下发。
2014
+ */
2015
+ errors: phase === 'done' || phase === 'cancelled' ? [] : (record.errors ?? []).slice(-20),
2016
+ ...(phase === 'done' || phase === 'cancelled'
2017
+ ? { archivedErrors: (record.errors ?? []).slice(-20) }
2018
+ : {}),
1472
2019
  createdAt: record.createdAt ?? plan?.createdAt ?? session.header.createdAt,
1473
2020
  updatedAt: record.updatedAt ?? Date.now(),
1474
2021
  createdTurn: plan?.createdTurn ?? record.createdTurn ?? null,
@@ -1486,6 +2033,16 @@ function serialisePlan(record, session) {
1486
2033
  deliveryReady: readiness.ready,
1487
2034
  deliveryBlockers: readiness.blockers.slice(0, 12),
1488
2035
  deliveryRemaining: readiness.remaining.slice(0, 20),
2036
+ /*
2037
+ * [1.11.0] 重规划与回报状态随载荷下发(T7 C-15)。
2038
+ *
2039
+ * `planRevision` 让界面能显示「第 N 次修订」;`changeRequest` 是执行中
2040
+ * 收到、尚未重规划的用户变更;`reportPending` 表示完成结果还没成功回报。
2041
+ * 三者都来自 record 的同一份事实,不另建缓存。
2042
+ */
2043
+ planRevision: Number(record.planRevision ?? 0),
2044
+ changeRequest: record.changeRequest ?? null,
2045
+ reportPending: record.reportPending === true,
1489
2046
  /*
1490
2047
  * Liveness and resume bookkeeping. Without these the dashboard could not
1491
2048
  * tell a slow-but-alive child from a wedged one, and the model could not
@@ -1636,6 +2193,8 @@ export function reconstructFromSession(session, targetPlanId) {
1636
2193
  superseded: false,
1637
2194
  supersededBy: undefined,
1638
2195
  errors: [],
2196
+ planRevision: Number(plan?.planRevision ?? 0) || 0,
2197
+ changeRequest: null,
1639
2198
  };
1640
2199
  snapshots.set(plan.planId, snap);
1641
2200
  }
@@ -1679,6 +2238,44 @@ export function reconstructFromSession(session, targetPlanId) {
1679
2238
  * that was the 13/14 → 5/14 replay regression. A plan never inherits
1680
2239
  * another plan's round phase or resume counter (each snapshot owns them).
1681
2240
  */
2241
+ /*
2242
+ * [1.11.0] 重规划记录:采用 durable 消息里的完整修订计划,不重新推导。
2243
+ * 旧行在同一份 plan 里带 supersededAt,状态条目同步标 closure='replanned'。
2244
+ */
2245
+ const replan = parseReplanMessage(event.data);
2246
+ if (replan && typeof replan.planId === 'string') {
2247
+ const snap = snapshots.get(replan.planId);
2248
+ if (snap) {
2249
+ snap.plan = replan.plan;
2250
+ snap.planRevision = Number(replan.revision) || snap.planRevision;
2251
+ snap.statuses = applyReplanStatuses(snap.statuses, replan);
2252
+ if (snap.changeRequest && snap.changeRequest.status !== 'replanned') {
2253
+ snap.changeRequest = {
2254
+ ...snap.changeRequest,
2255
+ status: 'replanned',
2256
+ replannedAt: replan.at,
2257
+ planRevision: snap.planRevision,
2258
+ };
2259
+ }
2260
+ }
2261
+ }
2262
+ /*
2263
+ * [1.11.0] 执行中收到的变更:恢复成 changeRequest,刷新后仍然可见、
2264
+ * 仍然阻止“静默收尾”。
2265
+ */
2266
+ const change = parseChangeRequestMessage(event.data);
2267
+ if (change && typeof change.planId === 'string') {
2268
+ const snap = snapshots.get(change.planId);
2269
+ if (snap) {
2270
+ snap.changeRequest = {
2271
+ seq: change.seq,
2272
+ text: change.text,
2273
+ at: change.at,
2274
+ turn: change.turn,
2275
+ status: 'pending',
2276
+ };
2277
+ }
2278
+ }
1682
2279
  const result = parseResultMessage(event.data);
1683
2280
  if (result && typeof result.planId === 'string') {
1684
2281
  const snap = snapshots.get(result.planId);
@@ -1930,6 +2527,19 @@ export function reconstructFromSession(session, targetPlanId) {
1930
2527
  superseded,
1931
2528
  supersedeRecorded: superseded,
1932
2529
  supersededBy: superseded ? chosen.supersededBy : undefined,
2530
+ /*
2531
+ * [1.11.0] 回放也恢复修订号与未处理变更。`reportPending` 由状态本身派生:
2532
+ * 存在 done 行却没到 reported,说明当时的结果消息没有成功写进会话。
2533
+ */
2534
+ planRevision: chosen.planRevision,
2535
+ changeRequest: chosen.changeRequest,
2536
+ /*
2537
+ * [1.11.0] 只把「本轮完成、还没回报」算作待回报:`closure:'done'` 是
2538
+ * 1.11.0 的显式中间态。旧日志的 done 行没有 closure(null),它本来就
2539
+ * 已经通过结果消息回报过,若用 `!== 'reported'` 判定,升级后每一份
2540
+ * 1.10.6 的历史计划都会被判成「未回报」而永久不可交付。
2541
+ */
2542
+ reportPending: statuses.some((item) => item?.status === 'done' && item?.closure === 'done'),
1933
2543
  };
1934
2544
  }
1935
2545
  function liveSessions(ctx) {
@@ -2054,6 +2664,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
2054
2664
  maxResumes: Number.isFinite(Number(options.maxResumes)) && Number(options.maxResumes) >= 0
2055
2665
  ? Math.min(5, Math.floor(Number(options.maxResumes)))
2056
2666
  : MAX_PLAN_RESUMES,
2667
+ autoResume: {
2668
+ enabled: options.autoResume === true,
2669
+ maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2670
+ },
2057
2671
  };
2058
2672
  async function onPreStep(payload, next) {
2059
2673
  let downstream;
@@ -2066,6 +2680,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
2066
2680
  if (downstream?.kind !== 'enter')
2067
2681
  return downstream;
2068
2682
  try {
2683
+ /*
2684
+ * [1.11.0] 回报自愈(契约 §7.3 B4):上一轮结果消息已写入,但回报标记
2685
+ * 写失败/进程中断时,下一步 pre-step 幂等补齐,不重复追加上下文。
2686
+ */
2687
+ const session = payload.agent?.session;
2688
+ const known = session ? state.records.get(session.id) : null;
2689
+ if (known?.plan && known.reportPending === true && known.resultWritten === true) {
2690
+ const changed = markReported(known, session, `${known.plan.planId}:${known.dispatchedAt ?? 0}`);
2691
+ if (changed > 0) {
2692
+ known.reportPending = (known.statuses ?? []).some((item) => item?.status === 'done' && item?.closure === 'done');
2693
+ }
2694
+ }
2069
2695
  return await maybePlan(ctx, state, payload, downstream, { ...options, limits });
2070
2696
  }
2071
2697
  catch (error) {
@@ -2140,6 +2766,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2140
2766
  record = adoptRequestedPlan(session, record, args?.planId);
2141
2767
  if (!record?.plan)
2142
2768
  throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
2769
+ // [1.10.4] 人工改判优先于任何已排期的自动续跑:先撤销定时器,再写状态。
2770
+ clearAutoResumeTimer(record, 'manual-update');
2143
2771
  const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId : '';
2144
2772
  if (!subtaskId)
2145
2773
  throw new PlanError('缺少 subtaskId', 'MISSING_SUBTASK');
@@ -2193,6 +2821,59 @@ export function createWorkplanRuntime(ctx, options = {}) {
2193
2821
  hint: '该子任务正在执行;请等待本轮结束,或传 force:true 覆盖(会被记录为人工改判)。',
2194
2822
  };
2195
2823
  }
2824
+ /*
2825
+ * [1.11.0] 待指示行的两条合法出口(T4 S4→S5 / S4→S6)。
2826
+ *
2827
+ * `dsh_workplan_update` 也是 `instruct` 的等价入口:带 instruction 即恢复
2828
+ * 推进,不带 instruction 直接 in_progress/done 会把一条未回答的请示洗成
2829
+ * 「在做/做完」,所以显式拒绝,并告诉主 Agent 该用哪个字段。
2830
+ */
2831
+ const instruction = typeof args?.instruction === 'string' ? args.instruction.trim() : '';
2832
+ if (instruction) {
2833
+ if (current?.closure !== 'escalated') {
2834
+ return {
2835
+ ok: false,
2836
+ code: 'NOT_ESCALATED',
2837
+ planId: record.plan.planId,
2838
+ subtaskId,
2839
+ error: '该子任务不在待指示状态,不需要 instruction;普通受阻请直接改判。',
2840
+ };
2841
+ }
2842
+ if (status !== 'in_progress') {
2843
+ return {
2844
+ ok: false,
2845
+ code: 'INSTRUCTION_REQUIRES_IN_PROGRESS',
2846
+ planId: record.plan.planId,
2847
+ subtaskId,
2848
+ error: '下发 instruction 时 status 必须是 in_progress(或改用 dsh_workplan_instruct)。',
2849
+ };
2850
+ }
2851
+ return instructSubtask(agent, {
2852
+ planId: args?.planId,
2853
+ subtaskId,
2854
+ instruction,
2855
+ }, undefined, record);
2856
+ }
2857
+ if (current?.closure === 'escalated') {
2858
+ if (status === 'done') {
2859
+ return {
2860
+ ok: false,
2861
+ code: 'ESCALATION_OPEN',
2862
+ planId: record.plan.planId,
2863
+ subtaskId,
2864
+ error: '该子任务仍在等待指示,不能直接改判 done:请先给出 instruction,或明确改判 blocked 放弃。',
2865
+ };
2866
+ }
2867
+ if (status === 'in_progress') {
2868
+ return {
2869
+ ok: false,
2870
+ code: 'INSTRUCTION_REQUIRED',
2871
+ planId: record.plan.planId,
2872
+ subtaskId,
2873
+ error: '该子任务正在等待指示:恢复推进必须传 instruction(或调用 dsh_workplan_instruct),不能只改 status。',
2874
+ };
2875
+ }
2876
+ }
2196
2877
  const revision = Number(current?.revision ?? 0) + 1;
2197
2878
  /*
2198
2879
  * [1.8.13] A manual verdict can carry structured evidence.
@@ -2219,6 +2900,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
2219
2900
  summary: summary || undefined,
2220
2901
  error: status === 'blocked' ? (summary || '由主 Agent 标记为受阻') : undefined,
2221
2902
  ...evidencePatch,
2903
+ /*
2904
+ * [1.11.0] 明确放弃(blocked)必须同时关掉 escalated,否则
2905
+ * applyStatus 会保留「等指示」投影,主 Agent 的放弃写了个寂寞。
2906
+ */
2907
+ ...(current?.closure === 'escalated' && status === 'blocked'
2908
+ ? { closure: 'blocked', blockedKind: 'failed', question: null, options: [] }
2909
+ : {}),
2222
2910
  revision,
2223
2911
  updatedBy: 'agent',
2224
2912
  });
@@ -2245,6 +2933,12 @@ export function createWorkplanRuntime(ctx, options = {}) {
2245
2933
  acceptance: writtenRow?.acceptance,
2246
2934
  artifacts: writtenRow?.artifacts,
2247
2935
  missingArtifacts: writtenRow?.missingArtifacts,
2936
+ closure: writtenRow?.closure,
2937
+ blockedKind: writtenRow?.blockedKind,
2938
+ question: writtenRow?.question,
2939
+ options: writtenRow?.options,
2940
+ instruction: writtenRow?.instruction,
2941
+ instructionSeq: writtenRow?.instructionSeq,
2248
2942
  }), { surfaceOp: 'append' });
2249
2943
  }
2250
2944
  catch (error) {
@@ -2263,7 +2957,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2263
2957
  record.updatedAt = Date.now();
2264
2958
  const snapshot = derivePlanSnapshot(record.statuses);
2265
2959
  const written = snapshot.statuses.find((item) => item.subtaskId === subtaskId);
2266
- const readiness = deliveryReadiness(snapshot, { phase: record.phase });
2960
+ const readiness = readinessOf(record, snapshot);
2267
2961
  return {
2268
2962
  ok: true,
2269
2963
  planId: record.plan.planId,
@@ -2284,6 +2978,126 @@ export function createWorkplanRuntime(ctx, options = {}) {
2284
2978
  }),
2285
2979
  };
2286
2980
  }
2981
+ /**
2982
+ * [1.11.0] C-11:需求变更的唯一写入入口(dsh_workplan_replan)。
2983
+ *
2984
+ * 为什么必须单独一个工具,而不是让模型直接改计划消息:
2985
+ * 1. 旧行的 `supersededAt` 与状态条的 `closure:'replanned'` 必须同一次写入,
2986
+ * 否则调度器会继续跑「已撤销」的工作;
2987
+ * 2. durable `workplan-replan` 带上完整修订计划,刷新后才能得到同一份定义;
2988
+ * 3. 执行中收到变更时,工具返回 `REPLAN_PLAN_RUNNING` 并保留 changeRequest,
2989
+ * 让模型等待而不是静默丢弃或强行中断正在跑的子任务。
2990
+ */
2991
+ async function replanPlan(agent, args) {
2992
+ const session = agent?.session;
2993
+ if (!session)
2994
+ throw new PlanError('只能在会话内重规划', 'NO_SESSION');
2995
+ if (!isRootSession(session))
2996
+ throw new PlanError('子 Agent 不能重规划主计划', 'NOT_ROOT');
2997
+ let record = state.records.get(session.id);
2998
+ if (!record?.plan)
2999
+ record = reconstructFromSession(session, args?.planId);
3000
+ record = adoptRequestedPlan(session, record, args?.planId);
3001
+ if (!record?.plan)
3002
+ throw new PlanError('当前会话还没有已生成的计划', 'NO_PLAN');
3003
+ const planId = record.plan.planId;
3004
+ const revisionNow = Number(record.planRevision ?? record.plan?.planRevision ?? 0);
3005
+ const base = {
3006
+ ok: false,
3007
+ planId,
3008
+ planRevision: revisionNow,
3009
+ stats: derivePlanSnapshot(record.statuses).stats,
3010
+ };
3011
+ if (record.phase === 'cancelled' || record.phase === 'superseded' || record.superseded === true) {
3012
+ return {
3013
+ ...base,
3014
+ code: 'REPLAN_TERMINAL',
3015
+ error: '计划已是终态(已取消/已被取代),不能重规划',
3016
+ hint: '终态计划不会复活:如需继续这项工作,请让主 Agent 生成新计划。',
3017
+ };
3018
+ }
3019
+ if (record.dispatchPromise) {
3020
+ /*
3021
+ * 执行中拒绝改写定义,但把变更原文记下来。旧行为(maybePlan 直接
3022
+ * return downstream)会让用户在派发期间说的新需求彻底消失。
3023
+ */
3024
+ const change = typeof args?.changeText === 'string' ? truncate(args.changeText.trim(), 4000) : '';
3025
+ if (change) {
3026
+ const seq = Number(record.changeRequestSeq ?? 0) + 1;
3027
+ record.changeRequestSeq = seq;
3028
+ record.changeRequest = {
3029
+ seq,
3030
+ text: change,
3031
+ at: Date.now(),
3032
+ turn: Number(state.activeTurns?.get?.(session.id) ?? NaN) || null,
3033
+ status: 'pending',
3034
+ };
3035
+ record.updatedAt = Date.now();
3036
+ }
3037
+ state.records.set(session.id, record);
3038
+ return {
3039
+ ...base,
3040
+ code: 'REPLAN_PLAN_RUNNING',
3041
+ error: '本轮派发仍在执行:重规划不会中途改写正在跑的子任务',
3042
+ hint: '先轮询 dsh_workplan_status 等本轮结束(或先 cancel 并等它收敛),再提交同一组 changes;变更已记录为 changeRequest,不会丢失。',
3043
+ running: true,
3044
+ changeRequest: record.changeRequest ?? null,
3045
+ };
3046
+ }
3047
+ const revision = revisionNow + 1;
3048
+ const at = Date.now();
3049
+ const result = planReplan(record.plan, args?.changes, {
3050
+ planId,
3051
+ reason: args?.reason,
3052
+ revision,
3053
+ at,
3054
+ });
3055
+ if (!result.ok)
3056
+ return { ...base, code: result.code, error: result.error };
3057
+ /*
3058
+ * 先落 durable 记录,再改内存:写失败时计划保持原样,不会出现
3059
+ * 「内存里已经改了、刷新后又退回去」的分叉。
3060
+ */
3061
+ try {
3062
+ session.append('user/message', buildReplanMessage(result.payload), { surfaceOp: 'append' });
3063
+ }
3064
+ catch (error) {
3065
+ return {
3066
+ ...base,
3067
+ code: 'REPLAN_WRITE_FAILED',
3068
+ error: `写入重规划记录失败:${error instanceof Error ? error.message : String(error)}`,
3069
+ hint: '计划未被改动;修复会话写入问题后重试同一组 changes。',
3070
+ };
3071
+ }
3072
+ record.plan = result.payload.plan;
3073
+ record.planRevision = revision;
3074
+ record.statuses = applyReplanStatuses(record.statuses, result.payload);
3075
+ record.phase = planPhase(record.statuses);
3076
+ record.error = null;
3077
+ record.updatedAt = at;
3078
+ if (record.changeRequest && record.changeRequest.status !== 'replanned') {
3079
+ record.changeRequest = {
3080
+ ...record.changeRequest,
3081
+ status: 'replanned',
3082
+ replannedAt: at,
3083
+ planRevision: revision,
3084
+ };
3085
+ }
3086
+ state.records.set(session.id, record);
3087
+ const snapshot = derivePlanSnapshot(record.statuses, definedSubtaskCount(record.plan));
3088
+ return {
3089
+ ok: true,
3090
+ planId,
3091
+ planRevision: revision,
3092
+ reason: result.payload.reason,
3093
+ marks: result.payload.marks,
3094
+ added: result.payload.added,
3095
+ phase: record.phase,
3096
+ stats: snapshot.stats,
3097
+ statuses: modelStatusLines(snapshot.statuses),
3098
+ hint: '旧行保留为 closure=replanned(可追溯、不计入剩余项、不再调度);修订后的新行是 pending,调用 dsh_workplan_dispatch 才会执行。',
3099
+ };
3100
+ }
2287
3101
  async function cancelPlan(agent, args) {
2288
3102
  const session = agent?.session;
2289
3103
  if (!session)
@@ -2336,6 +3150,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2336
3150
  const reason = typeof args?.reason === 'string' && args.reason.trim()
2337
3151
  ? args.reason.trim()
2338
3152
  : '用户取消';
3153
+ // [1.10.4] 取消是终态:必须撤销已排期的自动续跑,否则定时器会在取消之后复活计划。
3154
+ clearAutoResumeTimer(record, 'cancelled');
2339
3155
  /*
2340
3156
  * [1.5.2] 已完成即终态:取消不再把 100% 的计划改写成「已取消」。
2341
3157
  *
@@ -2468,21 +3284,291 @@ export function createWorkplanRuntime(ctx, options = {}) {
2468
3284
  stats: derivePlanSnapshot(record.statuses).stats,
2469
3285
  };
2470
3286
  }
2471
- /**
2472
- * Persist the round result and settle the phase.
3287
+ /*
3288
+ * [1.10.4][auto-resume] 自动续跑的记账与排期。
2473
3289
  *
2474
- * Extracted from the wait path so an async dispatch reaches exactly the same
2475
- * end state: a durable result message plus a reconciled phase. Anything less
2476
- * would make "start now, read later" a second, divergent code path.
3290
+ * 为什么在工具层而不是 `dispatchPlan` 里:被整轮预算中止时,这一轮已经没有
3291
+ * 预算可用,轮内重试必然再被同一把闸刀砍掉(`shouldRetryAttempt` 对
3292
+ * `TOTAL_TIMEOUT` / `ABORTED` 恒为 false 是正确的)。能重试的只有「下一轮」:
3293
+ * 新预算、新截止时间,未完成项由 `resetBlockedStatuses` 放回 pending,
3294
+ * done 项永不重跑。所以调度点属于「谁结束了一轮」,也就是这里。
3295
+ *
3296
+ * 所有停止分支都由纯函数 `decideAutoResume` 判定,本层只负责:
3297
+ * - 记录 done 水位与连续无进展轮数(防止空转);
3298
+ * - 用 unref 的定时器排期,并在取消/人工派发/进程销毁时撤销;
3299
+ * - 起跑前再核对一次记录身份与阶段(定时器期间状态可能已变)。
2477
3300
  */
2478
- function finishRound(record, session) {
2479
- if (!record.resultWritten) {
3301
+ function autoResumeBook(record) {
3302
+ if (!record.autoResume || typeof record.autoResume !== 'object') {
3303
+ record.autoResume = {
3304
+ attempt: 0,
3305
+ noProgressRounds: 0,
3306
+ doneBefore: null,
3307
+ nextAt: null,
3308
+ timer: null,
3309
+ lastDecision: null,
3310
+ history: [],
3311
+ };
3312
+ }
3313
+ return record.autoResume;
3314
+ }
3315
+ function clearAutoResumeTimer(record, reason) {
3316
+ const book = record?.autoResume;
3317
+ if (!book)
3318
+ return false;
3319
+ book.nextAt = null;
3320
+ if (!book.timer)
3321
+ return false;
3322
+ clearTimeout(book.timer);
3323
+ book.timer = null;
3324
+ book.lastStopReason = reason;
3325
+ return true;
3326
+ }
3327
+ function autoResumeView(record) {
3328
+ const book = record?.autoResume;
3329
+ return {
3330
+ enabled: limits.autoResume.enabled,
3331
+ attempt: Number(book?.attempt ?? 0),
3332
+ maxAttempts: limits.autoResume.maxAttempts,
3333
+ armed: Boolean(book?.timer),
3334
+ nextInMs: book?.nextAt ? Math.max(0, Number(book.nextAt) - Date.now()) : null,
3335
+ lastCode: book?.lastDecision?.code ?? null,
3336
+ lastReason: book?.lastDecision?.reason ?? null,
3337
+ lastStopReason: book?.lastStopReason ?? null,
3338
+ };
3339
+ }
3340
+ /**
3341
+ * 在一轮结束后决定是否再开一轮。
3342
+ *
3343
+ * @param record - 当前计划记录。
3344
+ * @param session - 根会话(结果消息与子 Agent 都归属它)。
3345
+ * @param base - 本轮派发的可复用参数(agent / modelSelection / cwd / conversationContext)。
3346
+ */
3347
+ function armAutoResume(record, session, base) {
3348
+ const book = autoResumeBook(record);
3349
+ clearAutoResumeTimer(record, 'rearmed');
3350
+ const snapshot = derivePlanSnapshot(record.statuses);
3351
+ const stats = snapshot.stats ?? {};
3352
+ const statuses = Array.isArray(record.statuses) ? record.statuses : [];
3353
+ const done = Number(stats.done ?? 0);
3354
+ const doneBefore = Number.isFinite(Number(book.doneBefore)) ? Number(book.doneBefore) : done;
3355
+ /*
3356
+ * 「有进展」只认新增的 done 行。被预算中止的子任务会把 error 从 pending
3357
+ * 一路写到重置,只有真正完成才会抬高 done;用 done 作水位既不会把
3358
+ * 「重跑一次又失败」误判成进展,也不会因错误文案变化而空转。
3359
+ */
3360
+ if (done > doneBefore)
3361
+ book.noProgressRounds = 0;
3362
+ else if (Number(book.attempt ?? 0) > 0)
3363
+ book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1;
3364
+ book.doneBefore = done;
3365
+ const pending = statuses.filter((item) => item?.status === 'pending').length;
3366
+ const blocked = statuses.filter((item) => item?.status === 'blocked').length;
3367
+ /*
3368
+ * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
3369
+ *
3370
+ * T7 实测:`armAutoResume` 在每一轮结束后都会被调用,正常完成的轮也会走到
3371
+ * `PHASE_NOT_PAUSED` 分支,于是每个顺利结束的计划都在 `record.errors` 里多一条
3372
+ * 「[auto-resume] 停止」——把真正需要看的中止信息埋掉。全部 done 且没有
3373
+ * pending/blocked 时,直接静默收尾,不写台账。
3374
+ */
3375
+ if (Number(stats.total ?? 0) > 0 && pending === 0 && blocked === 0 && done === Number(stats.total ?? 0)) {
3376
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code: 'NOTHING_PENDING', reason: '全部子任务已 done,无需自动续跑' };
3377
+ return book.lastDecision;
3378
+ }
3379
+ const decision = decideAutoResume({
3380
+ enabled: limits.autoResume.enabled,
3381
+ phase: record.phase,
3382
+ cancelled: record.cancelled === true,
3383
+ degraded: record.degraded === true,
3384
+ planMode: isPlanModeActive(ctx, session),
3385
+ running: Boolean(record.dispatchPromise),
3386
+ total: Number(stats.total ?? 0),
3387
+ done,
3388
+ pending,
3389
+ blocked,
3390
+ attempt: Number(book.attempt ?? 0),
3391
+ maxAttempts: limits.autoResume.maxAttempts,
3392
+ noProgressRounds: Number(book.noProgressRounds ?? 0),
3393
+ stallLimit: AUTO_RESUME_DEFAULTS.stallLimit,
3394
+ baseDelayMs: AUTO_RESUME_DEFAULTS.baseDelayMs,
3395
+ maxDelayMs: AUTO_RESUME_DEFAULTS.maxDelayMs,
3396
+ });
3397
+ book.lastDecision = { at: Date.now(), phase: record.phase, ...decision };
3398
+ book.history = [...(book.history ?? []), {
3399
+ at: Date.now(),
3400
+ phase: record.phase,
3401
+ done,
3402
+ pending,
3403
+ blocked,
3404
+ attempt: Number(book.attempt ?? 0),
3405
+ action: decision.action,
3406
+ code: decision.code,
3407
+ }].slice(-10);
3408
+ if (decision.action !== 'schedule') {
3409
+ /*
3410
+ * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
3411
+ * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
3412
+ */
3413
+ if (decision.code !== 'AUTO_RESUME_DISABLED') {
3414
+ record.errors = [...(record.errors ?? []),
3415
+ `[auto-resume] 停止(${decision.code}):${decision.reason}`].slice(-20);
3416
+ }
3417
+ return decision;
3418
+ }
3419
+ const attempt = Number(book.attempt ?? 0) + 1;
3420
+ book.attempt = attempt;
3421
+ book.nextAt = Date.now() + decision.delayMs;
3422
+ record.errors = [...(record.errors ?? []),
3423
+ `[auto-resume] 已排期第 ${attempt}/${limits.autoResume.maxAttempts} 次自动续跑:`
3424
+ + `${Math.round(decision.delayMs / 1000)}s 后开始(本轮预算到点,仍有 ${pending} 项 pending;done 项不重跑)`].slice(-20);
3425
+ const timer = setTimeout(() => {
3426
+ book.timer = null;
3427
+ book.nextAt = null;
3428
+ try {
3429
+ /*
3430
+ * 排期到点后逐项复核,任何一项不成立都安静退出:定时器活过了一个
3431
+ * 回合,期间用户可能已经取消、主 Agent 可能已经手动派发、页面可能
3432
+ * 已经换了一份计划记录。
3433
+ */
3434
+ /*
3435
+ * [1.10.4 / D1] 复核失败必须留下停止码。
3436
+ *
3437
+ * T5 的 I9:任何一次「本应自动续跑却没有发生」都要可解释。原先这里五个
3438
+ * 分支全是裸 `return`,计划停在 paused 而台账里没有任何痕迹,用户只能再
3439
+ * 做一次考古。现在每个分支都写 `lastStopReason`,并把原因追加到 history。
3440
+ */
3441
+ const stopTimer = (code) => {
3442
+ book.lastStopReason = code;
3443
+ book.lastDecision = { at: Date.now(), phase: record.phase, action: 'stop', code, reason: '定时器复核未通过' };
3444
+ book.history = [...(book.history ?? []), {
3445
+ at: Date.now(), phase: record.phase, action: 'stop', code,
3446
+ }].slice(-10);
3447
+ return;
3448
+ };
3449
+ if (state.records.get(session.id) !== record)
3450
+ return stopTimer('SCHEDULE_REVOKED_RECORD_REPLACED');
3451
+ if (record.dispatchPromise)
3452
+ return stopTimer('SCHEDULE_REVOKED_ALREADY_RUNNING');
3453
+ if (record.cancelled === true)
3454
+ return stopTimer('CANCELLED');
3455
+ if (isTerminalPhase(record.phase))
3456
+ return stopTimer('PHASE_TERMINAL');
3457
+ if (isPlanModeActive(ctx, session))
3458
+ return stopTimer('PLAN_MODE');
3459
+ if (record.phase !== 'paused')
3460
+ return stopTimer('PHASE_NOT_PAUSED');
3461
+ const live = derivePlanSnapshot(record.statuses);
3462
+ const livePending = (record.statuses ?? []).filter((item) => item?.status === 'pending').length;
3463
+ if (Number(live.stats?.total ?? 0) === 0 || livePending === 0)
3464
+ return stopTimer('NOTHING_PENDING');
3465
+ const controller = new AbortController();
3466
+ record.abortRequested = false;
3467
+ record.abortDispatch = (reason) => {
3468
+ if (!controller.signal.aborted)
3469
+ controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'));
3470
+ };
3471
+ record.dispatchStartedAt = Date.now();
3472
+ // 新一轮必须写一条新的结果消息,否则主 Agent 永远看不到自动续跑的结局。
3473
+ record.resultWritten = false;
3474
+ book.doneBefore = Number(live.stats?.done ?? 0);
3475
+ record.dispatchPromise = dispatchPlan(ctx, record, {
3476
+ ...base,
3477
+ signal: controller.signal,
3478
+ childTimeoutMs: limits.childTimeoutMs,
3479
+ idleTimeoutMs: limits.idleTimeoutMs,
3480
+ totalTimeoutMs: limits.totalTimeoutMs,
3481
+ maxResumes: limits.maxResumes,
3482
+ strictEvidence: options.strictEvidence,
3483
+ })
3484
+ .then(() => finishRound(record, session))
3485
+ .catch((error) => {
3486
+ pushRecordError(record, error);
3487
+ finishRound(record, session);
3488
+ })
3489
+ .finally(() => {
3490
+ record.dispatchPromise = null;
3491
+ record.dispatchStartedAt = null;
3492
+ record.abortDispatch = null;
3493
+ armAutoResume(record, session, base);
3494
+ });
3495
+ ctx.logger?.warn?.(`dsh-workplan: 计划 ${record.plan?.planId ?? '?'} 自动续跑第 ${attempt}/${limits.autoResume.maxAttempts} 轮已开始`
3496
+ + `(remaining ${Number(live.stats?.total ?? 0) - Number(live.stats?.done ?? 0)})`);
3497
+ }
3498
+ catch (error) {
3499
+ pushRecordError(record, error);
3500
+ ctx.logger?.warn?.(`dsh-workplan: 自动续跑失败:${error instanceof Error ? error.message : String(error)}`);
3501
+ }
3502
+ }, decision.delayMs);
3503
+ timer.unref?.();
3504
+ book.timer = timer;
3505
+ return decision;
3506
+ }
3507
+ /**
3508
+ * Persist the round result and settle the phase.
3509
+ *
3510
+ * Extracted from the wait path so an async dispatch reaches exactly the same
3511
+ * end state: a durable result message plus a reconciled phase. Anything less
3512
+ * would make "start now, read later" a second, divergent code path.
3513
+ */
3514
+ /**
3515
+ * [1.11.0] 完成必回报的写入点(T7 C-06;契约 S7 done → S8 reported)。
3516
+ *
3517
+ * 只有在「结果消息确实写进会话」之后才调用:没有证据的“已回报”比不回报
3518
+ * 更危险。写入走 applyStatus(唯一写入口),读到的是同一条状态条目上的
3519
+ * `closure:'reported'` + `report{state,at,ref,turn}`,与左侧栏 chip 同源。
3520
+ * 返回本次新标记的条数;已是 reported 的行不重复写,避免每轮刷新 revision。
3521
+ */
3522
+ function markReported(record, session, ref) {
3523
+ const at = Date.now();
3524
+ const rawTurn = Number(state.activeTurns?.get?.(session?.id) ?? NaN);
3525
+ const turn = Number.isFinite(rawTurn) ? rawTurn : null;
3526
+ let changed = 0;
3527
+ for (const item of Array.isArray(record?.statuses) ? record.statuses : []) {
3528
+ if (item?.status !== 'done')
3529
+ continue;
3530
+ if (item?.closure === 'reported' && item?.report?.state === 'sent')
3531
+ continue;
3532
+ try {
3533
+ record.statuses = applyStatus(record.statuses, item.subtaskId, {
3534
+ closure: 'reported',
3535
+ reportedAt: at,
3536
+ report: { state: 'sent', at, ref, turn },
3537
+ revision: Number(item.revision ?? 0) + 1,
3538
+ updatedBy: 'system',
3539
+ });
3540
+ changed += 1;
3541
+ }
3542
+ catch (error) {
3543
+ ctx.logger?.warn?.(`dsh-workplan: 回报标记失败 ${String(item?.subtaskId)}:${error instanceof Error ? error.message : String(error)}`);
3544
+ record.reportPending = true;
3545
+ }
3546
+ }
3547
+ return changed;
3548
+ }
3549
+ function finishRound(record, session) {
3550
+ const ref = `${record.plan?.planId ?? 'plan'}:${record.dispatchedAt ?? 0}`;
3551
+ if (!record.resultWritten) {
3552
+ /*
3553
+ * [1.11.0] 完成必回报的顺序:先标记 reported,再构建并落盘结果消息。
3554
+ *
3555
+ * 这样结果消息里的 statuses 就带着 `closure:'reported'`,刷新/重启后
3556
+ * 回放得到同一个结论;而“标记了但消息没写成功”会在 catch 里回滚,
3557
+ * 绝不留下没有证据的 reported。
3558
+ */
3559
+ const before = (record.statuses ?? []).map((item) => ({ ...item }));
3560
+ const needReport = before.filter((item) => item?.status === 'done' && item?.closure !== 'reported').length;
3561
+ // ^ 本轮结算:done 且未到 reported 的行(含旧日志的 null)都算待回报。
3562
+ const reported = markReported(record, session, ref);
2480
3563
  const resultMessage = buildRoundResult(record, session.id, limits);
2481
3564
  try {
2482
3565
  session.append('user/message', resultMessage, { surfaceOp: 'append' });
2483
3566
  record.resultWritten = true;
3567
+ record.reportPending = needReport > 0 && reported < needReport;
2484
3568
  }
2485
3569
  catch (error) {
3570
+ // 消息没写成功 ⇒ 回报没有证据:把状态回滚成写之前的快照。
3571
+ record.statuses = before;
2486
3572
  ctx.logger?.warn?.(`dsh-workplan: 写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
2487
3573
  /*
2488
3574
  * [1.8.14] N13: a failed result write is a real, user-visible failure —
@@ -2490,6 +3576,23 @@ export function createWorkplanRuntime(ctx, options = {}) {
2490
3576
  * disagree with the live phase. Log it durably, not only in the host log.
2491
3577
  */
2492
3578
  pushRecordError(record, `写入结果消息失败:${error instanceof Error ? error.message : String(error)}`);
3579
+ /*
3580
+ * [1.11.0] 写失败时不能假装回报过。保留 reportPending,让下一次
3581
+ * pre-step 或下一轮 finishRound 幂等补齐(契约 §7.3 B4)。
3582
+ */
3583
+ record.reportPending = true;
3584
+ }
3585
+ }
3586
+ else {
3587
+ /*
3588
+ * 旧日志 / 上一次写失败的重试:结果消息已在,但仍有 done 行没到
3589
+ * reported。幂等补齐,不重复追加消息。
3590
+ */
3591
+ const pending = (record.statuses ?? []).some((item) => item?.status === 'done' && item?.closure !== 'reported');
3592
+ if (pending) {
3593
+ const changed = markReported(record, session, ref);
3594
+ if (changed > 0)
3595
+ record.reportPending = false;
2493
3596
  }
2494
3597
  }
2495
3598
  /*
@@ -2510,7 +3613,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2510
3613
  * had no field telling it the round ended early. `complete`/`remaining` make
2511
3614
  * that state machine-readable instead of a sentence to interpret.
2512
3615
  */
2513
- function completionFields(snapshot, phase) {
3616
+ function completionFields(snapshot, phase, record) {
2514
3617
  const stats = snapshot?.stats ?? {};
2515
3618
  const total = Number(stats.total ?? 0);
2516
3619
  const done = Number(stats.done ?? 0);
@@ -2523,7 +3626,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
2523
3626
  * model now also sees whether the plan passed the delivery gate, plus the
2524
3627
  * exact gaps.
2525
3628
  */
2526
- const readiness = deliveryReadiness(snapshot, { phase });
3629
+ const readiness = record
3630
+ ? readinessOf(record, snapshot)
3631
+ : deliveryReadiness(snapshot, { phase });
2527
3632
  return {
2528
3633
  complete: total > 0 && done >= total,
2529
3634
  remaining: Math.max(0, total - done),
@@ -2540,7 +3645,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2540
3645
  runtime: runtimeIdentity(),
2541
3646
  planId: record.plan.planId,
2542
3647
  alreadyRunning: false,
2543
- ...completionFields(snapshot, record.phase),
3648
+ ...completionFields(snapshot, record.phase, record),
2544
3649
  ...extra,
2545
3650
  phase: record.phase,
2546
3651
  stats: snapshot.stats,
@@ -2586,7 +3691,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2586
3691
  }
2587
3692
  const running = Boolean(record.dispatchPromise);
2588
3693
  const snapshot = derivePlanSnapshot(record.statuses);
2589
- const readiness = deliveryReadiness(snapshot, { phase: record.phase });
3694
+ const readiness = readinessOf(record, snapshot);
2590
3695
  return {
2591
3696
  ok: true,
2592
3697
  version: pluginVersion,
@@ -2599,6 +3704,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
2599
3704
  statuses: modelStatusLines(snapshot.statuses),
2600
3705
  errors: (record.errors ?? []).slice(-10),
2601
3706
  resumeLimit: Number(record.resumeLimit ?? limits.maxResumes),
3707
+ // [1.10.4] 自动续跑的可观测面:开关、已用轮次、是否已排期、上一次判定码。
3708
+ autoResume: autoResumeView(record),
2602
3709
  deliveryReady: readiness.ready,
2603
3710
  deliveryBlockers: readiness.blockers.slice(0, 12),
2604
3711
  deliveryRemaining: readiness.remaining.slice(0, 20),
@@ -2673,6 +3780,518 @@ export function createWorkplanRuntime(ctx, options = {}) {
2673
3780
  };
2674
3781
  }
2675
3782
  }
3783
+ /**
3784
+ * [1.11.0] 子 → 父的唯一反向通道(T4 C-09 / T6 M5)。
3785
+ *
3786
+ * 子会话只知道自己的 `session.id` 和父会话 id。这里用父链 + `childId` 反查
3787
+ * 子任务,而不是相信子 Agent 自报的 subtaskId:自报值可以写错,父链不会。
3788
+ * 写入仍是 `applyStatus`(唯一写入口),并同步落一条 durable update,刷新后
3789
+ * 「有一条请示在等指示」不会退回 pending。
3790
+ */
3791
+ async function escalateSubtask(agent, args) {
3792
+ const childSession = agent?.session;
3793
+ if (!childSession?.id) {
3794
+ return { ok: false, code: 'NO_SESSION', error: '只能在子会话内上报遇阻' };
3795
+ }
3796
+ const parentId = childSession.header?.parentSession;
3797
+ if (!parentId) {
3798
+ return {
3799
+ ok: false,
3800
+ code: 'NOT_CHILD_SESSION',
3801
+ error: '当前不是子会话,无法反查父计划;请直接在结果块写 status=blocked + question',
3802
+ };
3803
+ }
3804
+ let record = state.records.get(parentId);
3805
+ if (!record?.plan) {
3806
+ const parent = ctx.sessions?.get?.(parentId);
3807
+ if (parent) {
3808
+ try {
3809
+ record = reconstructFromSession(parent);
3810
+ }
3811
+ catch (error) {
3812
+ pushRecordError({ errors: [] }, error);
3813
+ }
3814
+ }
3815
+ }
3816
+ if (!record?.plan) {
3817
+ return {
3818
+ ok: false,
3819
+ code: 'NO_PLAN',
3820
+ error: '父会话没有可关联的计划;请在结果块写 status=blocked + question,由主 Agent 处理',
3821
+ };
3822
+ }
3823
+ const row = (record.statuses ?? []).find((item) => item?.childId === childSession.id);
3824
+ if (!row) {
3825
+ return {
3826
+ ok: false,
3827
+ code: 'NO_SUBTASK',
3828
+ error: '计划里找不到与本子会话关联的子任务(childId 未登记);请在结果块写 status=blocked + question',
3829
+ };
3830
+ }
3831
+ if (row.status === 'done') {
3832
+ return { ok: false, code: 'ALREADY_DONE', subtaskId: row.subtaskId, error: '该子任务已标记完成,不能再提交请示' };
3833
+ }
3834
+ const question = truncate(String(args?.question ?? '').trim(), MAX_QUESTION_CHARS);
3835
+ if (!question) {
3836
+ return { ok: false, code: 'INVALID_QUESTION', subtaskId: row.subtaskId, error: 'question 必填:写清需要主 Agent 决定的单个问题' };
3837
+ }
3838
+ if (row.closure === 'escalated') {
3839
+ return {
3840
+ ok: true,
3841
+ alreadyEscalated: true,
3842
+ planId: record.plan.planId,
3843
+ subtaskId: row.subtaskId,
3844
+ status: 'blocked',
3845
+ closure: 'escalated',
3846
+ question: row.question ?? question,
3847
+ message: '这条请示已经在上报队列里,不要重复提交;停止推进,等待主 Agent 指示。',
3848
+ };
3849
+ }
3850
+ const options = (Array.isArray(args?.options) ? args.options : [])
3851
+ .slice(0, MAX_ESCALATION_OPTIONS)
3852
+ .map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
3853
+ .filter(Boolean);
3854
+ const needs = (Array.isArray(args?.needs) ? args.needs : [])
3855
+ .slice(0, 10)
3856
+ .map((item) => truncate(typeof item === 'string' ? item : String(item ?? ''), 300))
3857
+ .filter(Boolean);
3858
+ const now = Date.now();
3859
+ const revision = Number(row.revision ?? 0) + 1;
3860
+ record.statuses = applyStatus(record.statuses, row.subtaskId, {
3861
+ status: 'blocked',
3862
+ closure: 'escalated',
3863
+ blockedKind: 'escalated',
3864
+ question,
3865
+ options,
3866
+ needs: [...(Array.isArray(row.needs) ? row.needs : []), ...needs],
3867
+ progress: 100,
3868
+ finishedAt: now,
3869
+ error: question,
3870
+ summary: `待指示:${question}`,
3871
+ escalatedAt: now,
3872
+ escalationSeq: revision,
3873
+ revision,
3874
+ updatedBy: 'child',
3875
+ });
3876
+ record.updatedAt = now;
3877
+ try {
3878
+ const parent = ctx.sessions?.get?.(parentId);
3879
+ const written = record.statuses.find((item) => item?.subtaskId === row.subtaskId);
3880
+ parent?.append?.('user/message', buildUpdateMessage({
3881
+ planId: record.plan.planId,
3882
+ subtaskId: row.subtaskId,
3883
+ status: 'blocked',
3884
+ closure: 'escalated',
3885
+ blockedKind: 'escalated',
3886
+ question,
3887
+ options,
3888
+ needs: written?.needs,
3889
+ escalatedAt: now,
3890
+ escalationSeq: revision,
3891
+ revision,
3892
+ }), { surfaceOp: 'append' });
3893
+ }
3894
+ catch (error) {
3895
+ pushRecordError(record, error);
3896
+ }
3897
+ return {
3898
+ ok: true,
3899
+ planId: record.plan.planId,
3900
+ subtaskId: row.subtaskId,
3901
+ status: 'blocked',
3902
+ closure: 'escalated',
3903
+ question,
3904
+ revision,
3905
+ message: '已上报主 Agent。请立即停止推进,只允许做只读核对;等待指示期间不要开始新的写入或大改。',
3906
+ };
3907
+ }
3908
+ /**
3909
+ * [1.11.0] 指示回执(T4 B5 / M6,T10 N4)。
3910
+ *
3911
+ * 指示投递成功只证明消息进了收件箱,不证明子会话真的开始执行。三个观察点
3912
+ * 都以「该行仍是 instructed 且 instructionSeq 未变」为前提:
3913
+ * - 轮询:子会话 seq 增长 = 已开始执行 → 写 acknowledged(唯一正向回执);
3914
+ * - 60s:仍无增长 → 写 `instructionOverdue`(界面显示、主 Agent 可催);
3915
+ * - 180s:仍无增长 → 收束为 blocked/no-ack(不再无限等待)。
3916
+ * 主 Agent 再次改判或子会话产出结果都会让这三个观察点自然作废。
3917
+ */
3918
+ function scheduleInstructionAck(record, subtaskId, childId, revision) {
3919
+ const rowOf = () => record.statuses.find((item) => item?.subtaskId === subtaskId);
3920
+ const readSeq = () => {
3921
+ try {
3922
+ const seq = Number(ctx.sessions?.get?.(childId)?.seq);
3923
+ return Number.isFinite(seq) ? seq : undefined;
3924
+ }
3925
+ catch {
3926
+ return undefined;
3927
+ }
3928
+ };
3929
+ const baseline = readSeq();
3930
+ let stopped = false;
3931
+ const timers = [];
3932
+ const stop = () => {
3933
+ if (stopped)
3934
+ return;
3935
+ stopped = true;
3936
+ for (const timer of timers) {
3937
+ clearTimeout(timer);
3938
+ clearInterval(timer);
3939
+ }
3940
+ };
3941
+ const sameAttempt = (row) => {
3942
+ if (stopped)
3943
+ return false;
3944
+ if (!row || row.closure !== 'instructed')
3945
+ return false;
3946
+ return Number(row.instructionSeq ?? 0) === Number(revision);
3947
+ };
3948
+ const unchanged = (row) => {
3949
+ if (!sameAttempt(row))
3950
+ return false;
3951
+ const seq = readSeq();
3952
+ if (seq === undefined || baseline === undefined)
3953
+ return true;
3954
+ return seq <= baseline;
3955
+ };
3956
+ /*
3957
+ * 正向回执:没有这一步时,一个正常工作但耗时较长的子会话会在 180s 被
3958
+ * 误判成 no-ack 并阻断,而它其实早就在产出事件了。
3959
+ */
3960
+ const poll = setInterval(() => {
3961
+ const row = rowOf();
3962
+ if (!sameAttempt(row)) {
3963
+ stop();
3964
+ return;
3965
+ }
3966
+ const seq = readSeq();
3967
+ if (seq === undefined || baseline === undefined || seq <= baseline)
3968
+ return;
3969
+ try {
3970
+ writeSubtaskStatus(record, subtaskId, {
3971
+ closure: 'acknowledged',
3972
+ ackedAt: Date.now(),
3973
+ ackEvidence: { seq, elapsedMs: Date.now() - Number(row.instruction?.at ?? Date.now()) },
3974
+ instructionOverdue: false,
3975
+ progress: Math.max(Number(row.progress ?? 0), 15),
3976
+ }, { timedOut: false });
3977
+ }
3978
+ catch {
3979
+ // Row moved on between read and write; the next tick re-evaluates.
3980
+ return;
3981
+ }
3982
+ stop();
3983
+ }, INSTRUCTION_POLL_MS);
3984
+ poll.unref?.();
3985
+ timers.push(poll);
3986
+ const notice = setTimeout(() => {
3987
+ if (!unchanged(rowOf()))
3988
+ return;
3989
+ try {
3990
+ writeSubtaskStatus(record, subtaskId, { instructionOverdue: true }, { timedOut: false });
3991
+ }
3992
+ catch {
3993
+ // The row moved on between the read and the write; nothing to report.
3994
+ }
3995
+ }, INSTRUCTION_ACK_NOTICE_MS);
3996
+ notice.unref?.();
3997
+ timers.push(notice);
3998
+ const deadline = setTimeout(() => {
3999
+ if (!unchanged(rowOf())) {
4000
+ stop();
4001
+ return;
4002
+ }
4003
+ const seconds = Math.round(INSTRUCTION_ACK_DEADLINE_MS / 1000);
4004
+ const message = `指示下发后 ${seconds}s 子会话仍无任何新事件(no-ack):指示没有被执行`;
4005
+ try {
4006
+ writeSubtaskStatus(record, subtaskId, {
4007
+ status: 'blocked',
4008
+ closure: 'blocked',
4009
+ blockedKind: 'no-ack',
4010
+ progress: 100,
4011
+ finishedAt: Date.now(),
4012
+ instructionOverdue: true,
4013
+ error: message,
4014
+ summary: `未完成:${message}`,
4015
+ }, { timedOut: false });
4016
+ recordSubtaskError(record, subtaskId, message, { timedOut: false });
4017
+ }
4018
+ catch {
4019
+ // Same race as above: the row already left instructed.
4020
+ }
4021
+ stop();
4022
+ }, INSTRUCTION_ACK_DEADLINE_MS);
4023
+ deadline.unref?.();
4024
+ timers.push(deadline);
4025
+ }
4026
+ /**
4027
+ * [1.11.0] 主 → 子下发指示(T4 C-10 / T6 M6)。
4028
+ *
4029
+ * 只有根会话能调用;只接受 `closure:'escalated'` 的行;只投递给本会话直接
4030
+ * 子会话。投递失败时不改状态(不伪造成「已指示」),把错误原样交给主 Agent。
4031
+ */
4032
+ async function instructSubtask(agent, args, signal, existingRecord) {
4033
+ const session = agent?.session;
4034
+ if (!session)
4035
+ return { ok: false, code: 'NO_SESSION', error: '只能在会话内下发指示' };
4036
+ if (!isRootSession(session))
4037
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以下发指示' };
4038
+ let record = existingRecord ?? state.records.get(session.id);
4039
+ if (!record?.plan)
4040
+ record = reconstructFromSession(session, args?.planId);
4041
+ record = adoptRequestedPlan(session, record, args?.planId);
4042
+ if (!record?.plan)
4043
+ return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' };
4044
+ clearAutoResumeTimer(record, 'manual-instruct');
4045
+ const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : '';
4046
+ if (!subtaskId)
4047
+ return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' };
4048
+ const current = record.statuses.find((item) => item?.subtaskId === subtaskId);
4049
+ if (!current)
4050
+ return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` };
4051
+ if (current.closure !== 'escalated') {
4052
+ return {
4053
+ ok: false,
4054
+ code: 'NOT_ESCALATED',
4055
+ subtaskId,
4056
+ error: '该子任务不在待指示状态;普通受阻请用 dsh_workplan_update 改判',
4057
+ };
4058
+ }
4059
+ const instruction = truncate(String(args?.instruction ?? args?.text ?? '').trim(), MAX_INSTRUCTION_CHARS);
4060
+ if (!instruction)
4061
+ return { ok: false, code: 'INVALID_INSTRUCTION', subtaskId, error: 'instruction 必填:写清要子 Agent 执行的决定' };
4062
+ const childId = typeof current.childId === 'string' ? current.childId : '';
4063
+ if (!childId)
4064
+ return { ok: false, code: 'NO_CHILD', subtaskId, error: '该行没有关联子会话,无法投递指示' };
4065
+ if (!spawnedChildIds(session).has(childId)) {
4066
+ return { ok: false, code: 'NOT_DIRECT_CHILD', subtaskId, error: `${childId} 不是本会话的直接子会话,拒绝投递` };
4067
+ }
4068
+ const service = ctx.subagents;
4069
+ if (!service || typeof service.sendMessage !== 'function') {
4070
+ return { ok: false, code: 'NO_SUBAGENT_SERVICE', subtaskId, error: '当前部署没有可用的 subagent 服务,无法投递指示' };
4071
+ }
4072
+ let messageId = '';
4073
+ try {
4074
+ messageId = String(await service.sendMessage(agent, childId, [{
4075
+ type: 'text',
4076
+ text: [
4077
+ '【主 Agent 指示(对应你此前提交的请示)】',
4078
+ instruction,
4079
+ '',
4080
+ '请按上述指示继续原任务。若仍受阻,先调用 dsh_workplan_escalate 再次上报,然后停止推进等待指示;不要自行猜测未被回答的部分。',
4081
+ ].join('\n'),
4082
+ }], { signal }) ?? '');
4083
+ }
4084
+ catch (error) {
4085
+ return {
4086
+ ok: false,
4087
+ code: 'DELIVERY_FAILED',
4088
+ subtaskId,
4089
+ error: truncate(error instanceof Error ? error.message : String(error), 500),
4090
+ hint: '状态未改变,该行仍是待指示;可重试,或用 dsh_workplan_followup 直接投递同一段指示。',
4091
+ };
4092
+ }
4093
+ const now = Date.now();
4094
+ const revision = Number(current.revision ?? 0) + 1;
4095
+ record.statuses = applyStatus(record.statuses, subtaskId, {
4096
+ status: 'in_progress',
4097
+ closure: 'instructed',
4098
+ instruction: { text: instruction, at: now, by: 'agent', messageId, delivery: 'sent' },
4099
+ instructionSeq: revision,
4100
+ progress: Math.max(Number(current.progress ?? 0), 15),
4101
+ finishedAt: null,
4102
+ error: null,
4103
+ question: null,
4104
+ options: [],
4105
+ blockedKind: null,
4106
+ ackOverdue: false,
4107
+ ackedAt: null,
4108
+ ackEvidence: undefined,
4109
+ revision,
4110
+ updatedBy: 'agent',
4111
+ });
4112
+ /*
4113
+ * [1.11.0] 指示会解除「受阻」(T10 N3)。
4114
+ *
4115
+ * 行从 blocked/escalated 变成 in_progress/instructed 后,缓存的
4116
+ * `record.phase` 仍是 blocked;`reconcilePhase` 现在允许 blocked 在有
4117
+ * 活跃行时让位给 executing,这里必须重新对账,否则卡片继续显示
4118
+ * 「卡住了」,与事实相反。
4119
+ */
4120
+ record.phase = reconcilePhase(record.phase, record.statuses);
4121
+ record.updatedAt = now;
4122
+ try {
4123
+ const written = record.statuses.find((item) => item?.subtaskId === subtaskId);
4124
+ session.append('user/message', buildUpdateMessage({
4125
+ planId: record.plan.planId,
4126
+ subtaskId,
4127
+ status: 'in_progress',
4128
+ closure: 'instructed',
4129
+ instruction: written?.instruction,
4130
+ instructionSeq: revision,
4131
+ revision,
4132
+ }), { surfaceOp: 'append' });
4133
+ }
4134
+ catch (error) {
4135
+ pushRecordError(record, error);
4136
+ }
4137
+ scheduleInstructionAck(record, subtaskId, childId, revision);
4138
+ const snapshot = derivePlanSnapshot(record.statuses);
4139
+ const readiness = readinessOf(record, snapshot);
4140
+ return {
4141
+ ok: true,
4142
+ planId: record.plan.planId,
4143
+ subtaskId,
4144
+ status: 'in_progress',
4145
+ closure: 'instructed',
4146
+ revision,
4147
+ messageId,
4148
+ stats: snapshot.stats,
4149
+ deliveryReady: readiness.ready,
4150
+ hint: '指示已投递,该行已变为「已收到指示」。子 Agent 会开启新一轮;完成前仍不得交付。',
4151
+ };
4152
+ }
4153
+ /**
4154
+ * [1.11.0] 工具层入口:子会话的遇阻上报(T4 C-09 / T6 M5)。
4155
+ *
4156
+ * 单独一层包装而不是让 host 直接调内部函数:`escalateSubtask` 需要
4157
+ * `record`/`ctx` 闭包,host 侧只拿得到 runtime 的公开面;这一层也是
4158
+ * 唯一被 `dsh_workplan_escalate` 触发的地方,便于测试替身注入。
4159
+ */
4160
+ async function escalateTool(agent, args) {
4161
+ return escalateSubtask(agent, args);
4162
+ }
4163
+ /**
4164
+ * [1.11.0] 工具层入口:主 Agent 下发指示(T4 C-10 / T6 M6)。
4165
+ *
4166
+ * 前置校验(根会话、escalated、直接子会话、非空 instruction)全部在
4167
+ * `instructSubtask` 里,这一层只转发 —— 校验留在唯一实现处,两个入口
4168
+ * (工具与 `dsh_workplan_update` 的 instruction 字段)才不会分叉。
4169
+ */
4170
+ async function instructTool(agent, args, signal) {
4171
+ return instructSubtask(agent, args, signal);
4172
+ }
4173
+ /**
4174
+ * [1.11.0] 跨部门需求的唯一处置入口(用户 m00687)。
4175
+ *
4176
+ * 子 Agent 只能「提出」需求(needs → open handoff),不能宣称需求已解决;
4177
+ * 只有根会话的主 Agent 能把一条需求指派给部门(routed)、写入书面答复
4178
+ * (answered)或判定无需动作(closed)。处置结果写回同一条状态行并追加
4179
+ * 一条可回放的人工改判消息,刷新后仍然有效。
4180
+ */
4181
+ async function handoffTool(agent, args, signal) {
4182
+ const session = agent?.session;
4183
+ if (!session)
4184
+ return { ok: false, code: 'NO_SESSION', error: '只能在会话内处置跨部门需求' };
4185
+ if (!isRootSession(session))
4186
+ return { ok: false, code: 'NOT_ROOT', error: '只有根会话可以处置跨部门需求' };
4187
+ let record = state.records.get(session.id);
4188
+ if (!record?.plan)
4189
+ record = reconstructFromSession(session, args?.planId);
4190
+ record = adoptRequestedPlan(session, record, args?.planId);
4191
+ if (!record?.plan)
4192
+ return { ok: false, code: 'NO_PLAN', error: '当前会话还没有已生成的计划' };
4193
+ const action = ['list', 'assign', 'resolve', 'close'].includes(args?.action) ? args.action : '';
4194
+ if (!action)
4195
+ return { ok: false, code: 'INVALID_ACTION', error: 'action 必须是 list / assign / resolve / close' };
4196
+ if (action === 'list') {
4197
+ const rows = (record.statuses ?? []).flatMap((row) => openHandoffs(row).map((handoff) => ({
4198
+ subtaskId: row.subtaskId,
4199
+ id: handoff.id,
4200
+ department: handoff.department,
4201
+ status: handoff.status,
4202
+ request: handoff.request,
4203
+ })));
4204
+ return { ok: true, planId: record.plan.planId, handoffs: rows, count: rows.length };
4205
+ }
4206
+ const subtaskId = typeof args?.subtaskId === 'string' ? args.subtaskId.trim() : '';
4207
+ if (!subtaskId)
4208
+ return { ok: false, code: 'MISSING_SUBTASK', error: '缺少 subtaskId' };
4209
+ const row = record.statuses.find((item) => item?.subtaskId === subtaskId);
4210
+ if (!row)
4211
+ return { ok: false, code: 'UNKNOWN_SUBTASK', subtaskId, error: `未知子任务:${subtaskId}` };
4212
+ const handoffs = normaliseHandoffs(row.handoffs);
4213
+ const wanted = typeof args?.handoffId === 'string' ? args.handoffId.trim() : '';
4214
+ const index = wanted
4215
+ ? handoffs.findIndex((item) => item.id === wanted)
4216
+ : handoffs.findIndex((item) => item.status === 'open' || item.status === 'routed');
4217
+ if (index < 0) {
4218
+ return {
4219
+ ok: false,
4220
+ code: wanted ? 'UNKNOWN_HANDOFF' : 'NO_OPEN_HANDOFF',
4221
+ subtaskId,
4222
+ error: wanted ? `未知跨部门需求:${wanted}` : '该行没有待处理的跨部门需求',
4223
+ };
4224
+ }
4225
+ const handoff = handoffs[index];
4226
+ if (action === 'assign') {
4227
+ const department = typeof args?.department === 'string' ? args.department.trim() : '';
4228
+ if (!DEPARTMENTS[department]) {
4229
+ return { ok: false, code: 'INVALID_DEPARTMENT', error: `department 必须是 ${DEPARTMENT_IDS.join(' / ')} 之一` };
4230
+ }
4231
+ handoffs[index] = { ...handoff, department, status: 'routed', updatedAt: Date.now(), by: 'agent' };
4232
+ }
4233
+ else if (action === 'resolve') {
4234
+ const response = truncate(String(args?.response ?? '').trim(), MAX_HANDOFF_RESPONSE_CHARS);
4235
+ if (!response)
4236
+ return { ok: false, code: 'INVALID_RESPONSE', error: 'resolve 必须写清答复或已由哪项产物满足该需求' };
4237
+ handoffs[index] = { ...handoff, status: 'answered', response, updatedAt: Date.now(), by: 'agent' };
4238
+ }
4239
+ else {
4240
+ handoffs[index] = { ...handoff, status: 'closed', response: handoff.response ?? null, updatedAt: Date.now(), by: 'agent' };
4241
+ }
4242
+ const revision = Number(row.revision ?? 0) + 1;
4243
+ record.statuses = applyStatus(record.statuses, subtaskId, {
4244
+ handoffs,
4245
+ revision,
4246
+ updatedBy: 'agent',
4247
+ });
4248
+ record.updatedAt = Date.now();
4249
+ try {
4250
+ session.append('user/message', buildUpdateMessage({
4251
+ planId: record.plan.planId,
4252
+ subtaskId,
4253
+ status: row.status,
4254
+ handoffs,
4255
+ revision,
4256
+ }), { surfaceOp: 'append' });
4257
+ }
4258
+ catch (error) {
4259
+ pushRecordError(record, error);
4260
+ }
4261
+ /*
4262
+ * [1.11.0] 答复必须真的送到还在等它的子会话(用户 m00687)。
4263
+ *
4264
+ * 如果提出需求的行正处于「待指示」,它此刻停在那里等主 Agent:只把
4265
+ * handoff 写成 answered、不发指示,子会话永远不会继续,需求闭环只闭在
4266
+ * 计划表里。这里复用 instructSubtask 的唯一投递/回执链路(写 instructed、
4267
+ * 60s/180s 回执、下次激活注入),不另造第二条消息通道。
4268
+ * 投递失败不回滚 handoff:答复本身是真的,失败原因如实返回给主 Agent。
4269
+ */
4270
+ let instruction = null;
4271
+ if (action === 'resolve' && row.closure === 'escalated' && handoffs[index]?.response) {
4272
+ const answer = handoffs[index];
4273
+ instruction = await instructSubtask(agent, {
4274
+ planId: record.plan.planId,
4275
+ subtaskId,
4276
+ instruction: `跨部门需求 ${answer.id} 已答复${answer.department ? `(${answer.department})` : ''}:${answer.response}。按此答复继续原任务。`,
4277
+ }, signal);
4278
+ }
4279
+ const finalReadiness = readinessOf(record, derivePlanSnapshot(record.statuses));
4280
+ return {
4281
+ ok: true,
4282
+ planId: record.plan.planId,
4283
+ subtaskId,
4284
+ handoff: record.statuses.find((item) => item?.subtaskId === subtaskId)?.handoffs?.[index] ?? null,
4285
+ deliveryReady: finalReadiness.ready,
4286
+ deliveryBlockers: finalReadiness.blockers,
4287
+ ...(instruction ? { instruction } : {}),
4288
+ hint: action === 'assign'
4289
+ ? '已登记责任部门。插件没有常驻部门代理:这次指派不会自动产生工作,请用 dsh_workplan_replan(action=add) 建一个该部门的子任务,或由你直接完成,再用 action=resolve 写入答复或产物引用;否则交付仍被拦住。'
4290
+ : instruction && instruction.ok !== true
4291
+ ? '答复已记录,但投递到子会话失败:该行仍是待指示,按返回的 instruction.error 重试或改用 dsh_workplan_instruct。'
4292
+ : '已记录处置结果;交付阻塞按最新状态重新计算。',
4293
+ };
4294
+ }
2676
4295
  async function dispatchTool(agent, args, signal) {
2677
4296
  const session = agent?.session;
2678
4297
  if (!session)
@@ -2714,6 +4333,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
2714
4333
  }
2715
4334
  if (!record?.plan)
2716
4335
  throw new PlanError('当前会话没有可派发的计划', 'NO_PLAN');
4336
+ /*
4337
+ * [1.10.4] 人工/工具派发优先于自动续跑:撤销待触发的定时器,并把自动
4338
+ * 轮次计数归零(这一次是外部授权的新起点)。done 水位取当前值,下一轮
4339
+ * 结束后才能正确判断「有没有新增完成项」。
4340
+ */
4341
+ clearAutoResumeTimer(record, 'manual-dispatch');
4342
+ {
4343
+ const book = autoResumeBook(record);
4344
+ book.attempt = 0;
4345
+ book.noProgressRounds = 0;
4346
+ book.doneBefore = Number(derivePlanSnapshot(record.statuses).stats?.done ?? 0);
4347
+ }
2717
4348
  if (args?.planId && record.plan.planId !== args.planId) {
2718
4349
  throw new PlanError('planId 与当前计划不匹配', 'PLAN_ID_MISMATCH');
2719
4350
  }
@@ -2871,16 +4502,24 @@ export function createWorkplanRuntime(ctx, options = {}) {
2871
4502
  dispatchController.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'));
2872
4503
  }
2873
4504
  };
2874
- record.dispatchPromise = dispatchPlan(ctx, record, {
4505
+ const roundOptions = {
2875
4506
  agent,
2876
- signal: dispatchController.signal,
2877
4507
  modelSelection: selection.provider && selection.model ? selection : record.modelSelection,
2878
4508
  cwd: session.header?.cwd ?? options.cwd,
2879
4509
  conversationContext: record.conversationContext ?? '',
4510
+ };
4511
+ record.dispatchPromise = dispatchPlan(ctx, record, {
4512
+ ...roundOptions,
4513
+ signal: dispatchController.signal,
2880
4514
  childTimeoutMs: limits.childTimeoutMs,
2881
4515
  idleTimeoutMs: limits.idleTimeoutMs,
2882
4516
  totalTimeoutMs: limits.totalTimeoutMs,
2883
4517
  maxResumes: limits.maxResumes,
4518
+ /*
4519
+ * [1.11.0] 严格完成是运行时级配置,不是每个调用点各传一份。
4520
+ * 漏传会让 `strictCompletion:false` 的部署读到默认 true,行为无法预期。
4521
+ */
4522
+ strictEvidence: options.strictEvidence,
2884
4523
  }).finally(() => {
2885
4524
  record.dispatchPromise = null;
2886
4525
  record.dispatchStartedAt = null;
@@ -2899,11 +4538,13 @@ export function createWorkplanRuntime(ctx, options = {}) {
2899
4538
  .then(() => {
2900
4539
  finishRound(record, session);
2901
4540
  state.records.set(session.id, record);
4541
+ armAutoResume(record, session, roundOptions);
2902
4542
  })
2903
4543
  .catch((error) => {
2904
4544
  pushRecordError(record, error);
2905
4545
  finishRound(record, session);
2906
4546
  state.records.set(session.id, record);
4547
+ armAutoResume(record, session, roundOptions);
2907
4548
  });
2908
4549
  const live = derivePlanSnapshot(record.statuses);
2909
4550
  return {
@@ -2924,6 +4565,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2924
4565
  }
2925
4566
  await record.dispatchPromise;
2926
4567
  finishRound(record, session);
4568
+ armAutoResume(record, session, roundOptions);
2927
4569
  /*
2928
4570
  * The model's dispatch result reports the same snapshot the dashboard will
2929
4571
  * show. It used to send `record.stats` while the status list below was read
@@ -2962,8 +4604,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
2962
4604
  */
2963
4605
  const STOP_STEER_LIMIT = 2;
2964
4606
  function recordReadiness(record) {
2965
- const snapshot = derivePlanSnapshot(record.statuses);
2966
- return deliveryReadiness(snapshot, { phase: record.phase });
4607
+ return readinessOf(record);
2967
4608
  }
2968
4609
  function stopGateApplies(record, session, turn) {
2969
4610
  if (!record?.plan)
@@ -3234,6 +4875,8 @@ export function createWorkplanRuntime(ctx, options = {}) {
3234
4875
  stats: snapshot.stats,
3235
4876
  statuses: snapshot.statuses,
3236
4877
  attempt: book.count,
4878
+ changePending: record.changeRequest?.status === 'pending',
4879
+ reportPending: record.reportPending === true,
3237
4880
  }), {
3238
4881
  kind: 'workplan-continue',
3239
4882
  form: 'notice',
@@ -3383,7 +5026,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3383
5026
  return presentDenial(PRESENT_DENY_CODES.SUPERSEDED_STALE, `计划 ${planId} 已被取代,但承接计划 ${successorPlanId} 不存在、不是交付对象或已终止:`
3384
5027
  + '覆盖证据失效(SUPERSEDED_STALE)。被取代不等于完成:不得调用 present,不得声称“已完成/最终版/已交付”。');
3385
5028
  }
3386
- const readiness = deliveryReadiness(derivePlanSnapshot(successor.statuses), { phase: successor.phase });
5029
+ const readiness = readinessOf(successor);
3387
5030
  if (!readiness.ready) {
3388
5031
  const ids = readiness.remaining.slice(0, 10).join('、');
3389
5032
  return presentDenial(PRESENT_DENY_CODES.ACTIVE_NOT_READY, `计划 ${planId} 已被取代,承接计划 ${successorPlanId} 只完成 ${readiness.done}/${readiness.total}`
@@ -3404,8 +5047,18 @@ export function createWorkplanRuntime(ctx, options = {}) {
3404
5047
  }
3405
5048
  function presentDenialVerdict(agent) {
3406
5049
  const session = agent?.session;
3407
- if (!session || !isRootSession(session))
5050
+ if (!session)
3408
5051
  return undefined;
5052
+ /*
5053
+ * [1.11.0] 子会话不得直接交付(T7 P9 / R3)。
5054
+ *
5055
+ * 1.10.6 对非根会话直接返回 undefined,等于让子 Agent 绕过根交付门禁
5056
+ * 调用 present:中间产物会被当成最终交付展示给用户。交付只属于根会话;
5057
+ * 子会话的产物应写进工作区并由主 Agent 统一 present。
5058
+ */
5059
+ if (!isRootSession(session)) {
5060
+ return presentDenial(PRESENT_DENY_CODES.NOT_ROOT, '子 Agent 不能直接交付:请把产物写入工作区并在结论里给出路径,由主 Agent 统一核对后调用 present。');
5061
+ }
3409
5062
  if (isPlanModeActive(ctx, session))
3410
5063
  return undefined;
3411
5064
  /*
@@ -3445,7 +5098,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3445
5098
  const unresolved = gateable
3446
5099
  .map((item) => ({
3447
5100
  record: item,
3448
- readiness: deliveryReadiness(derivePlanSnapshot(item.statuses), { phase: item.phase }),
5101
+ readiness: readinessOf(item),
3449
5102
  }))
3450
5103
  /*
3451
5104
  * A cancelled plan is not a delivery blocker for *other* plans — the
@@ -3508,7 +5161,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3508
5161
  return denial;
3509
5162
  return undefined;
3510
5163
  }
3511
- readiness = deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase });
5164
+ readiness = readinessOf(record);
3512
5165
  if (readiness.ready)
3513
5166
  return undefined;
3514
5167
  }
@@ -3656,7 +5309,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3656
5309
  .map((planId) => recordForPlan(session, planId))
3657
5310
  .filter((record) => record?.plan
3658
5311
  && !isTerminalPhase(record.phase)
3659
- && !deliveryReadiness(derivePlanSnapshot(record.statuses), { phase: record.phase }).ready);
5312
+ && !readinessOf(record).ready);
3660
5313
  if (unresolved.length === 0)
3661
5314
  return undefined;
3662
5315
  const ids = unresolved.slice(0, 4).map((record) => record.plan.planId);
@@ -3745,6 +5398,9 @@ export function createWorkplanRuntime(ctx, options = {}) {
3745
5398
  }
3746
5399
  }
3747
5400
  function dispose() {
5401
+ // [1.10.4] 定时器不能吊住进程,也不能在记录清空后复活一个已销毁的计划。
5402
+ for (const record of state.records.values())
5403
+ clearAutoResumeTimer(record, 'dispose');
3748
5404
  state.records.clear();
3749
5405
  }
3750
5406
  return {
@@ -3761,6 +5417,10 @@ export function createWorkplanRuntime(ctx, options = {}) {
3761
5417
  dispatchTool,
3762
5418
  statusTool,
3763
5419
  followupTool,
5420
+ escalateTool,
5421
+ instructTool,
5422
+ handoffTool,
5423
+ replanPlan,
3764
5424
  plansPayload,
3765
5425
  route,
3766
5426
  dispose,
@@ -3833,6 +5493,25 @@ async function maybePlan(ctx, state, payload, downstream, options) {
3833
5493
  const existing = state.records.get(session.id);
3834
5494
  if (existing?.plan?.createdTurn === payload.turn)
3835
5495
  return downstream;
5496
+ /*
5497
+ * [1.11.0] 执行中记录的变更,在本轮结束后仍然没有被 replan 落实时,必须
5498
+ * 在下一步拦住“直接开始新一轮计划/直接收尾”:提醒模型先处理变更。每个
5499
+ * 变更序号只提醒一次(notifiedSeq),不会每步重复注入。
5500
+ */
5501
+ if (existing?.plan && !existing.dispatchPromise
5502
+ && existing.changeRequest?.status === 'pending'
5503
+ && existing.changeRequest.notifiedSeq !== existing.changeRequest.seq) {
5504
+ existing.changeRequest.notifiedSeq = existing.changeRequest.seq;
5505
+ const change = existing.changeRequest;
5506
+ return enterDecision(downstream, [buildChangeRequestMessage({
5507
+ kind: 'workplan-change',
5508
+ planId: String(existing.plan.planId ?? ''),
5509
+ seq: Number(change.seq) || 1,
5510
+ at: Number(change.at) || Date.now(),
5511
+ turn: Number(change.turn) || null,
5512
+ text: String(change.text ?? ''),
5513
+ }, { afterRound: true })]);
5514
+ }
3836
5515
  // A plan generated in plan mode is intentionally deferred: keep it intact
3837
5516
  // until the user leaves plan mode and dispatches it. Cancelling it here
3838
5517
  // would make the plan disappear before the main Agent can act on approval.
@@ -3856,8 +5535,46 @@ async function maybePlan(ctx, state, payload, downstream, options) {
3856
5535
  existing.errors = Array.isArray(existing.errors) ? existing.errors : [];
3857
5536
  existing.errors.push('计划已取消:上一轮未派发');
3858
5537
  }
3859
- if (existing?.dispatchPromise || existing?.phase === 'executing')
5538
+ if (existing?.dispatchPromise || existing?.phase === 'executing') {
5539
+ /*
5540
+ * [1.11.0] C-12:执行中收到的新需求不能静默丢弃。
5541
+ *
5542
+ * 旧代码在这里直接 `return downstream`,用户在看到「正在做」之后补充的要求
5543
+ * 既没写进状态、也没出现在会话里,下一轮计划更不会包含它们。现在:
5544
+ * - 原文落进 `record.changeRequest`(带序号/回合/时间),刷新后可恢复;
5545
+ * - 一条 notice 消息进入本轮上下文,明确告诉模型「先别打断、结束后用
5546
+ * dsh_workplan_replan 落实」;
5547
+ * - 同一段文本只记一次,避免每步重复注入。
5548
+ */
5549
+ const text = truncate(taskText, 4000);
5550
+ const previous = typeof existing.changeRequest?.text === 'string' ? existing.changeRequest.text : '';
5551
+ if (previous !== text) {
5552
+ const seq = Number(existing.changeRequestSeq ?? 0) + 1;
5553
+ const at = Date.now();
5554
+ existing.changeRequestSeq = seq;
5555
+ existing.changeRequest = {
5556
+ seq,
5557
+ text,
5558
+ at,
5559
+ turn: Number(payload.turn ?? 0),
5560
+ status: 'pending',
5561
+ notifiedSeq: seq,
5562
+ };
5563
+ existing.updatedAt = at;
5564
+ const active = (existing.statuses ?? [])
5565
+ .filter((item) => item?.status === 'in_progress')
5566
+ .map((item) => `${String(item.subtaskId)}「${String(item.title ?? '')}」`);
5567
+ return enterDecision(downstream, [buildChangeRequestMessage({
5568
+ kind: 'workplan-change',
5569
+ planId: String(existing.plan?.planId ?? ''),
5570
+ seq,
5571
+ at,
5572
+ turn: Number(payload.turn ?? 0),
5573
+ text,
5574
+ }, { activeSubtasks: active })]);
5575
+ }
3860
5576
  return downstream;
5577
+ }
3861
5578
  const modelSelection = resolveModelSelection(ctx, payload);
3862
5579
  if (!modelSelection?.provider || !modelSelection?.model) {
3863
5580
  const message = buildDegradedMessage({
@@ -4102,6 +5819,54 @@ export function statusToolOutputSchema() {
4102
5819
  additionalProperties: true,
4103
5820
  };
4104
5821
  }
5822
+ export function replanToolOutputSchema() {
5823
+ return {
5824
+ type: 'object',
5825
+ properties: {
5826
+ ok: { type: 'boolean' },
5827
+ planId: { type: 'string' },
5828
+ planRevision: { type: 'number' },
5829
+ reason: { type: 'string' },
5830
+ phase: { type: 'string' },
5831
+ stats: { type: 'object' },
5832
+ statuses: { type: 'array' },
5833
+ marks: {
5834
+ type: 'array',
5835
+ items: {
5836
+ type: 'object',
5837
+ properties: {
5838
+ subtaskId: { type: 'string' },
5839
+ action: { type: 'string' },
5840
+ replacedBy: { type: 'array', items: { type: 'string' } },
5841
+ reason: { type: 'string' },
5842
+ },
5843
+ additionalProperties: true,
5844
+ },
5845
+ },
5846
+ added: {
5847
+ type: 'array',
5848
+ items: {
5849
+ type: 'object',
5850
+ properties: {
5851
+ subtaskId: { type: 'string' },
5852
+ stageId: { type: 'string' },
5853
+ title: { type: 'string' },
5854
+ replaces: { oneOf: [{ type: 'string' }, { type: 'null' }] },
5855
+ },
5856
+ additionalProperties: true,
5857
+ },
5858
+ },
5859
+ // 执行中拒绝改计划时:变更已记录、本轮仍在跑(REPLAN_PLAN_RUNNING)。
5860
+ running: { type: 'boolean' },
5861
+ changeRequest: { oneOf: [{ type: 'object' }, { type: 'null' }] },
5862
+ code: { type: 'string' },
5863
+ error: { type: 'string' },
5864
+ hint: { type: 'string' },
5865
+ },
5866
+ required: ['ok'],
5867
+ additionalProperties: true,
5868
+ };
5869
+ }
4105
5870
  export function dispatchToolOutputSchema() {
4106
5871
  return {
4107
5872
  type: 'object',