sage-mem 2.18.0 → 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.
package/README.en.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  **Cross-session memory for DeepSeek Harness — plain markdown files, no database, no worker.**
14
14
 
15
- **Current release: `2.18.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
15
+ **Current release: `2.19.0`** — the npm badge above is the dynamic source of truth. **Contract baseline: `1.0.0`** — the first stable release, whose public commitments, the capability boundaries and the list of things it explicitly cannot do are frozen in the
16
16
  [frozen contract](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md).
17
17
 
18
18
  If it is useful to you, a Star is the most direct feedback.
@@ -405,7 +405,7 @@ The optional memory-consolidation feature (identifier `autodream`): it reads thr
405
405
  |---|---|---|
406
406
  | Trigger | Manual only / run automatically when conditions are met | Automatic mode goes through three levels of gating, **checking the cheapest first**: time gate (≥ N hours since last time, one read/write) → session gate (≥ M sessions with updates in between, one directory scan) → lock (against concurrency). A 10-minute scan throttle is sandwiched in between, so that while "the time gate passed but the session gate did not" it does not rescan for nothing every turn |
407
407
  | Mode of change | Report only / rewrite directly | In "report only" mode **the write tools are simply not attached for the model at all** — it is not constrained by a sentence saying "please do not write", it has no hands |
408
- | Input source | Memory directory only / memory + session records | The latter decompresses session records (zstd) for targeted keyword search; the cost is that private conversations enter the model context, and the token cost is higher too |
408
+ | Input source | Memory directory only / memory + session records | The latter decompresses session records (zstd) for a targeted keyword search (not a full index: at most the **40** most recent v4 sessions enter the queue, and the first line of every result states how much was actually covered); the cost is that private conversations enter the model context, and the token cost is higher too |
409
409
 
410
410
  Automatic triggering runs on the plugin's own timer (checks the gates every 30 minutes by default). Consolidation **deliberately does not run through your session** — the tool set is given by the plugin, the step count is capped, and it is not written into your session records.
411
411
 
@@ -427,6 +427,19 @@ So it may occasionally touch an entry you never asked it to change — **that is
427
427
 
428
428
  **With "memory directory only" this whole stage disappears** (there are no sessions to check against, and a list without sessions would only make it guess). The list itself carries only file names and day counts, never the body text.
429
429
 
430
+ ### Session search now states how much it looked at (2.19.0)
431
+
432
+ The `search_sessions` tool that consolidation holds is a **targeted keyword search**, not a full index. **The first line of every result is the coverage**:
433
+
434
+ - **How much is reachable**: how many session transcripts it recognises, how many actually entered the queue (**40 is the queue cap**, not "always exactly 40"; nor does entering the queue guarantee being fully read — the first line is the authoritative number), and how many were fully searched / only partly readable / unreadable / not looked at because of the cap / never started because the output budget ran out.
435
+ - **Each snippet is at most 500 characters and is centred on the keyword**: for an ordinary hit (the keyword itself no longer than the snippet cap) the match point is always inside the snippet; if the keyword is close to or longer than 500 characters, the window starts at the keyword. The old version cut 500 characters from the start of the line, so a keyword past the window produced a snippet that did not contain it at all.
436
+ - **8000 is the character budget for the matching snippets** — not a hard cap on the whole output including that first line.
437
+ - **Two axes are reported separately**: *input coverage* (did it look everywhere) and *output truncation* (were the snippets clipped). "Everything was read but each snippet was cut" and "only a few sessions were read" are different things, and `complete` / `truncated` each say one of them.
438
+ - **A zero result has two phrasings**: only with complete coverage may it say "searched all N sessions, found nothing"; with incomplete coverage it must say "found nothing among the M sessions it actually read, with … remaining", and state plainly that **this does not mean the sessions do not mention it**.
439
+ - **Old formats are reported, not read**: v3 and unversioned session transcripts are counted and appear in the coverage, but this version does not read them (that is left to a separate release).
440
+
441
+ So reconciliation has one discipline: **with incomplete coverage, "found nothing" must not be used as counter-evidence that a memory is stale or should be archived**; explicit contrary evidence (a session stating another address or another conclusion) is still acted on as before.
442
+
430
443
  ### The Consolidation Model Can Be Specified Separately
431
444
 
432
445
  Consolidation is a background batch job and need not be the same model as the one used for chatting. The settings page under 「高级设置 → 模型」(Advanced settings → Model) lets you pick one from **the model routes currently configured** (the options come from the same catalog as in 「模型选择」/ model selection).
package/README.md CHANGED
@@ -14,7 +14,7 @@
14
14
 
15
15
  > File-based cross-session memory for DeepSeek Harness — every memory is a plain markdown file you can open, edit and delete. No database, no worker, no port.
16
16
 
17
- **当前发布版本:`2.18.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
17
+ **当前发布版本:`2.19.0`** —— 顶部 npm 徽章是动态权威。**契约基线:`1.0.0`** —— 第一个稳定版,公开承诺、能力边界与「明确做不到」的清单冻结在
18
18
  [契约冻结](https://github.com/gezi-wen/sage-mem/blob/main/docs/1.0.0-contract.md)。
19
19
 
20
20
  如果它对你有用,给个 Star 是最直接的反馈。
@@ -407,7 +407,7 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
407
407
  |---|---|---|
408
408
  | 触发 | 只手动 / 满足条件自动跑 | 自动模式走三级门控,**最便宜的先查**:时间门(距上次 ≥ N 小时,一次读写)→ 会话门(期间 ≥ M 个会话有更新,一次目录扫描)→ 锁(防并发)。中间夹一层 10 分钟扫描节流,免得「时间门过了、会话门没过」时每轮白扫 |
409
409
  | 改动方式 | 只出报告 / 直接改写 | 「只出报告」模式下**写工具根本不会挂给模型** —— 不是靠一句「请不要写」约束,是它没有手 |
410
- | 输入源 | 仅记忆目录 / 记忆 + 会话记录 | 后者会解压会话记录(zstd)做定向关键词搜索;代价是私密对话会进入模型上下文,token 成本也更高 |
410
+ | 输入源 | 仅记忆目录 / 记忆 + 会话记录 | 后者会解压会话记录(zstd)做定向关键词搜索(不是全量索引:最近最多 **40 个** v4 会话,结果首行会写明实际覆盖了多少);代价是私密对话会进入模型上下文,token 成本也更高 |
411
411
 
412
412
  自动触发走插件自己的定时器(默认 30 分钟查一次门控)。整理**刻意不走会话** —— 工具集由插件给、步数有上限、不写进你的会话记录。
413
413
 
@@ -429,6 +429,19 @@ sage-mem 给记忆目录的写入加了**版本守卫**:写入前记下当前
429
429
 
430
430
  **选「仅记忆目录」时这一段完全不出现**(没有会话可核对,名单给出来只会让它硬猜)。名单本身只有文件名与天数,不含正文。
431
431
 
432
+ ### 搜会话时它会说清「看了多少」(2.19.0)
433
+
434
+ 整理时手上那个 `search_sessions` 是**定向关键词搜索**,不是全量索引。它的结果**首行就是覆盖率**:
435
+
436
+ - **看得到多少**:认得的会话正文有多少份、实际进队多少份(**40 是进队上限**,不是「每次必扫 40」;也不保证进队的那几份都能读完 —— 实际数字以首行为准)、完整搜索 / 只读到一部分 / 读不动 / 因上限没看 / 因输出预算没开始各多少份。
437
+ - **每段最多 500 字,以关键词为中心取**:常规命中(关键词本身不超过片段上限)时命中点一定在片段里;关键词长到接近或超过 500 字时,窗口从关键词开头取满。旧版从行首硬切,关键词落在窗口之后就等于返回了一段看不见它的文字。
438
+ - **8000 是命中片段的字符总预算** —— 不是整份输出(含首行)的硬上限。
439
+ - **两条轴分开报**:*输入覆盖*(有没有看完)与*输出截断*(片段有没有被裁)。「全都看了、每段被裁短」与「只看了几份」是两件不同的事,`complete` 与 `truncated` 各说一件。
440
+ - **零命中分两种说法**:覆盖完整才说「完整搜索了全部 N 个会话,没找到」;覆盖不完整只能说「在真正读到的 M 个会话里没找到,另有 …」,并明说**这不等于会话里没有**。
441
+ - **旧格式只报不读**:v3 与无版本号的会话正文会被数出来写进覆盖率,本版不读它们(读的行为留给单独一版)。
442
+
443
+ 所以对账有一条纪律:**覆盖率不完整时的「没搜到」不能当成「这条记忆过时 / 该归档」的反证**;而拿到明确相反的证据(会话里写着另一个地址、另一套结论)时照常改。
444
+
432
445
  ### 整理用的模型可以单独指定
433
446
 
434
447
  整理是后台批量任务,跟聊天用的不一定是同一个模型。设置页「高级设置 → 模型」可以从**当前已配置的模型路线**里挑一条(选项与「模型选择」里的目录同源)。
@@ -106,6 +106,15 @@ ${reconcileList}
106
106
  - **整条过时** → 可以考虑归档,但必须带 \`reason\`
107
107
  - **只是缺了新进展** → 合并进已有文件,不要新开一条
108
108
 
109
+ ⚠️ **先读搜索结果的覆盖率那一行,再决定怎么解释「没搜到」。** \`search_sessions\` **可能只覆盖得到
110
+ 一部分会话**(最近若干个、读得动的、认得的格式),首行会写明看了多少、漏了多少。所以:
111
+
112
+ - 覆盖率**不完整**时的零命中 = **没有看见**,不是**没有**。**它不能当成「这条记忆过时 / 该归档」的反证**,
113
+ 也不足以支撑「对不上」这个判断 —— 那就当这一条没核对成,放着别动。
114
+ - 覆盖率**完整**时的零命中,才可以说「会话里确实没有提到它」。
115
+ - 反过来,如果你拿到的是**明确相反的证据**(会话里写着另一个地址、另一套结论、已经推翻了它),
116
+ 那和覆盖率无关,照上面的规则改。
117
+
109
118
  ⚠️ 这一段的目标是**减少错记忆**,不是增加记忆条数。全部核对通过、一个字都不改,也是这一趟的正常结果。
110
119
  `
111
120
  : ''
@@ -154,7 +163,7 @@ ${reconcileList}
154
163
 
155
164
  1. **结构性毛病** —— 直接跑 \`audit_memory\`,它会把索引悬空、漏索引、type 与前缀不一致、双链断链、YAML 陷阱都列出来。这些是确定要做的事。
156
165
  2. **漂移的旧记忆** —— 描述与内容已经对不上的、日期还是相对写法的、被后续进展推翻的。
157
- 3. **(仅在需要具体细节时)** 用 \`search_sessions\` 定向搜一个具体词。不要通读会话记录。
166
+ 3. **(仅在需要具体细节时)** 用 \`search_sessions\` 定向搜一个具体词。它首行会写明这次覆盖了多少会话 —— 覆盖不完整时的「没搜到」只是没看见,不是证据。不要通读会话记录。
158
167
  ${stage25}
159
168
  ## 阶段 3 — 整合
160
169
 
@@ -0,0 +1,388 @@
1
+ /**
2
+ * sage-mem autodream — `search_sessions` 的**纯策略层**:选谁、切多宽、记哪些账、怎么说。
3
+ *
4
+ * 这一层**零 import**(连 `node:` 都没有):所有决定都能对着字符串与假对象断言。
5
+ * 真正的 readdir / readFile / zstd 解压在 `session-search.js`,纯度边界由
6
+ * `test/structure-test.mjs` 第 5 组看着。
7
+ *
8
+ * ## 为什么要把「决定」从「IO」里拆出来(2.19.0)
9
+ *
10
+ * 旧实现把五件事混在一个函数里,而**每一件都能静默缩小搜索面**:只扫最近若干个会话、
11
+ * 片段从行首硬切、字符预算按**未切片的整行长度**记账、文件名只认一个代际、
12
+ * 读不动或只解出一半的文件直接跳过。最后那句「在**全部**的会话记录里没找到」
13
+ * 于是把「看完了没有」与「没看全」说成了同一句话 —— 而下游会拿它当证据。
14
+ *
15
+ * ## 四条口径(本文件是它们的唯一落点)
16
+ *
17
+ * 1. **两条轴不许混算**:
18
+ * - **输入覆盖** `complete` —— 我到底看了多少、跳了多少;
19
+ * - **输出截断** `truncated` —— 给出去的片段有多完整。
20
+ * `complete:true, truncated:true` 完全合法(全部会话都读了,但每条证据被窗口裁短),
21
+ * 反过来 `complete:false, truncated:false` 也合法(只看了若干个,一个也没命中)。
22
+ * 把 `truncated` 塞进 `complete` 的判据里,这两件事就再也分不开了。
23
+ *
24
+ * 2. **文件桶互斥且穷尽**:每个「进队」的会话文件恰好落进
25
+ * `searched / partial / failed / skippedByOutput` 之一,再加上没进队的 `skippedByCap`,
26
+ * 其和必须等于 `available`。`partial` **不再**同时计入 `searched` —— 「解了一半」
27
+ * 被当成「完整」正是旧账算不清的根源。
28
+ *
29
+ * 3. **预算按实际吐出的字算**(`hitChars`),不是按源行长度。片段以关键词为中心取窗,
30
+ * 因此「片段里看得到关键词」是可断言的,而不是碰运气。
31
+ *
32
+ * 4. **零命中的说法由 `complete` 决定**:完整才允许说「没有」,不完整必须限定范围;
33
+ * 目录读不了时,一句话都不许听起来像「没有」。
34
+ */
35
+
36
+ /** 会话正文的**唯一**认得格式(2.19.0 只读 v4;v3 / 无版本只报告不读)。 */
37
+ export const RECOGNIZED_SESSION_FILE = 'session.v4.jsonl.zstd'
38
+
39
+ /** 单次最多看多少个会话(**不扩大**:要扩先做逐帧早停,见 session-search.js 的成本注释)。 */
40
+ export const SEARCH_DIR_CAP = 40
41
+
42
+ /** 单条命中片段最多多少字。 */
43
+ export const HIT_CHARS = 500
44
+
45
+ /**
46
+ * 命中片段的**总字符预算**(全部 hitChars 之和)。
47
+ *
48
+ * ⚠️ 旧实现的同名概念记的是**源行长度之和**,于是「一条几万字的长记录」就能把预算花光、
49
+ * 只吐出一小段。现在它约束的是真正发出去的字符数。
50
+ */
51
+ export const CHAR_BUDGET = 8000
52
+
53
+ /** `limit` 的默认值与上限(工具层夹取用)。 */
54
+ export const DEFAULT_HIT_LIMIT = 20
55
+ export const MAX_HIT_LIMIT = 60
56
+
57
+ /** 关键词至少几个字符。 */
58
+ export const MIN_NEEDLE_CHARS = 2
59
+
60
+ /** 短于这个长度的行直接跳过(粘贴出来的 `}` / `0` 之类,命中它没有信息量)。 */
61
+ export const MIN_LINE_CHARS = 8
62
+
63
+ /** coverage 的口径版本。加字段不换号,**改已有字段的含义**才换。 */
64
+ export const COVERAGE_SCHEMA = 1
65
+
66
+ /** 会话目录的根状态(决定「能不能搜索」,与「搜到了多少」是两件事)。 */
67
+ export const ROOT_STATES = ['ok', 'unset', 'missing', 'notdir', 'denied', 'error']
68
+
69
+ function intOf(v, dflt = 0) {
70
+ const n = Number(v)
71
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : dflt
72
+ }
73
+
74
+ function normalizeRoot(v) {
75
+ return ROOT_STATES.includes(v) ? v : 'error'
76
+ }
77
+
78
+ /**
79
+ * 一个会话目录里的文件名该算什么:认得 / 旧格式 / 与搜索无关。
80
+ *
81
+ * 为什么这条判据在纯层:它是「能不能看见这个会话」的**唯一**决定,
82
+ * 混进 readdir 里就没法对着文件名做单测。`test/session-search-test.mjs` 第 5 组
83
+ * 逐条钉住 v4 / v3 / 无版本 / `.bak` / 临时文件 / 点文件。
84
+ *
85
+ * @param {string} name 会话目录里的一个文件名
86
+ * @returns {'v4'|'unrecognized'|'ignore'}
87
+ */
88
+ export function classifySessionFileName(name) {
89
+ const base = String(name ?? '')
90
+ if (!base || base.startsWith('.')) return 'ignore'
91
+ // 备份 / 临时件:既不是「认得」,也不该被当成「旧格式」吓人一跳。
92
+ if (/\.bak(?:$|[-_.])/i.test(base)) return 'ignore'
93
+ if (base.endsWith('~') || /\.(?:tmp|temp|swp)$/i.test(base)) return 'ignore'
94
+ if (base.toLowerCase() === RECOGNIZED_SESSION_FILE) return 'v4'
95
+ // v3 / 无版本 / 将来别的代际:都是「会话正文但本条路径读不了」→ 只报告,不读。
96
+ if (/^session(?:\.[a-z0-9]+)?\.jsonl\.zstd$/i.test(base)) return 'unrecognized'
97
+ return 'ignore'
98
+ }
99
+
100
+ /**
101
+ * 按 mtime 由新到旧选会话,并把「因为上限没看」**数出来**(以前这个 40 是静默的)。
102
+ *
103
+ * `available` 是**过了时间过滤之后**的总数(coverage 的分母必须与「因上限没看」同源,
104
+ * 否则 `sinceMs>0` 时被时间滤掉的那些会被误算成「因上限没看」)。
105
+ *
106
+ * @param {Array<{file:string, mtimeMs:number}>} entries
107
+ * @param {{cap?:number, sinceMs?:number}} [opts]
108
+ * @returns {{considered:Array<{file:string, mtimeMs:number}>, skippedByCap:number, available:number}}
109
+ */
110
+ export function pickSessionsByMtime(entries, opts = {}) {
111
+ const cap = intOf(opts.cap ?? SEARCH_DIR_CAP, SEARCH_DIR_CAP)
112
+ const sinceMs = Number.isFinite(opts.sinceMs) ? Number(opts.sinceMs) : 0
113
+ const rows = (Array.isArray(entries) ? entries : [])
114
+ .filter((e) => e && typeof e.file === 'string' && Number.isFinite(e.mtimeMs) && e.mtimeMs >= sinceMs)
115
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
116
+ return { considered: rows.slice(0, cap), skippedByCap: Math.max(0, rows.length - cap), available: rows.length }
117
+ }
118
+
119
+ /**
120
+ * 在行里找关键词的起点。
121
+ *
122
+ * 先试**原样**匹配(对中文、对含大小写变化就改变长度的字符都稳),再退回小写匹配
123
+ * (`ERROR` 要能命中 `error`)。退回那条只在两侧长度一致时位置可信 —— 不一致时仍返回
124
+ * 小写索引(最好的努力),片段是否真的含关键词由 `hasMatch` 如实标出,不靠猜。
125
+ */
126
+ function findNeedle(line, raw, needle) {
127
+ if (!raw) return -1
128
+ const exact = line.indexOf(raw)
129
+ if (exact >= 0) return exact
130
+ return line.toLowerCase().indexOf(needle)
131
+ }
132
+
133
+ /**
134
+ * 以**关键词位置为中心**取窗(从行首硬切时,关键词落在窗口之后,片段里就看不到它)。
135
+ *
136
+ * `maxChars` 是硬上限:加了省略号也不会超。**省略号只在真的被裁掉的那一侧出现** ——
137
+ * 关键词几乎占满窗口时(例如 499 字关键词配 500 字窗口)左侧没有可省的上下文,
138
+ * 再补一个 `…` 就会吃掉关键词的第一个字,于是「命中」返回的片段里反而搜不到它。
139
+ */
140
+ export function centeredExcerpt(line, idx, needleLen, maxChars = HIT_CHARS) {
141
+ const src = String(line ?? '')
142
+ const room = Math.max(1, intOf(maxChars, HIT_CHARS) || HIT_CHARS)
143
+ if (src.length <= room) return { text: src, clipped: false }
144
+ if (needleLen >= room) return { text: src.slice(idx, idx + room), clipped: true }
145
+ let start = Math.max(0, idx - Math.floor((room - needleLen) / 2))
146
+ let end = Math.min(src.length, start + room)
147
+ // 贴到尾部时往回挪,别让窗口白白空出半截。
148
+ start = Math.max(0, end - room)
149
+ let text = src.slice(start, end)
150
+ // 省略号在窗口**内部**换字,因此总长恒等于 room。
151
+ // 左侧只在 `start < idx`(确有被省掉的上下文)时才补,否则会切到关键词本身。
152
+ if (start > 0 && start < idx && text.length >= room) text = '…' + text.slice(1)
153
+ if (end < src.length && end > idx + needleLen && text.length >= room) text = text.slice(0, room - 1) + '…'
154
+ return { text, clipped: true }
155
+ }
156
+
157
+ /**
158
+ * 在一份已解码的会话文本里找命中。
159
+ *
160
+ * @param {string} text 解出来的会话正文(逐行 jsonl)
161
+ * @param {string} rawQuery 模型给的原样关键词
162
+ * @param {{perLineChars?:number, limit?:number, charBudget?:number}} [opts]
163
+ * @returns {{hits:Array<{lineNo:number, offset:number, excerpt:string, chars:number, hasMatch:boolean}>,
164
+ * hitChars:number, stoppedBy:null|'limit'|'chars', clipped:boolean,
165
+ * stoppedEarly:boolean, scannedLines:number, totalLines:number}}
166
+ */
167
+ export function matchLines(text, rawQuery, opts = {}) {
168
+ const raw = String(rawQuery ?? '')
169
+ const needle = raw.toLowerCase()
170
+ const perLineChars = intOf(opts.perLineChars ?? HIT_CHARS, HIT_CHARS) || HIT_CHARS
171
+ const limit = Math.max(1, intOf(opts.limit ?? DEFAULT_HIT_LIMIT, DEFAULT_HIT_LIMIT) || DEFAULT_HIT_LIMIT)
172
+ const charBudget = intOf(opts.charBudget ?? CHAR_BUDGET, CHAR_BUDGET)
173
+ const lines = String(text ?? '').split(/\r?\n/)
174
+ // 尾随换行会 split 出一个空串:算「有没有读完」时得把它剔掉,否则会假报 stoppedEarly。
175
+ let effectiveTotal = 0
176
+ for (let i = 0; i < lines.length; i++) if (lines[i].length > 0) effectiveTotal = i + 1
177
+
178
+ const hits = []
179
+ let hitChars = 0
180
+ let stoppedBy = null
181
+ let clipped = false
182
+ let scannedLines = 0
183
+
184
+ for (let i = 0; i < lines.length; i++) {
185
+ const line = lines[i]
186
+ scannedLines = i + 1
187
+ if (line.length < MIN_LINE_CHARS) continue
188
+ if (needle.length < MIN_NEEDLE_CHARS) break
189
+ const idx = findNeedle(line, raw, needle)
190
+ if (idx < 0) continue
191
+ const cut = centeredExcerpt(line, idx, needle.length, perLineChars)
192
+ if (cut.clipped) clipped = true
193
+ // 预算判据按**实际吐出的字**算,且先判后加 —— 所以 hitChars 恒 ≤ charBudget。
194
+ if (hitChars + cut.text.length > charBudget) {
195
+ stoppedBy = 'chars'
196
+ break
197
+ }
198
+ hits.push({
199
+ lineNo: i + 1,
200
+ offset: idx,
201
+ excerpt: cut.text,
202
+ chars: cut.text.length,
203
+ hasMatch: cut.text.includes(raw) || cut.text.toLowerCase().includes(needle),
204
+ })
205
+ hitChars += cut.text.length
206
+ if (hits.length >= limit) {
207
+ stoppedBy = 'limit'
208
+ break
209
+ }
210
+ }
211
+
212
+ return {
213
+ hits,
214
+ hitChars,
215
+ stoppedBy,
216
+ clipped,
217
+ // 「这个文件没读完」—— 因为输出上限停下的,才算 partial;正好停在最后一行不算。
218
+ stoppedEarly: stoppedBy !== null && scannedLines < effectiveTotal,
219
+ scannedLines,
220
+ totalLines: effectiveTotal,
221
+ }
222
+ }
223
+
224
+ /**
225
+ * 把逐文件结果折成 coverage。**`complete` 只在这里算**(别处算就会有两套口径)。
226
+ *
227
+ * 派生关系(契约):
228
+ * `searched + partial + failed + skippedByCap + skippedByOutput === available`
229
+ * `complete = root==='ok' && !zstdUnsupported && enumerationFailed===0 && unrecognized===0
230
+ * && skippedByCap===0 && skippedByOutput===0 && failed===0 && partial===0`
231
+ * `truncated = clipped || stoppedBy !== null` —— **不进 complete**(见文件头第 1 条)。
232
+ *
233
+ * @param {object} input
234
+ * @param {string} [input.root] `ROOT_STATES` 之一
235
+ * @param {Array<'searched'|'partial'|'failed'>} [input.outcomes] 逐个**已开始**文件的结局
236
+ * @param {number} [input.available] 枚举到的、认得的会话总数(分母)
237
+ * @param {number} [input.skippedByOutput] 已进队但因输出停止没开始的份数
238
+ * @param {number} [input.unrecognized] 旧格式 / 不认得而没读的会话份数
239
+ * @param {number} [input.enumerationFailed] 枚举阶段失败的次数(目录列不出来等)
240
+ * @param {boolean} [input.zstdUnsupported] 当前 Node 没有 zstd 解压
241
+ * @param {string} [input.rootMessage] 根失败时的补充说明(给人看)
242
+ * @param {string|null} [input.stoppedBy] `null` / `'limit'` / `'chars'`
243
+ * @param {boolean} [input.clipped] 有片段被窗口裁短
244
+ * @param {number} [input.hitCount]
245
+ * @param {number} [input.hitChars]
246
+ * @param {object} [input.caps] `{dirCap, charBudget, limit}`
247
+ * @returns {object} coverage(字段见契约;schema 见 `COVERAGE_SCHEMA`)
248
+ */
249
+ export function classifyCoverage(input = {}) {
250
+ const outcomes = Array.isArray(input.outcomes) ? input.outcomes : []
251
+ let searched = 0
252
+ let partial = 0
253
+ let failed = 0
254
+ for (const o of outcomes) {
255
+ if (o === 'failed') failed += 1
256
+ else if (o === 'partial') partial += 1
257
+ else if (o === 'searched') searched += 1
258
+ }
259
+ const skippedByOutput = intOf(input.skippedByOutput)
260
+ const considered = searched + partial + failed + skippedByOutput
261
+ const available = input.available === undefined ? considered : intOf(input.available)
262
+ const skippedByCap = Math.max(0, available - considered)
263
+ const root = normalizeRoot(input.root)
264
+ const zstdUnsupported = input.zstdUnsupported === true
265
+ const unrecognized = intOf(input.unrecognized)
266
+ const enumerationFailed = intOf(input.enumerationFailed)
267
+ const stoppedBy = input.stoppedBy === 'limit' || input.stoppedBy === 'chars' ? input.stoppedBy : null
268
+ const clipped = input.clipped === true
269
+ const caps = input.caps && typeof input.caps === 'object' ? input.caps : {}
270
+
271
+ return {
272
+ schema: COVERAGE_SCHEMA,
273
+ root,
274
+ rootMessage: typeof input.rootMessage === 'string' ? input.rootMessage : '',
275
+ available,
276
+ considered,
277
+ searched,
278
+ partial,
279
+ failed,
280
+ skippedByCap,
281
+ skippedByOutput,
282
+ unrecognized,
283
+ enumerationFailed,
284
+ zstdUnsupported,
285
+ hitCount: intOf(input.hitCount),
286
+ hitChars: intOf(input.hitChars),
287
+ stoppedBy,
288
+ // 输出轴:只由「片段被裁」与「预算停下」决定,与输入覆盖无关。
289
+ truncated: clipped || stoppedBy !== null,
290
+ // 输入轴:派生值,不许单独赋真。
291
+ complete:
292
+ root === 'ok' &&
293
+ !zstdUnsupported &&
294
+ enumerationFailed === 0 &&
295
+ unrecognized === 0 &&
296
+ skippedByCap === 0 &&
297
+ skippedByOutput === 0 &&
298
+ failed === 0 &&
299
+ partial === 0,
300
+ dirCap: intOf(caps.dirCap ?? SEARCH_DIR_CAP, SEARCH_DIR_CAP),
301
+ charBudget: intOf(caps.charBudget ?? CHAR_BUDGET, CHAR_BUDGET),
302
+ limit: intOf(caps.limit ?? DEFAULT_HIT_LIMIT, DEFAULT_HIT_LIMIT),
303
+ }
304
+ }
305
+
306
+ /** 根不可用时的那一句(**不许**听起来像「搜过了但没有」)。 */
307
+ function rootHead(c) {
308
+ const tail = '本次一次会话都没读,既不能当「有」也不能当「没有」。'
309
+ if (c.root === 'unset') return `无法搜索:没有配置会话目录(DSH_HOME 未设置)。${tail}`
310
+ if (c.root === 'missing') return `无法搜索:会话目录不存在。${tail}`
311
+ if (c.root === 'notdir') return `无法搜索:会话目录的路径不是一个目录。${tail}`
312
+ if (c.root === 'denied') return `无法搜索:没有权限读取会话目录。${tail}`
313
+ if (c.root !== 'ok') {
314
+ const why = c.rootMessage ? `(${c.rootMessage})` : ''
315
+ return `无法搜索:读取会话目录失败${why}。${tail}`
316
+ }
317
+ // 根没问题,是运行时读不了:这是环境限制,同样不许说成「没有」。
318
+ return '无法搜索:当前 Node 不支持 zstd 解压,会话记录一个都读不了。这是环境限制,不代表会话里有没有相关内容。'
319
+ }
320
+
321
+ /** 覆盖那句话(首行)。 */
322
+ export function formatCoverageLine(c) {
323
+ const parts = [`可用 ${c.available} 个会话`]
324
+ parts.push(c.considered === c.available ? `进队 ${c.considered} 个` : `进队 ${c.considered} 个(上限 ${c.dirCap})`)
325
+ parts.push(`完整搜索 ${c.searched}`, `只读到一部分 ${c.partial}`, `读不动 ${c.failed}`)
326
+ if (c.skippedByCap) parts.push(`因上限没看 ${c.skippedByCap}`)
327
+ if (c.skippedByOutput) parts.push(`因输出预算没开始 ${c.skippedByOutput}`)
328
+ if (c.unrecognized) parts.push(`旧格式 / 不认得 ${c.unrecognized}`)
329
+ if (c.enumerationFailed) parts.push(`枚举失败 ${c.enumerationFailed}`)
330
+ return parts.join(' · ')
331
+ }
332
+
333
+ /** 输出被截断的原因(与输入覆盖是两件事,所以单列)。 */
334
+ export function stopReason(c) {
335
+ if (c.stoppedBy === 'limit') return `段数到上限 ${c.limit}`
336
+ if (c.stoppedBy === 'chars') return `片段字符预算 ${c.charBudget} 到顶`
337
+ if (c.truncated) return `每条片段都被窗口裁到 ${HIT_CHARS} 字以内`
338
+ return ''
339
+ }
340
+
341
+ /**
342
+ * 零命中时的那一句:**完整**才允许说「没有」。
343
+ *
344
+ * 范围的分母用 `searched + partial`(真正读到了内容的那些),**不**把
345
+ * `skippedByOutput` / `failed` 算进「看得到」—— 没开始读的与读不动的都不是证据。
346
+ */
347
+ export function formatMissLine(rawQuery, c) {
348
+ const q = String(rawQuery ?? '')
349
+ if (c.complete) return `(完整搜索了全部 ${c.available} 个会话,没找到含「${q}」的内容)`
350
+ const readable = c.searched + c.partial
351
+ const gaps = []
352
+ if (c.skippedByCap) gaps.push(`${c.skippedByCap} 个因上限没看`)
353
+ if (c.skippedByOutput) gaps.push(`${c.skippedByOutput} 个因输出预算没开始`)
354
+ if (c.failed) gaps.push(`${c.failed} 个读不动`)
355
+ if (c.partial) gaps.push(`${c.partial} 个只读到一部分`)
356
+ if (c.unrecognized) gaps.push(`${c.unrecognized} 个是旧格式没读`)
357
+ if (c.enumerationFailed) gaps.push(`${c.enumerationFailed} 次目录枚举失败`)
358
+ const scope = gaps.length ? `(另有 ${gaps.join('、')})` : ''
359
+ if (readable === 0) {
360
+ return `(一个会话都没读到内容${scope} —— 这既不是「有」也不是「没有」)`
361
+ }
362
+ return `(在真正读到的 ${readable} 个会话里没找到含「${q}」的内容${scope} —— **这不等于会话里没有**)`
363
+ }
364
+
365
+ /**
366
+ * 渲染整份结果:**首行先报覆盖,再报命中**(埋到末尾等于没有)。
367
+ *
368
+ * 兼容约定:命中行仍以 `[时间戳]` 开头、命中摘要仍是 `命中 N 段`、零命中仍是「没找到」——
369
+ * `test/q-fixes-095.mjs` 的判据依赖这三个 token(`isHit` 与 `/没找到/`)。
370
+ *
371
+ * @param {{rawQuery?:string, hits?:Array<{stamp:string, excerpt:string}>, coverage:object}} input
372
+ * @returns {string}
373
+ */
374
+ export function renderSearchReport(input = {}) {
375
+ const c = input.coverage
376
+ const rawQuery = String(input.rawQuery ?? '')
377
+ const hits = Array.isArray(input.hits) ? input.hits : []
378
+
379
+ if (c.root !== 'ok' || c.zstdUnsupported) return rootHead(c)
380
+
381
+ const head = `${c.complete ? '覆盖完整' : '覆盖不完整'}:${formatCoverageLine(c)}。`
382
+ const scopeNote = c.complete ? '' : '\n下面的结果只代表**看得到的这些会话**,不代表全部会话。'
383
+ if (!hits.length) return `${head}${scopeNote}\n${formatMissLine(rawQuery, c)}`
384
+
385
+ const body = hits.map((h) => `[${h.stamp}] ${h.excerpt}`).join('\n')
386
+ const tail = c.truncated ? `\n\n(输出被截断:${stopReason(c)};输入覆盖见首行)` : ''
387
+ return `${head}${scopeNote}\n命中 ${hits.length} 段(按 mtime 由新到旧):\n\n${body}${tail}`
388
+ }
@@ -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/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.18.0",
4
+ "version": "2.19.0",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "icon": "./icon.png",