@yolk_vat-y/dsh-project-memory 0.6.1 → 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.
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,
@@ -1087,7 +1039,8 @@ export function storeOverview(store) {
1087
1039
  return {
1088
1040
  files: Object.keys(store.files).length,
1089
1041
  entries: store.allEntries().length,
1090
- 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,
1091
1044
  latest,
1092
1045
  }
1093
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
+ }
@@ -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 自动提升)单独落盘
@@ -115,10 +115,14 @@ export function queryMemoryTool(ctx, config) {
115
115
  // 使用记账:检索命中也是"被用到"(活跃度/衰减用得上它,见 recordHit)。查询是热路径
116
116
  // (p50 2.6ms),这里只改内存 + 标脏,**不**强制落盘——注入路径会立即落盘,这条路
117
117
  // 靠下一次自然 save 带上。记账失败绝不影响查询结果。
118
- if (wantInsight) {
118
+ // 经验层同源(kind:'experience' 的 insight),所以两桶都要记:`insightId` 是 insight
119
+ // 适配器带的键,经验桶给的是原始条目,用 `id` 兜底。
120
+ for (const layer of ['insight', 'experience']) {
121
+ if (layer === 'insight' && !wantInsight) continue
122
+ if (layer === 'experience' && !(type === 'all' || type === 'experience')) continue
119
123
  try {
120
- const bucket = recalled.layers.find((l) => l.layer === 'insight')
121
- recordHit({ store, globalStore, ids: (bucket?.hits || []).map((h) => h.item?.insightId) })
124
+ const bucket = recalled.layers.find((l) => l.layer === layer)
125
+ recordHit({ store, globalStore, ids: (bucket?.hits || []).map((h) => h.item?.insightId || h.item?.id) })
122
126
  } catch {
123
127
  /* ignore:记账是旁路 */
124
128
  }
@@ -170,7 +174,9 @@ export function queryMemoryTool(ctx, config) {
170
174
  if (expBucket && expBucket.hits.length) {
171
175
  lines.push(`## Experience (past problems -> solutions)`)
172
176
  for (const { item: e, rel } of expBucket.hits) {
173
- const source = e.sourceFile ? ` (source: ${toAbs(root, e.sourceFile)})` : ''
177
+ // 统一存储后经验条目就是 insight:导入时 source_file 落在 files[0],新写的也走同一处。
178
+ const src = e.sourceFile || (Array.isArray(e.files) ? e.files[0] : '')
179
+ const source = src ? ` (source: ${toAbs(root, src)})` : ''
174
180
  lines.push(
175
181
  `### Problem: ${e.problem} (score: ${Math.round(rel * 100)}, id: ${e.id})\n- solution: ${e.solution}${source}\n- updated: ${e.updatedAt}`,
176
182
  )
@@ -1,16 +1,19 @@
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, saveInsight, GlobalStore, defaultGlobalFile } from '../insight-store.js'
5
+ import { ensureGlobalInit } from '../global-seed.js'
6
+ import { vectorItemsFrom } from '../vector-index.js'
7
+ import { createWriteCosine } from '../auto-inject.js'
4
8
 
5
9
  export function rememberTool(config) {
6
10
  return defineTool({
7
11
  name: 'remember',
8
12
  description:
9
13
  'Save an experience note (problem -> solution) into project memory, e.g. a bug you just fixed. ' +
10
- 'Retrieved later only when query_memory matches the problem, never auto-injected. ' +
11
- 'A note for a similar problem is superseded instead of duplicated. ' +
12
- 'This writes the standalone experience file: for lessons / decisions / procedures prefer save_lesson ' +
13
- '(the tiered insight store) — query_memory searches both.',
14
+ 'It lands as a `kind:experience` entry in the same store as lessons / decisions / procedures, so query_memory ' +
15
+ 'finds it and the same dedup applies (near-identical writes merge, similar ones report the nearest id). ' +
16
+ 'Prefer save_lesson for anything that is not a problem->solution note.',
14
17
  parameters: {
15
18
  problem: {
16
19
  type: 'string',
@@ -41,16 +44,29 @@ export function rememberTool(config) {
41
44
  assertIndexRoot(root, args.root || root)
42
45
  const memoryDir = memoryRootFor(root, config.memoryDir)
43
46
  const store = new ProjectMemoryStore(memoryDir).load()
44
- return store.commit((s) => {
45
- const result = s.addExperience({
46
- problem: args.problem,
47
- solution: args.solution,
48
- sourceFile: args.source_file,
49
- })
50
- return result.superseded
51
- ? `Updated existing experience note (${result.id}).`
52
- : `Saved experience note (${result.id}).`
47
+ const cfg = cfgInsight(config)
48
+ ensureGlobalInit(config) // 幂等:project 写入可能被自动提升到 global
49
+ const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
50
+ // 与 save_lesson 同一条写入路径 ⇒ 同一套去重/自动覆盖/近邻提示;没装 leanvec 时 `cosine` 为 null,
51
+ // 退回纯词法(与旧版经验层行为一致)。
52
+ const cosine = await createWriteCosine(config, { storeDir: memoryDir, items: vectorItemsFrom(store, globalStore) })
53
+ const raw = {
54
+ title: args.problem,
55
+ kind: 'experience',
56
+ problem: args.problem,
57
+ solution: args.solution,
58
+ files: args.source_file ? [args.source_file] : undefined,
59
+ confidence: 1,
60
+ }
61
+ let result
62
+ store.commit((s) => {
63
+ result = saveInsight({ store: s, globalStore, raw, scope: 'project', cfg, source: 'agent', cosine })
64
+ return result
53
65
  })
66
+ globalStore.commit()
67
+ if (!result || !result.ok) return `Failed: ${result?.error || '写入未完成'}`
68
+ const verb = result.action === 'created' ? 'Saved' : 'Updated existing'
69
+ return `${verb} experience note (${result.id}).${result.hint ? ` ${result.hint}` : ''}`
54
70
  },
55
71
  })
56
- }
72
+ }
package/src/types.js CHANGED
@@ -4,7 +4,8 @@
4
4
  /**
5
5
  * @typedef {'lesson' | 'decision' | 'procedure' | 'experience'} InsightKind
6
6
  * lesson: 曾踩坑/纠偏(pattern→fix);decision: 曾权衡的选型(topic→choice+reason);
7
- * procedure: 多步操作指南(steps);experience: v0.4 旧笔记迁移而来(problem→solution)。
7
+ * procedure: 多步操作指南(steps);experience: 问题→解法笔记(`remember` 写的就是它,
8
+ * v0.4 experience.json 在加载时导入成同一实体,不再有第二个存储)。
8
9
  *
9
10
  * @typedef {'task' | 'project' | 'global'} InsightScope
10
11
  * task: tasks.json 内嵌于任务实体 task.insights[](私有草稿);
@@ -35,6 +36,8 @@
35
36
  * @property {number} [confidence] 0..1
36
37
  * @property {number} [hitCount] 被注入/命中的次数(强化信号,无 LLM)
37
38
  * @property {string} [lastHitAt] 最近一次命中时间 ISO(衰减/归档依据)
39
+ * @property {object} [prev] 被自动覆盖/就地更新挤掉的**上一个**值(按字段名),只留一版:
40
+ * 误覆盖后用同一个 id 再写一次即可写回;不是历史(不做折叠、不压实)
38
41
  * @property {boolean} [archived] 归档 = 软删:不进召回/注入,可恢复
39
42
  * @property {string[]} [tags]
40
43
  * @property {string} createdAt
@@ -45,6 +48,10 @@
45
48
  * @typedef {object} InsightConfig
46
49
  * @property {number} [dedupOverlap] 双向 token overlap 阈值(≥ 合并/取代)
47
50
  * @property {number} [reinforceBand] 近重复强化带下界(0.65~dedupOverlap → 强化)
51
+ * @property {number} [autoMergeCos] 向量余弦自动覆盖带(默认 0.9,需 leanvec;无向量则不用)
52
+ * @property {number} [autoMergeMargin] 自动覆盖还要求第一名领先第二名这么多(默认 0.05)
53
+ * @property {number} [hintCos] 向量近邻提示带(默认 0.7,只在返回文本里提示 id,不改数据)
54
+ * @property {number} [maxForgetMatches] forget 关键词删除的命中上限(默认 10);超了一条都不删,只回报候选
48
55
  * @property {number} [maxProject] project insights 容量(归档区另计)
49
56
  * @property {number} [maxGlobalProcedures] global insights 容量
50
57
  * @property {number} [promoteConfidence] 提升 project 所需最低 confidence
package/src/util/fs.js CHANGED
@@ -6,6 +6,7 @@ import { readFile } from 'node:fs/promises'
6
6
  import { createHash } from 'node:crypto'
7
7
  import os from 'node:os'
8
8
  import path from 'node:path'
9
+ import { sessionWorkingDir } from './session-dir.js'
9
10
 
10
11
  /**
11
12
  * 原子写 JSON:先写同目录的 `<file>.<pid>.tmp`,再 rename 覆盖目标。
@@ -542,7 +543,8 @@ export function assertSafeRoot(root, { requested = root, allowUnsafe = false } =
542
543
 
543
544
  export function resolveIndexRoot(exec, explicitRoot) {
544
545
  if (explicitRoot && explicitRoot.trim()) return path.resolve(explicitRoot)
545
- const sessionCwd = exec?.agent?.session?.header?.cwd
546
+ // 会话当前工作目录:0.2.1+ 读 workingDirectory 投影(cd 后会变),老宿主回退 header.cwd。
547
+ const sessionCwd = sessionWorkingDir(exec?.agent?.session, { agent: exec?.agent })
546
548
  if (sessionCwd) return path.resolve(sessionCwd)
547
549
  return path.resolve(process.cwd())
548
550
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * 会话「当前工作目录」的唯一取值口。
3
+ *
4
+ * 为什么需要它:dsh 0.2.1 引入了 `@deepseek-ai/dsh-working-directory`,把**当前执行目录**
5
+ * 从 `Session.header.cwd` 里拆了出去——`header.cwd` 现在只表示「原始项目身份 / 权限根」,
6
+ * `working_directory({cd})` 改的是会话投影 `workingDirectory`,**不写回 header**。
7
+ * 本插件的全部根解析(索引 / 检索 / 懒索引 / 审计注入 / 任务桥 / watch)用的都是「人明确
8
+ * 选择的工作位置」这层语义(见 util/fs.js 的根推导注释),所以必须跟着这条新权威走,
9
+ * 否则用户 cd 到另一个项目后,记忆仍落在原项目的 store 上(不报错,只是静默错根)。
10
+ *
11
+ * 兼容策略:新服务用 `ctx.get()` **软探测**——它既不在插件的顶层 inject 里(那是装配期
12
+ * 门控,缺一项插件就整个不挂载),在老宿主(< 0.2.1)上也根本不存在;两者都回退到
13
+ * `header.cwd`,也就是该服务出现之前"当前工作目录"的存放位置。
14
+ */
15
+
16
+ /**
17
+ * 读该会话的当前工作目录。
18
+ *
19
+ * 取值顺序(前者只在真的可用时才生效):
20
+ * 1. `workingDirectory.get(session)` —— 0.2.1+ 的权威。该投影的 `init` 就是
21
+ * `header => header.cwd ?? null`,所以**没 cd 过时它与 header.cwd 恒等**,
22
+ * 本函数对既有行为是 no-op;cd 过才返回改写后的目录。
23
+ * 2. `session.header.cwd` —— 服务缺失(老宿主)或会话不是宿主 Session 时的回退。
24
+ * 3. `agent.session.header.cwd` —— 会话对象与服务都拿不到时的最后回退。
25
+ *
26
+ * 全程不抛出:根解析在审计 / 注入等旁路里被调用,那里读不到目录只应降级,不应带崩调用方。
27
+ * @param {object|null} [session] - 宿主 Session(`workingDirectory.get` 需要它)。
28
+ * @param {{agent?: object, ctx?: object}} [opts] - `agent` 提供 `agent.ctx` 回退;`ctx` 直接指定宿主上下文(任务桥这类只有 ctx 的地方)。
29
+ * @returns {string|undefined} 绝对目录;都取不到时 undefined。
30
+ */
31
+ export function sessionWorkingDir(session, opts = {}) {
32
+ const agent = opts.agent
33
+ const target = session || agent?.session || null
34
+ const host = opts.ctx || agent?.ctx || null
35
+
36
+ try {
37
+ const svc = host && typeof host.get === 'function' ? host.get('workingDirectory') : null
38
+ if (svc && typeof svc.get === 'function' && target) {
39
+ const dir = svc.get(target)
40
+ if (typeof dir === 'string' && dir) return dir
41
+ }
42
+ } catch {
43
+ // 老宿主没有该服务;或 session 不是宿主认识的 Session——两种情况都走 header 回退。
44
+ }
45
+
46
+ const cwd = target?.header?.cwd ?? agent?.session?.header?.cwd
47
+ return typeof cwd === 'string' && cwd ? cwd : undefined
48
+ }
@@ -172,14 +172,15 @@ export function openVectorIndex({ dir = null, items = [], embed, model, dim = DI
172
172
  }
173
173
 
174
174
  /**
175
- * 从两个 store 收集**要建索引的条目**:洞察层(项目 + 全局)+ 经验层。
175
+ * 从两个 store 收集**要建索引的条目**:洞察层(项目 + 全局)。
176
176
  * 与提示通道/召回看到的池子同源;归档条目不进(它们不会被召回)。
177
+ * v0.4 的经验笔记也在里面——统一存储后它们是 `kind:'experience'` 的 insight,
178
+ * 加载时已从 experience.json 导入,不再有第二个池子。
177
179
  */
178
180
  export function vectorItemsFrom(store, globalStore) {
179
181
  const out = []
180
182
  try { if (typeof store?.insightItems === 'function') out.push(...store.insightItems()) } catch { /* store 形状不保证 */ }
181
183
  try { if (typeof globalStore?.items === 'function') out.push(...globalStore.items()) } catch { /* 同上 */ }
182
- try { if (Array.isArray(store?.experience)) out.push(...store.experience) } catch { /* 同上 */ }
183
184
  return out.filter((it) => it && !it.archived)
184
185
  }
185
186