dsh-workplan 1.11.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/runtime.ts CHANGED
@@ -71,10 +71,11 @@ import {
71
71
  MAX_HANDOFF_RESPONSE_CHARS,
72
72
  } from './plan.js'
73
73
  import type { PresentDenialVerdict, PresentDenyCode } from './plan.js'
74
+ import { compactUnderstandingAudit, validatePlanContext } from './understanding.js'
74
75
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js'
75
76
  import { supersedePlanRecord } from './supersede.js'
76
77
  import { createProgressWatchdog, describeError } from './watchdog.js'
77
- import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js'
78
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume, liveResumeCounts } from './auto-resume.js'
78
79
  import {
79
80
  applyReplanStatuses,
80
81
  buildChangeRequestMessage,
@@ -335,8 +336,21 @@ async function collectStream(stream: any) {
335
336
  return text
336
337
  }
337
338
 
339
+ /**
340
+ * [1.12.0] Rollback switch for the context guard.
341
+ *
342
+ * `DSH_WORKPLAN_CONTEXT_GUARD=off` keeps the 1.11.1 behaviour (audit still runs
343
+ * and is attached for inspection, but no deviation can block a plan). This is a
344
+ * runtime switch rather than a code revert so a bad release can be defused
345
+ * without rebuilding, while the reason stays visible in the plan message.
346
+ */
347
+ function contextGuardStrict() {
348
+ const flag = String(process.env.DSH_WORKPLAN_CONTEXT_GUARD ?? '').trim().toLowerCase()
349
+ return flag !== 'off' && flag !== '0' && flag !== 'false'
350
+ }
351
+
338
352
  async function runPlanner(ctx: any, options: any) {
339
- const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {} } = options
353
+ const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {}, sourceMessageIds = [] } = options
340
354
  let lastErrors: string[] = []
341
355
  for (let attempt = 1; attempt <= 2; attempt += 1) {
342
356
  if (signal.aborted) throw abortError()
@@ -366,7 +380,28 @@ async function runPlanner(ctx: any, options: any) {
366
380
  const text = await collectStream(stream)
367
381
  const raw = extractJson(text)
368
382
  const validated = validatePlan(raw)
369
- if (validated.ok) return validated.plan
383
+ if (validated.ok) {
384
+ /*
385
+ * [1.12.0] Structure alone is not understanding. Run the three-stage
386
+ * audit against the user's own words before the plan can be returned;
387
+ * a deviation becomes a retry error so the planner gets one chance to
388
+ * fix it, and a second failure degrades instead of dispatching.
389
+ */
390
+ const guard = validatePlanContext(validated.plan, {
391
+ taskText,
392
+ conversationContext,
393
+ sourceMessageIds,
394
+ strict: contextGuardStrict(),
395
+ })
396
+ if (guard.ok) {
397
+ const plan: any = validated.plan
398
+ plan.taskAnchor = guard.audit.anchor
399
+ plan.understandingAudit = compactUnderstandingAudit(guard.audit)
400
+ return plan
401
+ }
402
+ lastErrors = guard.errors.length > 0 ? guard.errors : guard.warnings
403
+ continue
404
+ }
370
405
  lastErrors = validated.errors ?? []
371
406
  } catch (error) {
372
407
  if (signal.aborted || (controller.signal.aborted && (controller.signal.reason as any)?.code === 'ABORTED')) {
@@ -379,9 +414,10 @@ async function runPlanner(ctx: any, options: any) {
379
414
  signal.removeEventListener('abort', onAbort)
380
415
  }
381
416
  }
417
+ const deviation = lastErrors.some((error: any) => /^(?:DEVIATION|CLARIFY|CONTEXT):/.test(String(error)))
382
418
  throw new PlanError(
383
419
  `规划器两次输出均未通过校验:${lastErrors.slice(0, 5).join(';')}`,
384
- 'PLANNER_FAILED',
420
+ deviation ? 'DEVIATION' : 'PLANNER_FAILED',
385
421
  lastErrors,
386
422
  )
387
423
  }
@@ -733,6 +769,25 @@ export function budgetResetError(item: any, subtask: any, cwd: any, artifactExis
733
769
  if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
734
770
  parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`)
735
771
  }
772
+ /*
773
+ * [1.12.0][D-31] 预算重置不能把上一次的真实失败原因抹掉。
774
+ *
775
+ * 旧实现用「预算用尽」整段覆盖 `error`,原失败只留在 record.errors 的
776
+ * 尾部切片里;模型读状态行时看不到「为什么上一轮没做完」,只会以为
777
+ * 是时间不够。原值以只读摘要保留在前,重置原因仍然明确。
778
+ */
779
+ /*
780
+ * 只保留「真实失败」原因:`本轮预算用尽` 与中止哨兵 `总执行超时` 都不是
781
+ * 子任务的失败(后者会让 paused 计划看起来像集体超时,见 budget-pause
782
+ * 用例的硬断言)。优先读 applyStatus 留档的 lastError,其次读当前值。
783
+ */
784
+ const isSentinel = (text: string) => /本轮预算用尽|总执行超时/.test(text)
785
+ const previousFailure = [item?.lastError, item?.error]
786
+ .map((value: any) => (typeof value === 'string' ? value.trim() : ''))
787
+ .find((value: string) => value !== '' && !isSentinel(value)) ?? ''
788
+ if (previousFailure) {
789
+ parts.push(`上一次尝试的失败原因:${truncate(previousFailure, 300)}`)
790
+ }
736
791
  if (landed.length > 0) parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`)
737
792
  return parts.join(';')
738
793
  }
@@ -1783,6 +1838,21 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1783
1838
  let reset = record.statuses
1784
1839
  for (const item of record.statuses) {
1785
1840
  if (item.status === 'done') continue
1841
+ /*
1842
+ * [1.12.0] 预算到点不是这三类行的「尝试被打断」(T11):
1843
+ *
1844
+ * - `escalated`:正在等用户/主 Agent 拍板。pending 分支会清空
1845
+ * question/options/blockedKind,于是请示被静默吞掉、计划变回 paused,
1846
+ * 自动续跑再把它当普通 pending 重派一次。
1847
+ * - `instructed`:指示已投递给子会话,该子会话可能仍在写。重置成
1848
+ * pending 根本不在 `CLOSURE_TRANSITIONS.instructed` 里,会抛
1849
+ * INVALID_TRANSITION —— 而这里位于 catch 内部,异常会让 phase、
1850
+ * 结果消息与自动续跑排期全部不落。
1851
+ * - `replanned`:终态旧行,只为追溯保留(没有出边),同样会抛。
1852
+ *
1853
+ * 三者保留原状由后续人工/子会话推进;真正被预算打断的行照常回到 pending。
1854
+ */
1855
+ if (item.closure === 'escalated' || item.closure === 'instructed' || item.closure === 'replanned') continue
1786
1856
  // [1.8.19] Carry the aborted attempt's provenance and landed files into
1787
1857
  // the pause reason instead of silently erasing them.
1788
1858
  const definition = findSubtaskById(record.plan, item.subtaskId)
@@ -1792,8 +1862,16 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1792
1862
  })
1793
1863
  }
1794
1864
  record.statuses = reset
1795
- const total = record.statuses.length
1796
- const done = record.statuses.filter((item: any) => item.status === 'done').length
1865
+ /*
1866
+ * 按 live 行(排除 replanned)统计:一条只为追溯保留的旧行既不算完成,
1867
+ * 也不算「保留为未完成」,否则文案会说「12/13,其余 1 项未完成」——
1868
+ * 而那 1 项永远不会再跑。
1869
+ */
1870
+ const live = liveStatuses(record.statuses)
1871
+ const total = live.length
1872
+ const done = live.filter((item: any) => item.status === 'done').length
1873
+ const pendingNow = live.filter((item: any) => item.status === 'pending').length
1874
+ const blockedNow = live.filter((item: any) => item.status === 'blocked').length
1797
1875
  /*
1798
1876
  * [1.5.2] 预算到点 ≠ 一定是「暂停」。
1799
1877
  *
@@ -1803,11 +1881,18 @@ export async function dispatchPlan(ctx: any, record: any, options: any) {
1803
1881
  * 全部完成时直接进终态,并且不再写「其余 0 项保留为未完成」这种自相矛盾的说明。
1804
1882
  */
1805
1883
  const allDoneNow = total > 0 && done === total
1806
- record.phase = allDoneNow ? 'done' : 'paused'
1884
+ /*
1885
+ * [1.12.0] 与普通轮末同一判据(T11):只要有仍 live 的 blocked 行,
1886
+ * 阶段就是 blocked —— 其中可能包含一条保留下来的「待指示」。写成 paused
1887
+ * 会让卡片显示「预算用完、可续跑」,而真正该做的是 instruct。
1888
+ */
1889
+ record.phase = allDoneNow ? 'done' : (blockedNow > 0 ? 'blocked' : 'paused')
1807
1890
  const minutes = Math.max(1, Math.round((options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000))
1808
1891
  record.error = allDoneNow
1809
1892
  ? null
1810
- : `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`
1893
+ : blockedNow > 0
1894
+ ? `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total};${blockedNow} 项在等待指示或已受阻(续跑不会重派,请先 instruct 或改判),${pendingNow} 项保留为未完成,再次派发本计划即可继续`
1895
+ : `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`
1811
1896
  /*
1812
1897
  * Drop the failure lines the aborted children wrote on their way out.
1813
1898
  * They used to survive into the result payload as
@@ -2653,11 +2738,12 @@ export type WorkplanRuntimeOptions = {
2653
2738
  /** How many times a blocked plan may be resumed. */
2654
2739
  maxResumes?: number
2655
2740
  /**
2656
- * [1.10.4] 整轮预算到点后自动开始下一轮。**默认关闭**:默认值来自
2657
- * `AUTO_RESUME_DEFAULTS.enabled=false`,必须由宿主显式打开。
2741
+ * [1.10.4][1.12.0] 整轮预算到点后自动开始下一轮。**默认开启**:默认值来自
2742
+ * `AUTO_RESUME_DEFAULTS.enabled=true`;`autoResume:false` 或
2743
+ * `DSH_WORKPLAN_AUTO_RESUME=0` 显式关闭。
2658
2744
  *
2659
- * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败),
2660
- * 也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2745
+ * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败)与
2746
+ * `escalated`(待指示),也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2661
2747
  */
2662
2748
  autoResume?: boolean
2663
2749
  /** 自动续跑轮次上限(0–4,默认 2)。 */
@@ -2670,6 +2756,14 @@ export type WorkplanRuntimeOptions = {
2670
2756
  * 或 `DSH_WORKPLAN_STRICT_COMPLETION` 解析后传入。
2671
2757
  */
2672
2758
  strictEvidence?: boolean
2759
+ /**
2760
+ * [1.12.0] 计划生成后自动派发(T6 Q2 / 用户三项机制体检)。
2761
+ *
2762
+ * `undefined`/`true` = 计划一生成就以 async 方式开跑,不依赖主模型再调一次
2763
+ * `dsh_workplan_dispatch`;`false` = 保留 plan-first(计划消息要求模型显式
2764
+ * 派发)。plan 模式、已有计划执行中、预算/取消/幂等/交付门禁不受影响。
2765
+ */
2766
+ autoDispatch?: boolean
2673
2767
  /**
2674
2768
  * [1.8.13] Package version, supplied by the host from its `meta.version`.
2675
2769
  *
@@ -2757,6 +2851,57 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2757
2851
  },
2758
2852
  }
2759
2853
 
2854
+ /**
2855
+ * [1.12.0] 自动派发:计划生成后立即以 async 方式开跑。
2856
+ *
2857
+ * 与 `dsh_workplan_dispatch(mode:"async")` 走同一条 `dispatchPlan` 路径,
2858
+ * 区别只在「启动」是计划落地后的确定性动作,而不是模型的一次额外调用:
2859
+ * - 独立 AbortController:回合结束不会杀掉后台执行;
2860
+ * - 结果消息由 `finishRound` 写入,刷新后仍可见;
2861
+ * - 失败只记录错误,不把「派发失败」伪装成「计划生成失败」。
2862
+ */
2863
+ function startAutoDispatch(record: any, session: any, agent: any) {
2864
+ const controller = new AbortController()
2865
+ record.abortDispatch = (reason: string) => {
2866
+ if (!controller.signal.aborted) {
2867
+ controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2868
+ }
2869
+ }
2870
+ const roundOptions = {
2871
+ agent,
2872
+ modelSelection: record.modelSelection,
2873
+ cwd: session.header?.cwd ?? options.cwd,
2874
+ conversationContext: record.conversationContext ?? '',
2875
+ }
2876
+ record.dispatchStartedAt = Date.now()
2877
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2878
+ ...roundOptions,
2879
+ signal: controller.signal,
2880
+ childTimeoutMs: limits.childTimeoutMs,
2881
+ idleTimeoutMs: limits.idleTimeoutMs,
2882
+ totalTimeoutMs: limits.totalTimeoutMs,
2883
+ maxResumes: limits.maxResumes,
2884
+ strictEvidence: options.strictEvidence,
2885
+ }).finally(() => {
2886
+ record.dispatchPromise = null
2887
+ record.dispatchStartedAt = null
2888
+ record.abortDispatch = null
2889
+ })
2890
+ record.dispatchPromise
2891
+ .then(() => {
2892
+ finishRound(record, session)
2893
+ state.records.set(session.id, record)
2894
+ armAutoResume(record, session, roundOptions)
2895
+ })
2896
+ .catch((error: any) => {
2897
+ pushRecordError(record, error)
2898
+ finishRound(record, session)
2899
+ state.records.set(session.id, record)
2900
+ armAutoResume(record, session, roundOptions)
2901
+ })
2902
+ }
2903
+ state.startAutoDispatch = startAutoDispatch
2904
+
2760
2905
  async function onPreStep(payload: any, next: any) {
2761
2906
  let downstream
2762
2907
  try {
@@ -3437,8 +3582,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3437
3582
  if (done > doneBefore) book.noProgressRounds = 0
3438
3583
  else if (Number(book.attempt ?? 0) > 0) book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1
3439
3584
  book.doneBefore = done
3440
- const pending = statuses.filter((item: any) => item?.status === 'pending').length
3441
- const blocked = statuses.filter((item: any) => item?.status === 'blocked').length
3585
+ /*
3586
+ * [1.12.0] 只数仍参与调度的行(T11):replanned 旧行保持 status='pending'
3587
+ * 只为追溯,把它们算进 pending 会让「live 全 done」的计划也排一次续跑,
3588
+ * 那一轮什么都不会派发,还会往 errors 里写一条误导性的停止行。
3589
+ */
3590
+ const liveCounts = liveResumeCounts(statuses)
3591
+ const pending = liveCounts.pending
3592
+ const blocked = liveCounts.blocked
3442
3593
  /*
3443
3594
  * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
3444
3595
  *
@@ -3482,7 +3633,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3482
3633
  }].slice(-10)
3483
3634
  if (decision.action !== 'schedule') {
3484
3635
  /*
3485
- * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
3636
+ * 显式关闭开关时不写错误行:关闭不是一次「失败」,不该污染计划台账。
3486
3637
  * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
3487
3638
  */
3488
3639
  if (decision.code !== 'AUTO_RESUME_DISABLED') {
@@ -5598,6 +5749,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
5598
5749
  modelSelection,
5599
5750
  signal: payload.signal,
5600
5751
  conversationContext,
5752
+ sourceMessageIds: human.map((message: any) => message.id).filter((id: any) => typeof id === 'string'),
5601
5753
  /*
5602
5754
  * Hand the real limits to the planner. Without them it had no idea the
5603
5755
  * round budget was 20 minutes and happily planned 15 heavy subtasks,
@@ -5663,16 +5815,33 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
5663
5815
  planMode,
5664
5816
  }
5665
5817
  state.records.set(session.id, record)
5818
+ /*
5819
+ * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
5820
+ * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
5821
+ * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
5822
+ */
5823
+ const autoDispatched = !planMode && options?.autoDispatch !== false
5824
+ if (autoDispatched) {
5825
+ record.dispatchedAt = Date.now()
5826
+ state.startAutoDispatch?.(record, session, payload.agent)
5827
+ }
5666
5828
  /*
5667
5829
  * Plan-first: commit the plan with this step and let the main Agent call
5668
5830
  * dsh_workplan_dispatch. Dispatching here would hide the plan until every
5669
- * child finished, which is exactly the "没动静/没完成" failure. The dispatch
5670
- * tool appends the durable result after the children finish, and tools.guard
5671
- * stops the main Agent from doing other work before dispatching.
5831
+ * child finished, which is exactly the "没动静/没完成" failure.
5832
+ *
5833
+ * [1.12.0] There is no tool guard that forces dispatch before other work —
5834
+ * `toolGuardReason` only denies dispatch in plan mode and `present` when the
5835
+ * plan is not ready. What actually enforces the ordering is the system
5836
+ * prompt, plus the turn-stopping gate steering at most twice per turn
5837
+ * (`STOP_STEER_LIMIT`); if the model still never dispatches, the next turn
5838
+ * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
5672
5839
  */
5673
5840
  const planMessage = buildPlanMessage(fullPlan, {
5674
5841
  totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
5675
5842
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
5843
+ planMode,
5844
+ autoDispatched,
5676
5845
  })
5677
5846
  if (!planMode) return enterDecision(downstream, [planMessage])
5678
5847
  /*