dsh-workplan 3.0.3 → 3.0.9

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.
@@ -25,10 +25,16 @@
25
25
  * 3. check — compare the plan (and the model's own restatement) against the
26
26
  * read-only anchor, and report every dropped hard element.
27
27
  *
28
- * Everything here is pure: no model call, no network, no clock, no filesystem.
29
- * The same inputs always produce the same audit, which makes the result
30
- * reproducible and unit-testable. A model-based reviewer would be *another*
31
- * opinion, not evidence — so it is deliberately not part of this path.
28
+ * Almost everything here is pure: no model call, no network, no filesystem.
29
+ * The audit functions always produce the same result for the same inputs,
30
+ * which makes them reproducible and unit-testable. A model-based reviewer
31
+ * would be *another* opinion, not evidence — so it is deliberately not part
32
+ * of this path.
33
+ *
34
+ * The one deliberate exception is the clarify gate (auditClarifyNeed): it
35
+ * keeps a small in-memory round counter per session with a wall-clock TTL so
36
+ * the gate cannot ask the user the same class of question forever (see
37
+ * CLARIFY_GATE_MAX_ROUNDS below). The audit stages themselves stay pure.
32
38
  *
33
39
  * Failure policy (why not everything blocks)
34
40
  * ------------------------------------------
@@ -568,7 +574,7 @@ export function resolvePronounAntecedentInline(token, taskText) {
568
574
  * C4 missing UI object — a display change (折叠/展开/按钮…) that names no surface
569
575
  * (左侧栏/截图/插件…), so any implementation would be a guess.
570
576
  */
571
- export function auditClarifyNeed(taskText, conversationContext = '') {
577
+ function auditClarifyNeedRules(taskText, conversationContext = '') {
572
578
  const text = String(taskText ?? '').trim();
573
579
  const conversation = String(conversationContext ?? '');
574
580
  if (!text)
@@ -625,6 +631,79 @@ export function auditClarifyNeed(taskText, conversationContext = '') {
625
631
  }
626
632
  return { needed: false, rule: '', reason: '', question: '' };
627
633
  }
634
+ /* ------------------------------------------------------------------------ */
635
+ /* [3.0.2] 澄清闸轮次上限:同一会话连问 CLARIFY_GATE_MAX_ROUNDS 轮后放行 */
636
+ /* ------------------------------------------------------------------------ */
637
+ /**
638
+ * [3.0.2] 同一会话最多向用户发起 CLARIFY_GATE_MAX_ROUNDS 轮澄清提问。
639
+ *
640
+ * 背景:澄清闸(runtime 规划前拦截 + validatePlanContext 的 CLARIFY 错误)
641
+ * 对判定永远成立的任务会无限「问一句→用户补一点→还是缺→再问一句」,
642
+ * 计划永远进不来。达到上限后,该会话后续 auditClarifyNeed 一律放行
643
+ * (needed:false),把任务交还规划路径,由规划器按 assumption 显式标注
644
+ * 推进,而不是把会话钉死在提问环里。
645
+ */
646
+ export const CLARIFY_GATE_MAX_ROUNDS = 2;
647
+ /** 保守自愈:距上次触发超过 30 分钟视为新一轮会话目标,计数自动归零。 */
648
+ const CLARIFY_ROUNDS_TTL_MS = 30 * 60 * 1000;
649
+ /** 调用方未提供 sessionId 时的共享计数键。 */
650
+ const DEFAULT_CLARIFY_SESSION = '__default__';
651
+ const clarifyRounds = new Map();
652
+ /*
653
+ * 时钟可注入(测试用)。生产固定为 Date.now()。
654
+ * 说明:宿主 runtime 目前不传 sessionId(runtime.ts 归并行维护),因此
655
+ * 生产上所有会话共享默认键 + 30 分钟 TTL 自愈;若宿主侧能 hook 「会话
656
+ * 开始新规划」的时机,应调用 resetClarifyRounds(sessionId) 立即清零,
657
+ * 而不是等 30 分钟 TTL。
658
+ */
659
+ let clarifyGateClock = () => Date.now();
660
+ /** 测试专用:注入/恢复澄清闸时钟(不传参数则恢复真实时钟)。 */
661
+ export function __setClarifyGateClockForTests(clock) {
662
+ clarifyGateClock = clock ?? (() => Date.now());
663
+ }
664
+ /**
665
+ * 清空指定会话的澄清轮次计数。
666
+ *
667
+ * 意图调用时机:「会话开始新规划」的可感知点(新任务锚点落进规划器)。
668
+ * 当前宿主尚未 hook 该点(runtime.ts 不在本文件维护范围内),所以生产上
669
+ * 依赖 30 分钟 TTL 自愈;宿主一旦能感知规划起点,应调用本函数立即清零。
670
+ */
671
+ export function resetClarifyRounds(sessionId) {
672
+ clarifyRounds.delete(String(sessionId ?? '').trim() || DEFAULT_CLARIFY_SESSION);
673
+ }
674
+ /**
675
+ * [3.0.2] 澄清判定对外唯一入口:规则判定 + 轮次上限。
676
+ *
677
+ * - 规则未命中(含空文本):纯透传,不计数;
678
+ * - 规则命中且轮次未达上限:计数 +1 并原样返回 needed:true;
679
+ * - 同一会话 30 分钟内已触发 CLARIFY_GATE_MAX_ROUNDS 轮:返回
680
+ * needed:false(放行进入规划),不再计数、不刷新时间戳——「被上限挡住」
681
+ * 不算一次触发,TTL 自上次真实提问起算。
682
+ */
683
+ export function auditClarifyNeed(taskText, conversationContext = '', sessionId = '') {
684
+ const verdict = auditClarifyNeedRules(taskText, conversationContext);
685
+ if (!verdict.needed)
686
+ return verdict;
687
+ const key = String(sessionId ?? '').trim() || DEFAULT_CLARIFY_SESSION;
688
+ const now = clarifyGateClock();
689
+ let entry = clarifyRounds.get(key);
690
+ if (entry && now - entry.lastAt > CLARIFY_ROUNDS_TTL_MS) {
691
+ clarifyRounds.delete(key);
692
+ entry = undefined;
693
+ }
694
+ if (entry && entry.count >= CLARIFY_GATE_MAX_ROUNDS) {
695
+ return { needed: false, rule: '', reason: '', question: '' };
696
+ }
697
+ clarifyRounds.set(key, { count: (entry?.count ?? 0) + 1, lastAt: now });
698
+ // 顺手清扫其他会话的过期条目,避免长进程里 Map 只增不减。
699
+ if (clarifyRounds.size > 16) {
700
+ for (const [otherKey, other] of clarifyRounds) {
701
+ if (now - other.lastAt > CLARIFY_ROUNDS_TTL_MS)
702
+ clarifyRounds.delete(otherKey);
703
+ }
704
+ }
705
+ return verdict;
706
+ }
628
707
  /**
629
708
  * Split one clause into candidate noun phrases.
630
709
  *
@@ -1211,7 +1290,7 @@ export function validatePlanContext(plan, context = {}) {
1211
1290
  * [P0-2c] Missing inputs must stop the plan before any department agent runs:
1212
1291
  * MS2 T05-04/09/13/20 were all planned and dispatched with the key input absent.
1213
1292
  */
1214
- const clarify = auditClarifyNeed(context.taskText ?? audit.anchor?.text ?? '', context.conversationContext ?? '');
1293
+ const clarify = auditClarifyNeed(context.taskText ?? audit.anchor?.text ?? '', context.conversationContext ?? '', context.sessionId ?? '');
1215
1294
  if (clarify.needed) {
1216
1295
  errors.push('CLARIFY: ' + clarify.reason + '(规则 ' + clarify.rule + ')');
1217
1296
  }
@@ -3,8 +3,8 @@
3
3
  *
4
4
  * 单一事实源:两条会话固定文案、部门任务质量要求、极简任务硬门槛、专家精简
5
5
  * JSON 汇报、部门负责人精简 JSON 汇总。渲染函数与校验函数同源,保证提示词里
6
- * 写的规则与门禁实际执行的规则不可能分叉(与 2.x 的 comm-format / three-phase
7
- * 同一哲学)。
6
+ * 写的规则与门禁实际执行的规则不可能分叉(与 2.x 的 comm-format / three-phase、
7
+ * 3.0.8 的 five-step 同一哲学)。
8
8
  *
9
9
  * 纯函数、零依赖(不 import plan.ts,避免循环依赖),可被 host/plan/runtime/
10
10
  * llm-rules 与测试同口径消费。
@@ -123,24 +123,42 @@ export const MIN_ATOMIC_TASK_CHARS = 8;
123
123
  * 并列/多目标的强信号词。命中 1 个以上即视为「一个任务里塞了多件事」。
124
124
  * 只收强信号(明显的并列连词与小标题分隔),不收「和」这类高频虚词,
125
125
  * 避免把正常表述误判成多任务。
126
+ *
127
+ * [3.0.2] 补齐「并/然后/接着」:子 Agent 的任务书常写「改 A 并改 B」「先备份
128
+ * 然后上传」这类口语并列,旧词表全漏(英文盲区事故:英文句点 + 英文 then
129
+ * 都不在判据里,复合任务被当单句放行)。「并且」已含「并」,报错文案按
130
+ * 长词优先去重。
126
131
  */
127
132
  const MULTI_GOAL_MARKERS = Object.freeze([
128
- '并且', '同时', '另外', '还要', '以及', '分别', '顺便',
133
+ '并且', '同时', '另外', '还要', '以及', '分别', '顺便', '并', '然后', '接着',
129
134
  ]);
130
- /** 句末终止符:原子任务必须是单句。 */
131
- const SENTENCE_TERMINATORS = [new RegExp('[。!?!?]', 'g')];
135
+ /**
136
+ * [3.0.2] 「再」只在两个动作之间当连词时才算并列信号(「先备份再修改」)。
137
+ * 不再/再次/再三/再现/再也不/要再 等副词用法不算——「不要再等待」不会被误伤。
138
+ * 若后续实测「再」的误判率仍偏高,按用户裁决可仅保留 并/然后/接着 并删除
139
+ * 本规则。
140
+ */
141
+ const ZAI_CONJUNCTION_RE = /(?<![不未莫无勿别一要])再(?![次三现也])/;
142
+ /**
143
+ * 句末终止符:原子任务必须是单句。
144
+ * [3.0.2] 英文句点 `.` 计入,但只认「后跟空白或文本结尾」的句读——文件名
145
+ * (a.ts)、版本号(1.12.0)、省略号(...)里的点不算句子分隔。
146
+ */
147
+ const SENTENCE_TERMINATORS = [new RegExp('[。!?!?]|\\.(?:\\s|$)', 'g')];
132
148
  /**
133
149
  * 极简任务硬门槛(用户要求 5,用户裁决 A:不满足即拒绝派发并强制拆小)。
134
150
  *
135
151
  * 判据全部可机械复算,不看语义:
136
152
  * 1) 非空且长度在 8–300 字符之间;
137
- * 2) 只有一句话(不出现第二个句末标点,不含分号分句);
138
- * 3) 不含并列强信号词(并且/同时/另外/还要/以及/分别/顺便);
153
+ * 2) 只有一句话(不出现第二个句末标点——含英文句点 `.`,不含分号分句);
154
+ * 3) 不含并列强信号词(并且/并/同时/另外/还要/以及/分别/顺便/然后/接着,
155
+ * 以及两动作之间的连词「再」);
139
156
  * 4) 必须带非空的质量要求(用户要求 6:交代清楚成果必须达到的要求和质量)。
140
157
  *
141
158
  * 返回的 hint 是可直接照做的拆小指令,不是一句「不合格」。
142
159
  */
143
160
  export function checkAtomicAssignment(task, qualityRequirements) {
161
+ const rawLength = String(task ?? '').trim().length;
144
162
  const text = String(task ?? '').replace(/\s+/g, ' ').trim();
145
163
  if (text.length < MIN_ATOMIC_TASK_CHARS) {
146
164
  return {
@@ -154,7 +172,9 @@ export function checkAtomicAssignment(task, qualityRequirements) {
154
172
  return {
155
173
  ok: false,
156
174
  code: 'DELEGATE_TASK_NOT_ATOMIC',
157
- error: `分到的任务太长(${text.length} 字符 > ${MAX_ATOMIC_TASK_CHARS}),不是 1+1=2 的单项任务。`,
175
+ // [3.0.2] 如实报告截断后实际长度:调用方(llm-rules truncate(1500))先截断
176
+ // 再送检,这里的数字是被判定文本的真实长度,不是原始输入的长度。
177
+ error: `分到的任务太长(截断后实际 ${rawLength} 字符 > ${MAX_ATOMIC_TASK_CHARS}),不是 1+1=2 的单项任务。`,
158
178
  hint: '按「一个目标 / 一个主产物 / 一项可独立验收」拆成多条;每条只保留一个动作,其余另起一条。',
159
179
  };
160
180
  }
@@ -179,11 +199,15 @@ export function checkAtomicAssignment(task, qualityRequirements) {
179
199
  };
180
200
  }
181
201
  const hit = MULTI_GOAL_MARKERS.filter((marker) => text.includes(marker));
182
- if (hit.length > 0) {
202
+ // 「并且」与「并」同命中时只报长词,报错文案不重复列同一个信号。
203
+ const markers = hit.filter((marker) => !hit.some((other) => other !== marker && other.includes(marker)));
204
+ if (ZAI_CONJUNCTION_RE.test(text))
205
+ markers.push('再');
206
+ if (markers.length > 0) {
183
207
  return {
184
208
  ok: false,
185
209
  code: 'DELEGATE_TASK_NOT_ATOMIC',
186
- error: `分到的任务含并列词「${hit.join('、')}」,说明一个任务里有多件事。`,
210
+ error: `分到的任务含并列词「${markers.join('、')}」,说明一个任务里有多件事。`,
187
211
  hint: '把并列词前后的内容各拆成一条独立任务,每条只做一个动作。',
188
212
  };
189
213
  }
@@ -202,6 +226,14 @@ export function checkAtomicAssignment(task, qualityRequirements) {
202
226
  /* ========================================================================== */
203
227
  /** 单个汇报数组的条数上限:精简的量化口径。 */
204
228
  export const MAX_REPORT_ITEMS = 6;
229
+ /**
230
+ * [3.0.6][第 3 批③] sources(部门汇总「覆盖的专家汇报」)专用上限。
231
+ * 死锁修复:复杂任务按用户裁决 D1/D2 强制 ≥8 名专家(上限 12),而 sources
232
+ * 必须覆盖全部已派发专家——若与其他数组共用 6 条上限,7–12 人的部门永远
233
+ * 交不出合法汇总(覆盖诚实要求 vs 精简上限互相矛盾)。覆盖是硬要求,
234
+ * 故 sources 单独放宽到 16(≥ 复杂任务 12 人上限 + 余量),其余数组仍 6 条。
235
+ */
236
+ export const MAX_SOURCES_ITEMS = 16;
205
237
  /** 单条汇报文本的字符上限。 */
206
238
  export const MAX_REPORT_ITEM_CHARS = 200;
207
239
  /** 专家汇报的四个必填字段(与用户要求 7 的四个方向一一对应)。 */
@@ -311,8 +343,9 @@ function checkListField(container, name, violations, options) {
311
343
  if (lines.length < options.minItems) {
312
344
  violations.push(`${name} 至少 ${options.minItems} 条非空内容,当前 ${lines.length} 条`);
313
345
  }
314
- if (lines.length > MAX_REPORT_ITEMS) {
315
- violations.push(`${name} 最多 ${MAX_REPORT_ITEMS} 条(精简要求),当前 ${lines.length} 条,请合并去重`);
346
+ const maxItems = options.maxItems ?? MAX_REPORT_ITEMS;
347
+ if (lines.length > maxItems) {
348
+ violations.push(`${name} 最多 ${maxItems} 条(精简要求),当前 ${lines.length} 条,请合并去重`);
316
349
  }
317
350
  for (const line of lines) {
318
351
  if (line.length > MAX_REPORT_ITEM_CHARS) {
@@ -340,7 +373,7 @@ function checkListField(container, name, violations, options) {
340
373
  /**
341
374
  * 校验专家精简 JSON 汇报(用户要求 7)。
342
375
  *
343
- * 只做结构/精简判定,不判语义真伪(诚信由 F9 与三阶段门禁兜底)。
376
+ * 只做结构/精简判定,不判语义真伪(诚信由 F9 与五步证据门禁兜底)。
344
377
  */
345
378
  export function checkExpertReport(report) {
346
379
  if (!report || typeof report !== 'object' || Array.isArray(report)) {
@@ -377,7 +410,7 @@ export function checkDepartmentSummary(summary, expectedExperts = []) {
377
410
  checkListField(container, 'keyResults', violations, { minItems: 1, dedupeAcross: ['keyInfo', 'importantInfo'] });
378
411
  checkListField(container, 'keyInfo', violations, { minItems: 0, dedupeAcross: ['keyResults', 'importantInfo'] });
379
412
  checkListField(container, 'importantInfo', violations, { minItems: 0, dedupeAcross: ['keyResults', 'keyInfo'] });
380
- const covered = checkListField(container, 'sources', violations, { minItems: 0 });
413
+ const covered = checkListField(container, 'sources', violations, { minItems: 0, maxItems: MAX_SOURCES_ITEMS });
381
414
  if (expectedExperts.length > 0) {
382
415
  const joined = covered.join('\n').toLowerCase();
383
416
  const missing = expectedExperts.filter((member) => member.trim() !== '' && !joined.includes(member.trim().toLowerCase()));
@@ -420,7 +453,7 @@ export function renderDepartmentSummarySpec() {
420
453
  ' "sources": ["专家名:一句关键成果"]',
421
454
  ' }',
422
455
  ...DEPARTMENT_SUMMARY_FIELDS.map((field) => `- ${field.name}(${field.label}):${field.description}`),
423
- `- 每个数组最多 ${MAX_REPORT_ITEMS} 条、每条最多 ${MAX_REPORT_ITEM_CHARS} 字符;sources 必须覆盖本部门全部已派发专家,同一信息只能出现一次。`,
456
+ `- keyResults/keyInfo/importantInfo 每个数组最多 ${MAX_REPORT_ITEMS} 条、每条最多 ${MAX_REPORT_ITEM_CHARS} 字符;sources 最多 ${MAX_SOURCES_ITEMS} 条(不受 6 条精简上限约束——必须逐人覆盖本部门全部已派发专家,覆盖是诚实硬要求),同一信息只能出现一次。`,
424
457
  '- 门禁:缺 departmentSummary、字段缺失、未覆盖全部专家、或出现重复项,结果一律退回重交(DEPARTMENT_SUMMARY_INVALID / DEPARTMENT_SUMMARY_NOT_CONCISE)。',
425
458
  ].join('\n');
426
459
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-workplan",
3
- "version": "3.0.3",
3
+ "version": "3.0.9",
4
4
  "description": "Automatic task decomposition, real department subagents, and a responsive workplan dashboard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -53,8 +53,7 @@
53
53
  "scripts/repair-malformed-user-messages.mjs"
54
54
  ],
55
55
  "engines": {
56
- "node": ">=22",
57
- "dsh": ">=0.2.2-rc.3"
56
+ "node": ">=22"
58
57
  },
59
58
  "dsh": {
60
59
  "bundle": {
@@ -69,6 +69,66 @@ const APPROVAL_PATTERNS: Array<{ re: RegExp; label: string }> = [
69
69
  },
70
70
  ]
71
71
 
72
+ /*
73
+ * [3.0.2] 命中候选的语境排除:否定 / 引用 / 规章制度转述。
74
+ *
75
+ * 正则只看字面,两种常见文本会被误按:
76
+ * 1. 否定句——「不用经用户认可再执行,直接干」:用户恰恰在**取消**门槛,
77
+ * 字面却完整命中「经…认可再…」;
78
+ * 2. 引用/转述——用户粘贴规章制度原文(「制度规定:须经用户批准后再执行」)
79
+ * 或把门槛语当引文讨论,不是在给自己的任务设门槛。
80
+ *
81
+ * 排除判据(命中位置之前约 40 字符窗口内,命中任一则该条候选不触发):
82
+ * - 否定词:不用/无需/不必/不需要/禁止/谈不上;单字 勿/别 须紧贴命中
83
+ * (6 字内且无句断),避免「识别/分别/级别」里的「别」误伤;
84
+ * - 引号包裹:「」“”‘’以及直引号成对出现、且命中片段位于引号内;
85
+ * - 转述字样:原文/制度/规定/条款。
86
+ * 窗口只回看、不越过句读推断语义——拿不准时维持原判定(宁漏勿冤的
87
+ * 方向对漏判更有利:漏判只是回到默认自动派发,误判才会把普通任务按住)。
88
+ */
89
+ const NEGATION_WORDS: readonly string[] = Object.freeze(['不用', '无需', '不必', '不需要', '禁止', '谈不上'])
90
+ /** 单字否定必须紧贴命中(其后 ≤6 字即命中、中间无句末符),否则视为普通用字。 */
91
+ const SINGLE_CHAR_NEGATION = /[勿别][^。;!?\n]{0,6}$/
92
+ /** 用户转述规章制度时的常见字样(40 字窗口内出现即视为引用而非本任务门槛)。 */
93
+ const RULES_QUOTE_WORDS: readonly string[] = Object.freeze(['原文', '制度', '规定', '条款'])
94
+ /** 成对引号:「」“”‘’为不对称对;直引号 " 与 ' 按出现次数奇偶判定。 */
95
+ const QUOTE_PAIRS: ReadonlyArray<readonly [string, string]> = Object.freeze([
96
+ ['「', '」'], ['“', '”'], ['‘', '’'], ['"', '"'], ["'", "'"],
97
+ ])
98
+
99
+ function hasNegationBefore(window: string): boolean {
100
+ for (const word of NEGATION_WORDS) {
101
+ if (window.includes(word)) return true
102
+ }
103
+ return SINGLE_CHAR_NEGATION.test(window)
104
+ }
105
+
106
+ function isInsideQuotes(text: string, index: number): boolean {
107
+ const before = text.slice(0, index)
108
+ for (const [open, close] of QUOTE_PAIRS) {
109
+ if (open === close) {
110
+ let count = 0
111
+ for (let position = 0; position < before.length; position += 1) {
112
+ if (before[position] === open) count += 1
113
+ }
114
+ if (count % 2 === 1) return true
115
+ } else if (before.lastIndexOf(open) > before.lastIndexOf(close)) {
116
+ return true
117
+ }
118
+ }
119
+ return false
120
+ }
121
+
122
+ /** 命中位置之前约 40 字符窗口内是否存在否定/引用/转述标记。 */
123
+ function hasExemptContext(text: string, index: number): boolean {
124
+ const window = text.slice(Math.max(0, index - 40), index)
125
+ if (hasNegationBefore(window)) return true
126
+ for (const word of RULES_QUOTE_WORDS) {
127
+ if (window.includes(word)) return true
128
+ }
129
+ return isInsideQuotes(text, index)
130
+ }
131
+
72
132
  function excerptOf(text: string, match: RegExpExecArray, max = 60): string {
73
133
  const start = Math.max(0, match.index - 6)
74
134
  const end = Math.min(text.length, match.index + match[0].length + 10)
@@ -85,9 +145,23 @@ export function detectApprovalGate(taskText: string): ApprovalGateVerdict {
85
145
  if (!text) return { held: false, matched: [], reason: '' }
86
146
  const matched: ApprovalGateMatch[] = []
87
147
  for (const { re, label } of APPROVAL_PATTERNS) {
88
- const found = re.exec(text)
89
- if (found) {
90
- matched.push({ label, excerpt: excerptOf(text, found) })
148
+ // [3.0.2] 逐处匹配并跳过带否定/引用语境的候选;同一条规则后一处干净命中
149
+ // 仍可触发(如先转述制度、再给自己的任务立门槛)。
150
+ const scanner = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`)
151
+ let found: RegExpExecArray | null
152
+ let hit: RegExpExecArray | null = null
153
+ while ((found = scanner.exec(text)) !== null) {
154
+ if (found[0] === '') {
155
+ scanner.lastIndex += 1
156
+ continue
157
+ }
158
+ if (!hasExemptContext(text, found.index)) {
159
+ hit = found
160
+ break
161
+ }
162
+ }
163
+ if (hit) {
164
+ matched.push({ label, excerpt: excerptOf(text, hit) })
91
165
  // 一条规则命中即可;继续跑完所有规则只为汇总证据,不去重(同义重复无害)。
92
166
  }
93
167
  }
package/src/client.ts CHANGED
@@ -226,6 +226,7 @@ window.__ModuleLoader__.load({
226
226
  "vizStageTitle": "分步进度",
227
227
  "vizOverall": "总体进度",
228
228
  "allPlansHint": "上面是当前各会话最新计划的合计;历史计划不在此汇总,下面每张卡片只统计本计划。",
229
+ "trimNotice": "计划数据过大,部分会话或明细已在服务端省略,当前仅展示子集;缩小范围或会话后再看完整数据。",
229
230
  "openHint": "打开左侧「任务进度」看完整安排。",
230
231
  "timeNegotiation": "执行时间(无时限)",
231
232
  "noTimeLimit": "部门负责人和全球顶尖专家执行无时限;预估仅供参考,不影响完成验收",
@@ -461,6 +462,7 @@ window.__ModuleLoader__.load({
461
462
  "vizStageTitle": "Step progress",
462
463
  "vizOverall": "Overall progress",
463
464
  "allPlansHint": "These totals cover the latest plan in each live session; older plans are not included. Each card below counts only its own plan.",
465
+ "trimNotice": "The plan data was too large, so some sessions or details were omitted on the server; only a subset is shown. Narrow the scope to see the full data.",
464
466
  "openHint": "Open “Task progress” on the left for the full plan.",
465
467
  "timeNegotiation": "Execution time (no limit)",
466
468
  "noTimeLimit": "Department leads and domain experts have no execution time limit; estimates are informational and do not affect acceptance",
@@ -1589,35 +1591,173 @@ window.__ModuleLoader__.load({
1589
1591
  if (!payload || payload.ok !== true) {
1590
1592
  throw new Error(asText(payload?.error) || '计划接口返回异常')
1591
1593
  }
1592
- return Array.isArray(payload.sessions) ? payload.sessions : []
1594
+ /*
1595
+ * [复审修复] 返回完整载荷,不再只回 sessions:服务端 2.5MB 上限
1596
+ * (runtime.ts MAX_PLANS_RESPONSE_BYTES + trimPlansPayload)裁剪时会置
1597
+ * truncated / omittedSessions / omittedDetail,旧实现把它们丢掉,看板
1598
+ * 静默少显示数据。向后兼容:调用方仍取 .sessions(数组)。
1599
+ *
1600
+ * omittedDetail 在服务端是挂在每个 session 项上的(trimPlansPayload
1601
+ * 里 sessions[].omittedDetail = true),顶层也可能有;两者都要看。
1602
+ */
1603
+ const sessions = Array.isArray(payload.sessions) ? payload.sessions : []
1604
+ const omittedSessions = typeof payload.omittedSessions === 'number'
1605
+ && Number.isFinite(payload.omittedSessions) ? payload.omittedSessions : 0
1606
+ const omittedDetail = payload.omittedDetail === true
1607
+ || sessions.some((item: any) => item && item.omittedDetail === true)
1608
+ return { sessions, truncated: payload.truncated === true, omittedSessions, omittedDetail }
1609
+ }
1610
+
1611
+ /*
1612
+ * [3.0.6][第 2 批] 看板轮询按会话共享。
1613
+ *
1614
+ * 旧实现里每个 TurnCard 都调用 usePlans(sessionId),各自 4 秒一次请求:
1615
+ * 一个会话有 30 张卡就是 30 请求/4s,服务端每次还要重建无内存记录的计划。
1616
+ * 现在同一 key(''=全部会话,或具体 sessionId)只有一个轮询器 + 一组订阅者,
1617
+ * 最后一个订阅者卸载时才停止;新订阅者立即拿到当前快照,不重复请求。
1618
+ */
1619
+ const planPolls = new Map<string, any>()
1620
+
1621
+ /* [复审修复] 单次轮询的挂死上限:到点按超时错误路径处理,绝不让 running 永真。 */
1622
+ const PLAN_POLL_TIMEOUT_MS = 15000
1623
+
1624
+ function emptyPlansState() {
1625
+ return {
1626
+ loading: true,
1627
+ sessions: [],
1628
+ truncated: false,
1629
+ omittedSessions: 0,
1630
+ omittedDetail: false,
1631
+ error: null,
1632
+ updatedAt: null,
1633
+ }
1593
1634
  }
1594
1635
 
1595
1636
  function usePlans(sessionId?: string) {
1596
- const [state, setState] = useState({ loading: true, sessions: [], error: null, updatedAt: null })
1597
- const load = useCallback(async (signal?: AbortSignal) => {
1598
- try {
1599
- const sessions = await fetchPlans(sessionId, signal)
1600
- if (signal?.aborted) return
1601
- setState({ loading: false, sessions, error: null, updatedAt: Date.now() })
1602
- } catch (error) {
1603
- if (signal?.aborted) return
1604
- setState((previous: any) => ({
1605
- ...previous,
1606
- loading: false,
1607
- error: error instanceof Error ? error.message : String(error),
1608
- }))
1609
- }
1610
- }, [sessionId])
1637
+ const key = sessionId || ''
1638
+ const [state, setState] = useState(() => planPolls.get(key)?.state ?? emptyPlansState())
1611
1639
  useEffect(() => {
1612
- const controller = new AbortController()
1613
- load(controller.signal)
1614
- const timer = setInterval(() => load(controller.signal), 4000)
1640
+ let entry = planPolls.get(key)
1641
+ if (!entry) {
1642
+ entry = {
1643
+ state: emptyPlansState(),
1644
+ listeners: new Set(),
1645
+ timer: null,
1646
+ controller: null,
1647
+ running: false,
1648
+ run: null,
1649
+ timedOut: false,
1650
+ onVisible: null,
1651
+ }
1652
+ planPolls.set(key, entry)
1653
+ }
1654
+ const listener = (next: any) => setState(next)
1655
+ entry.listeners.add(listener)
1656
+ setState(entry.state)
1657
+ if (!entry.run) {
1658
+ entry.run = async () => {
1659
+ if (entry.running) return
1660
+ /*
1661
+ * [复审修复] 后台标签页跳过本次轮询:interval 保留,回到前台后
1662
+ * 自然恢复;另有 visibilitychange 监听立即补一轮(见下方注册)。
1663
+ */
1664
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
1665
+ entry.running = true
1666
+ entry.timedOut = false
1667
+ const controller = new AbortController()
1668
+ entry.controller = controller
1669
+ /*
1670
+ * [复审修复] 15s 超时:一次挂死的请求不再让 entry.running 永真、
1671
+ * 看板永久冻结。卸载中止保持静默;超时中止走错误路径:
1672
+ * console.warn + 结束本次 running,interval 继续。
1673
+ *
1674
+ * 优先 AbortSignal.timeout + AbortSignal.any(无 JS 侧计时器句柄,
1675
+ * 不存在悬挂/句柄卫生问题);宿主运行时不支持 any() 时退回手动
1676
+ * setTimeout 控制器(等效实现),句柄挂在 entry 上,finally 与
1677
+ * 卸载 cleanup 双路清理——注意这里禁止 unref:这是收束类计时器
1678
+ * (tests/handle-policy.test.ts 契约),unref 会让 node 事件循环
1679
+ * 提前排空、看板错误路径永远到不了。
1680
+ */
1681
+ const anySignal = typeof (AbortSignal as any).any === 'function'
1682
+ && typeof (AbortSignal as any).timeout === 'function'
1683
+ let timeoutTimer: any = null
1684
+ const signal = anySignal
1685
+ ? (AbortSignal as any).any([controller.signal, (AbortSignal as any).timeout(PLAN_POLL_TIMEOUT_MS)])
1686
+ : (() => {
1687
+ timeoutTimer = setTimeout(() => {
1688
+ entry.timedOut = true
1689
+ controller.abort()
1690
+ }, PLAN_POLL_TIMEOUT_MS)
1691
+ return controller.signal
1692
+ })()
1693
+ entry.timeoutTimer = timeoutTimer
1694
+ try {
1695
+ const plansPayload = await fetchPlans(sessionId, signal)
1696
+ if (signal.aborted) return
1697
+ entry.state = {
1698
+ loading: false,
1699
+ sessions: plansPayload.sessions,
1700
+ truncated: plansPayload.truncated === true,
1701
+ omittedSessions: plansPayload.omittedSessions,
1702
+ omittedDetail: plansPayload.omittedDetail === true,
1703
+ error: null,
1704
+ updatedAt: Date.now(),
1705
+ }
1706
+ } catch (error) {
1707
+ /*
1708
+ * 静默条件:仅「主动中止(卸载/重入)」。超时的判定两路都要覆盖——
1709
+ * 手动兜底路径置了 entry.timedOut;AbortSignal.any 路径里超时只体现为
1710
+ * 组合 signal 被中止而 controller 没有(卸载恰好相反:controller 先中止)。
1711
+ */
1712
+ const timedOut = entry.timedOut === true
1713
+ || (signal.aborted === true && controller.signal.aborted === false)
1714
+ if (signal.aborted && !timedOut) return
1715
+ if (timedOut) {
1716
+ console.warn('[dsh-workplan] plans 轮询超时(15000ms),已结束本轮,下一轮继续', error)
1717
+ }
1718
+ entry.state = {
1719
+ ...entry.state,
1720
+ loading: false,
1721
+ error: error instanceof Error ? error.message : String(error),
1722
+ }
1723
+ } finally {
1724
+ if (timeoutTimer !== null) clearTimeout(timeoutTimer)
1725
+ entry.timeoutTimer = null
1726
+ entry.running = false
1727
+ entry.timedOut = false
1728
+ entry.controller = null
1729
+ entry.listeners.forEach((notify: any) => notify(entry.state))
1730
+ }
1731
+ }
1732
+ entry.run()
1733
+ entry.timer = setInterval(() => entry.run(), 4000)
1734
+ /*
1735
+ * [复审修复] 回到前台立即补一轮:后台期间 interval 触发的轮询
1736
+ * 全部被跳过,不补的话用户切回来最多干等一个周期。
1737
+ */
1738
+ entry.onVisible = () => {
1739
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
1740
+ entry.run?.()
1741
+ }
1742
+ }
1743
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
1744
+ document.addEventListener('visibilitychange', entry.onVisible)
1745
+ }
1746
+ }
1615
1747
  return () => {
1616
- controller.abort()
1617
- clearInterval(timer)
1748
+ entry.listeners.delete(listener)
1749
+ if (entry.listeners.size === 0) {
1750
+ if (entry.timer) clearInterval(entry.timer)
1751
+ if (entry.timeoutTimer) clearTimeout(entry.timeoutTimer)
1752
+ entry.controller?.abort()
1753
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
1754
+ document.removeEventListener('visibilitychange', entry.onVisible)
1755
+ }
1756
+ planPolls.delete(key)
1757
+ }
1618
1758
  }
1619
- }, [load])
1620
- return { ...state, reload: () => load() }
1759
+ }, [key, sessionId])
1760
+ return { ...state, reload: () => planPolls.get(key)?.run?.() }
1621
1761
  }
1622
1762
 
1623
1763
  function ErrorBanner({ message, onRetry, t }: any) {
@@ -3133,7 +3273,10 @@ window.__ModuleLoader__.load({
3133
3273
  const BACK_TOP_THRESHOLD = 200
3134
3274
 
3135
3275
  function Dashboard({ t }: any) {
3136
- const { sessions, error, loading, updatedAt, reload } = usePlans()
3276
+ const {
3277
+ sessions, error, loading, updatedAt, reload,
3278
+ truncated, omittedSessions, omittedDetail,
3279
+ } = usePlans()
3137
3280
  const [openSessionId, setOpenSessionId] = useState(null)
3138
3281
  const selectSession = useCallback((sessionId: string) => {
3139
3282
  if (!sessionId) return
@@ -3317,6 +3460,17 @@ window.__ModuleLoader__.load({
3317
3460
  h('button', { type: 'button', className: 'dsh-wp-button', onClick: reload, disabled: loading }, t('refresh')),
3318
3461
  ),
3319
3462
  error ? h(ErrorBanner, { message: error, onRetry: reload, t }) : null,
3463
+ /*
3464
+ * [复审修复] 服务端裁剪提示:载荷被 2.5MB 上限裁剪(truncated /
3465
+ * omittedSessions / omittedDetail 任一成立)时明确告知「展示为子集」,
3466
+ * 不再静默少显示数据。复用现有 degraded 横幅样式,不新增 CSS/依赖。
3467
+ */
3468
+ (truncated === true || Number(omittedSessions) > 0 || omittedDetail === true)
3469
+ ? h('div', {
3470
+ className: 'dsh-wp-banner dsh-wp-banner--degraded dsh-wp-trim-notice',
3471
+ role: 'status',
3472
+ }, t('trimNotice'))
3473
+ : null,
3320
3474
  activeSessions.length > 0 ? h('div', { className: 'dsh-wp-statbar', role: 'list' },
3321
3475
  h('div', { className: 'dsh-wp-stat dsh-wp-stat--tasks', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, activeSessions.length), h('div', { className: 'dsh-wp-stat-label' }, t('sessionCount'))),
3322
3476
  h('div', { className: 'dsh-wp-stat', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.total), h('div', { className: 'dsh-wp-stat-label' }, t('workItems'))),