dsh-workplan 1.11.1 → 1.12.1

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
@@ -2358,7 +2443,12 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
2358
2443
  if (snap) {
2359
2444
  try {
2360
2445
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
2361
- status: update.status,
2446
+ /*
2447
+ * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
2448
+ * 重放时若再走 done 分支,会把已经 reported 的行打回 done 并抛
2449
+ * INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
2450
+ */
2451
+ status: update.handoffs === undefined ? update.status : undefined,
2362
2452
  progress: typeof update.progress === 'number' ? update.progress : undefined,
2363
2453
  summary: typeof update.note === 'string' ? update.note : undefined,
2364
2454
  // [1.8.13] Evidence written through the update tool must survive replay.
@@ -2366,6 +2456,7 @@ export function reconstructFromSession(session: any, targetPlanId?: string) {
2366
2456
  acceptance: update.acceptance,
2367
2457
  artifacts: update.artifacts,
2368
2458
  missingArtifacts: update.missingArtifacts,
2459
+ handoffs: update.handoffs,
2369
2460
  revision: Number.isInteger(update.revision) ? update.revision : undefined,
2370
2461
  updatedBy: 'agent',
2371
2462
  })
@@ -2653,11 +2744,12 @@ export type WorkplanRuntimeOptions = {
2653
2744
  /** How many times a blocked plan may be resumed. */
2654
2745
  maxResumes?: number
2655
2746
  /**
2656
- * [1.10.4] 整轮预算到点后自动开始下一轮。**默认关闭**:默认值来自
2657
- * `AUTO_RESUME_DEFAULTS.enabled=false`,必须由宿主显式打开。
2747
+ * [1.10.4][1.12.0] 整轮预算到点后自动开始下一轮。**默认开启**:默认值来自
2748
+ * `AUTO_RESUME_DEFAULTS.enabled=true`;`autoResume:false` 或
2749
+ * `DSH_WORKPLAN_AUTO_RESUME=0` 显式关闭。
2658
2750
  *
2659
- * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败),
2660
- * 也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2751
+ * 它只续跑 `paused`(预算到点)的计划,不动 `blocked`(真实失败)与
2752
+ * `escalated`(待指示),也不重跑任何 `done` 项;自动续跑本身不做任何证据判定。
2661
2753
  */
2662
2754
  autoResume?: boolean
2663
2755
  /** 自动续跑轮次上限(0–4,默认 2)。 */
@@ -2670,6 +2762,14 @@ export type WorkplanRuntimeOptions = {
2670
2762
  * 或 `DSH_WORKPLAN_STRICT_COMPLETION` 解析后传入。
2671
2763
  */
2672
2764
  strictEvidence?: boolean
2765
+ /**
2766
+ * [1.12.0] 计划生成后自动派发(T6 Q2 / 用户三项机制体检)。
2767
+ *
2768
+ * `undefined`/`true` = 计划一生成就以 async 方式开跑,不依赖主模型再调一次
2769
+ * `dsh_workplan_dispatch`;`false` = 保留 plan-first(计划消息要求模型显式
2770
+ * 派发)。plan 模式、已有计划执行中、预算/取消/幂等/交付门禁不受影响。
2771
+ */
2772
+ autoDispatch?: boolean
2673
2773
  /**
2674
2774
  * [1.8.13] Package version, supplied by the host from its `meta.version`.
2675
2775
  *
@@ -2757,6 +2857,57 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
2757
2857
  },
2758
2858
  }
2759
2859
 
2860
+ /**
2861
+ * [1.12.0] 自动派发:计划生成后立即以 async 方式开跑。
2862
+ *
2863
+ * 与 `dsh_workplan_dispatch(mode:"async")` 走同一条 `dispatchPlan` 路径,
2864
+ * 区别只在「启动」是计划落地后的确定性动作,而不是模型的一次额外调用:
2865
+ * - 独立 AbortController:回合结束不会杀掉后台执行;
2866
+ * - 结果消息由 `finishRound` 写入,刷新后仍可见;
2867
+ * - 失败只记录错误,不把「派发失败」伪装成「计划生成失败」。
2868
+ */
2869
+ function startAutoDispatch(record: any, session: any, agent: any) {
2870
+ const controller = new AbortController()
2871
+ record.abortDispatch = (reason: string) => {
2872
+ if (!controller.signal.aborted) {
2873
+ controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'))
2874
+ }
2875
+ }
2876
+ const roundOptions = {
2877
+ agent,
2878
+ modelSelection: record.modelSelection,
2879
+ cwd: session.header?.cwd ?? options.cwd,
2880
+ conversationContext: record.conversationContext ?? '',
2881
+ }
2882
+ record.dispatchStartedAt = Date.now()
2883
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2884
+ ...roundOptions,
2885
+ signal: controller.signal,
2886
+ childTimeoutMs: limits.childTimeoutMs,
2887
+ idleTimeoutMs: limits.idleTimeoutMs,
2888
+ totalTimeoutMs: limits.totalTimeoutMs,
2889
+ maxResumes: limits.maxResumes,
2890
+ strictEvidence: options.strictEvidence,
2891
+ }).finally(() => {
2892
+ record.dispatchPromise = null
2893
+ record.dispatchStartedAt = null
2894
+ record.abortDispatch = null
2895
+ })
2896
+ record.dispatchPromise
2897
+ .then(() => {
2898
+ finishRound(record, session)
2899
+ state.records.set(session.id, record)
2900
+ armAutoResume(record, session, roundOptions)
2901
+ })
2902
+ .catch((error: any) => {
2903
+ pushRecordError(record, error)
2904
+ finishRound(record, session)
2905
+ state.records.set(session.id, record)
2906
+ armAutoResume(record, session, roundOptions)
2907
+ })
2908
+ }
2909
+ state.startAutoDispatch = startAutoDispatch
2910
+
2760
2911
  async function onPreStep(payload: any, next: any) {
2761
2912
  let downstream
2762
2913
  try {
@@ -3437,8 +3588,14 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3437
3588
  if (done > doneBefore) book.noProgressRounds = 0
3438
3589
  else if (Number(book.attempt ?? 0) > 0) book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1
3439
3590
  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
3591
+ /*
3592
+ * [1.12.0] 只数仍参与调度的行(T11):replanned 旧行保持 status='pending'
3593
+ * 只为追溯,把它们算进 pending 会让「live 全 done」的计划也排一次续跑,
3594
+ * 那一轮什么都不会派发,还会往 errors 里写一条误导性的停止行。
3595
+ */
3596
+ const liveCounts = liveResumeCounts(statuses)
3597
+ const pending = liveCounts.pending
3598
+ const blocked = liveCounts.blocked
3442
3599
  /*
3443
3600
  * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
3444
3601
  *
@@ -3482,7 +3639,7 @@ export function createWorkplanRuntime(ctx: any, options: WorkplanRuntimeOptions
3482
3639
  }].slice(-10)
3483
3640
  if (decision.action !== 'schedule') {
3484
3641
  /*
3485
- * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
3642
+ * 显式关闭开关时不写错误行:关闭不是一次「失败」,不该污染计划台账。
3486
3643
  * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
3487
3644
  */
3488
3645
  if (decision.code !== 'AUTO_RESUME_DISABLED') {
@@ -5598,6 +5755,7 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
5598
5755
  modelSelection,
5599
5756
  signal: payload.signal,
5600
5757
  conversationContext,
5758
+ sourceMessageIds: human.map((message: any) => message.id).filter((id: any) => typeof id === 'string'),
5601
5759
  /*
5602
5760
  * Hand the real limits to the planner. Without them it had no idea the
5603
5761
  * round budget was 20 minutes and happily planned 15 heavy subtasks,
@@ -5663,16 +5821,33 @@ async function maybePlan(ctx: any, state: any, payload: any, downstream: any, op
5663
5821
  planMode,
5664
5822
  }
5665
5823
  state.records.set(session.id, record)
5824
+ /*
5825
+ * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
5826
+ * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
5827
+ * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
5828
+ */
5829
+ const autoDispatched = !planMode && options?.autoDispatch !== false
5830
+ if (autoDispatched) {
5831
+ record.dispatchedAt = Date.now()
5832
+ state.startAutoDispatch?.(record, session, payload.agent)
5833
+ }
5666
5834
  /*
5667
5835
  * Plan-first: commit the plan with this step and let the main Agent call
5668
5836
  * 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.
5837
+ * child finished, which is exactly the "没动静/没完成" failure.
5838
+ *
5839
+ * [1.12.0] There is no tool guard that forces dispatch before other work —
5840
+ * `toolGuardReason` only denies dispatch in plan mode and `present` when the
5841
+ * plan is not ready. What actually enforces the ordering is the system
5842
+ * prompt, plus the turn-stopping gate steering at most twice per turn
5843
+ * (`STOP_STEER_LIMIT`); if the model still never dispatches, the next turn
5844
+ * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
5672
5845
  */
5673
5846
  const planMessage = buildPlanMessage(fullPlan, {
5674
5847
  totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
5675
5848
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
5849
+ planMode,
5850
+ autoDispatched,
5676
5851
  })
5677
5852
  if (!planMode) return enterDecision(downstream, [planMessage])
5678
5853
  /*