@yolk_vat-y/dsh-project-memory 0.6.3 → 0.6.4

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/src/util/fs.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import {
2
- accessSync, constants, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync,
2
+ accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync,
3
3
  unlinkSync, writeFileSync,
4
4
  } from 'node:fs'
5
+ import { execFileSync } from 'node:child_process'
5
6
  import { readFile } from 'node:fs/promises'
6
7
  import { createHash } from 'node:crypto'
7
8
  import os from 'node:os'
@@ -37,6 +38,53 @@ export function writeJsonAtomic(file, data) {
37
38
  }
38
39
  }
39
40
 
41
+ /**
42
+ * 目录级写锁(跨进程)。写入前短暂持有,读改写之间不会交错。
43
+ * 锁文件是 `.write.lock`;崩溃留下的锁超过 staleMs 自动清掉。
44
+ * @param {string} dir 目标目录(不存在则创建)
45
+ * @param {{timeoutMs?: number, staleMs?: number}} [opts]
46
+ * @returns {null | (() => void)} 释放函数;拿不到锁返回 null
47
+ */
48
+ export function acquireDirLock(dir, { timeoutMs = 2000, staleMs = 10000 } = {}) {
49
+ try {
50
+ mkdirSync(dir, { recursive: true })
51
+ } catch {
52
+ return null
53
+ }
54
+ const file = path.join(dir, '.write.lock')
55
+ const deadline = Date.now() + timeoutMs
56
+ const sleeper = new Int32Array(new SharedArrayBuffer(4))
57
+ for (;;) {
58
+ try {
59
+ const fd = openSync(file, 'wx')
60
+ try {
61
+ writeFileSync(fd, String(process.pid))
62
+ } finally {
63
+ closeSync(fd)
64
+ }
65
+ return () => {
66
+ try {
67
+ unlinkSync(file)
68
+ } catch {
69
+ // 已被 stale 清理或目录不可写:不影响写入结果
70
+ }
71
+ }
72
+ } catch (err) {
73
+ if (err?.code !== 'EEXIST') return null
74
+ try {
75
+ if (Date.now() - statSync(file).mtimeMs > staleMs) {
76
+ unlinkSync(file)
77
+ continue
78
+ }
79
+ } catch {
80
+ // 锁刚好被释放:下一轮重试
81
+ }
82
+ if (Date.now() >= deadline) return null
83
+ Atomics.wait(sleeper, 0, 0, 10)
84
+ }
85
+ }
86
+ }
87
+
40
88
  export function assertReadableFile(filePath, maxFileSizeMb) {
41
89
  if (typeof filePath !== 'string' || !filePath) {
42
90
  throw new Error('file_path must be a non-empty string')
@@ -275,6 +323,85 @@ export function walkDir(root, opts = {}) {
275
323
  return { files: out, truncated, capped, skipped, unreadable }
276
324
  }
277
325
 
326
+ /**
327
+ * git 工作区文件(已跟踪 + 未跟踪且未被忽略);git 不可用/不是仓库时返回 null。
328
+ * `--exclude-standard` 让嵌套 `.gitignore` 也生效,构建产物与内部文档不会再进语料。
329
+ * @param {string} root 项目根
330
+ * @returns {string[]|null} 仓库相对路径(`/` 分隔)
331
+ */
332
+ function gitListedFiles(root) {
333
+ try {
334
+ const out = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
335
+ encoding: 'utf8',
336
+ maxBuffer: 64 * 1024 * 1024,
337
+ stdio: ['ignore', 'pipe', 'ignore'],
338
+ })
339
+ return out.split('\0').filter(Boolean)
340
+ } catch {
341
+ return null
342
+ }
343
+ }
344
+
345
+ /**
346
+ * 项目文件清单:git 仓库走 `git ls-files`(尊重 `.gitignore` 与嵌套规则),
347
+ * 非 git 目录回退 {@link walkDir}。返回形状与 walkDir 一致,调用方无需分支。
348
+ * @param {string} root 项目根
349
+ * @param {object} [opts] 同 walkDir,另加 `gitAware: false` 强制走 walkDir
350
+ * @returns {{files: string[], truncated: boolean, capped: boolean, skipped: string[], unreadable: string[]}}
351
+ */
352
+ export function listProjectFiles(root, opts = {}) {
353
+ const listed = opts.gitAware === false ? null : gitListedFiles(root)
354
+ if (listed === null) return walkDir(root, opts)
355
+ const maxFiles = Number.isFinite(opts.maxFiles) && opts.maxFiles > 0 ? opts.maxFiles : Infinity
356
+ const maxDepth = Number.isFinite(opts.maxDepth) && opts.maxDepth > 0 ? opts.maxDepth : Infinity
357
+ const nestedName = opts.nestedStoreName || null
358
+ const nested = nestedName
359
+ ? nestedStoreRoots(root, nestedName).map((p) => relativePath(root, p))
360
+ : []
361
+ const files = []
362
+ const skipped = new Set()
363
+ let capped = false
364
+ for (const raw of listed) {
365
+ const rel = String(raw).split(path.sep).join('/')
366
+ if (!rel) continue
367
+ const segs = rel.split('/')
368
+ if (segs.some((s) => DEFAULT_IGNORE.has(s))) continue
369
+ if (segs.length > maxDepth) {
370
+ capped = true
371
+ continue
372
+ }
373
+ const under = nested.find((n) => rel === n || rel.startsWith(`${n}/`))
374
+ if (under) {
375
+ skipped.add(path.join(root, under))
376
+ continue
377
+ }
378
+ if (files.length >= maxFiles) {
379
+ capped = true
380
+ break
381
+ }
382
+ const abs = path.join(root, rel)
383
+ try {
384
+ if (!statSync(abs).isFile()) continue
385
+ } catch {
386
+ continue
387
+ }
388
+ files.push(abs)
389
+ }
390
+ files.sort()
391
+ return { files, truncated: capped, capped, skipped: [...skipped].sort(), unreadable: [] }
392
+ }
393
+
394
+ /** 单个文件是否被 git 忽略(仅 git 仓库;非 git 目录返回 false)。 */
395
+ export function isGitIgnored(root, filePath) {
396
+ if (!root || !filePath || !existsSync(path.join(root, '.git'))) return false
397
+ try {
398
+ execFileSync('git', ['-C', root, 'check-ignore', '-q', '--', relativePath(root, filePath)], { stdio: 'ignore' })
399
+ return true
400
+ } catch {
401
+ return false
402
+ }
403
+ }
404
+
278
405
  export function isSupportedDoc(ext) {
279
406
  return ['.pdf', '.md', '.markdown', '.txt'].includes(ext)
280
407
  }
@@ -136,6 +136,8 @@ export function weightedFieldText(entry) {
136
136
  for (let i = 0; i < 5; i++) parts.push(entry.title || '')
137
137
  parts.push((entry.keywords || []).join(' '))
138
138
  parts.push(entry.summary || '')
139
+ // 符号的一行声明(签名/重载/类型体)也是可检索事实:只落盘不检索等于白存。
140
+ parts.push(entry.text || '')
139
141
  // 结构词项:覆盖整个 chunk 的字面词项,把「只有前 300 字符可检索」补回来(索引期零 LLM)
140
142
  parts.push(entry.terms || '')
141
143
  parts.push(entry.sourcePath || '')
@@ -172,33 +174,10 @@ export function rankEntriesMergedScored(entries, queries, limit = 8) {
172
174
  .slice(0, limit)
173
175
  }
174
176
 
175
- export function rankExperience(items, queryOrQueries, limit = 5) {
176
- return rankExperienceScored(items, queryOrQueries, limit).map((r) => r.item)
177
- }
178
-
179
- export function rankExperienceScored(items, queryOrQueries, limit = 5) {
180
- const bm25 = buildBm25(
181
- items,
182
- (item) => `${item.problem} ${item.problem} ${item.problem} ${item.solution} ${item.sourceFile || ''}`,
183
- (item) => [item.problem],
184
- )
185
- const queries = Array.isArray(queryOrQueries) ? queryOrQueries : [queryOrQueries]
186
- const merged = new Map()
187
- for (const query of queries) {
188
- for (const r of bm25.score(query)) {
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
193
- } else {
194
- merged.set(r.doc.id, { item: r.doc, score: r.score, matched: r.matched })
195
- }
196
- }
197
- }
198
- return [...merged.values()]
199
- .sort((a, b) => b.score - a.score)
200
- .slice(0, limit)
201
- }
177
+ // 说明:经验层(`kind:'experience'`)曾有自己的打分器 `rankExperienceScored`(v0.4 的
178
+ // `{problem,solution}` 形状)。统一存储后它与洞察层是同一个实体,也由 `save_lesson` 写出
179
+ // (没有 problem/solution 参数),独立打分器会把那种条目打成 0 分且无处可查。现由
180
+ // `recall.js` 用与洞察层相同的 `insightToEntry` 适配器打分,本函数随能力一起删除。
202
181
 
203
182
  function countOccurrences(text, token) {
204
183
  if (!token) return 0
@@ -24,9 +24,15 @@ const DIM = 256
24
24
  *
25
25
  * 为什么不用完整的评分文本:实测(36 条刻意无词重叠的查询 / 103 条池)标题变体的并集
26
26
  * hit@10 是 94%,而把 300 字摘要一起喂进去只有 89%——长文本在均值池化下会被稀释向语料均值。
27
+ *
28
+ * ⚠ 兜底链必须与 `normalizeInsight` 的标题推导**逐项相同**(含 `choice` 与否决 `topic`),
29
+ * 且同样截到 200:写入路径拿的是**归一化之前**的 raw(`save_lesson` 允许只给
30
+ * pattern / choice),只认 title 会让这类写入的查询文本变成空串 → 整条向量带去重静默失效
31
+ * (`vectorNear` 见空文本直接返回 null)。索引侧编码的是落盘后的 title,两边同源才可比。
27
32
  */
28
33
  export function vectorText(it) {
29
- return String(it?.title || it?.problem || it?.body || '').trim()
34
+ const t = it?.title || it?.pattern || it?.problem || it?.choice || it?.topic || it?.body
35
+ return String(t ?? '').trim().slice(0, 200)
30
36
  }
31
37
 
32
38
  const hashOf = (text) => createHash('sha256').update(String(text)).digest('hex').slice(0, 16)
@@ -89,10 +95,15 @@ export function openVectorIndex({ dir = null, items = [], embed, model, dim = DI
89
95
  let reused = 0
90
96
  let computed = 0
91
97
  let dirty = false
98
+ /**
99
+ * 本进程内被删掉的 id:`forget()` 之后即使调用方还拿着旧的条目列表,也不能把它重新编码
100
+ * 写回去(长驻进程里 store 对象可能仍持有已删条目的引用;"删了又活过来"比不删更难排查)。
101
+ */
102
+ const dropped = new Set()
92
103
 
93
104
  const ensure = (it) => {
94
105
  const key = keyOf(it)
95
- if (!key) return null
106
+ if (!key || dropped.has(key)) return null
96
107
  const text = vectorText(it)
97
108
  if (!text) return null
98
109
  const h = hashOf(text)
@@ -111,10 +122,17 @@ export function openVectorIndex({ dir = null, items = [], embed, model, dim = DI
111
122
  return v
112
123
  }
113
124
 
114
- /** 持久化(仅在有变化时写;失败不影响本次运行)。 */
125
+ /**
126
+ * 持久化(仅在有变化时写;失败不影响本次运行)。
127
+ * ⚠ **不建目录**:这是缓存写入,`score()` 会在读路径上调它,`writeJsonAtomic` 的
128
+ * `mkdirSync(recursive)` 会在"传错 root"时于任意可写位置造出 `<root>/.dsh-project-memory`
129
+ * ——那正是 query_memory / memory_stats 不得不加"根存在性"护栏的原因。目录在写入侧
130
+ * 早就存在(条目的来源),所以这条只会挡住"从零造目录"。
131
+ */
115
132
  const flush = () => {
116
133
  if (!dirty || !file) return false
117
134
  try {
135
+ if (!existsSync(dirname(file))) return false
118
136
  const keys = [...entryMap.keys()]
119
137
  const all = new Float32Array(keys.length * dim)
120
138
  const hashes = []
@@ -130,6 +148,27 @@ export function openVectorIndex({ dir = null, items = [], embed, model, dim = DI
130
148
  }
131
149
  }
132
150
 
151
+ /**
152
+ * 从索引里移除若干行(`forget` 之后调用)。**不需要加载模型**,也立即落盘:
153
+ * 删除承诺是"真删",而向量行是标题的 256 维均值池化——留着就不是真删。
154
+ * @param {string[]} ids
155
+ * @returns {number} 实际移除的行数
156
+ */
157
+ const forget = (ids) => {
158
+ let n = 0
159
+ for (const id of ids || []) {
160
+ if (!id) continue
161
+ // 两处都要删:`usable` 是打开时读回来的快照,`ensure()` 会从它那里复用旧行 ——
162
+ // 只删 entryMap 的话,下一次 score 会把被删的那一行原样复活。
163
+ let hit = false
164
+ if (usable?.map?.delete(id)) hit = true
165
+ if (entryMap.delete(id)) hit = true
166
+ if (hit) { n++; dirty = true; dropped.add(id) }
167
+ }
168
+ if (n) flush()
169
+ return n
170
+ }
171
+
133
172
  /**
134
173
  * 与 auto-inject / recall 两个接缝约定的同一签名:返回 Map<id, cos>。
135
174
  * 查询无法编码、或某条目无文本/无向量 → 该条不进 Map(调用方据此降级,不当 0 分罚它)。
@@ -161,6 +200,7 @@ export function openVectorIndex({ dir = null, items = [], embed, model, dim = DI
161
200
  return {
162
201
  score,
163
202
  flush,
203
+ forget,
164
204
  stats: {
165
205
  file, model, dim,
166
206
  persisted: entryMap.size,
@@ -217,22 +257,12 @@ async function resolveLeanvecDir(explicit) {
217
257
  }
218
258
 
219
259
  /**
220
- * 构造给 `recallItems` / `buildInjection` 用的 rerank。leanvec 不可用 → **null**。
221
- *
222
- * 装了就有向量、没装就纯词法,两条路的差别只在排序:闸门(覆盖率/共同词数)与返回条数都不变。
223
- * @param {object} o
224
- * @param {string|null} [o.storeDir] - 持久化位置(通常是项目 store 目录);null → 只在内存里
225
- * @param {object[]} [o.items] - 建索引的条目(见 {@link vectorItemsFrom})
226
- * @param {string|null} [o.vectorDir] - leanvec 目录(显式配置优先)
227
- * @param {number} [o.alpha] - 融合权重;实测 0.5 在小 k 上最优(见 recall.js 的注释)
228
- * @returns {Promise<{score: Function, alpha: number, stats: object}|null>}
260
+ * 解析当前可用的 leanvec 目录(**不加载模型**,只做 memo 过的解析 + 指纹)。
261
+ * 给 `memory_stats` 这类"只想知道开没开"的调用方用。
262
+ * @param {string|null} [vectorDir]
263
+ * @returns {Promise<{dir: string|null, fingerprint: string|null}>}
229
264
  */
230
- export async function createVectorRerank({ storeDir = null, items = [], vectorDir = null, alpha = 0.5 } = {}) {
231
- // 强制关闭:`vectorDir: 'off'`(或 alpha=0)一律返回 null,连模型都不加载。
232
- // 为什么需要:装了可选依赖之后,没有这个开关就无法退回纯词法——测试固定基线、
233
- // 线上排查"是不是向量层导致的"都会用得上。
234
- if (typeof vectorDir === 'string' && vectorDir.trim().toLowerCase() === 'off') return null
235
- if (alpha === 0) return null
265
+ export async function resolveVectorLayer(vectorDir = null) {
236
266
  const rk = `${typeof vectorDir === 'string' ? vectorDir : ''}\u0000${process.env.DSH_LEANVEC_DIR ?? ''}`
237
267
  let resolved = resolveCache.get(rk)
238
268
  if (resolved === undefined) {
@@ -240,10 +270,21 @@ export async function createVectorRerank({ storeDir = null, items = [], vectorDi
240
270
  resolved = { dir, fingerprint: dir ? leanvecFingerprint(dir) : null }
241
271
  resolveCache.set(rk, resolved) // 未安装也记下来:避免每步重复 resolve 的 IO
242
272
  }
243
- const { dir, fingerprint } = resolved
273
+ return resolved
274
+ }
275
+
276
+ /**
277
+ * 解析目录 + 加载运行时 + 打开(或复用)索引。**不含 alpha**——重排与写入侧去重
278
+ * 共用这一层,`alpha` 只属于前者(它是个排序权重,不该控制去重是否工作)。
279
+ * @returns {Promise<{index: object, fingerprint: string, dir: string}|null>}
280
+ */
281
+ async function openEngine({ storeDir = null, items = [], vectorDir = null } = {}) {
282
+ const { dir, fingerprint } = await resolveVectorLayer(vectorDir)
244
283
  if (!dir || !fingerprint) return null
245
284
  try {
246
- if (!runtimeCache || runtimeCache.dir !== dir) {
285
+ // 运行时按「目录 + 模型指纹」缓存:同一目录换了模型文件时必须重新加载,
286
+ // 否则会用旧模型编码、却把新指纹写进 vectors.json。
287
+ if (!runtimeCache || runtimeCache.dir !== dir || runtimeCache.fingerprint !== fingerprint) {
247
288
  const mod = await import(pathToFileURL(join(dir, 'src', 'embed.mjs')).href)
248
289
  const lv = mod.loadLeanvec({
249
290
  table: join(dir, 'dist', 'leanvec.f32'),
@@ -261,9 +302,121 @@ export async function createVectorRerank({ storeDir = null, items = [], vectorDi
261
302
  if (!index) return null
262
303
  indexCache.set(ck, index)
263
304
  }
264
- const a = typeof alpha === 'number' && alpha >= 0 && alpha <= 1 ? alpha : 0.5
265
- return { score: index.score, alpha: a, stats: index.stats }
305
+ return { index, fingerprint, dir }
266
306
  } catch {
267
307
  return null // 任何异常都降级到纯词法,绝不因为可选的向量层让召回失败
268
308
  }
269
309
  }
310
+
311
+ /**
312
+ * 构造给 `recallItems` / `buildInjection` 用的 rerank。leanvec 不可用 → **null**。
313
+ *
314
+ * 装了就有向量、没装就纯词法,两条路的差别只在排序:闸门(覆盖率/共同词数)与返回条数都不变。
315
+ * @param {object} o
316
+ * @param {string|null} [o.storeDir] - 持久化位置(通常是项目 store 目录);null → 只在内存里
317
+ * @param {object[]} [o.items] - 建索引的条目(见 {@link vectorItemsFrom})
318
+ * @param {string|null} [o.vectorDir] - leanvec 目录(显式配置优先)
319
+ * @param {number} [o.alpha] - 融合权重;实测 0.5 在小 k 上最优(见 recall.js 的注释)
320
+ * @param {number} [o.itemMin] - 条目的余弦下限(**实验性**,不设则不过滤;见 auto-inject 注释)
321
+ * @param {number} [o.speakMin] - 通道级语义救援阈值(**实验性**,不设则不启用)
322
+ * @returns {Promise<{score: Function, alpha: number, itemMin?: number, speakMin?: number, stats: object}|null>}
323
+ */
324
+ export async function createVectorRerank({ storeDir = null, items = [], vectorDir = null, alpha = 0.5, itemMin, speakMin } = {}) {
325
+ // 强制关闭:`vectorDir: 'off'`(或 alpha=0)一律返回 null,连模型都不加载。
326
+ // 为什么需要:装了可选依赖之后,没有这个开关就无法退回纯词法——测试固定基线、
327
+ // 线上排查"是不是向量层导致的"都会用得上。
328
+ if (typeof vectorDir === 'string' && vectorDir.trim().toLowerCase() === 'off') return null
329
+ if (alpha === 0) return null
330
+ const eng = await openEngine({ storeDir, items, vectorDir })
331
+ if (!eng) return null
332
+ const a = typeof alpha === 'number' && alpha >= 0 && alpha <= 1 ? alpha : 0.5
333
+ // `itemMin` / `speakMin` 只有**显式配置**时才进返回值:没有可发布的默认值(见 auto-inject
334
+ // 的证据),不设即整段逻辑不执行,默认路径与旧版逐字段一致。
335
+ const out = { score: eng.index.score, alpha: a, stats: eng.index.stats }
336
+ if (typeof itemMin === 'number' && Number.isFinite(itemMin)) out.itemMin = itemMin
337
+ if (typeof speakMin === 'number' && Number.isFinite(speakMin)) out.speakMin = speakMin
338
+ return out
339
+ }
340
+
341
+ /**
342
+ * 写入侧(近重复检测)用的余弦打分器。leanvec 不可用 / 显式关掉 → **null**。
343
+ *
344
+ * 与 `createVectorRerank` **刻意分开**:`autoContext.vectorAlpha` 是排序权重,把它设成 0
345
+ * 是"关掉重排",不该连带关掉写入去重(旧实现复用同一个函数,于是 `vectorAlpha: 0` 静默
346
+ * 停掉了 0.9 自动覆盖 / 0.7 近邻提示)。开关是独立的 `vectorDedup`。
347
+ * @returns {Promise<((text: string, items: object[]) => Map<string, number>)|null>}
348
+ */
349
+ export async function createVectorCosine({ storeDir = null, items = [], vectorDir = null, dedup = true } = {}) {
350
+ if (dedup === false) return null
351
+ if (typeof vectorDir === 'string' && vectorDir.trim().toLowerCase() === 'off') return null
352
+ const eng = await openEngine({ storeDir, items, vectorDir })
353
+ if (!eng) return null
354
+ return (text, cands) => eng.index.score(text, cands)
355
+ }
356
+
357
+ /**
358
+ * 删除若干条目的向量行(`forget` 之后调用)。**不加载模型**:只读文件、过滤 id、原子重写,
359
+ * 并同步清掉进程内缓存索引里的同名行(否则下次 flush 会把它写回去)。
360
+ * @param {{dir: string|null, ids: string[]}} o
361
+ * @returns {number} 移除的行数(尽力而为,绝不抛)
362
+ */
363
+ export function forgetVectorRows({ dir = null, ids = [] } = {}) {
364
+ const want = new Set((ids || []).filter(Boolean))
365
+ if (!dir || !want.size) return 0
366
+ let n = 0
367
+ // ① 进程内缓存:按 storeDir 前缀找对应的索引(一个 store 一般只有一份)
368
+ for (const [ck, idx] of indexCache) {
369
+ if (!ck.startsWith(`${dir}\u0000`)) continue
370
+ if (idx && typeof idx.forget === 'function') n += idx.forget([...want])
371
+ }
372
+ // ② 磁盘:文件可能是别的进程写的,单独再清一遍(幂等)
373
+ const file = join(dir, FILE)
374
+ try {
375
+ if (!existsSync(file)) return n
376
+ const doc = JSON.parse(readFileSync(file, 'utf8'))
377
+ if (!doc || !Array.isArray(doc.ids) || typeof doc.blob !== 'string') return n
378
+ const keep = []
379
+ for (let i = 0; i < doc.ids.length; i++) if (!want.has(doc.ids[i])) keep.push(i)
380
+ if (keep.length === doc.ids.length) return n
381
+ const buf = Buffer.from(doc.blob, 'base64')
382
+ const u8 = new Uint8Array(buf)
383
+ const stride = Number.isInteger(doc.dim) && doc.dim > 0 ? doc.dim : DIM
384
+ const all = new Float32Array(u8.buffer, 0, Math.floor(u8.byteLength / 4))
385
+ const next = new Float32Array(keep.length * stride)
386
+ keep.forEach((src, i) => next.set(all.subarray(src * stride, src * stride + stride), i * stride))
387
+ writeJsonAtomic(file, {
388
+ ...doc,
389
+ ids: keep.map((i) => doc.ids[i]),
390
+ hashes: keep.map((i) => doc.hashes?.[i] ?? ''),
391
+ blob: Buffer.from(next.buffer, next.byteOffset, next.byteLength).toString('base64'),
392
+ })
393
+ n = Math.max(n, doc.ids.length - keep.length)
394
+ } catch {
395
+ // 损坏/不可写:删除承诺只对条目本身负责,向量缓存坏掉会在下次重建
396
+ }
397
+ return n
398
+ }
399
+
400
+ /**
401
+ * 索引状态摘要(**不加载模型**):给 `memory_stats` 用的可观测量。
402
+ * 报告行数、陈旧行(文件里有、store 里已没有)、体积、模型指纹与落盘时间。
403
+ */
404
+ export function vectorIndexSummary({ dir = null, items = [] } = {}) {
405
+ const live = new Set((items || []).map((it) => (it?.insightId ?? it?.id)).filter(Boolean))
406
+ const summary = { file: dir ? join(dir, FILE) : null, rows: 0, live: live.size, stale: 0, bytes: 0, updatedAt: null, model: null }
407
+ if (!dir) return summary
408
+ try {
409
+ const st = statSync(summary.file)
410
+ summary.bytes = st.size
411
+ summary.updatedAt = st.mtime.toISOString()
412
+ const doc = JSON.parse(readFileSync(summary.file, 'utf8'))
413
+ summary.model = typeof doc?.model === 'string' ? doc.model : null
414
+ for (const id of Array.isArray(doc?.ids) ? doc.ids : []) {
415
+ summary.rows++
416
+ if (!live.has(id)) summary.stale++
417
+ }
418
+ } catch {
419
+ // 没有/坏了:rows=0,上层据此说"尚未建立"
420
+ }
421
+ return summary
422
+ }
package/src/watch.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { existsSync, statSync } from 'node:fs'
2
2
  import path from 'node:path'
3
- import { isUnsafeRoot, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey, walkDir } from './util/fs.js'
3
+ import { isUnsafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey } from './util/fs.js'
4
4
  import { OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from './index-pipeline.js'
5
5
  import { ProjectMemoryStore } from './store.js'
6
6
  import { onFileChanged, isTypeScriptFile } from './enhancer.js'
@@ -206,7 +206,7 @@ export class WatchManager {
206
206
  // 本轮用的 store:命中缓存即 O(1),被逐出则重新读盘。整个 pollRoot 期间共用同一个实例。
207
207
  const store = this.storeFor(root)
208
208
 
209
- const { files, truncated, capped, skipped: nestedRoots, unreadable } = walkDir(root, {
209
+ const { files, truncated, capped, skipped: nestedRoots, unreadable } = listProjectFiles(root, {
210
210
  ...scanLimits(this.config),
211
211
  nestedStoreName: memoryDirName(this.config),
212
212
  })