dsh-memu-memory 1.3.10 → 1.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # 更新日志 / Changelog
2
2
 
3
+ ## [1.3.11] - 2026-11-20
4
+
5
+ > 隐藏记忆不再经词法统计挤掉可见召回;必写候选核验改为保守证据比对,同日不同事/极性相反/数值改变不再被误判「已覆盖」。
6
+
7
+ - **召回语料资格前移**:私库纯词法与混合召回的词法支路在构建 BM25 语料**之前**应用会话可见性、自动资格、披露与说话人过滤(此前只在最终融合时过滤,隐藏条目仍污染 DF/avgdl,甚至触发高频词剪枝把可见命中裁掉)。精确 id 直达与全局域路由契约不变,显式读取保留原资格。语料缓存按过滤后文件集指纹隔离,资格变化即失效;缓存 key 追加 `auto/explicit : asked/plain : speaker` 标志,自动/显式交替不再每次重建语料(跨库 key 同步补说话人标志)。守卫:`tests/recall-corpus-eligibility.test.mjs`(3 后端 × secret/错角色/never_say/only_if_asked,断言可见命中与词法分数不变、精确 id 仍可读)。
8
+ - **必写候选保守核验**:`candidateCovered` 不再凭日期相同或两个共享 bigram 结算。日期从文本重合证据中剔除;要求 ≥2 个有效 token、重合数达 min(3, 候选 token 数) 且覆盖率 ≥55%,候选的汉字/Latin 词与数值集合须在同一条新增/更新记忆中保留,共享 token 的子句否定极性须一致;不足以证明时留在 carry 下窗顺延。仍是词法近似,可能保守保留已写入的同义改写(明说的取舍:误判覆盖会静默丢事实,误判未覆盖只是有界重写)。守卫:`tests/consolidation-fork.test.mjs` 新增同日不同事件/极性相反/动作改变/数值改变/日期单独命中反例与真实改写正例。
9
+ - **评测口径**:`scripts/recall-bench.mjs` 新增 `allExpectedAt3`(前三名须包含全部预期 id),冲突题仅命中一方不再被 `recallAt3` 误读为完整覆盖。
10
+ - 文档同步:README(含中文版特性条目)、`docs/memory-semantics.md`、`docs/troubleshooting.md` §3.41、绑定生命周期行号引用;`logs/` 加入 .gitignore。
11
+
3
12
  ## [1.3.10] - 2026-11-19
4
13
 
5
14
  > 冻结退避优化(1.3.9 复审建议级项落地):snapshot-failed 熔断期不再每 5 分钟重读快照/种子、不占整理 budget,且冻结后到来的新真人回合立即让路。
package/README.md CHANGED
@@ -58,6 +58,7 @@ All screenshots are the real WebUI on isolated example data, not anyone's memori
58
58
 
59
59
  - **Three layers, one timeline.** `short_term` drafts expire after 72 hours by default; `long_term` is the body of ordinary memory; `must_remember` needs a reason and a source, decays over 365 days with a 0.35 strength floor, and can be *marginalized* but never auto-deleted to make room.
60
60
  - **Recall is a moment, not a dump.** The first turn after a session starts (or after compaction) gets an anchor block with budgets for pinned, core and global memory. After that, each user turn gets at most one recall. Deduplication and a token budget are enforced in code, not left to the prompt. Anchor and recall entries are **title cards**: title, id and semantic tags only. The body stays in the drawer and behind `memu_private_recall` / `memu_global_recall`, so the same budget exposes far more memories without pasting text the model never asked for.
61
+ - **Invisible memories cannot crowd out visible ones.** Private lexical recall builds its scoring corpus after applying conversation context, speaker and disclosure rules, including the lexical branch of mixed recall. Explicit reads retain their disclosure permissions.
61
62
  - **A private lexicon writes itself.** The consolidation worker extracts stable, evidenced slang, memes and project terms with one term per entry. Ordinary entries become active immediately (no human review queue), while sensitive triggers and sensitive edits stay user-only. The lexicon page is a card flow with active/archived tabs, edit, archive/restore and two-step permanent delete. A **global lexicon** sits beside the per-library ones: every conversation reads it, only you write it. With same-domain cross-library recall on, the anchor, this-turn match and `memu_lexicon_search` merge those libraries too — the page still browses one book at a time.
62
63
  - **Private links come from assertions, not statistics.** `autoLinkMode` defaults to *candidates only*: a local zero-token pass ranks names into a review queue and writes nothing. Once you confirm an entity, its names and aliases are matched against memory text (`entity-mention`); `conflicts_with` / `supersedes` / the same `fact_key` add field-evidence edges. Lexical similarity, shared tokens and vectors never create an edge. Confirming, renaming, merging or deleting an entity maintains its edges immediately, and a removed auto edge is suppressed so it cannot come back. Links are metadata, shown with an “Auto” badge in the graph; they never rewrite a body, write a vector or delete anything. Existing libraries migrate with `node scripts/rebuild-auto-links.mjs` (dry-run first, `--apply` takes a backup).
63
64
  - **A date is either an anniversary or one day.** `MM-DD` recurs every year (a birthday); `YYYY-MM-DD` fires the day before and the day itself, then is spent. Relative wording (今天 / 明天 / 下周X / 月底) is resolved against the turn's scene time and stored as an absolute date; a memory that says "tomorrow" is stored as the dated form, so an appointment does not come back every year.
@@ -328,6 +329,7 @@ the idle window starts from real message activity or the agent's return to idle.
328
329
  - **Poisoned v4 sessions:** historical `format v4 message requires a producer-owned source kind` rows can be diagnosed but not rewritten; the plugin never edits private session files.
329
330
  - **Agent presets:** a conversation whose preset (`i-am-yuike`, `yuike-standard`, …) carries its own `cordis.yml` composes its model-facing plugins from that list alone, and its scope never delivers `agent/pre-step` to this plugin. At runtime `lib/preset-scope.js` attaches an injection listener to that agent's own context, so **anchor and recall delivery works**. All conversations now receive the memory rules as one `<memory-guide rules="…">` plugin message on the first step of a turn; the plugin no longer registers a system-prompt section, and the message is replaced after a domain/prompt change or a compaction (`rulesKey` / `guideLost`). The **final tool list** is a third, separate question: it follows the preset's own plugin list and the host scope, and it cannot be inferred from whether this plugin is listed — observations in this repo record both "no `memu_*` tools" and `memu_private_*` present in some presets' tool chains. **Per-preset tool availability still needs a real-host check (W3)**; until then do not read this as "presets have no tools", nor as "listing the plugin is enough". The plugin never edits anyone's preset files.
330
331
  - **Consolidation worker (C 包, 2026-10-30).** An idle or manual pass now works from a *fixed snapshot*: it takes the public `sessionQuery.observeSession()` lease (falling back to `readSession()` when the host offers no lease), cuts at the last complete `turn/end`, and drops unpaired tool calls and half steps — a live transcript whose last turn is still open is **deferred**, never consolidated. A job is settled only by a structured completion receipt that is cross-checked against the library index (an id the library does not contain is not a success, and a rewrite of an existing id counts as an update, not a new memory). Checked / pending / in-flight ranges and a lease are persisted separately in `consolidation.json`, so a crash, a timeout or a failed turn leaves the range pending instead of looking consolidated. **Limits:** the worker still runs inside the parent preset's own system prompt — it receives an explicit "you are a background consolidation worker, not this character" brief, which reduces but does not remove persona carry-over, because the host has no public API to replace that prompt; and when the conversation's tool surface carries no `memu_private_remember` / `memu_private_update` (or exposes memory only through PTC), consolidation reports `unavailable` (`worker-tools-missing` / `worker-tools-ptc-only`) rather than forking a worker that could not write. The parent's library, scope, domain and memory context are re-checked before dispatch, on every worker tool call, and again before any result is credited.
332
+ - **Consolidation coverage is conservative lexical evidence.** A matching date or a couple of shared terms does not prove a candidate was written. The local check also requires text coverage, retained characters/words and values, and matching clause polarity; uncertain candidates stay in carry. It can retain a paraphrase that was already saved, and it does not claim semantic equivalence.
331
333
  - **"Tomorrow" is resolved at write time.** A relative day (今天 / 明天 / 后天 / today / tomorrow) together with a month-day settles into one dated memory; a memory that only says "sometime next month" keeps no date rather than inventing one. A date that was already written as `MM-DD` is not rewritten — the fix applies to new writes.
332
334
  - **Not in scope:** cloud MemU integration, source backfill for old entries, automatic repair of already-written v4 corruption.
333
335
 
package/README.zh.md CHANGED
@@ -58,6 +58,7 @@
58
58
 
59
59
  - **三层,一条时间线。** `short_term` 草稿默认 72 小时到期;`long_term` 是记忆主体;`must_remember` 需要理由与来源,按 365 天半衰并带 0.35 强度地板,可以**边缘化**,但不会为腾名额被自动删除。
60
60
  - **召回是一个瞬间,不是一次倾倒。** 新会话或压缩后的第一个回合得到锚点块(pin / core / global 分段预算);之后每个用户回合最多一次召回。去重与 token 预算由代码执行,不交给提示词自觉。
61
+ - **不可见的记忆挤不掉可见的。** 私库词法召回(含混合召回的词法分支)在构建评分语料之前就应用会话可见性、说话人与披露资格;隐藏条目不参与词频统计,也不能触发高频剪枝。显式读取保留原有读取资格。
61
62
  - **日期要么是纪念日,要么是一天。** `MM-DD` 每年复发(生日);`YYYY-MM-DD` 在前一天和当天各响一次,之后就算用过了。说「今天 / 明天 / 下周X / 月底」的相对日期会按这一轮的场景时间换算成绝对日期再存;说「明天」的记忆存成带年份的日期,不会变成每年都冒出来的周年。
62
63
  - **记忆会不均匀地淡。** 新近、访问次数、峰终、首因、习惯化、闪光灯记忆的准确度共同参与强度。情绪用四项构成(joy / anger / sorrow / fear,和为 1)加唤醒度 `arousal`(强度)与掌控感 `dominance` 描述;「嫉妒」这类复合情绪是四项的具名混合比例,不是新维度。情绪只影响召回排序:不进注入文本,也不改记忆正文。门控是三条独立条件的 OR——主导项占比 ≥ 0.35、`|arousal − 0.35| ≥ 0.1`、`|dominance| ≥ 0.25`;三条都不满足时两项乘数恒为 1。旧条目没有 emotion 时继续走原来的 valence 路径,不从旧 valence 反推四轴。一条生动但可能记错的记忆会显示「细节未必准」,而不是假装确定。
63
64
  - **来源是事实,不是文风。** 每条记忆带 `source` / `source_kind`(`user_said` / `assistant_said` / `told` / `imagined` / `inferred` / `tool`)、`speaker_id`、`confidence`、`accuracy` 与说出口径。模糊的推断不能冒充原话,助手自己的承诺和计划也不能记成用户说的。
@@ -12,7 +12,7 @@
12
12
  |---|---|---|---|
13
13
  | 1. 持久绑定 | `state.json` 的 `sessions[sessionId]`:`scopeKey`、`libraryId`、开关、`memoryContext`、`inbound.pending/seen/claimed/clock`、`sleepRetryAt`、注入标记等 | 跨重启、fork、插件重载保留;只有显式状态写入才改变 | 只读快照可读;报告的核心对象 |
14
14
  | 2. 运行时监听器 | `lib/preset-scope.js:19` 的 `attachments`,按 **agent context 对象** 键控 | 随 context 存在;context 被替换时旧监听器应释放,下一次 attach 重新挂载 | 跨进程不可读,声明为 `runtime-listener` |
15
- | 3. 临时映射/缓存 | `lib/inbound.js:12-14` 的 `mediaJobs`/`calls`/`sessions`、`lib/media.js:19` 的 `captures`、`lib/private.js:213` 的 `inFlight`、`lib/curator.js:11` 的 `jobs`、`lib/state.js:1146` 的 `indexCache`、`lib/paths.js:52` 的 `readFailures` | 随 promise settle、turn/end、session/disposed、下一次成功读取或下一次加载清理 | 跨进程不可读,声明为 `temporary-map` 或 `cache` |
15
+ | 3. 临时映射/缓存 | `lib/inbound.js:12-14` 的 `mediaJobs`/`calls`/`sessions`、`lib/media.js:19` 的 `captures`、`lib/private.js:1028` 的 `inFlight`、`lib/curator.js:11` 的 `jobs`、`lib/state.js:1146` 的 `indexCache`、`lib/paths.js:52` 的 `readFailures` | 随 promise settle、turn/end、session/disposed、下一次成功读取或下一次加载清理 | 跨进程不可读,声明为 `temporary-map` 或 `cache` |
16
16
 
17
17
  **三层不混算。** `summary.bindings`、`summary.inbound`、`summary.unfinished` 只统计持久绑定;`summary.runtime` 只在调用方提供了进程内快照时出现,分别是 `runtimeListeners` 和 `temporaryMaps` 的合计。runtime 计数不会加进 binding 数,也不会把“持久层零候选”解释成“运行时没有残留”。同一份 state 在提供/不提供 runtime 快照时,`bindings` 与 `candidates` 必须完全一致。
18
18
 
@@ -111,7 +111,7 @@
111
111
  - 评估通过但整理写了 0 条 = 正常成功(`lastSleepAt` 前移),不会每小时重来。整理日志额外记录 `scanned/fresh/index +N`(`scanned` 现在是**这一窗**的事件数,`fresh` 是游标后的总增量)和 `remaining`(还余多少事件),`check` 日志记录 `score/reason/parts/空闲分钟/会话事件数/待整理事件数`。
112
112
  - 会话被删:host 对 `readSession` 报 `session "…" not found`,这是**不变量**而不是瞬时故障。`runSleepPass` 一旦看到就把 binding 标 `sessionGone: true` 并清掉重试计数,此后直接跳过(以前会按 2 的幂退避、封顶 1 小时,永远重试);同名会话后来真的收到新消息时(`lib/inbound.js`)会清掉这个标记。**"读不出来"不是"被删了"**:转录读失败(例如 `ENOENT`)由快照层显式标成可重试(`lib/consolidation-snapshot.js` 的 `failed()` → `retryable: true`),`runSleepPass` 只按退避重试、不打 `sessionGone`——`isGoneSessionError` 只认宿主那句 `session "…" not found` / `no such session`。
113
113
  - 手动「整理这场对话」(RPC `generatePrivate`)带 `force: true`,跳过上面两道评估与抑制:用户已经决定了。若游标已经到末尾,手动整理只重查最后 ≤300 个事件,不再重放整段历史。
114
- - **必写候选跨窗顺延。** 每窗本地抽 salience ≥3 的轮次(最多 8 条)作为必写清单;本窗没写进库的候选记入账本 `carry`,下一窗优先带 4 条、其余名额留给新候选。核验是纯本地 token 比对(日期命中或 ≥2 个有效 bigram),不额外调模型;最后一窗也会在同一份任务书里看到顺延候选,不需要为补写再开一次整窗 fork。
114
+ - **必写候选跨窗顺延。** 每窗本地抽 salience ≥3 的轮次(最多 8 条)作为必写清单;本窗没写进库的候选记入账本 `carry`,下一窗优先带 4 条、其余名额留给新候选。核验是纯本地保守证据比对,不额外调模型:日期从文本重合证据中剔除;至少 2 个有效 token,重合数须达 min(3, 候选 token 数) 且覆盖率 ≥55%,候选里的汉字 / Latin 词必须在同一条新增或更新记忆中出现,数值集合须包含候选值,共享 token 的子句否定极性须一致。日期相同、少量重词、不同动作或数值、相反极性不再单独算覆盖;不足以证明时保留在 carry。它仍是词法近似,不能证明任意改写的语义等价,因此可能保守保留已写入的改写候选;最后一窗也会在同一份任务书里看到顺延候选,不需要为补写再开一次整窗 fork。
115
115
 
116
116
  ---
117
117
 
@@ -143,6 +143,8 @@
143
143
 
144
144
  总结生成与向量路由解耦:常规私有整理通过 Agent fork;显式远程总结动作调用配置的聊天端点,其产物同样经 `privateRemember` 提交。启用向量不自动启用远程总结;聊天/总结模型不参与召回重排,也不作为向量失败回退。
145
145
 
146
+ 私有单库词法召回和受管召回的词法分支,均在构建 BM25 语料前应用会话可见性、说话人及披露资格;不可见条目不参与 DF/avgdl 或高频剪枝,避免通过统计量挤掉可见命中。自动 secret/never_say/未明确询问的 only_if_asked 被排除,显式查询保留原读取资格,精确 id 直达不改变。
147
+
146
148
  受管召回只在候选阶段把词法结果与 MemU semantic retrieve 结果按 RRF(k=60)融合:先按 `isMemoryEligible`、`visibleToSession`、自动召回的 `secret` 排除及 context/scope 过滤,再按 canonical id 去重与候选上限处理。显式与自动召回共用候选融合;`touchAccessMany` 仍只对显式召回执行。精确记忆 id 走直达路径,切库期间中止以避免混合两个库。
147
149
 
148
150
  服务不可用时仅回退词法并保留可见错误信号;不暗切远端、不调用 LLM。真实 embedding 质量、延迟和跨模型收益仍需单独评测;W8(助手重复提示)已决定不做,结论与理由见 `AGENTS.md`。
@@ -36,6 +36,7 @@
36
36
  精确读取分页 / 显式 topK 被扩大 → §3.38
37
37
  worker 前置依赖 / 完整包超限 / usage 未知 → §3.39
38
38
  整理输出截断 / 改预算后同快照仍冻结 → §3.40
39
+ 隐藏记忆增加后可见结果消失 / 必写候选误结算 → §3.41
39
40
  聊很久一条记忆都没写 → §3.18
40
41
  人格预设会话里完全没有记忆 → §3.19
41
42
  鉴权 / 401/403 行为说不清 → §3.20
@@ -721,3 +722,11 @@ grep tests 里的硬编码清单。守卫:全量 `npm test` 1676/1674 pass / 0
721
722
  宿主将输出截断映射为 `turn/end.reason.kind=max-tokens`,该响应里的工具不会执行。插件返回 `model-output-limit`,保留 pending,不推进已检查游标;失败 worker 保守退役。错误提示需调整宿主输出预算或选择模型支持的思考档,也可能涉及剩余上下文。已落库的部分写入不撤回,但不能据此结算整窗。持久 worker 的公开 AgentOptions 与新窗口要求不一致时,在等到 idle、补齐迟到计量后换新并交接,不能继续沿用旧实例的输出额度。
722
723
 
723
724
  同配置连续失败仍按上限暂停,防止无休止付费。输出失败保存不含凭据的执行指纹;输出上限、路由或思考配置改变后,下次允许检查时恢复同快照的受控重试;暂时读不到模型元数据不能伪装成配置改变,不把暂停标成已结算。缺指纹的旧输出失败只获得一次建立新指纹的机会;无法公开观测的上游变化仍可显式手动重试。守卫位于 `tests/consolidation-fork.test.mjs` 与 `tests/consolidation-ledger.test.mjs`,覆盖 fork/worker pending、无变更暂停、父输出限制及宿主默认限制变化后的恢复。
725
+
726
+ ### 3.41 隐藏记忆干扰召回与必写候选误结算
727
+
728
+ **症状:** 新增当前会话不可见的记忆后,原来能召回的可见条目消失;或同日不同事件、否定相反的记忆被当成已经覆盖,必写候选没有顺延。
729
+
730
+ **落点:** `lib/memory.js` 的私库纯词法与混合召回词法支路在建 BM25 语料前应用会话、自动资格、披露与说话人过滤。只在最终排序时过滤会让隐藏条目污染词频,甚至触发高频词裁剪。显式精确 id 读取维持原资格规则;全局路由不扩大可见范围。`lib/private.js` 的 `candidateCovered` 不能仅凭日期相同或两个相邻字片段就结算候选。
731
+
732
+ **守卫:** `tests/recall-corpus-eligibility.test.mjs` 用隔离临时库覆盖纯词法、成功的混合路径与向量故障回退,加入 secret、错角色、never_say、only_if_asked 条目后,可见命中保持不变,并保留精确 id 读取。`tests/consolidation-fork.test.mjs` 覆盖同日不同事件、极性相反、动作改变、数值改变及日期单独命中等反例,并保留真实改写正例。`scripts/recall-bench.mjs` 的 `recallAt3` 是任一预期条目命中率;新增 `allExpectedAt3` 要求前三名包含所有预期 id,避免冲突题仅命中一方就被误读为完整覆盖。
@@ -54,7 +54,7 @@ export const RUNTIME_STATE = Object.freeze([
54
54
  { layer: 'temporary-map', file: 'lib/inbound.js:13', name: 'calls', keyedBy: 'sessionId', clearedBy: 'tool/result or turn/end' },
55
55
  { layer: 'temporary-map', file: 'lib/inbound.js:14', name: 'sessions', keyedBy: 'sessionId', clearedBy: 'session/disposed (releaseInboundSession)' },
56
56
  { layer: 'temporary-map', file: 'lib/media.js:19', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
57
- { layer: 'temporary-map', file: 'lib/private.js:1014', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
57
+ { layer: 'temporary-map', file: 'lib/private.js:1028', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
58
58
  { layer: 'temporary-map', file: 'lib/curator.js:56', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
59
59
  { layer: 'cache', file: 'lib/state.js:1392', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
60
60
  { layer: 'cache', file: 'lib/paths.js:52', name: 'readFailures', keyedBy: 'absolute file', clearedBy: 'a later successful read' },
package/lib/memory.js CHANGED
@@ -305,8 +305,12 @@ async function withManagedGlobalWrite(action) {
305
305
  return withVectorWrite(() => { assertVectorWriteAllowed(); return action() })
306
306
  }
307
307
 
308
- async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null }) {
309
- const local = localRecall(index, query, undefined, { cacheKey: libraryId ? `lib:${libraryId}` : `global:${domain || 'all'}`, topK })
308
+ async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId, automatic = false, intent, retrieveImpl, byId = false, domain = null, disclosureAsked = false, speakerFilter = null }) {
309
+ // Private lexical statistics must use the same eligible corpus as final fusion.
310
+ // Exact-id reads and the global domain-scoped route keep their existing contract.
311
+ const gate = { automatic, sessionId: memorySessionId(exec), disclosureAsked, speakerFilter }
312
+ const filter = libraryId && !byId ? (file) => crossLibraryEligible(file.entry, gate) : undefined
313
+ const local = localRecall(index, query, filter, { cacheKey: libraryId ? `lib:${libraryId}:${gateCacheSuffix(gate)}` : `global:${domain || 'all'}`, topK })
310
314
  try {
311
315
  if (intent.error) throw intent.error
312
316
  const captured = intent.route === 'managed-local' ? captureGeneration() : null
@@ -355,8 +359,8 @@ async function managedRecall({ exec, index, sourceEmpty, query, topK, libraryId,
355
359
  if (!Array.isArray(semantic?.files)) throw new Error('managed vector recall returned no file list')
356
360
  if (captured) assertGeneration(captured)
357
361
  const fused = fuseRecallCandidates({ local: local.files, semantic: semantic.files, index,
358
- limit: hybridCandidateLimit(topK), automatic, disclosureAsked: detectQueryIntent(query) === 'boundary',
359
- speakerFilter: detectSpeakerQuery(query), sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
362
+ limit: hybridCandidateLimit(topK), automatic, disclosureAsked: libraryId ? disclosureAsked : detectQueryIntent(query) === 'boundary',
363
+ speakerFilter: libraryId ? speakerFilter : detectSpeakerQuery(query), sessionId: memorySessionId(exec), route: 'managed-vector-rrf' })
360
364
  return { ...semantic, files: fused.files, recallRoute: 'managed-vector-rrf', fusion: fused.debug, vectorGeneration: captured?.token ?? null }
361
365
  })
362
366
  clearRecallError(exec)
@@ -2593,6 +2597,11 @@ function crossLibraryEligible(entry, { automatic, sessionId, disclosureAsked, sp
2593
2597
  && speakerMatchesFilter(entry, speakerFilter)
2594
2598
  }
2595
2599
 
2600
+ // 资格标志进缓存 key:自动/显式的授权语料不同,共用 key 会让交替召回每次指纹失配重建。
2601
+ function gateCacheSuffix({ automatic, disclosureAsked, speakerFilter }) {
2602
+ return `${automatic ? 'auto' : 'explicit'}:${disclosureAsked ? 'asked' : 'plain'}${speakerFilter ? `:${speakerFilter}` : ''}`
2603
+ }
2604
+
2596
2605
  // R4:跨库统一词法评分。文档身份是复合 [libraryId,id] key,两库同 id 是两份
2597
2606
  // 文档而不是同一份;语料指纹含复合 id,任一成员库内容变化都会失效共享语料。
2598
2607
  // 评分规则与 localRecall 的 BM25 分支一致(日期加成、证据分离、date-only 末位),
@@ -2662,7 +2671,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
2662
2671
  }
2663
2672
  const managed = await managedRecall({
2664
2673
  exec, index: scoped, sourceEmpty: Object.keys(source.index.entries || {}).length === 0,
2665
- query, topK, libraryId: source.libraryId, automatic, intent, retrieveImpl, byId, domain,
2674
+ query, topK, libraryId: source.libraryId, automatic, intent, retrieveImpl, byId, domain, disclosureAsked, speakerFilter,
2666
2675
  })
2667
2676
  lists.push({
2668
2677
  libraryId: source.libraryId,
@@ -2689,7 +2698,7 @@ async function recallCrossLibrary({ exec, sources, query, topK, route, byId, aut
2689
2698
  return { ...base, files, fusion: { crossLibraryLexical: 'exact-id' } }
2690
2699
  }
2691
2700
  if (route === 'lexical') {
2692
- const cacheKey = `cross:${sources.map((source) => source.libraryId).join('|')}:${domain || 'all'}:${automatic ? 'auto' : 'explicit'}:${disclosureAsked ? 'asked' : 'plain'}`
2701
+ const cacheKey = `cross:${sources.map((source) => source.libraryId).join('|')}:${domain || 'all'}:${gateCacheSuffix(gate)}`
2693
2702
  const unified = crossLibraryLexical(lists.flatMap((list) => list.files), query, { cacheKey, topK })
2694
2703
  if (unified.mode === 'recency') {
2695
2704
  return { ...base, files: unified.files, fusion: { crossLibraryLexical: 'recency' } }
@@ -2880,14 +2889,17 @@ export async function privateRecall({ exec, query, topK, relevanceThreshold, pur
2880
2889
  if (excludedCount) candidateK = Math.min(HYBRID_CANDIDATE_MAX, candidateK + excludedCount)
2881
2890
  }
2882
2891
  const generationAtStart = scopeGenerationOf(binding)
2883
- // Single source keeps the old path byte-for-byte; the cross-library merge only
2892
+ // Single-source lexical scoring uses the same eligibility gate as the cross-library corpus.
2893
+ const gate = { automatic: purpose === 'automatic', sessionId: memorySessionId(exec),
2894
+ disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) }
2895
+ // The cross-library merge only
2884
2896
  // exists when another qualifying library is actually present.
2885
2897
  const retrievalStarted = performance.now()
2886
2898
  const result = sources.length === 1
2887
2899
  ? (route === 'lexical' || byId
2888
- ? { ...localRecall(sources[0].index, searchQuery, undefined, { cacheKey: `lib:${sources[0].libraryId}`, topK: candidateK }), recallRoute: 'local' }
2900
+ ? { ...localRecall(sources[0].index, searchQuery, byId ? undefined : (file) => crossLibraryEligible(file.entry, gate), { cacheKey: `lib:${sources[0].libraryId}:${gateCacheSuffix(gate)}`, topK: candidateK }), recallRoute: 'local' }
2889
2901
  : await managedRecall({ exec, index: sources[0].index, sourceEmpty: Object.keys(sources[0].index.entries || {}).length === 0,
2890
- query: searchQuery, topK: candidateK, libraryId: sources[0].libraryId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2902
+ query: searchQuery, topK: candidateK, libraryId: sources[0].libraryId, ...gate, intent: managedVectorIntent(), retrieveImpl, byId, domain }))
2891
2903
  : await recallCrossLibrary({ exec, sources, query: searchQuery, topK: candidateK, route, byId, automatic: purpose === 'automatic', intent: managedVectorIntent(), retrieveImpl, domain,
2892
2904
  disclosureAsked: recallIntent === 'boundary', speakerFilter: detectSpeakerQuery(query) })
2893
2905
  const retrievalMs = performance.now() - retrievalStarted
package/lib/private.js CHANGED
@@ -567,34 +567,48 @@ export function mergeMustCover(carry, fresh, { max = 8, carryMax = 4 } = {}) {
567
567
  return rows.slice(0, Math.max(1, Number(max) || 8))
568
568
  }
569
569
 
570
- const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*[月日号]/
571
- // 这些 bigram 到处出现,不能证明候选被写进库;命中两个以上才算覆盖。
570
+ const COVER_DATE_RE = /\d{4}-\d{2}-\d{2}|\d{1,2}\s*月\s*\d{1,2}\s*[日号]?|\d{1,2}\s*[月日号]/g
572
571
  const COVER_STOP = new Set([
573
572
  '我们', '他们', '你们', '现在', '已经', '可以', '什么', '这个', '那个',
574
573
  '时候', '今天', '明天', '昨天', '一下', '一个', '还是', '不是', '就是',
575
574
  ])
575
+ const COVER_TOKEN_RECALL = 0.55
576
+ function coverText(text) {
577
+ return String(text || '').normalize('NFKC').toLowerCase().replace(COVER_DATE_RE, ' ')
578
+ }
576
579
  function coverTokens(text) {
577
- return new Set(tokenize(String(text || ''))
578
- .filter((token) => typeof token === 'string' && token.length >= 2 && !COVER_STOP.has(token)))
580
+ return new Set(tokenize(text)
581
+ .filter((token) => typeof token === 'string' && token.length >= 2 && !/\d/.test(token) && !COVER_STOP.has(token)))
582
+ }
583
+ function coverAtoms(text) {
584
+ return new Set(text.match(/[\p{Script=Han}]|[a-z]+/gu) || [])
579
585
  }
580
- /** 本地零 Token 核验:候选里的关键事实是否真的出现在本窗新增/更新的条目里。 */
586
+ /** Conservative local evidence check; uncertainty keeps the candidate in carry. */
581
587
  export function candidateCovered(candidate, writtenIds, index) {
582
588
  const entries = index?.entries || {}
583
589
  const text = String(candidate?.text || '')
584
590
  if (!text) return true
585
- const date = (text.match(COVER_DATE_RE) || [])[0] || null
586
- const wanted = coverTokens(text)
587
- if (wanted.size === 0 && !date) return true
591
+ const normalized = coverText(text)
592
+ const wanted = coverTokens(normalized)
593
+ const atoms = coverAtoms(normalized)
594
+ const values = numericSet(text)
595
+ // A date or an uninformative fragment cannot prove a fact was written.
596
+ if (wanted.size < 2 || atoms.size === 0) return false
588
597
  for (const id of Array.isArray(writtenIds) ? writtenIds : []) {
589
598
  const entry = entries[id]
590
599
  if (!entry) continue
591
600
  const body = String(entry.title || '') + ' ' + String(entry.content || '')
592
- if (date && body.includes(date)) return true
593
- const have = coverTokens(body)
594
- let shared = 0
595
- for (const token of wanted) {
596
- if (have.has(token) && (shared += 1) >= 2) return true
597
- }
601
+ const haveValues = numericSet(body)
602
+ if ([...values].some((value) => !haveValues.has(value))) continue
603
+ const normalizedBody = coverText(body)
604
+ const haveAtoms = coverAtoms(normalizedBody)
605
+ // Missing names, actions or objects are not covered by a matching topic/date.
606
+ if ([...atoms].some((atom) => !haveAtoms.has(atom))) continue
607
+ const have = coverTokens(normalizedBody)
608
+ const shared = [...wanted].filter((token) => have.has(token))
609
+ if (shared.length < Math.min(3, wanted.size) || shared.length / wanted.size < COVER_TOKEN_RECALL) continue
610
+ if (shared.some((token) => polarityAt(text, token) !== polarityAt(body, token))) continue
611
+ return true
598
612
  }
599
613
  return false
600
614
  }
@@ -1037,7 +1051,7 @@ import {
1037
1051
  recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
1038
1052
  resolveConsolidationCwd, measurePacket, packetBudgetFit, createConsolidationMeasurement,
1039
1053
  } from './worker-pool.js'
1040
- import { tokenize, buildCorpus, bm25 } from './text-retrieval.js'
1054
+ import { tokenize, buildCorpus, bm25, numericSet, polarityAt } from './text-retrieval.js'
1041
1055
  import { isGoneSessionError } from './cycle.js'
1042
1056
  import { autoLinkPrivateMemories } from './private-links.js'
1043
1057
  import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
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.10",
4
+ "version": "1.3.11",
5
5
  "description": "面向长篇 RP 与陪伴对话的 DeepSeek Harness 记忆插件:三层记忆、逐轮召回、来源标注、关系图、图片附件与独立 WebUI。",
6
6
  "keywords": [
7
7
  "deepseek-harness",
@@ -282,6 +282,8 @@ function top3Of(ids) {
282
282
  * Definitions and empty-set rules:
283
283
  * - Recall@3 denominator = answerable samples only. A sample counts as a hit if
284
284
  * at least one expected id is in the first three positions.
285
+ * - allExpectedAt3 denominator = answerable samples only; all expected ids must
286
+ * appear in top-3 (sets larger than three cannot score a complete hit).
285
287
  * - MRR@3 denominator = answerable samples only. The reciprocal rank is 0 when no
286
288
  * expected id appears in the first three positions.
287
289
  * - No-answer false-recall denominator = no-answer samples only. It is the fraction
@@ -294,6 +296,7 @@ function top3Of(ids) {
294
296
  export function computeMetrics(records) {
295
297
  let answerable = 0
296
298
  let hits = 0
299
+ let completeHits = 0
297
300
  let reciprocalRankSum = 0
298
301
  let noAnswer = 0
299
302
  let noAnswerFalseRecall = 0
@@ -306,6 +309,8 @@ export function computeMetrics(records) {
306
309
  if (top3.length > 0) noAnswerFalseRecall += 1
307
310
  } else {
308
311
  answerable += 1
312
+ const expected = [...new Set(record.expectedIds || [])]
313
+ if (expected.length > 0 && expected.every(id => top3.includes(id))) completeHits += 1
309
314
  let rank = 0
310
315
  for (let index = 0; index < top3.length; index += 1) {
311
316
  if (record.expectedIds?.includes(top3[index])) {
@@ -325,6 +330,7 @@ export function computeMetrics(records) {
325
330
  }
326
331
  return {
327
332
  recallAt3: answerable === 0 ? 0 : round(hits / answerable),
333
+ allExpectedAt3: answerable === 0 ? 0 : round(completeHits / answerable),
328
334
  mrrAt3: answerable === 0 ? 0 : round(reciprocalRankSum / answerable),
329
335
  noAnswerFalseRecallRate: noAnswer === 0 ? 0 : round(noAnswerFalseRecall / noAnswer),
330
336
  isolationViolations: violations.length,
@@ -335,6 +341,7 @@ export function computeMetrics(records) {
335
341
  },
336
342
  emptySet: {
337
343
  recallAt3: answerable === 0,
344
+ allExpectedAt3: answerable === 0,
338
345
  mrrAt3: answerable === 0,
339
346
  noAnswerFalseRecallRate: noAnswer === 0,
340
347
  isolationViolations: forbiddenChecked === 0,
@@ -40,6 +40,8 @@ export const commit = async ({ payload, db }) => {
40
40
  for (const row of payload.recall_files) rows.set(db + '|' + row.name, row)
41
41
  return { ok: true }
42
42
  }
43
+ export const closeMemuResident = () => 0
44
+ export const prewarmMemuResident = async () => false
43
45
  export const retrieve = async () => ({ files: [] })
44
46
  export const forget = async ({ db, name }) => {
45
47
  calls.forget.push({ db, name })
@@ -564,6 +564,20 @@ test('a candidate is covered only when a written entry carries the fact', () =>
564
564
  assert.equal(candidateCovered({ text: '父亲不吃芹菜' }, [], index), false, 'no writes means no coverage')
565
565
  })
566
566
 
567
+ test('coverage does not discard facts for matching dates, polarity, values, or generic overlap', () => {
568
+ const covered = (text, content, title = '') => candidateCovered({ text }, ['mem-written'], { entries: { 'mem-written': { title, content } } })
569
+ assert.equal(covered('11月20日阿兰取伞', '11月20日小林去医院'), false, 'same date is not the same event')
570
+ assert.equal(covered('父亲不吃芹菜', '父亲爱吃芹菜'), false, 'opposite polarity is not coverage')
571
+ assert.equal(covered('父亲周末去图书馆还书', '父亲周末去图书馆借书'), false, 'shared topic must retain the action')
572
+ assert.equal(covered('父亲生日是11月20日', '父亲生日是11月21日'), false, 'different date is not coverage')
573
+ assert.equal(covered('项目预算是1200元', '项目预算是1500元'), false, 'different value is not coverage')
574
+ assert.equal(covered('11月20日', '11月20日小林去医院'), false, 'date alone is insufficient evidence')
575
+ assert.equal(covered('父亲不吃芹菜', '父亲不吃芹菜,母亲喜欢白菜'), true)
576
+ assert.equal(covered('父亲喜欢芹菜', '父亲喜欢芹菜,母亲不吃白菜'), true, 'unrelated negation does not alter the fact')
577
+ assert.equal(covered('11月20日阿兰取伞', '11月20日阿兰取伞,记得提前联系'), true)
578
+ assert.equal(covered('项目预算是1200元', '项目预算是1200元'), true)
579
+ })
580
+
567
581
  test('the same failed snapshot stops automatic re-forking after the failure cap', async () => {
568
582
  state.ensureSession('fork-failcap', { cwd: path.join(home, 'proj-failcap'), agentPreset: 'coding' })
569
583
  const ctx = host({ live: true, turnReason: { kind: 'error', error: { message: 'provider refused max-tokens argument' } } })
@@ -111,6 +111,17 @@ test('sample validation fails closed on a false answerable marker and on an out-
111
111
  assert.throws(() => bench.validateSampleShape({ ...base, draft: false, expectedIds: ['mem-rb-invalid'] }, 'bad'), /draft must be true/)
112
112
  })
113
113
 
114
+ test('complete expected-set metric distinguishes a partial conflict recall from full coverage', () => {
115
+ const records = [
116
+ { noAnswer: false, expectedIds: ['old', 'new'], top3: ['new'] },
117
+ { noAnswer: false, expectedIds: ['old', 'new'], top3: ['new', 'old'] },
118
+ ]
119
+ const metrics = bench.computeMetrics(records)
120
+ assert.equal(metrics.recallAt3, 1)
121
+ assert.equal(metrics.allExpectedAt3, 0.5)
122
+ assert.equal(bench.computeMetrics([{ noAnswer: true, top3: [] }]).emptySet.allExpectedAt3, true)
123
+ })
124
+
114
125
  test('metric math uses explicit denominators and scores empty top-3 as a no-answer success', () => {
115
126
  const metrics = bench.computeMetrics([
116
127
  { id: 'a', noAnswer: false, expectedIds: ['e1'], forbiddenIds: ['f'], top3: ['x', 'e1'] },
@@ -0,0 +1,51 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import fs from 'node:fs'
4
+ import os from 'node:os'
5
+ import path from 'node:path'
6
+
7
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'memu-corpus-gate-'))
8
+ process.env.DSH_MEMU_HOME = home
9
+ process.env.DSH_MEMU_MEMORY_HOME = home
10
+ const state = await import('../lib/state.js')
11
+ const { privateRecall } = await import('../lib/memory.js')
12
+ test.after(() => { state.flushState(); fs.rmSync(home, { recursive: true, force: true }) })
13
+
14
+ for (const backend of ['agent', 'api', 'api-fallback']) {
15
+ for (const [kind, hidden] of Object.entries({
16
+ secret: { visibility: 'secret' },
17
+ context: { context: { characterId: 'someone-else' } },
18
+ never: { disclosure: 'never_say' },
19
+ asked: { disclosure: 'only_if_asked' },
20
+ })) {
21
+ test('single-library ' + backend + ' excludes ' + kind + ' from BM25 statistics', async () => {
22
+ const sessionId = backend + '-' + kind
23
+ const cwd = path.join(home, sessionId)
24
+ state.ensureSession(sessionId, { cwd })
25
+ const libraryId = state.getSessionBinding(sessionId).libraryId
26
+ state.updateSettings({ memoryBackend: backend === 'agent' ? 'agent' : 'api', vectorSource: 'api', crossLibraryRecall: false })
27
+ const entries = {}
28
+ const entry = (title, extra = {}) => ({ title, content: title, layer: 'long_term', status: 'active', createdAt: new Date().toISOString(), ...extra })
29
+ entries['mem-target'] = entry('zxquartz')
30
+ for (let i = 0; i < 7; i++) entries['mem-filler-' + i] = entry('unrelated' + i)
31
+ state.savePrivateIndex(libraryId, { entries })
32
+ const exec = { agent: { session: { header: { id: sessionId } } } }
33
+ // Empty semantic results exercise the production mixed recall lexical leg.
34
+ const recall = (query = 'zxquartz', purpose = 'automatic') => privateRecall({ exec, query, purpose, topK: 5, relevanceThreshold: 0, retrieveImpl: async () => { if (backend === 'api-fallback') throw new Error('simulated vector outage'); return { files: [] } } })
35
+ const before = await recall()
36
+ assert.equal(before.recallRoute, backend === 'api-fallback' ? 'local-fallback' : backend === 'api' ? 'managed-vector-rrf' : 'local')
37
+ assert.deepEqual(before.files.map(f => f.name), ['mem-target'])
38
+ for (let i = 0; i < 12; i++) entries['mem-hidden-' + i] = entry('zxquartz', hidden)
39
+ state.savePrivateIndex(libraryId, { entries })
40
+ const after = await recall()
41
+ assert.equal(after.recallRoute, backend === 'api-fallback' ? 'local-fallback' : backend === 'api' ? 'managed-vector-rrf' : 'local')
42
+ assert.deepEqual(after.files.map(f => f.name), ['mem-target'], 'ineligible documents must not prune the visible query term')
43
+ if (backend === 'agent') assert.equal(after.files[0].lexical, before.files[0].lexical, 'visible corpus statistics stay unchanged')
44
+ // Explicit exact-id reads retain their existing permission contract.
45
+ if (kind !== 'context') {
46
+ const exact = await recall('mem-hidden-0', 'explicit')
47
+ assert.deepEqual(exact.files.map(f => f.name), ['mem-hidden-0'])
48
+ }
49
+ })
50
+ }
51
+ }