dsh-workplan 3.0.2 → 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.
- package/CHANGELOG.md +58 -0
- package/README.en.md +15 -7
- package/README.md +18 -8
- package/README.zh.md +8 -7
- package/client.js +181 -27
- package/docs/release-notes-3.0.3.md +7 -0
- package/lib/approval-gate.js +79 -3
- package/lib/client.js +181 -27
- package/lib/comm-format.js +11 -9
- package/lib/dept-journal.js +223 -6
- package/lib/host.js +215 -12
- package/lib/lessons.js +83 -15
- package/lib/llm-rules.js +3 -2
- package/lib/notice-ledger.js +238 -0
- package/lib/plan.js +122 -5
- package/lib/runtime.js +446 -34
- package/lib/three-phase.js +78 -25
- package/lib/understanding.js +85 -6
- package/lib/v3-contract.js +45 -12
- package/package.json +1 -1
- package/src/approval-gate.ts +77 -3
- package/src/client.ts +178 -24
- package/src/comm-format.ts +10 -9
- package/src/dept-journal.ts +219 -7
- package/src/host.ts +215 -12
- package/src/lessons.ts +88 -15
- package/src/llm-rules.ts +3 -2
- package/src/notice-ledger.ts +251 -0
- package/src/plan.ts +126 -5
- package/src/runtime.ts +488 -32
- package/src/three-phase.ts +96 -27
- package/src/understanding.ts +100 -6
- package/src/v3-contract.ts +46 -13
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
|
-
|
|
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
|
|
1597
|
-
const
|
|
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
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
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
|
-
|
|
1617
|
-
|
|
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
|
-
}, [
|
|
1620
|
-
return { ...state, reload: () =>
|
|
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 {
|
|
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'))),
|
package/src/comm-format.ts
CHANGED
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
* 专家结果查 F10,部门负责人结果查 F11,未声明层级时两条都不查
|
|
35
35
|
* (历史回放与其它调用点零回归)。
|
|
36
36
|
*/
|
|
37
|
-
export const COMM_FORMAT_VERSION =
|
|
37
|
+
export const COMM_FORMAT_VERSION = 3
|
|
38
38
|
|
|
39
39
|
/** 单条不合规项。 */
|
|
40
40
|
export interface CommFormatViolation {
|
|
@@ -70,8 +70,8 @@ export const COMM_FORMAT_SPEC = Object.freeze({
|
|
|
70
70
|
description: '证据块必须是合法 JSON 对象,顶层必须含 status 字段,取值只能是 done / blocked / partial',
|
|
71
71
|
rationale: 'status 是交付门禁的入口条件,缺失或非法则无法判定完成与否' }),
|
|
72
72
|
Object.freeze({ id: 'F3', category: 'phases',
|
|
73
|
-
description: '
|
|
74
|
-
rationale: '
|
|
73
|
+
description: '必须包含五步工作法证据:phases.planning(第一步问题梳理 problemAnalysis + 第二步资源 resources / 工具 tools / 方法流程步骤 approach / 依据 approachBasis)、phases.preparation(第三步准备与就绪证据)、phases.execution(第四步实际执行步骤)、phases.verification(第四步逐项验证与复盘);第五步交付由 F10/F11 的 report / departmentSummary 承载',
|
|
74
|
+
rationale: '五步是质量闭环的基础,缺任一步等于跳过对应质控环节' }),
|
|
75
75
|
Object.freeze({ id: 'F4', category: 'acceptance',
|
|
76
76
|
description: '验收结果必须逐条回应计划的验收标准(A1、A2…),且每条 result=pass 必须附带具体证据(命令输出/文件路径/引用),禁止空证据 pass',
|
|
77
77
|
rationale: '空证据 pass 是自述而非验证,交付门禁只认可证据' }),
|
|
@@ -98,7 +98,7 @@ export const COMM_FORMAT_SPEC = Object.freeze({
|
|
|
98
98
|
description: '专家(第三层执行者)结果必须包含 report 对象,只允许 keyResults/keyInfo/importantInfo/leadRequirements 四个字符串数组字段,至少各有 1 条非空内容(keyInfo/important 可为空数组但须存在),每数组最多 6 条、每条最多 200 字符,内部与跨字段不得出现重复表述',
|
|
99
99
|
rationale: '用户要求 7:专家成果必须非常精简地汇报给部门负责人,只要关键信息、关键成果、重要信息和负责人要求的东西,并以 JSON mode 结构化输出' }),
|
|
100
100
|
Object.freeze({ id: 'F11', category: 'report',
|
|
101
|
-
description: '部门负责人结果必须包含 departmentSummary 对象,只允许 keyResults/keyInfo/importantInfo/sources 四个字符串数组字段,keyResults 至少 1
|
|
101
|
+
description: '部门负责人结果必须包含 departmentSummary 对象,只允许 keyResults/keyInfo/importantInfo/sources 四个字符串数组字段,keyResults 至少 1 条非空,keyResults/keyInfo/importantInfo 每项最多 6 条、每条最多 200 字符;sources 最多 16 条且必须逐人覆盖本部门全部已派发专家,内部与跨字段不得出现重复表述',
|
|
102
102
|
rationale: '用户要求 8/10/11:部门负责人必须全面汇总全部专家汇报,汇总报告必须精简、禁止累赘重复,并以 JSON mode 结构化直接交回主 Agent' }),
|
|
103
103
|
]),
|
|
104
104
|
/*
|
|
@@ -165,14 +165,15 @@ export function checkCommFormatCompliance(
|
|
|
165
165
|
const phases = parsed.phases
|
|
166
166
|
if (!phases || typeof phases !== 'object') {
|
|
167
167
|
violations.push({ ruleId: 'F3', category: 'phases',
|
|
168
|
-
message: '缺少 phases 对象:planning / execution / verification
|
|
168
|
+
message: '缺少 phases 对象:planning / preparation / execution / verification 证据全部缺失' })
|
|
169
169
|
} else {
|
|
170
170
|
const missing: string[] = []
|
|
171
|
-
if (!phases.planning || typeof phases.planning !== 'object') missing.push('planning
|
|
172
|
-
if (!phases.
|
|
173
|
-
if (!phases.
|
|
171
|
+
if (!phases.planning || typeof phases.planning !== 'object') missing.push('planning(第一步问题梳理 + 第二步资源/工具/方案)')
|
|
172
|
+
if (!phases.preparation || typeof phases.preparation !== 'object') missing.push('preparation(第三步准备与就绪证据)')
|
|
173
|
+
if (!phases.execution || typeof phases.execution !== 'object') missing.push('execution(第四步实际执行步骤)')
|
|
174
|
+
if (!phases.verification || typeof phases.verification !== 'object') missing.push('verification(第四步逐项验证与复盘)')
|
|
174
175
|
if (missing.length > 0) {
|
|
175
|
-
violations.push({ ruleId: 'F3', category: 'phases', message:
|
|
176
|
+
violations.push({ ruleId: 'F3', category: 'phases', message: `五步证据缺失:${missing.join('、')}` })
|
|
176
177
|
}
|
|
177
178
|
}
|
|
178
179
|
|
package/src/dept-journal.ts
CHANGED
|
@@ -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
|
|
|
@@ -285,11 +285,12 @@ export function deptJournalPath(planId: string): string {
|
|
|
285
285
|
|
|
286
286
|
/**
|
|
287
287
|
* 追加一条留痕(契约 §2):先 validate,再 mkdirSync(recursive)+appendFileSync。
|
|
288
|
-
* 任何失败(校验不过 / planId 非法 /
|
|
288
|
+
* 任何失败(校验不过 / planId 非法 / 写盘失败 / 回读不一致)显式返回
|
|
289
|
+
* JOURNAL_WRITE_FAILED / JOURNAL_READBACK_FAILED,绝不静默。
|
|
289
290
|
*/
|
|
290
291
|
export function appendDeptMessage(
|
|
291
292
|
msg: unknown,
|
|
292
|
-
): { ok: true; path: string } | { ok: false; code: 'JOURNAL_WRITE_FAILED'; error: string } {
|
|
293
|
+
): { ok: true; path: string } | { ok: false; code: 'JOURNAL_WRITE_FAILED' | 'JOURNAL_READBACK_FAILED'; error: string } {
|
|
293
294
|
const verdict = validateDeptMessage(msg)
|
|
294
295
|
if (!verdict.ok) return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: verdict.error }
|
|
295
296
|
let path: string
|
|
@@ -299,25 +300,157 @@ export function appendDeptMessage(
|
|
|
299
300
|
return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: errorText(error) }
|
|
300
301
|
}
|
|
301
302
|
try {
|
|
302
|
-
|
|
303
|
-
|
|
303
|
+
/*
|
|
304
|
+
* [安全加固] 防符号链接投毒:journal 文件若是符号链接则跳过写入并告警——
|
|
305
|
+
* 绝不跟随链接把审计内容写到链接指向的任意路径;失败显式返回(绝不静默)。
|
|
306
|
+
* lstatSync 抛错(文件不存在等)属正常首写场景,交给 appendFileSync 处理。
|
|
307
|
+
*/
|
|
308
|
+
try {
|
|
309
|
+
if (lstatSync(path).isSymbolicLink()) {
|
|
310
|
+
console.warn(`dsh-workplan: journal 文件是符号链接,跳过写入 path=${path}`)
|
|
311
|
+
return {
|
|
312
|
+
ok: false,
|
|
313
|
+
code: 'JOURNAL_WRITE_FAILED',
|
|
314
|
+
error: `JOURNAL_WRITE_FAILED: journal 文件是符号链接,已跳过写入 path=${path}(防链接投毒)。`,
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
} catch {
|
|
318
|
+
/* 文件不存在(首写)或 lstat 失败:继续走正常写入,错误由 appendFileSync 显式上报。 */
|
|
319
|
+
}
|
|
320
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 })
|
|
321
|
+
appendFileSync(path, `${JSON.stringify(verdict.value)}\n`, { encoding: 'utf8', mode: 0o600 })
|
|
322
|
+
try {
|
|
323
|
+
// 既有文件权限收紧为 0o600(best-effort;新建文件已由 mode 覆盖)。
|
|
324
|
+
chmodSync(path, 0o600)
|
|
325
|
+
} catch {
|
|
326
|
+
/* best-effort:权限收紧失败不阻断追加。 */
|
|
327
|
+
}
|
|
304
328
|
} catch (error) {
|
|
305
329
|
return { ok: false, code: 'JOURNAL_WRITE_FAILED', error: errorText(error) }
|
|
306
330
|
}
|
|
331
|
+
/* [T3][回读校验] 写后读回比对关键字段(见下方 helper 注释),不一致绝不静默。 */
|
|
332
|
+
const readback = verifyJournalAppendReadback(path, verdict.value)
|
|
333
|
+
if (!readback.ok) return { ok: false, code: 'JOURNAL_READBACK_FAILED', error: readback.error }
|
|
307
334
|
return { ok: true, path }
|
|
308
335
|
}
|
|
309
336
|
|
|
337
|
+
/*
|
|
338
|
+
* [T3][回读校验] journal 追加写后读回。依据:reports/wp-member-expert-persist-call-T1.json
|
|
339
|
+
* 写盘点⑦(dept-journal.ts:290-308;2026-11-17 复核 mkdirSync:302、appendFileSync:303
|
|
340
|
+
* 无漂移)与 reports/wp-member-expert-storage-T1-storage.json(落盘路径
|
|
341
|
+
* <journalDir>/<planId>.jsonl,事件流追加、非整文件快照)。
|
|
342
|
+
* appendFileSync 成功后读回文件末尾窗口,JSON 解析后比对关键字段(v/id/planId/
|
|
343
|
+
* subtaskId/kind/ts/body 头 120 字摘要)。找不到匹配行 → 返回显式错误码
|
|
344
|
+
* JOURNAL_READBACK_FAILED(本模块「绝不静默」契约=显式错误码+处置指引,与
|
|
345
|
+
* JOURNAL_WRITE_FAILED 同口径;负责人硬性要求③的「抛显式错误」在本模块以
|
|
346
|
+
* 显式错误码实现,错误信息含文件路径与期望/实际摘要及指引:重试或让主 Agent
|
|
347
|
+
* 手动制定计划)。纯读校验、不写盘 → 幂等(硬性要求④)。
|
|
348
|
+
*
|
|
349
|
+
* [复审修复][O(n²)→O(窗口)] journal 默认永久保留,文件会涨到 MB 级;旧实现每次
|
|
350
|
+
* 追加后 readFileSync 整个文件逐行 parse,热路径每次请示/指示/完成/预估都全文件
|
|
351
|
+
* 重读。改为只读末尾一个窗口(JOURNAL_READBACK_WINDOW_BYTES):
|
|
352
|
+
* - O_APPEND 保证刚写入的行必在文件末尾;窗口 ≥ 单行最大体积(body ≤4000 字符 +
|
|
353
|
+
* data JSON ≤4000 字符,单 line 远小于 64KB)即可命中;
|
|
354
|
+
* - 窗口起点可能落在行中间 → 首行 parse 失败直接跳过该坏行继续;
|
|
355
|
+
* - 并发追加交错不会把新行挤出窗口(需同一瞬时有 64KB 更新行写入才会,
|
|
356
|
+
* 概率可忽略;且失败显式可重试)。
|
|
357
|
+
*/
|
|
358
|
+
function deptMessageKeyDigest(record: any): string {
|
|
359
|
+
return JSON.stringify({
|
|
360
|
+
v: record?.v,
|
|
361
|
+
id: record?.id,
|
|
362
|
+
planId: record?.planId,
|
|
363
|
+
subtaskId: record?.subtaskId,
|
|
364
|
+
kind: record?.kind,
|
|
365
|
+
ts: record?.ts,
|
|
366
|
+
bodyHead: String(record?.body ?? '').slice(0, 120),
|
|
367
|
+
})
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** 回读窗口字节数:64KB。单行最大体积(body 4000 + data JSON 4000 + 结构开销)远小于此。 */
|
|
371
|
+
const JOURNAL_READBACK_WINDOW_BYTES = 64 * 1024
|
|
372
|
+
|
|
373
|
+
/** 只读文件末尾一个窗口(按字节);文件小于窗口则全读。读失败由调用方捕获。 */
|
|
374
|
+
function readJournalTailWindow(path: string, windowBytes: number): string {
|
|
375
|
+
const { size } = statSync(path)
|
|
376
|
+
const start = Math.max(0, size - windowBytes)
|
|
377
|
+
const length = size - start
|
|
378
|
+
if (length <= 0) return ''
|
|
379
|
+
const buffer = Buffer.alloc(length)
|
|
380
|
+
const fd = openSync(path, 'r')
|
|
381
|
+
try {
|
|
382
|
+
let offset = 0
|
|
383
|
+
while (offset < length) {
|
|
384
|
+
const read = readSync(fd, buffer, offset, length - offset, start + offset)
|
|
385
|
+
if (read <= 0) break
|
|
386
|
+
offset += read
|
|
387
|
+
}
|
|
388
|
+
} finally {
|
|
389
|
+
closeSync(fd)
|
|
390
|
+
}
|
|
391
|
+
return buffer.toString('utf8')
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function verifyJournalAppendReadback(
|
|
395
|
+
path: string,
|
|
396
|
+
expected: DeptMessage,
|
|
397
|
+
): { ok: true } | { ok: false; error: string } {
|
|
398
|
+
let text: string
|
|
399
|
+
try {
|
|
400
|
+
text = readJournalTailWindow(path, JOURNAL_READBACK_WINDOW_BYTES)
|
|
401
|
+
} catch (error) {
|
|
402
|
+
return {
|
|
403
|
+
ok: false,
|
|
404
|
+
error: `dsh-workplan: journal 回读校验读不到文件 path=${path}(${errorText(error)})。`
|
|
405
|
+
+ '请重试;若多次失败请让主 Agent 手动制定计划。',
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
const lines = text.split('\n').filter((line) => line.trim() !== '')
|
|
409
|
+
const want = deptMessageKeyDigest(expected)
|
|
410
|
+
/*
|
|
411
|
+
* 只扫末尾窗口:窗口首行可能被截断(窗口从行中间字节开始),parse 失败跳过该
|
|
412
|
+
* 坏行继续;新追加的行(digest 匹配)由 O_APPEND 保证在文件末尾、必在窗口内。
|
|
413
|
+
*/
|
|
414
|
+
for (const line of lines) {
|
|
415
|
+
let parsed: any = null
|
|
416
|
+
try {
|
|
417
|
+
parsed = JSON.parse(line)
|
|
418
|
+
} catch {
|
|
419
|
+
continue
|
|
420
|
+
}
|
|
421
|
+
if (deptMessageKeyDigest(parsed) === want) return { ok: true }
|
|
422
|
+
}
|
|
423
|
+
const tail = lines.slice(-5)
|
|
424
|
+
const actual = tail
|
|
425
|
+
.map((line) => {
|
|
426
|
+
try {
|
|
427
|
+
return deptMessageKeyDigest(JSON.parse(line))
|
|
428
|
+
} catch {
|
|
429
|
+
return '<不可解析行>'
|
|
430
|
+
}
|
|
431
|
+
})
|
|
432
|
+
.join(' | ')
|
|
433
|
+
return {
|
|
434
|
+
ok: false,
|
|
435
|
+
error: `dsh-workplan: journal 落盘回读校验失败 path=${path}:写入内容与读回内容关键字段不一致。`
|
|
436
|
+
+ `期望=${want.slice(0, 300)} 实际(末${tail.length}行)=${actual.slice(0, 300)}。`
|
|
437
|
+
+ '请重试;若多次失败请让主 Agent 手动制定计划。',
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
310
441
|
export interface DeptReadFilter {
|
|
311
442
|
kind?: DeptKind
|
|
312
443
|
since?: number
|
|
313
444
|
limit?: number
|
|
445
|
+
/** true=取最近 limit 条(尾部);默认 false=按追加序取最早 limit 条。 */
|
|
446
|
+
newest?: boolean
|
|
314
447
|
}
|
|
315
448
|
|
|
316
449
|
/**
|
|
317
450
|
* 按追加序回放留痕(契约 §2):
|
|
318
451
|
* - 文件不存在 → 空列表(ok:true);
|
|
319
452
|
* - 坏行(JSON 损坏或校验不过)计入 skipped,不静默吞;
|
|
320
|
-
* - kind/since 过滤后按 limit 截取:默认 500、上限 5000;
|
|
453
|
+
* - kind/since 过滤后按 limit 截取:默认 500、上限 5000;newest=true 取最近,否则取最早;
|
|
321
454
|
* - planId 非法或读盘失败 → 显式 JOURNAL_READ_FAILED。
|
|
322
455
|
*/
|
|
323
456
|
export function readDeptMessages(
|
|
@@ -369,5 +502,84 @@ export function readDeptMessages(
|
|
|
369
502
|
if (since !== null && message.ts < since) continue
|
|
370
503
|
matched.push(message)
|
|
371
504
|
}
|
|
372
|
-
return { ok: true, messages: matched.slice(0, limit), skipped }
|
|
505
|
+
return { ok: true, messages: filter?.newest ? matched.slice(-limit) : matched.slice(0, limit), skipped }
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
/**
|
|
509
|
+
* [3.0.6][第 2 批] 留痕目录的可选保留策略(默认关闭)。
|
|
510
|
+
*
|
|
511
|
+
* 审计证据不该被默认删除,所以本函数只在显式配置
|
|
512
|
+
* `journalRetentionDays > 0`(或环境变量
|
|
513
|
+
* `DSH_WORKPLAN_JOURNAL_RETENTION_DAYS`)时被调用。它只删除同时满足以下
|
|
514
|
+
* 条件的文件:目录里直接的 `.jsonl` 普通文件、文件名是合法 planId、
|
|
515
|
+
* mtime 早于保留天数。活跃计划会持续追加,mtime 保持新,因此不会被误删。
|
|
516
|
+
*
|
|
517
|
+
* 单次最多删 `maxFiles`(默认 200,上限 1000)个最旧文件,避免一次启动
|
|
518
|
+
* 长时间阻塞;删除失败不再静默跳过——逐个 console.warn 一行并收集进
|
|
519
|
+
* 返回值的 `errors[]`(ok 保持 true,兼容既有调用方)。
|
|
520
|
+
*
|
|
521
|
+
* [复审修复] `excludePlanIds`(可选):文件名(去 .jsonl)在集合内的一律
|
|
522
|
+
* 跳过删除,防「活跃但安静」(久无新消息、mtime 变旧)的计划被误删。
|
|
523
|
+
*/
|
|
524
|
+
export function pruneJournal(options: {
|
|
525
|
+
retentionDays: number
|
|
526
|
+
now?: number
|
|
527
|
+
maxFiles?: number
|
|
528
|
+
/** 活跃计划保护名单:journal 文件名(去 .jsonl)在集合内的跳过删除。 */
|
|
529
|
+
excludePlanIds?: ReadonlySet<string>
|
|
530
|
+
}): { ok: boolean; scanned: number; deleted: string[]; error?: string; errors?: string[] } {
|
|
531
|
+
const days = Number(options?.retentionDays)
|
|
532
|
+
if (!Number.isFinite(days) || days <= 0) return { ok: true, scanned: 0, deleted: [] }
|
|
533
|
+
const dir = resolveJournalDir()
|
|
534
|
+
let names: string[]
|
|
535
|
+
try {
|
|
536
|
+
names = readdirSync(dir)
|
|
537
|
+
} catch (error: any) {
|
|
538
|
+
if (error?.code === 'ENOENT') return { ok: true, scanned: 0, deleted: [] }
|
|
539
|
+
return { ok: false, scanned: 0, deleted: [], error: errorText(error) }
|
|
540
|
+
}
|
|
541
|
+
const now = Number.isFinite(options?.now) ? Number(options.now) : Date.now()
|
|
542
|
+
const cutoff = now - days * 24 * 60 * 60 * 1000
|
|
543
|
+
const maxFiles = Math.max(0, Math.min(1000, Math.trunc(options?.maxFiles ?? 200)))
|
|
544
|
+
const exclude = options?.excludePlanIds
|
|
545
|
+
const candidates: Array<{ name: string; path: string; mtimeMs: number }> = []
|
|
546
|
+
for (const name of names) {
|
|
547
|
+
if (!name.endsWith('.jsonl')) continue
|
|
548
|
+
const planId = name.slice(0, -'.jsonl'.length)
|
|
549
|
+
if (!PLAN_ID_PATTERN.test(planId)) continue
|
|
550
|
+
// 活跃但安静的保护名单:在册计划即使 mtime 超期也不删。
|
|
551
|
+
if (exclude?.has(planId)) continue
|
|
552
|
+
const path = join(dir, name)
|
|
553
|
+
try {
|
|
554
|
+
const stat = lstatSync(path)
|
|
555
|
+
// 只删普通文件;符号链接一律跳过(防越界删除)。
|
|
556
|
+
if (!stat.isFile() || stat.isSymbolicLink()) continue
|
|
557
|
+
if (stat.mtimeMs >= cutoff) continue
|
|
558
|
+
candidates.push({ name, path, mtimeMs: stat.mtimeMs })
|
|
559
|
+
} catch {
|
|
560
|
+
// 单个文件 stat 失败不影响其他文件,最后以 scanned 如实反映总数。
|
|
561
|
+
continue
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
candidates.sort((a, b) => a.mtimeMs - b.mtimeMs)
|
|
565
|
+
const deleted: string[] = []
|
|
566
|
+
const errors: string[] = []
|
|
567
|
+
for (const candidate of candidates.slice(0, maxFiles)) {
|
|
568
|
+
try {
|
|
569
|
+
unlinkSync(candidate.path)
|
|
570
|
+
deleted.push(candidate.name)
|
|
571
|
+
} catch (error) {
|
|
572
|
+
// 单个 unlink 失败不再静默:收集原因 + 逐条 warn(ok 保持 true 兼容)。
|
|
573
|
+
const reason = `${candidate.name}: ${errorText(error)}`
|
|
574
|
+
errors.push(reason)
|
|
575
|
+
console.warn(`dsh-workplan: journal 保留清理删除失败 ${reason} path=${candidate.path}`)
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const result: { ok: boolean; scanned: number; deleted: string[]; error?: string; errors?: string[] } = {
|
|
579
|
+
ok: true,
|
|
580
|
+
scanned: names.length,
|
|
581
|
+
deleted,
|
|
582
|
+
}
|
|
583
|
+
if (errors.length > 0) result.errors = errors
|
|
584
|
+
return result
|
|
373
585
|
}
|