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/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
@@ -2317,7 +2401,12 @@ export function reconstructFromSession(session, targetPlanId) {
2317
2401
  if (snap) {
2318
2402
  try {
2319
2403
  snap.statuses = applyStatus(snap.statuses, update.subtaskId, {
2320
- status: update.status,
2404
+ /*
2405
+ * handoff 的 durable 记录携带的是状态快照,不是一次状态迁移。
2406
+ * 重放时若再走 done 分支,会把已经 reported 的行打回 done 并抛
2407
+ * INVALID_TRANSITION(wp-79c31abf 的 H1 就是这样被丢掉的)。
2408
+ */
2409
+ status: update.handoffs === undefined ? update.status : undefined,
2321
2410
  progress: typeof update.progress === 'number' ? update.progress : undefined,
2322
2411
  summary: typeof update.note === 'string' ? update.note : undefined,
2323
2412
  // [1.8.13] Evidence written through the update tool must survive replay.
@@ -2325,6 +2414,7 @@ export function reconstructFromSession(session, targetPlanId) {
2325
2414
  acceptance: update.acceptance,
2326
2415
  artifacts: update.artifacts,
2327
2416
  missingArtifacts: update.missingArtifacts,
2417
+ handoffs: update.handoffs,
2328
2418
  revision: Number.isInteger(update.revision) ? update.revision : undefined,
2329
2419
  updatedBy: 'agent',
2330
2420
  });
@@ -2669,6 +2759,56 @@ export function createWorkplanRuntime(ctx, options = {}) {
2669
2759
  maxAttempts: autoResumeAttemptCap(options.autoResumeMaxAttempts),
2670
2760
  },
2671
2761
  };
2762
+ /**
2763
+ * [1.12.0] 自动派发:计划生成后立即以 async 方式开跑。
2764
+ *
2765
+ * 与 `dsh_workplan_dispatch(mode:"async")` 走同一条 `dispatchPlan` 路径,
2766
+ * 区别只在「启动」是计划落地后的确定性动作,而不是模型的一次额外调用:
2767
+ * - 独立 AbortController:回合结束不会杀掉后台执行;
2768
+ * - 结果消息由 `finishRound` 写入,刷新后仍可见;
2769
+ * - 失败只记录错误,不把「派发失败」伪装成「计划生成失败」。
2770
+ */
2771
+ function startAutoDispatch(record, session, agent) {
2772
+ const controller = new AbortController();
2773
+ record.abortDispatch = (reason) => {
2774
+ if (!controller.signal.aborted) {
2775
+ controller.abort(new PlanError(`计划已取消:${reason}`, 'CANCELLED'));
2776
+ }
2777
+ };
2778
+ const roundOptions = {
2779
+ agent,
2780
+ modelSelection: record.modelSelection,
2781
+ cwd: session.header?.cwd ?? options.cwd,
2782
+ conversationContext: record.conversationContext ?? '',
2783
+ };
2784
+ record.dispatchStartedAt = Date.now();
2785
+ record.dispatchPromise = dispatchPlan(ctx, record, {
2786
+ ...roundOptions,
2787
+ signal: controller.signal,
2788
+ childTimeoutMs: limits.childTimeoutMs,
2789
+ idleTimeoutMs: limits.idleTimeoutMs,
2790
+ totalTimeoutMs: limits.totalTimeoutMs,
2791
+ maxResumes: limits.maxResumes,
2792
+ strictEvidence: options.strictEvidence,
2793
+ }).finally(() => {
2794
+ record.dispatchPromise = null;
2795
+ record.dispatchStartedAt = null;
2796
+ record.abortDispatch = null;
2797
+ });
2798
+ record.dispatchPromise
2799
+ .then(() => {
2800
+ finishRound(record, session);
2801
+ state.records.set(session.id, record);
2802
+ armAutoResume(record, session, roundOptions);
2803
+ })
2804
+ .catch((error) => {
2805
+ pushRecordError(record, error);
2806
+ finishRound(record, session);
2807
+ state.records.set(session.id, record);
2808
+ armAutoResume(record, session, roundOptions);
2809
+ });
2810
+ }
2811
+ state.startAutoDispatch = startAutoDispatch;
2672
2812
  async function onPreStep(payload, next) {
2673
2813
  let downstream;
2674
2814
  try {
@@ -3362,8 +3502,14 @@ export function createWorkplanRuntime(ctx, options = {}) {
3362
3502
  else if (Number(book.attempt ?? 0) > 0)
3363
3503
  book.noProgressRounds = Number(book.noProgressRounds ?? 0) + 1;
3364
3504
  book.doneBefore = done;
3365
- const pending = statuses.filter((item) => item?.status === 'pending').length;
3366
- const blocked = statuses.filter((item) => item?.status === 'blocked').length;
3505
+ /*
3506
+ * [1.12.0] 只数仍参与调度的行(T11):replanned 旧行保持 status='pending'
3507
+ * 只为追溯,把它们算进 pending 会让「live 全 done」的计划也排一次续跑,
3508
+ * 那一轮什么都不会派发,还会往 errors 里写一条误导性的停止行。
3509
+ */
3510
+ const liveCounts = liveResumeCounts(statuses);
3511
+ const pending = liveCounts.pending;
3512
+ const blocked = liveCounts.blocked;
3367
3513
  /*
3368
3514
  * [1.10.4 / D6] 正常完成的计划不许留「停止」噪音。
3369
3515
  *
@@ -3407,7 +3553,7 @@ export function createWorkplanRuntime(ctx, options = {}) {
3407
3553
  }].slice(-10);
3408
3554
  if (decision.action !== 'schedule') {
3409
3555
  /*
3410
- * 关闭开关时不写错误行:默认关闭不是一次「失败」,不该污染计划台账。
3556
+ * 显式关闭开关时不写错误行:关闭不是一次「失败」,不该污染计划台账。
3411
3557
  * 其余停止原因都要留痕,否则「为什么没有自动续跑」又变成考古。
3412
3558
  */
3413
3559
  if (decision.code !== 'AUTO_RESUME_DISABLED') {
@@ -5609,6 +5755,7 @@ async function maybePlan(ctx, state, payload, downstream, options) {
5609
5755
  modelSelection,
5610
5756
  signal: payload.signal,
5611
5757
  conversationContext,
5758
+ sourceMessageIds: human.map((message) => message.id).filter((id) => typeof id === 'string'),
5612
5759
  /*
5613
5760
  * Hand the real limits to the planner. Without them it had no idea the
5614
5761
  * round budget was 20 minutes and happily planned 15 heavy subtasks,
@@ -5676,16 +5823,33 @@ async function maybePlan(ctx, state, payload, downstream, options) {
5676
5823
  planMode,
5677
5824
  };
5678
5825
  state.records.set(session.id, record);
5826
+ /*
5827
+ * [1.12.0] Q2:默认自动派发。计划消息仍然先把计划完整展示出来,紧接着以
5828
+ * async 方式开跑——不是等所有子任务结束再显示(那才是旧的「没动静」)。
5829
+ * plan 模式不自动派发;显式 `autoDispatch:false` 保留 plan-first。
5830
+ */
5831
+ const autoDispatched = !planMode && options?.autoDispatch !== false;
5832
+ if (autoDispatched) {
5833
+ record.dispatchedAt = Date.now();
5834
+ state.startAutoDispatch?.(record, session, payload.agent);
5835
+ }
5679
5836
  /*
5680
5837
  * Plan-first: commit the plan with this step and let the main Agent call
5681
5838
  * 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.
5839
+ * child finished, which is exactly the "没动静/没完成" failure.
5840
+ *
5841
+ * [1.12.0] There is no tool guard that forces dispatch before other work —
5842
+ * `toolGuardReason` only denies dispatch in plan mode and `present` when the
5843
+ * plan is not ready. What actually enforces the ordering is the system
5844
+ * prompt, plus the turn-stopping gate steering at most twice per turn
5845
+ * (`STOP_STEER_LIMIT`); if the model still never dispatches, the next turn
5846
+ * cancels the stale plan ("计划已取消:上一轮未派发") and plans again.
5685
5847
  */
5686
5848
  const planMessage = buildPlanMessage(fullPlan, {
5687
5849
  totalBudgetMinutes: Math.max(1, Math.round(Number(options?.limits?.totalTimeoutMs ?? TOTAL_TIMEOUT_MS) / 60000)),
5688
5850
  maxResumes: Number(options?.limits?.maxResumes ?? MAX_PLAN_RESUMES),
5851
+ planMode,
5852
+ autoDispatched,
5689
5853
  });
5690
5854
  if (!planMode)
5691
5855
  return enterDecision(downstream, [planMessage]);