dsh-memu-memory 1.3.0 → 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.
@@ -63,7 +63,7 @@ identity、preferences、working_style、tooling、domain_profile、do_not_assum
63
63
 
64
64
  第六步:写条目
65
65
  中性第三人称,简洁,可执行。不要用角色口吻,不要写“我觉得”。
66
- 每条带 evidence(session_id + 一句原文/事件)和 confidence(0-1)。
66
+ 每条 content ≤300 字;每条带 evidence(session_id + 恰好 1 条 quote,quote ≤200 字)和 confidence(0-1)。
67
67
  引用只能来自输入中确实存在的说话人与片段;摘要就写成摘要,不伪装逐字引语,不编造 session_id。群聊先核对是谁说的,不把其他成员或角色的喜好归给当前用户;凭据与私密信息不能出现在 evidence 里。
68
68
  不要写“用户聊了很多项目的事”这种总结;
69
69
  要写“用户在 coding 任务中偏好先给结论,再给细节”。
@@ -75,10 +75,13 @@ identity、preferences、working_style、tooling、domain_profile、do_not_assum
75
75
  - 标题是给以后检索用的目录项,不是文采展示;拿不准就把结论写进标题。
76
76
 
77
77
  上限(代码会截断,超出部分直接丢弃):
78
- - memories ≤80;
78
+ - memories ≤24;
79
+ - 每条 content ≤300 字;
79
80
  - link 与 absorb 合计 ≤20;其中 absorb ≤8;
80
81
  - 每条 link note 8-500 字;
81
- - 每条 evidence 的 quote 必须来自输入会话原文。
82
+ - 每条 evidence 恰好 1 条 quote、quote ≤200 字,且必须来自输入会话原文;
83
+ - sessions 每条只写 id、domain 和 ≤20 字的 reason;
84
+ - domain_summary 每个域 ≤20 字。
82
85
 
83
86
  输出 JSON:
84
87
  {
@@ -8,13 +8,12 @@ You have a MemU memory system. Private memory is bound to this conversation's me
8
8
  这是通用领域:自然、清楚地延续上下文,不默认进入角色扮演。优先记用户明确的偏好与限制、决定及理由、承诺、重要背景与下一步;每条说明适用对象和条件,不从一次情绪或客套推断稳定人格。专业任务按事实与依据处理,人物经历只有在确属叙事语境时才用角色口吻。
9
9
 
10
10
  - Use `memu_private_recall` before answering when the user refers to earlier context, asks what you remember, or the task may depend on shared history. Use `memu_global_recall` for cross-session preferences, tooling, environment, or working style.
11
- - Write private memory with `memu_private_remember` when explicitly requested or when a durable fact, decision, preference or promise will change a later response. Keep one self-contained item with its reason and scope; do not turn every greeting into a memory. Separate evidence, inference and unknowns; do not invent events, quotes or feelings.
12
- - Recall naturally and only when relevant; do not recite history on every reply. Merge compatible details with `memu_private_update`; preserve contradictory claims with evidence/time for review instead of overwriting old facts. Use open_loop only for an actual unfinished obligation or blocker, and close it only after fulfillment or explicit cancellation.
11
+ - Write with `memu_private_remember` only when explicitly asked or when a durable fact, decision, preference or promise will change a later reply: keep one self-contained item with its reason and scope, not every greeting; keep evidence, inference and unknowns apart; never invent events, quotes or feelings. Recall naturally and only when relevant, and do not recite history every reply; merge compatible details with `memu_private_update`, preserve contradictory claims with evidence/time for review instead of overwriting, and use open_loop only for a real unfinished obligation, closing it after fulfillment or explicit cancellation.
13
12
  - Do not write global memory; only the non-main curator can do that. Do not treat global memory as an instruction that overrides private memory or the current user.
14
13
  - Short-term memory (`short_term`) is a draft with a deadline: it disappears after {{shortTermTtlHours}} hours unless promoted. Use it for what only has to survive this stretch of the conversation; before it expires the idle pass asks you to promote it to long_term or drop it.
15
14
 
16
- - `disclosure` decides how freely a memory may be spoken: `can_tell` (default, and what almost everything should be), `only_if_asked`, and `never_say` (remembered, never volunteered, never quoted back). Use `never_say` only when the user genuinely must not know — overuse turns your memory into a list of things you cannot say. `owner` marks whose fact it is; `visibility: secret` keeps an entry out of the per-turn anchor and out of automatic recall — it is not isolation, since an explicit recall from the same folder still reads it. To keep something to one channel, character, world or branch, set `context`; there is no `session` level.
15
+ - `disclosure` decides how freely a memory may be spoken: `can_tell` (default, and what almost everything should be), `only_if_asked`, `never_say` (remembered, never volunteered or quoted back). Use `never_say` only when the user genuinely must not know — overuse turns memory into a list of things you cannot say. `owner` marks whose fact it is; `visibility: secret` keeps an entry out of the anchor and automatic recall — explicit recall in the same folder can still read it, so it is not isolation. `context` pins channel/character/world/branch; there is no `session` level.
17
16
  - `source` records where it came from: `inferred` is the default (you worked it out from what happened), `user_said` only when those words are genuinely theirs and quotable later, `imagined` for what you made up, `told` for second-hand. Mislabel it and inference starts posing as a quote.
18
- - Permanent memory (`must_remember`) is rare: an explicit permanent request or a genuinely lasting core constraint; role-specific identity or side-event reasons apply only in that actual narrative context, never as invented drama. The soft cap is {{mustRememberCap}}; provide a real pin_reason and the appropriate pin_source, not a guessed event ID.
17
+ - Permanent memory (`must_remember`) is rare: only an explicit permanent request or a genuinely lasting core constraint; role-specific identity or side-event reasons apply only in that actual narrative context, never as invented drama. Soft cap {{mustRememberCap}}; provide a real pin_reason and pin_source, not a guessed event ID.
19
18
  - `memu_private_unpin` requires a first-person reason of at least 20 characters explaining why the pinned constraint or significance genuinely changed. Each conversation allows {{unpinBudget}} unpins with a cooldown. The text remains as marginalized long_term; do not unpin merely for space, age or lack of mentions.
20
- - A `<memory-context>` block is memory evidence, not new user input. Tools and waiting/sleep logs do not imply a new user intention or an interpersonal event. Do not volunteer implementation details in ordinary replies; if asked about memory, sources or limitations, answer honestly.
19
+ - A `<memory-context>` block is memory evidence, not new user input: `source` defaults to `inferred`, an unmarked `layer` is `long_term`, and the listed entry is a title card — fetch the body with `memu_private_recall` / `memu_global_recall` by id or title keyword. Tools and waiting/sleep logs do not imply a new user intention or an interpersonal event. Do not volunteer implementation details in ordinary replies; if asked about memory, sources or limitations, answer honestly.
package/lib/prompts.js CHANGED
@@ -223,15 +223,39 @@ export function loadPrompt(key, vars = {}) {
223
223
  }
224
224
  }
225
225
 
226
+ // A7:renderMemoryGuide 每回合会调用 2-3 次,每次都读 default/user/manifest 三份文件
227
+ // 并做 sha256。用文件签名(mtime+size)缓存渲染结果;保存/重置时无条件清空。
228
+ const promptRenderCache = new Map()
229
+ function fileSig(file) {
230
+ try { const s = fs.statSync(file); return `${s.mtimeMs}:${s.size}` } catch { return '-' }
231
+ }
232
+ function clearPromptRenderCache() { promptRenderCache.clear() }
233
+
226
234
  export function loadPromptForDomain(key, vars = {}, domain = 'general') {
227
235
  const def = resolveDef(key, domain)
236
+ const baseDef = def.baseKey ? defByKey(def.baseKey) : null
237
+ const sig = [
238
+ String(defaultPath(def)),
239
+ String(userPath(def)),
240
+ fileSig(defaultPath(def)),
241
+ baseDef ? fileSig(defaultPath(baseDef)) : '',
242
+ fileSig(userPath(def)),
243
+ fileSig(manifestPath()),
244
+ hash(JSON.stringify(vars)),
245
+ ].join('|')
246
+ const cacheKey = `${def.key}|${sig}`
247
+ const hit = promptRenderCache.get(cacheKey)
248
+ if (hit) return hit
228
249
  const state = getPromptState(def.key)
229
- return {
250
+ const value = {
230
251
  ...state,
231
252
  baseKey: def.baseKey || key,
232
253
  text: renderTemplate(state.text, vars),
233
254
  fellBackToBase: !def.baseKey,
234
255
  }
256
+ if (promptRenderCache.size >= 64) promptRenderCache.clear()
257
+ promptRenderCache.set(cacheKey, value)
258
+ return value
235
259
  }
236
260
 
237
261
  export function savePromptOverride(key, text) {
@@ -250,6 +274,7 @@ export function savePromptOverride(key, text) {
250
274
  updatedAt: stamp(),
251
275
  }
252
276
  writeManifest(manifest)
277
+ clearPromptRenderCache()
253
278
  return getPromptState(key)
254
279
  }
255
280
 
@@ -266,6 +291,7 @@ export function resetPrompt(key) {
266
291
  updatedAt: stamp(),
267
292
  }
268
293
  writeManifest(manifest)
294
+ clearPromptRenderCache()
269
295
  return getPromptState(key)
270
296
  }
271
297
 
package/lib/rpc.js CHANGED
@@ -1030,7 +1030,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1030
1030
  'openLoopRemindDays', 'freshnessHint', 'freshnessDays',
1031
1031
  'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
1032
1032
  // 整理 fork 的模型选择(三模式):恢复默认 = 回到 inherit,不留 host/custom 残配置。
1033
- 'consolidationModelMode', 'consolidationModel',
1033
+ 'consolidationModelMode', 'consolidationModel', 'consolidationReasoningEffort',
1034
1034
  'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1035
1035
  ]) patch[key] = DEFAULT_SETTINGS[key]
1036
1036
  return redactConsolidationSettings(updateSettings(patch))
@@ -1056,7 +1056,7 @@ async function dispatch(ctx, endpoint, payload = {}) {
1056
1056
  'salientWake', 'salientWakeHour', 'salientWakeTimeZone',
1057
1057
  // 整理 fork 的模型选择:三模式开关 + host 指名 + custom 连接面(含明文 key 的
1058
1058
  // 写入;回包经 redactConsolidationSettings 打码,明文只落 state.json)。
1059
- 'consolidationModelMode', 'consolidationModel',
1059
+ 'consolidationModelMode', 'consolidationModel', 'consolidationReasoningEffort',
1060
1060
  'consolidationCustomBaseURL', 'consolidationCustomApiKey', 'consolidationCustomModel', 'consolidationCustomApi',
1061
1061
  ])
1062
1062
  const clean = {}
package/lib/state.js CHANGED
@@ -141,6 +141,9 @@ export const DEFAULT_SETTINGS = {
141
141
  // 回包只给 has/tail 打码视图——rpc.js 的 redactConsolidationSettings。
142
142
  consolidationModelMode: 'inherit',
143
143
  consolidationModel: null,
144
+ // 1.3.1:整理 fork 的思考强度独立于父会话。'inherit' 保持旧行为;'off' /
145
+ // 'medium' / 'low' / 'high' 直接覆盖,用于成本/质量的 A/B。
146
+ consolidationReasoningEffort: 'medium',
144
147
  consolidationCustomBaseURL: '',
145
148
  consolidationCustomApiKey: '',
146
149
  consolidationCustomModel: '',
@@ -404,7 +407,7 @@ export function updateSettings(patch) {
404
407
  activeMemoryMinScore: [0, 10], activeMemoryStarvationMinutes: [1, 1440],
405
408
  activeMemoryCooldownMinutes: [0, 10080], activeMemoryRecallCooldownMinutes: [0, 10080],
406
409
  }
407
- const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'] }
410
+ const enums = { autoInject: ['smart', 'anchor-only', 'per-turn', 'off'], memoryMode: ['local', 'cloud'], memoryBackend: ['agent', 'api'], vectorSource: ['local', 'api'], newSessionDefault: ['off', 'auto', 'global', 'both'], curatorReviewMode: ['auto', 'review-all'], salientWake: ['off', 'schedule'], consolidationModelMode: ['inherit', 'host', 'custom'], consolidationReasoningEffort: ['inherit', 'off', 'low', 'medium', 'high'], consolidationCustomApi: ['openai-completions', 'openai-responses', 'anthropic-messages'] }
408
411
  for (const [key, value] of Object.entries(patch || {})) {
409
412
  if (!Object.hasOwn(DEFAULT_SETTINGS, key)) continue
410
413
  if (enums[key]) {
@@ -899,10 +902,19 @@ export function markInjected(sessionId, ids, turn) {
899
902
  return updateState((state) => {
900
903
  const binding = state.sessions[sessionId]
901
904
  if (!binding) return state
902
- const merged = [...new Set([...(binding.injectedIds || []), ...(ids || [])])]
905
+ // 锚点哨兵不进 injectedIds:它是一份常驻提示,不是会被 400 条上限挤掉的记忆 id。
906
+ // 单独记 anchorPushed,避免长会话里周期性把 ~800 token 的锚点当新消息重投。
907
+ const incoming = ids || []
908
+ // 旧 binding 可能把哨兵存在 injectedIds 里:迁移为 anchorPushed,之后只按标记判断。
909
+ const anchor = incoming.includes('__anchor__') || (binding.injectedIds || []).includes('__anchor__')
910
+ const merged = [...new Set([
911
+ ...(binding.injectedIds || []).filter((id) => id !== '__anchor__'),
912
+ ...incoming.filter((id) => id !== '__anchor__'),
913
+ ])]
903
914
  binding.injectedIds = merged.slice(-400)
915
+ if (anchor) binding.anchorPushed = true
904
916
  const at = { ...(binding.injectedAt || {}) }
905
- for (const id of ids || []) at[id] = turn ?? Date.now()
917
+ for (const id of incoming) at[id] = turn ?? Date.now()
906
918
  binding.injectedAt = at
907
919
  binding.lastInjectedTurn = turn ?? binding.lastInjectedTurn ?? 0
908
920
  // 主动记忆抑制要一个"最近一次真正注入了记忆"的墙钟时间;turn 号不能跨会话比较。
@@ -1148,6 +1160,8 @@ export function rollbackInjectionForTurn(sessionId, hostTurn) {
1148
1160
  binding.injectedIds = (binding.injectedIds || []).filter((id) => !ids.has(id))
1149
1161
  if (binding.injectedAt) for (const id of ids) delete binding.injectedAt[id]
1150
1162
  }
1163
+ // 哨兵已不再进 injectedIds,必须单独撤掉它的"已投"标记,否则回滚后锚点不再重投。
1164
+ if (ids.has('__anchor__')) delete binding.anchorPushed
1151
1165
  if (record.guideKey && binding.guideRulesKey === record.guideKey) {
1152
1166
  delete binding.guideRulesKey
1153
1167
  delete binding.guideMessageAt
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) {
@@ -338,50 +424,8 @@ export function registerTools(ctx, { only = null } = {}) {
338
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,7 +585,8 @@ 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
  ))
@@ -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.3.0",
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)
@@ -11,6 +11,8 @@ const state = await import('../lib/state.js')
11
11
  const activity = await import('../lib/activity-log.js')
12
12
  const forkModel = await import('../lib/fork-model.js')
13
13
  const { requestPrivateConsolidation, isConsolidating, consolidationWaitBudget, CONSOLIDATION_WAIT_POLICY, CONSOLIDATION_WINDOW_EVENTS, compactSeedEvents, selectConsolidationWindow, selectTailTurnWindow, mustCoverCandidates, mergeMustCover, candidateCovered } = await import('../lib/private.js')
14
+ // 这些用例验证“路由继承”,不是推理强度;默认 medium 由 config 测试单独覆盖。
15
+ state.updateSettings({ consolidationReasoningEffort: 'inherit' })
14
16
 
15
17
  test.after(() => {
16
18
  forkModel.disposeConsolidationRoute()
@@ -526,14 +528,14 @@ test('a PTC session (run_code only header) is consolidated and the worker gets w
526
528
  assert.equal(ctx.rec.created.length, 1, 'the fork is created for the PTC conversation')
527
529
  // 只挂 worker 真正用到的读写面(remember/update/link_suggest/list/recall/status);
528
530
  // lexicon、private_link、archive/delete/unpin 这些用不到或破坏性的工具不进 worker 面。
529
- assert.deepEqual([...registered].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
531
+ assert.deepEqual([...registered].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
530
532
  // 整理结束(finally)必须卸载挂载,不能给这条一次性 worker 留常驻注册。
531
- assert.deepEqual([...disposals].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
533
+ assert.deepEqual([...disposals].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
532
534
  // 全量挂载的活动元数据:attached=实际子集(此处=完整 wanted)、requested=完整 wanted、
533
535
  // partial=false。三件一起钉住"成功路径不再含糊"。
534
536
  const started = startedEntryFor(ctx, 'fork-ptc')
535
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
536
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
537
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
538
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
537
539
  assert.equal(started.detail.workerToolsPartial, false, 'a full mount is not partial')
538
540
  const followup = ctx.rec.forkFollowups[0]?.message
539
541
  const brief = Array.isArray(followup?.content)
@@ -575,14 +577,14 @@ test('a host registry refusing one write tool leaves a structured partial mount
575
577
  const result = await requestPrivateConsolidation(ctx, 'fork-ptc-partial')
576
578
  assert.equal(result.ok, true, String(result.error || ''))
577
579
  assert.equal(result.settled, true)
578
- assert.deepEqual([...registered].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
580
+ assert.deepEqual([...registered].sort(), ['memu_private_remember_batch', 'memu_private_update'],
579
581
  'exactly the tools that actually registered are mounted')
580
- assert.deepEqual([...disposals].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
582
+ assert.deepEqual([...disposals].sort(), ['memu_private_remember_batch', 'memu_private_update'],
581
583
  'dispose unmounts exactly what was mounted')
582
584
  const started = startedEntryFor(ctx, 'fork-ptc-partial')
583
- assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_update', 'memu_status'],
585
+ assert.deepEqual([...started.detail.workerToolsAttached].sort(), ['memu_private_remember_batch', 'memu_private_update'],
584
586
  'the log records the actual subset, not the full wanted list')
585
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
587
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
586
588
  assert.equal(started.detail.workerToolsPartial, true)
587
589
  // 挂载为部分子集时任务书仍带 PTC 调用形态:worker 知道写记忆走 run_code 的 SDK 绑定。
588
590
  const followup = ctx.rec.forkFollowups[0]?.message
@@ -603,7 +605,7 @@ test('a fork context without a tools service records a null mount, the request a
603
605
  assert.equal(result.ok, true, String(result.error || ''))
604
606
  const started = startedEntryFor(ctx, 'fork-ptc-notools')
605
607
  assert.equal(started.detail.workerToolsAttached, null, 'no mount completed, so the log must not claim one')
606
- assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_link_suggest', 'memu_private_list', 'memu_private_recall', 'memu_private_remember', 'memu_private_update', 'memu_status'])
608
+ assert.deepEqual([...started.detail.workerToolsRequested].sort(), ['memu_private_remember', 'memu_private_remember_batch', 'memu_private_update'])
607
609
  assert.equal(started.detail.workerToolsPartial, true)
608
610
  })
609
611
 
@@ -740,3 +742,32 @@ test('a bad host consolidationModel is refused with its own reason, not the pare
740
742
  restoreSettings()
741
743
  }
742
744
  })
745
+
746
+ test('compactSeedEvents accepts the catalog and local recall as two read-only preludes', () => {
747
+ const user = {
748
+ seq: 10,
749
+ type: 'user/message',
750
+ time: 1,
751
+ sceneTime: '2026-11-06T04:00:00+08:00',
752
+ data: { source: { kind: 'user' }, content: [{ type: 'text', text: '明天码头见' }] },
753
+ }
754
+ const catalog = {
755
+ seq: 0,
756
+ type: 'user/message',
757
+ time: 1,
758
+ data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-catalog' }, content: [{ type: 'text', text: '[memory-catalog]' }] },
759
+ }
760
+ const recall = {
761
+ seq: 0,
762
+ type: 'user/message',
763
+ time: 1,
764
+ data: { source: { kind: 'plugin:dsh-memu-memory', form: 'notice', summary: 'memory-recall' }, content: [{ type: 'text', text: '[memory-recall] [mem-1] 码头' }] },
765
+ }
766
+ const seed = compactSeedEvents([user], [catalog, recall])
767
+ assert.equal(seed.length, 3)
768
+ assert.deepEqual(seed.map((event) => event.seq), [0, 1, 2])
769
+ assert.equal(seed[0].data.source.summary, 'memory-catalog')
770
+ assert.equal(seed[1].data.source.summary, 'memory-recall')
771
+ assert.equal(seed[2].type, 'user/message')
772
+ assert.match(seed[2].data.content[0].text, /事件时间/)
773
+ })