dsh-workplan 1.11.0 → 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/lib/runtime.js CHANGED
@@ -15,10 +15,11 @@ import { randomUUID } from 'node:crypto';
15
15
  import { existsSync, statSync } from 'node:fs';
16
16
  import { isAbsolute, resolve } from 'node:path';
17
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
+ import { compactUnderstandingAudit, validatePlanContext } from './understanding.js';
18
19
  import { computeMappingDigest, verifyMappingDigest } from './supersede-digest.js';
19
20
  import { supersedePlanRecord } from './supersede.js';
20
21
  import { createProgressWatchdog, describeError } from './watchdog.js';
21
- import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume } from './auto-resume.js';
22
+ import { AUTO_RESUME_DEFAULTS, autoResumeAttemptCap, decideAutoResume, liveResumeCounts } from './auto-resume.js';
22
23
  import { applyReplanStatuses, buildChangeRequestMessage, buildReplanMessage, parseChangeRequestMessage, parseReplanMessage, planReplan, } from './replan.js';
23
24
  /**
24
25
  * [1.8.18] How many subtasks the plan *defines*.
@@ -274,8 +275,20 @@ async function collectStream(stream) {
274
275
  throw new PlanError('规划器返回空内容', 'EMPTY_OUTPUT');
275
276
  return text;
276
277
  }
278
+ /**
279
+ * [1.12.0] Rollback switch for the context guard.
280
+ *
281
+ * `DSH_WORKPLAN_CONTEXT_GUARD=off` keeps the 1.11.1 behaviour (audit still runs
282
+ * and is attached for inspection, but no deviation can block a plan). This is a
283
+ * runtime switch rather than a code revert so a bad release can be defused
284
+ * without rebuilding, while the reason stays visible in the plan message.
285
+ */
286
+ function contextGuardStrict() {
287
+ const flag = String(process.env.DSH_WORKPLAN_CONTEXT_GUARD ?? '').trim().toLowerCase();
288
+ return flag !== 'off' && flag !== '0' && flag !== 'false';
289
+ }
277
290
  async function runPlanner(ctx, options) {
278
- const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {} } = options;
291
+ const { taskText, cwd, sessionId, modelSelection, signal, conversationContext = '', budget = {}, sourceMessageIds = [] } = options;
279
292
  let lastErrors = [];
280
293
  for (let attempt = 1; attempt <= 2; attempt += 1) {
281
294
  if (signal.aborted)
@@ -306,8 +319,28 @@ async function runPlanner(ctx, options) {
306
319
  const text = await collectStream(stream);
307
320
  const raw = extractJson(text);
308
321
  const validated = validatePlan(raw);
309
- if (validated.ok)
310
- return validated.plan;
322
+ if (validated.ok) {
323
+ /*
324
+ * [1.12.0] Structure alone is not understanding. Run the three-stage
325
+ * audit against the user's own words before the plan can be returned;
326
+ * a deviation becomes a retry error so the planner gets one chance to
327
+ * fix it, and a second failure degrades instead of dispatching.
328
+ */
329
+ const guard = validatePlanContext(validated.plan, {
330
+ taskText,
331
+ conversationContext,
332
+ sourceMessageIds,
333
+ strict: contextGuardStrict(),
334
+ });
335
+ if (guard.ok) {
336
+ const plan = validated.plan;
337
+ plan.taskAnchor = guard.audit.anchor;
338
+ plan.understandingAudit = compactUnderstandingAudit(guard.audit);
339
+ return plan;
340
+ }
341
+ lastErrors = guard.errors.length > 0 ? guard.errors : guard.warnings;
342
+ continue;
343
+ }
311
344
  lastErrors = validated.errors ?? [];
312
345
  }
313
346
  catch (error) {
@@ -323,7 +356,8 @@ async function runPlanner(ctx, options) {
323
356
  signal.removeEventListener('abort', onAbort);
324
357
  }
325
358
  }
326
- throw new PlanError(`规划器两次输出均未通过校验:${lastErrors.slice(0, 5).join(';')}`, 'PLANNER_FAILED', lastErrors);
359
+ const deviation = lastErrors.some((error) => /^(?:DEVIATION|CLARIFY|CONTEXT):/.test(String(error)));
360
+ throw new PlanError(`规划器两次输出均未通过校验:${lastErrors.slice(0, 5).join(';')}`, deviation ? 'DEVIATION' : 'PLANNER_FAILED', lastErrors);
327
361
  }
328
362
  function createChildController(parentSignal) {
329
363
  const controller = new AbortController();
@@ -682,6 +716,25 @@ export function budgetResetError(item, subtask, cwd, artifactExists = existsSync
682
716
  if (Number.isFinite(item?.startedAt) && Number.isFinite(item?.finishedAt)) {
683
717
  parts.push(`运行 ${Math.max(0, Math.round((Number(item.finishedAt) - Number(item.startedAt)) / 1000))}s`);
684
718
  }
719
+ /*
720
+ * [1.12.0][D-31] 预算重置不能把上一次的真实失败原因抹掉。
721
+ *
722
+ * 旧实现用「预算用尽」整段覆盖 `error`,原失败只留在 record.errors 的
723
+ * 尾部切片里;模型读状态行时看不到「为什么上一轮没做完」,只会以为
724
+ * 是时间不够。原值以只读摘要保留在前,重置原因仍然明确。
725
+ */
726
+ /*
727
+ * 只保留「真实失败」原因:`本轮预算用尽` 与中止哨兵 `总执行超时` 都不是
728
+ * 子任务的失败(后者会让 paused 计划看起来像集体超时,见 budget-pause
729
+ * 用例的硬断言)。优先读 applyStatus 留档的 lastError,其次读当前值。
730
+ */
731
+ const isSentinel = (text) => /本轮预算用尽|总执行超时/.test(text);
732
+ const previousFailure = [item?.lastError, item?.error]
733
+ .map((value) => (typeof value === 'string' ? value.trim() : ''))
734
+ .find((value) => value !== '' && !isSentinel(value)) ?? '';
735
+ if (previousFailure) {
736
+ parts.push(`上一次尝试的失败原因:${truncate(previousFailure, 300)}`);
737
+ }
685
738
  if (landed.length > 0)
686
739
  parts.push(`声明产物已在盘上:${landed.slice(0, 6).join('、')}`);
687
740
  return parts.join(';');
@@ -1756,6 +1809,22 @@ export async function dispatchPlan(ctx, record, options) {
1756
1809
  for (const item of record.statuses) {
1757
1810
  if (item.status === 'done')
1758
1811
  continue;
1812
+ /*
1813
+ * [1.12.0] 预算到点不是这三类行的「尝试被打断」(T11):
1814
+ *
1815
+ * - `escalated`:正在等用户/主 Agent 拍板。pending 分支会清空
1816
+ * question/options/blockedKind,于是请示被静默吞掉、计划变回 paused,
1817
+ * 自动续跑再把它当普通 pending 重派一次。
1818
+ * - `instructed`:指示已投递给子会话,该子会话可能仍在写。重置成
1819
+ * pending 根本不在 `CLOSURE_TRANSITIONS.instructed` 里,会抛
1820
+ * INVALID_TRANSITION —— 而这里位于 catch 内部,异常会让 phase、
1821
+ * 结果消息与自动续跑排期全部不落。
1822
+ * - `replanned`:终态旧行,只为追溯保留(没有出边),同样会抛。
1823
+ *
1824
+ * 三者保留原状由后续人工/子会话推进;真正被预算打断的行照常回到 pending。
1825
+ */
1826
+ if (item.closure === 'escalated' || item.closure === 'instructed' || item.closure === 'replanned')
1827
+ continue;
1759
1828
  // [1.8.19] Carry the aborted attempt's provenance and landed files into
1760
1829
  // the pause reason instead of silently erasing them.
1761
1830
  const definition = findSubtaskById(record.plan, item.subtaskId);
@@ -1765,8 +1834,16 @@ export async function dispatchPlan(ctx, record, options) {
1765
1834
  });
1766
1835
  }
1767
1836
  record.statuses = reset;
1768
- const total = record.statuses.length;
1769
- const done = record.statuses.filter((item) => item.status === 'done').length;
1837
+ /*
1838
+ * 按 live 行(排除 replanned)统计:一条只为追溯保留的旧行既不算完成,
1839
+ * 也不算「保留为未完成」,否则文案会说「12/13,其余 1 项未完成」——
1840
+ * 而那 1 项永远不会再跑。
1841
+ */
1842
+ const live = liveStatuses(record.statuses);
1843
+ const total = live.length;
1844
+ const done = live.filter((item) => item.status === 'done').length;
1845
+ const pendingNow = live.filter((item) => item.status === 'pending').length;
1846
+ const blockedNow = live.filter((item) => item.status === 'blocked').length;
1770
1847
  /*
1771
1848
  * [1.5.2] 预算到点 ≠ 一定是「暂停」。
1772
1849
  *
@@ -1776,11 +1853,18 @@ export async function dispatchPlan(ctx, record, options) {
1776
1853
  * 全部完成时直接进终态,并且不再写「其余 0 项保留为未完成」这种自相矛盾的说明。
1777
1854
  */
1778
1855
  const allDoneNow = total > 0 && done === total;
1779
- record.phase = allDoneNow ? 'done' : 'paused';
1856
+ /*
1857
+ * [1.12.0] 与普通轮末同一判据(T11):只要有仍 live 的 blocked 行,
1858
+ * 阶段就是 blocked —— 其中可能包含一条保留下来的「待指示」。写成 paused
1859
+ * 会让卡片显示「预算用完、可续跑」,而真正该做的是 instruct。
1860
+ */
1861
+ record.phase = allDoneNow ? 'done' : (blockedNow > 0 ? 'blocked' : 'paused');
1780
1862
  const minutes = Math.max(1, Math.round((options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000));
1781
1863
  record.error = allDoneNow
1782
1864
  ? null
1783
- : `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`;
1865
+ : blockedNow > 0
1866
+ ? `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total};${blockedNow} 项在等待指示或已受阻(续跑不会重派,请先 instruct 或改判),${pendingNow} 项保留为未完成,再次派发本计划即可继续`
1867
+ : `本轮执行预算(${minutes} 分钟)已到:已完成 ${done}/${total},其余 ${total - done} 项保留为未完成,再次派发本计划即可续跑(已完成的不重跑)`;
1784
1868
  /*
1785
1869
  * Drop the failure lines the aborted children wrote on their way out.
1786
1870
  * They used to survive into the result payload as
@@ -2669,6 +2753,56 @@ export function createWorkplanRuntime(ctx, options = {}) {
2669
2753
  maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2670
2754
  },
2671
2755
  };
2756
+ /**
2757
+ * [1.12.0] 自动派发:计划生成后立即以 async 方式开跑。
2758
+ *
2759
+ * 与 `dsh_workplan_dispatch(mode:"async")` 走同一条 `dispatchPlan` 路径,
2760
+ * 区别只在「启动」是计划落地后的确定性动作,而不是模型的一次额外调用:
2761
+ * - 独立 AbortController:回合结束不会杀掉后台执行;
2762
+ * - 结果消息由 `finishRound` 写入,刷新后仍可见;
2763
+ * - 失败只记录错误,不把「派发失败」伪装成「计划生成失败」。
2764
+ */
2765
+ function startAutoDispatch(record, session, agent) {
2766
+ const controller = new AbortController();
2767
+ record.abortDispatch = (reason) => {
2768
+ if (!controller.signal.aborted) {
2769
+ controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'));
2770
+ }
2771
+ };
2772
+ const roundOptions = {
2773
+ agent,
2774
+ modelSelection: record.modelSelection,
2775
+ cwd: session.header?.cwd ?? options.cwd,
2776
+ conversationContext: record.conversationContext ?? '',
2777
+ };
2778
+ record.dispatchStartedAt = Date.now();
2779
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2780
+ ...roundOptions,
2781
+ signal: controller.signal,
2782
+ childTimeoutMs: limits.childTimeoutMs,
2783
+ idleTimeoutMs: limits.idleTimeoutMs,
2784
+ totalTimeoutMs: limits.totalTimeoutMs,
2785
+ maxResumes: limits.maxResumes,
2786
+ strictEvidence: options.strictEvidence,
2787
+ }).finally(() => {
2788
+ record.dispatchPromise = null;
2789
+ record.dispatchStartedAt = null;
2790
+ record.abortDispatch = null;
2791
+ });
2792
+ record.dispatchPromise
2793
+ .then(() => {
2794
+ finishRound(record, session);
2795
+ state.records.set(session.id, record);
2796
+ armAutoResume(record, session, roundOptions);
2797
+ })
2798
+ .catch((error) => {
2799
+ pushRecordError(record, error);
2800
+ finishRound(record, session);
2801
+ state.records.set(session.id, record);
2802
+ armAutoResume(record, session, roundOptions);
2803
+ });
2804
+ }
2805
+ state.startAutoDispatch = startAutoDispatch;
2672
2806
  async function onPreStep(payload, next) {
2673
2807
  let downstream;
2674
2808
  try {
@@ -3362,8 +3496,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
3362
3496
  else if (Number(book.attempt ?? 0) > 0)
3363
3497
  book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1;
3364
3498
  book.doneBefore = done;
3365
- const pending = statuses.filter((item) => item?.status === 'pending').length;
3366
- const blocked = statuses.filter((item) => item?.status === 'blocked').length;
3499
+ /*
3500
+ * [1.12.0] 只数仍参与调度的行(T11):replanned 旧行保持 status='pending'
3501
+ * 只为追溯,把它们算进 pending 会让「live 全 done」的计划也排一次续跑,
3502
+ * 那一轮什么都不会派发,还会往 errors 里写一条误导性的停止行。
3503
+ */
3504
+ const liveCounts = liveResumeCounts(statuses);
3505
+ const pending = liveCounts.pending;
3506
+ const blocked = liveCounts.blocked;
3367
3507
  /*
3368
3508
  * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
3369
3509
  *
@@ -3407,7 +3547,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3407
3547
  }].slice(-10);
3408
3548
  if (decision.action !== 'schedule') {
3409
3549
  /*
3410
- * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
3550
+ * 显式关闭开关时不写错误行:关闭不是一次「失败」,不该污染计划台账。
3411
3551
  * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
3412
3552
  */
3413
3553
  if (decision.code !== 'AUTO_RESUME_DISABLED') {
@@ -5609,6 +5749,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
5609
5749
  modelSelection,
5610
5750
  signal: payload.signal,
5611
5751
  conversationContext,
5752
+ sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
5612
5753
  /*
5613
5754
  * Hand the real limits to the planner. Without them it had no idea the
5614
5755
  * round budget was 20 minutes and happily planned 15 heavy subtasks,
@@ -5676,16 +5817,33 @@ async function maybePlan(ctx, state, payload, downstream, options) {
5676
5817
  planMode,
5677
5818
  };
5678
5819
  state.records.set(session.id, record);
5820
+ /*
5821
+ * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
5822
+ * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
5823
+ * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
5824
+ */
5825
+ const autoDispatched = !planMode && options?.autoDispatch !== false;
5826
+ if (autoDispatched) {
5827
+ record.dispatchedAt = Date.now();
5828
+ state.startAutoDispatch?.(record, session, payload.agent);
5829
+ }
5679
5830
  /*
5680
5831
  * Plan-first: commit the plan with this step and let the main Agent call
5681
5832
  * dsh_workplan_dispatch. Dispatching here would hide the plan until every
5682
- * child finished, which is exactly the "没动静/没完成" failure. The dispatch
5683
- * tool appends the durable result after the children finish, and tools.guard
5684
- * stops the main Agent from doing other work before dispatching.
5833
+ * child finished, which is exactly the "没动静/没完成" failure.
5834
+ *
5835
+ * [1.12.0] There is no tool guard that forces dispatch before other work —
5836
+ * `toolGuardReason` only denies dispatch in plan mode and `present` when the
5837
+ * plan is not ready. What actually enforces the ordering is the system
5838
+ * prompt, plus the turn-stopping gate steering at most twice per turn
5839
+ * (`STOP_STEER_LIMIT`); if the model still never dispatches, the next turn
5840
+ * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
5685
5841
  */
5686
5842
  const planMessage = buildPlanMessage(fullPlan, {
5687
5843
  totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
5688
5844
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
5845
+ planMode,
5846
+ autoDispatched,
5689
5847
  });
5690
5848
  if (!planMode)
5691
5849
  return enterDecision(downstream, [planMessage]);