dsh-memu-memory 1.2.9 → 1.3.1

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 (42) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +1 -1
  3. package/README.zh.md +1 -1
  4. package/docs/memory-semantics.md +4 -3
  5. package/lib/binding-diagnostics.js +3 -3
  6. package/lib/client.js +23 -1
  7. package/lib/consolidation-ledger.js +41 -1
  8. package/lib/consolidation-receipt.js +122 -21
  9. package/lib/consolidation-worker.js +81 -25
  10. package/lib/curator.js +91 -11
  11. package/lib/engine.js +13 -3
  12. package/lib/graph.js +57 -21
  13. package/lib/inject.js +35 -15
  14. package/lib/media.js +8 -1
  15. package/lib/memory.js +16 -1
  16. package/lib/memu.js +19 -6
  17. package/lib/private.js +374 -22
  18. package/lib/prompts/global-curator.md +6 -3
  19. package/lib/prompts/private-consolidation.md +2 -2
  20. package/lib/prompts/private-consolidation.rp.md +3 -2
  21. package/lib/prompts/system-guide.md +4 -5
  22. package/lib/prompts.js +27 -1
  23. package/lib/rpc.js +2 -2
  24. package/lib/state.js +17 -3
  25. package/lib/tools.js +257 -127
  26. package/package.json +1 -1
  27. package/tests/consolidation-credential.test.mjs +2 -2
  28. package/tests/consolidation-fork.test.mjs +92 -15
  29. package/tests/consolidation-ledger.test.mjs +95 -3
  30. package/tests/consolidation-snapshot.test.mjs +30 -13
  31. package/tests/curator-probe.test.mjs +32 -2
  32. package/tests/graph.test.mjs +21 -0
  33. package/tests/inject-conflict.test.mjs +1 -1
  34. package/tests/inject.test.mjs +1 -1
  35. package/tests/injection-chain.test.mjs +4 -4
  36. package/tests/injection-rollback.test.mjs +1 -1
  37. package/tests/memory-chain.test.mjs +28 -0
  38. package/tests/mock-llm.test.mjs +1 -1
  39. package/tests/prompt-semantics.test.mjs +1 -1
  40. package/tests/prompts.test.mjs +1 -1
  41. package/tests/tool-schema.test.mjs +2 -1
  42. package/tests/tools.test.mjs +25 -3
package/lib/tools.js CHANGED
@@ -120,11 +120,19 @@ function emotionBrief(entry) {
120
120
 
121
121
  function formatPrivateItem(item, index, options = {}) {
122
122
  const entry = item.entry || {}
123
- const lines = [
124
- `${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`,
125
- ` layer=${entry.layer || 'long_term'} status=${entry.status || 'active'}${entry.marginalized ? ' marginalized' : ''}${entry.openLoop ? ' open_loop' : ''}`,
126
- ` source=${entry.source || 'inferred'}`,
127
- ]
123
+ const layer = entry.layer || 'long_term'
124
+ const status = entry.status || 'active'
125
+ const source = entry.source || 'inferred'
126
+ // B7:默认值不逐条重写(guide 已说明缺省口径),非默认 layer/status/source 仍必须输出。
127
+ const flags = [
128
+ layer !== 'long_term' ? `layer=${layer}` : '',
129
+ status !== 'active' ? `status=${status}` : '',
130
+ entry.marginalized ? 'marginalized' : '',
131
+ entry.openLoop ? 'open_loop' : '',
132
+ ].filter(Boolean).join(' ')
133
+ const lines = [`${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`]
134
+ if (flags) lines.push(` ${flags}`)
135
+ if (source !== 'inferred') lines.push(` source=${source}`)
128
136
  // Same relative phrasing as the injected block: one memory must not read as
129
137
  // "2026-10-20" in a tool result and "8 天前" in the prompt.
130
138
  const when = relativeTime(entry.updatedAt || entry.createdAt)
@@ -168,10 +176,14 @@ function formatPrivateItem(item, index, options = {}) {
168
176
 
169
177
  function formatGlobalItem(item, index, options = {}) {
170
178
  const entry = item.entry || {}
171
- const lines = [
172
- `${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`,
173
- ` domain=${entry.domain || 'unknown'} confidence=${entry.confidence ?? '?'}`,
174
- ]
179
+ const domain = entry.domain || 'unknown'
180
+ // B7:unknown 域是默认值,省略后模型仍能按 guide 的缺省口径理解;confidence 保留。
181
+ const head = [
182
+ domain !== 'unknown' ? `domain=${domain}` : '',
183
+ entry.confidence !== undefined ? `confidence=${entry.confidence}` : '',
184
+ ].filter(Boolean).join(' ')
185
+ const lines = [`${index}. [${item.name}] ${entry.title || item.description || '(untitled)'}`]
186
+ if (head) lines.push(` ${head}`)
175
187
  const when = relativeTime(entry.updatedAt || entry.createdAt)
176
188
  if (when) lines.push(` updated=${when}`)
177
189
  if (Array.isArray(entry.appliesTo) && entry.appliesTo.length > 0) lines.push(` applies_to=${entry.appliesTo.join(',')}`)
@@ -181,9 +193,80 @@ function formatGlobalItem(item, index, options = {}) {
181
193
  : truncate(item.content, 1200)
182
194
  lines.push(' ' + body.replace(/\n/g, '\n '))
183
195
  }
184
- return lines.join('\n')
196
+ return redactSecrets(lines.join('\n'))
197
+ }
198
+
199
+ /**
200
+ * 1.3.1:单条 remember 与批量 remember_batch 共用同一套参数映射,避免两处字段漂移。
201
+ * 批量工具把重复率最高的公共字段放在 defaults 里,每条 item 只补差异字段。
202
+ */
203
+ async function rememberFromArgs(exec, args = {}) {
204
+ return privateRemember({
205
+ exec,
206
+ content: args.content,
207
+ title: args.title,
208
+ layer: args.layer,
209
+ track: args.track,
210
+ attachments: args.attachments,
211
+ context: args.context,
212
+ pinReason: args.pin_reason,
213
+ pinSource: args.pin_source,
214
+ sideEventId: args.side_event_id,
215
+ tags: args.tags,
216
+ openLoop: args.open_loop,
217
+ commitment: args.commitment,
218
+ factKey: args.fact_key ?? null,
219
+ conflictsWith: args.conflicts_with ?? null,
220
+ supersedes: args.supersedes ?? null,
221
+ disclosure: args.disclosure,
222
+ owner: args.owner,
223
+ visibility: args.visibility,
224
+ source: args.source,
225
+ sourceKind: args.source_kind,
226
+ speakerId: args.speaker_id ?? null,
227
+ quoteSpan: args.quote_span ?? null,
228
+ storylineId: args.storyline_id,
229
+ branchId: args.branch_id,
230
+ knownBy: args.known_by,
231
+ confidence: args.confidence,
232
+ moodValence: args.mood_valence ?? null,
233
+ arousal: args.arousal ?? null,
234
+ emotion: args.emotion,
235
+ dominance: args.dominance ?? null,
236
+ peak: args.peak === true,
237
+ salientDate: args.salient_date ?? null,
238
+ observedAt: args.observed_at ?? null,
239
+ absoluteDate: args.absolute_date ?? null,
240
+ validFrom: args.valid_from,
241
+ validTo: args.valid_to,
242
+ datePrecision: args.date_precision,
243
+ allowDuplicate: args.allow_duplicate === true,
244
+ })
245
+ }
246
+
247
+ /** 把 privateRemember 的结果压成 worker 能直接读的一行/一段;去重与冲突必须显式说。 */
248
+ function describeRememberResult(result, label = '') {
249
+ const prefix = label ? label + ': ' : ''
250
+ if (result?.deduped === true) {
251
+ return `${prefix}未写入:库内已有几乎相同的记忆 [${result.existingId}](相似度 ${(Number(result.similarity) || 0).toFixed(2)});要补充请用 memu_private_update id=${result.existingId}。`
252
+ }
253
+ const entry = result?.entry
254
+ if (result?.conflict) {
255
+ return `${prefix}已记录但与 [${result.conflict}] 冲突,进入待复核(id=${entry?.id});复核前不会出现在召回或注入里。`
256
+ }
257
+ return `${prefix}已写入私有记忆:${result?.id} · layer=${entry?.layer || 'long_term'} · title=${entry?.title || ''}`
258
+ }
259
+
260
+ async function rememberOneOutcome(exec, args) {
261
+ try {
262
+ const result = await rememberFromArgs(exec, args)
263
+ return { ok: true, result, text: describeRememberResult(result) }
264
+ } catch (error) {
265
+ return { ok: false, text: '未写入:' + errorText(error).replace(/\n/g, ' ') }
266
+ }
185
267
  }
186
268
 
269
+
187
270
  export function registerTools(ctx, { only = null } = {}) {
188
271
  const tools = []
189
272
  // 全量注册(宿主装载)才更新全局 registrationReport:整理 worker 的按需挂载
@@ -211,7 +294,10 @@ export function registerTools(ctx, { only = null } = {}) {
211
294
  (args, exec) => {
212
295
  if (args.relationship) {
213
296
  const relation = args.relationship
214
- return JSON.stringify(updateRelationship({ exec, fromId: relation.fromEntity, toId: relation.toEntity, state: relation.state, evidenceIds: relation.evidenceIds, reason: args.note }))
297
+ const updated = updateRelationship({ exec, fromId: relation.fromEntity, toId: relation.toEntity, state: relation.state, evidenceIds: relation.evidenceIds, reason: args.note })
298
+ const r = updated?.relationship || updated || {}
299
+ // 完整 history(≤50 版)不进模型上下文:只回一行,需要细节时再查。
300
+ return `已更新关系 ${r.fromId ?? relation.fromEntity}→${r.toId ?? relation.toEntity} · revision ${r.revision ?? '?'} · evidence ${Array.isArray(r.evidenceIds) ? r.evidenceIds.length : 0}`
215
301
  }
216
302
  let toId = args.to
217
303
  if (args.entity) {
@@ -267,19 +353,19 @@ export function registerTools(ctx, { only = null } = {}) {
267
353
 
268
354
  tools.push(toolBase(
269
355
  'memu_private_remember',
270
- 'Write one useful private memory in the bound library. Match the domain: engineering facts, logic and verification in coding; grounded in-character experiences in RP; neutral facts and preferences in general. Do not copy a transcript or invent evidence. layer=must_remember requires pin_reason and pin_source (user_explicit, side_event, self).',
356
+ 'Write one durable private memory. Match the domain; never copy a transcript or invent evidence. layer=must_remember requires pin_reason and pin_source.',
271
357
  {
272
- content: { type: 'string', required: true, description: 'Self-contained content appropriate to the domain. Coding: conclusion, scope/symbol, logic/conditions and verification; preserve necessary minimal code exactly. RP: an evidenced moment and its effect on later interaction, without invented facts.' },
273
- title: { type: 'string', description: '8-40 characters. This title is a permanent index: the anchor and turn recall show it WITHOUT the body, so it must name the concrete fact — people/objects/events or the conclusion keywords ("Yuike 名字来自小时候的白猫", "Postgres 连接池上限改为 40"). Never an empty label like "一些事" / "那段对话" / "关于XX的事"; the details belong in content. Defaults to the content when omitted.' },
274
- layer: { type: 'string', description: 'long_term (default), short_term, or must_remember. short_term is a draft with a deadline: it expires after shortTermTtlHours unless promoted to long_term before then. Use it for what only has to survive this stretch of conversation.' },
358
+ content: { type: 'string', required: true, description: 'Self-contained 50-170 char body: people, place, time, event, exact words. Coding keeps conclusion and verification; RP keeps evidenced moments, no invented facts.' },
359
+ title: { type: 'string', description: '8-40 chars naming the concrete fact; title is a permanent index, the anchor shows only titles WITHOUT the body. No empty labels. Defaults to content.' },
360
+ layer: { type: 'string', description: 'long_term (default), short_term, must_remember. short_term expires unless promoted.' },
275
361
  pin_reason: { type: 'string', description: 'Required for must_remember; first-person reason.' },
276
362
  pin_source: { type: 'string', description: 'user_explicit, side_event, or self.' },
277
363
  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.' },
364
+ fact_key: { type: 'string', description: 'Optional stable key. Reusing it marks another version of the same fact (conflict pair unless supersedes).' },
365
+ conflicts_with: { type: 'string', description: 'Existing memory id with a different version of the same fact; both stay active and recall together.' },
366
+ supersedes: { type: 'string', description: 'Existing memory id this explicitly replaces; old text stays but is retired.' },
281
367
  tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags.' },
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.' },
368
+ open_loop: { type: 'boolean', description: 'Unfinished promise/task; prefer commitment.' },
283
369
  commitment: {
284
370
  type: 'object',
285
371
  properties: {
@@ -291,97 +377,55 @@ export function registerTools(ctx, { only = null } = {}) {
291
377
  evidence_seq: { type: 'integer' },
292
378
  },
293
379
  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.',
380
+ description: 'Promise: counterparty, action, due_at (YYYY-MM-DD/ISO), status (open/done/cancelled/expired), closed_by/evidence_seq.',
295
381
  },
296
- disclosure: { type: 'string', description: 'can_tell, only_if_asked, or never_say.' },
297
- owner: { type: 'string', description: 'me, us, about_user, or about_project.' },
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.' },
382
+ disclosure: { type: 'string', description: 'can_tell, only_if_asked, never_say.' },
383
+ owner: { type: 'string', description: 'me, us, about_user, about_project.' },
384
+ visibility: { type: 'string', description: 'shared (default) or secret (no automatic injection/recall).' },
299
385
  source: {
300
386
  type: 'string',
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).',
387
+ description: 'inferred (default), user_said (quotable), assistant_said, imagined, told, tool.',
302
388
  },
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.' },
389
+ source_kind: { type: 'string', description: 'Same values as source; assistant promises/plans must not be user_said.' },
390
+ speaker_id: { type: 'string', description: 'user, assistant, character:<id>, group:<id>; never infer from a name.' },
305
391
  quote_span: {
306
392
  type: 'object',
307
393
  properties: { seq: { type: 'integer' }, turn: { type: 'integer' }, textHash: { type: 'string' } },
308
394
  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.',
395
+ description: 'Optional source pointer; do not paste the whole quote.',
310
396
  },
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.' },
314
- confidence: { type: 'number', description: '0-1 confidence in this memory. Below 0.45 it is injected as a hedge, so use it honestly.' },
315
- mood_valence: { type: 'number', description: '派生值:给了 emotion 时由四项算出,-1(坏)到 1(好)。省略则沿用当前会话读数。' },
316
- arousal: { type: 'number', description: 'How strongly it hit, 0-1.' },
397
+ storyline_id: { type: 'string', description: 'Optional storyline id.' },
398
+ branch_id: { type: 'string', description: 'Optional branch id.' },
399
+ known_by: { type: 'array', items: { type: 'string' }, description: 'Character ids that know this fact.' },
400
+ confidence: { type: 'number', description: '0-1; below 0.45 is injected as a hedge.' },
401
+ mood_valence: { type: 'number', description: '-1..1; omit to inherit the conversation reading.' },
402
+ arousal: { type: 'number', description: '0-1 intensity.' },
317
403
  emotion: {
318
404
  type: 'object',
319
405
  properties: { joy: { type: 'number' }, anger: { type: 'number' }, sorrow: { type: 'number' }, fear: { type: 'number' } },
320
406
  // 四个轴是封闭集合:多写的键只会被误当成第五种情绪。
321
407
  additionalProperties: false,
322
- description: '情绪构成:喜悦/愤怒/哀伤/恐惧,四项自动归一化到和为 1。填记忆所述那件事的情绪,不是此刻整理时的心情。省略=继承当前会话读数;显式全零=明确中性;工程事实请用中性,不要因为 bug 难修或结论重要就填负面情绪。',
408
+ description: 'joy/anger/sorrow/fear for the remembered event, not the consolidation mood. Omit to inherit; all-zero is neutral.',
323
409
  },
324
- dominance: { type: 'number', description: '谁在掌控:-1 完全失控 … +1 完全掌控。省略=继承当前会话。' },
325
- peak: { type: 'boolean', description: 'A high point or low point of the arc — peaks and endings stay easier to recall.' },
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.' },
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).' },
333
- track: { type: 'string', description: 'memory (default) or habit for an aggregated expression/sticker habit; do not write one habit per occurrence.' },
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.' },
410
+ dominance: { type: 'number', description: '-1..1; omit to inherit.' },
411
+ peak: { type: 'boolean', description: 'High/low point of the arc.' },
412
+ allow_duplicate: { type: 'boolean', description: 'Only for a genuinely independent second observation; default false refuses near-duplicates.' },
413
+ salient_date: { type: 'string', description: 'MM-DD for yearly recurrence; YYYY-MM-DD for a one-off appointment. Resolve 今天/明天/下周 to the absolute date; never send a bare MM-DD for a one-off.' },
414
+ observed_at: { type: 'string', description: 'ISO scene time of this statement; relative dates resolve against it, never the wall clock. Omit to use the conversation sceneTime.' },
415
+ absolute_date: { type: 'string', description: 'YYYY-MM-DD this fact is about; omit to let the plugin resolve observed_at + relative wording.' },
416
+ valid_from: { type: 'string', description: 'Optional YYYY-MM-DD when the fact starts.' },
417
+ valid_to: { type: 'string', description: 'Optional YYYY-MM-DD after which it no longer holds.' },
418
+ date_precision: { type: 'string', description: 'day, month, year, or unknown.' },
419
+ track: { type: 'string', description: 'memory (default) or habit (aggregated repeated expression).' },
420
+ attachments: { type: 'array', items: { type: 'object', properties: { sha256: { type: 'string', required: true } }, additionalProperties: true }, description: 'At most 8 sha256 refs received in this conversation; never paths or bytes.' },
335
421
  context: { type: 'object', properties: {
336
422
  speakerId: { type: 'string' }, channelId: { type: 'string' }, characterId: { type: 'string' }, worldId: { type: 'string' }, branchId: { type: 'string' },
337
423
  knownBy: { type: 'array', items: { type: 'string' } }, occurredAt: { type: 'string' },
338
- }, additionalProperties: true, description: 'Stable identities only; do not infer from a display name. Channel, character, world and branch inherit the configured conversation scope; cannot cross it. speakerId records whose words these were, knownBy limits character knowledge, occurredAt must be explicit.' },
424
+ }, additionalProperties: true, description: 'Stable identities only; scope inherits the conversation and cannot widen it.' },
339
425
  },
340
426
  async (args, exec) => {
341
- const result = await privateRemember({
342
- exec,
343
- content: args.content,
344
- title: args.title,
345
- layer: args.layer,
346
- track: args.track,
347
- attachments: args.attachments,
348
- context: args.context,
349
- pinReason: args.pin_reason,
350
- pinSource: args.pin_source,
351
- sideEventId: args.side_event_id,
352
- tags: args.tags,
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,
358
- disclosure: args.disclosure,
359
- owner: args.owner,
360
- visibility: args.visibility,
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,
368
- confidence: args.confidence,
369
- moodValence: args.mood_valence ?? null,
370
- arousal: args.arousal ?? null,
371
- // `undefined` means "the model said nothing" and is allowed to inherit the
372
- // turn's mood; `null` means "explicitly neutral" and must survive as such. Using
373
- // `?? null` here would erase that difference and re-inherit on a neutral call.
374
- emotion: args.emotion,
375
- dominance: args.dominance ?? null,
376
- peak: args.peak === true,
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,
383
- allowDuplicate: args.allow_duplicate === true,
384
- })
427
+ // D4:与 remember_batch 共用同一套参数映射,避免两处字段漂移。
428
+ const result = await rememberFromArgs(exec, args)
385
429
  // 事实级去重:几乎相同的重写被拒,返回的是
386
430
  // { deduped, existingId, hint },没有 entry——必须先接住,否则 result.entry.layer 抛错。
387
431
  if (result.deduped === true) {
@@ -411,6 +455,85 @@ export function registerTools(ctx, { only = null } = {}) {
411
455
  { timeoutMs: 180_000 },
412
456
  ))
413
457
 
458
+ tools.push(toolBase(
459
+ 'memu_private_remember_batch',
460
+ 'Write several private memories in one call. Put shared fields in defaults and only per-item differences in items; each item is one fact. Use this instead of calling memu_private_remember once per entry. Items that dedupe or conflict are reported per line.',
461
+ {
462
+ defaults: {
463
+ type: 'object',
464
+ properties: {
465
+ speaker_id: { type: 'string' },
466
+ source_kind: { type: 'string' },
467
+ source: { type: 'string' },
468
+ owner: { type: 'string' },
469
+ confidence: { type: 'number' },
470
+ observed_at: { type: 'string' },
471
+ absolute_date: { type: 'string' },
472
+ date_precision: { type: 'string' },
473
+ tags: { type: 'array', items: { type: 'string' } },
474
+ layer: { type: 'string' },
475
+ },
476
+ additionalProperties: true,
477
+ description: 'Shared fields for every item; per-item values override these.',
478
+ },
479
+ items: {
480
+ type: 'array',
481
+ description: '1-8 facts. Each item needs title + content; only include fields that differ from defaults.',
482
+ items: {
483
+ type: 'object',
484
+ properties: {
485
+ title: { type: 'string', required: true },
486
+ content: { type: 'string', required: true },
487
+ observed_at: { type: 'string' },
488
+ absolute_date: { type: 'string' },
489
+ date_precision: { type: 'string' },
490
+ speaker_id: { type: 'string' },
491
+ source_kind: { type: 'string' },
492
+ source: { type: 'string' },
493
+ owner: { type: 'string' },
494
+ confidence: { type: 'number' },
495
+ tags: { type: 'array', items: { type: 'string' } },
496
+ emotion: {
497
+ type: 'object',
498
+ properties: { joy: { type: 'number' }, anger: { type: 'number' }, sorrow: { type: 'number' }, fear: { type: 'number' } },
499
+ additionalProperties: false,
500
+ },
501
+ commitment: { type: 'object', additionalProperties: true },
502
+ conflicts_with: { type: 'string' },
503
+ salient_date: { type: 'string' },
504
+ open_loop: { type: 'boolean' },
505
+ layer: { type: 'string' },
506
+ },
507
+ additionalProperties: true,
508
+ },
509
+ },
510
+ },
511
+ async (args, exec) => {
512
+ const defaults = args?.defaults && typeof args.defaults === 'object' ? args.defaults : {}
513
+ const items = Array.isArray(args?.items) ? args.items.slice(0, 8) : []
514
+ if (items.length === 0) return '未写入:items 为空;每条至少需要 title 和 content。'
515
+ const lines = []
516
+ let written = 0
517
+ let deduped = 0
518
+ let held = 0
519
+ for (let index = 0; index < items.length; index += 1) {
520
+ const item = items[index]
521
+ if (!item || typeof item !== 'object') {
522
+ lines.push(`${index + 1}. 未写入:item 不是对象`)
523
+ continue
524
+ }
525
+ const outcome = await rememberOneOutcome(exec, { ...defaults, ...item })
526
+ lines.push(`${index + 1}. ${outcome.text}`)
527
+ if (!outcome.ok) continue
528
+ if (outcome.result?.deduped === true) deduped += 1
529
+ else if (outcome.result?.entry?.status === 'pending_review' || outcome.result?.conflict) held += 1
530
+ else written += 1
531
+ }
532
+ return [`批量写入完成:新增 ${written} · 去重 ${deduped} · 待复核 ${held}`, ...lines].join('\n')
533
+ },
534
+ { timeoutMs: 300_000 },
535
+ ))
536
+
414
537
  tools.push(toolBase(
415
538
  'memu_private_recall',
416
539
  '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.',
@@ -435,18 +558,25 @@ export function registerTools(ctx, { only = null } = {}) {
435
558
 
436
559
  tools.push(toolBase(
437
560
  'memu_private_list',
438
- 'List private memory metadata for the library bound to this conversation. When cross-library recall is on, same-domain libraries are included too. Does not return full bodies.',
439
- {},
440
- async (_args, exec) => {
561
+ 'List private memory metadata for the library bound to this conversation. When cross-library recall is on, same-domain libraries are included too. Does not return full bodies. Paged: default 50 rows, use offset to continue.',
562
+ {
563
+ limit: { type: 'number', description: 'Rows in this page; default 50, max 200.' },
564
+ offset: { type: 'number', description: '0-based row offset; for the next page pass the last returned offset + count.' },
565
+ },
566
+ async (args, exec) => {
441
567
  // A list is a pure read: if the conversation has no binding yet, say so
442
568
  // instead of ensureSession() silently creating a placeholder library.
443
569
  if (!peekBinding(exec)?.libraryId) return '当前对话没有绑定记忆库。'
444
- const result = await privateList({ exec })
570
+ const limit = Math.min(200, Math.max(1, Math.floor(Number(args?.limit) || 50)))
571
+ const offset = Math.max(0, Math.floor(Number(args?.offset) || 0))
572
+ const result = await privateList({ exec, limit, offset })
445
573
  const warning = result.warning ? `\n注意:${result.warning}` : ''
446
574
  const foreign = (result.libraries || []).filter((library) => library.id !== result.libraryId)
447
575
  const scopeNote = foreign.length ? `,跨库=${foreign.map((library) => library.name || library.id).join(',')}` : ''
448
- if (!result.files?.length) return `私有记忆库 ${result.libraryId} 为空${scopeNote}。${warning}`
449
- const lines = [`私有记忆库 ${result.libraryId}(${result.files.length} 条${scopeNote})`]
576
+ const total = Number.isFinite(result.total) ? result.total : (result.files?.length || 0)
577
+ if (!total) return `私有记忆库 ${result.libraryId} 为空${scopeNote}。${warning}`
578
+ const pageEnd = offset + (result.files?.length || 0)
579
+ const lines = [`私有记忆库 ${result.libraryId}(共 ${total} 条,本页 ${offset + 1}-${pageEnd}${scopeNote})`]
450
580
  for (const file of result.files) {
451
581
  const e = file.entry || {}
452
582
  const tag = salientTag(e)
@@ -455,21 +585,22 @@ export function registerTools(ctx, { only = null } = {}) {
455
585
  : ''
456
586
  lines.push(`- [${file.name}] ${e.title || file.description || '(untitled)'} · ${e.layer || 'long_term'} · ${e.status || 'active'}${e.marginalized ? ' · marginalized' : ''}${tag ? ` · ${tag}` : ''}${owner}`)
457
587
  }
458
- return lines.join('\n') + warning
588
+ const more = pageEnd < total ? `\n还有 ${total - pageEnd} 条:用 offset=${pageEnd} 继续。` : ''
589
+ return redactSecrets(lines.join('\n')) + more + warning
459
590
  },
460
591
  { isConcurrencySafe: () => true },
461
592
  ))
462
593
 
463
594
  tools.push(toolBase(
464
595
  'memu_private_update',
465
- 'Update a private memory in the bound library. Changing content rewrites the memory in MemU; metadata-only changes stay local. If the new content covers more than the old title says, rewrite the title under the same rule.',
596
+ 'Update a private memory. Content changes rewrite the stored body; metadata-only changes stay local. Rewrite the title when the new body no longer fits it.',
466
597
  {
467
598
  id: { type: 'string', required: true, description: 'Memory id.' },
468
- content: { type: 'string', description: 'New body.' },
469
- title: { type: 'string', description: 'New title under the same rule as memu_private_remember.title: 8-40 characters that name the concrete fact (people/objects/events or conclusion keywords), because the anchor shows only titles. Never an empty label like "关于XX的事"; details stay in content. Omit to keep the current title.' },
599
+ content: { type: 'string', description: 'New 50-170 char body.' },
600
+ title: { type: 'string', description: '8-40 chars naming the concrete fact; title is a permanent index, the anchor shows only titles WITHOUT the body. No empty labels. Omit to keep.' },
470
601
  tags: { type: 'array', items: { type: 'string' } },
471
- status: { type: 'string', description: 'active, archived, fragment, suppressed, or expired.' },
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.' },
602
+ status: { type: 'string', description: 'active, archived, fragment, suppressed, expired.' },
603
+ layer: { type: 'string', description: 'long_term (promote), short_term (re-arm expiry); must_remember only via remember.' },
473
604
  open_loop: { type: 'boolean' },
474
605
  commitment: {
475
606
  type: 'object',
@@ -482,38 +613,38 @@ export function registerTools(ctx, { only = null } = {}) {
482
613
  evidence_seq: { type: 'integer' },
483
614
  },
484
615
  additionalProperties: false,
485
- description: 'Replace the commitment object. Set status=done/cancelled/expired to close it; open_loop follows status.',
616
+ description: 'Replace commitment; status=done/cancelled/expired closes it.',
486
617
  },
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.' },
488
- owner: { type: 'string', description: 'me, us, about_user, or about_project.' },
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.' },
618
+ disclosure: { type: 'string', description: 'can_tell, only_if_asked, never_say.' },
619
+ owner: { type: 'string', description: 'me, us, about_user, about_project.' },
620
+ visibility: { type: 'string', description: 'shared or secret.' },
490
621
  confidence: { type: 'number' },
491
622
  // Provenance and track are claims about what a memory *is*; both were writable
492
623
  // in memory.js and the panel while staying unreachable from the tool surface,
493
624
  // so the agent could file a quote as an inference and never correct it.
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.' },
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.' },
502
- peak: { type: 'boolean', description: 'Flashbulb flag: the moment was charged. Changing it recomputes accuracy.' },
503
- mood_valence: { type: 'number', description: 'How the moment felt, -1..1. Used as a retrieval lens; omitted keeps the stored value.' },
504
- arousal: { type: 'number', description: 'How charged the moment was, 0..1. Used as a retrieval lens; omitted keeps the stored value.' },
625
+ source: { type: 'string', description: 'user_said, assistant_said, told, imagined, inferred, tool.' },
626
+ source_kind: { type: 'string', description: 'Same values as source; keep in sync.' },
627
+ speaker_id: { type: 'string', description: 'user, assistant, character:<id>, group:<id>; empty clears.' },
628
+ quote_span: { type: 'object', properties: { seq: { type: 'integer' }, turn: { type: 'integer' }, textHash: { type: 'string' } }, additionalProperties: false, description: 'Source pointer; omit to keep, null to clear.' },
629
+ storyline_id: { type: 'string', description: 'Storyline id; empty clears.' },
630
+ branch_id: { type: 'string', description: 'Branch id; empty clears.' },
631
+ known_by: { type: 'array', items: { type: 'string' }, description: 'Character ids; empty clears.' },
632
+ track: { type: 'string', description: 'memory or habit.' },
633
+ peak: { type: 'boolean', description: 'Flashbulb flag.' },
634
+ mood_valence: { type: 'number', description: '-1..1 retrieval lens; omit keeps.' },
635
+ arousal: { type: 'number', description: '0..1 retrieval lens; omit keeps.' },
505
636
  emotion: {
506
637
  type: 'object',
507
638
  properties: { joy: { type: 'number' }, anger: { type: 'number' }, sorrow: { type: 'number' }, fear: { type: 'number' } },
508
639
  additionalProperties: false,
509
- description: '情绪构成,三项语义不同:省略=保留原值;显式 null=清除 emotion,来源变 unknown;显式对象=校验并归一化后整份替换。改的是那条记忆所述事件的感受,不是此刻的心情。',
640
+ description: 'Omit keeps; null clears; object replaces after normalisation. Event feeling, not current mood.',
510
641
  },
511
- dominance: { type: 'number', description: '谁在掌控:-1 完全失控 … +1 完全掌控。省略=保留原值。' },
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.' },
642
+ dominance: { type: 'number', description: '-1..1; omit keeps.' },
643
+ salient_date: { type: 'string', description: 'MM-DD yearly or YYYY-MM-DD one-off; empty clears.' },
644
+ observed_at: { type: 'string', description: 'ISO scene time for this edit; omit uses conversation sceneTime.' },
645
+ absolute_date: { type: 'string', description: 'YYYY-MM-DD; omit re-derives, empty clears.' },
646
+ valid_from: { type: 'string', description: 'YYYY-MM-DD start; empty clears.' },
647
+ valid_to: { type: 'string', description: 'YYYY-MM-DD end; empty clears.' },
517
648
  },
518
649
  async (args, exec) => {
519
650
  const result = await privateUpdate({
@@ -599,7 +730,7 @@ export function registerTools(ctx, { only = null } = {}) {
599
730
  evidence ? ` evidence=${truncate(evidence, 200)}` : '',
600
731
  ].filter(Boolean).join('\n'))
601
732
  }
602
- return lines.join('\n') + warning
733
+ return redactSecrets(lines.join('\n')) + warning
603
734
  },
604
735
  { isConcurrencySafe: () => true },
605
736
  ))
@@ -719,7 +850,6 @@ export function registerTools(ctx, { only = null } = {}) {
719
850
  const pinned = Object.values(privateIndex.entries || {}).filter((e) => e.layer === 'must_remember' && e.status !== 'archived').length
720
851
  const activeEntries = Object.values(privateIndex.entries || {}).filter((e) => !['archived', 'suppressed', 'expired'].includes(e.status))
721
852
  const shortCount = activeEntries.filter((e) => e.layer === 'short_term').length
722
- const privateCount = Object.keys(privateIndex.entries || {}).filter((id) => privateIndex.entries[id].status !== 'archived').length
723
853
  const globalCount = Object.keys(globalIndex.entries || {}).filter((id) => ['active'].includes(globalIndex.entries[id].status || 'active')).length
724
854
  const health = storageHealth()
725
855
  const storageLines = []
@@ -753,7 +883,7 @@ export function registerTools(ctx, { only = null } = {}) {
753
883
  `library: ${library ? `${library.name} (${library.id})` : 'none'}`,
754
884
  `domain: ${domainOf(binding)}`,
755
885
  `useLibrary=${binding?.useLibrary !== false} useGlobal=${binding?.useGlobal !== false} autoInject=${settings.autoInject}`,
756
- `private: ${privateCount} active, ${pinned}/${settings.mustRememberCap} pinned`,
886
+ `private: ${activeEntries.length} active, ${pinned}/${settings.mustRememberCap} pinned`,
757
887
  `short_term: ${shortCount} active (ttl ${Number(settings.shortTermTtlHours) || 0}h)`,
758
888
  `global: ${globalCount} active`,
759
889
  `libraries: ${libraries.length}`,
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.9",
4
+ "version": "1.3.1",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -136,14 +136,14 @@ test('a verified receipt becomes the completion credential and advances the chec
136
136
  assert.equal(ctx.rec.disposed.length, 1)
137
137
  })
138
138
 
139
- test('a worker that reports but gives no receipt is a failure, not a success', async () => {
139
+ test('a worker that claims writes but leaves no receipt or library change is a failure, not a success', async () => {
140
140
  const sessionId = 'cred-no-receipt'
141
141
  state.ensureSession(sessionId, { cwd: path.join(home, 'proj-nr'), agentPreset: 'standard' })
142
142
  const ctx = host({ workerText: '我把能记的都记下来了。' })
143
143
  const result = await requestPrivateConsolidation(ctx, sessionId, { force: true })
144
144
  assert.equal(result.ok, false)
145
145
  assert.equal(result.settled, false)
146
- assert.equal(result.reasonCode, 'receipt-missing')
146
+ assert.equal(result.reasonCode, 'receipt-unverified')
147
147
  assert.match(result.error, /receipt/)
148
148
  assert.equal(state.getSessionBinding(sessionId).lastSleepSeq, undefined, 'without a credential the cursor must not advance')
149
149
  const job = ledger.sessionState(sessionId)