@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.
- package/CHANGELOG.md +222 -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/commands/task-actions.js +5 -0
- 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/setup/taskbridge.js +4 -3
- package/src/store.js +196 -20
- package/src/tools/lesson-tools.js +9 -3
- package/src/tools/query-memory.js +13 -9
- package/src/tools/task-tools.js +3 -0
- 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,25 +49,119 @@ const RESIDENT_KEY_BYTES = 40
|
|
|
49
49
|
const RESIDENT_STR_BYTES = 16
|
|
50
50
|
const RESIDENT_MAX_DEPTH = 8
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
/**
|
|
53
|
+
* 精确计量的版本戳:entries 的构成 + `searchText` 的物化状态 + 辅助集合的内容各算一维。
|
|
54
|
+
* 三维缺一不可——漏掉哪一维,估算就停在那一维变更前的水位。
|
|
55
|
+
*/
|
|
56
|
+
function residentStampOf(store) {
|
|
57
|
+
return `${store._entriesVersion}:${store._materializeVersion}:${store._auxVersion}`
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 精确计量的**触发上界**(不是估算本身):内存里文本字符数 × 4 + 骨架常数。
|
|
62
|
+
*
|
|
63
|
+
* 为什么必须有它:精确计量要遍历全库字符串(`Buffer.byteLength` 逐串编码),12.6k 文件 /
|
|
64
|
+
* 80k 条目实测 ~40ms。放在每次冷加载的热路径上,就是白花这笔钱去判断"要不要逐出"——
|
|
65
|
+
* 而绝大多数加载离 256MB 预算差得远,逐出根本不可能发生。
|
|
66
|
+
*
|
|
67
|
+
* 系数取偏保守:宁可多走一次精确计量,也不能把预算算松。ASCII 下 1 字符 ≈ 1 字节驻留
|
|
68
|
+
* 外加键与对象形状开销(符号条目实测 ~4×);CJK 字符驻留 2 字节,而 UTF-8 文本里 3 字节,
|
|
69
|
+
* 字符数只会更少。精确数一旦算过且版本未变,直接用它,不必再估。
|
|
70
|
+
*
|
|
71
|
+
* 两条腿合成一个数:
|
|
72
|
+
* - `_textChars`:entries 的文本量,由三条路径维护(读盘分片 / 写条目 / 物化 `searchText`),
|
|
73
|
+
* 按文件**替换式**累计,所以重写同一个文件不会把它算两遍;
|
|
74
|
+
* - `auxCharsOf()`:辅助集合(experience / insights / tasks / binding / watch)的文本量。
|
|
75
|
+
* 它们不在分片文本里,`load()` 之后还会被写大,单列一条腿才不会漏。
|
|
76
|
+
* 在真实语料上标定的上界 / 精确值比是 1.16~1.74 倍。
|
|
77
|
+
*/
|
|
78
|
+
const RESIDENT_BOUND_PER_CHAR = 4
|
|
79
|
+
const RESIDENT_SKELETON_BYTES = 1024
|
|
80
|
+
|
|
81
|
+
function residentBoundBytes(store) {
|
|
82
|
+
const stamp = residentStampOf(store)
|
|
83
|
+
if (store._residentStamp === stamp) return store._residentBytes
|
|
84
|
+
return RESIDENT_SKELETON_BYTES + (store._textChars + auxCharsOf(store)) * RESIDENT_BOUND_PER_CHAR
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 写路径的文本量估计(只用于上界):`searchText` + 不在它里面的字段 + 每条的键/JSON 开销。
|
|
89
|
+
* 不重复计 title / keywords / summary / terms / sourcePath —— 它们都已经在 `searchText` 里。
|
|
90
|
+
*/
|
|
91
|
+
function entryTextChars(entries) {
|
|
92
|
+
let sum = 0
|
|
93
|
+
for (const entry of entries) {
|
|
94
|
+
sum += 160
|
|
95
|
+
sum += (entry.searchText || '').length
|
|
96
|
+
sum += (entry.text || '').length
|
|
97
|
+
sum += (entry.id || '').length + (entry.relPath || '').length
|
|
98
|
+
}
|
|
99
|
+
return sum
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 仅供测试与标定:上界口径(必须 ≥ `_estimateResidentBytes`,否则字节预算会被算松)。 */
|
|
103
|
+
export function _residentBoundBytesForTest(store) {
|
|
104
|
+
return residentBoundBytes(store)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 驻留量的对象图遍历。精确口径与上界口径**共用这一份**——抄成两份迟早会漂。
|
|
109
|
+
*
|
|
110
|
+
* `charsOnly` 决定字符串怎么记:精确口径走 `Buffer.byteLength`(真字节数);上界口径只取
|
|
111
|
+
* `length` 字符数,省掉编码这一步。它是安全的上界:`RESIDENT_BOUND_PER_CHAR = 4` 保证 ×4 后
|
|
112
|
+
* 仍 ≥ 真字节数(UTF-8 里一个 UTF-16 码元最多 3 字节,代理对 2 码元 / 4 字节)。
|
|
113
|
+
*/
|
|
114
|
+
function residentSizeOf(value, charsOnly, depth = 0) {
|
|
53
115
|
if (depth > RESIDENT_MAX_DEPTH) return 0
|
|
54
116
|
const type = typeof value
|
|
55
|
-
if (type === 'string') return RESIDENT_STR_BYTES + Buffer.byteLength(value)
|
|
117
|
+
if (type === 'string') return RESIDENT_STR_BYTES + (charsOnly ? value.length : Buffer.byteLength(value))
|
|
56
118
|
if (type === 'number' || type === 'bigint') return 16
|
|
57
119
|
if (type === 'boolean' || value === null) return 8
|
|
58
120
|
if (Array.isArray(value)) {
|
|
59
121
|
let sum = RESIDENT_ARR_BYTES
|
|
60
|
-
for (const item of value) sum += 8 +
|
|
122
|
+
for (const item of value) sum += 8 + residentSizeOf(item, charsOnly, depth + 1)
|
|
61
123
|
return sum
|
|
62
124
|
}
|
|
63
125
|
if (type === 'object') {
|
|
64
126
|
let sum = RESIDENT_OBJ_BYTES
|
|
65
|
-
for (const key in value) sum += RESIDENT_KEY_BYTES +
|
|
127
|
+
for (const key in value) sum += RESIDENT_KEY_BYTES + residentSizeOf(value[key], charsOnly, depth + 1)
|
|
66
128
|
return sum
|
|
67
129
|
}
|
|
68
130
|
return 0
|
|
69
131
|
}
|
|
70
132
|
|
|
133
|
+
/** 精确口径:内存里留下的对象图,按真字节数(`_estimateResidentBytes` 用)。 */
|
|
134
|
+
function residentBytesOf(value) {
|
|
135
|
+
return residentSizeOf(value, false, 0)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 上界口径:只数字符(`auxCharsOf` 用)。给辅助集合单开这条路是因为它们条目数小(经验 / 任务
|
|
140
|
+
* 都有上限),逐节点求和的代价可以忽略;entries 有几万条,那条路继续走增量记账的 `_textChars`。
|
|
141
|
+
*/
|
|
142
|
+
function residentCharsOf(value) {
|
|
143
|
+
return residentSizeOf(value, true, 0)
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* 辅助集合的文本量(上界口径),按 `_auxVersion` 记忆化。
|
|
148
|
+
*
|
|
149
|
+
* 为什么单列:`_textChars` 只跟 entries;这几个集合在 `load()` 之后还会被写大,不进上界就会在
|
|
150
|
+
* 缓存其实已超预算时跳过精确计量与逐出(实测单 store 上界 1024 B、实际 19.08 MB)。
|
|
151
|
+
* 记忆化是必须的——`evictStoreCache` 对整个缓存逐 store 求和,不记忆化就是每次冷加载重算一遍。
|
|
152
|
+
*/
|
|
153
|
+
function auxCharsOf(store) {
|
|
154
|
+
if (store._auxStamp === store._auxVersion) return store._auxChars
|
|
155
|
+
store._auxChars =
|
|
156
|
+
residentCharsOf(store.experience) +
|
|
157
|
+
residentCharsOf(store.insights) +
|
|
158
|
+
residentCharsOf(store.tasks) +
|
|
159
|
+
residentCharsOf(store.binding) +
|
|
160
|
+
residentCharsOf(store.watchlist)
|
|
161
|
+
store._auxStamp = store._auxVersion
|
|
162
|
+
return store._auxChars
|
|
163
|
+
}
|
|
164
|
+
|
|
71
165
|
/**
|
|
72
166
|
* 单个 store 的驻留估算:数**内存里留下的对象图**,按版本记忆化。
|
|
73
167
|
*
|
|
@@ -76,7 +170,7 @@ function residentBytesOf(value, depth = 0) {
|
|
|
76
170
|
* `allEntries()` 才物化,同一份数据在物化前后估出两个数(实测 76MB → 107MB)。
|
|
77
171
|
* 2. 账不对物——旧分片里还带着 `searchText` / `linkedSymbols`,`load()` 会
|
|
78
172
|
* `stripPersistedDerived` 把它们删掉,可文本量已经把被删的字节算进去了。
|
|
79
|
-
*
|
|
173
|
+
* 实测一个 12.6k 文件的父目录 store:读盘 212.6MB,真实驻留 101.7MB。
|
|
80
174
|
*
|
|
81
175
|
* 两个版本键都参与失效:`_entriesVersion`(`setEntries` / `removeFile` / `_loadSharded`)
|
|
82
176
|
* 与 `_materializeVersion`(`allEntries()` 物化 `searchText`)。漏掉后者就是旧实现的错。
|
|
@@ -85,7 +179,7 @@ function residentBytesOf(value, depth = 0) {
|
|
|
85
179
|
* 是对**整个缓存**逐 store 求和的,不记忆化等于每次冷加载都把缓存里所有 store 重数一遍。
|
|
86
180
|
*/
|
|
87
181
|
export function _estimateResidentBytes(store) {
|
|
88
|
-
const stamp =
|
|
182
|
+
const stamp = residentStampOf(store)
|
|
89
183
|
if (store._residentStamp !== stamp) {
|
|
90
184
|
store._residentBytes =
|
|
91
185
|
residentBytesOf(store.entries) +
|
|
@@ -102,14 +196,25 @@ export function _estimateResidentBytes(store) {
|
|
|
102
196
|
|
|
103
197
|
/** 按 LRU 逐出,直到同时满足条数与字节预算;刚加入的 keepKey 即使超预算也保留。 */
|
|
104
198
|
function evictStoreCache(keepKey) {
|
|
199
|
+
// 只在**真有可能逐出**时才付精确计量的钱:条数超上限,或保守上界就已超字节预算。
|
|
200
|
+
// 宽裕时(单项目常态)一次对象图遍历都不做——冷加载因此不背那次全库扫描。
|
|
201
|
+
let exact = storeCache.size > STORE_CACHE_MAX
|
|
202
|
+
if (!exact) {
|
|
203
|
+
let bound = 0
|
|
204
|
+
for (const store of storeCache.values()) bound += residentBoundBytes(store)
|
|
205
|
+
exact = bound > STORE_CACHE_MAX_BYTES
|
|
206
|
+
}
|
|
105
207
|
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) {
|
|
208
|
+
if (exact) for (const store of storeCache.values()) total += _estimateResidentBytes(store)
|
|
209
|
+
while (storeCache.size > STORE_CACHE_MAX || (exact && total > STORE_CACHE_MAX_BYTES)) {
|
|
108
210
|
const oldest = storeCache.keys().next().value
|
|
109
211
|
if (oldest === undefined || oldest === keepKey) break
|
|
110
|
-
total -= _estimateResidentBytes(storeCache.get(oldest))
|
|
212
|
+
if (exact) total -= _estimateResidentBytes(storeCache.get(oldest))
|
|
111
213
|
storeCache.delete(oldest)
|
|
112
214
|
}
|
|
215
|
+
// 没做过精确计量就不报"单实例超预算":算都没算,报出来的数是估的。真超预算时
|
|
216
|
+
// (多一个 store 就会触发上界)下一次加载会走到这里并如实告警。
|
|
217
|
+
if (!exact) return
|
|
113
218
|
// keepKey 豁免是**有意**的:刚加载的 store 必须立刻可用。但它的代价是"单实例超预算时
|
|
114
219
|
// 预算不再是上界"——这个代价不能是隐式的,所以每个这样的 store 告警一次(每 root 一次)。
|
|
115
220
|
const kept = _estimateResidentBytes(storeCache.get(keepKey))
|
|
@@ -209,13 +314,16 @@ export function _stripPersistedDerivedForTest(entry) {
|
|
|
209
314
|
return stripPersistedDerived(entry)
|
|
210
315
|
}
|
|
211
316
|
|
|
212
|
-
function loadJson(filePath, fallback) {
|
|
317
|
+
function loadJson(filePath, fallback, counter) {
|
|
213
318
|
let raw
|
|
214
319
|
try {
|
|
215
320
|
raw = readFileSync(filePath, 'utf8')
|
|
216
321
|
} catch {
|
|
217
322
|
return fallback
|
|
218
323
|
}
|
|
324
|
+
// 可选:累计读盘文本的字符数。只用于 `residentBoundBytes`(要不要做精确计量的上界),
|
|
325
|
+
// 不参与精确估算本身——后者数的是内存里的对象图。
|
|
326
|
+
if (counter) counter.chars += raw.length
|
|
219
327
|
try {
|
|
220
328
|
return JSON.parse(raw)
|
|
221
329
|
} catch {
|
|
@@ -260,11 +368,25 @@ export class ProjectMemoryStore {
|
|
|
260
368
|
/** 驻留字节估算的记忆化结果与版本戳(见 `_estimateResidentBytes`)。 */
|
|
261
369
|
this._residentBytes = 0
|
|
262
370
|
this._residentStamp = ''
|
|
371
|
+
/**
|
|
372
|
+
* entries 的文本字符数累计(读盘分片 + 写条目 + 物化 `searchText`),按文件**替换式**记。
|
|
373
|
+
* **只**用于 `residentBoundBytes` 判断"要不要做精确计量";精确估算数的是对象图,不碰它。
|
|
374
|
+
*/
|
|
375
|
+
this._textChars = 0
|
|
376
|
+
/** 每个文件当前的文本字符数,写入时按文件替换,避免重写同一文件被算两遍。 */
|
|
377
|
+
this._fileTextChars = new Map()
|
|
263
378
|
/**
|
|
264
379
|
* `searchText` 的物化计数。它和 `_entriesVersion` 一起构成驻留估算的失效键:
|
|
265
380
|
* 物化只改 entry 对象本身,不改 entries 的构成,所以不会 bump `_entriesVersion`。
|
|
266
381
|
*/
|
|
267
382
|
this._materializeVersion = 0
|
|
383
|
+
/**
|
|
384
|
+
* 辅助集合(experience / insights / tasks / binding / watch)的内容版本:它们不在 entries
|
|
385
|
+
* 的记账面里,靠它让精确估算失效、并让 `auxCharsOf` 重算。每个改到它们的写口都要 bump。
|
|
386
|
+
*/
|
|
387
|
+
this._auxVersion = 0
|
|
388
|
+
this._auxChars = 0
|
|
389
|
+
this._auxStamp = ''
|
|
268
390
|
}
|
|
269
391
|
|
|
270
392
|
load() {
|
|
@@ -357,6 +479,24 @@ export class ProjectMemoryStore {
|
|
|
357
479
|
console.error(`[dsh-project-memory] migrated legacy store at ${this.dir} to sharded layout (${Object.keys(files).length} files)`)
|
|
358
480
|
}
|
|
359
481
|
|
|
482
|
+
/**
|
|
483
|
+
* 读一个辅助集合文件(experience / tasks / insights / binding / watch)。
|
|
484
|
+
*
|
|
485
|
+
* 它们的文本量**不进** `_textChars`:那份账只跟 entries(按文件替换),辅助集合交给
|
|
486
|
+
* `auxCharsOf` 按对象图直接算——同一个集合由两个口径各记一半,迟早会漂。
|
|
487
|
+
*/
|
|
488
|
+
_loadJson(filePath, fallback) {
|
|
489
|
+
return loadJson(filePath, fallback)
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
/** 按文件记文本量:替换而不是累加,重写同一个文件不会算两遍。 */
|
|
493
|
+
_setFileTextChars(relPath, chars) {
|
|
494
|
+
const prev = this._fileTextChars.get(relPath) || 0
|
|
495
|
+
if (chars > 0) this._fileTextChars.set(relPath, chars)
|
|
496
|
+
else this._fileTextChars.delete(relPath)
|
|
497
|
+
this._textChars += chars - prev
|
|
498
|
+
}
|
|
499
|
+
|
|
360
500
|
_loadSharded() {
|
|
361
501
|
let shardNames = []
|
|
362
502
|
try {
|
|
@@ -365,8 +505,10 @@ export class ProjectMemoryStore {
|
|
|
365
505
|
shardNames = []
|
|
366
506
|
}
|
|
367
507
|
for (const name of shardNames) {
|
|
368
|
-
const
|
|
508
|
+
const counter = { chars: 0 }
|
|
509
|
+
const shard = loadJson(path.join(this.dir, SHARDS_DIR, name), null, counter)
|
|
369
510
|
if (!shard || typeof shard.relPath !== 'string' || !isRecord(shard.record)) continue
|
|
511
|
+
this._setFileTextChars(shard.relPath, counter.chars)
|
|
370
512
|
this.files[shard.relPath] = shard.record
|
|
371
513
|
// 畸形 shard(entries 被写成对象/null)不能让 allEntries() 在 `for…of` 上抛错,
|
|
372
514
|
// 否则一个坏文件会拖垮整个进程的每一次读取。
|
|
@@ -376,10 +518,12 @@ export class ProjectMemoryStore {
|
|
|
376
518
|
this.entries[shard.relPath] = list.map(stripPersistedDerived)
|
|
377
519
|
}
|
|
378
520
|
this._entriesVersion++
|
|
379
|
-
this.experience =
|
|
380
|
-
this.tasks =
|
|
381
|
-
this.binding =
|
|
382
|
-
this.watchlist =
|
|
521
|
+
this.experience = this._loadJson(path.join(this.dir, EXPERIENCE_FILE), [])
|
|
522
|
+
this.tasks = this._loadJson(path.join(this.dir, TASKS_FILE), [])
|
|
523
|
+
this.binding = this._loadJson(path.join(this.dir, BINDING_FILE), {})
|
|
524
|
+
this.watchlist = this._loadJson(path.join(this.dir, WATCH_FILE), [])
|
|
525
|
+
// 这四个集合的内容刚刚被换掉,让 auxCharsOf/精确估算重算(而不是沿用上一份实例的账)。
|
|
526
|
+
this._auxVersion++
|
|
383
527
|
this._formatWritten = existsSafe(path.join(this.dir, FORMAT_FILE))
|
|
384
528
|
}
|
|
385
529
|
|
|
@@ -407,7 +551,7 @@ export class ProjectMemoryStore {
|
|
|
407
551
|
// 首次加载把旧笔记**复制导入** insights.json(kind: experience, source: migrate),
|
|
408
552
|
// migratedAt 落盘保证跨进程/崩溃幂等。销毁式收敛放到 recall 统一 PR。
|
|
409
553
|
_loadInsights() {
|
|
410
|
-
const doc =
|
|
554
|
+
const doc = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
|
|
411
555
|
this.insights = isRecord(doc) && Array.isArray(doc.items)
|
|
412
556
|
// items 里混进 null/非对象(手改或旧版写入)会让迁移与召回逐个 `.title` 抛错——过滤掉。
|
|
413
557
|
? { ...doc, items: doc.items.filter(isRecord) }
|
|
@@ -415,6 +559,8 @@ export class ProjectMemoryStore {
|
|
|
415
559
|
this._migrateExperienceToInsights()
|
|
416
560
|
// PR3:v1 → v2 懒回填派生 trigger(纯确定性、幂等;不调用模型,不改写已有字段)
|
|
417
561
|
if (backfillDerivedTriggers(this.insights)) this._dirtyInsights = true
|
|
562
|
+
// 迁移与回填都会改 items;换掉整个文档后让 auxCharsOf/精确估算重算。
|
|
563
|
+
this._auxVersion++
|
|
418
564
|
}
|
|
419
565
|
|
|
420
566
|
_migrateExperienceToInsights() {
|
|
@@ -465,10 +611,16 @@ export class ProjectMemoryStore {
|
|
|
465
611
|
replaceInsightItems(items) {
|
|
466
612
|
this.insights.items = items
|
|
467
613
|
this._dirtyInsights = true
|
|
614
|
+
this._auxVersion++
|
|
468
615
|
}
|
|
469
616
|
|
|
617
|
+
/**
|
|
618
|
+
* 调用方**直接改过** task 内容(包括 task 内的条目)后的标脏入口。任务树不在 `addTask` /
|
|
619
|
+
* `updateTask` 那几条写口里,所以这里也要 bump 内容版本,否则精确估算停在前一水位。
|
|
620
|
+
*/
|
|
470
621
|
markTasksDirty() {
|
|
471
622
|
this._dirtyTasks = true
|
|
623
|
+
this._auxVersion++
|
|
472
624
|
}
|
|
473
625
|
|
|
474
626
|
cleanStaleTmp() {
|
|
@@ -628,6 +780,7 @@ export class ProjectMemoryStore {
|
|
|
628
780
|
if (!this.watchlist.includes(root)) {
|
|
629
781
|
this.watchlist.push(root)
|
|
630
782
|
this._dirtyWatch = true
|
|
783
|
+
this._auxVersion++
|
|
631
784
|
return true
|
|
632
785
|
}
|
|
633
786
|
return false
|
|
@@ -636,7 +789,10 @@ export class ProjectMemoryStore {
|
|
|
636
789
|
removeWatch(root) {
|
|
637
790
|
const before = this.watchlist.length
|
|
638
791
|
this.watchlist = this.watchlist.filter((r) => r !== root)
|
|
639
|
-
if (this.watchlist.length !== before)
|
|
792
|
+
if (this.watchlist.length !== before) {
|
|
793
|
+
this._dirtyWatch = true
|
|
794
|
+
this._auxVersion++
|
|
795
|
+
}
|
|
640
796
|
return before !== this.watchlist.length
|
|
641
797
|
}
|
|
642
798
|
|
|
@@ -659,8 +815,10 @@ export class ProjectMemoryStore {
|
|
|
659
815
|
return out
|
|
660
816
|
})
|
|
661
817
|
this.entries[relPath] = enriched
|
|
818
|
+
this._setFileTextChars(relPath, entryTextChars(enriched))
|
|
662
819
|
} else {
|
|
663
820
|
delete this.entries[relPath]
|
|
821
|
+
this._setFileTextChars(relPath, 0)
|
|
664
822
|
}
|
|
665
823
|
this._entriesVersion++
|
|
666
824
|
this._dirtyShards.add(relPath)
|
|
@@ -671,6 +829,7 @@ export class ProjectMemoryStore {
|
|
|
671
829
|
if (relPath in this.files) {
|
|
672
830
|
delete this.files[relPath]
|
|
673
831
|
delete this.entries[relPath]
|
|
832
|
+
this._setFileTextChars(relPath, 0)
|
|
674
833
|
this._entriesVersion++
|
|
675
834
|
this._dirtyShards.add(relPath)
|
|
676
835
|
this._removedShards.add(relPath)
|
|
@@ -708,18 +867,23 @@ export class ProjectMemoryStore {
|
|
|
708
867
|
allEntries() {
|
|
709
868
|
const out = []
|
|
710
869
|
let materialized = 0
|
|
711
|
-
for (const list of Object.
|
|
870
|
+
for (const [relPath, list] of Object.entries(this.entries)) {
|
|
871
|
+
let addedChars = 0
|
|
712
872
|
for (const entry of list) {
|
|
713
873
|
// searchText 不落盘,首次用到时按需物化并挂在对象上(同一 entry 只算一次)。
|
|
714
874
|
if (entry.searchText === undefined) {
|
|
715
875
|
entry.searchText = makeSearchText(entry)
|
|
876
|
+
addedChars += entry.searchText.length
|
|
716
877
|
materialized++
|
|
717
878
|
}
|
|
718
879
|
out.push(entry)
|
|
719
880
|
}
|
|
881
|
+
// 物化是实打实的内存增量(70119 条目实测 +34MB),必须进上界——按文件替换,
|
|
882
|
+
// 与写路径同一套语义:之后重写 / 删掉这个文件时会连这笔一起替换掉。
|
|
883
|
+
if (addedChars) this._setFileTextChars(relPath, (this._fileTextChars.get(relPath) || 0) + addedChars)
|
|
720
884
|
}
|
|
721
885
|
// 物化只改 entry 对象、不改 entries 的构成,所以 `_entriesVersion` 不会动;但驻留会实打实
|
|
722
|
-
//
|
|
886
|
+
// 增加。这里是它的第二个失效键——漏了它,估算就停在物化前的水位。
|
|
723
887
|
if (materialized) this._materializeVersion++
|
|
724
888
|
return out
|
|
725
889
|
}
|
|
@@ -733,12 +897,14 @@ export class ProjectMemoryStore {
|
|
|
733
897
|
if (sourceFile) existing.sourceFile = sourceFile
|
|
734
898
|
existing.updatedAt = now
|
|
735
899
|
this._dirtyExperience = true
|
|
900
|
+
this._auxVersion++
|
|
736
901
|
return { id: existing.id, superseded: true }
|
|
737
902
|
}
|
|
738
903
|
const id = randomUUID()
|
|
739
904
|
this.experience.push({ id, problem, solution, sourceFile, createdAt: now, updatedAt: now })
|
|
740
905
|
this.pruneExperience()
|
|
741
906
|
this._dirtyExperience = true
|
|
907
|
+
this._auxVersion++
|
|
742
908
|
return { id, superseded: false }
|
|
743
909
|
}
|
|
744
910
|
|
|
@@ -749,6 +915,7 @@ export class ProjectMemoryStore {
|
|
|
749
915
|
const sorted = [...this.experience].sort((a, b) => (a.updatedAt < b.updatedAt ? -1 : 1))
|
|
750
916
|
const victims = new Set(sorted.slice(0, this.experience.length - max).map((e) => e.id))
|
|
751
917
|
this.experience = this.experience.filter((e) => !victims.has(e.id))
|
|
918
|
+
this._auxVersion++
|
|
752
919
|
return victims.size
|
|
753
920
|
}
|
|
754
921
|
|
|
@@ -785,7 +952,10 @@ export class ProjectMemoryStore {
|
|
|
785
952
|
return overlap / Math.min(tokens.length, itemTokens.length) < 0.5
|
|
786
953
|
})
|
|
787
954
|
}
|
|
788
|
-
if (this.experience.length !== before)
|
|
955
|
+
if (this.experience.length !== before) {
|
|
956
|
+
this._dirtyExperience = true
|
|
957
|
+
this._auxVersion++
|
|
958
|
+
}
|
|
789
959
|
return before - this.experience.length
|
|
790
960
|
}
|
|
791
961
|
|
|
@@ -813,6 +983,7 @@ export class ProjectMemoryStore {
|
|
|
813
983
|
addTask(task) {
|
|
814
984
|
this.tasks.push(task)
|
|
815
985
|
this._dirtyTasks = true
|
|
986
|
+
this._auxVersion++
|
|
816
987
|
}
|
|
817
988
|
|
|
818
989
|
updateTask(id, updates) {
|
|
@@ -820,6 +991,7 @@ export class ProjectMemoryStore {
|
|
|
820
991
|
if (!task) return false
|
|
821
992
|
Object.assign(task, updates, { updatedAt: new Date().toISOString() })
|
|
822
993
|
this._dirtyTasks = true
|
|
994
|
+
this._auxVersion++
|
|
823
995
|
return true
|
|
824
996
|
}
|
|
825
997
|
|
|
@@ -832,6 +1004,7 @@ export class ProjectMemoryStore {
|
|
|
832
1004
|
}
|
|
833
1005
|
this._dirtyTasks = true
|
|
834
1006
|
this._dirtyBinding = true
|
|
1007
|
+
this._auxVersion++
|
|
835
1008
|
return true
|
|
836
1009
|
}
|
|
837
1010
|
|
|
@@ -839,6 +1012,7 @@ export class ProjectMemoryStore {
|
|
|
839
1012
|
if (!sessionId) return
|
|
840
1013
|
this.binding[sessionId] = taskId
|
|
841
1014
|
this._dirtyBinding = true
|
|
1015
|
+
this._auxVersion++
|
|
842
1016
|
}
|
|
843
1017
|
|
|
844
1018
|
getBoundTaskId(sessionId) {
|
|
@@ -849,6 +1023,7 @@ export class ProjectMemoryStore {
|
|
|
849
1023
|
if (sessionId && sessionId in this.binding) {
|
|
850
1024
|
delete this.binding[sessionId]
|
|
851
1025
|
this._dirtyBinding = true
|
|
1026
|
+
this._auxVersion++
|
|
852
1027
|
}
|
|
853
1028
|
}
|
|
854
1029
|
|
|
@@ -865,6 +1040,7 @@ export class ProjectMemoryStore {
|
|
|
865
1040
|
task.archived = true
|
|
866
1041
|
this._dirtyTasks = true
|
|
867
1042
|
}
|
|
1043
|
+
if (toArchive.length) this._auxVersion++
|
|
868
1044
|
return toArchive.length
|
|
869
1045
|
}
|
|
870
1046
|
|
|
@@ -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/tools/task-tools.js
CHANGED
|
@@ -118,6 +118,8 @@ export function selectTaskTool(config, host) {
|
|
|
118
118
|
task.updatedAt = now
|
|
119
119
|
task.lastActiveAt = now
|
|
120
120
|
if (sid) task.lastSessionId = sid
|
|
121
|
+
// 解归档 / 改名 / 戳活动时间都是直接改 task:不标脏则 save() 早退,tasks.json 不落盘。
|
|
122
|
+
store.markTasksDirty()
|
|
121
123
|
store.save()
|
|
122
124
|
|
|
123
125
|
// 反向接管:绑定成功后,把任务步骤推成宿主 todo/write(dsh 清单跟随我们的任务)
|
|
@@ -181,6 +183,7 @@ export function archiveTaskTool(config, host) {
|
|
|
181
183
|
if (task.archived) return truncate(JSON.stringify({ success: false, error: 'Already archived' }), config.maxOutputChars)
|
|
182
184
|
task.archived = true
|
|
183
185
|
task.updatedAt = new Date().toISOString()
|
|
186
|
+
store.markTasksDirty()
|
|
184
187
|
store.save()
|
|
185
188
|
// 反思钩子:归档即收割最终教训(默认关)
|
|
186
189
|
fireReflect(config, host, root, args.taskId, 'archive', resolveRoute(exec, config))
|
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) {
|