@yolk_vat-y/dsh-project-memory 0.5.15 → 0.6.1

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.
@@ -107,9 +107,11 @@ export function buildBm25(docs, getFieldText, getPhraseFields) {
107
107
  .map((d) => {
108
108
  const len = d.length || 1
109
109
  let score = 0
110
+ let matched = 0
110
111
  for (const t of q) {
111
112
  const tf = d.tf[t] || 0
112
113
  if (!tf) continue
114
+ matched++
113
115
  score += idf(t) * ((tf * (K1 + 1)) / (tf + K1 * (1 - B + (B * len) / avgLen)))
114
116
  }
115
117
  for (const phrase of cjkPhrases) {
@@ -118,7 +120,10 @@ export function buildBm25(docs, getFieldText, getPhraseFields) {
118
120
  score *= 1.5
119
121
  }
120
122
  }
121
- return { doc: d.doc, score }
123
+ // `matched` = **命中的不同查询词数**。调用方用它做最小相关性闸门:
124
+ // 单个片段(`no` 这种从 `--no-edit` 切出来的 2 字符词)也能让 score>0,
125
+ // 而 score>0 本身不构成"相关"的证据。
126
+ return { doc: d.doc, score, matched }
122
127
  })
123
128
  .filter((r) => r.score > 0)
124
129
  .sort((a, b) => b.score - a.score)
@@ -147,16 +152,18 @@ export function makeSearchText(entry) {
147
152
  // 它们在生产路径上没有调用方,留着只会被误用。
148
153
 
149
154
  export function rankEntriesMergedScored(entries, queries, limit = 8) {
150
- if (!queries.length) return entries.slice(0, limit).map((entry) => ({ entry, score: 0 }))
155
+ if (!queries.length) return entries.slice(0, limit).map((entry) => ({ entry, score: 0, matched: 0 }))
151
156
  const bm25 = buildBm25(entries, weightedFieldText)
152
157
  const merged = new Map()
153
158
  for (const query of queries) {
154
159
  for (const r of bm25.score(query)) {
155
160
  const id = r.doc.id || r.doc.sourcePath
156
- if (merged.has(id)) {
157
- if (r.score > merged.get(id).score) merged.get(id).score = r.score
161
+ const prev = merged.get(id)
162
+ if (prev) {
163
+ if (r.score > prev.score) prev.score = r.score
164
+ if (r.matched > prev.matched) prev.matched = r.matched
158
165
  } else {
159
- merged.set(id, { entry: r.doc, score: r.score })
166
+ merged.set(id, { entry: r.doc, score: r.score, matched: r.matched })
160
167
  }
161
168
  }
162
169
  }
@@ -179,10 +186,12 @@ export function rankExperienceScored(items, queryOrQueries, limit = 5) {
179
186
  const merged = new Map()
180
187
  for (const query of queries) {
181
188
  for (const r of bm25.score(query)) {
182
- if (merged.has(r.doc.id)) {
183
- if (r.score > merged.get(r.doc.id).score) merged.get(r.doc.id).score = r.score
189
+ const prev = merged.get(r.doc.id)
190
+ if (prev) {
191
+ if (r.score > prev.score) prev.score = r.score
192
+ if (r.matched > prev.matched) prev.matched = r.matched
184
193
  } else {
185
- merged.set(r.doc.id, { item: r.doc, score: r.score })
194
+ merged.set(r.doc.id, { item: r.doc, score: r.score, matched: r.matched })
186
195
  }
187
196
  }
188
197
  }
@@ -0,0 +1,268 @@
1
+ // 经验/洞察层的**可选**向量索引(leanvec):持久化 + 逐条失效 + 优雅降级。
2
+ //
3
+ // 为什么持久化:实测 103 条 × 256 维 = **105 KB**,全量编码要 ~0.4s;读盘 + base64 解码 ~20ms。
4
+ // 为什么只覆盖这两层:它们的池子小(实测真实 store ≤103 条);doc/symbol 是 10⁴ 量级
5
+ // (某真实 TS 仓库 15.6k 条目),每查询全量编码要 60s,所以那一层继续纯词法。
6
+ //
7
+ // 失效分两级:
8
+ // ① **模型指纹**(词表内容哈希 + 表字节数)变了 → 整个文件作废,全量重建;
9
+ // ② **条目文本哈希**变了 → 只重算那一行(其余复用)。
10
+ // 降级:leanvec 不可用、文件损坏、embed 抛异常 —— 一律返回 null / 空 Map,
11
+ // 调用方不传 rerank,行为逐字段退回纯词法。
12
+ import { createHash } from 'node:crypto'
13
+ import { existsSync, readFileSync, statSync } from 'node:fs'
14
+ import { dirname, join } from 'node:path'
15
+ import { pathToFileURL } from 'node:url'
16
+ import { writeJsonAtomic } from './util/fs.js'
17
+
18
+ const FILE = 'vectors.json'
19
+ const VERSION = 1
20
+ const DIM = 256
21
+
22
+ /**
23
+ * 条目用于编码的文本:**只取标题**(经验条目取 problem)。
24
+ *
25
+ * 为什么不用完整的评分文本:实测(36 条刻意无词重叠的查询 / 103 条池)标题变体的并集
26
+ * hit@10 是 94%,而把 300 字摘要一起喂进去只有 89%——长文本在均值池化下会被稀释向语料均值。
27
+ */
28
+ export function vectorText(it) {
29
+ return String(it?.title || it?.problem || it?.body || '').trim()
30
+ }
31
+
32
+ const hashOf = (text) => createHash('sha256').update(String(text)).digest('hex').slice(0, 16)
33
+ const keyOf = (it) => (it?.insightId ?? it?.id ?? null)
34
+
35
+ /**
36
+ * leanvec 的模型指纹:词表内容 sha256 + 向量表字节数。
37
+ *
38
+ * 词表决定 token id、向量表按同一 id 排布,任一变化都必须让旧向量作废。
39
+ * 表全文哈希要 ~0.2s,与省下的 0.4s 相抵,所以用"内容哈希 + 字节数"近似——
40
+ * 只有"表内容变了但字节数恰好相同且词表没变"这种极罕见情形会漏判,日后再加密实指纹。
41
+ * @returns {string|null} null = 这个目录不是一份可用的 leanvec
42
+ */
43
+ export function leanvecFingerprint(modelDir) {
44
+ if (!modelDir) return null
45
+ const tj = join(modelDir, 'dist', 'leanvec.tokenizer.json')
46
+ const tb = join(modelDir, 'dist', 'leanvec.f32')
47
+ if (!existsSync(tj) || !existsSync(tb)) return null
48
+ const h = createHash('sha256').update(readFileSync(tj)).digest('hex').slice(0, 16)
49
+ return `l1:${h}:${statSync(tb).size}`
50
+ }
51
+
52
+ /** 从磁盘读回旧索引;任何异常都当成"没有",绝不抛。 */
53
+ function readSaved(file) {
54
+ try {
55
+ const doc = JSON.parse(readFileSync(file, 'utf8'))
56
+ if (doc?.version !== VERSION || typeof doc.blob !== 'string' || !Array.isArray(doc.ids) || !Array.isArray(doc.hashes)) return null
57
+ const buf = Buffer.from(doc.blob, 'base64')
58
+ // 复制一次拿到 byteOffset=0 且对齐的新缓冲——Buffer.from(base64) 的下层 ArrayBuffer
59
+ // 可能不是 4 字节对齐,直接 new Float32Array(buf.buffer, buf.byteOffset) 会抛。
60
+ const u8 = new Uint8Array(buf)
61
+ const all = new Float32Array(u8.buffer, 0, Math.floor(u8.byteLength / 4))
62
+ const map = new Map()
63
+ for (let i = 0; i < doc.ids.length; i++) {
64
+ const off = i * DIM
65
+ if (off + DIM > all.length) break
66
+ map.set(doc.ids[i], { v: all.subarray(off, off + DIM), h: String(doc.hashes[i] ?? '') })
67
+ }
68
+ return { model: doc.model, dim: doc.dim, map, all }
69
+ } catch {
70
+ return null
71
+ }
72
+ }
73
+
74
+ /**
75
+ * 打开(或新建)向量索引。
76
+ * @param {object} o
77
+ * @param {string|null} o.dir - 持久化目录(通常是项目 store 目录);null → 只在内存里
78
+ * @param {object[]} o.items - 要建索引的条目(经验 + 洞察两层合一份,id 互不冲突)
79
+ * @param {(text: string) => Float32Array|null} o.embed - leanvec 的编码函数
80
+ * @param {string} o.model - 模型指纹(见 {@link leanvecFingerprint})
81
+ * @returns {{score: Function, flush: Function, stats: object}|null} null = 不可用 → 调用方退回纯词法
82
+ */
83
+ export function openVectorIndex({ dir = null, items = [], embed, model, dim = DIM } = {}) {
84
+ if (typeof embed !== 'function' || !model || dim !== DIM) return null
85
+ const file = dir ? join(dir, FILE) : null
86
+ const saved = file ? readSaved(file) : null
87
+ const usable = saved && saved.model === model && saved.dim === dim ? saved : null
88
+ const entryMap = new Map() // key -> { v: Float32Array, h: string }
89
+ let reused = 0
90
+ let computed = 0
91
+ let dirty = false
92
+
93
+ const ensure = (it) => {
94
+ const key = keyOf(it)
95
+ if (!key) return null
96
+ const text = vectorText(it)
97
+ if (!text) return null
98
+ const h = hashOf(text)
99
+ const prev = usable?.map.get(key)
100
+ if (prev && prev.h === h) {
101
+ if (!entryMap.has(key)) { entryMap.set(key, prev); reused++ }
102
+ return prev.v
103
+ }
104
+ if (entryMap.has(key) && entryMap.get(key).h === h) return entryMap.get(key).v
105
+ let v = null
106
+ try { v = embed(text) } catch { v = null }
107
+ if (!v) return null
108
+ entryMap.set(key, { v, h })
109
+ computed++
110
+ dirty = true
111
+ return v
112
+ }
113
+
114
+ /** 持久化(仅在有变化时写;失败不影响本次运行)。 */
115
+ const flush = () => {
116
+ if (!dirty || !file) return false
117
+ try {
118
+ const keys = [...entryMap.keys()]
119
+ const all = new Float32Array(keys.length * dim)
120
+ const hashes = []
121
+ keys.forEach((k, i) => { all.set(entryMap.get(k).v, i * dim); hashes.push(entryMap.get(k).h) })
122
+ writeJsonAtomic(file, {
123
+ version: VERSION, model, dim, ids: keys, hashes,
124
+ blob: Buffer.from(all.buffer, all.byteOffset, all.byteLength).toString('base64'),
125
+ })
126
+ dirty = false
127
+ return true
128
+ } catch {
129
+ return false // 磁盘不可写等:本次仍可用,只是下次还要重算
130
+ }
131
+ }
132
+
133
+ /**
134
+ * 与 auto-inject / recall 两个接缝约定的同一签名:返回 Map<id, cos>。
135
+ * 查询无法编码、或某条目无文本/无向量 → 该条不进 Map(调用方据此降级,不当 0 分罚它)。
136
+ * 同时用 `insightId` 与 `id` 两个键登记,兼容两层各自的 id 约定。
137
+ */ const score = (q, cands) => {
138
+ const out = new Map()
139
+ let qv = null
140
+ try { qv = embed(typeof q === 'string' ? q : String(q ?? '')) } catch { qv = null }
141
+ if (!qv) return out
142
+ for (const it of cands || []) {
143
+ const v = ensure(it)
144
+ if (!v) continue
145
+ let s = 0
146
+ for (let i = 0; i < dim; i++) s += qv[i] * v[i]
147
+ const key = keyOf(it)
148
+ out.set(key, s)
149
+ if (it?.id && it.id !== key) out.set(it.id, s)
150
+ }
151
+ flush()
152
+ return out
153
+ }
154
+
155
+ // 首次打开时把给定条目全部对齐(复用旧行 / 补算缺失行),并**立即落盘**——
156
+ // 那 0.4s 的构建成本必须在本次会话就存下来,而不是等第一次查询才写。
157
+ // (必须放在 flush 定义之后:flush 是 const 箭头函数,提前调用会 TDZ。)
158
+ for (const it of items) ensure(it)
159
+ flush()
160
+
161
+ return {
162
+ score,
163
+ flush,
164
+ stats: {
165
+ file, model, dim,
166
+ persisted: entryMap.size,
167
+ reusedFirstOpen: reused,
168
+ computedFirstOpen: computed,
169
+ loadedFromDisk: Boolean(usable),
170
+ },
171
+ }
172
+ }
173
+
174
+ /**
175
+ * 从两个 store 收集**要建索引的条目**:洞察层(项目 + 全局)+ 经验层。
176
+ * 与提示通道/召回看到的池子同源;归档条目不进(它们不会被召回)。
177
+ */
178
+ export function vectorItemsFrom(store, globalStore) {
179
+ const out = []
180
+ try { if (typeof store?.insightItems === 'function') out.push(...store.insightItems()) } catch { /* store 形状不保证 */ }
181
+ try { if (typeof globalStore?.items === 'function') out.push(...globalStore.items()) } catch { /* 同上 */ }
182
+ try { if (Array.isArray(store?.experience)) out.push(...store.experience) } catch { /* 同上 */ }
183
+ return out.filter((it) => it && !it.archived)
184
+ }
185
+
186
+ /** leanvec 运行时只在进程内加载一次(77 MB 表 + 词表索引 Map,加载 ~90ms、常驻 ~120MB)。 */
187
+ let runtimeCache = null
188
+ /** 向量索引按 (storeDir, 模型指纹) 缓存;条目增删改由 `score()` 里的逐条对齐懒处理。 */
189
+ const indexCache = new Map()
190
+ /**
191
+ * "解析目录 + 模型指纹"的进程内记忆。
192
+ *
193
+ * 为什么必须缓存:`leanvecFingerprint()` 要 sha256 一份 1.94MB 的词表(~10ms),而
194
+ * `createVectorRerank` 在**每一步注入**上都会被调用——不缓存就是每步白付 10ms。
195
+ * 键取"显式配置 + 环境变量"的组合:两者都没变就不必重算。
196
+ */
197
+ const resolveCache = new Map()
198
+
199
+ /**
200
+ * 解析 leanvec 目录。顺序:显式配置 > 环境变量 `DSH_LEANVEC_DIR` > **作为可选依赖**。
201
+ * 三者都拿不到 → null(调用方退回纯词法,这是正常路径不是错误)。
202
+ */
203
+ async function resolveLeanvecDir(explicit) {
204
+ const cand = []
205
+ if (typeof explicit === 'string' && explicit) cand.push(explicit)
206
+ if (typeof process.env.DSH_LEANVEC_DIR === 'string' && process.env.DSH_LEANVEC_DIR) cand.push(process.env.DSH_LEANVEC_DIR)
207
+ try {
208
+ const { createRequire } = await import('node:module')
209
+ const req = createRequire(import.meta.url)
210
+ try { cand.push(dirname(req.resolve('leanvec/package.json'))) } catch { cand.push(dirname(dirname(req.resolve('leanvec')))) }
211
+ } catch {
212
+ // 未安装 leanvec:**正常**,不是故障——可选依赖的意义就在这里
213
+ }
214
+ for (const d of cand) if (leanvecFingerprint(d)) return d
215
+ return null
216
+ }
217
+
218
+ /**
219
+ * 构造给 `recallItems` / `buildInjection` 用的 rerank。leanvec 不可用 → **null**。
220
+ *
221
+ * 装了就有向量、没装就纯词法,两条路的差别只在排序:闸门(覆盖率/共同词数)与返回条数都不变。
222
+ * @param {object} o
223
+ * @param {string|null} [o.storeDir] - 持久化位置(通常是项目 store 目录);null → 只在内存里
224
+ * @param {object[]} [o.items] - 建索引的条目(见 {@link vectorItemsFrom})
225
+ * @param {string|null} [o.vectorDir] - leanvec 目录(显式配置优先)
226
+ * @param {number} [o.alpha] - 融合权重;实测 0.5 在小 k 上最优(见 recall.js 的注释)
227
+ * @returns {Promise<{score: Function, alpha: number, stats: object}|null>}
228
+ */
229
+ export async function createVectorRerank({ storeDir = null, items = [], vectorDir = null, alpha = 0.5 } = {}) {
230
+ // 强制关闭:`vectorDir: 'off'`(或 alpha=0)一律返回 null,连模型都不加载。
231
+ // 为什么需要:装了可选依赖之后,没有这个开关就无法退回纯词法——测试固定基线、
232
+ // 线上排查"是不是向量层导致的"都会用得上。
233
+ if (typeof vectorDir === 'string' && vectorDir.trim().toLowerCase() === 'off') return null
234
+ if (alpha === 0) return null
235
+ const rk = `${typeof vectorDir === 'string' ? vectorDir : ''}\u0000${process.env.DSH_LEANVEC_DIR ?? ''}`
236
+ let resolved = resolveCache.get(rk)
237
+ if (resolved === undefined) {
238
+ const dir = await resolveLeanvecDir(vectorDir)
239
+ resolved = { dir, fingerprint: dir ? leanvecFingerprint(dir) : null }
240
+ resolveCache.set(rk, resolved) // 未安装也记下来:避免每步重复 resolve 的 IO
241
+ }
242
+ const { dir, fingerprint } = resolved
243
+ if (!dir || !fingerprint) return null
244
+ try {
245
+ if (!runtimeCache || runtimeCache.dir !== dir) {
246
+ const mod = await import(pathToFileURL(join(dir, 'src', 'embed.mjs')).href)
247
+ const lv = mod.loadLeanvec({
248
+ table: join(dir, 'dist', 'leanvec.f32'),
249
+ tokenizer: join(dir, 'dist', 'leanvec.tokenizer.json'),
250
+ })
251
+ runtimeCache = { dir, lv, fingerprint }
252
+ }
253
+ const { lv } = runtimeCache
254
+ const ck = `${storeDir ?? ''}\u0000${fingerprint}`
255
+ // 索引按 (storeDir, 指纹) 缓存;之后新增/改写的条目由 `score()` 里的逐条对齐懒处理
256
+ // (内容变了就重算那一行并落盘),所以这里不需要按 items 签名判断是否重建。
257
+ let index = indexCache.get(ck)
258
+ if (!index) {
259
+ index = openVectorIndex({ dir: storeDir, items, embed: (t) => lv.embed(t), model: fingerprint })
260
+ if (!index) return null
261
+ indexCache.set(ck, index)
262
+ }
263
+ const a = typeof alpha === 'number' && alpha >= 0 && alpha <= 1 ? alpha : 0.5
264
+ return { score: index.score, alpha: a, stats: index.stats }
265
+ } catch {
266
+ return null // 任何异常都降级到纯词法,绝不因为可选的向量层让召回失败
267
+ }
268
+ }
package/src/watch.js CHANGED
@@ -17,6 +17,12 @@ export class WatchManager {
17
17
  this._unreadableWarned = new Set()
18
18
  /** 已就「跳过了嵌套项目根」告警过的根:同上,只提示一次。 */
19
19
  this._nestedStoreWarned = new Set()
20
+ /** 正在跑回合的会话 id 集合:**多会话**下任一在跑就算活跃(见 setSessionActive)。 */
21
+ this._activeSessions = new Set()
22
+ /** 当前是否处于"有人正在用"的活跃态。 */
23
+ this._active = false
24
+ /** 活跃态下的兜底间隔(见 start):活跃 ≠ 永不扫描,只是把节拍压到最低。 */
25
+ this._activeInterval = undefined
20
26
  }
21
27
 
22
28
  /** 包含该路径的已注册根(最长前缀):懒索引据此把文件归到显式 watch 过的无标记项目里。 */
@@ -111,13 +117,44 @@ export class WatchManager {
111
117
  // 轮询本身是 O(树) 的 walkDir + 逐文件 stat(本仓库一轮实测 58–87ms),
112
118
  // 常驻 15s 一轮意味着不管有没有改动都在磨 I/O。
113
119
  this._maxInterval = Math.max(this._baseInterval, Math.min(this._baseInterval * 8, 120000))
120
+ // 活跃兜底:**有人正在跑回合**时把节拍压到最低(默认 5 分钟、且不小于 base 的 10 倍)。
121
+ // 不是"永不扫描"——外部编辑器改文件、或回合一直不结束(崩溃/长任务)时,索引仍会自愈。
122
+ this._activeInterval = Math.max(this._baseInterval * 10, 300000)
114
123
  this._interval = this._baseInterval
115
124
  this._stopped = false
116
125
  this._schedule()
117
126
  }
118
127
 
119
- _schedule() {
120
- this.timer = setTimeout(() => this._tick(), this._interval)
128
+ /**
129
+ * 会话活跃信号:有会话在跑就把轮询压到最低,**回合结束立刻合并扫一次**。
130
+ *
131
+ * 为什么:轮询是唯一"用户没在等、却仍在花机器"的地方,而它扫描的时机(用户正打字/模型正在
132
+ * 跑)恰恰是最不该抢 CPU 的时候。活跃期间真实改动会由下一轮兜底(≤ activeInterval)覆盖,
133
+ * 回合一结束就把这一轮攒下的改动一次性并进来——索引还比"边跑边扫"更新鲜。
134
+ * @param key - 会话标识(`session.id`);多会话下任一活跃即活跃。
135
+ * @param active - 该会话是否正在跑回合。
136
+ */
137
+ setSessionActive(key, active) {
138
+ const id = String(key)
139
+ if (active) this._activeSessions.add(id)
140
+ else this._activeSessions.delete(id)
141
+ const next = this._activeSessions.size > 0
142
+ if (next === this._active) return
143
+ this._active = next
144
+ // 没 start()(watch: false)或已 stop():只记状态,不碰定时器。
145
+ if (this._stopped || this._activeInterval === undefined) return
146
+ if (this.timer) {
147
+ clearTimeout(this.timer)
148
+ this.timer = null
149
+ }
150
+ if (next) {
151
+ this._interval = this._activeInterval
152
+ this._schedule(this._activeInterval)
153
+ } else void this._tick() // 回合结束:立刻补扫,然后回到常规节拍
154
+ }
155
+
156
+ _schedule(interval = this._interval) {
157
+ this.timer = setTimeout(() => this._tick(), interval)
121
158
  if (this.timer.unref) this.timer.unref()
122
159
  }
123
160
 
@@ -130,7 +167,9 @@ export class WatchManager {
130
167
  // poll() 内部已逐根兜底;这里保证无论发生什么都一定排下一轮,不会静默停掉 watch。
131
168
  }
132
169
  if (this._stopped) return // 轮询期间被 stop() 了,不要再排下一轮
133
- this._interval = changed ? this._baseInterval : Math.min(this._interval * 2, this._maxInterval)
170
+ this._interval = this._active
171
+ ? this._activeInterval
172
+ : changed ? this._baseInterval : Math.min(this._interval * 2, this._maxInterval)
134
173
  this._schedule()
135
174
  }
136
175