dsh-memu-memory 1.2.6 → 1.2.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 (68) hide show
  1. package/AGENTS.md +1 -1
  2. package/README.md +10 -15
  3. package/README.zh.md +10 -15
  4. package/docs/contributing.md +1 -1
  5. package/docs/host-adaptation.md +1 -1
  6. package/docs/memory-semantics.md +26 -4
  7. package/docs/troubleshooting.md +3 -1
  8. package/lib/backup.js +1 -1
  9. package/lib/binding-diagnostics.js +2 -2
  10. package/lib/budget.js +31 -0
  11. package/lib/client.js +276 -28
  12. package/lib/commitment.js +138 -0
  13. package/lib/consolidation-receipt.js +2 -0
  14. package/lib/consolidation-worker.js +3 -0
  15. package/lib/curator-policy.js +98 -0
  16. package/lib/fork-model.js +312 -0
  17. package/lib/freshness.js +24 -0
  18. package/lib/inject.js +117 -10
  19. package/lib/lexicon.js +1 -1
  20. package/lib/local-vector-service.js +4 -1
  21. package/lib/memory.js +600 -43
  22. package/lib/memu.js +4 -0
  23. package/lib/private.js +49 -8
  24. package/lib/prompts/private-consolidation.mixed.md +3 -2
  25. package/lib/prompts/private-consolidation.rp.md +7 -1
  26. package/lib/prompts/private-policy.mixed.md +1 -0
  27. package/lib/prompts/private-policy.rp.md +5 -1
  28. package/lib/prompts/system-guide.rp.md +3 -0
  29. package/lib/recall-cache.js +212 -0
  30. package/lib/rpc.js +44 -6
  31. package/lib/snippet.js +25 -0
  32. package/lib/state.js +43 -1
  33. package/lib/temporal.js +329 -0
  34. package/lib/text-retrieval.js +292 -28
  35. package/lib/tokenizer-v2.js +295 -0
  36. package/lib/tools.js +81 -4
  37. package/lib/webui/standalone.css +17 -1
  38. package/package.json +1 -1
  39. package/scripts/bench-recall.mjs +142 -0
  40. package/scripts/check-seed-compat.mjs +118 -0
  41. package/tests/backup.test.mjs +2 -2
  42. package/tests/commitment.test.mjs +144 -0
  43. package/tests/consolidation-fork.test.mjs +122 -5
  44. package/tests/curator-clusters.test.mjs +7 -1
  45. package/tests/curator-pairing.test.mjs +52 -8
  46. package/tests/disclosure.test.mjs +34 -17
  47. package/tests/dynamic-rrf.test.mjs +179 -0
  48. package/tests/fact-version.test.mjs +128 -0
  49. package/tests/fork-model.test.mjs +345 -0
  50. package/tests/help-page.test.mjs +1 -1
  51. package/tests/inject-conflict.test.mjs +94 -0
  52. package/tests/inject-guide.test.mjs +5 -3
  53. package/tests/inject.test.mjs +2 -2
  54. package/tests/injection-intent-budget.test.mjs +92 -0
  55. package/tests/lexicon-frequency.test.mjs +1 -1
  56. package/tests/loader.mjs +3 -0
  57. package/tests/memory-chain.test.mjs +140 -0
  58. package/tests/memory-fields.test.mjs +134 -0
  59. package/tests/memu-resident.test.mjs +33 -0
  60. package/tests/negation-polarity.test.mjs +135 -0
  61. package/tests/prompt-semantics.test.mjs +51 -0
  62. package/tests/query-decompose.test.mjs +62 -0
  63. package/tests/recall-cache.test.mjs +292 -0
  64. package/tests/recall-intent.test.mjs +100 -0
  65. package/tests/speaker-provenance.test.mjs +120 -0
  66. package/tests/stubs/dsh-llm-pi-ai.js +13 -0
  67. package/tests/temporal.test.mjs +124 -0
  68. package/tests/tokenizer-v2.test.mjs +142 -0
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Tokenizer V2 — 智能分层分词器(召回升级 P0-1)。
3
+ *
4
+ * 相对 lib/text-retrieval.js 的 V1 口径(CJK 只出 bigram),V2 解决:
5
+ * - R-01:CJK 只有 bigram,缺 unigram/trigram 层级,短查询命中不了子词;
6
+ * - R-03:无实体保护,日期/周几/数字/邮箱/URL 被拆散。
7
+ *
8
+ * 设计原则:
9
+ * 1. 英文与 latin 口径与 V1 完全一致([a-z0-9]+(?:[._-][a-z0-9]+)*,≥2 字符);
10
+ * 2. CJK 输出 unigram + bigram + trigram 三层;完整 run 只在长度 ≤4 时保留,
11
+ * 长句 run 的完整串是噪声且会抬高 BM25 文档长度,不收;
12
+ * 3. 实体(日期/周几/数字/百分比/邮箱/URL)整体成 token,不被 n-gram 拆散;
13
+ * 日期/周几正则与 text-retrieval.js 的 numericSet 同口径(周X/星期X 无空格);
14
+ * 4. 纯函数:No state, no IO, no clock——同输入同输出;去重用 Set 的插入序
15
+ * (先实体、后英文、后 CJK run,保留首次出现),不做任何排序。
16
+ *
17
+ * 集成方式(双轨制):lib/text-retrieval.js 的 tokenize/tokenStream 按
18
+ * lib/curator-policy.js 的 TOKENIZER_V2 开关委托到这里;开关关闭走 V1 原路径。
19
+ */
20
+
21
+ // —— 规范化与清理——
22
+
23
+ /** NFKC 归一化 + 小写化(与 V1 的预处理一致)。 */
24
+ export function normalizeAndLower(text) {
25
+ return String(text || '').normalize('NFKC').toLowerCase()
26
+ }
27
+
28
+ // —— 英文 tokenization(保持 V1 逻辑)——
29
+
30
+ /**
31
+ * 英文与 latin:与 V1 完全同口径——[a-z0-9]+(?:[._-][a-z0-9]+)*,
32
+ * 连接符词(dsh-memu-memory_v2.today)保持整 token,单字符丢弃(≥2 才收)。
33
+ */
34
+ function tokenizeEnglishTokens(s) {
35
+ const out = []
36
+ for (const m of s.matchAll(/[a-z0-9]+(?:[._-][a-z0-9]+)*/g)) {
37
+ if (m[0].length >= 2) out.push(m[0])
38
+ }
39
+ return out
40
+ }
41
+
42
+ // —— CJK tokenization(三层 n-gram + 完整 run 上限)——
43
+
44
+ /**
45
+ * CJK 统一表意文字
46
+ * \u3400-\u9fff: CJK Unified Ideographs
47
+ * \uf900-\ufaff: CJK Compatibility Ideographs
48
+ */
49
+ const CJK_RANGE = /[\u3400-\u9fff\uf900-\ufaff]+/g
50
+
51
+ // 完整 run token 的保留上限:run 恰为 4 字时补收完整串(≤3 字时完整串已经是
52
+ // unigram/bigram/trigram 之一,≥5 字的长 run 完整串是噪声,都不另收)。
53
+ const CJK_RUN_KEEP_MAX = 4
54
+
55
+ /**
56
+ * CJK 字符序列的多层级 tokenization。
57
+ *
58
+ * - 单字 run → 只保留 unigram;
59
+ * - 长度 2~3 的 run → unigram + bigram(+trigram),完整串即其中之一;
60
+ * - 长度恰为 4 的 run → unigram + bigram + trigram + 完整 run token;
61
+ * - 长度 >4 的 run → 只输出 unigram + bigram + trigram(长句完整串不收,
62
+ * 避免噪声 token 抬高 BM25 文档长度)。
63
+ *
64
+ * 每层里同一个串只进流一次(无重复),tokenStreamV2 的 tf 不虚高。
65
+ *
66
+ * @param {string} run - CJK 字符序列
67
+ * @returns {string[]} 分层 token 列表(含重复语义由调用方决定,本函数不重复收串)
68
+ */
69
+ function tokenizeCJKRun(run) {
70
+ const out = []
71
+ if (run.length === 1) {
72
+ out.push(run)
73
+ return out
74
+ }
75
+ // Level 1: Unigram(每个字)
76
+ for (let i = 0; i < run.length; i++) out.push(run[i])
77
+ // Level 2: Bigram(相邻两个字)
78
+ for (let i = 0; i < run.length - 1; i++) out.push(run.slice(i, i + 2))
79
+ // Level 3: Trigram(相邻三个字)
80
+ if (run.length >= 3) {
81
+ for (let i = 0; i < run.length - 2; i++) out.push(run.slice(i, i + 3))
82
+ }
83
+ // Level 0: 完整 run——只在 4 字时是「额外」的一层(≤3 字已被上面覆盖)
84
+ if (run.length === CJK_RUN_KEEP_MAX) out.push(run)
85
+ return out
86
+ }
87
+
88
+ // —— 实体提取与保护——
89
+
90
+ // 数字边界:紧邻标识符连接字符的数字是标识符/日期的一部分,不作为独立数字
91
+ // 实体——'v2.today' 不拆出噪声 token '2','2026-11-05' 由完整日期实体覆盖而
92
+ // 不再拆出 '2026'/'11'/'05'。prev 看 [a-z0-9._-](标识符内部),next 看
93
+ // [a-z0-9_-](连字/日期连接;'.': 句点不拦,'85%.' 仍收 '85%')。
94
+ const IDENT_PREV_BOUNDARY = /[a-z0-9._-]/
95
+ const IDENT_NEXT_BOUNDARY = /[a-z0-9_-]/
96
+
97
+ function numberStandalone(text, index, length) {
98
+ const prev = index > 0 ? text[index - 1] : ''
99
+ const next = index + length < text.length ? text[index + length] : ''
100
+ if (IDENT_PREV_BOUNDARY.test(prev)) return false
101
+ if (IDENT_NEXT_BOUNDARY.test(next)) return false
102
+ return true
103
+ }
104
+
105
+ /**
106
+ * 提取需要保护的实体模式(口径对齐 text-retrieval.js numericSet:
107
+ * 周X/星期X 无空格、M月D日/号;在此之上保留完整 YYYY年M月D日):
108
+ * - 时间:YYYY-MM-DD、YYYY 年 M 月 D 日、M 月 D 日/号、周 X、星期 X
109
+ * - 数字/数值:整数、小数、百分比(只收独立数字——标识符/日期内部的数字不算)
110
+ * - 邮箱地址
111
+ * - URL(简化版——仅协议开头;去掉句尾标点,避免把「。」带进索引)
112
+ *
113
+ * @param {string} text - 已规范化的文本
114
+ * @returns {string[]} 提取的实体列表(按模式顺序,含重复)
115
+ */
116
+ function extractEntities(text) {
117
+ const entities = []
118
+
119
+ // 1. 日期时间
120
+ const datePatterns = [
121
+ /\d{4}-\d{1,2}-\d{1,2}/g, // YYYY-MM-DD
122
+ /\d{4}年\d{1,2}月\d{1,2}日/g, // YYYY 年 M 月 D 日
123
+ /\d{1,2}月\d{1,2}[日号]/g, // M 月 D 日/号(numericSet 同口径)
124
+ /周[一二三四五六日天]/g, // 周X(无空格——与 numericSet 对齐)
125
+ /星期[一二三四五六日天]/g, // 星期X(无空格——与 numericSet 对齐)
126
+ ]
127
+ for (const pattern of datePatterns) {
128
+ for (const match of text.matchAll(pattern)) {
129
+ entities.push(match[0])
130
+ }
131
+ }
132
+
133
+ // 2. 数字(整数、小数)——独立数字才收
134
+ const numberPattern = /\d+(?:\.\d+)?/g
135
+ for (const match of text.matchAll(numberPattern)) {
136
+ if (numberStandalone(text, match.index, match[0].length)) entities.push(match[0])
137
+ }
138
+
139
+ // 3. 百分比——同样要求独立('v2%' 不拆出 '2%')
140
+ const percentPattern = /\d+(?:\.\d+)?%/g
141
+ for (const match of text.matchAll(percentPattern)) {
142
+ if (numberStandalone(text, match.index, match[0].length)) entities.push(match[0])
143
+ }
144
+
145
+ // 4. 邮箱地址(简化版)
146
+ const emailPattern = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}/g
147
+ for (const match of text.matchAll(emailPattern)) {
148
+ entities.push(match[0])
149
+ }
150
+
151
+ // 5. URL(简化版——仅协议开头;剥掉句尾标点)
152
+ const urlPattern = /https?:\/\/[^\s]+/g
153
+ for (const match of text.matchAll(urlPattern)) {
154
+ entities.push(match[0].replace(/[)\]}.,;:!?'"]*[。,、;:!?)》」』…]+$/, ''))
155
+ }
156
+
157
+ return entities
158
+ }
159
+
160
+ // —— 主接口——
161
+
162
+ /**
163
+ * Tokenizer V2 — 主入口函数。
164
+ *
165
+ * 完整的 tokenization 流程:
166
+ * 1. 规范化文本 (NFKC + lowercase)
167
+ * 2. 提取并保护特殊实体(先占位——Set 插入序让实体 token 排在最前)
168
+ * 3. 英文部分与 V1 同口径
169
+ * 4. CJK 部分按 unigram+bigram+trigram 三层(4 字 run 另收完整串)
170
+ * 5. Set 按插入序去重(保留首次出现,不排序——同输入同输出)
171
+ *
172
+ * @param {string} text - 输入文本
173
+ * @returns {Set<string>} 去重后的 token 集合(插入序)
174
+ *
175
+ * @example
176
+ * tokenizeV2('人工智能是一种技术')
177
+ * // run '人工智能是一种技术' 长度 9 > 4:不出完整 run,只出三层 n-gram——
178
+ * // 9 个 unigram(人/工/智/…)+ 8 个 bigram(人工/工智/智能/…)
179
+ * // + 7 个 trigram(人工智/工智能/…),共 24 个 token,无重复。
180
+ *
181
+ * @example
182
+ * tokenizeV2('2026-11-05 AI 技术很火,比如 Qwen3-Embedding')
183
+ * // 输出包含:'2026-11-05'(实体,不被拆散)、'ai'、'qwen3-embedding'、
184
+ * // '技'/'技术'/'技术很' 等 CJK 三层 token。
185
+ */
186
+ export function tokenizeV2(text) {
187
+ const normalized = normalizeAndLower(text)
188
+ const out = []
189
+
190
+ // Step 1: 提取并保护实体(先占位)
191
+ out.push(...extractEntities(normalized))
192
+
193
+ // Step 2: 英文部分 tokenization(与 V1 同口径)
194
+ out.push(...tokenizeEnglishTokens(normalized))
195
+
196
+ // Step 3: CJK 部分 tokenization(三层)
197
+ for (const match of normalized.matchAll(CJK_RANGE)) {
198
+ out.push(...tokenizeCJKRun(match[0]))
199
+ }
200
+
201
+ // Step 4: 去重——Set 保留插入序(首次出现),不做任何排序
202
+ return new Set(out)
203
+ }
204
+
205
+ /**
206
+ * Tokenize V2 的流式版本(用于 BM25 的 tf 计算)。
207
+ * 不对 token 去重,保持频率信息;生成器与 tokenizeV2 完全一致,因此
208
+ * tokenStreamV2 的去重集合恒等于 tokenizeV2 的集合(⊂ 语义上的同一性)。
209
+ *
210
+ * @param {string} text - 输入文本
211
+ * @returns {string[]} 所有 token(含重复)
212
+ */
213
+ export function tokenStreamV2(text) {
214
+ const normalized = normalizeAndLower(text)
215
+ const out = []
216
+
217
+ // 提取实体(重复出现会多次记录)
218
+ out.push(...extractEntities(normalized))
219
+
220
+ // 英文部分(重复会出现多次)
221
+ out.push(...tokenizeEnglishTokens(normalized))
222
+
223
+ // CJK 部分(多层级 + 重复)
224
+ for (const match of normalized.matchAll(CJK_RANGE)) {
225
+ out.push(...tokenizeCJKRun(match[0]))
226
+ }
227
+
228
+ return out
229
+ }
230
+
231
+ // —— 向后兼容——
232
+
233
+ /**
234
+ * 提供与 V1 调用点兼容的 tokenize 接口:
235
+ * 内部调用 V2 实现并展开为数组(Set 的插入序)。
236
+ */
237
+ export function tokenize(text) {
238
+ return [...tokenizeV2(text)]
239
+ }
240
+
241
+ // —— 测试用工具函数——
242
+
243
+ /**
244
+ * Token 统计信息:total 用数组 length 计(tokenize 返回数组),
245
+ * byType 覆盖全部 token(unknown 兜底),两项之和恒相等。
246
+ */
247
+ export function tokenizeStats(text) {
248
+ const tokens = tokenize(text)
249
+ const byType = new Map()
250
+
251
+ for (const token of tokens) {
252
+ let type = 'unknown'
253
+ if (/^\d+$/.test(token)) type = 'number'
254
+ else if (/^\d{4}-\d{1,2}-\d{1,2}$/.test(token)) type = 'date_iso'
255
+ else if (/^\d+(?:\.\d+)?%$/.test(token)) type = 'percent'
256
+ else if (/^[0-9a-z._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/i.test(token)) type = 'email'
257
+ else if (/^https?:\/\//i.test(token)) type = 'url'
258
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]$/.test(token)) type = 'cjk_unigram'
259
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]{2}$/.test(token)) type = 'cjk_bigram'
260
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]{3}$/.test(token)) type = 'cjk_trigram'
261
+ else if (/^[\u3400-\u9fff\uf900-\ufaff]{4,}$/.test(token)) type = 'cjk_run'
262
+ else if (/^[a-z0-9]+$/i.test(token)) type = 'english'
263
+
264
+ byType.set(type, (byType.get(type) || 0) + 1)
265
+ }
266
+
267
+ return {
268
+ total: tokens.length,
269
+ byType: Object.fromEntries(byType),
270
+ }
271
+ }
272
+
273
+ // —— 测试场景清单(tests/tokenizer-v2.test.mjs 引用)——
274
+
275
+ /**
276
+ * Test cases for different scenarios
277
+ */
278
+ export const TEST_CASES = [
279
+ {
280
+ input: '人工智能是一种技术',
281
+ description: '纯中文短句',
282
+ },
283
+ {
284
+ input: '2026-11-05 AI 技术在快速发展',
285
+ description: '混合日期、英文缩写和中文',
286
+ },
287
+ {
288
+ input: 'Qwen3-Embedding 在 2026 年发布',
289
+ description: '混合产品名、年份和中文',
290
+ },
291
+ {
292
+ input: 'user@example.com 访问 https://example.com',
293
+ description: '邮箱和 URL',
294
+ },
295
+ ]
package/lib/tools.js CHANGED
@@ -275,15 +275,42 @@ export function registerTools(ctx, { only = null } = {}) {
275
275
  pin_reason: { type: 'string', description: 'Required for must_remember; first-person reason.' },
276
276
  pin_source: { type: 'string', description: 'user_explicit, side_event, or self.' },
277
277
  side_event_id: { type: 'string', description: 'Required when pin_source=side_event.' },
278
+ fact_key: { type: 'string', description: 'Optional stable key for the fact, such as "user:floor_color". Passing it declares that an existing active memory with the same key is another version of this fact; the new entry then becomes a conflict pair unless you pass supersedes.' },
279
+ conflicts_with: { type: 'string', description: 'Id of an existing memory that says something different about the same fact. Both versions stay active and are recalled together with a conflict card; use this instead of overwriting or deleting the old claim.' },
280
+ supersedes: { type: 'string', description: 'Id of an existing memory this new statement explicitly replaces. The old row keeps its text but is retired (superseded + valid_to). Use only when the newer statement really is the corrected truth.' },
278
281
  tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags.' },
279
- open_loop: { type: 'boolean', description: 'Mark an unfinished promise/task/unsaid thing.' },
282
+ open_loop: { type: 'boolean', description: 'Mark an unfinished promise/task/unsaid thing. Prefer the commitment object; this boolean remains for compatibility and is kept in sync with commitment.status.' },
283
+ commitment: {
284
+ type: 'object',
285
+ properties: {
286
+ counterparty: { type: 'string' },
287
+ action: { type: 'string' },
288
+ due_at: { type: 'string' },
289
+ status: { type: 'string' },
290
+ closed_by: { type: 'string' },
291
+ evidence_seq: { type: 'integer' },
292
+ },
293
+ additionalProperties: false,
294
+ description: 'A promise or arrangement: counterparty (who it is with), action (what was promised), due_at (YYYY-MM-DD or ISO), status (open/done/cancelled/expired), closed_by / evidence_seq (proof of fulfilment). Use status=open only while it is still owed; update it when it is done or cancelled.',
295
+ },
280
296
  disclosure: { type: 'string', description: 'can_tell, only_if_asked, or never_say.' },
281
297
  owner: { type: 'string', description: 'me, us, about_user, or about_project.' },
282
298
  visibility: { type: 'string', description: 'shared (default: the whole folder) or secret (kept out of the prompt and out of automatic recall; still readable by an explicit recall from the same folder). Scope a memory to one channel / character / world / branch with the context field instead of trying to hide it.' },
283
299
  source: {
284
300
  type: 'string',
285
- description: 'Where this came from: inferred (default — you concluded it), user_said (only when the words are actually theirs and quotable), imagined, or told.',
301
+ description: 'Where this came from: inferred (default — you concluded it), user_said (only when the words are actually theirs and quotable), assistant_said (your own promise, plan or claim), imagined, told, or tool (read from a tool result).',
286
302
  },
303
+ source_kind: { type: 'string', description: 'Provenance detail: user_said, assistant_said, told, imagined, inferred, or tool. Defaults to source. Assistant promises and plans belong here; never file them as user_said.' },
304
+ speaker_id: { type: 'string', description: 'Stable identity of who said it: user, assistant, character:<id>, or group:<id>. Never infer from a display name. Defaults to the conversation speaker or user/assistant by source_kind.' },
305
+ quote_span: {
306
+ type: 'object',
307
+ properties: { seq: { type: 'integer' }, turn: { type: 'integer' }, textHash: { type: 'string' } },
308
+ additionalProperties: false,
309
+ description: 'Optional pointer back to the source turn: seq/turn numbers plus a short text hash. Do not paste the whole quote here.',
310
+ },
311
+ storyline_id: { type: 'string', description: 'Optional storyline / plot thread id when several stories share one library.' },
312
+ branch_id: { type: 'string', description: 'Optional branch id; defaults to the conversation branch.' },
313
+ known_by: { type: 'array', items: { type: 'string' }, description: 'Character identities that know this fact. Omit to inherit the conversation boundary.' },
287
314
  confidence: { type: 'number', description: '0-1 confidence in this memory. Below 0.45 it is injected as a hedge, so use it honestly.' },
288
315
  mood_valence: { type: 'number', description: '派生值:给了 emotion 时由四项算出,-1(坏)到 1(好)。省略则沿用当前会话读数。' },
289
316
  arousal: { type: 'number', description: 'How strongly it hit, 0-1.' },
@@ -298,6 +325,11 @@ export function registerTools(ctx, { only = null } = {}) {
298
325
  peak: { type: 'boolean', description: 'A high point or low point of the arc — peaks and endings stay easier to recall.' },
299
326
  allow_duplicate: { type: 'boolean', description: 'Only for two genuinely independent observations of the same fact (e.g. the same event recorded twice in one day). The default false refuses a near-identical rewrite and returns the existing memory id; passing true states you looked at that existing memory and still want a separate entry.' },
300
327
  salient_date: { type: 'string', description: 'MM-DD for something that comes back every year (a birthday, an anniversary of an event); it resurfaces on that day each year. YYYY-MM-DD for a one-off dated commitment or appointment: it is raised the day before and on the day itself, and never again after it has passed. Use the annual form only when the day really does recur. A relative day (今天/明天/后天/today/tomorrow) must be resolved to the absolute date it points at: sending a bare MM-DD turns one appointment into a yearly reminder. If the content itself names a date, pass it here too: when this field is empty the plugin only falls back to a single unambiguous YYYY-MM-DD found in the text.' },
328
+ observed_at: { type: 'string', description: 'ISO date/time when this statement was made (the scene time). Omit to use the conversation sceneTime. Relative dates are resolved against this instant, never against the wall clock.' },
329
+ absolute_date: { type: 'string', description: 'YYYY-MM-DD this memory is about, when you already know it. The plugin also resolves 今天/明天/下周X/月底 itself against observed_at; pass this only to override or when the wording has no parseable date.' },
330
+ valid_from: { type: 'string', description: 'Optional YYYY-MM-DD from which the fact is true. Omit for facts with no known start.' },
331
+ valid_to: { type: 'string', description: 'Optional YYYY-MM-DD after which the fact is no longer true. Omit for open-ended facts; the entry is hidden from recall after this day.' },
332
+ date_precision: { type: 'string', description: 'day (default for a concrete date), month (月底/下个月), year (年初/年底), or unknown (relative wording that could not be resolved).' },
301
333
  track: { type: 'string', description: 'memory (default) or habit for an aggregated expression/sticker habit; do not write one habit per occurrence.' },
302
334
  attachments: { type: 'array', items: { type: 'object', properties: { sha256: { type: 'string', required: true } }, additionalProperties: true }, description: 'At most 8 sha256 references received in this conversation. Never supply paths or bytes. Ordinary image memories default to short_term if layer is omitted; choose long_term explicitly only when important.' },
303
335
  context: { type: 'object', properties: {
@@ -319,10 +351,20 @@ export function registerTools(ctx, { only = null } = {}) {
319
351
  sideEventId: args.side_event_id,
320
352
  tags: args.tags,
321
353
  openLoop: args.open_loop,
354
+ commitment: args.commitment,
355
+ factKey: args.fact_key ?? null,
356
+ conflictsWith: args.conflicts_with ?? null,
357
+ supersedes: args.supersedes ?? null,
322
358
  disclosure: args.disclosure,
323
359
  owner: args.owner,
324
360
  visibility: args.visibility,
325
361
  source: args.source,
362
+ sourceKind: args.source_kind,
363
+ speakerId: args.speaker_id ?? null,
364
+ quoteSpan: args.quote_span ?? null,
365
+ storylineId: args.storyline_id,
366
+ branchId: args.branch_id,
367
+ knownBy: args.known_by,
326
368
  confidence: args.confidence,
327
369
  moodValence: args.mood_valence ?? null,
328
370
  arousal: args.arousal ?? null,
@@ -333,6 +375,11 @@ export function registerTools(ctx, { only = null } = {}) {
333
375
  dominance: args.dominance ?? null,
334
376
  peak: args.peak === true,
335
377
  salientDate: args.salient_date ?? null,
378
+ observedAt: args.observed_at ?? null,
379
+ absoluteDate: args.absolute_date ?? null,
380
+ validFrom: args.valid_from,
381
+ validTo: args.valid_to,
382
+ datePrecision: args.date_precision,
336
383
  allowDuplicate: args.allow_duplicate === true,
337
384
  })
338
385
  // 事实级去重:几乎相同的重写被拒,返回的是
@@ -424,6 +471,19 @@ export function registerTools(ctx, { only = null } = {}) {
424
471
  status: { type: 'string', description: 'active, archived, fragment, suppressed, or expired.' },
425
472
  layer: { type: 'string', description: 'long_term to promote a short_term draft once it has proven worth keeping, or short_term to re-arm the deadline. must_remember needs a pin_reason and is only writable through memu_private_remember.' },
426
473
  open_loop: { type: 'boolean' },
474
+ commitment: {
475
+ type: 'object',
476
+ properties: {
477
+ counterparty: { type: 'string' },
478
+ action: { type: 'string' },
479
+ due_at: { type: 'string' },
480
+ status: { type: 'string' },
481
+ closed_by: { type: 'string' },
482
+ evidence_seq: { type: 'integer' },
483
+ },
484
+ additionalProperties: false,
485
+ description: 'Replace the commitment object. Set status=done/cancelled/expired to close it; open_loop follows status.',
486
+ },
427
487
  disclosure: { type: 'string', description: 'can_tell, only_if_asked, or never_say. Changing this changes how the memory is phrased when it is injected.' },
428
488
  owner: { type: 'string', description: 'me, us, about_user, or about_project.' },
429
489
  visibility: { type: 'string', description: 'shared or secret. secret keeps it out of the prompt and out of automatic recall; an explicit recall from the same folder can still read it.' },
@@ -431,7 +491,13 @@ export function registerTools(ctx, { only = null } = {}) {
431
491
  // Provenance and track are claims about what a memory *is*; both were writable
432
492
  // in memory.js and the panel while staying unreachable from the tool surface,
433
493
  // so the agent could file a quote as an inference and never correct it.
434
- source: { type: 'string', description: 'user_said, inferred, imagined, or told. Only user_said may be repeated as the user\'s own words, so correct this rather than living with a wrong provenance.' },
494
+ source: { type: 'string', description: 'user_said, assistant_said, told, imagined, inferred, or tool. Only user_said may be repeated as the user\'s own words, so correct this rather than living with a wrong provenance.' },
495
+ source_kind: { type: 'string', description: 'Same values as source; correcting the provenance must keep this in sync.' },
496
+ speaker_id: { type: 'string', description: 'Who said it: user, assistant, character:<id>, or group:<id>. Empty string clears it.' },
497
+ quote_span: { type: 'object', properties: { seq: { type: 'integer' }, turn: { type: 'integer' }, textHash: { type: 'string' } }, additionalProperties: false, description: 'Pointer back to the source turn; omit to keep, null to clear.' },
498
+ storyline_id: { type: 'string', description: 'Storyline / plot thread id; empty string clears it.' },
499
+ branch_id: { type: 'string', description: 'Branch id; empty string clears it.' },
500
+ known_by: { type: 'array', items: { type: 'string' }, description: 'Character identities that know this fact; empty array clears it.' },
435
501
  track: { type: 'string', description: 'memory or habit. habit folds repeat attachments of the same fact into one entry; a wrong track changes that aggregation and can now be corrected.' },
436
502
  peak: { type: 'boolean', description: 'Flashbulb flag: the moment was charged. Changing it recomputes accuracy.' },
437
503
  mood_valence: { type: 'number', description: 'How the moment felt, -1..1. Used as a retrieval lens; omitted keeps the stored value.' },
@@ -444,18 +510,29 @@ export function registerTools(ctx, { only = null } = {}) {
444
510
  },
445
511
  dominance: { type: 'number', description: '谁在掌控:-1 完全失控 … +1 完全掌控。省略=保留原值。' },
446
512
  salient_date: { type: 'string', description: 'Re-date the memory: MM-DD for an annual anniversary, YYYY-MM-DD for a one-off dated commitment, or an empty string to remove the date. Use this to repair a date that was stored without its year.' },
513
+ observed_at: { type: 'string', description: 'ISO scene time for this edit; relative dates in the new text resolve against it. Omit to use the conversation sceneTime.' },
514
+ absolute_date: { type: 'string', description: 'YYYY-MM-DD this memory is about. Omit to re-derive from the new title/content; pass an empty string to clear it.' },
515
+ valid_from: { type: 'string', description: 'YYYY-MM-DD the fact starts being true; empty string clears it.' },
516
+ valid_to: { type: 'string', description: 'YYYY-MM-DD the fact stops being true; empty string clears it.' },
447
517
  },
448
518
  async (args, exec) => {
449
519
  const result = await privateUpdate({
450
520
  exec, id: args.id, content: args.content, title: args.title, tags: args.tags,
451
- status: args.status, openLoop: args.open_loop, disclosure: args.disclosure, confidence: args.confidence,
521
+ status: args.status, openLoop: args.open_loop, commitment: args.commitment, disclosure: args.disclosure, confidence: args.confidence,
452
522
  layer: args.layer, owner: args.owner, visibility: args.visibility,
453
523
  source: args.source, track: args.track, peak: args.peak,
524
+ sourceKind: args.source_kind, speakerId: args.speaker_id,
525
+ quoteSpan: args.quote_span, storylineId: args.storyline_id,
526
+ branchId: args.branch_id, knownBy: args.known_by,
454
527
  moodValence: args.mood_valence, arousal: args.arousal,
455
528
  // undefined 就是"省略",必须原样传下去;换成 null 会把保留变成清除。
456
529
  emotion: args.emotion, dominance: args.dominance,
457
530
  // Sentinel: absent means "leave the date as it is", '' means "clear it".
458
531
  salientDate: args.salient_date,
532
+ observedAt: args.observed_at,
533
+ absoluteDate: args.absolute_date,
534
+ validFrom: args.valid_from,
535
+ validTo: args.valid_to,
459
536
  })
460
537
  return `已更新 ${result.id}: ${result.entry.title} (${result.entry.layer}, ${result.entry.status})`
461
538
  },
@@ -851,7 +851,8 @@ html[data-standalone] .dshm-root input[type="radio"] {
851
851
 
852
852
  /* The tuning form is a long single column in the host. On a desktop page it reads
853
853
  as a sparse list with half a card empty; two columns put the knobs side by side
854
- without splitting each row's label from its control. */
854
+ without splitting each row's label from its control. Rows share one min-height so
855
+ a 24px toggle or a bare checkbox lines up with a 32px input in the neighbour cell. */
855
856
  html[data-standalone] .dshm-settings-grid {
856
857
  display: grid;
857
858
  grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -861,15 +862,30 @@ html[data-standalone] .dshm-settings-grid {
861
862
  html[data-standalone] .dshm-settings-grid > label {
862
863
  margin: 5px 0;
863
864
  min-width: 0;
865
+ min-height: 42px;
864
866
  }
865
867
  html[data-standalone] .dshm-settings-grid input:not([type="checkbox"]):not([type="radio"]),
866
868
  html[data-standalone] .dshm-settings-grid select {
867
869
  width: 100%;
868
870
  max-width: 280px;
869
871
  }
872
+ html[data-standalone] .dshm-settings-grid input[type="checkbox"] {
873
+ width: 15px;
874
+ height: 15px;
875
+ margin: 0;
876
+ flex: 0 0 auto;
877
+ }
878
+ /* The tool allowlist input arrives without S.input; give it the same height and
879
+ radius as its neighbours so the grid reads as one control size. */
880
+ html[data-standalone] .dshm-settings-grid .dshm-inbound-tools {
881
+ height: 32px;
882
+ padding: 0 10px;
883
+ border-radius: 9px;
884
+ }
870
885
  html[data-standalone] .dshm-settings-note {
871
886
  grid-column: 1 / -1;
872
887
  margin-top: 8px !important;
888
+ white-space: pre-line;
873
889
  }
874
890
  @media (max-width: 1250px) {
875
891
  html[data-standalone] .dshm-settings-grid {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-memu-memory",
3
3
  "icon": "./assets/icon.png",
4
- "version": "1.2.6",
4
+ "version": "1.2.8",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -0,0 +1,142 @@
1
+ // 召回基准台(1.2.8 P1-3):对比 HEAD 基线与升级后 lib 的检索质量与延迟。
2
+ //
3
+ // 用法:
4
+ // node scripts/bench-recall.mjs # 测当前仓库 lib
5
+ // node scripts/bench-recall.mjs --lib <路径>/lib # 测指定 lib(如 HEAD 基线 worktree)
6
+ //
7
+ // 设计:
8
+ // - 完全确定性:语料与查询由固定种子 LCG 生成,两次运行同输入同输出,前后版本可比。
9
+ // - 指标:rankPairCandidates 延迟(N=300 精确两两 / N=2000 blocking 两档)、
10
+ // buildCandidateClusters 延迟、Recall@10 / MRR(查询 → 目标条目是否进前 10)。
11
+ // - 不引入任何依赖;被测导出(buildCorpus/rankPairCandidates/buildCandidateClusters)
12
+ // 是 curator.js/global-graph.js 的既有公共面,任何改动都不应改动其签名。
13
+
14
+ import { pathToFileURL, fileURLToPath } from 'node:url'
15
+ import { performance } from 'node:perf_hooks'
16
+
17
+ function parseLibArg(argv) {
18
+ const i = argv.indexOf('--lib')
19
+ if (i >= 0 && argv[i + 1]) return String(argv[i + 1]).replace(/[\\/]+$/, '')
20
+ return fileURLToPath(new URL('../lib', import.meta.url)).replace(/[\\/]+$/, '')
21
+ }
22
+
23
+ // —— 确定性随机(mulberry32 风格,无 clock/全局态)——
24
+ function lcg(seed) {
25
+ let s = seed >>> 0
26
+ return () => {
27
+ s = (s + 0x6D2B79F5) >>> 0
28
+ let t = s
29
+ t = Math.imul(t ^ (t >>> 15), t | 1)
30
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
31
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
32
+ }
33
+ }
34
+
35
+ // —— 合成语料:中英混合的记忆条目 ——
36
+ const CN_TOPICS = ['缓存策略', '部署流程', '数据库备份', '通知偏好', '角色设定', '会话管理', '向量检索', '日志轮转', '权限边界', '情绪记忆']
37
+ const CN_DETAIL = ['统一走内存队列', '保留 14 天后轮转', '每天凌晨三点执行', '失败时只发一次告警', '按库串行化写入', '先回应当下再回扣过去', '召回前先查旧条目', '到期前升级为长期', '跨域只 link 不吸收', '冲突进入待复核']
38
+ const EN_TOKENS = ['redis', 'postgres', 'bm25', 'embedding', 'workspace', 'session', 'curator', 'checkpoint', 'rollback', 'throttle']
39
+ const DOMAINS = ['coding', 'rp', 'general']
40
+
41
+ function makeEntry(rand, id) {
42
+ const topic = CN_TOPICS[Math.floor(rand() * CN_TOPICS.length)]
43
+ const detail = CN_DETAIL[Math.floor(rand() * CN_DETAIL.length)]
44
+ const en = EN_TOKENS[Math.floor(rand() * EN_TOKENS.length)]
45
+ const domain = DOMAINS[Math.floor(rand() * DOMAINS.length)]
46
+ return {
47
+ id: `mem-${String(id).padStart(4, '0')}`,
48
+ title: `${topic}(${en})`,
49
+ content: `${topic}${detail},${en} 相关配置在 2026-0${1 + Math.floor(rand() * 9)}-1${Math.floor(rand() * 9)} 调整过,适用域 ${domain}。`,
50
+ track: 'memory',
51
+ domain,
52
+ appliesTo: rand() < 0.4 ? [`entity-${Math.floor(rand() * 8)}`] : [],
53
+ updatedAt: `2026-11-${String(1 + Math.floor(rand() * 27)).padStart(2, '0')}T10:00:00Z`,
54
+ status: 'active',
55
+ }
56
+ }
57
+
58
+ function buildEntries(n, seed = 20261106) {
59
+ const rand = lcg(seed)
60
+ return Array.from({ length: n }, (_, i) => makeEntry(rand, i))
61
+ }
62
+
63
+ // —— 评测查询:目标条目的换序改写(测试「换个说法还能不能找回」)——
64
+ function buildQueries(entries, rand) {
65
+ return entries.map((entry) => {
66
+ const en = (entry.title.match(/[a-z0-9]+/i) || ['memory'])[0]
67
+ const topic = entry.title.split(/(/)[0]
68
+ const query = rand() < 0.5
69
+ ? `之前关于${topic}和 ${en} 的那条记忆`
70
+ : `${en} ${topic} 是怎么定的来着`
71
+ return { query, target: entry.id }
72
+ })
73
+ }
74
+
75
+ function recallAtK(results, target, k = 10) {
76
+ return results.slice(0, k).some((r) => r.id === target) ? 1 : 0
77
+ }
78
+
79
+ function mrr(results, target) {
80
+ const i = results.findIndex((r) => r.id === target)
81
+ return i < 0 ? 0 : 1 / (i + 1)
82
+ }
83
+
84
+ function bench(name, fn, runs = 5) {
85
+ // 预热一次再计时,取中位数,避免首跑 JIT/IO 噪声。
86
+ fn()
87
+ const samples = []
88
+ for (let i = 0; i < runs; i++) {
89
+ const t0 = performance.now()
90
+ fn()
91
+ samples.push(performance.now() - t0)
92
+ }
93
+ samples.sort((a, b) => a - b)
94
+ return { name, median: samples[Math.floor(runs / 2)], min: samples[0] }
95
+ }
96
+
97
+ async function main() {
98
+ const libPath = parseLibArg(process.argv)
99
+ const mod = await import(pathToFileURL(`${libPath}/text-retrieval.js`).href)
100
+ const { buildCorpus, rankPairCandidates, buildCandidateClusters } = mod
101
+ console.log(`被测 lib: ${libPath}`)
102
+ if (typeof mod.tokenize === 'function') {
103
+ const probe = JSON.stringify([...new Set(mod.tokenize('向量检索与缓存策略'))])
104
+ console.log(`tokenize 探针: ${probe.slice(0, 120)}`)
105
+ }
106
+
107
+ // —— 延迟:N=300(精确两两档)与 N=2000(blocking 档)——
108
+ for (const n of [300, 2000]) {
109
+ const entries = buildEntries(n)
110
+ const corpus = buildCorpus(entries.map((e) => ({ ...e })))
111
+ const proposal = entries[Math.floor(n / 2)]
112
+ const r1 = bench(`rankPairCandidates N=${n}`, () => rankPairCandidates({ corpus, proposal, limit: 20 }))
113
+ console.log(`${r1.name.padEnd(34)} median=${r1.median.toFixed(2)}ms min=${r1.min.toFixed(2)}ms`)
114
+ }
115
+
116
+ // —— 延迟:候选簇(§4.4)——
117
+ {
118
+ const entries = buildEntries(500)
119
+ const index = Object.fromEntries(entries.map((e) => [e.id, e]))
120
+ const r2 = bench('buildCandidateClusters N=500', () => buildCandidateClusters(index), 3)
121
+ console.log(`${r2.name.padEnd(34)} median=${r2.median.toFixed(2)}ms min=${r2.min.toFixed(2)}ms`)
122
+ }
123
+
124
+ // —— 质量:Recall@10 / MRR ——
125
+ {
126
+ const entries = buildEntries(400)
127
+ const rand = lcg(99)
128
+ const queries = buildQueries(entries, rand)
129
+ const corpus = buildCorpus(entries.map((e) => ({ ...e })))
130
+ let hit10 = 0
131
+ let rrSum = 0
132
+ for (const { query, target } of queries) {
133
+ const results = rankPairCandidates({ corpus, proposal: { title: query, content: '', track: 'memory', domain: 'general' }, limit: 20 })
134
+ hit10 += recallAtK(results, target)
135
+ rrSum += mrr(results, target)
136
+ }
137
+ const n = queries.length
138
+ console.log(`Recall@10 = ${(hit10 / n).toFixed(4)} MRR = ${(rrSum / n).toFixed(4)} (queries=${n})`)
139
+ }
140
+ }
141
+
142
+ main().catch((error) => { console.error(error); process.exitCode = 1 })