dsh-memu-memory 1.3.7 → 1.3.8

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 (54) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +58 -0
  3. package/README.md +7 -7
  4. package/README.zh.md +7 -7
  5. package/docs/client-conventions.md +1 -0
  6. package/docs/contributing.md +2 -2
  7. package/docs/memory-semantics.md +7 -6
  8. package/docs/troubleshooting.md +74 -7
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/client.js +150 -81
  11. package/lib/consolidation-ledger.js +6 -2
  12. package/lib/inbound.js +24 -9
  13. package/lib/inject.js +379 -215
  14. package/lib/memory.js +704 -181
  15. package/lib/paths.js +24 -0
  16. package/lib/private.js +242 -132
  17. package/lib/rpc.js +53 -6
  18. package/lib/snippet.js +49 -28
  19. package/lib/state.js +185 -26
  20. package/lib/tools.js +137 -28
  21. package/lib/webui.js +25 -1
  22. package/lib/worker-pool.js +260 -26
  23. package/package.json +1 -1
  24. package/scripts/check-i18n.mjs +19 -0
  25. package/scripts/recall-bench.mjs +4 -4
  26. package/scripts/simulate-injection.mjs +3 -0
  27. package/tests/activity-wiring.test.mjs +52 -0
  28. package/tests/client-render.test.mjs +207 -0
  29. package/tests/consolidation-feed.test.mjs +26 -0
  30. package/tests/consolidation-fork.test.mjs +587 -26
  31. package/tests/cross-library-recall.test.mjs +156 -0
  32. package/tests/cue.test.mjs +15 -2
  33. package/tests/hybrid-recall.test.mjs +488 -0
  34. package/tests/inbound.test.mjs +49 -4
  35. package/tests/inject-conflict.test.mjs +70 -9
  36. package/tests/inject-guide.test.mjs +13 -1
  37. package/tests/inject.test.mjs +10 -0
  38. package/tests/injection-budget.test.mjs +101 -0
  39. package/tests/injection-chain.test.mjs +37 -0
  40. package/tests/injection-rollback.test.mjs +172 -9
  41. package/tests/issue2-chain.test.mjs +169 -0
  42. package/tests/lexicon-inject.test.mjs +33 -5
  43. package/tests/managed-memory.test.mjs +625 -1
  44. package/tests/media.test.mjs +1 -1
  45. package/tests/new-session-gate.test.mjs +280 -25
  46. package/tests/open-loop-date.test.mjs +11 -1
  47. package/tests/recall-intent.test.mjs +52 -3
  48. package/tests/simulate-injection.test.mjs +4 -4
  49. package/tests/snippet.test.mjs +33 -1
  50. package/tests/state.test.mjs +8 -3
  51. package/tests/tool-schema.test.mjs +52 -0
  52. package/tests/tools.test.mjs +394 -0
  53. package/tests/webui.test.mjs +16 -2
  54. package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/tools.js CHANGED
@@ -2,11 +2,11 @@ import { defineTool } from '@deepseek-ai/dsh-tools'
2
2
  import {
3
3
  privateRemember, privateRecall, privateList, privateUpdate, privateArchive,
4
4
  privateUnpin, globalRecall, globalList, bindingFor, peekBinding, sessionIdOf, domainOf, relativeTime,
5
- isDatedSalientDate,
5
+ isDatedSalientDate, readMemoryByRef,
6
6
  } from './memory.js'
7
7
  import { engineStatus, ENGINE_VERSION } from './engine.js'
8
8
  import { getMissingVectorLibraries } from './local-vector-service.js'
9
- import { centeredSnippet } from './snippet.js'
9
+ import { centeredSnippetWindow } from './snippet.js'
10
10
  import { redactSecrets } from './paths.js'
11
11
  import { linkEntries, createEntity, listEntities, updateRelationship } from './graph.js'
12
12
  import { normalizeEntityName } from './private-links.js'
@@ -34,7 +34,97 @@ function errorText(error) {
34
34
  if (error?.code === 'MEMU_COMMAND_FAILED') {
35
35
  return `MemU 命令失败:${message}`
36
36
  }
37
- return `dsh-memu-memory error: ${message}`
37
+ const code = typeof error?.code === 'string' && /^[A-Z][A-Z0-9_]{0,79}$/.test(error.code) ? ` [${error.code}]` : ''
38
+ return `dsh-memu-memory error${code}: ${redactSecrets(message)}`
39
+ }
40
+
41
+ function recallError(code, message) {
42
+ throw Object.assign(new Error(message), { code })
43
+ }
44
+
45
+ // The host's value-schema DSL has no minimum/maximum or cross-field rules.
46
+ // Validate before any memory access; natural searches cannot target a library.
47
+ function parseRecallRequest(args, scope) {
48
+ if (typeof args.query !== 'string' || !args.query.trim()) recallError('INVALID_RECALL_ARGUMENT', 'query is required')
49
+ const exact = !/\s/.test(args.query) && /^g?mem[-_][a-z0-9_-]+(?:\.md)?$/i.test(args.query)
50
+ const view = args.view === undefined ? 'auto' : args.view
51
+ if (!['auto', 'snippet', 'full'].includes(view)) recallError('INVALID_RECALL_ARGUMENT', 'view must be auto, snippet or full')
52
+ if (args.topK !== undefined && (!Number.isInteger(args.topK) || args.topK < 1 || args.topK > 20)) {
53
+ recallError('INVALID_RECALL_ARGUMENT', 'topK must be an integer in 1..20')
54
+ }
55
+ if (!exact && view === 'full') recallError('EXACT_ID_REQUIRED', 'view=full requires an exact memory id (no whitespace)')
56
+ if (!exact && ['libraryId', 'offset', 'limitChars', 'revision'].some((key) => Object.hasOwn(args, key))) {
57
+ recallError('INVALID_RECALL_ARGUMENT', 'libraryId/offset/limitChars/revision require an exact memory id, not a natural-language query')
58
+ }
59
+ if (Object.hasOwn(args, 'libraryId') && (scope !== 'private' || typeof args.libraryId !== 'string' || !args.libraryId.trim())) {
60
+ recallError('INVALID_RECALL_ARGUMENT', 'libraryId is a nonempty string for private exact reads only')
61
+ }
62
+ const offset = args.offset === undefined ? 0 : args.offset
63
+ const limitChars = args.limitChars === undefined ? 2000 : args.limitChars
64
+ if (!Number.isSafeInteger(offset) || offset < 0) recallError('INVALID_RECALL_ARGUMENT', 'offset must be an integer >= 0')
65
+ if (!Number.isInteger(limitChars) || limitChars < 1 || limitChars > 8000) recallError('INVALID_RECALL_ARGUMENT', 'limitChars must be an integer in 1..8000')
66
+ if (args.revision !== undefined && (typeof args.revision !== 'string' || !args.revision)) recallError('INVALID_RECALL_ARGUMENT', 'revision must be a nonempty string')
67
+ if (offset > 0 && !args.revision) recallError('REVISION_REQUIRED', 'offset > 0 requires revision from the first page')
68
+ return { exact, query: args.query, view: view === 'auto' ? (exact ? 'full' : 'snippet') : view,
69
+ topK: args.topK, libraryId: args.libraryId ?? null, offset, limitChars, revision: args.revision ?? null }
70
+ }
71
+
72
+ function recallReadParameters() {
73
+ return {
74
+ view: { type: 'string', enum: ['auto', 'snippet', 'full'], default: 'auto', description: 'auto: exact id reads full, natural query returns a snippet. full requires an exact id; snippet stays short.' },
75
+ offset: { type: 'integer', description: 'Exact id only: 0-based offset in redacted Unicode code points, integer >= 0. Continuing requires revision.' },
76
+ limitChars: { type: 'integer', description: 'Exact id only: page size in redacted Unicode code points, 1..8000; default 2000.' },
77
+ revision: { type: 'string', description: 'Exact id only: redacted body SHA256 from the first page; required when offset > 0. Changed bodies return MEMORY_CHANGED.' },
78
+ }
79
+ }
80
+
81
+ function refText(scope, libraryId, id) {
82
+ return `scope=${scope} libraryId=${JSON.stringify(libraryId ?? null)} id=${JSON.stringify(id)}`
83
+ }
84
+
85
+ // Only the read API's redacted page and whitelisted metadata are rendered. No
86
+ // entry/raw body fallback, second body read or conflict expansion is permitted.
87
+ function renderMemoryPage(page, request) {
88
+ const ref = page.ref
89
+ const provenance = page.provenance || {}
90
+ const restrictions = page.restrictions || {}
91
+ let body = page.body
92
+ let pagination = page.pagination
93
+ if (request.view === 'snippet') {
94
+ const snippet = centeredSnippetWindow(body, request.query)
95
+ const offset = pagination.offset + snippet.start
96
+ const end = pagination.offset + snippet.end
97
+ pagination = { offset, returnedChars: snippet.returnedChars, totalChars: pagination.totalChars,
98
+ truncated: offset > 0 || end < pagination.totalChars, nextOffset: end < pagination.totalChars ? end : null }
99
+ body = snippet.body
100
+ }
101
+ const lines = [
102
+ `${ref.scope === 'private' ? '私有' : '全局'}记忆 [${ref.id}] ${redactSecrets(page.title || '(untitled)')}`,
103
+ `library=${ref.libraryId ?? 'global'} · source=${provenance.source || 'inferred'} · source_kind=${provenance.sourceKind || provenance.source || 'inferred'} · speaker_id=${provenance.speakerId ?? '?'} · view=${request.view}`,
104
+ `ref: ${refText(ref.scope, ref.libraryId, ref.id)}`,
105
+ `visibility=${restrictions.visibility || 'shared'} · disclosure=${restrictions.disclosure || 'can_tell'} · status=${restrictions.status || 'active'} · layer=${restrictions.layer || 'long_term'}`,
106
+ `domain=${page.domain || 'unknown'} · unbound=${page.unbound === true}`,
107
+ `pagination: unit=codepoint · offset=${pagination.offset} · returned_chars=${pagination.returnedChars} · total_chars=${pagination.totalChars} · truncated=${pagination.truncated} · next_offset=${pagination.nextOffset ?? 'null'}`,
108
+ `revision=${page.revision}`,
109
+ ]
110
+ const header = redactSecrets(lines.join('\n'))
111
+ const footer = []
112
+ if (pagination.nextOffset !== null) {
113
+ footer.push(`next: memu_${ref.scope}_recall query=${JSON.stringify(ref.id)} view="full"${ref.scope === 'private' ? ` libraryId=${JSON.stringify(ref.libraryId)}` : ''} offset=${pagination.nextOffset} limitChars=${request.limitChars} revision=${JSON.stringify(page.revision)}`)
114
+ }
115
+ for (const related of page.related || []) {
116
+ if (related.kind === 'conflict') footer.push(`conflict: [${related.id}] ${refText(ref.scope, related.libraryId, related.id)}· available=${related.available !== false}(尚未读取另一版,不能据此裁决)`)
117
+ }
118
+ return `${header}\nbody:\n${body}${footer.length ? '\n' + redactSecrets(footer.join('\n')) : ''}`
119
+ }
120
+
121
+ function searchSnippet(item, query) {
122
+ // Redact before cutting: a key split at the snippet boundary must not leak.
123
+ return centeredSnippetWindow(redactSecrets(item.content || ''), query)
124
+ }
125
+
126
+ function searchRefLine(scope, item, snippet, homeLibraryId = null) {
127
+ return ` view=snippet · ref: ${refText(scope, scope === 'private' ? (item.libraryId || homeLibraryId) : null, item.name)} · unit=codepoint · offset=${snippet.start} · returned_chars=${snippet.returnedChars} · total_chars=${snippet.totalChars} · truncated=${snippet.truncated}`
38
128
  }
39
129
 
40
130
  // 词典核心(lib/lexicon.js)按需加载:工具注册面不能被一个
@@ -124,7 +214,7 @@ function formatPrivateItem(item, index, options = {}) {
124
214
  const layer = entry.layer || 'long_term'
125
215
  const status = entry.status || 'active'
126
216
  const source = entry.source || 'inferred'
127
- // B7:默认值不逐条重写(guide 已说明缺省口径),非默认 layer/status/source 仍必须输出。
217
+ // B7:默认 layer/status 不逐条重写;显式读取始终标明来源,避免把推断当引文。
128
218
  const flags = [
129
219
  layer !== 'long_term' ? `layer=${layer}` : '',
130
220
  status !== 'active' ? `status=${status}` : '',
@@ -133,7 +223,9 @@ function formatPrivateItem(item, index, options = {}) {
133
223
  ].filter(Boolean).join(' ')
134
224
  const lines = [`${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`]
135
225
  if (flags) lines.push(` ${flags}`)
136
- if (source !== 'inferred') lines.push(` source=${source}`)
226
+ lines.push(` source=${source}`)
227
+ if (entry.source_kind) lines.push(` source_kind=${entry.source_kind}`)
228
+ if (entry.speaker_id) lines.push(` speaker_id=${entry.speaker_id}`)
137
229
  // Same relative phrasing as the injected block: one memory must not read as
138
230
  // "2026-10-20" in a tool result and "8 天前" in the prompt.
139
231
  const when = relativeTime(entry.updatedAt || entry.createdAt)
@@ -164,13 +256,13 @@ function formatPrivateItem(item, index, options = {}) {
164
256
  const brief = emotionBrief(entry)
165
257
  if (brief) lines.push(` emo=${brief}`)
166
258
  else if (typeof entry.moodValence === 'number' && entry.moodValence !== 0) lines.push(` mood=${entry.moodValence.toFixed(2)}`)
167
- if (item.content) {
168
- const body = options.query
169
- ? centeredSnippet(item.content, options.query)
170
- : truncate(item.content, 1200)
171
- lines.push(' ' + body.replace(/\n/g, '\n '))
259
+ const snippet = searchSnippet(item, options.query)
260
+ lines.push(searchRefLine('private', item, snippet, options.homeLibraryId))
261
+ if (snippet.body) lines.push(' ' + snippet.body.replace(/\n/g, '\n '))
262
+ for (const related of item.related || []) {
263
+ if (related.kind === 'conflict') lines.push(` conflict: ${refText('private', related.libraryId || item.libraryId || options.homeLibraryId, related.id)} · conflictComplete=${related.complete === true} · available=${related.available !== false}(关系指针,不包含另一版正文)`)
264
+ else lines.push(` related: [${related.id}] ${related.title} (${related.kind})`)
172
265
  }
173
- for (const related of item.related || []) lines.push(` related: [${related.id}] ${related.title} (${related.kind})`)
174
266
  for (const image of entry.attachments || []) lines.push(` image: ${image.sha256} ${image.caption || '[图片]'}${image.missing ? ' [missing]' : ''} (${image.captionBy || 'none'})`)
175
267
  return redactSecrets(lines.join('\n'))
176
268
  }
@@ -188,12 +280,13 @@ function formatGlobalItem(item, index, options = {}) {
188
280
  const when = relativeTime(entry.updatedAt || entry.createdAt)
189
281
  if (when) lines.push(` updated=${when}`)
190
282
  if (Array.isArray(entry.appliesTo) && entry.appliesTo.length > 0) lines.push(` applies_to=${entry.appliesTo.join(',')}`)
191
- if (item.content) {
192
- const body = options.query
193
- ? centeredSnippet(item.content, options.query)
194
- : truncate(item.content, 1200)
195
- lines.push(' ' + body.replace(/\n/g, '\n '))
196
- }
283
+ lines.push(` source=${entry.source || 'inferred'} · source_kind=${entry.source_kind || entry.source || 'inferred'}`)
284
+ if (entry.speaker_id) lines.push(` speaker_id=${entry.speaker_id}`)
285
+ if (entry.visibility) lines.push(` visibility=${entry.visibility}`)
286
+ if (entry.disclosure) lines.push(` disclosure=${entry.disclosure}`)
287
+ const snippet = searchSnippet(item, options.query)
288
+ lines.push(searchRefLine('global', item, snippet))
289
+ if (snippet.body) lines.push(' ' + snippet.body.replace(/\n/g, '\n '))
197
290
  return redactSecrets(lines.join('\n'))
198
291
  }
199
292
 
@@ -539,13 +632,21 @@ export function registerTools(ctx, { only = null } = {}) {
539
632
 
540
633
  tools.push(toolBase(
541
634
  'memu_private_recall',
542
- 'Retrieve relevant private memories from the library bound to this conversation. Use it when the user refers to something from before, asks you to remember, or the current task may depend on earlier context.',
635
+ 'Retrieve relevant private memories from the library bound to this conversation. Natural queries return short snippets; exact mem- ids (or unique prefixes, optionally .md, no whitespace) read one redacted body page with auto/full. Secret memories remain explicitly readable with disclosure restrictions. Use libraryId only to disambiguate an allowed exact reference, never to widen scope.',
543
636
  {
544
- query: { type: 'string', required: true, description: 'Natural-language query.' },
545
- topK: { type: 'integer', description: 'Max entries; default from settings.' },
637
+ query: { type: 'string', required: true, description: 'Natural-language search or exact mem- id / unique prefix (optional .md, no whitespace).' },
638
+ topK: { type: 'integer', description: 'Search row limit, integer 1..20; default from settings. Exact reads return one entry.' },
639
+ ...recallReadParameters(),
640
+ libraryId: { type: 'string', description: 'Private exact id only: owning library from a returned ref; must be in the allowed library set.' },
546
641
  },
547
642
  async (args, exec) => {
548
- const result = await privateRecall({ exec, query: args.query, topK: args.topK })
643
+ const request = parseRecallRequest(args, 'private')
644
+ if (request.exact) {
645
+ const page = readMemoryByRef({ exec, scope: 'private', id: request.query, libraryId: request.libraryId,
646
+ offset: request.offset, limitChars: request.limitChars, revision: request.revision })
647
+ return renderMemoryPage(page, request)
648
+ }
649
+ const result = await privateRecall({ exec, query: request.query, topK: request.topK, purpose: 'explicit' })
549
650
  // Surface a degraded semantic leg on the explicit tool path too; silently
550
651
  // returning fewer hits would make a failed backend look like an empty library.
551
652
  const warning = (result.errors || []).length ? `\n注意:本次召回已降级:${(result.errors || []).join('; ')}` : ''
@@ -803,18 +904,26 @@ export function registerTools(ctx, { only = null } = {}) {
803
904
 
804
905
  tools.push(toolBase(
805
906
  'memu_global_recall',
806
- 'Retrieve cross-session global memories applicable to the current domain. Global memory is read-only for the main agent.',
907
+ 'Retrieve cross-session global memories applicable to the current domain. Natural queries return snippets; exact gmem- ids (or unique prefixes, optionally .md, no whitespace) read one redacted body page with auto/full. Global memory stays read-only with existing automatic/domain eligibility.',
807
908
  {
808
- query: { type: 'string', required: true },
809
- topK: { type: 'integer' },
909
+ query: { type: 'string', required: true, description: 'Natural-language search or exact gmem- id / unique prefix (optional .md, no whitespace).' },
910
+ topK: { type: 'integer', description: 'Search row limit, integer 1..20; default from settings. Exact reads return one entry.' },
911
+ ...recallReadParameters(),
810
912
  },
811
913
  async (args, exec) => {
812
- const result = await globalRecall({ exec, query: args.query, topK: args.topK })
813
- if (!result.files?.length) return `全局记忆(domain=${result.domain})没有命中。`
914
+ const request = parseRecallRequest(args, 'global')
915
+ if (request.exact) {
916
+ const page = readMemoryByRef({ exec, scope: 'global', id: request.query,
917
+ offset: request.offset, limitChars: request.limitChars, revision: request.revision })
918
+ return renderMemoryPage(page, request)
919
+ }
920
+ const result = await globalRecall({ exec, query: request.query, topK: request.topK, purpose: 'explicit' })
921
+ const warning = (result.errors || []).length ? `\n注意:本次召回已降级:${(result.errors || []).join('; ')}` : ''
922
+ if (!result.files?.length) return `全局记忆(domain=${result.domain})没有命中。${warning}`
814
923
  return [
815
924
  `全局记忆(domain=${result.domain})`,
816
- ...result.files.map((f, i) => formatGlobalItem(f, i + 1, { query: args.query })),
817
- ].join('\n\n')
925
+ ...result.files.map((f, i) => formatGlobalItem(f, i + 1, { query: request.query })),
926
+ ].join('\n\n') + warning
818
927
  },
819
928
  { isConcurrencySafe: () => true },
820
929
  ))
package/lib/webui.js CHANGED
@@ -11,6 +11,11 @@ export const SETTINGS_PATH = '/dsh-memu-memory/settings'
11
11
  const require = createRequire(import.meta.url)
12
12
 
13
13
  export function standaloneAsset(pathname) {
14
+ const file = assetFile(pathname)
15
+ return file ? fs.readFileSync(file, pathname.endsWith('.png') ? undefined : 'utf8') : null
16
+ }
17
+
18
+ function assetFile(pathname) {
14
19
  const assets = {
15
20
  '/dsh-memu-memory/ui-assets/react.js': () => path.join(path.dirname(require.resolve('react/package.json')), 'umd', 'react.production.min.js'),
16
21
  '/dsh-memu-memory/ui-assets/react-dom.js': () => path.join(path.dirname(require.resolve('react-dom/package.json')), 'umd', 'react-dom.production.min.js'),
@@ -22,7 +27,26 @@ export function standaloneAsset(pathname) {
22
27
  '/dsh-memu-memory/ui-assets/mark.svg': () => path.join(DIR, 'mark.svg'),
23
28
  }
24
29
  const resolve = assets[pathname]
25
- return resolve ? fs.readFileSync(resolve(), pathname.endsWith('.png') ? undefined : 'utf8') : null
30
+ return resolve ? resolve() : null
31
+ }
32
+
33
+ // 首屏要顺次拉 react/react-dom/standalone/client 四个脚本(client 约 600KB)。
34
+ // no-cache 无校验器时浏览器每次全量重传;按 mtime+size 缓存内容并发 ETag,
35
+ // 命中 If-None-Match 回 304 空体。插件更新会改文件 mtime,校验器随之失效。
36
+ const assetCache = new Map()
37
+ export function standaloneAssetResponse(pathname, ifNoneMatch = null) {
38
+ const file = assetFile(pathname)
39
+ if (!file) return null
40
+ let stat
41
+ try { stat = fs.statSync(file) } catch { return null }
42
+ let cached = assetCache.get(pathname)
43
+ if (!cached || cached.mtimeMs !== stat.mtimeMs || cached.size !== stat.size) {
44
+ const body = fs.readFileSync(file, pathname.endsWith('.png') ? undefined : 'utf8')
45
+ cached = { mtimeMs: stat.mtimeMs, size: stat.size, body, etag: `"${stat.mtimeMs.toString(36)}-${stat.size.toString(36)}"` }
46
+ assetCache.set(pathname, cached)
47
+ }
48
+ if (ifNoneMatch && ifNoneMatch === cached.etag) return { notModified: true, etag: cached.etag }
49
+ return { notModified: false, body: cached.body, etag: cached.etag }
26
50
  }
27
51
 
28
52
  /** The studio stylesheet lives next to this file so it can be read and edited as CSS. */