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

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/recall.js CHANGED
@@ -63,7 +63,7 @@ function matchedFloor(scored, queries, hasVector) {
63
63
  return scored.filter((r) => (r.matched ?? 0) >= need)
64
64
  }
65
65
 
66
- /** 各层先验:insight 是"踩过的坑",略高于普通文档;经验层已由 experience 文件服务,略低。 */
66
+ /** 各层先验:insight 是"踩过的坑",略高于普通文档;经验笔记(同库、kind 区分)留痕价值略低。 */
67
67
  export const LAYER_PRIORS = Object.freeze({
68
68
  insight: 1.15,
69
69
  doc: 1,
@@ -164,8 +164,8 @@ export function insightScoringText(ins) {
164
164
  * 召回可见的 insight 集合:作用域可见性跟随会话绑定。
165
165
  * - project / global:始终可见(归档除外);
166
166
  * - task:只在该会话绑定了对应任务时可见(任务私有,不泄露给别的会话);
167
- * - 迁移影子(kind=experience 且 source=migrate)不在此列:它们由 experience 层服务,
168
- * 否则同一内容会在 `## Insights` 与 `## Experience` 里各出现一次。
167
+ * - `kind:'experience'`(v0.4 经验笔记,加载时导入)**也在这里**——统一存储后没有第二个真相源,
168
+ * 它由 experience 那一桶按 kind 取走;本函数不做排除(排除会让同一内容在别的视图里消失)。
169
169
  * @param {{ store?: object, globalStore?: object, boundTaskId?: string|null }} opts
170
170
  * @returns {object[]} 可检索的 insight 条目。
171
171
  */
@@ -175,7 +175,6 @@ export function visibleInsights({ store = null, globalStore = null, boundTaskId
175
175
  if (!it || it.archived) continue
176
176
  if (it.scope === 'task') continue
177
177
  if (it.draft === true) continue
178
- if (it.kind === 'experience' && it.source === 'migrate') continue // v0.4 影子,交给 experience 层
179
178
  out.push(it)
180
179
  }
181
180
  for (const it of (globalStore && typeof globalStore.items === 'function' ? globalStore.items() : []) || []) {
@@ -249,7 +248,7 @@ function fuseVectorHits(scored, queries, rerank) {
249
248
  /**
250
249
  * 按层召回:每层各自 top-k,桶内保留原始分与层内相对分。
251
250
  * @param {object} opts
252
- * @param {object} [opts.store] - ProjectMemoryStore;提供 doc/symbol/experience 池与 IDF 缓存。
251
+ * @param {object} [opts.store] - ProjectMemoryStore;提供 doc/symbol 池与 IDF 缓存。
253
252
  * @param {object} [opts.globalStore] - GlobalStore;提供 global 级 insight。
254
253
  * @param {object[]} [opts.entries] - 直接给定检索池(测试/自定义场景),优先于 store。
255
254
  * @param {string[]|string} [opts.queries] - 一条或多条查询(LLM 扩展变体也走这里)。
@@ -303,7 +302,13 @@ export function recallItems(opts = {}) {
303
302
  }
304
303
 
305
304
  if (want.has('experience')) {
306
- const expPool = (store && store.experience) || []
305
+ // 经验层不再是第二个 store:它就是 `kind:'experience'` 的 insight(v0.4 的旧笔记在加载时导入、
306
+ // 旧文件归档为 experience.json.migrated)。池子与 insight 层同源,所以两边必须**互斥**:
307
+ // insight 桶排除 experience,否则同一内容会同时出现在 `## Insights` 与 `## Experience` 里。
308
+ // `entries` 给了就用给的:那是一份"调用方指定了这个层"的池子,不再按 kind 二次筛。
309
+ const expPool = entries !== null
310
+ ? entries
311
+ : visibleInsights({ store, globalStore, boundTaskId }).filter((it) => it.kind === 'experience')
307
312
  // 有向量时在**全量** BM25 序上融合(见 fuseVectorHits 注释),截断到 limit 放到融合之后;
308
313
  // 没有向量时沿用原来的 limit 语义,输出与纯词法路径逐字段一致。
309
314
  const scored0 = matchedFloor(rankExperienceScored(expPool, qsLayers, rerank ? expPool.length : limit), qsLayers, Boolean(rerank))
@@ -320,8 +325,8 @@ export function recallItems(opts = {}) {
320
325
 
321
326
  if (want.has('insight')) {
322
327
  const pool = entries !== null
323
- ? entries.filter((e) => e && e.type === 'insight')
324
- : visibleInsights({ store, globalStore, boundTaskId }).map(insightToEntry)
328
+ ? entries.filter((e) => e && e.type === 'insight' && e.kind !== 'experience')
329
+ : visibleInsights({ store, globalStore, boundTaskId }).filter((it) => it.kind !== 'experience').map(insightToEntry)
325
330
  const scored0 = matchedFloor(rankEntriesMergedScored(pool, qsLayers, rerank ? pool.length : limit), qsLayers, Boolean(rerank))
326
331
  if (scored0.length) {
327
332
  const scored = fuseVectorHits(scored0.map((r) => ({ item: r.entry, score: r.score })), qs, rerank).slice(0, limit)
@@ -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)
@@ -204,7 +209,7 @@ export function onSessionEvent(config, session, event, meta) {
204
209
  return
205
210
  }
206
211
 
207
- const { root, store } = taskStoreFor(session?.header?.cwd, config)
212
+ const { root, store } = taskStoreFor(cwd, config)
208
213
  // 没有项目根(家目录/系统目录会话):不建档、不记文件、不落任何盘。
209
214
  if (!store) return
210
215
 
@@ -279,7 +284,7 @@ export function setupTaskbridge(ctx, config) {
279
284
  const meta = new Map()
280
285
  ctx.on('session/event', (session, event) => {
281
286
  try {
282
- onSessionEvent(config, session, event, meta)
287
+ onSessionEvent(config, session, event, meta, ctx)
283
288
  } catch (err) {
284
289
  console.error('[dsh-project-memory] taskbridge:', err?.message)
285
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
 
@@ -153,7 +153,6 @@ function residentCharsOf(value) {
153
153
  function auxCharsOf(store) {
154
154
  if (store._auxStamp === store._auxVersion) return store._auxChars
155
155
  store._auxChars =
156
- residentCharsOf(store.experience) +
157
156
  residentCharsOf(store.insights) +
158
157
  residentCharsOf(store.tasks) +
159
158
  residentCharsOf(store.binding) +
@@ -184,7 +183,6 @@ export function _estimateResidentBytes(store) {
184
183
  store._residentBytes =
185
184
  residentBytesOf(store.entries) +
186
185
  residentBytesOf(store.files) +
187
- residentBytesOf(store.experience) +
188
186
  residentBytesOf(store.tasks) +
189
187
  residentBytesOf(store.insights) +
190
188
  residentBytesOf(store.watchlist) +
@@ -354,7 +352,6 @@ export class ProjectMemoryStore {
354
352
  this.watchlist = []
355
353
  this._dirtyShards = new Set()
356
354
  this._removedShards = new Set()
357
- this._dirtyExperience = false
358
355
  this._dirtyInsights = false
359
356
  this._dirtyTasks = false
360
357
  this._dirtyBinding = false
@@ -546,10 +543,13 @@ export class ProjectMemoryStore {
546
543
  }
547
544
 
548
545
  // ---- v0.5 insights:project 级 insight 文档(任务级在 task.insights[]) ----
549
- // 迁移语义(旧版 store 的兼容策略):
550
- // v0.4 experience.json 仍由 remember/forget/query_memory 服务,不删除;
551
- // 首次加载把旧笔记**复制导入** insights.json(kind: experience, source: migrate),
552
- // 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` 也永远留着第二份内容——正是"散"的来源。
553
553
  _loadInsights() {
554
554
  const doc = this._loadJson(path.join(this.dir, INSIGHTS_FILE), null)
555
555
  this.insights = isRecord(doc) && Array.isArray(doc.items)
@@ -564,40 +564,61 @@ export class ProjectMemoryStore {
564
564
  }
565
565
 
566
566
  _migrateExperienceToInsights() {
567
- if (this.insights.migratedAt) return
568
- const legacy = this.experience
569
- if (!Array.isArray(legacy) || legacy.length === 0) return
570
- const now = new Date().toISOString()
571
- 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
+ }
572
574
  let imported = 0
573
- for (const item of legacy) {
574
- if (!item || !item.problem || known.has(item.id)) continue
575
- known.add(item.id)
576
- this.insights.items.push({
577
- id: item.id,
578
- kind: 'experience',
579
- scope: 'project',
580
- title: String(item.problem).slice(0, 120),
581
- problem: item.problem,
582
- solution: item.solution,
583
- files: item.sourceFile ? [item.sourceFile] : [],
584
- symbols: [],
585
- sourceTaskIds: [],
586
- source: 'migrate',
587
- confidence: 1,
588
- hitCount: 0,
589
- createdAt: item.createdAt || now,
590
- updatedAt: item.updatedAt || now,
591
- })
592
- 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
+ }
593
613
  }
594
- this.insights.migratedAt = now
595
- try {
596
- mkdirSync(this.dir, { recursive: true })
597
- writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
598
- } catch (err) {
599
- 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
+ }
600
620
  }
621
+ this.experience = []
601
622
  }
602
623
 
603
624
  insightsDoc() {
@@ -675,7 +696,6 @@ export class ProjectMemoryStore {
675
696
  compacting ||
676
697
  this._dirtyShards.size > 0 ||
677
698
  this._removedShards.size > 0 ||
678
- this._dirtyExperience ||
679
699
  this._dirtyInsights ||
680
700
  this._dirtyTasks ||
681
701
  this._dirtyBinding ||
@@ -718,13 +738,10 @@ export class ProjectMemoryStore {
718
738
  }
719
739
  }
720
740
  this._removedShards.clear()
721
- if (this._dirtyExperience) {
722
- writeJsonAtomic(path.join(this.dir, EXPERIENCE_FILE), this.experience)
723
- this._dirtyExperience = false
724
- }
725
741
  if (this._dirtyInsights) {
726
- // PR3:落盘即把格式标记推到 v2(v1 → v2 是纯增量:只多一个可选的 triggerDerived)
727
- 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
728
745
  writeJsonAtomic(path.join(this.dir, INSIGHTS_FILE), this.insights)
729
746
  this._dirtyInsights = false
730
747
  }
@@ -888,82 +905,17 @@ export class ProjectMemoryStore {
888
905
  return out
889
906
  }
890
907
 
891
- addExperience({ problem, solution, sourceFile }) {
892
- const existing = this.findSupersede(problem)
893
- const now = new Date().toISOString()
894
- if (existing) {
895
- existing.problem = problem
896
- existing.solution = solution
897
- if (sourceFile) existing.sourceFile = sourceFile
898
- existing.updatedAt = now
899
- this._dirtyExperience = true
900
- this._auxVersion++
901
- return { id: existing.id, superseded: true }
902
- }
903
- const id = randomUUID()
904
- this.experience.push({ id, problem, solution, sourceFile, createdAt: now, updatedAt: now })
905
- this.pruneExperience()
906
- this._dirtyExperience = true
907
- this._auxVersion++
908
- return { id, superseded: false }
909
- }
910
-
911
- pruneExperience() {
912
- const indexedFileCount = Object.keys(this.files).length
913
- const max = Math.max(100, Math.min(2000, indexedFileCount * 2))
914
- if (this.experience.length <= max) return 0
915
- const sorted = [...this.experience].sort((a, b) => (a.updatedAt < b.updatedAt ? -1 : 1))
916
- const victims = new Set(sorted.slice(0, this.experience.length - max).map((e) => e.id))
917
- this.experience = this.experience.filter((e) => !victims.has(e.id))
918
- this._auxVersion++
919
- return victims.size
920
- }
921
-
922
- findSupersede(problem) {
923
- const tokens = tokenize(problem)
924
- if (!tokens.length) return null
925
- let best = null
926
- let bestOverlap = 0
927
- for (const item of this.experience) {
928
- const itemTokens = tokenize(item.problem)
929
- const overlap = itemTokens.filter((t) => tokens.includes(t)).length
930
- if (overlap === 0) continue
931
- const ratioQuery = overlap / tokens.length
932
- const ratioItem = overlap / itemTokens.length
933
- if (ratioQuery >= 0.7 && ratioItem >= 0.7 && overlap > bestOverlap) {
934
- best = item
935
- bestOverlap = overlap
936
- }
937
- }
938
- return best
939
- }
940
-
941
- removeExperience(idOrQuery) {
942
- const before = this.experience.length
943
- if (idOrQuery && this.experience.some((item) => item.id === idOrQuery)) {
944
- this.experience = this.experience.filter((item) => item.id !== idOrQuery)
945
- } else {
946
- const tokens = tokenize(idOrQuery)
947
- if (!tokens.length) return 0
948
- this.experience = this.experience.filter((item) => {
949
- const itemTokens = tokenize(`${item.problem} ${item.solution}`)
950
- if (!itemTokens.length) return true
951
- const overlap = itemTokens.filter((t) => tokens.includes(t)).length
952
- return overlap / Math.min(tokens.length, itemTokens.length) < 0.5
953
- })
954
- }
955
- if (this.experience.length !== before) {
956
- this._dirtyExperience = true
957
- this._auxVersion++
958
- }
959
- return before - this.experience.length
960
- }
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` 的导入源。
961
912
 
962
913
  stats() {
963
914
  return {
964
915
  files: Object.keys(this.files).length,
965
916
  entries: this.allEntries().length,
966
- experience: this.experience.length,
917
+ // 经验笔记 = insight 里 kind:'experience' 的那些(含从 v0.4 导入的)。project 级为准。
918
+ experience: this.insights.items.filter((it) => it && it.kind === 'experience').length,
967
919
  tasks: this.tasks.length,
968
920
  tasksActive: this.tasks.filter((t) => !t.archived).length,
969
921
  tasksArchived: this.tasks.filter((t) => t.archived).length,
@@ -1027,11 +979,23 @@ export class ProjectMemoryStore {
1027
979
  }
1028
980
  }
1029
981
 
1030
- /** 每项目任务数上限随项目体积自适应;超限按 lastActiveAt 归档最旧(只统计非归档)。 */
982
+ /**
983
+ * 每项目任务数上限随项目体积自适应;超限按 lastActiveAt 归档最旧(只统计非归档)。
984
+ *
985
+ * **仍被会话绑定的任务不参与裁剪**(这条是修 bug,不是放宽上限):
986
+ * 绑定 = "这个任务还没结束,某个会话随时会回来接着干"。旧实现按 `lastActiveAt` 一刀切,
987
+ * 一个长期挂着的绑定任务会被更新的任务挤到最旧、被静默归档;会话回来写 todo 时,
988
+ * `taskbridge` 把"归档"按"停止同步"处理(那是归档的文档语义),于是**另建一条新任务**——
989
+ * 同一个会话的历史被静默拆成两条记录,原条目变成归档孤儿。
990
+ * 代价是活跃列表可能比上限多出"绑定任务数"条;这是刻意取舍:上限只是启发式,
991
+ * 而"别把用户正在做的任务从脚底下抽走"是正确性。想真正停掉一个任务,先解绑或显式归档。
992
+ * @returns {number} 本轮归档的条数
993
+ */
1031
994
  pruneTasks() {
1032
995
  const fileCount = Object.keys(this.files).length
1033
996
  const maxTasks = Math.min(100, Math.max(5, Math.floor(fileCount / 20)))
1034
- const nonArchived = this.tasks.filter((t) => !t.archived)
997
+ const bound = new Set(Object.values(this.binding || {}))
998
+ const nonArchived = this.tasks.filter((t) => !t.archived && !bound.has(t.id))
1035
999
  if (nonArchived.length <= maxTasks) return 0
1036
1000
  const ts = (t) => new Date(t.lastActiveAt || t.updatedAt || t.createdAt || 0).getTime()
1037
1001
  const sorted = [...nonArchived].sort((a, b) => ts(a) - ts(b))
@@ -1087,7 +1051,8 @@ export function storeOverview(store) {
1087
1051
  return {
1088
1052
  files: Object.keys(store.files).length,
1089
1053
  entries: store.allEntries().length,
1090
- experience: store.experience.length,
1054
+ // 不调 store.stats():overview 也会被喂裸桩(测试/子索引汇总),少一个必需方法就少一处崩点。
1055
+ experience: Array.isArray(store.insights?.items) ? store.insights.items.filter((it) => it && it.kind === 'experience').length : 0,
1091
1056
  latest,
1092
1057
  }
1093
1058
  }
@@ -1,17 +1,44 @@
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, DELETED_KEEP, 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
+ }
10
+
11
+ /**
12
+ * 删除留痕的回报后缀:把留痕文件的**真实路径**直接写进结果。
13
+ *
14
+ * 为什么不只写在工具描述里、而是每次删除都回报:描述是静态文本,说不清项目目录在哪
15
+ * (`memoryDir` 可配、项目根随会话变);而模型要"自己去找"就必须先知道路径。这条不影响
16
+ * 任何判据,只是把地址递到手里。
17
+ * @param {{keptIn?: string[]}} res - removeMemory 的返回
18
+ * @returns {string} 直接拼在删除回报后面的文本(无留痕时为空串)
19
+ */
20
+ function keptHint(res) {
21
+ const files = Array.isArray(res?.keptIn) ? res.keptIn : []
22
+ if (!files.length) return ''
23
+ return `\nLast ${DELETED_KEEP} deleted entries kept for manual recovery (read them to restore, then save again):\n`
24
+ + files.map((f) => `- ${f}`).join('\n')
25
+ }
4
26
 
5
27
  export function forgetTool(config) {
6
28
  return defineTool({
7
29
  name: 'forget',
8
30
  description:
9
- 'Delete experience notes from project memory by id or by matching keywords. Use to clean stale/obsolete notes.',
31
+ 'Delete memories by id or by matching keywords — lessons / decisions / procedures and experience notes, ' +
32
+ 'at task / project / global scope alike (one call, no need to know which layer it lives in). Real deletion, no undo. ' +
33
+ 'An exact id deletes that one entry; keywords match on how much of the query the entry covers. ' +
34
+ 'A keyword that matches more than the configured cap deletes nothing and lists the candidates instead. ' +
35
+ `The ${DELETED_KEEP} most recently deleted entries are kept in that layer's deleted.json next to its store ` +
36
+ '(the path is returned after every deletion) — read it to recover an accidental deletion and save it again.',
10
37
  parameters: {
11
38
  id_or_query: {
12
39
  type: 'string',
13
40
  required: true,
14
- description: 'Experience note id (from remember or query_memory output), or keywords to match.',
41
+ 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
42
  },
16
43
  root: {
17
44
  type: 'string',
@@ -27,10 +54,23 @@ export function forgetTool(config) {
27
54
  assertIndexRoot(root, args.root || root)
28
55
  const memoryDir = memoryRootFor(root, config.memoryDir)
29
56
  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.'
57
+ const cfg = cfgInsight(config)
58
+ const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
59
+ let res
60
+ store.commit((s) => {
61
+ res = removeMemory({ store: s, globalStore, idOrQuery: args.id_or_query, maxMatches: cfg.maxForgetMatches })
62
+ return res
33
63
  })
64
+ globalStore.commit() // global 侧若被删过才落盘
65
+ if (res && res.tooMany) {
66
+ const head = res.matches.slice(0, 10).map(line)
67
+ const more = res.matches.length > head.length ? ` …(共 ${res.matches.length} 条)` : ''
68
+ 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
69
+ }
70
+ if (!res || !res.ok || !res.removed.length) return 'No matching memory found.'
71
+ return `Removed ${res.removed.length} memory entries:\n`
72
+ + res.removed.map((e) => `- ${line(e)}`).join('\n')
73
+ + keptHint(res)
34
74
  },
35
75
  })
36
- }
76
+ }
@@ -6,22 +6,26 @@ import { cfgInsight, saveInsight, defaultGlobalFile, GlobalStore } from '../insi
6
6
  import { ensureGlobalInit } from '../global-seed.js'
7
7
  import { INSIGHT_KINDS, INSIGHT_SCOPES } from '../insight-store.js'
8
8
  import { sessionIdOf } from '../util/task-view.js'
9
+ import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
10
+ import { createWriteCosine } from '../auto-inject.js'
9
11
 
10
12
  export function lessonTool(config) {
11
13
  // 描述预算:这两段以前同时出现在「工具描述」和「参数描述」里,等于付两遍钱。
12
14
  // 现在只在参数上写一次 —— 语义一条没少,只是不再重复。
13
- const kindDesc = 'lesson(踩坑/纠偏, 用 pattern+fix) | decision(选型, choice+reason) | procedure(步骤, steps) | experience(problem→solution, v0.4 兼容);默认 lesson。'
15
+ const kindDesc = 'lesson(踩坑/纠偏, 用 pattern+fix) | decision(选型, choice+reason) | procedure(步骤, steps) | experience(问题→解法,remember 写的形态);默认 lesson。'
14
16
  const scopeDesc =
15
17
  'task(任务私有,随任务归档) | project(项目资产) | global(个人能力库,跨项目);默认 project。' +
16
- '解析顺序:显式 scope > task_id > 当前绑定任务 > project。'
18
+ '解析顺序:显式 scope > task_id > 当前绑定任务 > project。给了 id 时忽略 scope:条目留在原层。'
17
19
  return defineTool({
18
20
  name: 'save_lesson',
19
21
  description:
20
22
  '把一条教训 / 决策 / 流程写进分层记忆(单条 insight)。新的经验优先用它,而不是 remember。' +
21
- '在踩到坑、被纠正、做了值得记住的取舍时调用;日常琐事不要写。' +
22
- '近重复按词重叠 ≥0.7 合并、0.65~0.7 强化;同一 insight 被 2+ 任务命中自动 task→project、3+ →global。' +
23
+ '在踩到坑、被纠正、做了值得记的取舍时调用;日常琐事不要写。' +
24
+ '写入前会与既有记忆比对:相似度 ≥0.9 自动覆盖那一条(旧值留在 prev,可写回);≥0.7 在返回里提示近邻 id。' +
25
+ '发现记错了/过时了:带 id 再调一次就是就地覆盖,不必新写一条;确定该删的用 forget。' +
23
26
  'kind / scope / trigger 的语义见对应参数。',
24
27
  parameters: {
28
+ id: { type: 'string', description: '要就地更新的既有条目 id(来自 query_memory 或上一次写入返回的近邻提示)。给了它只覆盖本次显式传的字段,忽略 scope。' },
25
29
  title: { type: 'string', description: 'One-line title (lesson: the failure pattern; decision: the topic; procedure: the name).' },
26
30
  kind: { type: 'string', enum: INSIGHT_KINDS, description: kindDesc },
27
31
  scope: { type: 'string', enum: INSIGHT_SCOPES, description: scopeDesc },
@@ -89,6 +93,7 @@ export function lessonTool(config) {
89
93
  const taskId = args.task_id || boundTaskId
90
94
 
91
95
  const raw = {
96
+ id: args.id,
92
97
  title: args.title,
93
98
  kind: args.kind,
94
99
  pattern: args.pattern,
@@ -101,23 +106,31 @@ export function lessonTool(config) {
101
106
  symbols: args.symbols,
102
107
  confidence: args.confidence,
103
108
  }
104
- if (!raw.title && !raw.pattern && !raw.choice) {
105
- return truncate(JSON.stringify({ success: false, error: '需要 title / pattern / choice 之一' }), config.maxOutputChars || 8000)
109
+ // 就地更新只要求 id(可以只改一个字段);新建仍然要求有个能当标题的东西。
110
+ if (!args.id && !raw.title && !raw.pattern && !raw.choice) {
111
+ return truncate(JSON.stringify({ success: false, error: '需要 title / pattern / choice 之一(或给 id 做就地更新)' }), config.maxOutputChars || 8000)
106
112
  }
107
113
  if (!INSIGHT_KINDS.includes(raw.kind)) raw.kind = 'lesson'
108
114
 
109
115
  let scope = args.scope
110
116
  if (!scope) scope = taskId ? 'task' : 'project'
111
- if (scope === 'task' && !taskId) {
117
+ if (!args.id && scope === 'task' && !taskId) {
112
118
  return truncate(JSON.stringify({ success: false, error: 'task 级写入需要 task_id(或先 select_task 绑定会话)' }), config.maxOutputChars || 8000)
113
119
  }
114
120
 
115
121
  ensureGlobalInit(config) // 幂等确保 global 文件结构就绪
116
122
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
117
123
 
124
+ // 可选向量层:**没装/没配就是 null**,此时 saveInsight 逐字段退回原来的纯词法行为。
125
+ // 就地更新(给了 id)不需要比对,跳过它可以省掉一次模型加载(~118ms / ~120MB)。
126
+ let cosine = null
127
+ if (!args.id) {
128
+ cosine = await createWriteCosine(config, { storeDir: memoryDir, items: vectorItemsFrom(store, globalStore) })
129
+ }
130
+
118
131
  let result
119
132
  store.commit((s) => {
120
- result = saveInsight({ store: s, globalStore, raw, scope, taskId, cfg, source: 'agent' })
133
+ result = saveInsight({ store: s, globalStore, raw, scope, taskId, cfg, source: 'agent', cosine })
121
134
  return result
122
135
  })
123
136
  // global 变更(global scope 直写或 project 自动提升)单独落盘
@@ -1,6 +1,6 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import path from 'node:path'
3
- import { memoryDirName, memoryRootFor, nestedStoreRoots, resolveSafeIndexRoot } from '../util/fs.js'
3
+ import { assertIndexRoot, memoryDirName, memoryRootFor, nestedStoreRoots, resolveSafeIndexRoot } from '../util/fs.js'
4
4
  import { ProjectMemoryStore, storeOverview } from '../store.js'
5
5
  import { expandQuery } from '../llm.js'
6
6
  import { resolveRoute } from '../llm-route.js'
@@ -66,6 +66,11 @@ export function queryMemoryTool(ctx, config) {
66
66
  },
67
67
  async execute(args, exec) {
68
68
  const root = resolveSafeIndexRoot(exec, args.root, config)
69
+ // 读路径也要验根存在。这条不是洁癖:可选的向量层(leanvec)在空 store 上会建
70
+ // `<root>/.dsh-project-memory/vectors.json`,于是传错一个 root(拼写错误/旧路径)就能
71
+ // 在任意可写位置造出目录和空 store,而回报是"No memory matches"——看起来像"这个项目
72
+ // 没有记忆",用户不会意识到自己查错了地方。与 index_repo/watch_repo 同一道护栏。
73
+ assertIndexRoot(root, args.root || root)
69
74
  // 空查询不是"全部":recallItems 会过滤空串,rankEntriesStreaming 随即返回
70
75
  // entries.slice(0, limit)(任意条目、分数 0),task 分支的 includes('') 更是命中所有任务。
71
76
  if (!String(args.query ?? '').trim()) {
@@ -115,10 +120,14 @@ export function queryMemoryTool(ctx, config) {
115
120
  // 使用记账:检索命中也是"被用到"(活跃度/衰减用得上它,见 recordHit)。查询是热路径
116
121
  // (p50 2.6ms),这里只改内存 + 标脏,**不**强制落盘——注入路径会立即落盘,这条路
117
122
  // 靠下一次自然 save 带上。记账失败绝不影响查询结果。
118
- if (wantInsight) {
123
+ // 经验层同源(kind:'experience' 的 insight),所以两桶都要记:`insightId` 是 insight
124
+ // 适配器带的键,经验桶给的是原始条目,用 `id` 兜底。
125
+ for (const layer of ['insight', 'experience']) {
126
+ if (layer === 'insight' && !wantInsight) continue
127
+ if (layer === 'experience' && !(type === 'all' || type === 'experience')) continue
119
128
  try {
120
- const bucket = recalled.layers.find((l) => l.layer === 'insight')
121
- recordHit({ store, globalStore, ids: (bucket?.hits || []).map((h) => h.item?.insightId) })
129
+ const bucket = recalled.layers.find((l) => l.layer === layer)
130
+ recordHit({ store, globalStore, ids: (bucket?.hits || []).map((h) => h.item?.insightId || h.item?.id) })
122
131
  } catch {
123
132
  /* ignore:记账是旁路 */
124
133
  }
@@ -170,7 +179,9 @@ export function queryMemoryTool(ctx, config) {
170
179
  if (expBucket && expBucket.hits.length) {
171
180
  lines.push(`## Experience (past problems -> solutions)`)
172
181
  for (const { item: e, rel } of expBucket.hits) {
173
- const source = e.sourceFile ? ` (source: ${toAbs(root, e.sourceFile)})` : ''
182
+ // 统一存储后经验条目就是 insight:导入时 source_file 落在 files[0],新写的也走同一处。
183
+ const src = e.sourceFile || (Array.isArray(e.files) ? e.files[0] : '')
184
+ const source = src ? ` (source: ${toAbs(root, src)})` : ''
174
185
  lines.push(
175
186
  `### Problem: ${e.problem} (score: ${Math.round(rel * 100)}, id: ${e.id})\n- solution: ${e.solution}${source}\n- updated: ${e.updatedAt}`,
176
187
  )