@yolk_vat-y/dsh-project-memory 0.5.15 → 0.6.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/CHANGELOG.md +206 -0
- package/README.md +39 -41
- package/README.zh-CN.md +39 -41
- package/client/client.js +201 -39
- package/client/client.js.map +1 -1
- package/cordis.patch.yml +1 -1
- package/package.json +5 -2
- package/scripts/bench-synthetic.mjs +7 -4
- package/scripts/bench.mjs +11 -4
- package/scripts/file-peak.mjs +2 -1
- package/scripts/tool-schema-size.mjs +2 -2
- package/src/audit.js +10 -1
- package/src/auto-inject.js +105 -8
- package/src/chunker.js +55 -22
- package/src/client/MemoryView.tsx +4 -2
- package/src/client/TaskPanel.tsx +17 -6
- package/src/client/client.ts +67 -10
- package/src/client/locales.ts +4 -0
- package/src/client/services.ts +118 -0
- package/src/client/slash.ts +3 -2
- package/src/commands/insight-actions.js +5 -4
- package/src/doc-pipeline.js +0 -1
- package/src/index.js +28 -5
- package/src/parsers/pdfjs-parser.js +0 -0
- package/src/readiness.js +6 -3
- package/src/recall.js +112 -7
- package/src/store.js +102 -12
- package/src/tools/lesson-tools.js +9 -3
- package/src/tools/query-memory.js +13 -9
- package/src/util/fs.js +46 -3
- package/src/util/search.js +17 -8
- package/src/vector-index.js +268 -0
- package/src/watch.js +42 -3
package/src/store.js
CHANGED
|
@@ -49,6 +49,54 @@ const RESIDENT_KEY_BYTES = 40
|
|
|
49
49
|
const RESIDENT_STR_BYTES = 16
|
|
50
50
|
const RESIDENT_MAX_DEPTH = 8
|
|
51
51
|
|
|
52
|
+
/** 精确计量的版本戳:entries 的构成 + `searchText` 的物化状态各算一维。 */
|
|
53
|
+
function residentStampOf(store) {
|
|
54
|
+
return `${store._entriesVersion}:${store._materializeVersion}`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 精确计量的**触发上界**(不是估算本身):内存里文本字符数 × 4 + 骨架常数。
|
|
59
|
+
*
|
|
60
|
+
* 为什么必须有它:精确计量要遍历全库字符串(`Buffer.byteLength` 逐串编码),12.6k 文件 /
|
|
61
|
+
* 80k 条目实测 ~40ms。放在每次冷加载的热路径上,就是白花这笔钱去判断"要不要逐出"——
|
|
62
|
+
* 而绝大多数加载离 256MB 预算差得远,逐出根本不可能发生。
|
|
63
|
+
*
|
|
64
|
+
* 系数取偏保守:宁可多走一次精确计量,也不能把预算算松。ASCII 下 1 字符 ≈ 1 字节驻留
|
|
65
|
+
* 外加键与对象形状开销(符号条目实测 ~4×);CJK 字符驻留 2 字节,而 UTF-8 文本里 3 字节,
|
|
66
|
+
* 字符数只会更少。精确数一旦算过且版本未变,直接用它,不必再估。
|
|
67
|
+
*
|
|
68
|
+
* `_textChars` 由三条路径维护(读盘分片 / 写条目 / 非分片 JSON),按文件**替换式**累计,
|
|
69
|
+
* 所以重写同一个文件不会把它算两遍。在真实语料上标定的上界 / 精确值比是 1.16~1.74 倍。
|
|
70
|
+
*/
|
|
71
|
+
const RESIDENT_BOUND_PER_CHAR = 4
|
|
72
|
+
const RESIDENT_SKELETON_BYTES = 1024
|
|
73
|
+
|
|
74
|
+
function residentBoundBytes(store) {
|
|
75
|
+
const stamp = residentStampOf(store)
|
|
76
|
+
if (store._residentStamp === stamp) return store._residentBytes
|
|
77
|
+
return RESIDENT_SKELETON_BYTES + store._textChars * RESIDENT_BOUND_PER_CHAR
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 写路径的文本量估计(只用于上界):`searchText` + 不在它里面的字段 + 每条的键/JSON 开销。
|
|
82
|
+
* 不重复计 title / keywords / summary / terms / sourcePath —— 它们都已经在 `searchText` 里。
|
|
83
|
+
*/
|
|
84
|
+
function entryTextChars(entries) {
|
|
85
|
+
let sum = 0
|
|
86
|
+
for (const entry of entries) {
|
|
87
|
+
sum += 160
|
|
88
|
+
sum += (entry.searchText || '').length
|
|
89
|
+
sum += (entry.text || '').length
|
|
90
|
+
sum += (entry.id || '').length + (entry.relPath || '').length
|
|
91
|
+
}
|
|
92
|
+
return sum
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** 仅供测试与标定:上界口径(必须 ≥ `_estimateResidentBytes`,否则字节预算会被算松)。 */
|
|
96
|
+
export function _residentBoundBytesForTest(store) {
|
|
97
|
+
return residentBoundBytes(store)
|
|
98
|
+
}
|
|
99
|
+
|
|
52
100
|
function residentBytesOf(value, depth = 0) {
|
|
53
101
|
if (depth > RESIDENT_MAX_DEPTH) return 0
|
|
54
102
|
const type = typeof value
|
|
@@ -76,7 +124,7 @@ function residentBytesOf(value, depth = 0) {
|
|
|
76
124
|
* `allEntries()` 才物化,同一份数据在物化前后估出两个数(实测 76MB → 107MB)。
|
|
77
125
|
* 2. 账不对物——旧分片里还带着 `searchText` / `linkedSymbols`,`load()` 会
|
|
78
126
|
* `stripPersistedDerived` 把它们删掉,可文本量已经把被删的字节算进去了。
|
|
79
|
-
*
|
|
127
|
+
* 实测一个 12.6k 文件的父目录 store:读盘 212.6MB,真实驻留 101.7MB。
|
|
80
128
|
*
|
|
81
129
|
* 两个版本键都参与失效:`_entriesVersion`(`setEntries` / `removeFile` / `_loadSharded`)
|
|
82
130
|
* 与 `_materializeVersion`(`allEntries()` 物化 `searchText`)。漏掉后者就是旧实现的错。
|
|
@@ -85,7 +133,7 @@ function residentBytesOf(value, depth = 0) {
|
|
|
85
133
|
* 是对**整个缓存**逐 store 求和的,不记忆化等于每次冷加载都把缓存里所有 store 重数一遍。
|
|
86
134
|
*/
|
|
87
135
|
export function _estimateResidentBytes(store) {
|
|
88
|
-
const stamp =
|
|
136
|
+
const stamp = residentStampOf(store)
|
|
89
137
|
if (store._residentStamp !== stamp) {
|
|
90
138
|
store._residentBytes =
|
|
91
139
|
residentBytesOf(store.entries) +
|
|
@@ -102,14 +150,25 @@ export function _estimateResidentBytes(store) {
|
|
|
102
150
|
|
|
103
151
|
/** 按 LRU 逐出,直到同时满足条数与字节预算;刚加入的 keepKey 即使超预算也保留。 */
|
|
104
152
|
function evictStoreCache(keepKey) {
|
|
153
|
+
// 只在**真有可能逐出**时才付精确计量的钱:条数超上限,或保守上界就已超字节预算。
|
|
154
|
+
// 宽裕时(单项目常态)一次对象图遍历都不做——冷加载因此不背那次全库扫描。
|
|
155
|
+
let exact = storeCache.size > STORE_CACHE_MAX
|
|
156
|
+
if (!exact) {
|
|
157
|
+
let bound = 0
|
|
158
|
+
for (const store of storeCache.values()) bound += residentBoundBytes(store)
|
|
159
|
+
exact = bound > STORE_CACHE_MAX_BYTES
|
|
160
|
+
}
|
|
105
161
|
let total = 0
|
|
106
|
-
for (const store of storeCache.values()) total += _estimateResidentBytes(store)
|
|
107
|
-
while (storeCache.size > STORE_CACHE_MAX || total > STORE_CACHE_MAX_BYTES) {
|
|
162
|
+
if (exact) for (const store of storeCache.values()) total += _estimateResidentBytes(store)
|
|
163
|
+
while (storeCache.size > STORE_CACHE_MAX || (exact && total > STORE_CACHE_MAX_BYTES)) {
|
|
108
164
|
const oldest = storeCache.keys().next().value
|
|
109
165
|
if (oldest === undefined || oldest === keepKey) break
|
|
110
|
-
total -= _estimateResidentBytes(storeCache.get(oldest))
|
|
166
|
+
if (exact) total -= _estimateResidentBytes(storeCache.get(oldest))
|
|
111
167
|
storeCache.delete(oldest)
|
|
112
168
|
}
|
|
169
|
+
// 没做过精确计量就不报"单实例超预算":算都没算,报出来的数是估的。真超预算时
|
|
170
|
+
// (多一个 store 就会触发上界)下一次加载会走到这里并如实告警。
|
|
171
|
+
if (!exact) return
|
|
113
172
|
// keepKey 豁免是**有意**的:刚加载的 store 必须立刻可用。但它的代价是"单实例超预算时
|
|
114
173
|
// 预算不再是上界"——这个代价不能是隐式的,所以每个这样的 store 告警一次(每 root 一次)。
|
|
115
174
|
const kept = _estimateResidentBytes(storeCache.get(keepKey))
|
|
@@ -209,13 +268,16 @@ export function _stripPersistedDerivedForTest(entry) {
|
|
|
209
268
|
return stripPersistedDerived(entry)
|
|
210
269
|
}
|
|
211
270
|
|
|
212
|
-
function loadJson(filePath, fallback) {
|
|
271
|
+
function loadJson(filePath, fallback, counter) {
|
|
213
272
|
let raw
|
|
214
273
|
try {
|
|
215
274
|
raw = readFileSync(filePath, 'utf8')
|
|
216
275
|
} catch {
|
|
217
276
|
return fallback
|
|
218
277
|
}
|
|
278
|
+
// 可选:累计读盘文本的字符数。只用于 `residentBoundBytes`(要不要做精确计量的上界),
|
|
279
|
+
// 不参与精确估算本身——后者数的是内存里的对象图。
|
|
280
|
+
if (counter) counter.chars += raw.length
|
|
219
281
|
try {
|
|
220
282
|
return JSON.parse(raw)
|
|
221
283
|
} catch {
|
|
@@ -260,6 +322,13 @@ export class ProjectMemoryStore {
|
|
|
260
322
|
/** 驻留字节估算的记忆化结果与版本戳(见 `_estimateResidentBytes`)。 */
|
|
261
323
|
this._residentBytes = 0
|
|
262
324
|
this._residentStamp = ''
|
|
325
|
+
/**
|
|
326
|
+
* 内存里文本字符数的累计(读盘分片 + 写条目 + 非分片 JSON)。**只**用于
|
|
327
|
+
* `residentBoundBytes` 判断"要不要做精确计量";精确估算数的是对象图,不碰这个数。
|
|
328
|
+
*/
|
|
329
|
+
this._textChars = 0
|
|
330
|
+
/** 每个文件当前的文本字符数,写入时按文件替换,避免重写同一文件被算两遍。 */
|
|
331
|
+
this._fileTextChars = new Map()
|
|
263
332
|
/**
|
|
264
333
|
* `searchText` 的物化计数。它和 `_entriesVersion` 一起构成驻留估算的失效键:
|
|
265
334
|
* 物化只改 entry 对象本身,不改 entries 的构成,所以不会 bump `_entriesVersion`。
|
|
@@ -357,6 +426,22 @@ export class ProjectMemoryStore {
|
|
|
357
426
|
console.error(`[dsh-project-memory] migrated legacy store at ${this.dir} to sharded layout (${Object.keys(files).length} files)`)
|
|
358
427
|
}
|
|
359
428
|
|
|
429
|
+
/** 读一个 JSON 文件,并把读入文本的字符数记到 `_textChars`(供驻留上界用)。 */
|
|
430
|
+
_loadJson(filePath, fallback) {
|
|
431
|
+
const counter = { chars: 0 }
|
|
432
|
+
const data = loadJson(filePath, fallback, counter)
|
|
433
|
+
this._textChars += counter.chars
|
|
434
|
+
return data
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** 按文件记文本量:替换而不是累加,重写同一个文件不会算两遍。 */
|
|
438
|
+
_setFileTextChars(relPath, chars) {
|
|
439
|
+
const prev = this._fileTextChars.get(relPath) || 0
|
|
440
|
+
if (chars > 0) this._fileTextChars.set(relPath, chars)
|
|
441
|
+
else this._fileTextChars.delete(relPath)
|
|
442
|
+
this._textChars += chars - prev
|
|
443
|
+
}
|
|
444
|
+
|
|
360
445
|
_loadSharded() {
|
|
361
446
|
let shardNames = []
|
|
362
447
|
try {
|
|
@@ -365,8 +450,10 @@ export class ProjectMemoryStore {
|
|
|
365
450
|
shardNames = []
|
|
366
451
|
}
|
|
367
452
|
for (const name of shardNames) {
|
|
368
|
-
const
|
|
453
|
+
const counter = { chars: 0 }
|
|
454
|
+
const shard = loadJson(path.join(this.dir, SHARDS_DIR, name), null, counter)
|
|
369
455
|
if (!shard || typeof shard.relPath !== 'string' || !isRecord(shard.record)) continue
|
|
456
|
+
this._setFileTextChars(shard.relPath, counter.chars)
|
|
370
457
|
this.files[shard.relPath] = shard.record
|
|
371
458
|
// 畸形 shard(entries 被写成对象/null)不能让 allEntries() 在 `for…of` 上抛错,
|
|
372
459
|
// 否则一个坏文件会拖垮整个进程的每一次读取。
|
|
@@ -376,10 +463,10 @@ export class ProjectMemoryStore {
|
|
|
376
463
|
this.entries[shard.relPath] = list.map(stripPersistedDerived)
|
|
377
464
|
}
|
|
378
465
|
this._entriesVersion++
|
|
379
|
-
this.experience =
|
|
380
|
-
this.tasks =
|
|
381
|
-
this.binding =
|
|
382
|
-
this.watchlist =
|
|
466
|
+
this.experience = this._loadJson(path.join(this.dir, EXPERIENCE_FILE), [])
|
|
467
|
+
this.tasks = this._loadJson(path.join(this.dir, TASKS_FILE), [])
|
|
468
|
+
this.binding = this._loadJson(path.join(this.dir, BINDING_FILE), {})
|
|
469
|
+
this.watchlist = this._loadJson(path.join(this.dir, WATCH_FILE), [])
|
|
383
470
|
this._formatWritten = existsSafe(path.join(this.dir, FORMAT_FILE))
|
|
384
471
|
}
|
|
385
472
|
|
|
@@ -407,7 +494,7 @@ export class ProjectMemoryStore {
|
|
|
407
494
|
// 首次加载把旧笔记**复制导入** insights.json(kind: experience, source: migrate),
|
|
408
495
|
// migratedAt 落盘保证跨进程/崩溃幂等。销毁式收敛放到 recall 统一 PR。
|
|
409
496
|
_loadInsights() {
|
|
410
|
-
const doc =
|
|
497
|
+
const doc = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
|
|
411
498
|
this.insights = isRecord(doc) && Array.isArray(doc.items)
|
|
412
499
|
// items 里混进 null/非对象(手改或旧版写入)会让迁移与召回逐个 `.title` 抛错——过滤掉。
|
|
413
500
|
? { ...doc, items: doc.items.filter(isRecord) }
|
|
@@ -659,8 +746,10 @@ export class ProjectMemoryStore {
|
|
|
659
746
|
return out
|
|
660
747
|
})
|
|
661
748
|
this.entries[relPath] = enriched
|
|
749
|
+
this._setFileTextChars(relPath, entryTextChars(enriched))
|
|
662
750
|
} else {
|
|
663
751
|
delete this.entries[relPath]
|
|
752
|
+
this._setFileTextChars(relPath, 0)
|
|
664
753
|
}
|
|
665
754
|
this._entriesVersion++
|
|
666
755
|
this._dirtyShards.add(relPath)
|
|
@@ -671,6 +760,7 @@ export class ProjectMemoryStore {
|
|
|
671
760
|
if (relPath in this.files) {
|
|
672
761
|
delete this.files[relPath]
|
|
673
762
|
delete this.entries[relPath]
|
|
763
|
+
this._setFileTextChars(relPath, 0)
|
|
674
764
|
this._entriesVersion++
|
|
675
765
|
this._dirtyShards.add(relPath)
|
|
676
766
|
this._removedShards.add(relPath)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { defineTool } from '@deepseek-ai/dsh-tools'
|
|
2
|
-
import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
|
|
2
|
+
import { assertIndexRoot, memoryRootFor, normalizeCitationFiles, resolveSafeIndexRoot } from '../util/fs.js'
|
|
3
3
|
import { ProjectMemoryStore } from '../store.js'
|
|
4
4
|
import { truncate } from '../util/text.js'
|
|
5
5
|
import { cfgInsight, saveInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
|
|
@@ -79,6 +79,8 @@ export function lessonTool(config) {
|
|
|
79
79
|
async execute(args, exec) {
|
|
80
80
|
const root = resolveSafeIndexRoot(exec, args.root, config)
|
|
81
81
|
assertIndexRoot(root, args.root || root)
|
|
82
|
+
// 写入期约束:files 只收项目内相对路径(schema 早就这么承诺,此前没有校验)。
|
|
83
|
+
const citationFiles = normalizeCitationFiles(args.files, root)
|
|
82
84
|
const memoryDir = memoryRootFor(root, config.memoryDir)
|
|
83
85
|
const store = new ProjectMemoryStore(memoryDir).load()
|
|
84
86
|
const cfg = cfgInsight(config)
|
|
@@ -95,7 +97,7 @@ export function lessonTool(config) {
|
|
|
95
97
|
reason: args.reason,
|
|
96
98
|
steps: args.steps,
|
|
97
99
|
trigger: args.trigger,
|
|
98
|
-
files:
|
|
100
|
+
files: citationFiles.files,
|
|
99
101
|
symbols: args.symbols,
|
|
100
102
|
confidence: args.confidence,
|
|
101
103
|
}
|
|
@@ -124,7 +126,11 @@ export function lessonTool(config) {
|
|
|
124
126
|
const body = result.ok
|
|
125
127
|
? `Saved insight ${result.id} [scope=${result.scope || scope}] action=${result.action}${result.hint ? ` — ${result.hint}` : ''}`
|
|
126
128
|
: `Failed: ${result.error}`
|
|
127
|
-
|
|
129
|
+
// 丢弃必须说出来:静默少几行引用,事后只能靠审计发现"查不到"。
|
|
130
|
+
const note = citationFiles.dropped.length
|
|
131
|
+
? `\n(${citationFiles.dropped.length} 个 files 既不是项目内相对路径也不是项目内绝对路径,已丢弃:${citationFiles.dropped.slice(0, 3).join(', ')}${citationFiles.dropped.length > 3 ? ' …' : ''})`
|
|
132
|
+
: ''
|
|
133
|
+
return truncate(body + note, config.maxOutputChars || 8000)
|
|
128
134
|
},
|
|
129
135
|
})
|
|
130
136
|
}
|
|
@@ -6,6 +6,8 @@ import { expandQuery } from '../llm.js'
|
|
|
6
6
|
import { resolveRoute } from '../llm-route.js'
|
|
7
7
|
import { GlobalStore, cfgInsight, defaultGlobalFile, recordHit } from '../insight-store.js'
|
|
8
8
|
import { recallItems } from '../recall.js'
|
|
9
|
+
import { cfgEngine } from '../auto-inject.js'
|
|
10
|
+
import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
|
|
9
11
|
import { resolveLinkedSymbols } from '../link.js'
|
|
10
12
|
import { truncate } from '../util/text.js'
|
|
11
13
|
import { stepContent, stepStatus } from '../util/task-view.js'
|
|
@@ -85,6 +87,15 @@ export function queryMemoryTool(ctx, config) {
|
|
|
85
87
|
/** 本根记忆层(doc/symbol)的命中数:0 且存在子索引时,末尾要指路。 */
|
|
86
88
|
let memHitCount = 0
|
|
87
89
|
const wantInsight = type === 'all' || type === 'insight'
|
|
90
|
+
// 可选向量层:**没装/没配就是 null**,此时 recallItems 拿到 rerank:null 与纯词法路径逐字段一致。
|
|
91
|
+
// 只影响 experience/insight 两层的排序(doc/symbol 与返回条数都不变)。
|
|
92
|
+
const cfg = cfgEngine(config)
|
|
93
|
+
const rerank = await createVectorRerank({
|
|
94
|
+
storeDir: memoryRootFor(root, config.memoryDir),
|
|
95
|
+
items: vectorItemsFrom(store, globalStore),
|
|
96
|
+
vectorDir: cfg.vectorDir,
|
|
97
|
+
alpha: cfg.vectorAlpha,
|
|
98
|
+
})
|
|
88
99
|
// 一次 recall 覆盖全部层:doc/symbol/experience/insight 共用同一个检索核心(src/recall.js)。
|
|
89
100
|
const recalled = recallItems({
|
|
90
101
|
store,
|
|
@@ -92,6 +103,7 @@ export function queryMemoryTool(ctx, config) {
|
|
|
92
103
|
queries,
|
|
93
104
|
boundTaskId,
|
|
94
105
|
limit,
|
|
106
|
+
rerank,
|
|
95
107
|
layers: [
|
|
96
108
|
...(wantMemory ? (type === 'symbol' ? ['symbol'] : type === 'doc' ? ['doc'] : ['doc', 'symbol']) : []),
|
|
97
109
|
...(wantInsight ? ['insight'] : []),
|
|
@@ -125,15 +137,7 @@ export function queryMemoryTool(ctx, config) {
|
|
|
125
137
|
for (const { item: e, weightedScore } of memHits) {
|
|
126
138
|
const absSource = e.sourceLine ? `${toAbs(root, e.sourcePath)}:${e.sourceLine}` : toAbs(root, e.sourcePath)
|
|
127
139
|
const rel = Math.round((weightedScore / top) * 100)
|
|
128
|
-
|
|
129
|
-
if (e.type === 'doc' && e.blindSpots) {
|
|
130
|
-
const queryTokens = queries.flatMap(q => q.split(/[\s\-_]+/)).map(t => t.toLowerCase()).filter(Boolean)
|
|
131
|
-
const blindTokens = e.blindSpots.split(/[\s\-\u3000、,,、;;.。]+/).map(t => t.toLowerCase()).filter(Boolean)
|
|
132
|
-
const hit = queryTokens.some(qt => blindTokens.some(bt => bt.includes(qt) || qt.includes(bt)))
|
|
133
|
-
if (hit) {
|
|
134
|
-
summaryLine += `\n- ⚠️ 摘要未覆盖:${e.blindSpots.replace(/^\s*\/\/\s*未覆盖[::]\s*/, '')}。建议读原文 ${absSource}`
|
|
135
|
-
}
|
|
136
|
-
}
|
|
140
|
+
const summaryLine = `- ${e.summary}`
|
|
137
141
|
// 条目状态占位(可证伪状态机落地前恒为 exact)。
|
|
138
142
|
// 先立字段,后续状态机到位时只改值、不改输出契约。
|
|
139
143
|
lines.push(`### ${e.title} (score: ${rel})\n- source: ${absSource}\n- status: ${e.status || 'exact'}\n${summaryLine}`)
|
package/src/util/fs.js
CHANGED
|
@@ -142,8 +142,7 @@ export const DEFAULT_SCAN_FILES = 20000
|
|
|
142
142
|
export const DEFAULT_SCAN_DEPTH = 12
|
|
143
143
|
|
|
144
144
|
/**
|
|
145
|
-
* 从 config
|
|
146
|
-
* 把保护整个关掉。显式传 `maxScanFiles: 0` 才会真的关掉(见 README)。
|
|
145
|
+
* 从 config 解析扫描上限。0 / 负数 / 非数值一律回落到出厂值:上限只能放宽,不能取消。见 README 配置表。
|
|
147
146
|
*/
|
|
148
147
|
export function scanLimits(config) {
|
|
149
148
|
const files = Number(config?.maxScanFiles)
|
|
@@ -220,7 +219,7 @@ export function walkDir(root, opts = {}) {
|
|
|
220
219
|
const maxDepth = Number.isFinite(opts.maxDepth) && opts.maxDepth > 0 ? opts.maxDepth : Infinity
|
|
221
220
|
// 传 memoryDir 名即开启「嵌套根不重复索引」:子目录自带 store 时不再往下走。
|
|
222
221
|
// 理由是跟解析规则保持一致——`findProjectRoot()` 对子树里的文件返回的正是那个子根,
|
|
223
|
-
//
|
|
222
|
+
// 扫描也该同意这一点;否则父根会把子项目的全部内容再存一份(实测一个父目录
|
|
224
223
|
// 的 store 里 9075/9081 个文件是子根 store 的重复副本)。
|
|
225
224
|
const nestedStoreName = opts.nestedStoreName || null
|
|
226
225
|
const out = []
|
|
@@ -300,6 +299,50 @@ export function relativePath(root, filePath) {
|
|
|
300
299
|
return path.relative(root, filePath).split(path.sep).join('/')
|
|
301
300
|
}
|
|
302
301
|
|
|
302
|
+
/**
|
|
303
|
+
* `insight.files` 的写入期归一 —— 工具 schema 承诺的是「项目相对路径」,但此前**没有任何校验**:
|
|
304
|
+
* 项目外的绝对路径会原样落盘,事后只能靠审计发现"查不到"(实测 144 处引用里 3 处项目外、
|
|
305
|
+
* 6 处真悬空)。这里把承诺兑现成入口约束,而不是每次统计:
|
|
306
|
+
* - 非空字符串;反斜杠 → `/`;去掉 `./` 前缀;重复值合并;
|
|
307
|
+
* - **项目内**绝对路径 → 项目相对路径(`path.resolve` 判定,跨 OS 形态同样适用);
|
|
308
|
+
* - 其余(项目外绝对、`..` 逃出根、没有根时无法判定的绝对路径)**丢弃**并回报 ——
|
|
309
|
+
* 调用方负责把丢弃数量说出来,而不是静默少几行。
|
|
310
|
+
* @param {unknown} files - 原始 files(工具参数 / 编辑表单)。
|
|
311
|
+
* @param {string} root - 目标项目根(`save_lesson` 的 root 参数即权威)。
|
|
312
|
+
* @returns {{files: string[], dropped: string[]}} 归一后的相对路径,以及被丢弃的原值。
|
|
313
|
+
*/
|
|
314
|
+
export function normalizeCitationFiles(files, root) {
|
|
315
|
+
const kept = []
|
|
316
|
+
const dropped = []
|
|
317
|
+
const base = typeof root === 'string' && root.trim() ? path.resolve(root) : null
|
|
318
|
+
for (const raw of Array.isArray(files) ? files : []) {
|
|
319
|
+
if (typeof raw !== 'string') continue
|
|
320
|
+
const value = raw.trim().replace(/\\/g, '/')
|
|
321
|
+
if (!value) continue
|
|
322
|
+
const looksAbsolute = value.startsWith('/') || /^[A-Za-z]:\//.test(value)
|
|
323
|
+
if (base === null && looksAbsolute) {
|
|
324
|
+
dropped.push(raw)
|
|
325
|
+
continue
|
|
326
|
+
}
|
|
327
|
+
const abs = base === null ? null : path.resolve(base, looksAbsolute ? value : value.replace(/^\.\//, ''))
|
|
328
|
+
let rel = value.replace(/^\.\//, '')
|
|
329
|
+
if (abs !== null) {
|
|
330
|
+
const inside = path.relative(base, abs)
|
|
331
|
+
if (inside === '' || inside.startsWith('..') || path.isAbsolute(inside)) {
|
|
332
|
+
dropped.push(raw)
|
|
333
|
+
continue
|
|
334
|
+
}
|
|
335
|
+
rel = inside.split(path.sep).join('/')
|
|
336
|
+
}
|
|
337
|
+
if (!rel || rel.startsWith('..')) {
|
|
338
|
+
dropped.push(raw)
|
|
339
|
+
continue
|
|
340
|
+
}
|
|
341
|
+
if (!kept.includes(rel)) kept.push(rel)
|
|
342
|
+
}
|
|
343
|
+
return { files: kept, dropped }
|
|
344
|
+
}
|
|
345
|
+
|
|
303
346
|
export const CASE_INSENSITIVE_FS = process.platform === 'win32' || process.platform === 'darwin'
|
|
304
347
|
|
|
305
348
|
export function storeKey(rel, platform = process.platform) {
|
package/src/util/search.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
157
|
-
|
|
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
|
-
|
|
183
|
-
|
|
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
|
}
|