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

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/enhancer.js CHANGED
@@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs'
3
3
  import { join } from 'node:path'
4
4
  import { createRequire } from 'node:module'
5
5
  import { oneLineDeclaration } from './util/text.js'
6
+ import { entryIdPrefix } from './util/entry-id.js'
6
7
 
7
8
  const require = createRequire(import.meta.url)
8
9
 
@@ -95,8 +96,22 @@ const PRIORITY = {
95
96
  BACKLOG: 3
96
97
  }
97
98
 
99
+ /**
100
+ * TS 增强队列的上界。
101
+ *
102
+ * 为什么需要它(0.5.15 加固):`index_repo` 对**全部** TS/JS 一次性入队,而队列此前
103
+ * 没有任何 cap。配合下面的"出队才解析",队列里每条只剩元数据(≈ 几百字节),默认
104
+ * `maxScanFiles`(20000)量级下上限约几 MB —— 这个数取成与扫描上限同量级,正常仓库够不到,
105
+ * 它只是防御"被抬高的 maxScanFiles / 异常调用方"的兜底阀。
106
+ */
107
+ const ENHANCE_QUEUE_MAX = 20000
108
+
98
109
  const enhanceQueue = []
110
+ let enhanceQueueMax = ENHANCE_QUEUE_MAX
99
111
  let processing = false
112
+ /** `dropped` 计数两类丢弃:被挤掉的旧任务与被拒的新任务;`parsed` 是"出队后才解析"的证据。 */
113
+ const enhanceStats = { dropped: 0, parsed: 0 }
114
+ let droppedWarned = false
100
115
 
101
116
  function getCacheKey(content) {
102
117
  const hash = createHash('sha256').update(content).digest('hex').slice(0, 16)
@@ -337,6 +352,20 @@ export function deepParseWithTS(filePath, content) {
337
352
  return symbols
338
353
  }
339
354
 
355
+ /**
356
+ * 入队一个 TS 增强任务。两条不变式(0.5.15 加固):
357
+ *
358
+ * 1. **任务体在出队时才跑**。入队只读一次文件算 `cacheKey`(16 字节哈希),正文与解析结果
359
+ * 都不留在队列里;真正读正文 + `deepParseWithTS` + 提交发生在 `runEnhance()`。
360
+ * 旧实现在入队时就同步跑到第一个 `await`,于是 `index_repo` 对整棵 TS 树一次性入队 =
361
+ * 同时持有**所有**文件的正文与符号数组 —— 长驻 `dsh web` 的 RSS 单调爬升就是这个形状。
362
+ * 2. **有界**。队列长度不超过 `enhanceQueueMax`,超了先挤队尾(最不紧急的),挤不动就丢新
363
+ * 来的那条;被丢的任务 promise 立刻 resolve(调用方都是 fire-and-forget),丢弃计数由
364
+ * `enhanceQueueStats()` 暴露、并由 `index_repo` 写进报告 —— 不静默。
365
+ *
366
+ * 去重语义与旧实现一致(同 relPath 同内容复用,内容变了换掉)。已经开始跑的任务不在队列里,
367
+ * 因此不受替换/挤掉影响。
368
+ */
340
369
  export function enqueueEnhance(store, relPath, filePath, priority = PRIORITY.BATCH, config, root) {
341
370
  if (!ts) return Promise.resolve()
342
371
 
@@ -352,59 +381,92 @@ export function enqueueEnhance(store, relPath, filePath, priority = PRIORITY.BAT
352
381
  }
353
382
  const cacheKey = getCacheKey(content)
354
383
 
355
- // Dedupe by (relPath, contentHash) - if same content, skip; if different, replace
384
+ // 去重语义与旧实现一致:同 relPath 同内容 → 复用队列里那条 promise;内容变了 → 换掉它。
356
385
  const existingIdx = enhanceQueue.findIndex(q => q.relPath === relPath)
357
386
  if (existingIdx >= 0) {
358
387
  const existing = enhanceQueue[existingIdx]
359
388
  if (existing.cacheKey === cacheKey) {
360
- // Same content, just update priority if higher
361
389
  if (priority < existing.priority) {
362
- enhanceQueue[existingIdx].priority = priority
390
+ existing.priority = priority
363
391
  enhanceQueue.sort((a, b) => a.priority - b.priority)
364
392
  }
365
393
  return existing.promise
366
- } else {
367
- // Content changed - replace the task
368
- enhanceQueue[existingIdx] = { relPath, filePath, priority, cacheKey, promise: null }
369
- // Will create new promise below
370
394
  }
395
+ // 内容变了:那条还没开始跑(跑起来的早已出队)→ 换掉,并让它的 promise 立刻 resolve,
396
+ // 否则调用方 await 的那个 promise 永远悬着。
397
+ existing.resolve()
398
+ enhanceQueue.splice(existingIdx, 1)
371
399
  }
372
400
 
373
- // 先登记队列条目,再启动任务。
374
- //
375
- // 任务体可能在**同步阶段**就跑完:`deepParseWithTS` 是同步的,没有增强结果时根本走不到
376
- // 那个 `await`,于是 `finally` 立刻执行。旧实现在任务启动**之后**才登记条目,并在 finally
377
- // 里用 `enhanceQueue.findIndex(q => q.promise === p)` 反查自己 ——
378
- // · 队列为空时 `findIndex` 的回调根本不会被调用,`p` 不被求值,看不出问题;
379
- // · 队列非空(真实的 watch 轮询里必然如此)时回调被调用,读到尚未初始化的 `const p`
380
- // → `ReferenceError: Cannot access 'p' before initialization`。
381
- // `scheduleProcess` 会 await 这个 promise,但 watch 路径上抛出的那一个没人接,未处理的
382
- // rejection 直接把宿主打成 `dsh: fatal load failure`。
383
- //
384
- // 现在:条目先入队,finally 按**对象身份**摘除自己,完全不引用尚未初始化的绑定。
385
- const entry = { relPath, filePath, priority, cacheKey, promise: null }
386
- if (existingIdx >= 0) enhanceQueue[existingIdx] = entry
387
- else enhanceQueue.push(entry)
388
-
389
- entry.promise = (async () => {
390
- try {
391
- const content = readFileSync(filePath, 'utf8')
392
- const enhanced = deepParseWithTS(filePath, content)
393
- if (enhanced?.length) {
394
- await store.commit(fn => applyEnhancedSymbols(fn, relPath, enhanced))
395
- }
396
- } catch (err) {
397
- console.warn(`[dsh-project-memory] enhance failed for ${relPath}: ${err.message}`)
398
- } finally {
399
- // 只摘自己那一条:同 relPath 的新任务可能已经把它替换掉了(那种情况这里是 -1)。
400
- const idx = enhanceQueue.indexOf(entry)
401
- if (idx >= 0) enhanceQueue.splice(idx, 1)
401
+ const task = { store, relPath, filePath, priority, cacheKey, promise: null, resolve: null }
402
+ task.promise = new Promise((resolve) => { task.resolve = resolve })
403
+
404
+ if (enhanceQueue.length >= enhanceQueueMax) {
405
+ // 满了:优先挤掉队尾(`priority` 数字最大 = 最不紧急)的那条;挤不动(对方更紧急)
406
+ // 就丢掉新来的这条。两条路都计数 + 一次告警,绝不静默。
407
+ const last = enhanceQueue[enhanceQueue.length - 1]
408
+ if (last && last.priority > priority) {
409
+ enhanceQueue.pop()
410
+ last.resolve()
411
+ warnDropped()
412
+ } else {
413
+ warnDropped()
414
+ task.resolve()
415
+ return task.promise
402
416
  }
403
- })()
404
- enhanceQueue.sort((a, b) => a.priority - b.priority)
417
+ }
405
418
 
419
+ enhanceQueue.push(task)
420
+ enhanceQueue.sort((a, b) => a.priority - b.priority)
406
421
  scheduleProcess()
407
- return entry.promise
422
+ return task.promise
423
+ }
424
+
425
+ /** 只打一次:这是**降级说明**(有些文件这轮没有 L2 增强),不是每轮都刷屏的故障。 */
426
+ function warnDropped() {
427
+ enhanceStats.dropped++
428
+ if (droppedWarned) return
429
+ droppedWarned = true
430
+ console.warn(
431
+ `[dsh-project-memory] TS 增强队列已满(上限 ${enhanceQueueMax}):优先级最低的任务被丢弃。` +
432
+ '这些文件仍有 L1 正则符号,只是没有 L2 类型增强;下次索引 / 改动会重新入队。',
433
+ )
434
+ }
435
+
436
+ /**
437
+ * 队列现状。`index_repo` 用它把"这轮丢了多少"写进报告(不静默),测试用它断言
438
+ * 「入队同步阶段只解析 1 个」与上界。
439
+ */
440
+ export function enhanceQueueStats() {
441
+ return { queued: enhanceQueue.length, max: enhanceQueueMax, dropped: enhanceStats.dropped, parsed: enhanceStats.parsed }
442
+ }
443
+
444
+ /** 仅供测试:临时收窄队列上限(返回恢复函数),免得测试真去排两万条。 */
445
+ export function _setEnhanceQueueMaxForTest(n) {
446
+ const previous = enhanceQueueMax
447
+ enhanceQueueMax = Number.isFinite(n) && n > 0 ? n : ENHANCE_QUEUE_MAX
448
+ return () => { enhanceQueueMax = previous }
449
+ }
450
+
451
+ /** 出队之后才真正干活:此刻才读正文、才解析(正文与解析结果只活到这一步结束)。 */
452
+ async function runEnhance(task) {
453
+ let content
454
+ try {
455
+ content = readFileSync(task.filePath, 'utf8')
456
+ } catch {
457
+ return // 同入队路径:文件没了不是故障,安静跳过
458
+ }
459
+ enhanceStats.parsed++
460
+ try {
461
+ const enhanced = deepParseWithTS(task.filePath, content)
462
+ if (enhanced?.length) {
463
+ await task.store.commit(fn => applyEnhancedSymbols(fn, task.relPath, enhanced))
464
+ }
465
+ } catch (err) {
466
+ console.warn(`[dsh-project-memory] enhance failed for ${task.relPath}: ${err.message}`)
467
+ } finally {
468
+ task.resolve()
469
+ }
408
470
  }
409
471
 
410
472
  function scheduleProcess() {
@@ -415,9 +477,11 @@ function scheduleProcess() {
415
477
  while (enhanceQueue.length > 0) {
416
478
  const task = enhanceQueue.shift()
417
479
  try {
418
- await task.promise
480
+ await runEnhance(task)
419
481
  } catch (err) {
482
+ // runEnhance 内部已兜底;这里再兜一层,保证调度循环不会因单条任务死掉。
420
483
  console.warn(`[dsh-project-memory] enhance task failed: ${err.message}`)
484
+ task.resolve()
421
485
  }
422
486
  await new Promise(r => setImmediate(r))
423
487
  }
@@ -457,7 +521,7 @@ function applyEnhancedSymbols(fn, relPath, enhanced) {
457
521
  const newEntries = []
458
522
  for (const s of enhanced) {
459
523
  if (existingKeys.has(`${s.name}#${s.line}`)) continue
460
- const base = `${relPath.replace(/[\/:\s]/g, '_')}#${s.line}`
524
+ const base = `${entryIdPrefix(relPath)}#${s.line}`
461
525
  let id = base
462
526
  if (usedIds.has(id)) id = `${base}-${s.kind}`
463
527
  for (let n = 2; usedIds.has(id); n++) id = `${base}-${s.kind}-${n}`
package/src/index.js CHANGED
@@ -24,7 +24,10 @@ export const Config = Schema.object({
24
24
  memoryDir: Schema.string().default('.dsh-project-memory'),
25
25
  chunkChars: Schema.number().default(3000),
26
26
  maxChunksPerFile: Schema.number().default(40),
27
- maxFileSizeMb: Schema.number().default(50),
27
+ // 单文件内存闸门,不是磁盘设置:索引一个文件要先把它整个物化,峰值随文件大小线性走。
28
+ // 实测边际系数(峰值 RSS / 磁盘 MB,见 bench/file-peak.mjs 与 README「单文件内存预算」):
29
+ // 典型源码 ~10×、符号密集代码 ~21×、文本型 PDF ~19×。10 把单文件增量压在 ~+300 MB。
30
+ maxFileSizeMb: Schema.number().default(10),
28
31
  maxOutputChars: Schema.number().default(8000),
29
32
  maxPdfPages: Schema.number().default(1000),
30
33
  llmQueryExpansion: Schema.boolean().default(false),
@@ -106,8 +109,11 @@ export const Config = Schema.object({
106
109
  // Schema 里声明过:走 cordis.patch.yml 配它们会被宿主按「not a declared property」拒掉,
107
110
  // 等于文档里的旋钮是假的。默认值以 cfgEngine 的兜底值为准(那里是权威,这里只负责暴露)。
108
111
  gateCooldownSteps: Schema.number().default(2),
109
- maxItemsPerSession: Schema.number().default(12),
110
- maxItemCharsPerSession: Schema.number().default(4000),
112
+ // 这两个是**保险丝**不是节流阀:节流由 gateCooldownSteps 与单轮 maxTokens 负责。
113
+ // 旧默认 12 / 4000 ≈ 11 条,实测真实日志里 11/81 个会话打满、打满后永久静默(1234 步失明);
114
+ // 实测最长会话用 35 条 / 8640 字符,故抬到 60 / 24000。显式配小值可复现旧行为。
115
+ maxItemsPerSession: Schema.number().default(60),
116
+ maxItemCharsPerSession: Schema.number().default(24000),
111
117
  hintMinCoverage: Schema.number().default(0.45),
112
118
  hintMinMatched: Schema.number().default(2),
113
119
  hintMinSupport: Schema.number().default(0.15),
@@ -117,8 +123,10 @@ export const Config = Schema.object({
117
123
  // 影子记录(admission-shadow.jsonl):**每步**一行,含全部候选的判据特征与场景。
118
124
  // 主审计只在真的注入时写,静默步零痕迹 → 无法离线重放"换个阈值会怎样",也攒不出样本。
119
125
  // 只写盘、不进 prompt、不花 token,所以默认开。
126
+ // 512KB 而不是 2MB:轮转只留 `.1` 一代,所以单项目日志的硬上限是
127
+ // `2 × shadowMaxBytes + 2 × auditMaxBytes`(原 4.6MB);512KB 下约 1.5MB。
120
128
  shadowLog: Schema.boolean().default(true),
121
- shadowMaxBytes: Schema.number().default(2097152),
129
+ shadowMaxBytes: Schema.number().default(524288),
122
130
  }).default({}),
123
131
  })
124
132
 
@@ -6,10 +6,11 @@
6
6
  // - 归档 = 软删(archived:true,不进召回/注入);物理删除只发生在容量溢出
7
7
  // - 写盘前密文过滤:命中密钥/token/私钥形态 → 拒绝写入
8
8
  import { randomUUID } from 'node:crypto'
9
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
9
+ import { readFileSync, renameSync } from 'node:fs'
10
10
  import path from 'node:path'
11
11
  import os from 'node:os'
12
12
  import { normalizedTokenOverlap, findBestOverlapMatch, insightMatchText } from './similarity.js'
13
+ import { writeJsonAtomic } from './util/fs.js'
13
14
  import { backfillDerivedTriggers } from './readiness.js'
14
15
 
15
16
  export const INSIGHT_KINDS = ['lesson', 'decision', 'procedure', 'experience']
@@ -332,22 +333,6 @@ function readJson(file, fallback) {
332
333
  }
333
334
  }
334
335
 
335
- function writeJsonAtomic(file, data) {
336
- mkdirSync(path.dirname(file), { recursive: true })
337
- const tmp = `${file}.${process.pid}.tmp`
338
- try {
339
- writeFileSync(tmp, JSON.stringify(data))
340
- renameSync(tmp, file)
341
- } catch (err) {
342
- try {
343
- renameSync(tmp, file) // fsync 无关紧要:单文件覆盖 + 崩溃后 .tmp 清理即可
344
- } catch {
345
- /* ignore */
346
- }
347
- throw err
348
- }
349
- }
350
-
351
336
  function normalizeDoc(doc) {
352
337
  if (doc && typeof doc === 'object' && Array.isArray(doc.items)) {
353
338
  if (typeof doc.version !== 'number') doc.version = 1
package/src/ops.js CHANGED
@@ -6,15 +6,10 @@
6
6
  //
7
7
  // 分工:ops.js 只负责"把调用读成什么动作",不负责决定注入什么(那是 readiness/auto-inject)。
8
8
  // 刻意不 import readiness:readiness 要 import 本模块的 op 闭集,反向依赖会造成循环。
9
+ // 路径 token 的规则因此收在 util/path-token.js —— 它谁也不依赖,两个模块都能 import
10
+ // (原先这里就地抄了一份,注释还写着"与 readiness.extractPaths 同规则",实际已漂移)。
9
11
 
10
- /** 带扩展名的路径 token(与 readiness.extractPaths 同规则;这里就地实现以免循环依赖)。 */
11
- const PATH_TOKEN = /(?:[A-Za-z0-9_.@-]+\/)*[A-Za-z0-9_.@-]+\.[A-Za-z][A-Za-z0-9]{0,7}\b/g
12
-
13
- function extractPaths(text) {
14
- const s = String(text || '')
15
- if (!s) return []
16
- return [...new Set([...s.matchAll(PATH_TOKEN)].map((m) => m[0]))]
17
- }
12
+ import { extractPathTokens } from './util/path-token.js'
18
13
 
19
14
  /** op 闭集。新增一个 op 必须同时想清楚:它是动作,不是话题。 */
20
15
  export const OP_IDS = [
@@ -133,7 +128,7 @@ export function classifyShellCommand(command) {
133
128
  }
134
129
  }
135
130
  if (!ops.length) ops.push('shell-run')
136
- const targets = SHELL_WRITE_RE.test(cmd) ? extractPaths(cmd) : []
131
+ const targets = SHELL_WRITE_RE.test(cmd) ? extractPathTokens(cmd) : []
137
132
  const hosts = WSL_HINT_RE.test(cmd) || /\b(powershell|pwsh|cmd)\.exe\b/i.test(cmd) ? ['wsl'] : []
138
133
  return { ops, targets, hosts }
139
134
  }
@@ -152,7 +147,7 @@ export function classifyToolCall(name, argsText) {
152
147
  if (FETCH_TOOLS.has(tool)) return { ops: ['fetch-web'], targets: [], hosts: [] }
153
148
  if (QUERY_TOOLS.has(tool)) return { ops: ['query-memory'], targets: [], hosts: [] }
154
149
  if (WRITE_TOOLS.has(tool)) {
155
- const targets = path ? [path, ...extractPaths(path)] : []
150
+ const targets = path ? [path, ...extractPathTokens(path)] : []
156
151
  const hosts = targets.some((t) => WSL_HINT_RE.test(t)) ? ['wsl'] : []
157
152
  return { ops: ['file-write'], targets: [...new Set(targets)], hosts }
158
153
  }
@@ -191,9 +186,12 @@ export function activityFromText(text) {
191
186
  // 先按"工具调用"解析(`edit {"file_path":"..."}`):结构化参数比正则猜命令可靠得多。
192
187
  const call = /^\s*([A-Za-z_][\w-]*)\s+(\{[\s\S]*\})\s*$/.exec(line)
193
188
  const r = call ? classifyToolCall(call[1], call[2]) : classifyShellCommand(line)
194
- // 纯文本行里没有 shell 动作时不要退化成 shell-run(那是噪音源)
195
- if (r.ops.length === 1 && r.ops[0] === 'shell-run' && !/\b\w+\s+-/.test(line)) continue
196
- for (const op of r.ops) ops.add(op)
189
+ // 纯文本行里没有 shell 动作时不要退化成 shell-run(那是噪音源)。但**只丢这个 op**:
190
+ // 行里的写目标/主机是具体事实(要靠路径 token、/mnt/ 这类签名才抽得出,泛泛的散文产不出来),
191
+ // 一起丢掉会让 `bash {"command":"echo x >> .gitignore"}` 这种 shell-run-only 的写意图
192
+ // 到不了 when.writes —— 实测它连结构化工具调用行的写目标都会被静默吞掉。
193
+ const noiseOp = r.ops.length === 1 && r.ops[0] === 'shell-run' && !/\b\w+\s+-/.test(line)
194
+ if (!noiseOp) for (const op of r.ops) ops.add(op)
197
195
  for (const t of r.targets) targets.add(t)
198
196
  for (const h of r.hosts) hosts.add(h)
199
197
  }
@@ -107,36 +107,6 @@ export async function parsePdf(filePath, { pages = null, maxPages = 1000, backen
107
107
  }
108
108
  }
109
109
 
110
- export async function parsePdfInfo(filePath, maxPages = 1000) {
111
- const data = new Uint8Array(await readFile(filePath))
112
- const { getDocument } = await loadPdfjs()
113
- const loadingTask = getDocument({ data, ...PDFJS_OPTIONS })
114
- try {
115
- const doc = await loadingTask.promise
116
- if (doc.numPages > maxPages) {
117
- throw new Error(`PDF has ${doc.numPages} pages, over the maxPages limit of ${maxPages}`)
118
- }
119
- let meta = {}
120
- try {
121
- meta = await doc.getMetadata()
122
- } catch {
123
- // metadata is optional
124
- }
125
- const info = meta.info || {}
126
- return {
127
- pageCount: doc.numPages,
128
- title: info.Title ?? null,
129
- author: info.Author ?? null,
130
- subject: info.Subject ?? null,
131
- created: info.CreationDate ?? null,
132
- modified: info.ModDate ?? null,
133
- encrypted: doc.isEncrypted,
134
- }
135
- } finally {
136
- await loadingTask.destroy()
137
- }
138
- }
139
-
140
110
  export function configurePdfjsWorker(workerSrc) {
141
111
  configuredWorkerSrc = workerSrc
142
112
  if (pdfjsPromise) {
package/src/readiness.js CHANGED
@@ -17,6 +17,7 @@
17
17
  */
18
18
 
19
19
  import { FALLBACK_OPS, WEAK_OPS, activityFromText, opForLegacyAction } from './ops.js'
20
+ import { extractPathTokens } from './util/path-token.js'
20
21
  import { CJK_RANGE, tokenize } from './util/search.js'
21
22
 
22
23
  /**
@@ -35,11 +36,6 @@ export const ACTION_LEXICON = [
35
36
  ['deploy', [/\bdeploy\b/i, /部署/]],
36
37
  ]
37
38
 
38
- /** 带扩展名的路径 token(README.md、src/util/fs.js …)。 */
39
- const PATH_TOKEN = /(?:[A-Za-z0-9_.@-]+\/)*[A-Za-z0-9_.@-]+\.[A-Za-z][A-Za-z0-9]{0,7}\b/g
40
- /** 点开头的裸文件名(.gitignore、.npmrc …)。 */
41
- const DOTFILE_TOKEN = /(?:^|[\s"'`(])(\.[A-Za-z0-9_-]{2,})/g
42
-
43
39
  /**
44
40
  * 文本 → 动作 id 列表(确定性、去重、词典序稳定)。
45
41
  * @param {string} text - 人类消息或工具调用参数。
@@ -56,17 +52,14 @@ export function detectActions(text) {
56
52
  }
57
53
 
58
54
  /**
59
- * 文本 → 路径 token(用于 trigger.paths 的 glob 匹配)。
55
+ * 文本 → 路径 token(用于 trigger 的 `writes` / `guard.paths` 匹配)。
56
+ * 规则收在 `util/path-token.js`:与 ops 抽写目标是**同一份实现**
57
+ * (原先这里与 ops.js 各抄一份,ops 那份漏了点开头文件名且已漂移)。
60
58
  * @param {string} text - 工具调用参数或人类消息。
61
59
  * @returns {string[]} 去重后的路径 token。
62
60
  */
63
61
  export function extractPaths(text) {
64
- const s = String(text || '')
65
- if (!s) return []
66
- const out = new Set()
67
- for (const m of s.matchAll(PATH_TOKEN)) out.add(m[0])
68
- for (const m of s.matchAll(DOTFILE_TOKEN)) out.add(m[1])
69
- return [...out]
62
+ return extractPathTokens(text)
70
63
  }
71
64
 
72
65
  /**
@@ -447,10 +440,35 @@ export function auditTriggers(items, opts = {}) {
447
440
  * @returns {{coverage: number, matched: number, supported: number, terms: number}}
448
441
  */
449
442
  export function idfCoverage(query, itemText, corpusTexts) {
443
+ return idfCoveragePrepared(query, itemText, corpusTermSets(corpusTexts))
444
+ }
445
+
446
+ /**
447
+ * 语料 → 词集合数组。**对一批候选循环评分时必须只建一次**。
448
+ *
449
+ * `idfCoverage(query, item, corpusTexts)` 每次都把整个语料重新 tokenize 一遍;调用方对 C 个
450
+ * 候选各调一次,就是 C×C 次 tokenize —— 实测真实 store(72 条)单步 147 ms,提出循环外
451
+ * 降到 1.3 ms(109×),且 coverage 结果逐字段一致。热路径上每个 pre-step 都要跑一次,所以
452
+ * 这个差别是"每条模型消息"级别的。
453
+ * @param {string[]} texts - 语料正文
454
+ * @returns {Set<string>[]} 与输入同序的词集合
455
+ */
456
+ export function corpusTermSets(texts) {
457
+ return (texts || []).map((t) => new Set(tokenize(t)))
458
+ }
459
+
460
+ /**
461
+ * 与 {@link idfCoverage} 同一套判据,但语料词集合由调用方预先建好(见 {@link corpusTermSets})。
462
+ * @param {string} query - 查询文本
463
+ * @param {string} itemText - 被测条目的评分文本
464
+ * @param {Set<string>[]} corpusSets - {@link corpusTermSets} 的产物
465
+ * @returns {{coverage: number, matched: number, supported: number, terms: number}}
466
+ */
467
+ export function idfCoveragePrepared(query, itemText, corpusSets) {
450
468
  const q = [...new Set(tokenize(query))]
451
469
  if (!q.length) return { coverage: 0, matched: 0, supported: 0, terms: 0 }
452
470
  const item = new Set(tokenize(itemText))
453
- const corpus = (corpusTexts || []).map((t) => new Set(tokenize(t)))
471
+ const corpus = corpusSets || []
454
472
  const n = Math.max(corpus.length, 1)
455
473
  let total = 0
456
474
  let hit = 0
package/src/store.js CHANGED
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto'
2
2
  import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
3
3
  import path from 'node:path'
4
4
  import { rankExperience, tokenize, tokenizeRaw, extractCjkPhrases, makeSearchText } from './util/search.js'
5
+ import { writeJsonAtomic } from './util/fs.js'
5
6
  import { backfillDerivedTriggers } from './readiness.js'
6
7
 
7
8
  const FORMAT_FILE = 'format.json'
@@ -152,19 +153,60 @@ function isRecord(value) {
152
153
  * 实测两者在一个真实大仓库 store 里合计约 245MB(链接 222.8MB + searchText 22.7MB)。
153
154
  */
154
155
  const PERSISTED_DERIVED = ['linkedSymbols', 'searchText', 'typeSig']
156
+ const PERSISTED_DERIVED_SET = new Set(PERSISTED_DERIVED)
155
157
 
156
- /** 原地剥离派生字段(加载路径用,省掉一次分配)。 */
158
+ /** 有没有派生字段要剥。没有就走零分配路径(绝大多数条目、以及所有新写的分片)。 */
159
+ function hasPersistedDerived(entry) {
160
+ for (const key of PERSISTED_DERIVED) if (key in entry) return true
161
+ return false
162
+ }
163
+
164
+ /**
165
+ * 按**非派生键重建**一个对象。
166
+ *
167
+ * 不用 `delete`:删除属性会把 entry 推进 V8 的字典模式,之后每个属性都变成哈希表项。
168
+ * 本仓库真实条目形状实测 —— `delete` 后 **1196 B/条**,重建后 **436 B/条**(20k 条 / --expose-gc)。
169
+ * 加载路径上这是常驻内存(`storeCache` 里所有 store 都算),写盘路径上同款浪费。
170
+ *
171
+ * `undefined` 值的键也不复制:`typeSig: undefined` 是 enhancer 的实现细节(见 src/enhancer.js),
172
+ * JSON 里本来就不存在,留在内存对象里只会占一个属性槽。
173
+ */
174
+ function rebuildWithoutDerived(entry) {
175
+ const out = {}
176
+ for (const key of Object.keys(entry)) {
177
+ if (PERSISTED_DERIVED_SET.has(key)) continue
178
+ const value = entry[key]
179
+ if (value === undefined) continue
180
+ // JSON.parse 可以把 `__proto__` 变成自有属性,而 `out[key] = value` 会走去改原型 —— 显式定义。
181
+ if (key === '__proto__') Object.defineProperty(out, key, { value, enumerable: true, writable: true, configurable: true })
182
+ else out[key] = value
183
+ }
184
+ return out
185
+ }
186
+
187
+ /**
188
+ * 剥掉派生字段(加载路径用)。没有派生字段时**原对象返回**(零分配热路径)。
189
+ * @returns {object} 不含派生字段的条目(可能是同一个对象)
190
+ */
157
191
  function stripPersistedDerived(entry) {
158
192
  if (!entry || typeof entry !== 'object') return entry
159
- for (const key of PERSISTED_DERIVED) if (key in entry) delete entry[key]
160
- return entry
193
+ if (!hasPersistedDerived(entry)) return entry
194
+ return rebuildWithoutDerived(entry)
161
195
  }
162
196
 
163
- /** 返回不含派生字段的副本(写盘路径用,不能动内存里的对象)。 */
197
+ /**
198
+ * 返回不含派生字段的条目(写盘路径用,不能动内存里的对象)。
199
+ * 同样重建而不是 spread+delete —— 两个路径的字典模式代价是一样的。
200
+ */
164
201
  function withoutPersistedDerived(entry) {
165
- const out = { ...entry }
166
- for (const key of PERSISTED_DERIVED) delete out[key]
167
- return out
202
+ if (!entry || typeof entry !== 'object') return entry
203
+ if (!hasPersistedDerived(entry)) return entry
204
+ return rebuildWithoutDerived(entry)
205
+ }
206
+
207
+ /** 仅供测试:加载/写盘路径的剥离实现(内存形状由测试用 --expose-gc 度量)。 */
208
+ export function _stripPersistedDerivedForTest(entry) {
209
+ return stripPersistedDerived(entry)
168
210
  }
169
211
 
170
212
  function loadJson(filePath, fallback) {
@@ -188,21 +230,6 @@ function loadJson(filePath, fallback) {
188
230
  }
189
231
  }
190
232
 
191
- function writeJsonAtomic(filePath, data) {
192
- const tmp = `${filePath}.${process.pid}.tmp`
193
- try {
194
- writeFileSync(tmp, JSON.stringify(data))
195
- renameSync(tmp, filePath)
196
- } catch (err) {
197
- try {
198
- unlinkSync(tmp)
199
- } catch {
200
- // tmp already gone (rename succeeded) or undeletable; nothing to do
201
- }
202
- throw err
203
- }
204
- }
205
-
206
233
  function shardRelPath(dir, rel) {
207
234
  return path.join(dir, SHARDS_DIR, createHash('sha256').update(rel).digest('hex') + '.json')
208
235
  }
@@ -315,8 +342,8 @@ export class ProjectMemoryStore {
315
342
  `[dsh-project-memory] migration dropped ${orphans.length} entry group(s) with no index record: ${orphans.slice(0, 3).join(', ')}${orphans.length > 3 ? ' …' : ''}`,
316
343
  )
317
344
  }
318
- mkdirSync(path.join(this.dir, SHARDS_DIR), { recursive: true })
319
345
  for (const rel of Object.keys(files)) {
346
+ // 父目录由 writeJsonAtomic 保证
320
347
  writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: files[rel], entries: (entries[rel] || []).map(withoutPersistedDerived) })
321
348
  }
322
349
  writeJsonAtomic(formatPath, { version: 2, layout: 'sharded' })
@@ -524,7 +551,7 @@ export class ProjectMemoryStore {
524
551
  }
525
552
  for (const rel of this._dirtyShards) {
526
553
  if (this.files[rel]) {
527
- mkdirSync(path.join(this.dir, SHARDS_DIR), { recursive: true })
554
+ // 父目录由 writeJsonAtomic 保证
528
555
  writeJsonAtomic(shardRelPath(this.dir, rel), { relPath: rel, record: this.files[rel], entries: (this.entries[rel] || []).map(withoutPersistedDerived) })
529
556
  } else {
530
557
  this._removedShards.add(rel)
@@ -580,11 +607,11 @@ export class ProjectMemoryStore {
580
607
  if (N === 0) return {}
581
608
  const df = {}
582
609
  for (const entry of entries) {
583
- const text = entry.title || ''
584
- const keywords = (entry.keywords || []).join(' ')
585
- const summary = entry.summary || ''
586
- const combined = `${text} ${text} ${text} ${text} ${text} ${keywords} ${summary}`.toLowerCase()
587
- const terms = tokenizeRaw(combined)
610
+ // 语料必须与**检索**同源:检索走 search.js 的 weightedFieldText = title×5 + keywords
611
+ // + summary + **terms** + sourcePath。此前这里手抄了一份少了 `terms`/`sourcePath` 的
612
+ // 副本,于是只出现在 `terms` 里的词 df=0 → 被当成极稀有词拿虚高 IDF(而 `terms` 正是
613
+ // 0.5.x 为修"只有前 300 字符可检索"加的主检索面)。直接调 makeSearchText,权重自动对齐。
614
+ const terms = tokenizeRaw(makeSearchText(entry))
588
615
  const seen = new Set(terms)
589
616
  for (const t of seen) {
590
617
  df[t] = (df[t] || 0) + 1
package/src/symbols.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFileSync } from 'node:fs'
2
2
  import { oneLineDeclaration } from './util/text.js'
3
+ import { entryIdPrefix } from './util/entry-id.js'
3
4
 
4
5
  const JS_LIKE = new Set(['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts', '.jsx', '.tsx'])
5
6
  const PYTHON = new Set(['.py'])
@@ -460,7 +461,7 @@ function buildSymbol(matched, relPath, rawLine, lineNo) {
460
461
  const identity = `${prefix}${typeSig}${overloadPart} — ${relPath}:${lineNo}`
461
462
 
462
463
  return {
463
- id: `${String(relPath).replace(/[\\/:\s]/g, '_')}#${lineNo}`,
464
+ id: `${entryIdPrefix(relPath)}#${lineNo}`,
464
465
  sourcePath: relPath,
465
466
  sourceLine: lineNo,
466
467
  type: 'symbol',
@@ -11,11 +11,11 @@ export function forgetTool(config) {
11
11
  id_or_query: {
12
12
  type: 'string',
13
13
  required: true,
14
- description: 'Experience note id (from remember/search output), or keywords to match.',
14
+ description: 'Experience note id (from remember or query_memory output), or keywords to match.',
15
15
  },
16
16
  root: {
17
17
  type: 'string',
18
- description: 'Project root of the memory store. Defaults to the current working directory.',
18
+ description: '项目根目录,默认当前工作目录。',
19
19
  },
20
20
  },
21
21
  output: {
@@ -20,7 +20,7 @@ export function indexDocTool(ctx, config) {
20
20
  },
21
21
  root: {
22
22
  type: 'string',
23
- description: 'Project root where the .dsh-project-memory store lives. Defaults to the session\'s project root.',
23
+ description: '项目根目录(store 存放处),默认会话的项目根。',
24
24
  },
25
25
  },
26
26
  output: {