sage-mem 2.17.1 → 2.19.0

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,406 @@
1
+ /**
2
+ * sage-mem autodream — `search_sessions` 的**运行时层**:zstd 帧解析、目录枚举、读文件、编排。
3
+ *
4
+ * 与 `session-search-policy.js` 的分工:**这里只做 IO,不做决定**。选哪个会话、片段切多宽、
5
+ * 账怎么算、话怎么说,全在纯层(那条边界由 `test/structure-test.mjs` 第 5 组看着)。
6
+ *
7
+ * ## 为什么解压要逐帧走
8
+ *
9
+ * 会话正文是**逐行一个 zstd 帧**拼起来的,而 Node 的解码器都只认第一个帧:
10
+ * - `zstdDecompressSync(buf)` 只解第一帧,后面的帧全丢,于是搜到的永远只有会话开头
11
+ * - `zstdDecompress(buf)` 单参数调用直接抛(它要 callback)—— 旧代码正是这么调的,
12
+ * 于是每个会话都在 catch 里被静默跳过,整条 `search_sessions` **一次都没成功过**
13
+ * 所以沿帧头走:Magic → Frame_Header_Descriptor → (Window / DictID / ContentSize) →
14
+ * 逐块 Block_Header 直到 Last_Block → 可选 checksum。
15
+ *
16
+ * ## 2.19.0:把「解了一半」变成可证的事实
17
+ *
18
+ * 旧解码器只回 `text|null`,于是「5 帧里坏了 1 帧」与「5 帧全好」在调用方看来完全一样。
19
+ * 现在 `decodeZstdFramesDetailed` 回报 `frames` / `decoded` / `resynced`,纯层据此把该文件
20
+ * 记成 `partial` 而不是 `searched` —— 覆盖率才不是自述。
21
+ *
22
+ * ## 成本(为什么不扩大上限)
23
+ *
24
+ * 解压是整份进内存的:未命中时没有任何早停点,候选份数 × 单份正文体积就是每次调用的固定开销,
25
+ * 而单份会话解出来往往是它压缩体积的数倍。要扩大扫描面,第一步是逐帧早停或流式,
26
+ * 而不是把上限改大。
27
+ *
28
+ * ## 两个注入点(都只为测试,生产不传)
29
+ *
30
+ * - `opts.zlib`:证明「没有 zstd 时不许谎称零命中」;
31
+ * - `opts.io`:`{readdir, stat, readFile}` —— 让 ENOTDIR / 枚举失败这类**真实失败分支**
32
+ * 能被确定性地跑到(照 `autodream/reconcile.js` 注入 `listEntries` / `readLedger` 的同一手法)。
33
+ */
34
+
35
+ import { readFile, readdir, stat } from 'node:fs/promises'
36
+ import { join } from 'node:path'
37
+ import { stampHuman as localStamp } from '../shared/stamp.js'
38
+ import {
39
+ CHAR_BUDGET,
40
+ DEFAULT_HIT_LIMIT,
41
+ HIT_CHARS,
42
+ MAX_HIT_LIMIT,
43
+ MIN_NEEDLE_CHARS,
44
+ SEARCH_DIR_CAP,
45
+ classifyCoverage,
46
+ classifySessionFileName,
47
+ matchLines,
48
+ pickSessionsByMtime,
49
+ renderSearchReport,
50
+ } from './session-search-policy.js'
51
+
52
+ /** zstd 帧魔数(小端读出来的值)。 */
53
+ const ZSTD_MAGIC = 0xfd2fb528
54
+ /** 同一个魔数的字节形态:认不出帧头时要靠它找下一个帧的起点。 */
55
+ const ZSTD_MAGIC_BYTES = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
56
+
57
+ /** 真实文件系统(测试可经 `opts.io` 换掉)。 */
58
+ const REAL_IO = Object.freeze({ readdir, stat, readFile })
59
+
60
+ /**
61
+ * 量一个 zstd 帧占多少字节(从 `off` 开始)。不是合法帧头、或帧被截断,返回 0。
62
+ * @returns {number}
63
+ */
64
+ export function zstdFrameLength(buf, off) {
65
+ if (off + 5 > buf.length) return 0
66
+ if (buf.readUInt32LE(off) !== ZSTD_MAGIC) return 0
67
+ let p = off + 4
68
+ const fhd = buf[p++]
69
+ const fcsFlag = fhd >> 6
70
+ const singleSegment = (fhd >> 5) & 1
71
+ const checksum = (fhd >> 2) & 1
72
+ const dictIdFlag = fhd & 3
73
+ if (!singleSegment) p += 1 // Window_Descriptor
74
+ p += [0, 1, 2, 4][dictIdFlag] // Dictionary_ID
75
+ p += singleSegment ? [1, 2, 4, 8][fcsFlag] : [0, 2, 4, 8][fcsFlag] // Frame_Content_Size
76
+ if (p > buf.length) return 0
77
+ for (;;) {
78
+ if (p + 3 > buf.length) return 0
79
+ const h = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16)
80
+ p += 3
81
+ const last = h & 1
82
+ const type = (h >> 1) & 3
83
+ const size = h >>> 3
84
+ if (type === 3) return 0 // Reserved:不是我们能认的帧
85
+ p += type === 1 ? 1 : size // RLE 块只存 1 字节
86
+ if (last) break
87
+ if (p > buf.length) return 0
88
+ }
89
+ if (checksum) p += 4
90
+ return p <= buf.length ? p - off : 0
91
+ }
92
+
93
+ /**
94
+ * 把「可能由多个帧拼成」的 zstd 缓冲解成文本,并**如实回报解了多少**。
95
+ *
96
+ * - `frames`:认出长度的帧数(含解失败的);
97
+ * - `decoded`:真正解出来的帧数;
98
+ * - `resynced`:认不出帧头、跳到下一个魔数的次数(中间那些字节被丢弃);
99
+ * - `trailing`:扫完后**还剩下没被解析的字节**(帧被截断时最外层帧头都读不出来,
100
+ * 于是它既不算 frames 也不算 resynced —— 不单独记这一条,「尾部丢了」就会无声无息);
101
+ * - `fallback`:一帧都没认出长度时,退回整块解(单帧老文件的形状)。
102
+ *
103
+ * `text === null` 才是「一个字节都没解出来」;`decoded < frames`、`resynced > 0` 或
104
+ * `trailing === true` 都表示**部分解码** —— 由纯层记成 `partial`。
105
+ *
106
+ * @returns {{text:string|null, frames:number, decoded:number, resynced:number,
107
+ * trailing:boolean, fallback:boolean}}
108
+ */
109
+ export function decodeZstdFramesDetailed(zlib, buf) {
110
+ const parts = []
111
+ let off = 0
112
+ let frames = 0
113
+ let decoded = 0
114
+ let resynced = 0
115
+ while (off < buf.length) {
116
+ const len = zstdFrameLength(buf, off)
117
+ if (len <= 0) {
118
+ /**
119
+ * 认不出帧头:**跳到下一个魔数**继续,而不是停下。
120
+ *
121
+ * 停下的代价是「这一帧之后的内容全部静默丢失」—— 而那些帧本来是好的
122
+ * (把某帧的块头改成 Reserved 就能让后面所有帧都再也搜不到)。
123
+ */
124
+ const next = buf.indexOf(ZSTD_MAGIC_BYTES, off + 1)
125
+ if (next < 0) break
126
+ off = next
127
+ resynced += 1
128
+ continue
129
+ }
130
+ try {
131
+ parts.push(zlib.zstdDecompressSync(buf.subarray(off, off + len)))
132
+ decoded += 1
133
+ } catch {
134
+ // 单帧坏掉:跳过它,继续后面的帧
135
+ }
136
+ off += len
137
+ frames += 1
138
+ }
139
+ // 循环退出时 off 还没走到末尾 = 尾部有解析不了的字节(典型形态:最后一帧被截断)。
140
+ const trailing = off < buf.length
141
+ if (frames === 0) {
142
+ try {
143
+ return {
144
+ text: zlib.zstdDecompressSync(buf).toString('utf8'),
145
+ frames: 0,
146
+ decoded: 1,
147
+ resynced,
148
+ trailing,
149
+ fallback: true,
150
+ }
151
+ } catch {
152
+ return { text: null, frames: 0, decoded: 0, resynced, trailing, fallback: true }
153
+ }
154
+ }
155
+ if (decoded === 0) return { text: null, frames, decoded, resynced, trailing, fallback: false }
156
+ return { text: Buffer.concat(parts).toString('utf8'), frames, decoded, resynced, trailing, fallback: false }
157
+ }
158
+
159
+ /** `err.code` → coverage 的根状态。**不许**把读不了降级成「空的」。 */
160
+ function rootStateOf(err) {
161
+ const code = err?.code
162
+ if (code === 'ENOENT') return 'missing'
163
+ if (code === 'ENOTDIR') return 'notdir'
164
+ if (code === 'EACCES' || code === 'EPERM') return 'denied'
165
+ return 'error'
166
+ }
167
+
168
+ function messageOf(err) {
169
+ return String(err?.message ?? err ?? '')
170
+ }
171
+
172
+ /**
173
+ * 走一遍 `$DSH_HOME/sessions`:project 目录 → 会话目录 → 认得的会话文件。
174
+ *
175
+ * 两处刻意与旧实现相反:
176
+ * - 项目的 `readdir` 失败**不再** `catch(() => [])`(那等于「这个 project 不存在」),
177
+ * 而是记进 `enumerationFailed` —— 枚举不全本身就是覆盖不完整的一条;
178
+ * - 一个会话目录里**先数完所有文件名**:认不得的代际(v3 / 无版本)一律计入
179
+ * `unrecognized`,再去挑 v4。先挑后数会漏掉「v4 与旧格式同目录」里的旧格式。
180
+ *
181
+ * @param {string} root
182
+ * @param {{readdir:Function, stat:Function}} [io]
183
+ * @returns {Promise<{root:string, message:string, files:Array<{file:string, mtimeMs:number}>,
184
+ * unrecognized:number, enumerationFailed:number}>}
185
+ */
186
+ export async function enumerateSessions(root, io = REAL_IO) {
187
+ const out = { root: 'ok', message: '', files: [], unrecognized: 0, enumerationFailed: 0 }
188
+ let projects
189
+ try {
190
+ projects = await io.readdir(root, { withFileTypes: true })
191
+ } catch (err) {
192
+ out.root = rootStateOf(err)
193
+ out.message = messageOf(err)
194
+ return out
195
+ }
196
+ for (const p of projects) {
197
+ if (!p.isDirectory()) continue
198
+ const projPath = join(root, p.name)
199
+ let sessions
200
+ try {
201
+ sessions = await io.readdir(projPath, { withFileTypes: true })
202
+ } catch {
203
+ out.enumerationFailed += 1
204
+ continue
205
+ }
206
+ for (const s of sessions) {
207
+ if (!s.isDirectory()) continue
208
+ const dirPath = join(projPath, s.name)
209
+ let names
210
+ try {
211
+ names = await io.readdir(dirPath, { withFileTypes: true })
212
+ } catch {
213
+ out.enumerationFailed += 1
214
+ continue
215
+ }
216
+ let recognized = ''
217
+ for (const f of names) {
218
+ // 候选既可以是普通文件,也可以是符号链接:链接目标是不是普通文件由下面的
219
+ // `stat` 判定(`stat` 跟着链接走)。早先用 `isFile()` 把它们直接跳过,
220
+ // 结果是「stat 能读到、搜索却看不见」—— 同一份会话在两条路径上待遇不同。
221
+ if (!f.isFile() && !f.isSymbolicLink()) continue
222
+ const kind = classifySessionFileName(f.name)
223
+ // 先把旧代际数掉,再挑 v4:**不许**在遇到 v4 时 break —— 否则同一目录里
224
+ // 排在 v4 之后的旧格式会被静默漏计。
225
+ if (kind === 'unrecognized') {
226
+ out.unrecognized += 1
227
+ continue
228
+ }
229
+ if (kind !== 'v4') continue
230
+ // 同一目录出现第二份 v4(大小写不同的文件系统上可能)不是「随便挑一个」的时候:
231
+ // 挑哪份都会漏另一份,所以记账(枚举失败)并只用第一份。
232
+ if (recognized) {
233
+ out.enumerationFailed += 1
234
+ continue
235
+ }
236
+ recognized = f.name
237
+ }
238
+ if (!recognized) continue
239
+ const file = join(dirPath, recognized)
240
+ let info
241
+ try {
242
+ info = await io.stat(file)
243
+ } catch {
244
+ out.enumerationFailed += 1
245
+ continue
246
+ }
247
+ // 链接指向目录 / 设备 / 不存在的东西:读不了就是读不了,记一笔,别让它变成「零命中」。
248
+ if (typeof info.isFile !== 'function' || !info.isFile()) {
249
+ out.enumerationFailed += 1
250
+ continue
251
+ }
252
+ out.files.push({ file, mtimeMs: info.mtimeMs })
253
+ }
254
+ }
255
+ return out
256
+ }
257
+
258
+ /** `limit` 夹到 1..MAX_HIT_LIMIT;非法回落默认值。 */
259
+ function clampLimit(raw) {
260
+ const n = Number(raw)
261
+ if (!Number.isFinite(n)) return DEFAULT_HIT_LIMIT
262
+ return Math.max(1, Math.min(MAX_HIT_LIMIT, Math.floor(n)))
263
+ }
264
+
265
+ /** 取 zlib;允许注入(测试要证明「没有 zstd 时不许谎称零命中」)。 */
266
+ async function resolveZlib(injected) {
267
+ if (injected !== undefined) return injected
268
+ try {
269
+ return await import('node:zlib')
270
+ } catch {
271
+ return null
272
+ }
273
+ }
274
+
275
+ /**
276
+ * 搜索的**结构化**形态:`{text, hits, coverage}`。
277
+ *
278
+ * 为什么要和 `searchSessions` 分开:工具契约是「永远回字符串」(`llm-loop.js:383` 只吃字符串),
279
+ * 但覆盖率是一份**账**,测试与将来可能的报告要能逐字段断言,而不是去正则里捞。
280
+ *
281
+ * @param {string} sessionsRoot — `$DSH_HOME/sessions`
282
+ * @param {string} query — 关键词(≥2 字符)
283
+ * @param {{limit?:number, sinceMs?:number, zlib?:object|null, io?:object, cap?:number, charBudget?:number}} [opts]
284
+ * @returns {Promise<{text:string, hits:Array<object>, coverage:object|null}>}
285
+ */
286
+ export async function runSessionSearch(sessionsRoot, query, opts = {}) {
287
+ const raw = String(query ?? '')
288
+ const needle = raw.toLowerCase()
289
+ if (needle.length < MIN_NEEDLE_CHARS) {
290
+ return { text: `(关键词太短,至少 ${MIN_NEEDLE_CHARS} 个字符)`, hits: [], coverage: null }
291
+ }
292
+
293
+ const limit = clampLimit(opts.limit)
294
+ const dirCap = Number.isFinite(opts.cap) ? Math.max(1, Math.floor(opts.cap)) : SEARCH_DIR_CAP
295
+ const charBudget = Number.isFinite(opts.charBudget) ? Math.max(1, Math.floor(opts.charBudget)) : CHAR_BUDGET
296
+ const caps = { dirCap, charBudget, limit }
297
+ const sinceMs = Number.isFinite(opts.sinceMs) ? Number(opts.sinceMs) : 0
298
+ const io = opts.io ?? REAL_IO
299
+
300
+ const build = (partial) => {
301
+ const coverage = classifyCoverage({ caps, ...partial })
302
+ const hits = Array.isArray(partial.hits) ? partial.hits : []
303
+ return { text: renderSearchReport({ rawQuery: raw, hits, coverage }), hits, coverage }
304
+ }
305
+
306
+ if (!sessionsRoot) return build({ root: 'unset' })
307
+
308
+ const zlib = await resolveZlib(opts.zlib)
309
+ const zstdUnsupported = !zlib || typeof zlib.zstdDecompressSync !== 'function'
310
+
311
+ const enumerated = await enumerateSessions(sessionsRoot, io)
312
+ if (enumerated.root !== 'ok') {
313
+ return build({ root: enumerated.root, rootMessage: enumerated.message })
314
+ }
315
+ const picked = pickSessionsByMtime(enumerated.files, { cap: dirCap, sinceMs })
316
+
317
+ if (zstdUnsupported) {
318
+ /**
319
+ * 读不了解压就别假装看过:但**账要真实** —— 枚举到的份数、上限截掉的份数、
320
+ * 旧格式的份数照记,进队的那几份以「一个字节都解不出来」记成 `failed`。
321
+ *
322
+ * 两处刻意不做的假账:不把 `available` 抹成 0(那会让「有 40 份会话」变成「一份都没有」),
323
+ * 也不把进队的记成 `skippedByOutput`(它们根本不是被输出预算停下的)。
324
+ */
325
+ return build({
326
+ root: 'ok',
327
+ zstdUnsupported: true,
328
+ available: picked.available,
329
+ outcomes: picked.considered.map(() => 'failed'),
330
+ unrecognized: enumerated.unrecognized,
331
+ enumerationFailed: enumerated.enumerationFailed,
332
+ })
333
+ }
334
+
335
+ const outcomes = []
336
+ const hits = []
337
+ let hitChars = 0
338
+ let clipped = false
339
+ let stoppedBy = null
340
+ let skippedByOutput = 0
341
+
342
+ for (const entry of picked.considered) {
343
+ // 输出已经停了:后面的会话**一份都不读**(不花 I/O),但必须记账 —— 它们是「没开始」。
344
+ if (stoppedBy) {
345
+ skippedByOutput += 1
346
+ continue
347
+ }
348
+ let buf
349
+ try {
350
+ buf = await io.readFile(entry.file)
351
+ } catch {
352
+ outcomes.push('failed')
353
+ continue
354
+ }
355
+ const decoded = decodeZstdFramesDetailed(zlib, buf)
356
+ if (decoded.text === null) {
357
+ outcomes.push('failed')
358
+ continue
359
+ }
360
+ const scan = matchLines(decoded.text, raw, {
361
+ perLineChars: HIT_CHARS,
362
+ limit: Math.max(1, limit - hits.length),
363
+ charBudget: Math.max(0, charBudget - hitChars),
364
+ })
365
+ for (const h of scan.hits) hits.push({ ...h, stamp: localStamp(entry.mtimeMs) })
366
+ hitChars += scan.hitChars
367
+ if (scan.clipped) clipped = true
368
+ if (scan.stoppedBy) stoppedBy = scan.stoppedBy
369
+ // 四条 partial 通道:帧解丢、跳帧重同步、尾部有没解析到的字节、这一份没读完(输出上限)。
370
+ const decodePartial =
371
+ (decoded.frames > 0 && decoded.decoded < decoded.frames) || decoded.resynced > 0 || decoded.trailing === true
372
+ outcomes.push(decodePartial || scan.stoppedEarly ? 'partial' : 'searched')
373
+ }
374
+
375
+ return build({
376
+ root: 'ok',
377
+ // 分母与「因上限没看」同源:都取自时间过滤之后的那份名单。
378
+ available: picked.available,
379
+ outcomes,
380
+ skippedByOutput,
381
+ unrecognized: enumerated.unrecognized,
382
+ enumerationFailed: enumerated.enumerationFailed,
383
+ hitCount: hits.length,
384
+ hitChars,
385
+ stoppedBy,
386
+ clipped,
387
+ hits,
388
+ })
389
+ }
390
+
391
+ /**
392
+ * 工具面入口:**永远回字符串**(失败也是话,不是异常)。
393
+ *
394
+ * @returns {Promise<string>}
395
+ */
396
+ export async function searchSessions(sessionsRoot, query, opts = {}) {
397
+ const result = await runSessionSearch(sessionsRoot, query, opts)
398
+ return result.text
399
+ }
400
+
401
+ /** 三个上限的单一来源(测试据此断言「没被悄悄改大」;生产代码别读)。 */
402
+ export const SESSION_SEARCH_CAPS = Object.freeze({
403
+ dirCap: SEARCH_DIR_CAP,
404
+ charBudget: CHAR_BUDGET,
405
+ hitChars: HIT_CHARS,
406
+ })
@@ -40,13 +40,19 @@ import { decideWriteIntent } from '../memory/write-gate.js'
40
40
  import { inspectMemoryEntry, readVerified, reservedIdentitySet } from '../memory/scan.js'
41
41
  // 2.10.1 体积治理:模型面的 `archive_segment` 与「压缩留痕」都在 size-tools.js(本文件已顶到行数上限)。
42
42
  import { archiveSegmentToolSchema, runArchiveSegment, withCompressionNote } from './size-tools.js'
43
+ // 2.19.0 搜索覆盖度:解码 / 枚举 / 编排在 session-search.js,纯策略在 session-search-policy.js。
44
+ import { searchSessions } from './session-search.js'
43
45
 
44
46
  /** 单次 read_memory 返回的正文上限(字符)。超过就截断并明确告诉模型。 */
45
47
  const READ_LIMIT = 20000
46
48
  /** list_memory 里每条描述保留多少字。 */
47
49
  const LIST_DESC_CHARS = 70
48
- /** search_sessions 单次返回上限(字符)。 */
49
- const SEARCH_LIMIT = 8000
50
+ /**
51
+ * 2.19.0:`search_sessions` 的实现搬到 `session-search.js`(IO)与
52
+ * `session-search-policy.js`(纯策略)。旧实现与「在**全部**的会话记录里没找到」这句话
53
+ * 混在一起,于是「没看全」被说成了「没有」;搬出来之后三条上限各有单一来源,
54
+ * 覆盖率由纯层派生,工具面只剩注册与薄调用。
55
+ */
50
56
  /**
51
57
  * 把一个模型给的文件名收敛成 memory 目录顶层的一个真实路径。
52
58
  *
@@ -149,173 +155,6 @@ async function scanEntries(memoryDir, ctx) {
149
155
  return out
150
156
  }
151
157
 
152
- /** zstd 帧魔数(小端读出来的值)。 */
153
- const ZSTD_MAGIC = 0xfd2fb528
154
- /** 同一个魔数的字节形态:认不出帧头时要靠它找下一个帧的起点。 */
155
- const ZSTD_MAGIC_BYTES = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
156
-
157
- /**
158
- * 量一个 zstd 帧占多少字节(从 `off` 开始)。不是合法帧头、或帧被截断,返回 0。
159
- *
160
- * 为什么要自己量:会话记录是**逐行一个帧**拼起来的,而 Node 的解码器都只认第一个帧 ——
161
- * - `zstdDecompressSync(buf)`:实测只解出第一帧(4.44 MB / 3148 帧的文件只出 266 字符)
162
- * - `zstdDecompress(buf)`:**单参数调用直接抛** `ERR_INVALID_ARG_TYPE`(它要 callback,
163
- * 不是 promise 版)—— 旧代码正是这么调的,于是每个会话都在 `catch` 里被静默跳过,
164
- * 整条 `search_sessions` 实际上**一次都没成功过**
165
- * 所以只能沿帧头走一遍:Magic → Frame_Header_Descriptor → (Window / DictID / ContentSize)
166
- * → 逐块 Block_Header 直到 Last_Block → 可选 checksum。
167
- */
168
- function zstdFrameLength(buf, off) {
169
- if (off + 5 > buf.length) return 0
170
- if (buf.readUInt32LE(off) !== ZSTD_MAGIC) return 0
171
- let p = off + 4
172
- const fhd = buf[p++]
173
- const fcsFlag = fhd >> 6
174
- const singleSegment = (fhd >> 5) & 1
175
- const checksum = (fhd >> 2) & 1
176
- const dictIdFlag = fhd & 3
177
- if (!singleSegment) p += 1 // Window_Descriptor
178
- p += [0, 1, 2, 4][dictIdFlag] // Dictionary_ID
179
- p += singleSegment ? [1, 2, 4, 8][fcsFlag] : [0, 2, 4, 8][fcsFlag] // Frame_Content_Size
180
- if (p > buf.length) return 0
181
- for (;;) {
182
- if (p + 3 > buf.length) return 0
183
- const h = buf[p] | (buf[p + 1] << 8) | (buf[p + 2] << 16)
184
- p += 3
185
- const last = h & 1
186
- const type = (h >> 1) & 3
187
- const size = h >>> 3
188
- if (type === 3) return 0 // Reserved:不是我们能认的帧
189
- p += type === 1 ? 1 : size // RLE 块只存 1 字节
190
- if (last) break
191
- if (p > buf.length) return 0
192
- }
193
- if (checksum) p += 4
194
- return p <= buf.length ? p - off : 0
195
- }
196
-
197
- /**
198
- * 把「可能由多个帧拼成」的 zstd 缓冲解成文本。
199
- *
200
- * 逐帧解、**一帧坏掉不影响后面的帧**;连帧头都认不出时跳到下一个魔数继续。
201
- * 解不出来的帧会被跳过(可能返回空串),整个缓冲里一帧都没解出来则返回 `null`
202
- * —— 由调用方决定怎么记账。
203
- */
204
- function decodeZstdFrames(zlib, buf) {
205
- const parts = []
206
- let off = 0
207
- let frames = 0
208
- let decoded = 0
209
- while (off < buf.length) {
210
- const len = zstdFrameLength(buf, off)
211
- if (len <= 0) {
212
- /**
213
- * 认不出帧头:**跳到下一个魔数**继续,而不是停下。
214
- *
215
- * 停下的代价是「这一帧之后的内容全部静默丢失」—— 而那些帧本来是好的
216
- * (实测:5 帧里第 3 帧的块头被改成 Reserved,后面两帧就再也搜不到了)。
217
- * 未对齐的魔数也可能落在压缩数据里,那时的帧长多半解析不通,由下面的 catch 兜住。
218
- */
219
- const next = buf.indexOf(ZSTD_MAGIC_BYTES, off + 1)
220
- if (next < 0) break
221
- off = next
222
- continue
223
- }
224
- try {
225
- parts.push(zlib.zstdDecompressSync(buf.subarray(off, off + len)))
226
- decoded += 1
227
- } catch {
228
- // 单帧坏掉:跳过它,继续后面的帧
229
- }
230
- off += len
231
- frames += 1
232
- }
233
- if (frames === 0) {
234
- try {
235
- return zlib.zstdDecompressSync(buf).toString('utf8')
236
- } catch {
237
- return null
238
- }
239
- }
240
- if (decoded === 0) return null
241
- return Buffer.concat(parts).toString('utf8')
242
- }
243
-
244
- /**
245
- * 在 DSH 会话记录里做定向搜索。
246
- *
247
- * 会话正文是 zstd 压缩的(`session.v4.jsonl.zstd`),而且是**逐行一个帧** ——
248
- * 所以解压必须逐帧走(见 `decodeZstdFrames`),不需要外部 zstd 可执行文件。
249
- * 只按 mtime 从新到旧扫,命中够数就停:这是「找昨天的报错原文」这类
250
- * 定向问题的用法,不是全量索引。
251
- *
252
- * @param {string} sessionsRoot — `$DSH_HOME/sessions`
253
- * @param {string} query — 关键词(≥2 字符)
254
- * @param {number} limit — 最多返回多少段
255
- * @param {number} sinceMs — 只看这个时间之后改过的会话。工具层**有意传 0**:
256
- * 模型搜的是全部会话,不限于上次整理之后(这个参数留给按需过滤的调用方)
257
- * @returns {Promise<string>}
258
- */
259
- async function searchSessions(sessionsRoot, query, limit, sinceMs) {
260
- if (!sessionsRoot) return '(未配置 sessions 目录,无法搜索会话记录)'
261
- const needle = String(query || '').toLowerCase()
262
- if (needle.length < 2) return '(关键词太短,至少 2 个字符)'
263
-
264
- let zlib
265
- try {
266
- zlib = await import('node:zlib')
267
- } catch {
268
- return '(当前 Node 不支持 zstd 解压,无法读取会话记录)'
269
- }
270
- if (typeof zlib.zstdDecompressSync !== 'function') {
271
- return '(当前 Node 不支持 zstd 解压,无法读取会话记录)'
272
- }
273
-
274
- let dirs
275
- try {
276
- const projects = await readdir(sessionsRoot, { withFileTypes: true })
277
- dirs = []
278
- for (const p of projects) {
279
- if (!p.isDirectory()) continue
280
- const projPath = join(sessionsRoot, p.name)
281
- const sessions = await readdir(projPath, { withFileTypes: true }).catch(() => [])
282
- for (const s of sessions) {
283
- if (!s.isDirectory()) continue
284
- const file = join(projPath, s.name, 'session.v4.jsonl.zstd')
285
- const info = await stat(file).catch(() => null)
286
- if (info && info.mtimeMs >= sinceMs) dirs.push({ file, mtimeMs: info.mtimeMs })
287
- }
288
- }
289
- } catch (err) {
290
- return `(读取 sessions 目录失败:${err?.message ?? err})`
291
- }
292
-
293
- dirs.sort((a, b) => b.mtimeMs - a.mtimeMs)
294
- const hits = []
295
- let total = 0
296
- for (const d of dirs.slice(0, 40)) {
297
- try {
298
- const raw = await readFile(d.file)
299
- const text = decodeZstdFrames(zlib, raw)
300
- if (text === null) continue
301
- const lines = text.split(/\r?\n/)
302
- for (const line of lines) {
303
- if (line.length < 8) continue
304
- if (!line.toLowerCase().includes(needle)) continue
305
- hits.push(`[${localStamp(d.mtimeMs)}] ${line.length > 500 ? line.slice(0, 500) + '…' : line}`)
306
- total += line.length
307
- // `>= limit`:判据是「已经攒够 limit 段了」,不是「超过了」——后者每次多返回一段。
308
- if (total > SEARCH_LIMIT || hits.length >= limit) break
309
- }
310
- } catch {
311
- // 单个会话读不动就跳过:autodream 不该因为一个坏文件整体失败。
312
- }
313
- if (total > SEARCH_LIMIT || hits.length >= limit) break
314
- }
315
- if (!hits.length) return `(在 ${sinceMs ? '上次整理之后' : '全部'}的会话记录里没找到含「${query}」的内容)`
316
- return `命中 ${hits.length} 段(按 mtime 由新到旧):\n\n${hits.join('\n')}`
317
- }
318
-
319
158
  /** JSON Schema 片段:工具参数。 */
320
159
  const str = (description) => ({ type: 'string', description })
321
160
 
@@ -353,12 +192,14 @@ export function autodreamToolSchemas(opts) {
353
192
  tools.push({
354
193
  name: 'search_sessions',
355
194
  description:
356
- '在 DSH 会话记录(zstd 压缩的 jsonl)里做定向关键词搜索,由新到旧。只在确实需要某个具体细节时才用(例如某次报错原文),不要用它通读会话。',
195
+ '在 DSH 会话记录(zstd 压缩的 jsonl)里做定向关键词搜索,由新到旧。只在确实需要某个具体细节时才用(例如某次报错原文),不要用它通读会话。' +
196
+ '**结果首行是覆盖率**:本次一共看得到多少个会话、实际进了多少个、多少个没看 / 读不动 / 只读到一部分 / 是旧格式。' +
197
+ '覆盖不完整时,「没搜到」只代表「在看到的这些会话里没有」,**不等于会话里没有** —— 尤其不要拿它当「这条记忆已经过时 / 该归档」的反证。',
357
198
  parameters: {
358
199
  type: 'object',
359
200
  properties: {
360
201
  query: str('要搜的关键词,至少 2 个字符'),
361
- limit: { type: 'number', description: '最多返回多少段,默认 20' },
202
+ limit: { type: 'number', description: '最多返回多少段命中,默认 20(只管段数;另有片段字符总预算)' },
362
203
  },
363
204
  required: ['query'],
364
205
  additionalProperties: false,
@@ -883,8 +724,9 @@ export function createToolRunner(opts) {
883
724
  }
884
725
  case 'search_sessions': {
885
726
  if (!withSessions) return '错误:本次 autodream 的输入源不包含会话记录,search_sessions 不可用。'
886
- const lim = Number.isFinite(a.limit) ? Math.max(1, Math.min(60, Number(a.limit))) : 20
887
- return await searchSessions(sessionsRoot, a.query, lim, 0)
727
+ // 参数收敛与覆盖率口径都在 session-search(policy 定账、runtime 做 IO)。
728
+ // `limit` 的夹取留在那边:它是纯策略的一部分,别在这里写第二份 1..60。
729
+ return await searchSessions(sessionsRoot, a.query, { limit: a.limit })
888
730
  }
889
731
  case 'write_memory': {
890
732
  if (!apply) return '错误:当前是「只出报告」模式,没有写权限。请把改动写进你的最终回复。'
package/lib/client.js CHANGED
@@ -4575,7 +4575,7 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
4575
4575
  "ad.row.source": "输入源",
4576
4576
  "ad.source.memory": "仅记忆目录",
4577
4577
  "ad.source.sessions": "记忆 + 会话记录",
4578
- "ad.note.sourceSessions": "会解压会话记录做定向搜索 —— 私密对话会进入模型上下文,token 成本也更高。",
4578
+ "ad.note.sourceSessions": "会解压会话记录做定向搜索 —— 私密对话会进入模型上下文,token 成本也更高。整理前还会挑出几条「还在被注入、但很久没改」的记忆去核对(最多 5 条):所以它偶尔会动到你没明说要改的条目,那是对账,不是乱动。",
4579
4579
  "ad.note.sourceMemory": "只看记忆文件本身,不碰会话记录。",
4580
4580
  "ad.note.applySnapshot": "改写前会自动把整个记忆目录快照一份(memory 上一层 .sage-mem/autodream/snapshots/),改坏可回退。",
4581
4581
  "ad.note.reportOnly": "只读模式:这一趟连写工具都不会挂给模型,所以它不可能改到任何文件。",
@@ -5242,7 +5242,7 @@ h("span", { key: "sep", className: "smem-actions-sep", "aria-hidden": "true" }),
5242
5242
  "ad.row.source": "Input",
5243
5243
  "ad.source.memory": "Memory directory only",
5244
5244
  "ad.source.sessions": "Memory + session logs",
5245
- "ad.note.sourceSessions": "Session logs are unpacked for a targeted search — private conversations enter the model context, and token cost is higher.",
5245
+ "ad.note.sourceSessions": "Session logs are unpacked for a targeted search — private conversations enter the model context, and token cost is higher. Before consolidating it also picks a few memories that are still being injected but haven't changed for a long time and checks them against recent sessions (at most 5) — so it may occasionally touch an entry you never asked to change. That is reconciliation, not random editing.",
5246
5246
  "ad.note.sourceMemory": "Only the memory files themselves; session logs are never touched.",
5247
5247
  "ad.note.applySnapshot": "Before rewriting, the whole memory directory is snapshotted (under .sage-mem/autodream/snapshots/, one level above memory), so a bad run can be rolled back.",
5248
5248
  "ad.note.reportOnly": "Read-only mode: this run does not even give the model write tools, so it cannot change any file.",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "sage-mem",
3
3
  "description": "Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.",
4
- "version": "2.17.1",
4
+ "version": "2.19.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",