dsh-workplan 1.9.1 → 1.10.6

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/host.js CHANGED
@@ -13,6 +13,7 @@ import { fileURLToPath } from 'node:url';
13
13
  */
14
14
  import { applyHardeningHeaders, cancelToolOutputSchema, createWorkplanRuntime, dispatchToolOutputSchema, plannerOutputSchema, statusToolOutputSchema, updateToolOutputSchema, } from './runtime.js';
15
15
  import { isRecord } from './plan.js';
16
+ import { autoResumeEnabledFrom } from './auto-resume.js';
16
17
  /*
17
18
  * [1.8.14] Identity of the modules this process actually loaded (N1).
18
19
  *
@@ -543,6 +544,27 @@ function createDispatchTool(runtime) {
543
544
  * short of editing the source, so any machine with slower subagents hit the
544
545
  * wall on every plan. These knobs let operations tune it without a rebuild.
545
546
  */
547
+ /**
548
+ * [1.10.4] 布尔开关:配置项优先,其次环境变量。
549
+ *
550
+ * 与 `numericSetting` 不同,显式 `false` 必须能被表达,所以先判 boolean;
551
+ * 环境变量只接受 1/true/yes/on,大小写不敏感。未配置时返回 `false`。
552
+ *
553
+ * [1.10.6] 注意:`autoResume` 已改用 `autoResumeEnabledFrom`(默认开启,
554
+ * 且 `0/false/no/off` 可以显式关闭)。本函数保留给「默认关闭」语义的开关。
555
+ */
556
+ function booleanSetting(configValue, envName) {
557
+ if (typeof configValue === 'boolean')
558
+ return configValue;
559
+ const raw = typeof process !== 'undefined' ? process.env?.[envName] : undefined;
560
+ if (raw === undefined || raw === '')
561
+ return false;
562
+ return /^(1|true|yes|on)$/i.test(String(raw).trim());
563
+ }
564
+ /** [1.10.6] 原样读取环境变量,供三态解析使用(未设置返回 undefined)。 */
565
+ function settingEnv(envName) {
566
+ return typeof process !== 'undefined' ? process.env?.[envName] : undefined;
567
+ }
546
568
  function numericSetting(configValue, envName) {
547
569
  if (configValue !== undefined && configValue !== null && configValue !== '') {
548
570
  const numeric = Number(configValue);
@@ -591,6 +613,13 @@ export function apply(ctx, config = {}) {
591
613
  idleTimeoutMs: numericSetting(config.idleTimeoutMs, 'DSH_WORKPLAN_IDLE_TIMEOUT_MS'),
592
614
  totalTimeoutMs: numericSetting(config.totalTimeoutMs, 'DSH_WORKPLAN_TOTAL_TIMEOUT_MS'),
593
615
  maxResumes: numericSetting(config.maxResumes, 'DSH_WORKPLAN_MAX_RESUMES'),
616
+ /*
617
+ * [1.10.6] 三态解析:显式配置 > 显式环境变量 > 默认开启。
618
+ * 旧实现用 `booleanSetting(..., false)`,未配置即等于关闭,于是「预算到点
619
+ * 自动续跑」这个能力在用户机器上从来没打开过(1h57m 空窗的直接原因)。
620
+ */
621
+ autoResume: autoResumeEnabledFrom(config.autoResume, settingEnv('DSH_WORKPLAN_AUTO_RESUME')),
622
+ autoResumeMaxAttempts: numericSetting(config.autoResumeMaxAttempts, 'DSH_WORKPLAN_AUTO_RESUME_MAX'),
594
623
  });
595
624
  ctx.effect(() => ctx.systemPrompt.section({
596
625
  name: 'dsh-workplan',
@@ -673,7 +702,7 @@ export function apply(ctx, config = {}) {
673
702
  }
674
703
  export const meta = {
675
704
  name,
676
- version: '1.9.1',
705
+ version: '1.10.6',
677
706
  promptOrder: PROMPT_ORDER,
678
707
  routes: ['/dsh-workplan/plans', '/dsh-workplan/vendor/chart.umd.js'],
679
708
  };
package/lib/plan.js CHANGED
@@ -1670,11 +1670,13 @@ export function applyResultStatuses(statuses, result) {
1670
1670
  continue;
1671
1671
  /*
1672
1672
  * A manually re-adjudicated status (durable `workplan-update`) must not be
1673
- * rolled back by an older result snapshot. Only comparable revisions are
1674
- * ordered; legacy entries without `revision` keep the old "last wins" rule.
1673
+ * rolled back by an older result snapshot — and the *same* snapshot must not
1674
+ * be applied twice. 1.9.1 skipped only `entry.revision < current.revision`,
1675
+ * so an equal revision was re-applied and bumped every row by one revision
1676
+ * on each replay (T1 实测:T1–T7 各 +1)。
1675
1677
  */
1676
1678
  if (Number.isInteger(entry.revision) && Number.isInteger(current.revision)
1677
- && Number(entry.revision) < Number(current.revision))
1679
+ && Number(entry.revision) <= Number(current.revision))
1678
1680
  continue;
1679
1681
  try {
1680
1682
  next = applyStatus(next, entry.subtaskId, {
@@ -1743,8 +1745,19 @@ export function applyStatus(statuses, subtaskId, patch) {
1743
1745
  next.finishedAt = patch.finishedAt;
1744
1746
  if (patch.summary !== undefined)
1745
1747
  next.summary = truncate(String(patch.summary), 3000);
1746
- if (patch.error !== undefined)
1748
+ if (patch.error !== undefined) {
1749
+ /*
1750
+ * [1.10.0] 显式清空 `error` 也属于一次「失败记录退场」:先留档再清空。
1751
+ *
1752
+ * 回放路径(`applyResultStatuses`)对 done 行传的是 `error: null`,如果这里
1753
+ * 只是把它抹掉,事故记录里「为什么这一行曾经没做完」就再也查不到了。
1754
+ */
1755
+ if (patch.error === null && typeof current.error === 'string' && current.error.trim() !== '') {
1756
+ next.lastError = current.error;
1757
+ next.lastErrorAt = Date.now();
1758
+ }
1747
1759
  next.error = patch.error === null ? null : truncate(String(patch.error), 2000);
1760
+ }
1748
1761
  if (patch.verification !== undefined) {
1749
1762
  if (!VERIFICATIONS.includes(patch.verification)) {
1750
1763
  throw new PlanError(`非法 verification:${String(patch.verification)}`, 'INVALID_VERIFICATION');
@@ -1769,6 +1782,20 @@ export function applyStatus(statuses, subtaskId, patch) {
1769
1782
  }
1770
1783
  if (patch.needs !== undefined)
1771
1784
  next.needs = readEvidenceNeeds(patch.needs);
1785
+ /*
1786
+ * [1.10.6] The files a retry refused to touch.
1787
+ *
1788
+ * A ceiling timeout can be retried once, but only when the artifacts the first
1789
+ * attempt landed are unchanged. When they did change, `runtime.ts` records
1790
+ * their refs here instead of overwriting them, so "why was there no retry"
1791
+ * stays answerable from the plan record alone.
1792
+ */
1793
+ if (patch.artifactConflict !== undefined) {
1794
+ next.artifactConflict = (Array.isArray(patch.artifactConflict) ? patch.artifactConflict : [])
1795
+ .slice(0, 8)
1796
+ .map((ref) => truncate(String(ref ?? ''), 300))
1797
+ .filter((ref) => ref !== '');
1798
+ }
1772
1799
  if (patch.blockedBy !== undefined) {
1773
1800
  next.blockedBy = (Array.isArray(patch.blockedBy) ? patch.blockedBy : [])
1774
1801
  .slice(0, 10)
@@ -1789,6 +1816,46 @@ export function applyStatus(statuses, subtaskId, patch) {
1789
1816
  next.progress = 100;
1790
1817
  if (next.finishedAt === null)
1791
1818
  next.finishedAt = Date.now();
1819
+ /*
1820
+ * [1.10.0] R-01:「完成」与「失败原因」不能同时成立。
1821
+ *
1822
+ * 1.9.1 及以前,done 分支根本不碰 `error`,而改判路径对非 blocked 传的是
1823
+ * `undefined`,被上面 1816 行解释成「保留旧值」。于是「预算用尽,等待续跑」
1824
+ * 这类上一轮的失败文本会永久留在一个 status=done 的行上,界面再无条件把它
1825
+ * 渲染成「卡住原因」——同一行同时写着「已完成」和「卡住了」,就是这次
1826
+ * 事故的同屏矛盾。
1827
+ *
1828
+ * 旧文本不丢弃,迁入 `lastError` 供审计;`error` 只描述「当前这一行为什么
1829
+ * 没做完」,完成的行没有这种原因。
1830
+ */
1831
+ if (typeof next.error === 'string' && next.error.trim() !== '') {
1832
+ next.lastError = next.error;
1833
+ next.lastErrorAt = Date.now();
1834
+ }
1835
+ /*
1836
+ * [1.10.2] 写侧补漏:显式传 `error` 的 done 也必须清空。
1837
+ *
1838
+ * 1.10.0/1.10.1 只在 `patch.error` 为 `undefined`/`null` 时清空,因此
1839
+ * `applyStatus(rows, id, { status: 'done', error: '...' })`(以及把子会话
1840
+ * result 原样回放的 `applyResultStatuses`)仍能把「完成 + 失败文本」写进
1841
+ * 持久化记录。读侧 `normaliseStatusEntry` 会在下发的载荷里清洗,界面看不到,
1842
+ * 但只要有任何消费者直接读 `record.statuses`(审计、导出、后续新增字段),
1843
+ * 这个不变量就又破了。这里与读侧使用同一条规则:旧文本只进 `lastError`。
1844
+ */
1845
+ next.error = null;
1846
+ next.completedBy = ['child', 'agent', 'system'].includes(patch.completedBy)
1847
+ ? patch.completedBy
1848
+ : (next.completedBy ?? next.updatedBy ?? 'system');
1849
+ if (next.attemptOutcome !== undefined && next.attemptOutcome !== null
1850
+ && next.attemptOutcome !== 'completed' && next.attemptOutcome !== 'manual') {
1851
+ next.priorOutcome = next.attemptOutcome;
1852
+ }
1853
+ next.attemptOutcome = patch.attemptOutcome
1854
+ ?? (next.completedBy === 'agent' ? 'manual' : 'completed');
1855
+ next.attemptEndedAt = patch.attemptEndedAt ?? Date.now();
1856
+ // [1.10.6] A finished row cannot also be "we refused to overwrite it".
1857
+ if (patch.artifactConflict === undefined)
1858
+ next.artifactConflict = undefined;
1792
1859
  }
1793
1860
  if (patch.status === 'pending') {
1794
1861
  /*
@@ -1821,10 +1888,16 @@ export function applyStatus(statuses, subtaskId, patch) {
1821
1888
  next.needs = undefined;
1822
1889
  if (patch.blockedBy === undefined)
1823
1890
  next.blockedBy = undefined;
1891
+ // [1.10.6] A conflict belongs to one attempt; a reset starts a new one.
1892
+ if (patch.artifactConflict === undefined)
1893
+ next.artifactConflict = undefined;
1824
1894
  }
1825
1895
  if (patch.status === 'in_progress') {
1826
1896
  if (next.startedAt === null)
1827
1897
  next.startedAt = Date.now();
1898
+ // [1.10.6] The retry of a conflicting row is itself the new attempt.
1899
+ if (patch.artifactConflict === undefined)
1900
+ next.artifactConflict = undefined;
1828
1901
  /*
1829
1902
  * [1.5.2] 「正在做」不允许自称 100%。
1830
1903
  *
@@ -1877,6 +1950,21 @@ export function normaliseStatusEntry(entry) {
1877
1950
  const source = entry ?? {};
1878
1951
  const status = isSubtaskStatus(source.status) ? source.status : 'pending';
1879
1952
  const progress = status === 'done' ? 100 : status === 'pending' ? 0 : clampProgress(source.progress);
1953
+ /*
1954
+ * [1.10.0] R-01 读侧兜底:历史脏数据在载荷层就要干净。
1955
+ *
1956
+ * 1.9.1 写下的记录里,被人工改判为 done 的行仍带着上一轮的失败文本。只修写
1957
+ * 入口不会让已经落盘的记录自愈,而状态只存在于会话事件日志里、不会重写,
1958
+ * 所以必须在每次派生载荷时把「done + error」拆成「done + lastError」,
1959
+ * 否则用户刷新一次就又能看到「已完成 + 卡住原因」。
1960
+ */
1961
+ const legacyError = typeof source.error === 'string' && source.error.trim() !== ''
1962
+ ? source.error
1963
+ : null;
1964
+ const error = status === 'done' ? null : legacyError;
1965
+ const lastError = status === 'done'
1966
+ ? (typeof source.lastError === 'string' && source.lastError !== '' ? source.lastError : legacyError)
1967
+ : (typeof source.lastError === 'string' ? source.lastError : null);
1880
1968
  return {
1881
1969
  ...source,
1882
1970
  subtaskId: stringOr(source.subtaskId, ''),
@@ -1890,7 +1978,8 @@ export function normaliseStatusEntry(entry) {
1890
1978
  startedAt: status === 'pending' ? null : numberOrNull(source.startedAt),
1891
1979
  finishedAt: status === 'pending' ? null : numberOrNull(source.finishedAt),
1892
1980
  summary: stringOr(source.summary, ''),
1893
- error: typeof source.error === 'string' ? source.error : null,
1981
+ error,
1982
+ ...(lastError ? { lastError } : {}),
1894
1983
  };
1895
1984
  }
1896
1985
  /**
@@ -1922,7 +2011,7 @@ export function normaliseStatuses(statuses) {
1922
2011
  * therefore never drag the plan's percentage up to where the cards say it is
1923
2012
  * finished — that was the “100% 但 11/12” contradiction users saw.
1924
2013
  */
1925
- export function deriveAggregates(statuses) {
2014
+ export function deriveAggregates(statuses, expectedTotal) {
1926
2015
  const departments = new Map();
1927
2016
  let done = 0;
1928
2017
  let blocked = 0;
@@ -1961,7 +2050,20 @@ export function deriveAggregates(statuses) {
1961
2050
  department.inProgress += 1;
1962
2051
  departments.set(item.department, department);
1963
2052
  }
1964
- const total = statuses.length;
2053
+ /*
2054
+ * [1.10.0] R-07:分母必须来自「计划定义」,不能是「实际有几行状态」。
2055
+ *
2056
+ * 1.9.1 的 `total = statuses.length`,而 I1 又只是拿它和自身比较(同义反复),
2057
+ * 于是构造出「定义 13 项、只写 5 行状态」就得到 5/5 = 100%(T3 反例 C16)。
2058
+ * 现在调用方把定义条数传进来:缺的行按 pending 计入总数,既不会把分母缩小,
2059
+ * 也不会凭空造出几行明细。
2060
+ */
2061
+ const defined = Number.isInteger(expectedTotal) && Number(expectedTotal) > 0
2062
+ ? Number(expectedTotal)
2063
+ : 0;
2064
+ const total = Math.max(statuses.length, defined);
2065
+ const missing = Math.max(0, total - statuses.length);
2066
+ pending += missing;
1965
2067
  const allDone = total > 0 && done === total;
1966
2068
  /*
1967
2069
  * [1.5.2] 加权进度在「未全部完成」时不得四舍五入成 100。
@@ -1991,9 +2093,9 @@ export function deriveAggregates(statuses) {
1991
2093
  * values share one array instance, so `stats`, `departments` and `statuses` in
1992
2094
  * a single payload cannot disagree.
1993
2095
  */
1994
- export function derivePlanSnapshot(raw) {
2096
+ export function derivePlanSnapshot(raw, expectedTotal) {
1995
2097
  const statuses = normaliseStatuses(raw);
1996
- const { stats, departments } = deriveAggregates(statuses);
2098
+ const { stats, departments } = deriveAggregates(statuses, expectedTotal);
1997
2099
  return { statuses, stats, departments };
1998
2100
  }
1999
2101
  /**
@@ -2020,8 +2122,23 @@ export function computeStats(statuses) {
2020
2122
  export function aggregateInvariantViolations(snapshot, phase) {
2021
2123
  const violations = [];
2022
2124
  const { statuses, stats, departments } = snapshot;
2023
- if (stats.total !== statuses.length) {
2024
- violations.push(`I1 stats.total=${stats.total} 与 statuses.length=${statuses.length} 不一致`);
2125
+ /*
2126
+ * [1.10.0] I1 改为「不得小于」,并新增 I12/I13。
2127
+ *
2128
+ * 旧 I1 是 `stats.total === statuses.length`——与产生它的表达式同义反复,
2129
+ * 永远成立,等于没检查(T3 实测 C16)。现在分母允许大于明细行数(缺行按
2130
+ * pending 计入),真正要禁止的是「分母比明细还小」这种把 100% 造出来的情形。
2131
+ * I12 封住本次事故的同屏矛盾:done 行不允许带 error。
2132
+ * I13 封住反过来的一侧:全部 done 却写着 progress<100。
2133
+ */
2134
+ if (stats.total < statuses.length) {
2135
+ violations.push(`I1 stats.total=${stats.total} 小于 statuses.length=${statuses.length}`);
2136
+ }
2137
+ if (stats.total > 0 && stats.done === stats.total && stats.progress !== 100) {
2138
+ violations.push(`I13 全部 ${stats.total} 项已 done,但 stats.progress=${stats.progress}`);
2139
+ }
2140
+ if (stats.done < stats.total && stats.progress >= 100) {
2141
+ violations.push(`I13 仅 ${stats.done}/${stats.total} 项 done,但 stats.progress=100`);
2025
2142
  }
2026
2143
  const counted = stats.done + stats.blocked + stats.inProgress + stats.pending;
2027
2144
  if (counted !== stats.total) {
@@ -2058,6 +2175,10 @@ export function aggregateInvariantViolations(snapshot, phase) {
2058
2175
  if (item.status === 'done' && item.progress !== 100) {
2059
2176
  violations.push(`I6 ${item.subtaskId} 是 done 但 progress=${item.progress}`);
2060
2177
  }
2178
+ /* [1.10.0] I12:「完成」与「卡住原因」不能同屏。 */
2179
+ if (item.status === 'done' && typeof item.error === 'string' && item.error.trim() !== '') {
2180
+ violations.push(`I12 ${item.subtaskId} 是 done 但仍带 error=${item.error.slice(0, 80)}`);
2181
+ }
2061
2182
  }
2062
2183
  const sums = { total: 0, done: 0, blocked: 0, inProgress: 0 };
2063
2184
  for (const department of departments) {
@@ -2245,6 +2366,18 @@ export function deliveryReadiness(snapshot, options = {}) {
2245
2366
  }
2246
2367
  const done = Number(snapshot?.stats?.done ?? 0);
2247
2368
  const total = Number(snapshot?.stats?.total ?? 0);
2369
+ /*
2370
+ * [1.10.1] DF-05(P0):分母对账必须同时作用在交付门上。
2371
+ *
2372
+ * 1.10.0 把 `stats.total` 改成了计划定义条数,但 `deliveryReadiness` 仍然只遍历
2373
+ * 实际存在的状态行——于是「定义 13 项、只写 5 行且全 done」会得到
2374
+ * `done=5 / total=13` 却 **ready=true**,present 门禁可放行只做了 5/13 的计划
2375
+ * (T10 实测 `[done=5,total=13,ready=True]`)。缺失的行就是没做完,必须算阻塞。
2376
+ */
2377
+ const missingRows = total - statuses.length;
2378
+ if (total > 0 && missingRows > 0) {
2379
+ blockers.push(`状态明细缺少 ${missingRows} 行(计划定义 ${total} 项,实际只写 ${statuses.length} 行):缺失项按未完成计`);
2380
+ }
2248
2381
  if (phase === 'cancelled' && (remaining.length > 0 || blockers.length > 0)) {
2249
2382
  blockers.unshift(`计划已取消但只完成 ${done}/${total}:取消只停止执行,不等于完成`);
2250
2383
  }