@restregular/dsh-memory 0.9.8 → 0.9.10

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/README.md CHANGED
@@ -129,7 +129,7 @@ memory_save({
129
129
  - **截断标签**:正文因 `topK` / 预算没注入时,附一条独立的「相关记忆索引」——每条只给 8 位 id、标签/主题、类型、作用域,以及 `memory_search` 检索指引;标签有 `digest.hintBudget` / `digest.hintMaxItems` 独立预算。标签也溢出时报告省略数量与原因。
130
130
  - **退役规则**:被 `supersedes` 指向的旧记录不再进入摘要、规则段和自动召回;`memory_search` / `memory_get` 仍可查历史。
131
131
  - **mandatory / pinned**:规则标签里写 `mandatory` / `pinned`(或 `必含` / `强制`)的条目排在规则段最前;超预算时输出明确警告,不静默丢弃。
132
- - **标签触发的行为召回(0.9.7)**:设置里的 `autoRecall.tags` 是**标签**,不是正则;默认还会并入记忆库里已有的标签(`useMemoryTags`)。匹配源包括 `tool/call` 的 name / description / 参数、`tool/result` 的失败描述、可见 `assistant/message` 文本、`todo/write` 任务清单、`command/run`、`goal/change`。命中标签后,在下一个 `agent/pre-step` 用标签 + 命中片段检索;工具失败则始终用该工具调用自己的 `description`(取不到才退回错误类别)。中英标签有最小同义词映射(如 `deploy` ↔ 部署、`database` ↔ 数据库)。
132
+ - **标签触发的行为召回(0.9.7)**:设置里的 `autoRecall.tags` 是**标签**,不是正则;默认还会并入记忆库里已有的标签(`useMemoryTags`)。自动召回只检索 **global + 当前会话 + 当前工作区**,不含自定义作用域 / fork 父会话;普通每轮召回仍按原配置。匹配源包括 `tool/call` 的 name / description / 参数、`tool/result` 的失败描述、可见 `assistant/message` 文本、`todo/write` 任务清单、`command/run`、`goal/change`。命中标签后,在下一个 `agent/pre-step` 用标签 + 命中片段检索;工具失败则始终用该工具调用自己的 `description`(取不到才退回错误类别)。中英标签有最小同义词映射(如 `deploy` ↔ 部署、`database` ↔ 数据库)。
133
133
  - **去重**:已注入正文按 **sessionId + 记忆 id/版本** 跳过;只给过标签的会补正文;内容更新会重新评估;compaction 后重置摘要与去重状态。
134
134
  - **标签可检索**:`search` 的词法通道把记录标签也并入检索文本,所以中文正文 + 英文标签也能被标签查询命中。
135
135
  - **审计**:每次摘要/召回/规则评估写入内存审计环,`GET /memory/api/audit?session=<id>` 可查触发原因、阶段、候选、正文、标签、去重、省略原因与各通道预算;不记录凭据。
@@ -349,6 +349,16 @@ tools/build-single-package.mjs 构建(产物契约检查 + 可选加载验证)
349
349
 
350
350
  ## 版本
351
351
 
352
+ - **0.9.10** —— 修复 `memory_get` 没有注册:
353
+ - `memoryTools()` 一直有 `memory_get` 的实现,但工具注册层漏了 `register(tools.memory_get, …)`,所以模型侧只能看到 save/search/forget/list 四个工具。
354
+ - 现在注册完整五个工具;`memory_get` 输出完整 id、作用域、类型、标签和全文,找不到的 id 单独列出。
355
+ - 新增静态守卫测试:`memoryTools` 里的每个工具都必须在 `apply.ts` 注册,防止再次“实现了但没注册”。
356
+ - **0.9.9** —— 收敛自动召回作用域与相关性:
357
+ - 自动召回只检索 **global + 当前会话 + 当前工作区** 三个标准作用域。
358
+ - 不再把 `inject.extraScopes` 的自定义作用域或 fork 父会话带进自动召回;普通每轮召回仍按原配置。
359
+ - 标签触发的召回要求命中记录真的带该标签(或同义词);一个泛标签不会再靠向量相似度把完全无关的全局记忆带进来。
360
+ - `pickQueryText` 只取**人类 user 消息**,跳过 memory / runtime / time / skill 等合成上下文,避免把上一块召回摘要当成下一轮查询。
361
+ - `autoRecallScopes()`、合成消息过滤、标签过滤都有单元测试。
352
362
  - **0.9.8** —— 设置页重写为卡片式:
353
363
  - 每个开关都有可见 label、说明和「已开启 / 已关闭」状态,不再只靠 tooltip;数值项也有独立 label 与提示。
354
364
  - 分组改成卡片:每轮召回 / 印象形态 / 会话摘要 / 记忆使用策略 / 硬性规则 / 自动召回 / 轮末提醒 / 侧栏入口;规则卡显示当前规则条数与作用域数。
@@ -28,6 +28,7 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm'
28
28
  import {
29
29
  MemoryDigester,
30
30
  MemoryInjector,
31
+ autoRecallScopes,
31
32
  hasRecallMessage,
32
33
  normalizeExtraScopes,
33
34
  pickQueryText,
@@ -116,6 +117,7 @@ export function apply(ctx , config = {}) {
116
117
  const signals = new BehaviorSignalStore()
117
118
  const callMeta = new Map ()
118
119
  const sessionScopes = new Map ()
120
+ const sessionAutoScopes = new Map ()
119
121
  const tagCache = new Map ()
120
122
  let attachedMemory = null
121
123
 
@@ -164,6 +166,24 @@ export function apply(ctx , config = {}) {
164
166
  return []
165
167
  }
166
168
 
169
+ /** 自动召回专用范围:只保留 global + 当前会话 + 当前工作区。 */
170
+ const autoScopesForSession = (
171
+ sessionId ,
172
+ memory ,
173
+ session ,
174
+ fallback ,
175
+ ) => {
176
+ const known = sessionAutoScopes.get(sessionId)
177
+ if (known !== undefined) return known
178
+ let resolved
179
+ try {
180
+ resolved = memory?.resolveReadScopes?.({ session })
181
+ } catch { resolved = undefined }
182
+ const scopes = autoRecallScopes(resolved ?? fallback)
183
+ if (scopes !== undefined) sessionAutoScopes.set(sessionId, scopes)
184
+ return scopes
185
+ }
186
+
167
187
  /**
168
188
  * 触发词 = 设置里的额外标签 ∪ 当前记忆库里已有的标签(可关)。
169
189
  * 后者让“记忆标签”本身成为触发词,不需要用户把每个标签抄进设置。
@@ -272,6 +292,7 @@ export function apply(ctx , config = {}) {
272
292
  signals.clear(sessionId)
273
293
  digester.reset(sessionId)
274
294
  sessionScopes.delete(sessionId)
295
+ sessionAutoScopes.delete(sessionId)
275
296
  for (const key of tagCache.keys()) if (key.startsWith(`${sessionId}|`)) tagCache.delete(key)
276
297
  callMeta.clear()
277
298
  return
@@ -279,7 +300,9 @@ export function apply(ctx , config = {}) {
279
300
  const settings = enabled ? settingsOf() : undefined
280
301
  const auto = settings?.autoRecall
281
302
  if (!auto?.enabled) return
282
- const scopes = scopesForSession(sessionId, memory , session)
303
+ const allScopes = scopesForSession(sessionId, memory , session)
304
+ const scopes = autoScopesForSession(sessionId, memory, session, allScopes)
305
+ if (scopes === undefined) return
283
306
  const tags = triggerTags(memory , sessionId, scopes, auto)
284
307
 
285
308
  if (type === 'tool/call') {
@@ -391,8 +414,14 @@ export function apply(ctx , config = {}) {
391
414
  const sessionId = sessionIdOf(agent)
392
415
  const scopes = readScopesFor(memory, agent)
393
416
  if (sessionId !== undefined && scopes !== undefined) sessionScopes.set(sessionId, [...scopes])
417
+ let autoScopes
418
+ try { autoScopes = autoRecallScopes(memory.resolveReadScopes?.(agent) ) } catch { autoScopes = undefined }
419
+ if (autoScopes === undefined) autoScopes = autoRecallScopes(scopes)
420
+ if (sessionId !== undefined && autoScopes !== undefined) sessionAutoScopes.set(sessionId, [...autoScopes])
394
421
  const exclude = excludedIds(memory, scopes)
422
+ const excludeAuto = excludedIds(memory, autoScopes)
395
423
  const signal = sessionId === undefined ? undefined : signals.take(sessionId)
424
+ const usableSignal = autoScopes === undefined ? undefined : signal
396
425
  const userQuery = pickQueryText(input.messages )
397
426
 
398
427
  // 摘要(每个会话一次)、召回(每轮有新内容时)、轮末提醒(下一轮首步)合成
@@ -470,24 +499,27 @@ export function apply(ctx , config = {}) {
470
499
 
471
500
  // 行为信号优先:发布/推送/失败事件触发定向查询;没有信号才走普通用户消息召回。
472
501
  // 同一轮普通 query 已处理过时跳过重复检索(去重状态仍会兜底)。
473
- const skipNormalRecall = signal === undefined && step > 1 && sessionId !== undefined
502
+ const skipNormalRecall = usableSignal === undefined && step > 1 && sessionId !== undefined
474
503
  && userQuery !== '' && injectionState.lastQueryOf(sessionId) === userQuery
475
504
  if (!skipNormalRecall) {
505
+ const recallScopes = usableSignal === undefined ? scopes : autoScopes
506
+ const recallExclude = usableSignal === undefined ? exclude : excludeAuto
476
507
  const recall = await injector.maybeInjectDetailed(
477
- { messages: input.messages , signal: input.signal, ...(scopes !== undefined ? { scopes } : {}), ...(sessionId !== undefined ? { sessionId } : {}) },
508
+ { messages: input.messages , signal: input.signal, ...(recallScopes !== undefined ? { scopes: recallScopes } : {}), ...(sessionId !== undefined ? { sessionId } : {}) },
478
509
  { messages: decision.messages },
479
510
  {
480
511
  ...(sessionId !== undefined ? { sessionId } : {}),
481
- ...(signal !== undefined ? { query: signal.query, trigger: signal.reason, force: true } : { trigger: 'turn_start' }),
482
- excludeIds: exclude,
512
+ ...(usableSignal !== undefined ? { query: usableSignal.query, trigger: usableSignal.reason, force: true } : { trigger: 'turn_start' }),
513
+ ...(usableSignal?.tag ? { tag: usableSignal.tag, requireTag: true } : {}),
514
+ excludeIds: recallExclude,
483
515
  },
484
516
  )
485
517
  if (recall?.text) parts.push(recall.text)
486
518
  if (recall) {
487
519
  recordAudit({
488
520
  ...(sessionId !== undefined ? { sessionId } : {}),
489
- trigger: signal?.reason ?? 'turn_start',
490
- phase: signal?.phase ?? detectPhase(userQuery),
521
+ trigger: usableSignal?.reason ?? 'turn_start',
522
+ phase: usableSignal?.phase ?? detectPhase(userQuery),
491
523
  ...(auditQuery(recall.query) !== undefined ? { query: auditQuery(recall.query) } : {}),
492
524
  candidates: recall.candidates,
493
525
  contentIds: recall.ids,
@@ -496,8 +528,8 @@ export function apply(ctx , config = {}) {
496
528
  dedupSkipped: recall.dedupSkipped,
497
529
  budgets: { recall: auditBudget(settings.recall.tokenBudget, recall.tokens) },
498
530
  retrieval: recall.retrieval,
499
- ...(signal !== undefined
500
- ? { signal: { reason: signal.reason, ...(signal.errorClass ? { errorClass: signal.errorClass } : {}), ...(signal.tool ? { tool: signal.tool } : {}) } }
531
+ ...(usableSignal !== undefined
532
+ ? { signal: { reason: usableSignal.reason, ...(usableSignal.errorClass ? { errorClass: usableSignal.errorClass } : {}), ...(usableSignal.tool ? { tool: usableSignal.tool } : {}), ...(usableSignal.tag ? { tag: usableSignal.tag } : {}), ...(usableSignal.source ? { source: usableSignal.source } : {}) } }
501
533
  : {}),
502
534
  })
503
535
  }
@@ -8,6 +8,7 @@
8
8
 
9
9
  import { estimateTokens } from '../provider/rerank.js'
10
10
  import { normalizeScopeInput } from '../provider/scope.js'
11
+ import { textHasTag } from './signals.js'
11
12
  import { InjectionState } from './state.js'
12
13
 
13
14
 
@@ -59,6 +60,20 @@ export function normalizeExtraScopes(raw , warn
59
60
  return out
60
61
  }
61
62
 
63
+ /**
64
+ * 自动召回的作用域:global + 当前会话 + 当前工作区。
65
+ *
66
+ * 普通每轮召回仍按用户配置使用 session + project + global(可额外加 extraScopes
67
+ * 或 fork 父会话);但行为信号触发的自动召回只认这三个标准范围,不把额外自定义
68
+ * 作用域 / 父会话一起搜进来。没有可用范围时返回 undefined,调用方跳过自动召回。
69
+ */
70
+ export function autoRecallScopes(scopes ) {
71
+ if (scopes === undefined) return undefined
72
+ const out = scopes.filter((scope) =>
73
+ scope === 'global' || scope.startsWith('session:') || scope.startsWith('project:'))
74
+ return out.length > 0 ? out : undefined
75
+ }
76
+
62
77
  /**
63
78
  * 无显式 scope 时的召回范围:当前会话 + 当前项目 + global(provider 解析)
64
79
  * + inject.extraScopes + 父会话(fork 时,只读召回)。
@@ -95,6 +110,8 @@ export function resolveInjectScopes(
95
110
 
96
111
 
97
112
 
113
+                         
114
+
98
115
 
99
116
 
100
117
 
@@ -115,14 +132,21 @@ export function resolveInjectScopes(
115
132
 
116
133
 
117
134
  /**
118
- * Extract the retrieval query: the text of the LAST user message. Synthetic
119
- * context injections (file notices etc.) are user-role too, so scanning from
120
- * the end finds the freshest human-visible input; empty text → no injection.
135
+ * Extract the retrieval query: the text of the LAST **human** user message.
136
+ *
137
+ * Synthetic context messages are also role=user (memory recall, runtime/time
138
+ * context, skill catalog, file notices...). Taking the last user-role message
139
+ * blindly makes the next recall query the previous recall block itself — a
140
+ * cross-project self-recall loop (observed in a dsh-pocket session pulling a
141
+ * dsh-memory global record). Skip every known synthetic source; messages with
142
+ * no source (unit-test scaffolds / older hosts) are treated as human.
121
143
  */
122
144
  export function pickQueryText(messages ) {
123
145
  for (let i = messages.length - 1; i >= 0; i--) {
124
146
  const m = messages[i]
125
147
  if (m.role !== 'user') continue
148
+ const kind = m.source?.kind
149
+ if (kind !== undefined && kind !== '' && kind !== 'user') continue
126
150
  const text = (m.content ?? [])
127
151
  .filter((b) => b.type === 'text' && typeof b.text === 'string')
128
152
  .map((b) => b.text )
@@ -239,6 +263,9 @@ export function recallText(text ) {
239
263
 
240
264
                               
241
265
 
266
+                          
267
+
268
+
242
269
 
243
270
 
244
271
 
@@ -316,8 +343,17 @@ export class MemoryInjector {
316
343
  // 成功检索后记住查询(即使没有新正文):同一 query 的后续 step 不再重复全量检索。
317
344
  this.state.setLastQuery(sessionId, query)
318
345
 
346
+ // 标签触发的自动召回:只接受真正带该标签(或同义词)的记录。
347
+ // 否则一个泛标签(如 git)会把向量上勉强相关、但完全没有该标签的全局记忆
348
+ // 带进当前项目 —— 实测 dsh-pocket 会话因此注入过 dsh-memory 的 digest 记忆。
349
+ const requiredTag = options.requireTag === true && typeof options.tag === 'string' && options.tag.trim() !== ''
350
+ ? options.tag.trim()
351
+ : ''
352
+ const taggedHits = requiredTag === ''
353
+ ? hits
354
+ : hits.filter((hit) => (hit.record.tags ?? []).some((tag) => textHasTag(String(tag), requiredTag)))
319
355
  const seenIds = options.excludeIds
320
- const candidates = seenIds === undefined ? hits : hits.filter((hit) => !seenIds.has(hit.record.id))
356
+ const candidates = seenIds === undefined ? taggedHits : taggedHits.filter((hit) => !seenIds.has(hit.record.id))
321
357
  const { fresh, deduplicated, updated } = this.state.filterNewContent(
322
358
  sessionId,
323
359
  candidates.map((hit) => hit.record),
@@ -120,6 +120,17 @@ export function apply(ctx , config = {}) {
120
120
  const summary = scopeSummary(value, agent)
121
121
  return summary ? `${body}\n${summary}` : body
122
122
  })
123
+
124
+ register(tools.memory_get, (value, _args, exec) => {
125
+ const agent = (exec )?.agent
126
+ const body = value.records.map((r) => {
127
+ const tags = Array.isArray(r.tags) && r.tags.length > 0 ? ` · ${r.tags.join(', ')}` : ''
128
+ return `[${r.id}] (${renderScope(r.scope, agent)}/${r.kind}${tags})\n${r.content}`
129
+ }).join('\n\n')
130
+ const missing = value.missing.length > 0 ? `未找到:${value.missing.join(', ')}` : ''
131
+ if (body === '') return missing || '没有找到记忆。'
132
+ return missing === '' ? body : `${body}\n\n${missing}`
133
+ })
123
134
  }
124
135
 
125
136
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@restregular/dsh-memory",
3
- "version": "0.9.8",
3
+ "version": "0.9.10",
4
4
  "description": "DeepSeek Harness 本地长期记忆(单包单入口):JSONL 存储 + 本地向量检索(BGE-M3)+ 五个模型工具 + 自动召回注入 + 管理面板。",
5
5
  "icon": "./icon.svg",
6
6
  "type": "module",