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.
@@ -0,0 +1,251 @@
1
+ /**
2
+ * [3.0.6][第 3 批②] dsh-workplan 专用通知台账(notice ledger)。
3
+ *
4
+ * 审计病根:插件通知唯一的持久可见通道是 user/message,与用户真实输入混在同
5
+ * 一条事件流里(source.kind 虽可区分,但没有任何插件侧权威台账可供工具/前端
6
+ * 直接消费)。
7
+ *
8
+ * 官方约束(dsh-agent-preset/skills/dsh-doc/references/practices.md:21):
9
+ * 1. 禁止给 Session 新增自定义事件类型——live Session.append 无法打
10
+ * ignorable 标记,重启后 Session 会拒绝重新打开;
11
+ * 2. appendPluginRecord() 保留给 DSH 实验包,本插件不得使用;
12
+ * 3. 插件自有数据应放在插件自己的存储里。
13
+ *
14
+ * 因此 v1 专用通道 = 插件自有 JSONL 台账(默认 ~/.dsh/workplan/notices.jsonl,
15
+ * 可用 DSH_WORKPLAN_NOTICES_FILE 覆盖):
16
+ * - appendUserMessage 每次成功落盘一条 workplan 通知后,同步追加一行台账;
17
+ * - 台账行自带 sessionId/planId/kind/form/summary/text,是机器可读的权威
18
+ * 通知流(区别于用户真实输入——真实输入永远不会进本文件);
19
+ * - 写入失败不拖垮通知投递(user/message 才是模型的权威通道,且已通过
20
+ * 回读校验):失败行进内存环形缓冲,下一次写入时先行补落,尽最大努力
21
+ * 不丢、且绝不静默。
22
+ *
23
+ * 纪律与 lessons.ts(第 1 批)一致:同步读写、整行 JSON、坏行读端跳过/写端
24
+ * 原样保留。审计证据默认永久保留,不做轮转(与 journalRetentionDays 默认 0
25
+ * 的裁决一致)。
26
+ *
27
+ * [复审修复][第 4 批] 治理与安全加固:
28
+ * - 行数上限 NOTICE_LEDGER_MAX_LINES(默认 5000,可被正整数环境变量
29
+ * DSH_WORKPLAN_NOTICES_MAX_LINES 覆盖):超限即重写为「最新 N 行」
30
+ * (读全 → 取末 N → tmp+rename 原子替换),重写失败 best-effort 不拖垮写入;
31
+ * - 权限:目录 0o700、文件 0o600(新建以 mode 落盘、既有文件 best-effort chmod);
32
+ * - 防符号链接投毒:写/重写前 lstatSync 目标文件,是符号链接则跳过写入并
33
+ * console.warn(不抛错),绝不跟随链接写任意路径。
34
+ */
35
+ import { appendFileSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'
36
+ import { homedir } from 'node:os'
37
+ import { dirname, join } from 'node:path'
38
+
39
+ export const NOTICE_LEDGER_VERSION = 1
40
+ /** 写失败时的内存环形缓冲上限(尽最大努力补落,绝不清空丢弃)。 */
41
+ export const NOTICE_LEDGER_OVERFLOW_MAX = 100
42
+ /** 台账行数上限:超过即重写为「最新 N 行」。可被 DSH_WORKPLAN_NOTICES_MAX_LINES(正整数)覆盖。 */
43
+ export const NOTICE_LEDGER_MAX_LINES = 5000
44
+
45
+ function errorText(error: unknown): string {
46
+ const text = error instanceof Error ? error.message : String(error)
47
+ return text.slice(0, 500)
48
+ }
49
+
50
+ /** 解析行数上限(env 优先,沿用 resolveNoticeLedgerFile 的解析风格)。 */
51
+ function resolveNoticeLedgerMaxLines(env: NodeJS.ProcessEnv = process.env): number {
52
+ const raw = typeof env?.DSH_WORKPLAN_NOTICES_MAX_LINES === 'string'
53
+ ? env.DSH_WORKPLAN_NOTICES_MAX_LINES.trim()
54
+ : ''
55
+ if (!raw) return NOTICE_LEDGER_MAX_LINES
56
+ const parsed = Number(raw)
57
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : NOTICE_LEDGER_MAX_LINES
58
+ }
59
+
60
+ /** 统计文本中的行数(按换行计;本模块写盘恒以 \n 结尾,行数 == \n 数)。 */
61
+ function countNewlines(text: string): number {
62
+ let count = 0
63
+ for (let i = 0; i < text.length; i += 1) {
64
+ if (text.charCodeAt(i) === 10) count += 1
65
+ }
66
+ return count
67
+ }
68
+
69
+ /**
70
+ * 行数治理:写后若总行数超过上限,重写为「最新 N 行」。
71
+ * 全程 best-effort:任何失败只 console.warn,绝不抛错、绝不拖垮已成功的写入。
72
+ */
73
+ function enforceNoticeLedgerCap(file: string, maxLines: number): void {
74
+ if (!Number.isSafeInteger(maxLines) || maxLines <= 0) return
75
+ let text: string
76
+ try {
77
+ text = readFileSync(file, 'utf8')
78
+ } catch (error) {
79
+ console.warn(`dsh-workplan: notice 台账行数统计失败(不重写)file=${file}(${errorText(error)})`)
80
+ return
81
+ }
82
+ const total = countNewlines(text)
83
+ if (total <= maxLines) return
84
+ // 防符号链接投毒:重写前再确认目标是普通文件(TOCTOU 缩小面;rename 只换链接本身也不跟随,但按纪律跳过)。
85
+ try {
86
+ if (lstatSync(file).isSymbolicLink()) {
87
+ console.warn(`dsh-workplan: notice 台账是符号链接,跳过重写 file=${file}`)
88
+ return
89
+ }
90
+ } catch (error) {
91
+ console.warn(`dsh-workplan: notice 台账重写前 lstat 失败(不重写)file=${file}(${errorText(error)})`)
92
+ return
93
+ }
94
+ const kept = text.split('\n').filter((line) => line.trim() !== '').slice(-maxLines)
95
+ const body = kept.length > 0 ? `${kept.join('\n')}\n` : ''
96
+ const tmp = `${file}.tmp-${process.pid}`
97
+ try {
98
+ writeFileSync(tmp, body, { encoding: 'utf8', mode: 0o600 })
99
+ renameSync(tmp, file)
100
+ } catch (error) {
101
+ console.warn(`dsh-workplan: notice 台账超限重写失败(保留原文件)file=${file}(${errorText(error)})`)
102
+ try {
103
+ unlinkSync(tmp)
104
+ } catch {
105
+ /* 临时文件清理失败可忽略。 */
106
+ }
107
+ }
108
+ }
109
+
110
+ export type NoticeLedgerRecord = {
111
+ version: number
112
+ at: number
113
+ sessionId: string
114
+ planId: string
115
+ kind: string
116
+ form: string
117
+ summary: string
118
+ text: string
119
+ /** 对应的 user/message 事件 seq(写入时未知则为 -1)。 */
120
+ surfaceSeq: number
121
+ }
122
+
123
+ /** 台账文件位置:默认用户主目录,跨项目保留;测试可用环境变量覆盖。 */
124
+ export function resolveNoticeLedgerFile(env: NodeJS.ProcessEnv = process.env): string {
125
+ const override = typeof env?.DSH_WORKPLAN_NOTICES_FILE === 'string'
126
+ ? env.DSH_WORKPLAN_NOTICES_FILE.trim()
127
+ : ''
128
+ if (override) return override
129
+ return join(homedir(), '.dsh', 'workplan', 'notices.jsonl')
130
+ }
131
+
132
+ function isRecord(value: unknown): value is Record<string, unknown> {
133
+ return !!value && typeof value === 'object' && !Array.isArray(value)
134
+ }
135
+
136
+ function coerceRecord(raw: unknown): NoticeLedgerRecord | null {
137
+ if (!isRecord(raw)) return null
138
+ return {
139
+ version: Number(raw.version) || NOTICE_LEDGER_VERSION,
140
+ at: Number(raw.at) || 0,
141
+ sessionId: typeof raw.sessionId === 'string' ? raw.sessionId : '',
142
+ planId: typeof raw.planId === 'string' ? raw.planId : '',
143
+ kind: typeof raw.kind === 'string' ? raw.kind : '',
144
+ form: typeof raw.form === 'string' ? raw.form : '',
145
+ summary: typeof raw.summary === 'string' ? raw.summary : '',
146
+ text: typeof raw.text === 'string' ? raw.text : '',
147
+ surfaceSeq: Number.isSafeInteger(Number(raw.surfaceSeq)) ? Number(raw.surfaceSeq) : -1,
148
+ }
149
+ }
150
+
151
+ /** 读端:坏行跳过不拖垮整份台账。 */
152
+ export function readNoticeLedger(file: string = resolveNoticeLedgerFile()): NoticeLedgerRecord[] {
153
+ if (!existsSync(file)) return []
154
+ let text = ''
155
+ try {
156
+ text = readFileSync(file, 'utf8')
157
+ } catch {
158
+ return []
159
+ }
160
+ const out: NoticeLedgerRecord[] = []
161
+ for (const line of text.split('\n')) {
162
+ const trimmed = line.trim()
163
+ if (!trimmed) continue
164
+ try {
165
+ const parsed = coerceRecord(JSON.parse(trimmed))
166
+ if (parsed) out.push(parsed)
167
+ } catch {
168
+ // 单行损坏跳过:append-only 文件不做重写,坏行原样留在盘上。
169
+ }
170
+ }
171
+ return out
172
+ }
173
+
174
+ /** 内存补落缓冲:文件写入失败时暂存,下一次写入先行补落。 */
175
+ let overflow: string[] = []
176
+
177
+ /** 取出当前积压的补落行数(可观测性/测试用)。 */
178
+ export function noticeLedgerOverflowSize(): number {
179
+ return overflow.length
180
+ }
181
+
182
+ function textOfMessage(message: any): string {
183
+ const content = message?.content
184
+ if (typeof content === 'string') return content
185
+ if (Array.isArray(content)) {
186
+ return content
187
+ .map((block: any) => (typeof block?.text === 'string' ? block.text : ''))
188
+ .filter(Boolean)
189
+ .join('\n')
190
+ }
191
+ return ''
192
+ }
193
+
194
+ /**
195
+ * 追加一行通知台账(同步、尽力而为)。
196
+ *
197
+ * @returns 是否写入(含补落)成功;失败行留在内存环形缓冲等待下次补落。
198
+ */
199
+ export function appendNoticeLedger(
200
+ sessionId: string,
201
+ message: any,
202
+ file: string = resolveNoticeLedgerFile(),
203
+ now: number = Date.now(),
204
+ ): boolean {
205
+ const source = isRecord(message?.source) ? message.source : {}
206
+ const record: NoticeLedgerRecord = {
207
+ version: NOTICE_LEDGER_VERSION,
208
+ at: now,
209
+ sessionId: String(sessionId ?? ''),
210
+ planId: typeof source.planId === 'string' ? source.planId
211
+ : (typeof message?.planId === 'string' ? message.planId : ''),
212
+ kind: typeof source.kind === 'string' ? source.kind : 'workplan',
213
+ form: typeof source.form === 'string' ? source.form : 'notice',
214
+ summary: typeof source.summary === 'string' ? source.summary : '',
215
+ text: textOfMessage(message),
216
+ surfaceSeq: typeof message?.seq === 'number' ? message.seq : -1,
217
+ }
218
+ return flushNoticeLedger(file, [JSON.stringify(record)])
219
+ }
220
+
221
+ /** 先补落积压行,再写新行;全部成功才清空缓冲。 */
222
+ function flushNoticeLedger(file: string, freshLines: string[]): boolean {
223
+ const pending = [...overflow, ...freshLines]
224
+ // 防符号链接投毒:目标是符号链接则跳过写入并告警(不抛错,行留缓冲等待下次)。
225
+ try {
226
+ if (lstatSync(file).isSymbolicLink()) {
227
+ console.warn(`dsh-workplan: notice 台账目标是符号链接,跳过写入 file=${file}`)
228
+ overflow = pending.slice(-NOTICE_LEDGER_OVERFLOW_MAX)
229
+ return false
230
+ }
231
+ } catch {
232
+ /* 文件不存在(ENOENT,首写)或 lstat 失败:交给 appendFileSync 显式成败。 */
233
+ }
234
+ try {
235
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 })
236
+ appendFileSync(file, `${pending.join('\n')}\n`, { encoding: 'utf8', mode: 0o600 })
237
+ try {
238
+ // 既有文件权限收紧为 0o600(best-effort;新建文件已由 mode 覆盖)。
239
+ chmodSync(file, 0o600)
240
+ } catch {
241
+ /* best-effort:权限收紧失败不阻断追加。 */
242
+ }
243
+ overflow = []
244
+ // 行数治理(best-effort):超限即重写为「最新 N 行」,失败只 warn 不拖垮写入。
245
+ enforceNoticeLedgerCap(file, resolveNoticeLedgerMaxLines())
246
+ return true
247
+ } catch {
248
+ overflow = pending.slice(-NOTICE_LEDGER_OVERFLOW_MAX)
249
+ return false
250
+ }
251
+ }