dsh-workplan 3.0.3 → 3.0.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.
@@ -54,6 +54,68 @@ const APPROVAL_PATTERNS = [
54
54
  label: '「认可后开始执行」',
55
55
  },
56
56
  ];
57
+ /*
58
+ * [3.0.2] 命中候选的语境排除:否定 / 引用 / 规章制度转述。
59
+ *
60
+ * 正则只看字面,两种常见文本会被误按:
61
+ * 1. 否定句——「不用经用户认可再执行,直接干」:用户恰恰在**取消**门槛,
62
+ * 字面却完整命中「经…认可再…」;
63
+ * 2. 引用/转述——用户粘贴规章制度原文(「制度规定:须经用户批准后再执行」)
64
+ * 或把门槛语当引文讨论,不是在给自己的任务设门槛。
65
+ *
66
+ * 排除判据(命中位置之前约 40 字符窗口内,命中任一则该条候选不触发):
67
+ * - 否定词:不用/无需/不必/不需要/禁止/谈不上;单字 勿/别 须紧贴命中
68
+ * (6 字内且无句断),避免「识别/分别/级别」里的「别」误伤;
69
+ * - 引号包裹:「」“”‘’以及直引号成对出现、且命中片段位于引号内;
70
+ * - 转述字样:原文/制度/规定/条款。
71
+ * 窗口只回看、不越过句读推断语义——拿不准时维持原判定(宁漏勿冤的
72
+ * 方向对漏判更有利:漏判只是回到默认自动派发,误判才会把普通任务按住)。
73
+ */
74
+ const NEGATION_WORDS = Object.freeze(['不用', '无需', '不必', '不需要', '禁止', '谈不上']);
75
+ /** 单字否定必须紧贴命中(其后 ≤6 字即命中、中间无句末符),否则视为普通用字。 */
76
+ const SINGLE_CHAR_NEGATION = /[勿别][^。;!?\n]{0,6}$/;
77
+ /** 用户转述规章制度时的常见字样(40 字窗口内出现即视为引用而非本任务门槛)。 */
78
+ const RULES_QUOTE_WORDS = Object.freeze(['原文', '制度', '规定', '条款']);
79
+ /** 成对引号:「」“”‘’为不对称对;直引号 " 与 ' 按出现次数奇偶判定。 */
80
+ const QUOTE_PAIRS = Object.freeze([
81
+ ['「', '」'], ['“', '”'], ['‘', '’'], ['"', '"'], ["'", "'"],
82
+ ]);
83
+ function hasNegationBefore(window) {
84
+ for (const word of NEGATION_WORDS) {
85
+ if (window.includes(word))
86
+ return true;
87
+ }
88
+ return SINGLE_CHAR_NEGATION.test(window);
89
+ }
90
+ function isInsideQuotes(text, index) {
91
+ const before = text.slice(0, index);
92
+ for (const [open, close] of QUOTE_PAIRS) {
93
+ if (open === close) {
94
+ let count = 0;
95
+ for (let position = 0; position < before.length; position += 1) {
96
+ if (before[position] === open)
97
+ count += 1;
98
+ }
99
+ if (count % 2 === 1)
100
+ return true;
101
+ }
102
+ else if (before.lastIndexOf(open) > before.lastIndexOf(close)) {
103
+ return true;
104
+ }
105
+ }
106
+ return false;
107
+ }
108
+ /** 命中位置之前约 40 字符窗口内是否存在否定/引用/转述标记。 */
109
+ function hasExemptContext(text, index) {
110
+ const window = text.slice(Math.max(0, index - 40), index);
111
+ if (hasNegationBefore(window))
112
+ return true;
113
+ for (const word of RULES_QUOTE_WORDS) {
114
+ if (window.includes(word))
115
+ return true;
116
+ }
117
+ return isInsideQuotes(text, index);
118
+ }
57
119
  function excerptOf(text, match, max = 60) {
58
120
  const start = Math.max(0, match.index - 6);
59
121
  const end = Math.min(text.length, match.index + match[0].length + 10);
@@ -70,9 +132,23 @@ export function detectApprovalGate(taskText) {
70
132
  return { held: false, matched: [], reason: '' };
71
133
  const matched = [];
72
134
  for (const { re, label } of APPROVAL_PATTERNS) {
73
- const found = re.exec(text);
74
- if (found) {
75
- matched.push({ label, excerpt: excerptOf(text, found) });
135
+ // [3.0.2] 逐处匹配并跳过带否定/引用语境的候选;同一条规则后一处干净命中
136
+ // 仍可触发(如先转述制度、再给自己的任务立门槛)。
137
+ const scanner = new RegExp(re.source, re.flags.includes('g') ? re.flags : `${re.flags}g`);
138
+ let found;
139
+ let hit = null;
140
+ while ((found = scanner.exec(text)) !== null) {
141
+ if (found[0] === '') {
142
+ scanner.lastIndex += 1;
143
+ continue;
144
+ }
145
+ if (!hasExemptContext(text, found.index)) {
146
+ hit = found;
147
+ break;
148
+ }
149
+ }
150
+ if (hit) {
151
+ matched.push({ label, excerpt: excerptOf(text, hit) });
76
152
  // 一条规则命中即可;继续跑完所有规则只为汇总证据,不去重(同义重复无害)。
77
153
  }
78
154
  }
package/lib/client.js CHANGED
@@ -224,6 +224,7 @@ window.__ModuleLoader__.load({
224
224
  "vizStageTitle": "分步进度",
225
225
  "vizOverall": "总体进度",
226
226
  "allPlansHint": "上面是当前各会话最新计划的合计;历史计划不在此汇总,下面每张卡片只统计本计划。",
227
+ "trimNotice": "计划数据过大,部分会话或明细已在服务端省略,当前仅展示子集;缩小范围或会话后再看完整数据。",
227
228
  "openHint": "打开左侧「任务进度」看完整安排。",
228
229
  "timeNegotiation": "执行时间(无时限)",
229
230
  "noTimeLimit": "部门负责人和全球顶尖专家执行无时限;预估仅供参考,不影响完成验收",
@@ -459,6 +460,7 @@ window.__ModuleLoader__.load({
459
460
  "vizStageTitle": "Step progress",
460
461
  "vizOverall": "Overall progress",
461
462
  "allPlansHint": "These totals cover the latest plan in each live session; older plans are not included. Each card below counts only its own plan.",
463
+ "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.",
462
464
  "openHint": "Open “Task progress” on the left for the full plan.",
463
465
  "timeNegotiation": "Execution time (no limit)",
464
466
  "noTimeLimit": "Department leads and domain experts have no execution time limit; estimates are informational and do not affect acceptance",
@@ -1539,37 +1541,178 @@ window.__ModuleLoader__.load({
1539
1541
  if (!payload || payload.ok !== true) {
1540
1542
  throw new Error(asText(payload?.error) || '计划接口返回异常');
1541
1543
  }
1542
- return Array.isArray(payload.sessions) ? payload.sessions : [];
1544
+ /*
1545
+ * [复审修复] 返回完整载荷,不再只回 sessions:服务端 2.5MB 上限
1546
+ * (runtime.ts MAX_PLANS_RESPONSE_BYTES + trimPlansPayload)裁剪时会置
1547
+ * truncated / omittedSessions / omittedDetail,旧实现把它们丢掉,看板
1548
+ * 静默少显示数据。向后兼容:调用方仍取 .sessions(数组)。
1549
+ *
1550
+ * omittedDetail 在服务端是挂在每个 session 项上的(trimPlansPayload
1551
+ * 里 sessions[].omittedDetail = true),顶层也可能有;两者都要看。
1552
+ */
1553
+ const sessions = Array.isArray(payload.sessions) ? payload.sessions : [];
1554
+ const omittedSessions = typeof payload.omittedSessions === 'number'
1555
+ && Number.isFinite(payload.omittedSessions) ? payload.omittedSessions : 0;
1556
+ const omittedDetail = payload.omittedDetail === true
1557
+ || sessions.some((item) => item && item.omittedDetail === true);
1558
+ return { sessions, truncated: payload.truncated === true, omittedSessions, omittedDetail };
1559
+ }
1560
+ /*
1561
+ * [3.0.6][第 2 批] 看板轮询按会话共享。
1562
+ *
1563
+ * 旧实现里每个 TurnCard 都调用 usePlans(sessionId),各自 4 秒一次请求:
1564
+ * 一个会话有 30 张卡就是 30 请求/4s,服务端每次还要重建无内存记录的计划。
1565
+ * 现在同一 key(''=全部会话,或具体 sessionId)只有一个轮询器 + 一组订阅者,
1566
+ * 最后一个订阅者卸载时才停止;新订阅者立即拿到当前快照,不重复请求。
1567
+ */
1568
+ const planPolls = new Map();
1569
+ /* [复审修复] 单次轮询的挂死上限:到点按超时错误路径处理,绝不让 running 永真。 */
1570
+ const PLAN_POLL_TIMEOUT_MS = 15000;
1571
+ function emptyPlansState() {
1572
+ return {
1573
+ loading: true,
1574
+ sessions: [],
1575
+ truncated: false,
1576
+ omittedSessions: 0,
1577
+ omittedDetail: false,
1578
+ error: null,
1579
+ updatedAt: null,
1580
+ };
1543
1581
  }
1544
1582
  function usePlans(sessionId) {
1545
- const [state, setState] = useState({ loading: true, sessions: [], error: null, updatedAt: null });
1546
- const load = useCallback(async (signal) => {
1547
- try {
1548
- const sessions = await fetchPlans(sessionId, signal);
1549
- if (signal?.aborted)
1550
- return;
1551
- setState({ loading: false, sessions, error: null, updatedAt: Date.now() });
1583
+ const key = sessionId || '';
1584
+ const [state, setState] = useState(() => planPolls.get(key)?.state ?? emptyPlansState());
1585
+ useEffect(() => {
1586
+ let entry = planPolls.get(key);
1587
+ if (!entry) {
1588
+ entry = {
1589
+ state: emptyPlansState(),
1590
+ listeners: new Set(),
1591
+ timer: null,
1592
+ controller: null,
1593
+ running: false,
1594
+ run: null,
1595
+ timedOut: false,
1596
+ onVisible: null,
1597
+ };
1598
+ planPolls.set(key, entry);
1552
1599
  }
1553
- catch (error) {
1554
- if (signal?.aborted)
1555
- return;
1556
- setState((previous) => ({
1557
- ...previous,
1558
- loading: false,
1559
- error: error instanceof Error ? error.message : String(error),
1560
- }));
1600
+ const listener = (next) => setState(next);
1601
+ entry.listeners.add(listener);
1602
+ setState(entry.state);
1603
+ if (!entry.run) {
1604
+ entry.run = async () => {
1605
+ if (entry.running)
1606
+ return;
1607
+ /*
1608
+ * [复审修复] 后台标签页跳过本次轮询:interval 保留,回到前台后
1609
+ * 自然恢复;另有 visibilitychange 监听立即补一轮(见下方注册)。
1610
+ */
1611
+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden')
1612
+ return;
1613
+ entry.running = true;
1614
+ entry.timedOut = false;
1615
+ const controller = new AbortController();
1616
+ entry.controller = controller;
1617
+ /*
1618
+ * [复审修复] 15s 超时:一次挂死的请求不再让 entry.running 永真、
1619
+ * 看板永久冻结。卸载中止保持静默;超时中止走错误路径:
1620
+ * console.warn + 结束本次 running,interval 继续。
1621
+ *
1622
+ * 优先 AbortSignal.timeout + AbortSignal.any(无 JS 侧计时器句柄,
1623
+ * 不存在悬挂/句柄卫生问题);宿主运行时不支持 any() 时退回手动
1624
+ * setTimeout 控制器(等效实现),句柄挂在 entry 上,finally 与
1625
+ * 卸载 cleanup 双路清理——注意这里禁止 unref:这是收束类计时器
1626
+ * (tests/handle-policy.test.ts 契约),unref 会让 node 事件循环
1627
+ * 提前排空、看板错误路径永远到不了。
1628
+ */
1629
+ const anySignal = typeof AbortSignal.any === 'function'
1630
+ && typeof AbortSignal.timeout === 'function';
1631
+ let timeoutTimer = null;
1632
+ const signal = anySignal
1633
+ ? AbortSignal.any([controller.signal, AbortSignal.timeout(PLAN_POLL_TIMEOUT_MS)])
1634
+ : (() => {
1635
+ timeoutTimer = setTimeout(() => {
1636
+ entry.timedOut = true;
1637
+ controller.abort();
1638
+ }, PLAN_POLL_TIMEOUT_MS);
1639
+ return controller.signal;
1640
+ })();
1641
+ entry.timeoutTimer = timeoutTimer;
1642
+ try {
1643
+ const plansPayload = await fetchPlans(sessionId, signal);
1644
+ if (signal.aborted)
1645
+ return;
1646
+ entry.state = {
1647
+ loading: false,
1648
+ sessions: plansPayload.sessions,
1649
+ truncated: plansPayload.truncated === true,
1650
+ omittedSessions: plansPayload.omittedSessions,
1651
+ omittedDetail: plansPayload.omittedDetail === true,
1652
+ error: null,
1653
+ updatedAt: Date.now(),
1654
+ };
1655
+ }
1656
+ catch (error) {
1657
+ /*
1658
+ * 静默条件:仅「主动中止(卸载/重入)」。超时的判定两路都要覆盖——
1659
+ * 手动兜底路径置了 entry.timedOut;AbortSignal.any 路径里超时只体现为
1660
+ * 组合 signal 被中止而 controller 没有(卸载恰好相反:controller 先中止)。
1661
+ */
1662
+ const timedOut = entry.timedOut === true
1663
+ || (signal.aborted === true && controller.signal.aborted === false);
1664
+ if (signal.aborted && !timedOut)
1665
+ return;
1666
+ if (timedOut) {
1667
+ console.warn('[dsh-workplan] plans 轮询超时(15000ms),已结束本轮,下一轮继续', error);
1668
+ }
1669
+ entry.state = {
1670
+ ...entry.state,
1671
+ loading: false,
1672
+ error: error instanceof Error ? error.message : String(error),
1673
+ };
1674
+ }
1675
+ finally {
1676
+ if (timeoutTimer !== null)
1677
+ clearTimeout(timeoutTimer);
1678
+ entry.timeoutTimer = null;
1679
+ entry.running = false;
1680
+ entry.timedOut = false;
1681
+ entry.controller = null;
1682
+ entry.listeners.forEach((notify) => notify(entry.state));
1683
+ }
1684
+ };
1685
+ entry.run();
1686
+ entry.timer = setInterval(() => entry.run(), 4000);
1687
+ /*
1688
+ * [复审修复] 回到前台立即补一轮:后台期间 interval 触发的轮询
1689
+ * 全部被跳过,不补的话用户切回来最多干等一个周期。
1690
+ */
1691
+ entry.onVisible = () => {
1692
+ if (typeof document !== 'undefined' && document.visibilityState === 'visible') {
1693
+ entry.run?.();
1694
+ }
1695
+ };
1696
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
1697
+ document.addEventListener('visibilitychange', entry.onVisible);
1698
+ }
1561
1699
  }
1562
- }, [sessionId]);
1563
- useEffect(() => {
1564
- const controller = new AbortController();
1565
- load(controller.signal);
1566
- const timer = setInterval(() => load(controller.signal), 4000);
1567
1700
  return () => {
1568
- controller.abort();
1569
- clearInterval(timer);
1701
+ entry.listeners.delete(listener);
1702
+ if (entry.listeners.size === 0) {
1703
+ if (entry.timer)
1704
+ clearInterval(entry.timer);
1705
+ if (entry.timeoutTimer)
1706
+ clearTimeout(entry.timeoutTimer);
1707
+ entry.controller?.abort();
1708
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
1709
+ document.removeEventListener('visibilitychange', entry.onVisible);
1710
+ }
1711
+ planPolls.delete(key);
1712
+ }
1570
1713
  };
1571
- }, [load]);
1572
- return { ...state, reload: () => load() };
1714
+ }, [key, sessionId]);
1715
+ return { ...state, reload: () => planPolls.get(key)?.run?.() };
1573
1716
  }
1574
1717
  function ErrorBanner({ message, onRetry, t }) {
1575
1718
  return h('div', { className: 'dsh-wp-banner dsh-wp-banner--error', role: 'alert' }, h('div', { className: 'dsh-wp-section-title' }, t('error')), h('div', { className: 'dsh-wp-error-text' }, message || t('noResult')), h('button', { type: 'button', className: 'dsh-wp-button', style: { marginTop: '8px' }, onClick: onRetry }, t('retry')));
@@ -2762,7 +2905,7 @@ window.__ModuleLoader__.load({
2762
2905
  /* [T4] 回到顶部的显示阈值(px):scrollTop 严格大于该值才显示。 */
2763
2906
  const BACK_TOP_THRESHOLD = 200;
2764
2907
  function Dashboard({ t }) {
2765
- const { sessions, error, loading, updatedAt, reload } = usePlans();
2908
+ const { sessions, error, loading, updatedAt, reload, truncated, omittedSessions, omittedDetail, } = usePlans();
2766
2909
  const [openSessionId, setOpenSessionId] = useState(null);
2767
2910
  const selectSession = useCallback((sessionId) => {
2768
2911
  if (!sessionId)
@@ -2944,7 +3087,18 @@ window.__ModuleLoader__.load({
2944
3087
  className: 'dsh-wp',
2945
3088
  ref: (node) => { if (node !== panelEl)
2946
3089
  setPanelEl(node); },
2947
- }, h('header', { className: 'dsh-wp-header' }, h('div', null, h('h1', { className: 'dsh-wp-title' }, t('title')), h('p', { className: 'dsh-wp-subtitle' }, t('subtitle')), h('div', { className: 'dsh-wp-meta' }, updatedAt ? h('span', null, `${t('updatedAt')} ${formatTime(updatedAt)}`) : null, h('span', null, `${t('scopeAll')}:${activeSessions.length} ${t('sessionCount')},${t('taskBreakdown')} ${totals.total} ${t('subtaskCount')}`))), h('button', { type: 'button', className: 'dsh-wp-button', onClick: reload, disabled: loading }, t('refresh'))), error ? h(ErrorBanner, { message: error, onRetry: reload, t }) : null, activeSessions.length > 0 ? h('div', { className: 'dsh-wp-statbar', role: 'list' }, 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'))), 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'))), h('div', { className: 'dsh-wp-stat dsh-wp-stat--done', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.done), h('div', { className: 'dsh-wp-stat-label' }, t('stats.done'))), h('div', { className: 'dsh-wp-stat dsh-wp-stat--active', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.inProgress), h('div', { className: 'dsh-wp-stat-label' }, t('stats.inProgress'))), h('div', { className: 'dsh-wp-stat dsh-wp-stat--blocked', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.blocked), h('div', { className: 'dsh-wp-stat-label' }, t('stats.blocked')))) : null, activeSessions.length > 0 ? h('div', { className: 'dsh-wp-scope-note' }, t('allPlansHint')) : null, activeSessions.length === 0
3090
+ }, h('header', { className: 'dsh-wp-header' }, h('div', null, h('h1', { className: 'dsh-wp-title' }, t('title')), h('p', { className: 'dsh-wp-subtitle' }, t('subtitle')), h('div', { className: 'dsh-wp-meta' }, updatedAt ? h('span', null, `${t('updatedAt')} ${formatTime(updatedAt)}`) : null, h('span', null, `${t('scopeAll')}:${activeSessions.length} ${t('sessionCount')},${t('taskBreakdown')} ${totals.total} ${t('subtaskCount')}`))), h('button', { type: 'button', className: 'dsh-wp-button', onClick: reload, disabled: loading }, t('refresh'))), error ? h(ErrorBanner, { message: error, onRetry: reload, t }) : null,
3091
+ /*
3092
+ * [复审修复] 服务端裁剪提示:载荷被 2.5MB 上限裁剪(truncated /
3093
+ * omittedSessions / omittedDetail 任一成立)时明确告知「展示为子集」,
3094
+ * 不再静默少显示数据。复用现有 degraded 横幅样式,不新增 CSS/依赖。
3095
+ */
3096
+ (truncated === true || Number(omittedSessions) > 0 || omittedDetail === true)
3097
+ ? h('div', {
3098
+ className: 'dsh-wp-banner dsh-wp-banner--degraded dsh-wp-trim-notice',
3099
+ role: 'status',
3100
+ }, t('trimNotice'))
3101
+ : null, activeSessions.length > 0 ? h('div', { className: 'dsh-wp-statbar', role: 'list' }, 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'))), 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'))), h('div', { className: 'dsh-wp-stat dsh-wp-stat--done', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.done), h('div', { className: 'dsh-wp-stat-label' }, t('stats.done'))), h('div', { className: 'dsh-wp-stat dsh-wp-stat--active', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.inProgress), h('div', { className: 'dsh-wp-stat-label' }, t('stats.inProgress'))), h('div', { className: 'dsh-wp-stat dsh-wp-stat--blocked', role: 'listitem' }, h('div', { className: 'dsh-wp-stat-value' }, totals.blocked), h('div', { className: 'dsh-wp-stat-label' }, t('stats.blocked')))) : null, activeSessions.length > 0 ? h('div', { className: 'dsh-wp-scope-note' }, t('allPlansHint')) : null, activeSessions.length === 0
2948
3102
  ? h('div', { className: 'dsh-wp-empty' }, h('div', { style: { fontWeight: 650, marginBottom: '4px' } }, t('empty')), h('div', null, t('emptyHint')))
2949
3103
  : h('div', { className: 'dsh-wp-groups' },
2950
3104
  // [用户要求] 总览块(完成率环 + 每个任务的进度)上移到分组之前:
@@ -70,7 +70,7 @@ export const COMM_FORMAT_SPEC = Object.freeze({
70
70
  description: '专家(第三层执行者)结果必须包含 report 对象,只允许 keyResults/keyInfo/importantInfo/leadRequirements 四个字符串数组字段,至少各有 1 条非空内容(keyInfo/important 可为空数组但须存在),每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
71
71
  rationale: '用户要求 7:专家成果必须非常精简地汇报给部门负责人,只要关键信息、关键成果、重要信息和负责人要求的东西,并以 JSON mode 结构化输出' }),
72
72
  Object.freeze({ id: 'F11', category: 'report',
73
- description: '部门负责人结果必须包含 departmentSummary 对象,只允许 keyResults/keyInfo/importantInfo/sources 四个字符串数组字段,keyResults 至少 1 条非空、sources 必须覆盖本部门全部已派发专家,每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
73
+ description: '部门负责人结果必须包含 departmentSummary 对象,只允许 keyResults/keyInfo/importantInfo/sources 四个字符串数组字段,keyResults 至少 1 条非空,keyResults/keyInfo/importantInfo 每项最多 6 条、每条最多 200 字符;sources 最多 16 条且必须逐人覆盖本部门全部已派发专家,内部与跨字段不得出现重复表述',
74
74
  rationale: '用户要求 8/10/11:部门负责人必须全面汇总全部专家汇报,汇总报告必须精简、禁止累赘重复,并以 JSON mode 结构化直接交回主 Agent' }),
75
75
  ]),
76
76
  /*
@@ -16,7 +16,7 @@
16
16
  * 由 channel-expert 按契约 §3 实现)。
17
17
  */
18
18
  import { randomBytes } from 'node:crypto';
19
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
19
+ import { appendFileSync, chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, statSync, unlinkSync } from 'node:fs';
20
20
  import { homedir } from 'node:os';
21
21
  import { dirname, join } from 'node:path';
22
22
  /** 接口版本(契约 §1:字面量 1)。 */
@@ -235,7 +235,8 @@ export function deptJournalPath(planId) {
235
235
  }
236
236
  /**
237
237
  * 追加一条留痕(契约 §2):先 validate,再 mkdirSync(recursive)+appendFileSync。
238
- * 任何失败(校验不过 / planId 非法 / 写盘失败)显式返回 JOURNAL_WRITE_FAILED,绝不静默。
238
+ * 任何失败(校验不过 / planId 非法 / 写盘失败 / 回读不一致)显式返回
239
+ * JOURNAL_WRITE_FAILED / JOURNAL_READBACK_FAILED,绝不静默。
239
240
  */
240
241
  export function appendDeptMessage(msg) {
241
242
  const verdict = validateDeptMessage(msg);
@@ -249,19 +250,152 @@ export function appendDeptMessage(msg) {
249
250
  return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: errorText(error) };
250
251
  }
251
252
  try {
252
- mkdirSync(dirname(path), { recursive: true });
253
- appendFileSync(path, `${JSON.stringify(verdict.value)}\n`, 'utf8');
253
+ /*
254
+ * [安全加固] 防符号链接投毒:journal 文件若是符号链接则跳过写入并告警——
255
+ * 绝不跟随链接把审计内容写到链接指向的任意路径;失败显式返回(绝不静默)。
256
+ * lstatSync 抛错(文件不存在等)属正常首写场景,交给 appendFileSync 处理。
257
+ */
258
+ try {
259
+ if (lstatSync(path).isSymbolicLink()) {
260
+ console.warn(`dsh-workplan: journal 文件是符号链接,跳过写入 path=${path}`);
261
+ return {
262
+ ok: false,
263
+ code: 'JOURNAL_WRITE_FAILED',
264
+ error: `JOURNAL_WRITE_FAILED: journal 文件是符号链接,已跳过写入 path=${path}(防链接投毒)。`,
265
+ };
266
+ }
267
+ }
268
+ catch {
269
+ /* 文件不存在(首写)或 lstat 失败:继续走正常写入,错误由 appendFileSync 显式上报。 */
270
+ }
271
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
272
+ appendFileSync(path, `${JSON.stringify(verdict.value)}\n`, { encoding: 'utf8', mode: 0o600 });
273
+ try {
274
+ // 既有文件权限收紧为 0o600(best-effort;新建文件已由 mode 覆盖)。
275
+ chmodSync(path, 0o600);
276
+ }
277
+ catch {
278
+ /* best-effort:权限收紧失败不阻断追加。 */
279
+ }
254
280
  }
255
281
  catch (error) {
256
282
  return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: errorText(error) };
257
283
  }
284
+ /* [T3][回读校验] 写后读回比对关键字段(见下方 helper 注释),不一致绝不静默。 */
285
+ const readback = verifyJournalAppendReadback(path, verdict.value);
286
+ if (!readback.ok)
287
+ return { ok: false, code: 'JOURNAL_READBACK_FAILED', error: readback.error };
258
288
  return { ok: true, path };
259
289
  }
290
+ /*
291
+ * [T3][回读校验] journal 追加写后读回。依据:reports/wp-member-expert-persist-call-T1.json
292
+ * 写盘点⑦(dept-journal.ts:290-308;2026-11-17 复核 mkdirSync:302、appendFileSync:303
293
+ * 无漂移)与 reports/wp-member-expert-storage-T1-storage.json(落盘路径
294
+ * <journalDir>/<planId>.jsonl,事件流追加、非整文件快照)。
295
+ * appendFileSync 成功后读回文件末尾窗口,JSON 解析后比对关键字段(v/id/planId/
296
+ * subtaskId/kind/ts/body 头 120 字摘要)。找不到匹配行 → 返回显式错误码
297
+ * JOURNAL_READBACK_FAILED(本模块「绝不静默」契约=显式错误码+处置指引,与
298
+ * JOURNAL_WRITE_FAILED 同口径;负责人硬性要求③的「抛显式错误」在本模块以
299
+ * 显式错误码实现,错误信息含文件路径与期望/实际摘要及指引:重试或让主 Agent
300
+ * 手动制定计划)。纯读校验、不写盘 → 幂等(硬性要求④)。
301
+ *
302
+ * [复审修复][O(n²)→O(窗口)] journal 默认永久保留,文件会涨到 MB 级;旧实现每次
303
+ * 追加后 readFileSync 整个文件逐行 parse,热路径每次请示/指示/完成/预估都全文件
304
+ * 重读。改为只读末尾一个窗口(JOURNAL_READBACK_WINDOW_BYTES):
305
+ * - O_APPEND 保证刚写入的行必在文件末尾;窗口 ≥ 单行最大体积(body ≤4000 字符 +
306
+ * data JSON ≤4000 字符,单 line 远小于 64KB)即可命中;
307
+ * - 窗口起点可能落在行中间 → 首行 parse 失败直接跳过该坏行继续;
308
+ * - 并发追加交错不会把新行挤出窗口(需同一瞬时有 64KB 更新行写入才会,
309
+ * 概率可忽略;且失败显式可重试)。
310
+ */
311
+ function deptMessageKeyDigest(record) {
312
+ return JSON.stringify({
313
+ v: record?.v,
314
+ id: record?.id,
315
+ planId: record?.planId,
316
+ subtaskId: record?.subtaskId,
317
+ kind: record?.kind,
318
+ ts: record?.ts,
319
+ bodyHead: String(record?.body ?? '').slice(0, 120),
320
+ });
321
+ }
322
+ /** 回读窗口字节数:64KB。单行最大体积(body 4000 + data JSON 4000 + 结构开销)远小于此。 */
323
+ const JOURNAL_READBACK_WINDOW_BYTES = 64 * 1024;
324
+ /** 只读文件末尾一个窗口(按字节);文件小于窗口则全读。读失败由调用方捕获。 */
325
+ function readJournalTailWindow(path, windowBytes) {
326
+ const { size } = statSync(path);
327
+ const start = Math.max(0, size - windowBytes);
328
+ const length = size - start;
329
+ if (length <= 0)
330
+ return '';
331
+ const buffer = Buffer.alloc(length);
332
+ const fd = openSync(path, 'r');
333
+ try {
334
+ let offset = 0;
335
+ while (offset < length) {
336
+ const read = readSync(fd, buffer, offset, length - offset, start + offset);
337
+ if (read <= 0)
338
+ break;
339
+ offset += read;
340
+ }
341
+ }
342
+ finally {
343
+ closeSync(fd);
344
+ }
345
+ return buffer.toString('utf8');
346
+ }
347
+ function verifyJournalAppendReadback(path, expected) {
348
+ let text;
349
+ try {
350
+ text = readJournalTailWindow(path, JOURNAL_READBACK_WINDOW_BYTES);
351
+ }
352
+ catch (error) {
353
+ return {
354
+ ok: false,
355
+ error: `dsh-workplan: journal 回读校验读不到文件 path=${path}(${errorText(error)})。`
356
+ + '请重试;若多次失败请让主 Agent 手动制定计划。',
357
+ };
358
+ }
359
+ const lines = text.split('\n').filter((line) => line.trim() !== '');
360
+ const want = deptMessageKeyDigest(expected);
361
+ /*
362
+ * 只扫末尾窗口:窗口首行可能被截断(窗口从行中间字节开始),parse 失败跳过该
363
+ * 坏行继续;新追加的行(digest 匹配)由 O_APPEND 保证在文件末尾、必在窗口内。
364
+ */
365
+ for (const line of lines) {
366
+ let parsed = null;
367
+ try {
368
+ parsed = JSON.parse(line);
369
+ }
370
+ catch {
371
+ continue;
372
+ }
373
+ if (deptMessageKeyDigest(parsed) === want)
374
+ return { ok: true };
375
+ }
376
+ const tail = lines.slice(-5);
377
+ const actual = tail
378
+ .map((line) => {
379
+ try {
380
+ return deptMessageKeyDigest(JSON.parse(line));
381
+ }
382
+ catch {
383
+ return '<不可解析行>';
384
+ }
385
+ })
386
+ .join(' | ');
387
+ return {
388
+ ok: false,
389
+ error: `dsh-workplan: journal 落盘回读校验失败 path=${path}:写入内容与读回内容关键字段不一致。`
390
+ + `期望=${want.slice(0, 300)} 实际(末${tail.length}行)=${actual.slice(0, 300)}。`
391
+ + '请重试;若多次失败请让主 Agent 手动制定计划。',
392
+ };
393
+ }
260
394
  /**
261
395
  * 按追加序回放留痕(契约 §2):
262
396
  * - 文件不存在 → 空列表(ok:true);
263
397
  * - 坏行(JSON 损坏或校验不过)计入 skipped,不静默吞;
264
- * - kind/since 过滤后按 limit 截取:默认 500、上限 5000;
398
+ * - kind/since 过滤后按 limit 截取:默认 500、上限 5000;newest=true 取最近,否则取最早;
265
399
  * - planId 非法或读盘失败 → 显式 JOURNAL_READ_FAILED。
266
400
  */
267
401
  export function readDeptMessages(planId, filter) {
@@ -315,5 +449,88 @@ export function readDeptMessages(planId, filter) {
315
449
  continue;
316
450
  matched.push(message);
317
451
  }
318
- return { ok: true, messages: matched.slice(0, limit), skipped };
452
+ return { ok: true, messages: filter?.newest ? matched.slice(-limit) : matched.slice(0, limit), skipped };
453
+ }
454
+ /**
455
+ * [3.0.6][第 2 批] 留痕目录的可选保留策略(默认关闭)。
456
+ *
457
+ * 审计证据不该被默认删除,所以本函数只在显式配置
458
+ * `journalRetentionDays > 0`(或环境变量
459
+ * `DSH_WORKPLAN_JOURNAL_RETENTION_DAYS`)时被调用。它只删除同时满足以下
460
+ * 条件的文件:目录里直接的 `.jsonl` 普通文件、文件名是合法 planId、
461
+ * mtime 早于保留天数。活跃计划会持续追加,mtime 保持新,因此不会被误删。
462
+ *
463
+ * 单次最多删 `maxFiles`(默认 200,上限 1000)个最旧文件,避免一次启动
464
+ * 长时间阻塞;删除失败不再静默跳过——逐个 console.warn 一行并收集进
465
+ * 返回值的 `errors[]`(ok 保持 true,兼容既有调用方)。
466
+ *
467
+ * [复审修复] `excludePlanIds`(可选):文件名(去 .jsonl)在集合内的一律
468
+ * 跳过删除,防「活跃但安静」(久无新消息、mtime 变旧)的计划被误删。
469
+ */
470
+ export function pruneJournal(options) {
471
+ const days = Number(options?.retentionDays);
472
+ if (!Number.isFinite(days) || days <= 0)
473
+ return { ok: true, scanned: 0, deleted: [] };
474
+ const dir = resolveJournalDir();
475
+ let names;
476
+ try {
477
+ names = readdirSync(dir);
478
+ }
479
+ catch (error) {
480
+ if (error?.code === 'ENOENT')
481
+ return { ok: true, scanned: 0, deleted: [] };
482
+ return { ok: false, scanned: 0, deleted: [], error: errorText(error) };
483
+ }
484
+ const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now();
485
+ const cutoff = now - days * 24 * 60 * 60 * 1000;
486
+ const maxFiles = Math.max(0, Math.min(1000, Math.trunc(options?.maxFiles ?? 200)));
487
+ const exclude = options?.excludePlanIds;
488
+ const candidates = [];
489
+ for (const name of names) {
490
+ if (!name.endsWith('.jsonl'))
491
+ continue;
492
+ const planId = name.slice(0, -'.jsonl'.length);
493
+ if (!PLAN_ID_PATTERN.test(planId))
494
+ continue;
495
+ // 活跃但安静的保护名单:在册计划即使 mtime 超期也不删。
496
+ if (exclude?.has(planId))
497
+ continue;
498
+ const path = join(dir, name);
499
+ try {
500
+ const stat = lstatSync(path);
501
+ // 只删普通文件;符号链接一律跳过(防越界删除)。
502
+ if (!stat.isFile() || stat.isSymbolicLink())
503
+ continue;
504
+ if (stat.mtimeMs >= cutoff)
505
+ continue;
506
+ candidates.push({ name, path, mtimeMs: stat.mtimeMs });
507
+ }
508
+ catch {
509
+ // 单个文件 stat 失败不影响其他文件,最后以 scanned 如实反映总数。
510
+ continue;
511
+ }
512
+ }
513
+ candidates.sort((a, b) => a.mtimeMs - b.mtimeMs);
514
+ const deleted = [];
515
+ const errors = [];
516
+ for (const candidate of candidates.slice(0, maxFiles)) {
517
+ try {
518
+ unlinkSync(candidate.path);
519
+ deleted.push(candidate.name);
520
+ }
521
+ catch (error) {
522
+ // 单个 unlink 失败不再静默:收集原因 + 逐条 warn(ok 保持 true 兼容)。
523
+ const reason = `${candidate.name}: ${errorText(error)}`;
524
+ errors.push(reason);
525
+ console.warn(`dsh-workplan: journal 保留清理删除失败 ${reason} path=${candidate.path}`);
526
+ }
527
+ }
528
+ const result = {
529
+ ok: true,
530
+ scanned: names.length,
531
+ deleted,
532
+ };
533
+ if (errors.length > 0)
534
+ result.errors = errors;
535
+ return result;
319
536
  }