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

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +162 -8
  2. package/README.md +44 -26
  3. package/README.zh-CN.md +42 -24
  4. package/client/client.js +272 -138
  5. package/client/client.js.map +1 -1
  6. package/cordis.patch.yml +6 -1
  7. package/package.json +3 -2
  8. package/scripts/bench-synthetic.mjs +22 -11
  9. package/src/audit.js +36 -32
  10. package/src/auto-inject.js +55 -32
  11. package/src/client/MemoryView.tsx +72 -4
  12. package/src/client/ShowTaskPanelNode.tsx +8 -5
  13. package/src/client/TaskCommandNode.tsx +22 -17
  14. package/src/client/TaskComponents.tsx +18 -3
  15. package/src/client/TaskPanel.tsx +50 -85
  16. package/src/client/client.ts +26 -6
  17. package/src/client/commands.ts +67 -0
  18. package/src/client/task-ui-store.ts +15 -2
  19. package/src/commands/insight-actions.js +1 -1
  20. package/src/commands/task-actions.js +57 -3
  21. package/src/commands/tasks.js +1 -1
  22. package/src/index.js +29 -11
  23. package/src/insight-store.js +200 -78
  24. package/src/lazy.js +7 -3
  25. package/src/ops.js +1 -1
  26. package/src/readiness.js +1 -1
  27. package/src/recall.js +76 -30
  28. package/src/setup/taskbridge.js +37 -6
  29. package/src/store.js +315 -44
  30. package/src/tools/forget.js +11 -8
  31. package/src/tools/index-doc.js +14 -8
  32. package/src/tools/index-repo.js +10 -11
  33. package/src/tools/lesson-tools.js +25 -35
  34. package/src/tools/query-memory.js +81 -28
  35. package/src/tools/remember.js +14 -11
  36. package/src/tools/stats.js +26 -3
  37. package/src/tools/task-tools.js +11 -12
  38. package/src/tools/watch-repo.js +6 -8
  39. package/src/types.js +9 -4
  40. package/src/util/fs.js +502 -37
  41. package/src/util/search.js +6 -27
  42. package/src/vector-index.js +175 -22
  43. package/src/watch.js +15 -10
package/cordis.patch.yml CHANGED
@@ -12,8 +12,13 @@
12
12
  watch: true
13
13
  watchInterval: 30
14
14
  # 危险根护栏(家目录 / 文件系统根 / 系统与包管理器前缀整体扫描会吃满内存)。
15
- # 懒索引/会话审计/任务桥永不越权;true 放开**显式**带 root 的工具调用,也放行 autoIndexOnFirstUse。
15
+ # 兼容开关:只放开内置名单;roots.deny / roots.exclude 仍然优先。
16
16
  allowUnsafeRoots: false
17
+ # 自定义根名单(可选;allow/deny 精确匹配目录本身,exclude 是子树前缀)。
18
+ # roots:
19
+ # allow: []
20
+ # deny: []
21
+ # exclude: []
17
22
  # 单次扫描上限;截断会报告,且不会删除未扫到的条目。
18
23
  maxScanFiles: 20000
19
24
  maxScanDepth: 12
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yolk_vat-y/dsh-project-memory",
3
- "version": "0.6.3",
3
+ "version": "0.6.5",
4
4
  "description": "Persistent project memory for dsh agents: index docs (PDF/Markdown/text) and code symbols into a searchable per-workspace store, recall them with cited sources, and keep experience entries (problems -> solutions) searchable on demand.",
5
5
  "author": "00080000 <3388065969@qq.com>",
6
6
  "type": "module",
@@ -19,13 +19,14 @@
19
19
  "url": "https://github.com/00080000/dsh-project-memory.git"
20
20
  },
21
21
  "scripts": {
22
- "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/enhancer.test.mjs",
22
+ "test": "node test/run-test.mjs && node test/taskbridge.test.mjs && node test/insight-store.test.mjs && node test/reflection-pipeline.test.mjs && node test/auto-inject.test.mjs && node test/insight-actions.test.mjs && node test/insight-paging.test.mjs && node test/config-schema.test.mjs && node test/host-contract.test.mjs && node test/session-dir.test.mjs && node test/llm-route.test.mjs && node test/doc-index.test.mjs && node test/chunker.test.mjs && node test/client-hints.test.mjs && node test/client-paging.test.mjs && node test/client-task-sync.test.mjs && node test/recall.test.mjs && node test/recall-vector-fusion.test.mjs && node test/vector-index.test.mjs && node test/readiness.test.mjs && node test/insight-derive.test.mjs && node test/readiness-eval.test.mjs && node test/ops.test.mjs && node test/injection-audit.test.mjs && node test/injection-budget.test.mjs && node test/injection-scenarios.test.mjs && node test/bugfix-0.5.7.test.mjs && node test/client-icons.test.mjs && node test/client-slash.test.mjs && node test/client-toolview.test.mjs && node test/workflow-command.test.mjs && node test/client-session-id.test.mjs && node test/client-degraded.test.mjs && node test/watch-idle.test.mjs && node test/citation-paths.test.mjs && node test/task-view.test.mjs && node test/root-guards.test.mjs && node test/root-policy.test.mjs && node test/gitignore-index.test.mjs && node test/store-gitignore.test.mjs && node test/atomic-write.test.mjs && node test/store-cache.test.mjs && node test/store-concurrent.test.mjs && node test/tool-schema-size.test.mjs && node test/enhancer.test.mjs",
23
23
  "eval:injection": "node test/injection-scenarios.test.mjs",
24
24
  "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.client.json",
25
25
  "selfcheck:triggers": "node test/injection-scenarios.test.mjs --selfcheck",
26
26
  "bench": "node scripts/bench.mjs",
27
27
  "bench:synthetic": "node scripts/bench-synthetic.mjs",
28
28
  "bench:peak": "node --expose-gc scripts/file-peak.mjs",
29
+ "bench:store": "node scripts/bench-store.mjs",
29
30
  "schema:size": "node scripts/tool-schema-size.mjs",
30
31
  "build:client": "tsdown"
31
32
  },
@@ -2,8 +2,8 @@
2
2
  * dsh-project-memory — 微基准测试(micro-benchmark)
3
3
  *
4
4
  * 直接驱动内核热路径(不经过 defineTool / HTTP / LLM):
5
- * - store.js : load / commit / addExperience(findSupersede) / removeExperience
6
- * - util/search.js : buildBm25 / rankEntriesStreaming / rankExperienceScored
5
+ * - store.js : load / commit / removeFile
6
+ * - util/search.js : buildBm25 / rankEntriesStreaming
7
7
  * - symbols.js : scanSymbols(零 token 符号抽取,无 LLM)
8
8
  * - link.js : resolveLinkedSymbols(doc↔symbol 交叉链接,读取期解算)
9
9
  * - insight-store.js: GlobalStore read/write + saveInsight(归一化去重)
@@ -23,8 +23,8 @@ import { performance } from 'node:perf_hooks'
23
23
  import { ProjectMemoryStore } from '../src/store.js'
24
24
  import { walkDir, readFileForIndex, relativePath, storeKey, isSupportedCode } from '../src/util/fs.js'
25
25
  import { scanSymbols } from '../src/symbols.js'
26
- import { rankEntriesStreaming, rankExperienceScored, makeSearchText } from '../src/util/search.js'
27
- import { GlobalStore, saveInsight, normalizeInsight } from '../src/insight-store.js'
26
+ import { rankEntriesStreaming, makeSearchText } from '../src/util/search.js'
27
+ import { GlobalStore, saveInsight, normalizeInsight, cfgInsight } from '../src/insight-store.js'
28
28
  import { normalizedTokenOverlap } from '../src/similarity.js'
29
29
 
30
30
  const FILES = Number(process.argv[2] || 5000)
@@ -329,26 +329,37 @@ async function main() {
329
329
  console.log(` -> 候选池 1000,最高 overlap ≈ ${Math.round(bestSeen * 100)}%`)
330
330
  }
331
331
 
332
- // ---------- 8. remember(addExperience + findSupersede)----------
333
- console.log('\n--- 9. remember / addExperience(problem→solution,双向 0.7 去重)---')
332
+ // ---------- 8. remember(saveInsight,kind:experience)----------
333
+ console.log('\n--- 8. remember / saveInsight(problem→solution,去重合并)---')
334
334
  {
335
335
  const root = tmpd('pm-exp-')
336
336
  const store = new ProjectMemoryStore(path.join(root, config.memoryDir)).load()
337
- // 用互异的 problem(含随机 token)让经验池真实增长,避免互相 supersede 合并成一条
337
+ const expCfg = { ...cfgInsight({}), maxProject: 2000 }
338
+ // 用互异的 problem(含随机 token)让经验池真实增长,避免互相合并成一条
338
339
  const times = []
339
340
  const total = []
340
341
  for (let i = 0; i < 1000; i++) {
341
- // 每个 problem 含两个高熵 token,使公共词只占 <0.7,池真实增长而非互相 supersede
342
342
  const uniq = Math.floor(Math.random() * 1e9).toString(36)
343
343
  const rand = Math.random().toString(36).slice(2, 10)
344
344
  const t0 = performance.now()
345
- store.addExperience({ problem: `payment gateway timeout ${uniq} ${rand}`, solution: `add exponential backoff ${uniq}` })
345
+ store.commit((s) => saveInsight({
346
+ store: s,
347
+ raw: {
348
+ kind: 'experience',
349
+ title: `payment gateway timeout ${uniq} ${rand}`,
350
+ problem: `payment gateway timeout ${uniq} ${rand}`,
351
+ solution: `add exponential backoff ${uniq}`,
352
+ },
353
+ scope: 'project',
354
+ cfg: expCfg,
355
+ }))
346
356
  const dt = performance.now() - t0
347
357
  times.push(dt)
348
358
  total.push(dt)
349
359
  }
350
- show('addExperience 单条 (含去重扫描,池增长)', stats('exp', times))
351
- console.log(` -> 池增长到 ${store.experience.length} 条;1000 次累计 ${total.reduce((s, t) => s + t, 0).toFixed(1)} ms`)
360
+ const experience = store.insightItems().filter((it) => it.kind === 'experience').length
361
+ show('saveInsight(experience) 单条 (含去重扫描,池增长)', stats('exp', times))
362
+ console.log(` -> 池增长到 ${experience} 条;1000 次累计 ${total.reduce((s, t) => s + t, 0).toFixed(1)} ms`)
352
363
  }
353
364
 
354
365
  // 清理
package/src/audit.js CHANGED
@@ -1,4 +1,4 @@
1
- // 注入审计(PLAN S0):把每次**真实进入上下文**的注入决策落成 JSONL。
1
+ // 注入审计:把每次**真实进入上下文**的注入决策落成 JSONL。
2
2
  //
3
3
  // 为什么需要:注入的有效性无法在线逐条归因——宿主只给 turn 级聚合(cacheReadTokens /
4
4
  // inputTokens),拿不到"这一条记忆值多少"。所以"当时注入了哪几条、因为什么命中、同一轮
@@ -35,26 +35,33 @@ const DEFAULT_SHADOW_MAX_BYTES = 512 * 1024
35
35
  */
36
36
  const SHADOW_MAX_CANDIDATES = 16
37
37
 
38
- /** 审计配置:默认开(观测是这个插件唯一的仪表盘),显式 `auditLog: false` 才关。 */
39
- export function cfgAudit(config) {
38
+ /**
39
+ * 两份 JSONL 旁路日志共用的配置归一。它们的差别只有「开关名 / 字节上限键 / 默认上限」,
40
+ * 其余判定(默认开、非法上限退回默认)必须完全一致——抄成两份就等着一边补了 `> 0`、
41
+ * 另一边忘了。语义刻意选择:
42
+ * - `!== false` 而不是 `=== true`:未配置 = 开(观测是这个插件唯一的仪表盘);
43
+ * - `> 0` 而不是 `!= null`:0 / 负数 / NaN 都视为「没配」,退回默认上限,而不是禁用。
44
+ */
45
+ function cfgSideLog(config, { enabledKey, maxKey, defaultMaxBytes }) {
40
46
  const c = (config && config.autoContext) || {}
41
47
  return {
42
- enabled: c.auditLog !== false,
43
- maxBytes: typeof c.auditMaxBytes === 'number' && c.auditMaxBytes > 0 ? c.auditMaxBytes : DEFAULT_MAX_BYTES,
48
+ enabled: c[enabledKey] !== false,
49
+ maxBytes: typeof c[maxKey] === 'number' && c[maxKey] > 0 ? c[maxKey] : defaultMaxBytes,
44
50
  }
45
51
  }
46
52
 
53
+ /** 审计配置:默认开,显式 `auditLog: false` 才关。 */
54
+ export function cfgAudit(config) {
55
+ return cfgSideLog(config, { enabledKey: 'auditLog', maxKey: 'auditMaxBytes', defaultMaxBytes: DEFAULT_MAX_BYTES })
56
+ }
57
+
47
58
  export function auditFileFor(memoryDir) {
48
59
  return path.join(memoryDir, AUDIT_FILE)
49
60
  }
50
61
 
51
62
  /** 影子记录配置:默认开(它只写盘、不进 prompt、不花 token),显式 `shadowLog: false` 才关。 */
52
63
  export function cfgShadow(config) {
53
- const c = (config && config.autoContext) || {}
54
- return {
55
- enabled: c.shadowLog !== false,
56
- maxBytes: typeof c.shadowMaxBytes === 'number' && c.shadowMaxBytes > 0 ? c.shadowMaxBytes : DEFAULT_SHADOW_MAX_BYTES,
57
- }
64
+ return cfgSideLog(config, { enabledKey: 'shadowLog', maxKey: 'shadowMaxBytes', defaultMaxBytes: DEFAULT_SHADOW_MAX_BYTES })
58
65
  }
59
66
 
60
67
  export function shadowFileFor(memoryDir) {
@@ -121,11 +128,6 @@ export function shadowRecordFrom(input) {
121
128
  }
122
129
  }
123
130
 
124
- /**
125
- * 追加一行影子记录。返回是否写入成功(仅供测试断言)。与主审计同约定:任何异常一律吞掉,
126
- * 绝不影响宿主请求。
127
- */
128
-
129
131
  /**
130
132
  * 审计**只为"已经存在"或"结论明确"的根创建 store 目录**。
131
133
  *
@@ -148,22 +150,37 @@ function auditDirReady(memoryDir, root) {
148
150
  return hasProjectMarker(root || path.dirname(memoryDir))
149
151
  }
150
152
 
151
- export function appendShadowAudit(memoryDir, record, cfg, root) {
153
+ /**
154
+ * 两份旁路日志共用的追加:目录门禁 / mkdir / 轮转 / 吞异常**只有这一份实现**,
155
+ * 调用方只声明文件名与默认上限。分开写两份时,一处补了护栏另一处就会漏
156
+ * (影子记录与主审计的"不建推测根"曾经就是各写一遍)。
157
+ * @returns {boolean} 是否写入成功(仅供测试断言)
158
+ */
159
+ function appendJsonlRecord({ memoryDir, record, cfg, root, fileFor, defaultMaxBytes }) {
152
160
  const c = cfg || {}
153
161
  if (c.enabled === false) return false
154
162
  if (!memoryDir || !record) return false
155
163
  if (!auditDirReady(memoryDir, root)) return false
156
164
  try {
157
165
  mkdirSync(memoryDir, { recursive: true })
158
- const file = shadowFileFor(memoryDir)
159
- rotateIfOversized(file, c.maxBytes || DEFAULT_SHADOW_MAX_BYTES)
166
+ const file = fileFor(memoryDir)
167
+ rotateIfOversized(file, c.maxBytes || defaultMaxBytes)
160
168
  appendFileSync(file, `${JSON.stringify(record)}\n`)
161
169
  return true
162
170
  } catch {
171
+ // 旁路契约:写不进去不能影响这一轮注入,更不能影响宿主的请求
163
172
  return false
164
173
  }
165
174
  }
166
175
 
176
+ /**
177
+ * 追加一行影子记录。返回是否写入成功(仅供测试断言)。与主审计同约定:任何异常一律吞掉,
178
+ * 绝不影响宿主请求。
179
+ */
180
+ export function appendShadowAudit(memoryDir, record, cfg, root) {
181
+ return appendJsonlRecord({ memoryDir, record, cfg, root, fileFor: shadowFileFor, defaultMaxBytes: DEFAULT_SHADOW_MAX_BYTES })
182
+ }
183
+
167
184
  /**
168
185
  * 一次注入的审计记录(纯函数,可单测)。字段刻意保持"能直接回答两个问题":
169
186
  * 注入了什么(injected)、为什么没注入别的(dropped)。
@@ -208,20 +225,7 @@ export function auditRecordFrom(input) {
208
225
  * @param {{enabled?: boolean, maxBytes?: number}} [cfg] {@link cfgAudit} 的产物
209
226
  */
210
227
  export function appendInjectionAudit(memoryDir, record, cfg, root) {
211
- const c = cfg || {}
212
- if (c.enabled === false) return false
213
- if (!memoryDir || !record) return false
214
- if (!auditDirReady(memoryDir, root)) return false
215
- try {
216
- mkdirSync(memoryDir, { recursive: true })
217
- const file = auditFileFor(memoryDir)
218
- rotateIfOversized(file, c.maxBytes || DEFAULT_MAX_BYTES)
219
- appendFileSync(file, `${JSON.stringify(record)}\n`)
220
- return true
221
- } catch {
222
- // 审计是旁路:写不进去不能影响这一轮注入,更不能影响宿主的请求
223
- return false
224
- }
228
+ return appendJsonlRecord({ memoryDir, record, cfg, root, fileFor: auditFileFor, defaultMaxBytes: DEFAULT_MAX_BYTES })
225
229
  }
226
230
 
227
231
  function rotateIfOversized(file, maxBytes) {
@@ -8,11 +8,11 @@
8
8
  import { createHash } from 'node:crypto'
9
9
  import { createUserMessage } from '@deepseek-ai/dsh-llm'
10
10
  import { ProjectMemoryStore } from './store.js'
11
- import { hasProjectMarker, isUnsafeRoot, memoryRootFor, resolveProjectMemoryRoot } from './util/fs.js'
11
+ import { hasProjectMarker, memoryRootFor, resolveProjectMemoryRoot, rootRejection } from './util/fs.js'
12
12
  import { textOf } from './util/text.js'
13
13
  import { stepContent } from './util/task-view.js'
14
14
  import { insightMatchText, normalizedTokenOverlap } from './similarity.js'
15
- import { createVectorRerank, vectorItemsFrom } from './vector-index.js'
15
+ import { createVectorCosine, createVectorRerank, vectorItemsFrom } from './vector-index.js'
16
16
  import { BoundedMap, SessionCache } from './util/session-cache.js'
17
17
  import { sessionWorkingDir } from './util/session-dir.js'
18
18
  import { cfgInsight, GlobalStore, defaultGlobalFile, recordHit } from './insight-store.js'
@@ -102,9 +102,8 @@ export function cfgEngine(config) {
102
102
  // 整块重发同一条 1200 字 procedure 只是重复占位。>0 用于历史可能被外部裁剪的场景。
103
103
  reinjectItemsAfter: typeof c.reinjectItemsAfter === 'number' && c.reinjectItemsAfter >= 0 ? c.reinjectItemsAfter : 0,
104
104
  // ---- S2/S3/S4 新增(准入化改造) ----
105
- // 旧 `scope` 的处理:'filter'(默认,保留旧语义——不静默改用户数据)或 'ignore'。
106
- // legacy `trigger.scope`:默认 **ignore**(与 `src/index.js` 的 schema 默认一致)。
107
- // 值由作者手写,落不进自动派生的画像 tag 空间 → 当收窄条件用等于判死条目。
105
+ // 旧 `scope` 的处理:默认 **ignore**(保留历史数据、不静默改用户数据);
106
+ // legacy `trigger.scope` 的值由作者手写,落不进自动派生的画像 tag 空间 → 当收窄条件用等于判死条目。
108
107
  // 显式配 'filter' 才恢复旧的收窄语义。
109
108
  legacyScope: c.legacyScope === 'filter' ? 'filter' : 'ignore',
110
109
  // 条目通道的步间隔:两次"条目注入"之间至少隔这么多步(常驻任务卡不受限——它是状态快照,
@@ -134,15 +133,21 @@ export function cfgEngine(config) {
134
133
  // 只有配置了目录(或环境变量、或装上可选依赖)才构造 rerank,见 src/vector-index.js。
135
134
  vectorDir: typeof c.vectorDir === 'string' && c.vectorDir ? c.vectorDir : null,
136
135
  vectorAlpha: typeof c.vectorAlpha === 'number' && c.vectorAlpha >= 0 && c.vectorAlpha <= 1 ? c.vectorAlpha : 0.5,
136
+ // 写入侧近重复检测的独立开关(默认开)。**不跟随 vectorAlpha**:那条是排序权重,
137
+ // 设成 0 只该关掉重排,不该连带停掉 0.9 自动覆盖 / 0.7 近邻提示。
138
+ vectorDedup: c.vectorDedup !== false,
139
+ // 两个**实验性**旋钮:没有可发布的默认值(证据见 scoreHints 的注释),所以不设就不启用。
140
+ vectorItemMin: typeof c.vectorItemMin === 'number' && Number.isFinite(c.vectorItemMin) ? c.vectorItemMin : undefined,
141
+ vectorSpeakMin: typeof c.vectorSpeakMin === 'number' && Number.isFinite(c.vectorSpeakMin) ? c.vectorSpeakMin : undefined,
137
142
  }
138
143
  }
139
144
 
140
145
  /**
141
146
  * 给写入路径(`save_lesson` / `remember`)用的向量打分器:**没装/没配就是 null**。
142
147
  *
143
- * 与注入路径共用一个解析入口(`cfgEngine` + `createVectorRerank`),所以"装了 leanvec 就用、
144
- * 没装就纯词法"这条规则只有一处实现、一处配置。返回的函数是同步的,供 `saveInsight` 在
145
- * 写事务里直接调用;任何异常都降级成 null,绝不因为可选的向量层挡住写入。
148
+ * 与注入路径共用一个解析入口(`openEngine`),但**不共用开关**:写入去重由
149
+ * `autoContext.vectorDedup` 控制,不受 `vectorAlpha`(排序权重)影响。返回的函数是同步的,
150
+ * 供 `saveInsight` 在写事务里直接调用;任何异常都降级成 null,绝不因为可选的向量层挡住写入。
146
151
  * @param {object} config - 插件配置
147
152
  * @param {{storeDir: string|null, items: object[]}} o - 持久化位置与候选池(见 vectorItemsFrom)
148
153
  * @returns {Promise<((text: string, items: object[]) => Map<string, number>)|null>}
@@ -150,9 +155,7 @@ export function cfgEngine(config) {
150
155
  export async function createWriteCosine(config, { storeDir = null, items = [] } = {}) {
151
156
  const engine = cfgEngine(config)
152
157
  try {
153
- const rerank = await createVectorRerank({ storeDir, items, vectorDir: engine.vectorDir, alpha: engine.vectorAlpha })
154
- if (!rerank || typeof rerank.score !== 'function') return null
155
- return (text, cands) => rerank.score(text, cands)
158
+ return await createVectorCosine({ storeDir, items, vectorDir: engine.vectorDir, dedup: engine.vectorDedup })
156
159
  } catch {
157
160
  return null
158
161
  }
@@ -214,7 +217,8 @@ export function shouldEchoTaskCard(task, cfg) {
214
217
  }
215
218
 
216
219
  /** 任务卡 + 非草稿任务级 insights 摘要(常驻块主体)。
217
- * withEdited=false 用于去重指纹:排除随写文件高频变化的“编辑中”行。 */
220
+ * withEdited=false 只留给需要稳定正文的调用方;去重指纹现在**包含**“编辑中”行:
221
+ * 否则常驻卡会永远停在第一次注入时的文件列表(写文件不会改变指纹)。 */
218
222
  export function buildEntryContent(task, cfg, { withEdited = true } = {}) {
219
223
  if (!task) return ''
220
224
  const c = cfg || {}
@@ -429,7 +433,15 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped, rerank =
429
433
  // 顺序与真实判据一致(support → coverage → thin → relative),最后 'cand' = 过了全部门槛
430
434
  // (注意 'cand' 不等于"真的注入了":还要过去重/预算/冷却,那些写在同一行的 injected/silence)。
431
435
  {
436
+ // 两个分母必须分开:真实判据(`relative`)用的是**融合后**的分,而影子记录的 `rel`
437
+ // 承诺的是**词法**相对分。此前两者共用 `scored[0].score`,于是 `rel` 的分子是 BM25 原分、
438
+ // 分母是融合 top —— 实测同一行里 `rel` 能到 5.925(应当 ≤1),离线拿它重放阈值会全歪。
432
439
  const top = scored[0]?.score || 0
440
+ let lexTop = 0
441
+ for (const r of scored) {
442
+ const lex = r.bm25 ?? r.score
443
+ if (Number.isFinite(lex) && lex > lexTop) lexTop = lex
444
+ }
433
445
  const ratio = typeof cfg.signalMinRatio === 'number' && Number.isFinite(cfg.signalMinRatio) ? cfg.signalMinRatio : 0.5
434
446
  for (const r of scored) {
435
447
  const it = byId.get(r.entry.insightId)
@@ -445,8 +457,9 @@ function scoreHints({ cands, query, humanText, hintQuery, cfg, dropped, rerank =
445
457
  const cand = {
446
458
  id: it.id,
447
459
  channel: 'hint',
448
- // `rel` 恒为**词法**相对分(未融合),供离线重放对照;融合后的分另记 fused。
449
- rel: Number(((r.bm25 ?? r.score) / (top || 1)).toFixed(3)),
460
+ // `rel` 恒为**词法**相对分(未融合,分母是词法 top),供离线重放对照;
461
+ // 融合后的分另记 fused,`decision: 'relative'` 用的仍是融合分(与真实判据一致)。
462
+ rel: Number(((r.bm25 ?? r.score) / (lexTop || 1)).toFixed(3)),
450
463
  coverage: Number(ev.coverage.toFixed(3)),
451
464
  matched: ev.matched,
452
465
  support: ev.supported,
@@ -522,11 +535,12 @@ export function buildInjection(opts) {
522
535
  rerank: opts.rerank || null,
523
536
  })
524
537
 
525
- // 常驻块文本。去重指纹只看稳定内容(任务标题/步骤/insights + 相关 insights):
526
- // “编辑中”随每次写文件变化,若参与指纹会导致每写一个文件就重发整块(噪音 + token 浪费)。
538
+ // 常驻块文本。去重指纹包含“编辑中”行:否则这条常驻状态只会在别的条目变化时顺带更新,
539
+ // 模型会一直看到旧文件列表。editedFiles 只返回文件名(不含时间戳),所以同一个文件
540
+ // 反复写不会改变指纹;只有热点文件集合/顺序变化时才重发整块。
527
541
  const echo = cfg.entryOn !== false && shouldEchoTaskCard(task, cfg)
528
542
  const entry = echo ? buildEntryContent(task, cfg) : ''
529
- const entryStable = echo ? buildEntryContent(task, cfg, { withEdited: false }) : ''
543
+ const entryStable = entry
530
544
  let used = entry.length
531
545
  let itemUsed = 0
532
546
  let itemCount = 0
@@ -688,11 +702,12 @@ export function installAutoInject(ctx, config) {
688
702
  /** 已就「会话根不安全」提示过的目录:每个进程、每个根只提示一次。 */
689
703
  const warnedUnsafeRoots = new Set()
690
704
 
691
- function warnUnsafeSessionRoot(root) {
705
+ function warnUnsafeSessionRoot(root, rejection) {
692
706
  if (warnedUnsafeRoots.has(root)) return
693
707
  warnedUnsafeRoots.add(root)
708
+ const field = rejection?.field ? `; adjust \`${rejection.field}\` under \`- id: project-memory\` if this is intentional` : ''
694
709
  console.error(
695
- `[dsh-project-memory] session cwd ${root} is not a project root (home / system / package-manager prefix); ` +
710
+ `[dsh-project-memory] session cwd ${root} is not a project root (${rejection?.reason || 'home / system / package-manager prefix'}${field}); ` +
696
711
  'project memory and its audit logs are disabled for this session. Start dsh inside a project directory to enable them.',
697
712
  )
698
713
  }
@@ -708,16 +723,17 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
708
723
  const cwd = sessionWorkingDir(session, { agent: payload?.agent })
709
724
  const sessionId = session && session.id
710
725
  if (!cwd || !sessionId) return null
711
- // 会话 cwd 是家目录/系统目录时整条链路停在这里:不读 store(历史遗留的超大 store
712
- // 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的 mkdirSync 正是把
713
- // `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
714
- if (isUnsafeRoot(cwd)) {
715
- warnUnsafeSessionRoot(cwd)
726
+ // 会话 cwd 命中内置名单 / roots.deny / roots.exclude 时整条链路停在这里:不读 store
727
+ // (历史遗留的超大 store 光是 load() 就能 OOM),也不写审计——`appendShadowAudit` 里的
728
+ // mkdirSync 正是把 `.dsh-project-memory` 造进家目录、进而触发"目录自标记 → 家目录被锁成项目"的那一步。
729
+ const rejection = rootRejection(cwd, config)
730
+ if (rejection) {
731
+ warnUnsafeSessionRoot(cwd, rejection)
716
732
  return null
717
733
  }
718
734
  // 记忆根与懒索引/工具侧同一套解析:项目标记优先,其次是安全的会话工作目录。
719
735
  // 少了这一步,同一个会话的审计日志与懒索引会落在两个不同的 store 里。
720
- const root = resolveProjectMemoryRoot(cwd)
736
+ const root = resolveProjectMemoryRoot(cwd, config)
721
737
  if (!root) return null
722
738
 
723
739
  const query = lastUserText(decision.messages)
@@ -766,6 +782,9 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
766
782
  items: vectorItemsFrom(store, globalStore),
767
783
  vectorDir: cfg.vectorDir,
768
784
  alpha: cfg.vectorAlpha,
785
+ // 两个实验性旋钮:不配就是 undefined → 对应的闸门整段不执行(默认路径与旧版一致)
786
+ itemMin: cfg.vectorItemMin,
787
+ speakMin: cfg.vectorSpeakMin,
769
788
  }),
770
789
  })
771
790
 
@@ -799,6 +818,10 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
799
818
  const injectedText = notice ? (built.text ? `${notice}\n${built.text}` : notice) : built.text
800
819
  if (!injectedText || fp === sessions.lastText.peek(sessionId)) return null
801
820
  sessions.lastText.set(sessionId, fp)
821
+ const itemCount = built.reasons.length
822
+ const summary = itemCount
823
+ ? `memory inject: ${itemCount} item(s)${built.entry ? ' + task card' : ''}`
824
+ : built.entry ? 'memory inject: task card' : 'memory root notice'
802
825
 
803
826
  // 只记真的进了上下文的那几条:dropped 的没被看到,不能记账(否则以后永远不再注入)。
804
827
  const seen = sessions.items.ensure(sessionId)
@@ -840,7 +863,7 @@ async function injectForStep({ payload, decision, config, cfg, audit, shadow, se
840
863
  silence: silence.reason,
841
864
  }), audit, root)
842
865
 
843
- return { ...decision, messages: [...decision.messages, injectionMessage(injectedText)] }
866
+ return { ...decision, messages: [...decision.messages, injectionMessage(injectedText, summary)] }
844
867
  }
845
868
 
846
869
  /**
@@ -904,16 +927,16 @@ function recordDropped({ sessions, sessionId, dropped, budgetLog }) {
904
927
  }
905
928
 
906
929
  /** 追加的注入消息:必须是带 source 的完整消息——裸 {role,content} 会让宿主读 message.source 时崩。 */
907
- function injectionMessage(text) {
930
+ function injectionMessage(text, summary) {
908
931
  return createUserMessage({
909
932
  content: [{ type: 'text', text: `\n\n${INJECT_MARK} ${PLUGIN_NAME} · auto-context\n${text}` }],
910
- // 这一块是「同一生产者后续快照会取代的当前状态」,不是一次性通知。
911
- // 宿主 ContextFormed 是判别联合:snapshot 必须带 sections(notice 才需要 summary)。
912
- // kind 必须是生产者自有的(v4 没有 'plugin' 兜底 kind),见 SOURCE_KIND 的注释。
933
+ // 宿主对第三方生产者的 `snapshot` 只做追加,不会用后一条替换前一条(只有它自己的
934
+ // runtime-context 走 surfaceOp replace)。所以这里声明 `notice`:它如实表示“这一步注入了
935
+ // 什么”,不会让 UI 打出“取代先前快照”的空头承诺。summary 是 UI 收起时的一行说明。
913
936
  source: {
914
937
  kind: SOURCE_KIND,
915
- form: 'snapshot',
916
- sections: [{ name: 'project-memory', text }],
938
+ form: 'notice',
939
+ summary,
917
940
  },
918
941
  })
919
942
  }
@@ -49,6 +49,57 @@ interface ListPayload {
49
49
  items: InsightRow[]
50
50
  }
51
51
 
52
+ /**
53
+ * 切页缓存:任务/项目/全局三页在同一个面板里来回切时,30 秒内直接复用上一份列表,
54
+ * 不再发 /tasks insight list。宿主每次命令都会在会话里留一个 command 节点,
55
+ * 而"切回刚才那页"并不需要重新证明数据没变;动作之后的 reloadWindow 会更新缓存。
56
+ */
57
+ const INSIGHT_CACHE_TTL_MS = 30_000
58
+ const INSIGHT_CACHE_MAX = 12
59
+ interface InsightCacheEntry {
60
+ rows: InsightRow[]
61
+ total: number
62
+ nextOffset: number | null
63
+ at: number
64
+ }
65
+ const insightCache = new Map<string, InsightCacheEntry>()
66
+
67
+ function insightCacheKey(sessionId: string | null, scope: InsightScope, root: string | null, boundTaskId: string | null): string {
68
+ // 同一会话里 cd 到另一个项目时 sessionId 不变;不带 root 会把上一个项目的列表复用过来。
69
+ // task 页还依赖当前绑定的任务:换绑后必须重新取,不能复用上一个任务的草稿列表。
70
+ return `${sessionId || ''}|${root || ''}|${scope}|${boundTaskId || ''}`
71
+ }
72
+
73
+ function readInsightCache(sessionId: string | null, scope: InsightScope, root: string | null, boundTaskId: string | null): InsightCacheEntry | null {
74
+ const key = insightCacheKey(sessionId, scope, root, boundTaskId)
75
+ const hit = insightCache.get(key)
76
+ if (!hit) return null
77
+ if (Date.now() - hit.at > INSIGHT_CACHE_TTL_MS) {
78
+ insightCache.delete(key)
79
+ return null
80
+ }
81
+ return hit
82
+ }
83
+
84
+ function writeInsightCache(
85
+ sessionId: string | null,
86
+ scope: InsightScope,
87
+ root: string | null,
88
+ boundTaskId: string | null,
89
+ rows: InsightRow[],
90
+ total: number,
91
+ nextOffset: number | null,
92
+ ): void {
93
+ const key = insightCacheKey(sessionId, scope, root, boundTaskId)
94
+ insightCache.delete(key)
95
+ insightCache.set(key, { rows, total, nextOffset, at: Date.now() })
96
+ while (insightCache.size > INSIGHT_CACHE_MAX) {
97
+ const oldest = insightCache.keys().next().value
98
+ if (oldest === undefined) break
99
+ insightCache.delete(oldest)
100
+ }
101
+ }
102
+
52
103
  export function parseInsightPayloadText(text?: string | null): ListPayload | null {
53
104
  if (!text) return null
54
105
  let jsonBlock: string | null = null
@@ -85,6 +136,7 @@ export function MemoryView({
85
136
  ctx,
86
137
  sessionId,
87
138
  scope,
139
+ root,
88
140
  boundTaskId,
89
141
  showHints,
90
142
  t,
@@ -92,6 +144,7 @@ export function MemoryView({
92
144
  ctx: any
93
145
  sessionId: string | null
94
146
  scope: InsightScope
147
+ root: string | null
95
148
  boundTaskId: string | null
96
149
  showHints: boolean
97
150
  t: any
@@ -185,7 +238,11 @@ export function MemoryView({
185
238
  setError('unparsable payload')
186
239
  return
187
240
  }
188
- setRows((prev) => (append ? appendUnique(prev, parsed.items) : parsed.items))
241
+ setRows((prev) => {
242
+ const next = append ? appendUnique(prev, parsed.items) : parsed.items
243
+ writeInsightCache(sessionId, requestedScope, root, boundTaskId, next, parsed.total, parsed.nextOffset)
244
+ return next
245
+ })
189
246
  setTotal(parsed.total)
190
247
  setNextOffset(parsed.nextOffset)
191
248
  } finally {
@@ -198,7 +255,7 @@ export function MemoryView({
198
255
  }
199
256
  }
200
257
  },
201
- [runLine, sessionId],
258
+ [runLine, sessionId, root, boundTaskId],
202
259
  )
203
260
 
204
261
  // load 的身份随 runLine 变(ctx/sessionId 变化);用 ref 持有它,让下面的 effect
@@ -210,12 +267,23 @@ export function MemoryView({
210
267
  }, [load])
211
268
 
212
269
  useEffect(() => {
213
- // 换 scope / 换会话 = 换了一个列表:清空并从头取第一页。
270
+ // 换 scope / 换会话 = 换了一个列表:先看 30 秒缓存,命中就不发命令。
214
271
  setRows([])
215
272
  setTotal(0)
216
273
  setNextOffset(null)
217
274
  setError(null)
218
275
  if (!sessionId) return
276
+ const cached = readInsightCache(sessionId, scope, root, boundTaskId)
277
+ if (cached) {
278
+ setRows(cached.rows)
279
+ setTotal(cached.total)
280
+ setNextOffset(cached.nextOffset)
281
+ // 上一页的在途请求可能还没回落;缓存命中时直接把加载态关掉。
282
+ setLoading(false)
283
+ setLoadingMore(false)
284
+ setShowSpinner(false)
285
+ return
286
+ }
219
287
  void loadRef.current(0, PAGE_SIZE, false)
220
288
  }, [scope, sessionId])
221
289
 
@@ -425,7 +493,7 @@ export function MemoryView({
425
493
  </div>
426
494
  {row.body && row.body !== row.title && <div className={css.memBody}>{String(row.body).slice(0, 160)}</div>}
427
495
  <div className={css.memActs}>
428
- <Button variant="outline" size="sm" disabled={busy} onClick={() => startEdit(row)}>{t('mem.edit')}</Button>
496
+ {scope !== 'task' && <Button variant="outline" size="sm" disabled={busy} onClick={() => startEdit(row)}>{t('mem.edit')}</Button>}
429
497
  {scope === 'task' && !row.archived && (
430
498
  <>
431
499
  {row.draft && <Button variant="outline" size="sm" disabled={busy} onClick={() => void act('confirm', row.id)}>{t('mem.confirm')}</Button>}
@@ -43,9 +43,12 @@ export function ShowTaskPanelNode(props: any) {
43
43
  }
44
44
 
45
45
  /** 把 `show_task_panel` 的视图注册进宿主的 `tool.call.toolview` 槽。 */
46
- export function registerShowTaskPanelView(slots: any): void {
47
- slots.inject('tool.call.toolview', () => slots.register(
48
- { name: 'tool.call.toolview', key: 'show_task_panel' },
49
- ShowTaskPanelNode,
50
- ))
46
+ export function registerShowTaskPanelView(slots: any, keep?: (off: unknown) => void): void {
47
+ slots.inject('tool.call.toolview', () => {
48
+ const off = slots.register(
49
+ { name: 'tool.call.toolview', key: 'show_task_panel' },
50
+ ShowTaskPanelNode,
51
+ )
52
+ if (typeof keep === 'function') keep(off)
53
+ })
51
54
  }
@@ -14,12 +14,21 @@ export function TaskCommandNode({ node }: { node?: any }) {
14
14
  const name = node?.name ?? 'task'
15
15
  const outcome = node?.outcome ?? null
16
16
  const args = typeof node?.args === 'string' ? node.args : ''
17
- const verb = args.trim().split(/\s+/)[0] ?? ''
18
- const isList = name === 'tasks' || !verb
17
+ const tokens = args.trim().split(/\s+/).filter(Boolean)
18
+ const verb = tokens[0] ?? ''
19
+ const sub = tokens[1] ?? ''
20
+ const isTasks = name === 'tasks'
21
+ // 合并后只有一个用户命令 /tasks:记忆列表是 `/tasks insight list …`,
22
+ // 不能只按命令名判断——否则切一次记忆页就会留一行“已执行”节点。
23
+ const isInsight = name === 'insight' || (isTasks && verb === 'insight')
24
+ const insightVerb = name === 'insight' ? verb : sub
25
+ const isList = isInsight
26
+ ? (name === 'insight' ? (!verb || verb === 'list') : sub === 'list')
27
+ : isTasks && !verb
19
28
  const text = outcome?.text ?? ''
20
29
 
21
- const parsedTasks = name !== 'insight' ? parseTaskPayloadText(text) : null
22
- const parsedInsights = name === 'insight' ? parseInsightPayloadText(text) : null
30
+ const parsedTasks = isInsight ? null : parseTaskPayloadText(text)
31
+ const parsedInsights = isInsight ? parseInsightPayloadText(text) : null
23
32
 
24
33
  // 该节点是否“现场执行”(挂载时处于执行中):为 true 说明是用户当场输入的命令,
25
34
  // 完成后同步数据并打开面板。刷新/切换会话后历史节点以完成态重挂载,
@@ -47,20 +56,16 @@ export function TaskCommandNode({ node }: { node?: any }) {
47
56
  return <div className={css.row} data-variant="error">/{name} 失败{brief ? `:${brief}` : ''}</div>
48
57
  }
49
58
 
50
- // /insight:列表只显示一行摘要,动作类只显示一句结果(永不整段渲染)
51
- if (name === 'insight') {
52
- if (verb === 'list' && parsedInsights) {
53
- const scope = parsedInsights.scope
54
- const count = parsedInsights.count ?? parsedInsights.items.length
55
- return (
56
- <div className={css.row} data-variant="ok">
57
- <IconFolderOpenOutline16 className={css.icon} />
58
- <span>记忆 {scope} · {count} 条 · 已同步到记忆视图</span>
59
- </div>
60
- )
61
- }
59
+ // 列表型命令是**面板自己的读通道**,不是对话内容:宿主每次 execute 都会写
60
+ // command/run + command/done,客户端唯一能抑制的就是这里的渲染。载荷已同步进 store
61
+ // (/tasks 还会打开面板),再留一行只会让切页/刷新在会话里堆节点。
62
+ // 解析失败时保留一行,避免"命令成功了却什么都不显示"。
63
+ if (isList && (isInsight ? parsedInsights : parsedTasks)) return null
64
+
65
+ // /insight:动作类只显示一句结果(永不整段渲染)
66
+ if (isInsight) {
62
67
  const note = String(text ?? '').split('\n')[0].slice(0, 120)
63
- return <div className={css.row} data-variant="ok">/insight {verb} {note || '已完成'}</div>
68
+ return <div className={css.row} data-variant="ok">/insight {insightVerb} {note || '已完成'}</div>
64
69
  }
65
70
 
66
71
  if (!isList) {