@yolk_vat-y/dsh-project-memory 0.6.0 → 0.6.2

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.
@@ -4,6 +4,7 @@
4
4
  import path from 'node:path'
5
5
  import { createHash, randomUUID } from 'node:crypto'
6
6
  import { memoryRootFor, resolveProjectMemoryRoot } from '../util/fs.js'
7
+ import { sessionWorkingDir } from '../util/session-dir.js'
7
8
  import { ProjectMemoryStore } from '../store.js'
8
9
  import { stepContent, stepStatus } from '../util/task-view.js'
9
10
 
@@ -170,11 +171,15 @@ export function touchTaskFile(task, rel, kind, now) {
170
171
  * todo/write → 已绑定则覆盖 steps,未绑定则自动新建任务并绑定(子代理会话除外,
171
172
  * 由 isSubagentSession 判定);tool/call(fs 工具)→ 绑定任务 files 并集。
172
173
  */
173
- export function onSessionEvent(config, session, event, meta) {
174
+ export function onSessionEvent(config, session, event, meta, ctx) {
174
175
  const sessionId = session?.id
175
176
  const type = event?.type
176
177
  if (!sessionId || !type) return
177
178
  const now = new Date().toISOString()
179
+ // 任务清单按「会话当前工作目录」归属:0.2.1+ 该目录由 workingDirectory 投影决定
180
+ // (cd 后会变),老宿主回退 header.cwd。`ctx` 只在宿主装配路径上给得到;测试与
181
+ // 老调用方不给也能跑(回退 header.cwd)。
182
+ const cwd = sessionWorkingDir(session, { ctx })
178
183
 
179
184
  // 人类消息:记首条真人文本 + 若已绑定任务则刷新 lastHumanAt(供“模型自维护不回声任务卡”判断)
180
185
  if (type === 'user/message') {
@@ -185,7 +190,7 @@ export function onSessionEvent(config, session, event, meta) {
185
190
  m.lastHumanAt = now
186
191
  meta.set(sessionId, m)
187
192
  try {
188
- const { store } = taskStoreFor(session?.header?.cwd, config)
193
+ const { store } = taskStoreFor(cwd, config)
189
194
  if (!store) return
190
195
  store.commit((s) => {
191
196
  const tid = s.getBoundTaskId(sessionId)
@@ -193,7 +198,8 @@ export function onSessionEvent(config, session, event, meta) {
193
198
  if (task && !task.archived) {
194
199
  task.lastHumanAt = now
195
200
  task.updatedAt = now
196
- s._dirtyTasks = true
201
+ // 直接改了 task 内容就必须走标脏入口:只手置 _dirtyTasks 会漏掉驻留估算的新版本维。
202
+ s.markTasksDirty()
197
203
  }
198
204
  })
199
205
  } catch {
@@ -203,7 +209,7 @@ export function onSessionEvent(config, session, event, meta) {
203
209
  return
204
210
  }
205
211
 
206
- const { root, store } = taskStoreFor(session?.header?.cwd, config)
212
+ const { root, store } = taskStoreFor(cwd, config)
207
213
  // 没有项目根(家目录/系统目录会话):不建档、不记文件、不落任何盘。
208
214
  if (!store) return
209
215
 
@@ -240,7 +246,7 @@ export function onSessionEvent(config, session, event, meta) {
240
246
  task.updatedAt = now
241
247
  task.lastActiveAt = now
242
248
  task.lastSessionId = sessionId
243
- s._dirtyTasks = true
249
+ s.markTasksDirty()
244
250
  })
245
251
  return
246
252
  }
@@ -267,7 +273,7 @@ export function onSessionEvent(config, session, event, meta) {
267
273
  if (!task || task.archived) return
268
274
  touchTaskFile(task, rel, kind, now)
269
275
  task.lastActiveAt = now
270
- s._dirtyTasks = true
276
+ s.markTasksDirty()
271
277
  })
272
278
  }
273
279
  }
@@ -278,7 +284,7 @@ export function setupTaskbridge(ctx, config) {
278
284
  const meta = new Map()
279
285
  ctx.on('session/event', (session, event) => {
280
286
  try {
281
- onSessionEvent(config, session, event, meta)
287
+ onSessionEvent(config, session, event, meta, ctx)
282
288
  } catch (err) {
283
289
  console.error('[dsh-project-memory] taskbridge:', err?.message)
284
290
  }
package/src/store.js CHANGED
@@ -1,7 +1,7 @@
1
- import { createHash, randomUUID } from 'node:crypto'
1
+ import { createHash } 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
- import { rankExperience, tokenize, tokenizeRaw, extractCjkPhrases, makeSearchText } from './util/search.js'
4
+ import { tokenizeRaw, makeSearchText } from './util/search.js'
5
5
  import { writeJsonAtomic } from './util/fs.js'
6
6
  import { backfillDerivedTriggers } from './readiness.js'
7
7
 
@@ -49,9 +49,12 @@ const RESIDENT_KEY_BYTES = 40
49
49
  const RESIDENT_STR_BYTES = 16
50
50
  const RESIDENT_MAX_DEPTH = 8
51
51
 
52
- /** 精确计量的版本戳:entries 的构成 + `searchText` 的物化状态各算一维。 */
52
+ /**
53
+ * 精确计量的版本戳:entries 的构成 + `searchText` 的物化状态 + 辅助集合的内容各算一维。
54
+ * 三维缺一不可——漏掉哪一维,估算就停在那一维变更前的水位。
55
+ */
53
56
  function residentStampOf(store) {
54
- return `${store._entriesVersion}:${store._materializeVersion}`
57
+ return `${store._entriesVersion}:${store._materializeVersion}:${store._auxVersion}`
55
58
  }
56
59
 
57
60
  /**
@@ -65,8 +68,12 @@ function residentStampOf(store) {
65
68
  * 外加键与对象形状开销(符号条目实测 ~4×);CJK 字符驻留 2 字节,而 UTF-8 文本里 3 字节,
66
69
  * 字符数只会更少。精确数一旦算过且版本未变,直接用它,不必再估。
67
70
  *
68
- * `_textChars` 由三条路径维护(读盘分片 / 写条目 / 非分片 JSON),按文件**替换式**累计,
69
- * 所以重写同一个文件不会把它算两遍。在真实语料上标定的上界 / 精确值比是 1.16~1.74 倍。
71
+ * 两条腿合成一个数:
72
+ * - `_textChars`:entries 的文本量,由三条路径维护(读盘分片 / 写条目 / 物化 `searchText`),
73
+ * 按文件**替换式**累计,所以重写同一个文件不会把它算两遍;
74
+ * - `auxCharsOf()`:辅助集合(experience / insights / tasks / binding / watch)的文本量。
75
+ * 它们不在分片文本里,`load()` 之后还会被写大,单列一条腿才不会漏。
76
+ * 在真实语料上标定的上界 / 精确值比是 1.16~1.74 倍。
70
77
  */
71
78
  const RESIDENT_BOUND_PER_CHAR = 4
72
79
  const RESIDENT_SKELETON_BYTES = 1024
@@ -74,7 +81,7 @@ const RESIDENT_SKELETON_BYTES = 1024
74
81
  function residentBoundBytes(store) {
75
82
  const stamp = residentStampOf(store)
76
83
  if (store._residentStamp === stamp) return store._residentBytes
77
- return RESIDENT_SKELETON_BYTES + store._textChars * RESIDENT_BOUND_PER_CHAR
84
+ return RESIDENT_SKELETON_BYTES + (store._textChars + auxCharsOf(store)) * RESIDENT_BOUND_PER_CHAR
78
85
  }
79
86
 
80
87
  /**
@@ -97,25 +104,63 @@ export function _residentBoundBytesForTest(store) {
97
104
  return residentBoundBytes(store)
98
105
  }
99
106
 
100
- function residentBytesOf(value, depth = 0) {
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) {
101
115
  if (depth > RESIDENT_MAX_DEPTH) return 0
102
116
  const type = typeof value
103
- if (type === 'string') return RESIDENT_STR_BYTES + Buffer.byteLength(value)
117
+ if (type === 'string') return RESIDENT_STR_BYTES + (charsOnly ? value.length : Buffer.byteLength(value))
104
118
  if (type === 'number' || type === 'bigint') return 16
105
119
  if (type === 'boolean' || value === null) return 8
106
120
  if (Array.isArray(value)) {
107
121
  let sum = RESIDENT_ARR_BYTES
108
- for (const item of value) sum += 8 + residentBytesOf(item, depth + 1)
122
+ for (const item of value) sum += 8 + residentSizeOf(item, charsOnly, depth + 1)
109
123
  return sum
110
124
  }
111
125
  if (type === 'object') {
112
126
  let sum = RESIDENT_OBJ_BYTES
113
- for (const key in value) sum += RESIDENT_KEY_BYTES + residentBytesOf(value[key], depth + 1)
127
+ for (const key in value) sum += RESIDENT_KEY_BYTES + residentSizeOf(value[key], charsOnly, depth + 1)
114
128
  return sum
115
129
  }
116
130
  return 0
117
131
  }
118
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.insights) +
157
+ residentCharsOf(store.tasks) +
158
+ residentCharsOf(store.binding) +
159
+ residentCharsOf(store.watchlist)
160
+ store._auxStamp = store._auxVersion
161
+ return store._auxChars
162
+ }
163
+
119
164
  /**
120
165
  * 单个 store 的驻留估算:数**内存里留下的对象图**,按版本记忆化。
121
166
  *
@@ -138,7 +183,6 @@ export function _estimateResidentBytes(store) {
138
183
  store._residentBytes =
139
184
  residentBytesOf(store.entries) +
140
185
  residentBytesOf(store.files) +
141
- residentBytesOf(store.experience) +
142
186
  residentBytesOf(store.tasks) +
143
187
  residentBytesOf(store.insights) +
144
188
  residentBytesOf(store.watchlist) +
@@ -308,7 +352,6 @@ export class ProjectMemoryStore {
308
352
  this.watchlist = []
309
353
  this._dirtyShards = new Set()
310
354
  this._removedShards = new Set()
311
- this._dirtyExperience = false
312
355
  this._dirtyInsights = false
313
356
  this._dirtyTasks = false
314
357
  this._dirtyBinding = false
@@ -323,8 +366,8 @@ export class ProjectMemoryStore {
323
366
  this._residentBytes = 0
324
367
  this._residentStamp = ''
325
368
  /**
326
- * 内存里文本字符数的累计(读盘分片 + 写条目 + 非分片 JSON)。**只**用于
327
- * `residentBoundBytes` 判断"要不要做精确计量";精确估算数的是对象图,不碰这个数。
369
+ * entries 的文本字符数累计(读盘分片 + 写条目 + 物化 `searchText`),按文件**替换式**记。
370
+ * **只**用于 `residentBoundBytes` 判断"要不要做精确计量";精确估算数的是对象图,不碰它。
328
371
  */
329
372
  this._textChars = 0
330
373
  /** 每个文件当前的文本字符数,写入时按文件替换,避免重写同一文件被算两遍。 */
@@ -334,6 +377,13 @@ export class ProjectMemoryStore {
334
377
  * 物化只改 entry 对象本身,不改 entries 的构成,所以不会 bump `_entriesVersion`。
335
378
  */
336
379
  this._materializeVersion = 0
380
+ /**
381
+ * 辅助集合(experience / insights / tasks / binding / watch)的内容版本:它们不在 entries
382
+ * 的记账面里,靠它让精确估算失效、并让 `auxCharsOf` 重算。每个改到它们的写口都要 bump。
383
+ */
384
+ this._auxVersion = 0
385
+ this._auxChars = 0
386
+ this._auxStamp = ''
337
387
  }
338
388
 
339
389
  load() {
@@ -426,12 +476,14 @@ export class ProjectMemoryStore {
426
476
  console.error(`[dsh-project-memory] migrated legacy store at ${this.dir} to sharded layout (${Object.keys(files).length} files)`)
427
477
  }
428
478
 
429
- /** 读一个 JSON 文件,并把读入文本的字符数记到 `_textChars`(供驻留上界用)。 */
479
+ /**
480
+ * 读一个辅助集合文件(experience / tasks / insights / binding / watch)。
481
+ *
482
+ * 它们的文本量**不进** `_textChars`:那份账只跟 entries(按文件替换),辅助集合交给
483
+ * `auxCharsOf` 按对象图直接算——同一个集合由两个口径各记一半,迟早会漂。
484
+ */
430
485
  _loadJson(filePath, fallback) {
431
- const counter = { chars: 0 }
432
- const data = loadJson(filePath, fallback, counter)
433
- this._textChars += counter.chars
434
- return data
486
+ return loadJson(filePath, fallback)
435
487
  }
436
488
 
437
489
  /** 按文件记文本量:替换而不是累加,重写同一个文件不会算两遍。 */
@@ -467,6 +519,8 @@ export class ProjectMemoryStore {
467
519
  this.tasks = this._loadJson(path.join(this.dir, TASKS_FILE), [])
468
520
  this.binding = this._loadJson(path.join(this.dir, BINDING_FILE), {})
469
521
  this.watchlist = this._loadJson(path.join(this.dir, WATCH_FILE), [])
522
+ // 这四个集合的内容刚刚被换掉,让 auxCharsOf/精确估算重算(而不是沿用上一份实例的账)。
523
+ this._auxVersion++
470
524
  this._formatWritten = existsSafe(path.join(this.dir, FORMAT_FILE))
471
525
  }
472
526
 
@@ -489,10 +543,13 @@ export class ProjectMemoryStore {
489
543
  }
490
544
 
491
545
  // ---- v0.5 insights:project 级 insight 文档(任务级在 task.insights[]) ----
492
- // 迁移语义(旧版 store 的兼容策略):
493
- // v0.4 experience.json 仍由 remember/forget/query_memory 服务,不删除;
494
- // 首次加载把旧笔记**复制导入** insights.json(kind: experience, source: migrate),
495
- // migratedAt 落盘保证跨进程/崩溃幂等。销毁式收敛放到 recall 统一 PR。
546
+ // 统一语义(本版起):insight 是**唯一**的记忆实体,`kind:'experience'` 就是 v0.4 的经验笔记。
547
+ // 旧版 store 的兼容策略:把 experience.json 的内容**导入** insights.json 一次,随后把旧文件改名成
548
+ // `experience.json.migrated` 只读归档——不删(升级后想人工比对还有原文),但不再读写它。
549
+ //
550
+ // 归档那一步必须与"导入"分开判:0.5.x/0.6.x 用户的 store 里 `migratedAt` 早就写上了(那时导入的是
551
+ // 影子副本),可旧文件还留在磁盘上。只看 migratedAt 的话,老用户永远收不走它,
552
+ // `store.experience` 也永远留着第二份内容——正是"散"的来源。
496
553
  _loadInsights() {
497
554
  const doc = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
498
555
  this.insights = isRecord(doc) && Array.isArray(doc.items)
@@ -502,43 +559,66 @@ export class ProjectMemoryStore {
502
559
  this._migrateExperienceToInsights()
503
560
  // PR3:v1 → v2 懒回填派生 trigger(纯确定性、幂等;不调用模型,不改写已有字段)
504
561
  if (backfillDerivedTriggers(this.insights)) this._dirtyInsights = true
562
+ // 迁移与回填都会改 items;换掉整个文档后让 auxCharsOf/精确估算重算。
563
+ this._auxVersion++
505
564
  }
506
565
 
507
566
  _migrateExperienceToInsights() {
508
- if (this.insights.migratedAt) return
509
- const legacy = this.experience
510
- if (!Array.isArray(legacy) || legacy.length === 0) return
511
- const now = new Date().toISOString()
512
- const known = new Set(this.insights.items.map((it) => it.id))
567
+ const legacyFile = path.join(this.dir, EXPERIENCE_FILE)
568
+ const legacyOnDisk = existsSafe(legacyFile)
569
+ const legacy = Array.isArray(this.experience) ? this.experience : []
570
+ if (legacyOnDisk && !Array.isArray(this.experience)) {
571
+ console.error(`[dsh-project-memory] ${EXPERIENCE_FILE} is not an array; importing nothing (file kept as-is)`)
572
+ return
573
+ }
513
574
  let imported = 0
514
- for (const item of legacy) {
515
- if (!item || !item.problem || known.has(item.id)) continue
516
- known.add(item.id)
517
- this.insights.items.push({
518
- id: item.id,
519
- kind: 'experience',
520
- scope: 'project',
521
- title: String(item.problem).slice(0, 120),
522
- problem: item.problem,
523
- solution: item.solution,
524
- files: item.sourceFile ? [item.sourceFile] : [],
525
- symbols: [],
526
- sourceTaskIds: [],
527
- source: 'migrate',
528
- confidence: 1,
529
- hitCount: 0,
530
- createdAt: item.createdAt || now,
531
- updatedAt: item.updatedAt || now,
532
- })
533
- imported++
575
+ // 导入 + 落盘这条支路必须有"值得写"的输入才走:`migratedAt` 为空 + 旧文件不在 + 内存里也没有
576
+ // 旧条目(全新根)时直接跳过。否则 `load()` 会在一个从没被索引过的空目录里 mkdir + 写
577
+ // insights.json —— 那会让 `audit.js` 的 auditDirReady("目录已存在")与 auto-inject 的
578
+ // `if (store.hasContent) store.save()` 双双失效,容器目录被当成项目根(issue #5 同类)。
579
+ // 归档旧文件是**另一支**(下面单独判 legacyOnDisk),所以跳过这里不影响真升级。
580
+ if (!this.insights.migratedAt && (legacyOnDisk || legacy.length > 0)) {
581
+ const now = new Date().toISOString()
582
+ const known = new Set(this.insights.items.map((it) => it.id))
583
+ for (const item of legacy) {
584
+ if (!item || !item.problem || known.has(item.id)) continue
585
+ known.add(item.id)
586
+ this.insights.items.push({
587
+ id: item.id,
588
+ kind: 'experience',
589
+ scope: 'project',
590
+ title: String(item.problem).slice(0, 120),
591
+ problem: item.problem,
592
+ solution: item.solution,
593
+ files: item.sourceFile ? [item.sourceFile] : [],
594
+ symbols: [],
595
+ sourceTaskIds: [],
596
+ source: 'migrate',
597
+ confidence: 1,
598
+ hitCount: 0,
599
+ createdAt: item.createdAt || now,
600
+ updatedAt: item.updatedAt || now,
601
+ })
602
+ imported++
603
+ }
604
+ this.insights.migratedAt = now
605
+ try {
606
+ mkdirSync(this.dir, { recursive: true })
607
+ writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
608
+ } catch (err) {
609
+ // 没写进 insights.json 就**不能**把旧文件收走:那会真的丢数据。
610
+ console.error(`[dsh-project-memory] insights migration write failed, keeping ${EXPERIENCE_FILE}: ${err.message}`)
611
+ return
612
+ }
534
613
  }
535
- this.insights.migratedAt = now
536
- try {
537
- mkdirSync(this.dir, { recursive: true })
538
- writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
539
- } catch (err) {
540
- console.error(`[dsh-project-memory] insights migration write failed: ${err.message}`)
614
+ if (legacyOnDisk) {
615
+ try {
616
+ renameSync(legacyFile, `${legacyFile}.migrated`)
617
+ } catch (err) {
618
+ console.error(`[dsh-project-memory] could not archive ${EXPERIENCE_FILE} (imported ${imported} note(s)): ${err.message}`)
619
+ }
541
620
  }
621
+ this.experience = []
542
622
  }
543
623
 
544
624
  insightsDoc() {
@@ -552,10 +632,16 @@ export class ProjectMemoryStore {
552
632
  replaceInsightItems(items) {
553
633
  this.insights.items = items
554
634
  this._dirtyInsights = true
635
+ this._auxVersion++
555
636
  }
556
637
 
638
+ /**
639
+ * 调用方**直接改过** task 内容(包括 task 内的条目)后的标脏入口。任务树不在 `addTask` /
640
+ * `updateTask` 那几条写口里,所以这里也要 bump 内容版本,否则精确估算停在前一水位。
641
+ */
557
642
  markTasksDirty() {
558
643
  this._dirtyTasks = true
644
+ this._auxVersion++
559
645
  }
560
646
 
561
647
  cleanStaleTmp() {
@@ -610,7 +696,6 @@ export class ProjectMemoryStore {
610
696
  compacting ||
611
697
  this._dirtyShards.size > 0 ||
612
698
  this._removedShards.size > 0 ||
613
- this._dirtyExperience ||
614
699
  this._dirtyInsights ||
615
700
  this._dirtyTasks ||
616
701
  this._dirtyBinding ||
@@ -653,13 +738,10 @@ export class ProjectMemoryStore {
653
738
  }
654
739
  }
655
740
  this._removedShards.clear()
656
- if (this._dirtyExperience) {
657
- writeJsonAtomic(path.join(this.dir, EXPERIENCE_FILE), this.experience)
658
- this._dirtyExperience = false
659
- }
660
741
  if (this._dirtyInsights) {
661
- // PR3:落盘即把格式标记推到 v2(v1 → v2 是纯增量:只多一个可选的 triggerDerived)
662
- if (this.insights && this.insights.version !== 2) this.insights.version = 2
742
+ // v2 → v3 是纯语义升级(`kind:'experience'` 从"影子副本"变成一等实体),形状不变;
743
+ // 落盘即把版本推上去,老版本读到 v3 也照样按 v2 的字段解析(它只是排除 experience 影子)。
744
+ if (this.insights && this.insights.version !== 3) this.insights.version = 3
663
745
  writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
664
746
  this._dirtyInsights = false
665
747
  }
@@ -715,6 +797,7 @@ export class ProjectMemoryStore {
715
797
  if (!this.watchlist.includes(root)) {
716
798
  this.watchlist.push(root)
717
799
  this._dirtyWatch = true
800
+ this._auxVersion++
718
801
  return true
719
802
  }
720
803
  return false
@@ -723,7 +806,10 @@ export class ProjectMemoryStore {
723
806
  removeWatch(root) {
724
807
  const before = this.watchlist.length
725
808
  this.watchlist = this.watchlist.filter((r) => r !== root)
726
- if (this.watchlist.length !== before) this._dirtyWatch = true
809
+ if (this.watchlist.length !== before) {
810
+ this._dirtyWatch = true
811
+ this._auxVersion++
812
+ }
727
813
  return before !== this.watchlist.length
728
814
  }
729
815
 
@@ -798,92 +884,38 @@ export class ProjectMemoryStore {
798
884
  allEntries() {
799
885
  const out = []
800
886
  let materialized = 0
801
- for (const list of Object.values(this.entries)) {
887
+ for (const [relPath, list] of Object.entries(this.entries)) {
888
+ let addedChars = 0
802
889
  for (const entry of list) {
803
890
  // searchText 不落盘,首次用到时按需物化并挂在对象上(同一 entry 只算一次)。
804
891
  if (entry.searchText === undefined) {
805
892
  entry.searchText = makeSearchText(entry)
893
+ addedChars += entry.searchText.length
806
894
  materialized++
807
895
  }
808
896
  out.push(entry)
809
897
  }
898
+ // 物化是实打实的内存增量(70119 条目实测 +34MB),必须进上界——按文件替换,
899
+ // 与写路径同一套语义:之后重写 / 删掉这个文件时会连这笔一起替换掉。
900
+ if (addedChars) this._setFileTextChars(relPath, (this._fileTextChars.get(relPath) || 0) + addedChars)
810
901
  }
811
902
  // 物化只改 entry 对象、不改 entries 的构成,所以 `_entriesVersion` 不会动;但驻留会实打实
812
- // 增加(70119 条目实测 +34MB)。这里是它的第二个失效键——漏了它,估算就停在物化前的水位。
903
+ // 增加。这里是它的第二个失效键——漏了它,估算就停在物化前的水位。
813
904
  if (materialized) this._materializeVersion++
814
905
  return out
815
906
  }
816
907
 
817
- addExperience({ problem, solution, sourceFile }) {
818
- const existing = this.findSupersede(problem)
819
- const now = new Date().toISOString()
820
- if (existing) {
821
- existing.problem = problem
822
- existing.solution = solution
823
- if (sourceFile) existing.sourceFile = sourceFile
824
- existing.updatedAt = now
825
- this._dirtyExperience = true
826
- return { id: existing.id, superseded: true }
827
- }
828
- const id = randomUUID()
829
- this.experience.push({ id, problem, solution, sourceFile, createdAt: now, updatedAt: now })
830
- this.pruneExperience()
831
- this._dirtyExperience = true
832
- return { id, superseded: false }
833
- }
834
-
835
- pruneExperience() {
836
- const indexedFileCount = Object.keys(this.files).length
837
- const max = Math.max(100, Math.min(2000, indexedFileCount * 2))
838
- if (this.experience.length <= max) return 0
839
- const sorted = [...this.experience].sort((a, b) => (a.updatedAt < b.updatedAt ? -1 : 1))
840
- const victims = new Set(sorted.slice(0, this.experience.length - max).map((e) => e.id))
841
- this.experience = this.experience.filter((e) => !victims.has(e.id))
842
- return victims.size
843
- }
844
-
845
- findSupersede(problem) {
846
- const tokens = tokenize(problem)
847
- if (!tokens.length) return null
848
- let best = null
849
- let bestOverlap = 0
850
- for (const item of this.experience) {
851
- const itemTokens = tokenize(item.problem)
852
- const overlap = itemTokens.filter((t) => tokens.includes(t)).length
853
- if (overlap === 0) continue
854
- const ratioQuery = overlap / tokens.length
855
- const ratioItem = overlap / itemTokens.length
856
- if (ratioQuery >= 0.7 && ratioItem >= 0.7 && overlap > bestOverlap) {
857
- best = item
858
- bestOverlap = overlap
859
- }
860
- }
861
- return best
862
- }
863
-
864
- removeExperience(idOrQuery) {
865
- const before = this.experience.length
866
- if (idOrQuery && this.experience.some((item) => item.id === idOrQuery)) {
867
- this.experience = this.experience.filter((item) => item.id !== idOrQuery)
868
- } else {
869
- const tokens = tokenize(idOrQuery)
870
- if (!tokens.length) return 0
871
- this.experience = this.experience.filter((item) => {
872
- const itemTokens = tokenize(`${item.problem} ${item.solution}`)
873
- if (!itemTokens.length) return true
874
- const overlap = itemTokens.filter((t) => tokens.includes(t)).length
875
- return overlap / Math.min(tokens.length, itemTokens.length) < 0.5
876
- })
877
- }
878
- if (this.experience.length !== before) this._dirtyExperience = true
879
- return before - this.experience.length
880
- }
908
+ // v0.4 的 experience 读写入口(addExperience / pruneExperience / findSupersede / removeExperience)
909
+ // 已随统一存储删除:经验笔记现在是 `kind:'experience'` 的 insight,写入走 `src/tools/remember.js`
910
+ // → `saveInsight`,删除走 `removeMemory`,容量归 insight 层的 maxProject。
911
+ // `experience.json` 只剩一个角色:`_migrateExperienceToInsights` 的导入源。
881
912
 
882
913
  stats() {
883
914
  return {
884
915
  files: Object.keys(this.files).length,
885
916
  entries: this.allEntries().length,
886
- experience: this.experience.length,
917
+ // 经验笔记 = insight 里 kind:'experience' 的那些(含从 v0.4 导入的)。project 级为准。
918
+ experience: this.insights.items.filter((it) => it && it.kind === 'experience').length,
887
919
  tasks: this.tasks.length,
888
920
  tasksActive: this.tasks.filter((t) => !t.archived).length,
889
921
  tasksArchived: this.tasks.filter((t) => t.archived).length,
@@ -903,6 +935,7 @@ export class ProjectMemoryStore {
903
935
  addTask(task) {
904
936
  this.tasks.push(task)
905
937
  this._dirtyTasks = true
938
+ this._auxVersion++
906
939
  }
907
940
 
908
941
  updateTask(id, updates) {
@@ -910,6 +943,7 @@ export class ProjectMemoryStore {
910
943
  if (!task) return false
911
944
  Object.assign(task, updates, { updatedAt: new Date().toISOString() })
912
945
  this._dirtyTasks = true
946
+ this._auxVersion++
913
947
  return true
914
948
  }
915
949
 
@@ -922,6 +956,7 @@ export class ProjectMemoryStore {
922
956
  }
923
957
  this._dirtyTasks = true
924
958
  this._dirtyBinding = true
959
+ this._auxVersion++
925
960
  return true
926
961
  }
927
962
 
@@ -929,6 +964,7 @@ export class ProjectMemoryStore {
929
964
  if (!sessionId) return
930
965
  this.binding[sessionId] = taskId
931
966
  this._dirtyBinding = true
967
+ this._auxVersion++
932
968
  }
933
969
 
934
970
  getBoundTaskId(sessionId) {
@@ -939,6 +975,7 @@ export class ProjectMemoryStore {
939
975
  if (sessionId && sessionId in this.binding) {
940
976
  delete this.binding[sessionId]
941
977
  this._dirtyBinding = true
978
+ this._auxVersion++
942
979
  }
943
980
  }
944
981
 
@@ -955,6 +992,7 @@ export class ProjectMemoryStore {
955
992
  task.archived = true
956
993
  this._dirtyTasks = true
957
994
  }
995
+ if (toArchive.length) this._auxVersion++
958
996
  return toArchive.length
959
997
  }
960
998
 
@@ -1001,7 +1039,8 @@ export function storeOverview(store) {
1001
1039
  return {
1002
1040
  files: Object.keys(store.files).length,
1003
1041
  entries: store.allEntries().length,
1004
- experience: store.experience.length,
1042
+ // 不调 store.stats():overview 也会被喂裸桩(测试/子索引汇总),少一个必需方法就少一处崩点。
1043
+ experience: Array.isArray(store.insights?.items) ? store.insights.items.filter((it) => it && it.kind === 'experience').length : 0,
1005
1044
  latest,
1006
1045
  }
1007
1046
  }
@@ -1,17 +1,26 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
3
  import { ProjectMemoryStore } from '../store.js'
4
+ import { cfgInsight, GlobalStore, defaultGlobalFile, removeMemory } from '../insight-store.js'
5
+
6
+ /** 回报用的一行:`ins_xxx《标题》(project)`。标题已在 removeMemory 里截断。 */
7
+ function line(e) {
8
+ return `${e.id}《${e.title}》(${e.home})`
9
+ }
4
10
 
5
11
  export function forgetTool(config) {
6
12
  return defineTool({
7
13
  name: 'forget',
8
14
  description:
9
- 'Delete experience notes from project memory by id or by matching keywords. Use to clean stale/obsolete notes.',
15
+ 'Delete memories by id or by matching keywords — lessons / decisions / procedures and experience notes, ' +
16
+ 'at task / project / global scope alike (one call, no need to know which layer it lives in). Real deletion, no undo. ' +
17
+ 'An exact id deletes that one entry; keywords match on how much of the query the entry covers. ' +
18
+ 'A keyword that matches more than the configured cap deletes nothing and lists the candidates instead.',
10
19
  parameters: {
11
20
  id_or_query: {
12
21
  type: 'string',
13
22
  required: true,
14
- description: 'Experience note id (from remember or query_memory output), or keywords to match.',
23
+ description: 'Insight/experience id (from save_lesson, query_memory or a near-match hint), or keywords to match. An exact id always wins over treating it as keywords.',
15
24
  },
16
25
  root: {
17
26
  type: 'string',
@@ -27,10 +36,21 @@ export function forgetTool(config) {
27
36
  assertIndexRoot(root, args.root || root)
28
37
  const memoryDir = memoryRootFor(root, config.memoryDir)
29
38
  const store = new ProjectMemoryStore(memoryDir).load()
30
- return store.commit((s) => {
31
- const removed = s.removeExperience(args.id_or_query)
32
- return removed > 0 ? `Removed ${removed} experience note(s).` : 'No matching experience note found.'
39
+ const cfg = cfgInsight(config)
40
+ const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
41
+ let res
42
+ store.commit((s) => {
43
+ res = removeMemory({ store: s, globalStore, idOrQuery: args.id_or_query, maxMatches: cfg.maxForgetMatches })
44
+ return res
33
45
  })
46
+ globalStore.commit() // global 侧若被删过才落盘
47
+ if (res && res.tooMany) {
48
+ const head = res.matches.slice(0, 10).map(line)
49
+ const more = res.matches.length > head.length ? ` …(共 ${res.matches.length} 条)` : ''
50
+ return `Matched ${res.matches.length} memories (cap ${cfg.maxForgetMatches}), removed none — narrow the query or delete by id:\n` + head.map((l) => `- ${l}`).join('\n') + more
51
+ }
52
+ if (!res || !res.ok || !res.removed.length) return 'No matching memory found.'
53
+ return `Removed ${res.removed.length} memory entries:\n` + res.removed.map((e) => `- ${line(e)}`).join('\n')
34
54
  },
35
55
  })
36
- }
56
+ }