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

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.
@@ -1,7 +1,7 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import path from 'node:path'
3
3
  import { statSync } from 'node:fs'
4
- import { assertIndexRoot, assertSafeRoot, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey, walkDir } from '../util/fs.js'
4
+ import { assertIndexRoot, assertSafeRoot, listProjectFiles, memoryDirName, memoryRootFor, relativePath, scanLimits, storeKey } from '../util/fs.js'
5
5
  import { DROP, OVERSIZE, UNCHANGED, commitFileUpdates, fileKind, planFileIndex, toFileUpdate } from '../index-pipeline.js'
6
6
  import { ProjectMemoryStore } from '../store.js'
7
7
  import { onFileIndexed, isTypeScriptFile, enhanceQueueStats } from '../enhancer.js'
@@ -38,7 +38,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
38
38
  batch = []
39
39
  }
40
40
 
41
- const { files, truncated, capped, skipped: nestedRoots, unreadable } = walkDir(root, {
41
+ const { files, truncated, capped, skipped: nestedRoots, unreadable } = listProjectFiles(root, {
42
42
  ...scanLimits(config),
43
43
  nestedStoreName: memoryDirName(config),
44
44
  })
@@ -87,7 +87,7 @@ export async function indexRepository(ctx, config, root, { reindex = false, allo
87
87
  const stats = store.stats()
88
88
  let report =
89
89
  `Indexed project: ${root}\n` +
90
- `docs indexed: ${indexed}, code symbols updated: ${updated}, unchanged skipped: ${skipped}, removed: ${removed}\n` +
90
+ `docs indexed: ${indexed}, code files updated: ${updated}, unchanged skipped: ${skipped}, removed: ${removed}\n` +
91
91
  `memory store: ${stats.files} files, ${stats.entries} entries, ${stats.experience} experience notes`
92
92
  if (unreadable.length) {
93
93
  const rels = unreadable.map((p) => storeKey(relativePath(root, p)))
@@ -131,19 +131,17 @@ export function indexRepoTool(ctx, config) {
131
131
  return defineTool({
132
132
  name: 'index_repo',
133
133
  description:
134
- 'Index a whole project into persistent memory. Documents (PDF/Markdown/txt) get a short cited summary plus ' +
135
- 'a full-chunk literal term index (no LLM at index time); ' +
136
- 'code files get a zero-token symbol table (function/class names with line numbers). Incremental: only changed ' +
137
- 'files are re-extracted (content-hash), deleted files are removed from memory. Call once per project, then query_memory.',
134
+ 'Index a project into memory (docs + code symbols), incremental by content hash. '
135
+ + 'Call once per project, then query_memory.',
138
136
  parameters: {
139
137
  root: {
140
138
  type: 'string',
141
139
  required: true,
142
- description: '要索引的项目根目录(绝对路径)。',
140
+ description: '项目根(绝对路径)',
143
141
  },
144
142
  reindex: {
145
143
  type: 'boolean',
146
- description: 'Force full re-index, ignoring content-hash skips. Default false.',
144
+ description: '忽略哈希,强制重抽',
147
145
  },
148
146
  },
149
147
  output: {
@@ -155,8 +153,9 @@ export function indexRepoTool(ctx, config) {
155
153
  // 透传原始入参:Windows 风格路径在 POSIX 上会被 resolve 成 <cwd>/D:\...,
156
154
  // 报错时要点明这是路径风格问题,而不是“目录被删了”。
157
155
  assertIndexRoot(root, args.root)
158
- assertSafeRoot(root, { requested: args.root, allowUnsafe: config?.allowUnsafeRoots === true })
159
- return indexRepository(ctx, config, root, { reindex: Boolean(args.reindex) })
156
+ const allowUnsafe = config?.allowUnsafeRoots === true
157
+ assertSafeRoot(root, { requested: args.root, allowUnsafe })
158
+ return indexRepository(ctx, config, root, { reindex: Boolean(args.reindex), allowUnsafe })
160
159
  },
161
160
  })
162
161
  }
@@ -10,30 +10,24 @@ import { createVectorRerank, vectorItemsFrom } from '../vector-index.js'
10
10
  import { createWriteCosine } from '../auto-inject.js'
11
11
 
12
12
  export function lessonTool(config) {
13
- // 描述预算:这两段以前同时出现在「工具描述」和「参数描述」里,等于付两遍钱。
14
- // 现在只在参数上写一次 —— 语义一条没少,只是不再重复。
15
- const kindDesc = 'lesson(踩坑/纠偏, 用 pattern+fix) | decision(选型, choice+reason) | procedure(步骤, steps) | experience(问题→解法,remember 写的形态);默认 lesson。'
13
+ const kindDesc = 'lesson(坑→改法) | decision(选择+理由) | procedure(步骤) | experience(问题→解法);默认 lesson。'
16
14
  const scopeDesc =
17
- 'task(任务私有,随任务归档) | project(项目资产) | global(个人能力库,跨项目);默认 project。' +
18
- '解析顺序:显式 scope > task_id > 当前绑定任务 > project。给了 id 时忽略 scope:条目留在原层。'
15
+ 'task(任务私有) | project(项目资产) | global(跨项目);默认 project;给 id 时就地更新。'
19
16
  return defineTool({
20
17
  name: 'save_lesson',
21
18
  description:
22
- '把一条教训 / 决策 / 流程写进分层记忆(单条 insight)。新的经验优先用它,而不是 remember。' +
23
- '在踩到坑、被纠正、做了值得记的取舍时调用;日常琐事不要写。' +
24
- '写入前会与既有记忆比对:相似度 ≥0.9 自动覆盖那一条(旧值留在 prev,可写回);≥0.7 在返回里提示近邻 id。' +
25
- '发现记错了/过时了:带 id 再调一次就是就地覆盖,不必新写一条;确定该删的用 forget。' +
26
- 'kind / scope / trigger 的语义见对应参数。',
19
+ '写入一条教训 / 决策 / 流程(单条 insight)。写入前与既有记忆比对:高相似度自动覆盖(旧值留在 prev),'
20
+ + '较近的提示近邻 id。发现记错/过时:带 id 再写一次即就地覆盖;确定要删用 forget。',
27
21
  parameters: {
28
- id: { type: 'string', description: '要就地更新的既有条目 id(来自 query_memory 或上一次写入返回的近邻提示)。给了它只覆盖本次显式传的字段,忽略 scope。' },
29
- title: { type: 'string', description: 'One-line title (lesson: the failure pattern; decision: the topic; procedure: the name).' },
22
+ id: { type: 'string', description: '既有条目 id(就地更新,忽略 scope)' },
23
+ title: { type: 'string', description: '一行标题' },
30
24
  kind: { type: 'string', enum: INSIGHT_KINDS, description: kindDesc },
31
25
  scope: { type: 'string', enum: INSIGHT_SCOPES, description: scopeDesc },
32
- pattern: { type: 'string', description: 'kind=lesson: 具体错误模式(同 title 时二选一)' },
33
- fix: { type: 'string', description: 'kind=lesson: 修正做法' },
34
- choice: { type: 'string', description: 'kind=decision: 选了什么' },
35
- reason: { type: 'string', description: 'kind=decision: 为什么(权衡点)' },
36
- steps: { type: 'array', items: { type: 'string' }, description: 'kind=procedure: 有序步骤(未来静默注入的正文)' },
26
+ pattern: { type: 'string', description: '错误模式' },
27
+ fix: { type: 'string', description: '修正做法' },
28
+ choice: { type: 'string', description: '选了什么' },
29
+ reason: { type: 'string', description: '为什么' },
30
+ steps: { type: 'array', items: { type: 'string' }, description: '有序步骤' },
37
31
  trigger: {
38
32
  type: 'object',
39
33
  additionalProperties: false,
@@ -42,9 +36,9 @@ export function lessonTool(config) {
42
36
  type: 'object',
43
37
  additionalProperties: false,
44
38
  properties: {
45
- ops: { type: 'array', items: { type: 'string' }, description: '归一动作 id:file-write / file-delete / shell-run / git-commit / git-push / release / npm-publish / deploy / migrate / render-doc / index-doc / read-image / fetch-web / run-bench / query-memory。' },
46
- writes: { type: 'array', items: { type: 'string' }, description: '本次要【写】的项目相对路径(禁扩展名/泛名 glob)。' },
47
- intents: { type: 'array', items: { type: 'string' }, description: '人类消息里剥离引用后的意图词(CJK ≥2 字、拉丁 ≥5 字符且不含 _ . /)。' },
39
+ ops: { type: 'array', items: { type: 'string' }, description: 'file-write|file-delete|shell-run|git-commit|git-push|release|npm-publish|deploy|migrate|render-doc|index-doc|read-image|fetch-web|run-bench|query-memory' },
40
+ writes: { type: 'array', items: { type: 'string' }, description: '项目相对路径,禁 glob' },
41
+ intents: { type: 'array', items: { type: 'string' }, description: '意图词(CJK≥2,拉丁≥5)' },
48
42
  },
49
43
  description: '唯一触发面:三者取或。',
50
44
  },
@@ -52,32 +46,28 @@ export function lessonTool(config) {
52
46
  type: 'object',
53
47
  additionalProperties: false,
54
48
  properties: {
55
- paths: { type: 'array', items: { type: 'string' }, description: '收窄:写目标必须命中其中之一(自己不能触发)。' },
49
+ paths: { type: 'array', items: { type: 'string' }, description: '写目标须命中其一' },
56
50
  not_paths: { type: 'array', items: { type: 'string' } },
57
- hosts: { type: 'array', items: { type: 'string' }, description: '例如 wsl(命令里出现 /mnt/* 或 powershell.exe)。' },
58
- tags: { type: 'array', items: { type: 'string' }, description: '项目画像 tag 交集(画像未知时不过滤)。' },
51
+ hosts: { type: 'array', items: { type: 'string' }, description: '如 wsl' },
52
+ tags: { type: 'array', items: { type: 'string' }, description: '画像 tag 交集' },
59
53
  },
60
- description: '收窄条件:全部满足才注入。',
54
+ description: '收窄条件:全部满足才放行。',
61
55
  },
62
- prevents: { type: 'string', description: '准入条件:不知道这条,这一步会做错什么;写不出来就不该自动注入。' },
63
- // 旧字段:只为兼容历史条目与旧调用而保留 schema 形状,描述不再占 prompt 预算。
64
- // 语义(keywords→intents 与召回排序、actions→when.ops、paths→when.writes、scope→画像 tag)
65
- // 见 README「save_lesson」与 autoContext.legacyScope。
56
+ prevents: { type: 'string', description: '不知道它会做错什么' },
57
+ // 旧字段:历史条目与旧调用仍可能带它们,保留形状但不占描述预算。
66
58
  keywords: { type: 'array', items: { type: 'string' } },
67
59
  symbols: { type: 'array', items: { type: 'string' } },
68
60
  actions: { type: 'array', items: { type: 'string' } },
69
61
  paths: { type: 'array', items: { type: 'string' } },
70
62
  scope: { type: 'array', items: { type: 'string' } },
71
63
  },
72
- description:
73
- 'authored trigger:命中即在动手前确定性注入。when 是唯一触发面(ops / writes / intents 取或),' +
74
- 'guard 只能收窄,没有 when 的条目不会自动推送。',
64
+ description: '命中即在动手前注入;when 是唯一触发面,guard 只能收窄。',
75
65
  },
76
- task_id: { type: 'string', description: '目标任务 id(scope 缺省时优先于绑定任务)' },
77
- files: { type: 'array', items: { type: 'string' }, description: '关联文件(项目相对路径)' },
66
+ task_id: { type: 'string', description: '目标任务 id' },
67
+ files: { type: 'array', items: { type: 'string' }, description: '关联文件(项目相对)' },
78
68
  symbols: { type: 'array', items: { type: 'string' }, description: '关联符号' },
79
- confidence: { type: 'number', description: '置信 0..1(默认 0.8)' },
80
- root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
69
+ confidence: { type: 'number', description: '0..1' },
70
+ root: { type: 'string', description: '项目根' },
81
71
  },
82
72
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
83
73
  async execute(args, exec) {
@@ -31,33 +31,54 @@ function nestedIndexNote(root, config) {
31
31
  )
32
32
  }
33
33
 
34
+ /**
35
+ * 一段结果里最佳条目的跨层排序分(`rel × 层先验`,与 `recallItems` 返回的 `flat.hint`
36
+ * 同一口径)。只用于决定段落先后,不参与打分,也不改变任何条目自身的 score。
37
+ */
38
+ function bestHint(hits) {
39
+ let best = 0
40
+ for (const h of hits || []) best = Math.max(best, (h.rel || 0) * (h.prior || 1))
41
+ return best
42
+ }
43
+
44
+ /** 被覆盖字段的上一版:只显示一行,方便模型判断是否写回;空槽不占位。 */
45
+ function previousLine(item) {
46
+ if (!item || !item.prev || typeof item.prev !== 'object' || Array.isArray(item.prev)) return ''
47
+ const parts = []
48
+ for (const [key, value] of Object.entries(item.prev)) {
49
+ if (value === undefined || value === null || value === '') continue
50
+ const raw = typeof value === 'string' ? value : JSON.stringify(value)
51
+ const text = raw ? raw.replace(/\s+/g, ' ').trim() : ''
52
+ if (!text) continue
53
+ parts.push(`${key}=${text}`)
54
+ }
55
+ return parts.length ? parts.join('; ').slice(0, 300) : ''
56
+ }
57
+
34
58
  export function queryMemoryTool(ctx, config) {
35
59
  return defineTool({
36
60
  name: 'query_memory',
37
61
  description:
38
- 'Search persistent project memory: doc summaries and code symbol tables (indexed via index_doc/index_repo), ' +
39
- 'experience notes (problem -> solution, saved via remember) and insights (lessons / decisions / procedures, ' +
40
- 'saved via save_lesson). Every hit returns its source path and line, or its insight id, so you can verify. ' +
41
- 'Docs are cross-linked to the code symbols they mention. ' +
42
- 'Use BEFORE grepping when you need orientation, a spec constraint, or a past decision.',
62
+ 'Search project memory: docs, symbols, experience and insights. Returns cited sources or insight ids. '
63
+ + 'Use before grepping for orientation, a spec constraint, or a past decision.',
43
64
  parameters: {
44
65
  query: {
45
66
  type: 'string',
46
67
  required: true,
47
- description: 'What to look for, e.g. "payment module fees", "who handles refunds", "spec constraint on timeouts".',
68
+ description: 'What to look for',
48
69
  },
49
70
  root: {
50
71
  type: 'string',
51
- description: '搜索用的项目根目录,默认当前工作目录。',
72
+ description: '项目根(默认当前工作目录)',
52
73
  },
53
74
  type: {
54
75
  type: 'string',
55
76
  enum: ['all', 'doc', 'symbol', 'experience', 'insight', 'task'],
56
- description: 'Which memory layer to search. Default "all". "insight" searches lessons / decisions / procedures; "task" searches task records.',
77
+ description: 'all|doc|symbol|experience|insight|task;默认 all',
57
78
  },
58
79
  limit: {
59
80
  type: 'number',
60
- description: 'Max results to return. Default 8.',
81
+ description: '最多返回条数,默认 8',
61
82
  },
62
83
  },
63
84
  output: {
@@ -117,6 +138,8 @@ export function queryMemoryTool(ctx, config) {
117
138
  })
118
139
 
119
140
  const lines = []
141
+ // 结果段先按相关性排序,最后再拼进 lines(见下方 sections.sort)。
142
+ const sections = []
120
143
  // 使用记账:检索命中也是"被用到"(活跃度/衰减用得上它,见 recordHit)。查询是热路径
121
144
  // (p50 2.6ms),这里只改内存 + 标脏,**不**强制落盘——注入路径会立即落盘,这条路
122
145
  // 靠下一次自然 save 带上。记账失败绝不影响查询结果。
@@ -133,62 +156,92 @@ export function queryMemoryTool(ctx, config) {
133
156
  }
134
157
  }
135
158
  if (wantMemory) {
136
- // doc/symbol 同源同尺度:合并后按加权分排序(规范段提权已计入 weightedScore)
137
- const memHits = recalled.layers
138
- .filter((l) => l.layer === 'doc' || l.layer === 'symbol')
139
- .flatMap((l) => l.hits)
140
- .sort((a, b) => b.weightedScore - a.weightedScore)
141
- .slice(0, limit)
159
+ // doc/symbol 的原始 BM25 分不可直接比:符号正文短,同等相关时分会更高/更低,
160
+ // 用原始分排序会让一层把另一层整体挤掉。先按**层内相对分 rel** 排序,并在
161
+ // limit≥2 时各保留一条,剩余名额再按 rel 填。
162
+ const docHits = recalled.layers.find((l) => l.layer === 'doc')?.hits || []
163
+ const symbolHits = recalled.layers.find((l) => l.layer === 'symbol')?.hits || []
164
+ const byRel = (a, b) => (b.rel || 0) - (a.rel || 0) || (b.weightedScore || 0) - (a.weightedScore || 0)
165
+ const merged = [...docHits, ...symbolHits].sort(byRel)
166
+ const picked = []
167
+ const seenHits = new Set()
168
+ const take = (h) => {
169
+ if (!h || picked.length >= limit) return
170
+ const key = h.item?.id || `${h.item?.type}:${h.item?.title}`
171
+ if (seenHits.has(key)) return
172
+ seenHits.add(key)
173
+ picked.push(h)
174
+ }
175
+ if (limit >= 2) {
176
+ for (const h of [docHits[0], symbolHits[0]].filter(Boolean).sort(byRel)) take(h)
177
+ }
178
+ for (const h of merged) take(h)
179
+ const memHits = picked
142
180
  memHitCount = memHits.length
143
181
  if (memHits.length) {
144
- const top = memHits[0].weightedScore || 1
145
- lines.push(`## Memory (${type === 'all' ? 'docs + symbols' : type})`)
146
- for (const { item: e, weightedScore } of memHits) {
182
+ const block = [`## Memory (${type === 'all' ? 'docs + symbols' : type})`]
183
+ for (const { item: e, rel } of memHits) {
147
184
  const absSource = e.sourceLine ? `${toAbs(root, e.sourcePath)}:${e.sourceLine}` : toAbs(root, e.sourcePath)
148
- const rel = Math.round((weightedScore / top) * 100)
149
- const summaryLine = `- ${e.summary}`
185
+ const score = Math.round((rel || 0) * 100)
186
+ // 符号没有 summary:它的正文就是一行声明。缺正文时退到标题,绝不输出 `- undefined`。
187
+ const body = e.type === 'symbol' ? (e.text || e.title) : e.summary
188
+ const summaryLine = body ? `\n- ${body}` : ''
150
189
  // 条目状态占位(可证伪状态机落地前恒为 exact)。
151
190
  // 先立字段,后续状态机到位时只改值、不改输出契约。
152
- lines.push(`### ${e.title} (score: ${rel})\n- source: ${absSource}\n- status: ${e.status || 'exact'}\n${summaryLine}`)
191
+ block.push(`### ${e.title} (score: ${score})\n- source: ${absSource}\n- status: ${e.status || 'exact'}${summaryLine}`)
153
192
  if (e.type === 'doc') {
154
193
  // 读取期解算:链接不落盘,按当前符号表排序取前 5(见 src/link.js)
155
194
  const refs = resolveLinkedSymbols(store, e, 5).map(
156
195
  (s) => `${s.title} @ ${toAbs(root, s.sourcePath)}:${s.sourceLine}`,
157
196
  )
158
- if (refs.length) lines.push(`- references: ${refs.join('; ')}`)
197
+ if (refs.length) block.push(`- references: ${refs.join('; ')}`)
159
198
  }
160
199
  }
200
+ sections.push({ block, best: bestHint(memHits) })
161
201
  }
162
202
  }
163
203
  if (wantInsight) {
164
204
  const bucket = recalled.layers.find((l) => l.layer === 'insight')
165
205
  if (bucket && bucket.hits.length) {
166
- lines.push('## Insights (lessons / decisions / procedures)')
206
+ const block = ['## Insights (lessons / decisions / procedures)']
167
207
  for (const { item: e, rel } of bucket.hits) {
168
208
  const scope = e.scope ? `, scope: ${e.scope}` : ''
169
209
  const files = e.files && e.files.length ? `\n- files: ${e.files.map((f) => toAbs(root, f)).join(', ')}` : ''
170
210
  const conf = typeof e.confidence === 'number' ? `\n- confidence: ${e.confidence}` : ''
171
- lines.push(
172
- `### ${e.title} (score: ${Math.round(rel * 100)}, kind: ${e.kind}${scope}, id: ${e.insightId})\n- ${e.summary}${files}${conf}`,
211
+ const previous = previousLine(e)
212
+ block.push(
213
+ `### ${e.title} (score: ${Math.round(rel * 100)}, kind: ${e.kind}${scope}, id: ${e.insightId})\n- ${e.summary}${files}${conf}${previous ? `\n- previous: ${previous}` : ''}`,
173
214
  )
174
215
  }
216
+ sections.push({ block, best: bestHint(bucket.hits) })
175
217
  }
176
218
  }
177
219
  if (type === 'all' || type === 'experience') {
178
220
  const expBucket = recalled.layers.find((l) => l.layer === 'experience')
179
221
  if (expBucket && expBucket.hits.length) {
180
- lines.push(`## Experience (past problems -> solutions)`)
222
+ const block = ['## Experience (past problems -> solutions)']
181
223
  for (const { item: e, rel } of expBucket.hits) {
182
224
  // 统一存储后经验条目就是 insight:导入时 source_file 落在 files[0],新写的也走同一处。
183
225
  const src = e.sourceFile || (Array.isArray(e.files) ? e.files[0] : '')
184
226
  const source = src ? ` (source: ${toAbs(root, src)})` : ''
185
- lines.push(
186
- `### Problem: ${e.problem} (score: ${Math.round(rel * 100)}, id: ${e.id})\n- solution: ${e.solution}${source}\n- updated: ${e.updatedAt}`,
227
+ // `problem`/`solution` 只是 v0.4 的字段形状:`save_lesson` 写 kind:'experience'
228
+ // 时没有这两个参数(正文在 fix/choice/body 里),直接用会渲染出 `undefined`。
229
+ const problem = e.problem || e.title || '(untitled)'
230
+ const solution = e.solution || e.fix || e.choice || e.body || '(no text)'
231
+ block.push(
232
+ `### Problem: ${problem} (score: ${Math.round(rel * 100)}, id: ${e.id})\n- solution: ${solution}${source}\n- updated: ${e.updatedAt}`,
187
233
  )
188
234
  }
235
+ sections.push({ block, best: bestHint(expBucket.hits) })
189
236
  }
190
237
  }
191
238
 
239
+ // 段落顺序按相关性,而不是写死的 docs 优先:检索已经给出跨层 hint(rel × 层先验),
240
+ // 排版照它来。否则查一条明确的记忆时,无关的长文档会排在最前、正确答案埋在几千字符
241
+ // 之后——模型很可能根本没读到。sort 稳定,同分保持 memory → insight → experience。
242
+ sections.sort((a, b) => b.best - a.best)
243
+ for (const s of sections) for (const line of s.block) lines.push(line)
244
+
192
245
  // TaskBridge: type:'task' 专门查任务记录;type:'all' 尾部附一行任务计数提示
193
246
  const tasks = store.tasks || []
194
247
  if (type === 'task') {
@@ -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 { cfgInsight, saveInsight, GlobalStore, defaultGlobalFile } from '../insight-store.js'
5
5
  import { ensureGlobalInit } from '../global-seed.js'
@@ -10,28 +10,26 @@ export function rememberTool(config) {
10
10
  return defineTool({
11
11
  name: 'remember',
12
12
  description:
13
- 'Save an experience note (problem -> solution) into project memory, e.g. a bug you just fixed. ' +
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.',
13
+ 'Save a problem→solution note as kind:experience; same dedup as save_lesson. '
14
+ + 'Prefer save_lesson for anything that is not a problem→solution note.',
17
15
  parameters: {
18
16
  problem: {
19
17
  type: 'string',
20
18
  required: true,
21
- description: 'The problem/situation, e.g. "pdfjs OPS import fails on Node 24".',
19
+ description: '问题/现象',
22
20
  },
23
21
  solution: {
24
22
  type: 'string',
25
23
  required: true,
26
- description: 'The concrete fix or decision, e.g. "import OPS from pdfjs-dist/legacy/build/pdf.mjs".',
24
+ description: '具体解法',
27
25
  },
28
26
  root: {
29
27
  type: 'string',
30
- description: '项目根目录,默认当前工作目录。',
28
+ description: '项目根(默认当前工作目录)',
31
29
  },
32
30
  source_file: {
33
31
  type: 'string',
34
- description: 'Optional file the problem is about, for traceability.',
32
+ description: '关联文件(项目相对)',
35
33
  },
36
34
  },
37
35
  output: {
@@ -45,6 +43,8 @@ export function rememberTool(config) {
45
43
  const memoryDir = memoryRootFor(root, config.memoryDir)
46
44
  const store = new ProjectMemoryStore(memoryDir).load()
47
45
  const cfg = cfgInsight(config)
46
+ // 与 save_lesson 同一条约束:files 只收项目内相对路径,项目外/逃出根的丢弃并回报。
47
+ const citation = normalizeCitationFiles(args.source_file ? [args.source_file] : [], root)
48
48
  ensureGlobalInit(config) // 幂等:project 写入可能被自动提升到 global
49
49
  const globalStore = new GlobalStore(cfg.globalFile || defaultGlobalFile()).load()
50
50
  // 与 save_lesson 同一条写入路径 ⇒ 同一套去重/自动覆盖/近邻提示;没装 leanvec 时 `cosine` 为 null,
@@ -55,7 +55,7 @@ export function rememberTool(config) {
55
55
  kind: 'experience',
56
56
  problem: args.problem,
57
57
  solution: args.solution,
58
- files: args.source_file ? [args.source_file] : undefined,
58
+ files: citation.files.length ? citation.files : undefined,
59
59
  confidence: 1,
60
60
  }
61
61
  let result
@@ -66,7 +66,10 @@ export function rememberTool(config) {
66
66
  globalStore.commit()
67
67
  if (!result || !result.ok) return `Failed: ${result?.error || '写入未完成'}`
68
68
  const verb = result.action === 'created' ? 'Saved' : 'Updated existing'
69
- return `${verb} experience note (${result.id}).${result.hint ? ` ${result.hint}` : ''}`
69
+ const dropped = citation.dropped.length
70
+ ? `\n(${citation.dropped.length} 个 source_file 不是项目内路径,已丢弃)`
71
+ : ''
72
+ return `${verb} experience note (${result.id}).${result.hint ? ` ${result.hint}` : ''}${dropped}`
70
73
  },
71
74
  })
72
75
  }
@@ -1,6 +1,9 @@
1
1
  import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import { assertIndexRoot, memoryRootFor, resolveSafeIndexRoot } from '../util/fs.js'
3
3
  import { ProjectMemoryStore, storeOverview } from '../store.js'
4
+ import { cfgInsight, defaultGlobalFile, GlobalStore } from '../insight-store.js'
5
+ import { cfgEngine } from '../auto-inject.js'
6
+ import { resolveVectorLayer, vectorIndexSummary, vectorItemsFrom } from '../vector-index.js'
4
7
  import { truncate } from '../util/text.js'
5
8
 
6
9
  const TOP_N = 30
@@ -9,12 +12,11 @@ export function statsTool(config) {
9
12
  return defineTool({
10
13
  name: 'memory_stats',
11
14
  description:
12
- 'Show what the project memory store contains: totals (files / entries / experience notes), last index time, ' +
13
- 'and the per-file list with entry counts sorted by most recently indexed. Use this to answer "what is in my memory store" without reading JSON files.',
15
+ 'Show store totals, last index time and the per-file index list.',
14
16
  parameters: {
15
17
  root: {
16
18
  type: 'string',
17
- description: '项目根目录,默认当前工作目录。',
19
+ description: '项目根(默认当前工作目录)',
18
20
  },
19
21
  },
20
22
  output: {
@@ -43,6 +45,27 @@ export function statsTool(config) {
43
45
  }
44
46
  if (files.length > TOP_N) lines.push(`- ... ${files.length - TOP_N} more files`)
45
47
  }
48
+ // 可选向量层的**状态**(不含模型加载):这一层静默降级太厉害——`vectorDir` 拼错一个
49
+ // 字母与"没装 leanvec"在输出上完全一样,而两者的语义差别是"排序里有没有语义"。
50
+ // 只报三件可判定的东西:能不能用、缓存索引对不对得上、写入去重开没开。
51
+ {
52
+ const engine = cfgEngine(config)
53
+ const off = typeof engine.vectorDir === 'string' && engine.vectorDir.trim().toLowerCase() === 'off'
54
+ let resolved = { dir: null }
55
+ try { resolved = off ? { dir: null } : await resolveVectorLayer(engine.vectorDir) } catch { resolved = { dir: null } }
56
+ const memDir = memoryRootFor(root, config.memoryDir)
57
+ const cfgI = cfgInsight(config)
58
+ const globalStore = new GlobalStore(cfgI.globalFile || defaultGlobalFile()).load()
59
+ const vs = vectorIndexSummary({ dir: memDir, items: vectorItemsFrom(store, globalStore) })
60
+ const state = resolved?.dir ? `on (leanvec @ ${resolved.dir})` : off ? "off (vectorDir: 'off')" : 'off (leanvec 未解析到)'
61
+ lines.push('')
62
+ lines.push(`Vector: ${state} | re-rank alpha ${engine.vectorAlpha} | write-dedup ${engine.vectorDedup ? 'on' : 'off'}`)
63
+ lines.push(
64
+ vs.rows
65
+ ? `Vector index: ${vs.rows} rows · ${vs.live} live / ${vs.stale} stale · ${(vs.bytes / 1024).toFixed(0)} KB · model ${vs.model || '?'} · updated ${vs.updatedAt || '?'}`
66
+ : 'Vector index: 尚未建立(首次查询/写入时构建)',
67
+ )
68
+ }
46
69
  return truncate(lines.join('\n'), config.maxOutputChars)
47
70
  },
48
71
  })
@@ -19,9 +19,9 @@ export function listTasksTool(config) {
19
19
  return defineTool({
20
20
  name: 'list_tasks',
21
21
  description:
22
- '列出本项目的任务记录(含归档,带标记)。新会话或续接工作前先看它,再用 select_task 选一个。',
22
+ '列出本项目的任务记录(含归档)。新会话或续接前先看它,再用 select_task 选一个。',
23
23
  parameters: {
24
- root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
24
+ root: { type: 'string', description: '项目根(默认当前工作目录)' },
25
25
  },
26
26
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
27
27
  async execute(args, exec) {
@@ -44,12 +44,12 @@ export function selectTaskTool(config, host) {
44
44
  return defineTool({
45
45
  name: 'select_task',
46
46
  description:
47
- '把会话绑定到一个任务:此后 todo 清单与读过的文件都同步进该任务。开始新工作前先调它(title 自取,短的就行,不用复述用户原话),再用 todo_write 维护计划。' +
48
- 'taskId:list_tasks 里的精确 id(会自动解归档;同时给 title 则改名)。title:完全匹配,多个同名返回候选,无匹配则新建。返回任务卡(title/steps/files)用于重建会话清单。',
47
+ '把会话绑定到一个任务(此后 todo 与读过的文件同步进它)。按 taskId 精确绑定,或按 title 完全匹配'
48
+ + '(无则新建);返回任务卡用于重建清单。',
49
49
  parameters: {
50
- taskId: { type: 'string', description: 'Exact task id, e.g. tsk_ab12cd34_...' },
51
- title: { type: 'string', description: 'Exact task title; creates a new task when absent' },
52
- root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
50
+ taskId: { type: 'string', description: '精确 task id' },
51
+ title: { type: 'string', description: '精确标题;无则新建' },
52
+ root: { type: 'string', description: '项目根(默认当前工作目录)' },
53
53
  },
54
54
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
55
55
  async execute(args, exec) {
@@ -148,8 +148,7 @@ export function selectTaskTool(config, host) {
148
148
  export function showTaskPanelTool(config) {
149
149
  return defineTool({
150
150
  name: 'show_task_panel',
151
- description:
152
- 'Show the task panel in the UI. Call this when the user asks to see the task list or when you want to display the task panel to the user.',
151
+ description: 'Open the task panel in the UI.',
153
152
  parameters: {},
154
153
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
155
154
  async execute() {
@@ -168,10 +167,10 @@ export function showTaskPanelTool(config) {
168
167
  export function archiveTaskTool(config, host) {
169
168
  return defineTool({
170
169
  name: 'archive_task',
171
- description: 'Archive a task: hide from default views, exclude from capacity, stop syncing. Restore by selecting it again.',
170
+ description: 'Archive a task (restore by selecting it again).',
172
171
  parameters: {
173
- taskId: { type: 'string', required: true, description: 'Task id to archive (from list_tasks / select_task)' },
174
- root: { type: 'string', description: '项目根目录,默认当前工作目录。' },
172
+ taskId: { type: 'string', required: true, description: 'task id' },
173
+ root: { type: 'string', description: '项目根(默认当前工作目录)' },
175
174
  },
176
175
  output: { schema: { type: 'string' }, render: (_a, v) => [{ type: 'text', text: v }] },
177
176
  async execute(args, exec) {
@@ -7,18 +7,16 @@ export function watchRepoTool(watchManager, config) {
7
7
  return defineTool({
8
8
  name: 'watch_repo',
9
9
  description:
10
- 'Start silent auto-refresh for a project: the plugin polls the root (configurable interval), ' +
11
- 'detects changed/new docs and code files via mtime+content-hash, and re-indexes only those silently. ' +
12
- 'No manual re-index needed after this. Call again with watch=false to stop.',
10
+ 'Auto-refresh a project on change; watch=false stops.',
13
11
  parameters: {
14
12
  root: {
15
13
  type: 'string',
16
14
  required: true,
17
- description: '要监听的项目根目录(绝对路径)。',
15
+ description: '项目根(绝对路径)',
18
16
  },
19
17
  watch: {
20
18
  type: 'boolean',
21
- description: 'Set false to stop watching this root. Default true.',
19
+ description: 'false = 停止监听',
22
20
  },
23
21
  },
24
22
  output: {
package/src/types.js CHANGED
@@ -31,8 +31,13 @@
31
31
  * @property {string[]} [sourceTaskIds] 曾在哪些任务中出现/被命中(提升判定唯一依据)
32
32
  * @property {'reflect' | 'agent' | 'user' | 'migrate'} [source] 来源
33
33
  * @property {{ scope: string, id: string, at: string }} [movedFrom] 提升/降级审计
34
- * @property {{ keywords: string[], symbols?: string[], scope?: string[] }} [trigger]
35
- * procedure 的 "生成 Skill" 触发规则(无独立 skill 实体)
34
+ * @property {{ when?: { ops?: string[], writes?: string[], intents?: string[] },
35
+ * guard?: { paths?: string[], not_paths?: string[], hosts?: string[], tags?: string[] },
36
+ * prevents?: string, keywords?: string[], symbols?: string[], actions?: string[],
37
+ * paths?: string[], scope?: string[] }} [trigger]
38
+ * authored 触发规则:when 是唯一触发面(三者取或),guard 只收窄;旧字段仅为历史数据兼容。
39
+ * @property {{ keywords: string[], actions: string[], paths: string[] }} [triggerDerived]
40
+ * 从正文确定性派生的检索信号,只提升召回、不参与强制注入
36
41
  * @property {number} [confidence] 0..1
37
42
  * @property {number} [hitCount] 被注入/命中的次数(强化信号,无 LLM)
38
43
  * @property {string} [lastHitAt] 最近一次命中时间 ISO(衰减/归档依据)
@@ -52,11 +57,11 @@
52
57
  * @property {number} [autoMergeMargin] 自动覆盖还要求第一名领先第二名这么多(默认 0.05)
53
58
  * @property {number} [hintCos] 向量近邻提示带(默认 0.7,只在返回文本里提示 id,不改数据)
54
59
  * @property {number} [maxForgetMatches] forget 关键词删除的命中上限(默认 10);超了一条都不删,只回报候选
55
- * @property {number} [maxProject] project insights 容量(归档区另计)
60
+ * @property {number} [maxProject] project insights 容量(含归档;超限先删归档条目)
56
61
  * @property {number} [maxGlobalProcedures] global insights 容量
57
62
  * @property {number} [promoteConfidence] 提升 project 所需最低 confidence
58
63
  * @property {number} [globalPromoteTasks] sourceTaskIds ≥ N → 提升 global
59
- * @property {number} [decayDays] 久置归档启发:hitCount==0 超该天数 → 归档(软删)
64
+ * @property {number} [decayDays] 久置归档启发:最近活动(hit/updated/created)超该天数 → 归档(软删)
60
65
  * @property {string} [globalFile] global.json 绝对路径(默认 ~/.config/dsh-project-memory/global.json)
61
66
  */
62
67