dsh-memu-memory 1.3.1 → 1.3.2

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 (46) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +3 -3
  3. package/README.zh.md +3 -1
  4. package/docs/contributing.md +2 -2
  5. package/docs/env-and-commands.md +12 -1
  6. package/docs/memory-semantics.md +8 -2
  7. package/docs/troubleshooting.md +9 -6
  8. package/lib/auto-link/apply.js +249 -0
  9. package/lib/auto-link/candidates.js +155 -0
  10. package/lib/auto-link/decide.js +304 -0
  11. package/lib/auto-link/normalize.js +99 -0
  12. package/lib/auto-link/policy.js +42 -0
  13. package/lib/auto-link/suppression.js +101 -0
  14. package/lib/auto-link/terminology.js +265 -0
  15. package/lib/binding-diagnostics.js +2 -2
  16. package/lib/client.js +1412 -69
  17. package/lib/graph.js +269 -18
  18. package/lib/memory.js +11 -0
  19. package/lib/memu.js +7 -6
  20. package/lib/private-links.js +105 -137
  21. package/lib/private.js +138 -38
  22. package/lib/rpc.js +67 -7
  23. package/lib/state.js +7 -2
  24. package/lib/tools.js +4 -2
  25. package/lib/webui/graph-LICENSE.txt +1 -62
  26. package/lib/webui/graph-view.bundle.js +1 -1
  27. package/lib/webui/graph-view.js +891 -124
  28. package/lib/webui/standalone.js +3 -3
  29. package/package.json +1 -2
  30. package/scripts/build-graph.mjs +3 -3
  31. package/scripts/check-graph-browser.mjs +106 -23
  32. package/scripts/rebuild-auto-links.mjs +252 -0
  33. package/tests/audit-regression.test.mjs +11 -8
  34. package/tests/auto-link-candidates.test.mjs +161 -0
  35. package/tests/auto-link-decide.test.mjs +512 -0
  36. package/tests/auto-link-migration.test.mjs +133 -0
  37. package/tests/client-render.test.mjs +7 -6
  38. package/tests/consolidation-fork.test.mjs +148 -0
  39. package/tests/cycle.test.mjs +1 -1
  40. package/tests/graph-view.test.mjs +163 -21
  41. package/tests/graph.test.mjs +5 -0
  42. package/tests/help-page.test.mjs +3 -3
  43. package/tests/memu-resident-route.test.mjs +130 -0
  44. package/tests/private-links.test.mjs +81 -45
  45. package/tests/stubs/child-process-spy.mjs +14 -0
  46. package/tests/tools.test.mjs +24 -18
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # 更新日志 / Changelog
2
2
 
3
+ ## [1.3.2] - 2026-11-10
4
+
5
+ > 独立「关系图谱」页与确定性自动关联:记忆墙里的内嵌节点图升级为侧边栏独立页面(自研力导向引擎,移除 d3 运行时依赖);自动关联改为断言驱动(已确认实体提及 / 字段证据),默认只出候选,旧库可用脚本迁移。
6
+
7
+ ### 关系图谱(WebUI)
8
+
9
+ - 新增独立「关系图谱」导航页(在「MemU 记忆」之后);「MemU 记忆」页不再内嵌节点图,只保留记忆墙。
10
+ - 引擎换为自研力导向(空间网格近程斥力 + 连线弹簧 + 可选向心力),**移除 d3-force 运行时依赖**;持续轻微呼吸,空闲降频,管理视图/页面隐藏自动暂停。
11
+ - 拖动节点即固定(fx/fy),邻居被弹簧链牵动,松手不回弹;拖动期间只模拟所连簇,其他簇冻结但作为障碍排斥,避免重合;Shift 拖整簇、右键解固定、双击聚焦。
12
+ - 力参数滑杆(斥力 / 连线距离 / 向心力),规则筛选(提及 / 冲突 / 取代 / 同键 / 引文),标签随缩放渐隐,全高画布与缩略图;配色跟随 DSH token。
13
+ - 管理视图支持新增/删除节点:可新增记忆或实体(「全部记忆库」模式下可选目标库);删除为两段确认,实体被引用时再确认一次即连同关联边删除。
14
+ - 管理视图支持编辑已有节点:记忆可改标题/内容/层级(层级只开放后端允许的路径——短期升长期、永久可降级,提升为永久仍须走带 pin 理由的写入口),实体可改名称与别名(保存时带回当前别名,避免被整体替换清空);保存走 `updateMemory` / `renameEntity`,写完立即重取图。
15
+ - 旧版自动边(无 `evidence.rule`)在规则筛选里归入「旧版自动」桶,老数据不再显示「没有规则」;过滤与边标签统一走可读规则名。
16
+
17
+ ### 自动关联
18
+
19
+ - `autoLinkMode` 默认 `suggest`:本地零 Token 出候选、不写边,候选在关系图谱页审核;`deterministic` 只写断言型边。
20
+ - 确定性边只来自:已确认实体的 `entity-mention`,以及 `conflicts_with` / `supersedes` / 同 `fact_key` 的字段证据;词面相似、共享 token、向量永远不建边。
21
+ - 实体确认/改名/合并/删除即时维护提及边;删除的自动边写入抑制表防复活。
22
+ - 新增 `memu_private_link_suggest` 工具与按本轮 id 的增量刷新;新增 `node scripts/rebuild-auto-links.mjs`(默认 dry-run,`--apply` 先备份再清理重建旧统计边)。
23
+
24
+ ### 其它
25
+
26
+ - 常驻 Python worker 统一用于所有路由:API 模式不再每条命令冷启动解释器。
27
+ - `getGraph` 为旧自动边补稳定的 `rule:'auto'` 显示桶;节点图规则筛选按显示层 rule 过滤。
28
+ - 依赖:移除 `d3-force`,graph bundle 无第三方运行时依赖(许可证文件同步)。
29
+
3
30
  ## [1.3.1] - 2026-11-08
4
31
 
5
32
  > 整理成本与注入瘦身:worker 只留写工具、回执本地合成、批量写、最小整理回合顺延;注入侧修 guide 预算与锚点重投;工具返回值脱敏与分页。
package/README.md CHANGED
@@ -63,7 +63,7 @@ All screenshots are the real WebUI on isolated example data, not anyone's memori
63
63
  - **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.
64
64
  - **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.
65
65
  - **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.
66
- - **Private links are algorithm-first.** After consolidation, a zero-token pass connects memories that share a rare name or alias in the same context/track and creates/reuses an entity hub (for example `yuike`). Uncertain pairs are handed to the consolidation worker for an evidence-based decision. Links are metadata (`source: 'auto'`), shown with an “Auto” badge in the graph and removable; they never rewrite a body, write a vector or delete anything.
66
+ - **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).
67
67
  - **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.
68
68
  - **Memory fades unevenly.** Recency, access count, peak and end effects, primacy, habituation and flashbulb accuracy feed one strength score. Mood is described by four components (joy / anger / sorrow / fear, summing to 1) plus arousal (intensity) and dominance (sense of control); a compound mood such as jealousy is a named mix of the four, not a new axis. Mood only reorders recall: it never enters the injected text and never rewrites a memory body. Gating is the OR of three independent conditions — the dominant share is >= 0.35, |arousal - 0.35| >= 0.1, or |dominance| >= 0.25; when none holds, both multipliers are exactly 1. Older entries carry no emotion and keep the old valence path; the four axes are never inferred back from valence. A vivid memory can be more confident than it is accurate, and the UI says so.
69
69
  - **Provenance is a fact, not a style.** Every entry carries `source` / `source_kind` (`user_said` / `assistant_said` / `told` / `imagined` / `inferred` / `tool`), `speaker_id`, `confidence`, `accuracy`, and disclosure rules. A vague recollection cannot impersonate a quote, and the assistant's own promises or plans cannot be filed as something the user said.
@@ -239,8 +239,8 @@ Folder policy is a **ceiling, not an initial value**: turning a folder switch of
239
239
  | `memu_private_update` | Edit, without bypassing pin admission, review or visibility rules |
240
240
  | `memu_private_archive` | Archive; never delete |
241
241
  | `memu_private_unpin` | Marginalize a permanent memory with a first-person reason, quota and cooldown |
242
- | `memu_private_link` | Link memories/entities with evidence, or update a relationship snapshot; also adjudicates `memu_private_link_suggest` candidates; cannot delete edges |
243
- | `memu_private_link_suggest` | Run the local high-confidence linking/entity-hub pass for ids written this consolidation and return only uncertain candidate pairs |
242
+ | `memu_private_link` | Link memories/entities with evidence, or update a relationship snapshot; also adjudicates uncertain `memu_private_link_suggest` candidates; cannot delete edges |
243
+ | `memu_private_link_suggest` | Refresh deterministic edges (confirmed-entity mentions and field evidence) for ids written this consolidation and return only uncertain candidate pairs |
244
244
  | `memu_lexicon_search` | Search active lexicon terms this conversation can see: bound library + global lexicon (+ same-domain libraries when cross-library recall is on); archived and tombstoned terms stay hidden |
245
245
  | `memu_lexicon_propose` | Add or update a lexicon term in the bound library (never the global lexicon); ordinary entries become active immediately, sensitive triggers remain user-only |
246
246
  | `memu_global_recall` / `memu_global_list` | Read the global layer by domain |
package/README.zh.md CHANGED
@@ -68,6 +68,7 @@
68
68
  - **矛盾不会被悄悄合并。** 普通矛盾仍进入 `pending_review`:不注入、不召回,只出现在复核队列,等人或整理作业裁决。写入方明确把两种说法标成同一事实的版本(`conflicts_with`)时,两条都保持 active、一起召回并注入一张冲突卡;显式 `supersedes` 才退休旧条,正文不删。
69
69
  - **秘密不进自动召回。** `secret`、群聊频道、角色、世界线、剧情分支与 `knownBy` 共同约束读写;`secret` 永远不会被自动注入,但同文件夹里**主动检索仍然读得到**——它挡的是「自己冒出来」,不是保险箱。真正把同一文件夹里的两段对话隔开的是 `context` 作用域(`channelId` / `characterId` / `worldId` / `branchId`);两边都没填就是同一个作用域,这正是「文件夹」的含义。旧的 `visibility: 'session'` 级别已删除:读到就按 `shared` 处理、`context` 原样保留,仍存着该级别的库用 `node scripts/migrate-visibility.mjs` 重写(`--apply` 才写,先备份)。
70
70
  - **人与故事是有结构的。** 群聊用稳定的 `speakerId` / `channelId`,不拿显示名当身份;RP 用 `characterId` / `worldId` / `branchId` 隔离知识。关系边有理由和置信度,实体改名不动记忆正文,关系当前状态(熟悉、信任、温度、边界、承诺)是带证据和历史快照。
71
+ - **关联只来自已确认的实体与字段证据。** 设置里的「自动关联」默认只出候选、不写边;你确认过的实体名/别名才会把已有记忆的提及连起来(`entity-mention`),冲突/取代/同 `fact_key` 的相邻版本则建立字段证据边。词面相似、共享 token 与向量永远不建边;候选队列在节点图页审核。旧库的统计噪声边用 `node scripts/rebuild-auto-links.mjs` 先 dry-run、确认后 `--apply`(自动备份)清理;删掉的自动边会写进抑制表,不会复活。
71
72
  - **图片是指针加描述,不是假装能看图。** 附件按 SHA-256 去重、有配额、分三级留存;没有描述时只记「收到一张图片」,绝不编造画面。
72
73
  - **整理在后台。** 整理跑在种子 fork 子会话里,不会在你的待发区多出一轮;失败退避重试,不伪记成功。
73
74
 
@@ -237,7 +238,8 @@ npx --package dsh-memu-memory dsh-memu-memory-setup
237
238
  | `memu_private_update` | 编辑,但不能绕过永久准入、复核或可见性规则 |
238
239
  | `memu_private_archive` | 归档,不删除 |
239
240
  | `memu_private_unpin` | 用第一人称理由、配额和冷却边缘化一条永久记忆 |
240
- | `memu_private_link` | 用证据连接记忆/实体,或更新关系快照;不能删边 |
241
+ | `memu_private_link` | 用证据连接记忆/实体,或更新关系快照;可裁决 `memu_private_link_suggest` 的不确定候选;不能删边 |
242
+ | `memu_private_link_suggest` | 为本轮整理写入的 id 刷新确定性边(已确认实体提及 / 字段证据),只返回不确定候选 |
241
243
  | `memu_global_recall` / `memu_global_list` | 按 domain 读取全局记忆 |
242
244
  | `memu_status` | 存储健康、同步心跳、召回状态与图片回合状态 |
243
245
 
@@ -75,9 +75,9 @@ npm run check # node --check + i18n 键对齐 + package.j
75
75
 
76
76
  ### 5.3 新增一个 RPC 方法
77
77
 
78
- <!-- rpc-method-count: 97 -->
78
+ <!-- rpc-method-count: 101 -->
79
79
 
80
- 1. `lib/rpc.js` 的 `switch` 加 case(共 95 个方法,按功能分组,别乱插)。
80
+ 1. `lib/rpc.js` 的 `switch` 加 case(共 101 个方法,按功能分组,别乱插)。
81
81
  2. 返回**形状稳定**:客户端 `call()` 直接解构,列表类给 `{items, total}` 而不是裸数组。
82
82
  3. `revisionOnly` 分支只回 `{revision, stamp}`、**不要求 sessionId**(三端轮询,设置页与独立页没会话)、**不塞业务数据**(每 2.5 秒一次);顺带 `noteMemoryBeat()`,`memu_status` 靠它分「没写」与「没人轮询」。
83
83
  4. 写成功后 `bumpMemoryRevision()`/`notifyMemoryWrite()`(§7);能让 `state.json` 或索引落盘的写,`state.js` 自动记写事件供 `memu_status` 展示。
@@ -30,6 +30,17 @@ npm run replay
30
30
 
31
31
  `scripts/replay.mjs`:不走测试框架,按生产代码路径端到端重放七条链路(事实级去重工具层、PTC 整理成功/失败、整理提醒与日志页数据、侧边栏提醒块真实渲染、向量计数账本+戳、MemU 记忆页分组/多选/查看跳转)。只有 MemU 引擎子进程换成内存桩,其余全是真实模块;退出码 0 = 全部检查点通过。改动整理/去重/向量计数/提醒任一链路后跑一次,比单测更接近「用户点下去会发生什么」。
32
32
 
33
+ ### 9.1.2 自动关联迁移(v3)
34
+
35
+ ```bash
36
+ node scripts/rebuild-auto-links.mjs # 默认 dry-run:只读索引/实体,打印旧 auto 边、实体分级计划与“确认前 N 个队列实体”的提及边预估
37
+ node scripts/rebuild-auto-links.mjs --apply # 先整库备份,再删全部 source:'auto' 旧边、落实体状态、为已确认实体重建确定性边
38
+ node scripts/rebuild-auto-links.mjs --library lib_x --json
39
+ node scripts/rebuild-auto-links.mjs --include-archived # 连归档库一起处理(默认只跑未归档库)
40
+ ```
41
+
42
+ 迁移后把设置里的 `autoLinkMode` 从 `suggest` 切到 `deterministic`;候选确认在节点图页「待确认实体」。脚本只删 `source:'auto'` 边,非 auto(手动/worker)边、正文、向量、附件与 `link-suppression.json` 一律不动;apply 在同一轮里为**已确认**实体重建确定性边(设计 §14 原文要求 S3 不建边,实现把 S3+S4 的“已确认”部分合并,未确认的名字仍等人工),apply 后重跑 dry-run 应显示 legacy 0。回滚 = 恢复 `backups/` 里最近一次备份(脚本没有独立 rollback 子命令)。单个库的实体文件损坏只记进 `failures` 并继续跑其余库,`--json` 的 `ok` 为 false、进程退出码非 0。建议在 DSH 关闭时运行(S0 的“冻结整理”没有单独开关,脚本只负责备份)。
43
+
33
44
  ### 9.2 本地 link 到 DSH profile
34
45
 
35
46
  `~/.dsh/profiles/<profile>/package.json` 里 `"dsh-memu-memory": "link:D:/Code/dsh-plugin/dsh-memu-memory"` 并加入 `dsh.profile.bundles`。是符号链接 → 改源码即刻生效(无 bundle 缓存)。`lstat` 验证是否 symlink(§3.10)。
@@ -51,7 +62,7 @@ npm run replay
51
62
  - `memu-cli` 是 **PyPI 上的 Python 包,不是 npm 包**;锁定 `0.11.0b3`。
52
63
  - 发布版 `memu --help` 只有 `retrieve, search, list-files, commit`;源码里的 `memorize prepare/commit` **尚未发布**,**不要依赖 `memorize`**——当可选能力(启动探测 `memu memorize --help`,成功才注册入口,失败隐藏不报错)。
53
64
  - 必需命令 `retrieve` / `list-files` / `commit`;必需 flag `--json` / `--db` / `--provider` / `--embed-model` / `--api-key` / `--base-url`。**所有 CLI 字符串只在 `lib/memu.js`**。
54
- - 本地向量模式下插件**常驻一个解释器**(`lib/memu.js` 的 resident engine):启动时 `import memu.cli` 一次,随后 `retrieve` / `list-files` / `commit` 通过 JSON 行协议调用同一个 `main(argv)`,省掉每条命令约 2 s 的导入链;每条命令结束显式 `database.close()`,空闲期不占 sqlite 句柄。远端 API 路由仍按命令新起进程;插件卸载或引擎安装/切换前关闭常驻进程,异常退出时下一条命令冷启动(见 `docs/troubleshooting.md` §3.26)。
65
+ - 本地向量模式下插件**常驻一个解释器**(`lib/memu.js` 的 resident engine):启动时 `import memu.cli` 一次,随后 `retrieve` / `list-files` / `commit` 通过 JSON 行协议调用同一个 `main(argv)`,省掉每条命令约 2 s 的导入链;每条命令结束显式 `database.close()`,空闲期不占 sqlite 句柄。远端 API 路由复用同一个常驻进程(每条命令单独传 base URL/key/model/db 的 env);插件卸载或引擎安装/切换前关闭常驻进程,异常退出时下一条命令冷启动(见 `docs/troubleshooting.md` §3.26)。
55
66
 
56
67
  ```bash
57
68
  python -m memu retrieve "query" --json --db <db>
@@ -60,7 +60,7 @@
60
60
  - **职责分工**:`system-guide.*` 是唯一常驻规则,只写领域行为、检索时机、回答口径;`private-policy.*` 保留为字段规约参考,不再投放,避免两套常驻文本互相漂移。
61
61
  - **只有三个 key 分域**:`system-guide`、`private-policy`、`private-consolidation`;`global-curator` 不分域。
62
62
  - **远程与本地共用一份 `private-consolidation`**:正文讲「记什么、字段怎么填」,差异只有输出协议(`CONSOLIDATION_CONTRACTS.local` 调工具 / `.remote` 返回 JSON,代码追加)。不要拆第二份。
63
- - **1.2.2 起整理稿负责标题质量**:title 按「只看标题就知道具体事实」写(8–40 字、具体关键词、集合稿覆盖全部来源),`global-curator` 同一口径。词典/关联的工具调用属于**本地工作流**:领域整理稿与远程 JSON 路径共用,因此不写 `memu_*` 工具名;领域稿只保留「可抽什么词」的差异,稳定复用的黑话/梗/术语先 `memu_lexicon_search` 再 `memu_lexicon_propose`、写完用 `memu_private_link_suggest` 裁决候选的工具流程只出现在 local worker brief。远程契约明确「没有工具」,title 长度同样是 8–40 字。
63
+ - **1.2.2 起整理稿负责标题质量**:title 按「只看标题就知道具体事实」写(8–40 字、具体关键词、集合稿覆盖全部来源),`global-curator` 同一口径。词典/关联的工具调用属于**本地工作流**:领域整理稿与远程 JSON 路径共用,因此不写 `memu_*` 工具名;领域稿只保留「可抽什么词」的差异,稳定复用的黑话/梗/术语先 `memu_lexicon_search` 再 `memu_lexicon_propose`、写完调用 `memu_private_link_suggest` 刷新确定性边(已确认实体提及 / 字段证据)并取得不确定候选、需要时用 `memu_private_link` 显式裁决的工具流程只出现在 local worker brief。远程契约明确「没有工具」,title 长度同样是 8–40 字。
64
64
  - RP 与 coding 是**内容**差异:coding 记事实(决定、约束、踩过的坑、工程偏好),召回当「可能过期的事实」,与代码冲突时以代码为准;rp 记经验(具体瞬间、半句原话、身体感觉、没说出口的话),允许模糊记错,不确定就标低 `confidence`。rp/mixed 同时收对方主动给出的**现实生活事实**(作息、行程、口味、健康、家人朋友、在忙的事):`about_user` 平实短条(30–80 字),不需要「瞬间+影响」模板,剧情与现实条分开写、不互相合并;单次提及低 confidence 或 `short_term`,重复出现才升 `long_term`(`寒暄不留`的口径只拦寒暄本身,不拦寒暄里夹带的事实)。
65
65
  - **KV cache**:section 文本随 domain 变,但同一会话内恒定,缓存不受影响;中途改 domain 会让该会话失效一次缓存。别在文档里写「文本恒定」。
66
66
 
@@ -159,7 +159,13 @@
159
159
 
160
160
  **词典生命周期。** 公开状态只有 `active` / `archived`:用户新建、模型 `memu_lexicon_propose`、curator 带证据抽取都直接 active;`archiveLexiconTerm` / `restoreLexiconTerm` 负责可逆退场,删除只属于管理面。`rejected` 只作为 legacy 墓碑/指纹留在数据里,UI、注入、检索与计数都看不到;`pending` 只作为旧版本迁移输入:新提案 → active(敏感 → archived),revision 草稿 → archived。敏感 trigger 的新建/修改只能由用户完成,模型/curator 得到 typed 拒绝;非用户修改普通 active 词条的敏感字段也直接拒绝,不再生成 pending revision。RPC 的 `lexiconReview` 已删除(方法数见 `docs/contributing.md` 的 rpc-method-count 标记)。**哪些词条进得来**是另一层:全局词典 + 同域跨库,见 §8.16。
161
161
 
162
- **私有自动关联。** 整理结算后 `lib/private-links.js` 只做本地算法:同库、同 context/track、可见非 secret、标题共享稀有 name-like token、pairScore < 0.82 且无冲突时,建立 memory↔memory `relation` 并写 `source:'auto'`;≥2 条记忆共享该 token 时复用/创建实体枢纽(人物信号 → `person`,无信号的拉丁名保守 → `thing`,CJK 无信号或 kind 冲突 → 不确定候选)。高置信写库在算法侧完成;1.3.1 起整理 worker 不再接收 `link_suggest`,不确定候选只留在本地算法结果里,需要时由主会话用 `memu_private_link` 裁决;不另起整理、不重读转录。算法/写入失败只记 warn,不能让已经成功的整理失败;自动关联不改正文、不写向量、不删除,边可在关系图移除。worker 写工具为 remember/remember_batch/update,读工具为空(记忆目录与本地召回由插件在种子开头注入),但「有没有写能力」仍只由 remember/update 判定。
162
+ **私有自动关联(v3 确定性版)。** 写边只有一条路径:`lib/auto-link/` 的纯函数判定。`settings.autoLinkMode` 三档:`suggest`(默认)只生成候选、**自动整理不写边**,但你显式确认实体仍会补挂(§14 S4 的迁移流程);`deterministic` 自动整理也写由证据推出的确定性边;`off` 全关——连确认/新建/改名/合并触发的提及维护也不写。判定表只有两类:① `entity-mention`——记忆标题/正文按 NFKC+大小写/标点归一化后命中一个 **confirmed** 实体的名字/别名(CJK 子串 ≥2 字,Latin 词边界,`yuike` 不命中 `yuikeee`),产出 `memory→entity` 边;② 字段证据——`conflicts_with` / `supersedes` / 同 `fact_key`+同上下文签名的相邻版本,产出 memory↔memory 的 `conflict` / `supersede` / `fact-key` 边。两类边固定 `confidence: 1.0`、`schemaVersion: 2`,带 `evidence.rule`(枚举 `entity-mention` / `conflict` / `supersede` / `fact-key` / `worker-quote`)。词面相似度、共享 token、向量与所有统计量**永不建边**;它们只参与 `anchor-candidates.json` 的候选排序。
163
+
164
+ **实体生命周期。** `provisional`(默认)不产生任何边,`confirmed` 才允许 R1,`archived` 视同不可用。手工创建(UI/RPC)直接 confirmed;worker 经 `memu_private_link` 点名只创建 provisional 实体与一条非 auto 边(`allowWorkerAssertion` 是 v3 预留开关,本版不读取)。确认/改名/合并/删除都会级联:确认立即跑一次增量提及(不等下次整理);rename 重算该实体的提及边;merge 把来源实体的 `evidence.entityId` 改指主节点并继承 confirmed;delete(force)回收 auto 边并把 `(from,to,kind,rule)` 写进 `index/<lib>.link-suppression.json`。带 `conflicts_with` / `supersedes` / 同 `fact_key` 配对的写入,以及复核接受(replace 会把旧条目改成 superseded)也会立即重算受影响条目的字段证据边,不等下一次整理。用户在关系图删除 auto 边同样写抑制键,后续重算不会复活。
165
+
166
+ **候选队列与迁移。** `anchor-candidates.json` 是派生物:CJK 2–4gram / Latin token 的 df/titleDf/边界/凝聚/PMI/LLR 只用于排序;Tier 1 是有表面证据(引号/名字引导/标识符/用户维护词典)的候选,Tier 2 仅统计特征。没有 status 的旧实体按 DESIGN §9.3 分级:只有 `origin ∈ {user,agent,worker}` 或被非 auto 边引用才保留 confirmed,其余落 provisional。`scripts/rebuild-auto-links.mjs`(默认 dry-run,`--apply` 先整库备份)删除全部 `source:'auto'` 旧边、落实体状态,并为已确认实体重建确定性边;确认与 dry-run 幂等后再把 `autoLinkMode` 切到 `deterministic`。
167
+
168
+ **召回治理与失败隔离。** `recallRelations` 的 top-2 扩展显式排除 `evidence.rule === 'entity-mention'`——提及是事实索引不是关系,`confidence=1.0` 不能挤掉手动边与字段证据;字段证据边照常参与。判定层纯函数、无 IO/时钟/随机;写库失败只 warn,绝不让已经成功的整理失败;`links[]` 仍只是元数据,不改正文、不写向量、不删记忆。worker 写工具为 remember/remember_batch/update,读工具为空(记忆目录与本地召回由插件在种子开头注入),但「有没有写能力」仍只由 remember/update 判定。
163
169
 
164
170
  ### 8.14 日期联动、到点唤醒与实体合并(1.2.3)
165
171
 
@@ -362,7 +362,7 @@ S8 展示回写 client.js 面板 + useMemoryBeat 心跳 + rpc.js allowed + tool
362
362
 
363
363
  ### 2.1 模块地图
364
364
 
365
- <!-- rpc-method-count: 97 -->
365
+ <!-- rpc-method-count: 101 -->
366
366
 
367
367
  | 文件 | 职责 / 什么时候碰它 |
368
368
  |---|---|
@@ -376,12 +376,13 @@ S8 展示回写 client.js 面板 + useMemoryBeat 心跳 + rpc.js allowed + tool
376
376
  | `lib/private.js` | 私有整理:当前对话、历史 fork、notice 消息 |
377
377
  | `lib/curator.js` / `lib/cycle.js` | 全局 curator 与 `pending_review`;空闲整理 pass(过期/降级/晋升/自动整理) |
378
378
  | `lib/mood.js` / `lib/budget.js` / `lib/snippet.js` | 情绪价与峰值;token 换算(中文≈1 字符/token、英文≈3.4,任何 token 都走它);注入片段裁剪 |
379
- | `lib/rpc.js` / `lib/client.js` / `lib/webui.js` + `lib/webui/standalone.js` | `/dsh-memu-memory` 的 95 个方法(旧路由别名同一鉴权);九页设置 + 侧边栏 `MemoryTab` + `useMemoryBeat`;独立壳挂载同一 SettingsPage,不复制实现 |
379
+ | `lib/rpc.js` / `lib/client.js` / `lib/webui.js` + `lib/webui/standalone.js` | `/dsh-memu-memory` 的 101 个方法(旧路由别名同一鉴权);九页设置 + 侧边栏 `MemoryTab` + `useMemoryBeat`;独立壳挂载同一 SettingsPage,不复制实现 |
380
380
  | `lib/graph.js` / `lib/context.js` / `lib/media.js` | 关系边与实体;说话人/频道/角色/世界线/知情边界;附件采集、缩略图、受保护路由、ZIP |
381
381
  | `lib/prompts.js` + `lib/prompts/` | 提示词加载/覆盖/恢复/domain 变体解析 |
382
382
  | `lib/engine.js` / `lib/memu.js` / `lib/memu-config.js` | Python 引擎安装探测切换回滚;MemU CLI 适配(**所有 CLI 字符串只在这里**);`~/.memu/config.env` 的 embedding |
383
383
  | `lib/stats.js` | 私有库旁路计数(`written/injected/recalled/archived`,90 天滚动);读失败只降级页面,不碰记忆 |
384
- | `lib/lexicon.js` / `lib/private-links.js` | 词典条目与 `active/archived` 生命周期、注入行渲染;整理后的本地自动关联候选与枢纽 |
384
+ | `lib/lexicon.js` / `lib/private-links.js` | 词典条目与 `active/archived` 生命周期、注入行渲染;私有自动关联的旧候选纯函数(统计不再写边) |
385
+ | `lib/auto-link/` / `scripts/rebuild-auto-links.mjs` | 确定性判定(confirmed 实体提及 / 字段证据)、suppression、候选队列与旧实体分级;迁移脚本(dry-run/apply,apply 先备份) |
385
386
  | `lib/freshness.js` / `lib/salient-wake.js` | 时间敏感信号的只读判定(喂 `<memory-freshness>` 提示);用宿主 `ctx.schedule` 排「到点唤醒」一次性任务(默认关闭) |
386
387
  | `lib/remote-summary.js` | 远程摘要 |
387
388
 
@@ -523,7 +524,9 @@ section 的 `text(context)` 能拿到 `context.agent`,所以 system prompt **
523
524
  - **词典词条没注入**:按顺序查——是否 `archived`(不注入、不检索,可恢复);是否 `secret`(不进锚点摘要,但用户点名时 B 通道可解释);context/knownBy 是否匹配;是否在 30 分钟冷却内;是否被锚点摘要 top8/敏感词单列的名额挤掉。词典没有 pending 人审状态;新词条直接 active。
524
525
  - **模型说写了词典但没生效**:`memu_lexicon_propose` 命中 archived 词条会返回 notOwned(不复活);修改敏感字段会被 typed 拒绝;sensitive trigger 只能由用户在词典页管理。检查活动日志/工具回执,不要假设 pending。
525
526
  - **旧库里的 pending 词条去哪了**:周期巡检(`runVisibilityMigrationPass` → `migrateLexiconLibraries`)把 pending 新提案转 active、敏感转 archived、pending revision 转 archived;rejected 保留为内部墓碑。迁移只写有变化的文件;损坏的词典文件不会被当空库覆盖,报 `LEXICON_CORRUPT` 并保持只读。
526
- - **私有自动关联没出现**:算法宁漏勿错。检查两条记忆是否同库、同 context/track、都可见且非 secret;标题是否共享稀有 name-like token(英文 ≥3 字母,或低频 CJK 名称;通用词被停用词表挡掉);pairScore 是否 ≥0.82(重复应走 update/合并)、是否有冲突、是否已有同向 link;每轮还有 2 条/entry、5 条/轮、2 个实体/轮的上限。边上的「自动」Tag 与 `source:'auto'` 是算法写的,可在关系图移除。
527
- - **实体枢纽名称重复(Yuike / yuike)**:算法按 NFKC/大小写/空白/标点归一化复用实体;`memu_private_link` 的 `entity` 参数也按同一规则复用同名实体。若已存在但 kind 冲突,会拒绝并提示改用既有 kind,而不是静默建第二个。
528
- - **worker 没裁决不确定候选**:`memu_private_link_suggest` 只返回候选卡,不自动连;worker 未调用或证据不足就保持不连(宁漏勿错)。`lib/private.js` 的结算兜底只重跑高置信算法,不会把不确定候选偷偷连上。自动关联失败只写 warn,不影响整理成功。
527
+ - **私有自动关联没写边**:先看设置 `autoLinkMode`——默认 `suggest` 只出候选、不写任何边(v3 迁移默认)。切到 `deterministic` 后也只写两类边:已确认实体的提及、字段证据;统计相似度永远不写。确认入口在节点图页「待确认实体」,确认后会立即补挂提及边。实体仍是 provisional、名字只有 1 个字、记忆已归档/待复核/secret、或命中 suppression 时都不会有边。
528
+ - **旧库还挂着一堆自动边**:先跑 `node scripts/rebuild-auto-links.mjs` 看 dry-run(列出 legacy auto 边与旧实体分级计划);确认后 `--apply`(自动先做整库备份)删除全部 `source:'auto'` 旧边,并为已确认实体重建确定性边;再跑一次 dry-run 应显示 legacy 0。
529
+ - **删掉的自动边又回来了**:删除动作会把 `(from,to,kind)` 写进 `index/<lib>.link-suppression.json`(精确 rule + `|*` 通配);检查该文件是否被手动清掉或从旧备份恢复。命中抑制键的边不会在下次整理/重算时重建。**想主动恢复**:节点图页「解除删除标记」(RPC `clearLinkSuppression`);deterministic 模式下会顺带全量重算一次,被删的边按现有证据重建。
530
+ - **实体确认后没有提及边**:确认只匹配已确认实体的名字/别名;检查名字是否 <2 字、记忆是否 archived/pending_review/secret、实体是否 archived(archived 不可确认)、抑制表是否有同名 (from,to,kind) 键(删过的边会写 `|*` 通配,换 rule 也不复活)、以及 `autoLinkMode` 是否为 `off`(off 连确认也不写)。worker 通过 `memu_private_link` 新建的实体默认 provisional,需要用户在审核区确认。
531
+ - **worker 没裁决不确定候选**:`memu_private_link_suggest` 现在只刷新确定性边并返回统计候选卡,不自动连;worker 未调用或证据不足就保持不连(宁漏勿错)。`lib/private.js` 的结算兜底同样只跑确定性判定,不会把统计候选偷偷连上。自动关联失败只写 warn,不影响整理成功。
529
532
  - **要不要数据库/向量重算**:自动关联只是 `links[]` 元数据,不改正文、不写向量;移除边不会触发重建。实体删除仍按既有规则(有引用时需显式 force,避免悬空)。
@@ -0,0 +1,249 @@
1
+ // Write side of the deterministic link layer. All decisions come from decide.js;
2
+ // this module only persists them (idempotently) and keeps the activity log
3
+ // honest. A failing pass must never fail the consolidation that triggered it —
4
+ // the caller catches and warns.
5
+
6
+ import { getSettings, updatePrivateIndex } from '../state.js'
7
+ import { stamp } from '../paths.js'
8
+ import { record } from '../activity-log.js'
9
+ import { isMemoryEligible } from '../memory.js'
10
+ import { AUTOLINK_SCHEMA_VERSION, EVIDENCE_RULES } from './policy.js'
11
+ import { decideAutoLinksFor, eligibleEntries, mentionEdges } from './decide.js'
12
+ import { isSuppressed } from './suppression.js'
13
+
14
+ // Rules this layer owns. worker-quote edges come from the explicit tool and must
15
+ // survive a recompute; anything else auto-generated is replaced, not appended.
16
+ export const AUTO_RULES = Object.freeze(['entity-mention', 'conflict', 'supersede', 'fact-key'])
17
+
18
+ function isEligibleEntry(entry) {
19
+ return Boolean(entry) && entry.visibility !== 'secret' && isMemoryEligible(entry, { automatic: true })
20
+ }
21
+
22
+ function noteFor(edge) {
23
+ if (edge.rule === 'entity-mention') {
24
+ const surface = edge.evidence?.surface ? `「${edge.evidence.surface}」` : ''
25
+ const field = edge.evidence?.field === 'title' ? '标题' : '正文'
26
+ return `提及已确认实体${surface}(${field})。`
27
+ }
28
+ if (edge.rule === 'conflict') return '字段证据:conflicts_with 指向这条记忆,两者是同一事实的不同版本。'
29
+ if (edge.rule === 'supersede') return '字段证据:supersedes 指向被取代的旧记忆。'
30
+ if (edge.rule === 'fact-key') return '字段证据:同一 fact_key 且上下文一致的相邻版本。'
31
+ return `确定性关联:${edge.rule}。`
32
+ }
33
+
34
+ function recordFor(edge, existing) {
35
+ return {
36
+ to: edge.to,
37
+ kind: edge.kind,
38
+ note: noteFor(edge),
39
+ confidence: 1,
40
+ createdAt: existing?.createdAt || stamp(),
41
+ source: 'auto',
42
+ schemaVersion: edge.schemaVersion || AUTOLINK_SCHEMA_VERSION,
43
+ evidence: { ...(edge.evidence || {}), rule: edge.rule },
44
+ }
45
+ }
46
+
47
+ // A repeated decision over unchanged content must not look like a write: same
48
+ // target, rule, note and evidence means the edge already says exactly this.
49
+ function sameAsRecord(existing, edge) {
50
+ if (!existing || existing.source !== 'auto') return false
51
+ const record_ = recordFor(edge, existing)
52
+ return existing.kind === record_.kind
53
+ && existing.note === record_.note
54
+ && existing.confidence === 1
55
+ && existing.schemaVersion === record_.schemaVersion
56
+ && JSON.stringify(existing.evidence || null) === JSON.stringify(record_.evidence)
57
+ }
58
+
59
+ /**
60
+ * Apply decided edges inside one index transaction. Existing manual/user edges
61
+ * with the same (to, kind) win — an automatic fact never overwrites what a
62
+ * person or the worker asserted. Returns counts plus the applied edge list.
63
+ */
64
+ export function applyAutoEdges({ libraryId, edges, entities = [], sessionId = null, operation = 'auto-link-apply' } = {}) {
65
+ const counts = { added: 0, updated: 0, skippedManual: 0, skippedCap: 0, skipped: 0, memory: 0, entity: 0 }
66
+ const applied = []
67
+ if (!libraryId || !Array.isArray(edges) || edges.length === 0) return { ...counts, applied }
68
+ const entityIds = new Set((Array.isArray(entities) ? entities : []).map(entity => entity?.id).filter(Boolean))
69
+ updatePrivateIndex(libraryId, index => {
70
+ for (const edge of edges) {
71
+ // The write layer only accepts the declared evidence vocabulary; an
72
+ // unknown rule is a caller bug, never a new edge category.
73
+ if (!EVIDENCE_RULES.includes(edge?.rule)) { counts.skipped += 1; continue }
74
+ const from = index.entries[edge?.from]
75
+ if (!from || !isEligibleEntry(from)) { counts.skipped += 1; continue }
76
+ const isMemoryTarget = Boolean(index.entries[edge.to])
77
+ if (!isMemoryTarget && !entityIds.has(edge.to)) { counts.skipped += 1; continue }
78
+ const links = Array.isArray(from.links) ? from.links : []
79
+ const at = links.findIndex(link => link && link.to === edge.to && link.kind === edge.kind)
80
+ if (at >= 0 && links[at].source !== 'auto') { counts.skippedManual += 1; continue }
81
+ if (at >= 0 && sameAsRecord(links[at], edge)) continue
82
+ if (at < 0 && links.length >= 100) { counts.skippedCap += 1; continue }
83
+ const record_ = recordFor(edge, at >= 0 ? links[at] : null)
84
+ if (at >= 0) {
85
+ links[at] = record_
86
+ counts.updated += 1
87
+ } else {
88
+ links.push(record_)
89
+ counts.added += 1
90
+ }
91
+ from.links = links
92
+ counts[isMemoryTarget ? 'memory' : 'entity'] += 1
93
+ applied.push({ from: edge.from, to: edge.to, kind: edge.kind, rule: edge.rule })
94
+ }
95
+ })
96
+ if (counts.added || counts.updated) {
97
+ try {
98
+ record({
99
+ kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
100
+ message: `自动关联写入 ${counts.added + counts.updated} 条(新增 ${counts.added} / 更新 ${counts.updated})`,
101
+ detail: {
102
+ op: operation, added: counts.added, updated: counts.updated,
103
+ skippedManual: counts.skippedManual, skippedCap: counts.skippedCap, skipped: counts.skipped,
104
+ memory: counts.memory, entity: counts.entity,
105
+ },
106
+ refs: [...new Set(applied.map(edge => edge.from))].slice(0, 20),
107
+ })
108
+ } catch {}
109
+ }
110
+ return { ...counts, applied }
111
+ }
112
+
113
+ /**
114
+ * Incremental refresh for the memories a consolidation touched: drop the auto
115
+ * edges this layer generated for them, then re-add today's deterministic ones.
116
+ * Removal and addition share one index lock, so a crash cannot leave the entry
117
+ * with half a rule set.
118
+ */
119
+ export function refreshMemoryAutoLinks({ libraryId, ids, entities = [], suppression = null, sessionId = null, operation = 'auto-link-apply' } = {}) {
120
+ const wanted = [...new Set((Array.isArray(ids) ? ids : []).map(id => String(id)).filter(Boolean))]
121
+ const counts = { added: 0, updated: 0, removed: 0, skippedManual: 0, skippedCap: 0, skipped: 0, memory: 0, entity: 0 }
122
+ const applied = []
123
+ if (!libraryId || !wanted.length) return { ...counts, applied }
124
+ const entityIds = new Set((Array.isArray(entities) ? entities : []).map(entity => entity?.id).filter(Boolean))
125
+ updatePrivateIndex(libraryId, index => {
126
+ const decided = decideAutoLinksFor({ index, entities, ids: wanted, suppression })
127
+ // Diff instead of wipe-and-rebuild: an unchanged edge keeps its createdAt and
128
+ // counts as no write, so a repeat pass over the same window is a no-op.
129
+ const byMemory = new Map()
130
+ for (const edge of decided) {
131
+ if (!byMemory.has(edge.from)) byMemory.set(edge.from, new Map())
132
+ byMemory.get(edge.from).set(`${edge.to}\u0000${edge.kind}`, edge)
133
+ }
134
+ for (const id of wanted) {
135
+ const entry = index.entries[id]
136
+ if (!entry || !Array.isArray(entry.links)) continue
137
+ const candidates = byMemory.get(id) || new Map()
138
+ const next = []
139
+ let changed = false
140
+ for (const link of entry.links) {
141
+ // Rule-owned edges plus marker-less legacy auto edges: both are this
142
+ // layer's noise and are replaced by today's decision.
143
+ const owned = link && link.source === 'auto' && (AUTO_RULES.includes(link.evidence?.rule) || !link.evidence?.rule)
144
+ if (!owned) { next.push(link); continue }
145
+ const key = `${link.to}\u0000${link.kind}`
146
+ const edge = candidates.get(key)
147
+ if (edge && sameAsRecord(link, edge)) { candidates.delete(key); next.push(link); continue }
148
+ counts.removed += 1
149
+ changed = true
150
+ }
151
+ if (changed) entry.links = next
152
+ }
153
+ for (const [fromId, candidates] of byMemory) {
154
+ const from = index.entries[fromId]
155
+ if (!from || !isEligibleEntry(from)) { counts.skipped += candidates.size; continue }
156
+ const links = Array.isArray(from.links) ? from.links : []
157
+ for (const edge of candidates.values()) {
158
+ const isMemoryTarget = Boolean(index.entries[edge.to])
159
+ if (!isMemoryTarget && !entityIds.has(edge.to)) { counts.skipped += 1; continue }
160
+ const at = links.findIndex(link => link && link.to === edge.to && link.kind === edge.kind)
161
+ if (at >= 0 && links[at].source !== 'auto') { counts.skippedManual += 1; continue }
162
+ if (at < 0 && links.length >= 100) { counts.skippedCap += 1; continue }
163
+ const record_ = recordFor(edge, at >= 0 ? links[at] : null)
164
+ if (at >= 0) { links[at] = record_; counts.updated += 1 }
165
+ else { links.push(record_); counts.added += 1 }
166
+ counts[isMemoryTarget ? 'memory' : 'entity'] += 1
167
+ applied.push({ from: edge.from, to: edge.to, kind: edge.kind, rule: edge.rule })
168
+ }
169
+ from.links = links
170
+ }
171
+ })
172
+ const written = counts.added + counts.updated
173
+ if (written || counts.removed) {
174
+ try {
175
+ record({
176
+ kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
177
+ message: `自动关联重算 ${written} 条(新增 ${counts.added} / 更新 ${counts.updated} / 清理 ${counts.removed})`,
178
+ detail: {
179
+ op: operation, added: counts.added, updated: counts.updated, removed: counts.removed,
180
+ skippedManual: counts.skippedManual, skippedCap: counts.skippedCap, skipped: counts.skipped,
181
+ memory: counts.memory, entity: counts.entity,
182
+ },
183
+ refs: [...new Set(applied.map(edge => edge.from))].slice(0, 20),
184
+ })
185
+ } catch {}
186
+ }
187
+ return { ...counts, applied }
188
+ }
189
+
190
+ /**
191
+ * Recompute one entity's mention edges across the whole library. Used when an
192
+ * entity is confirmed, renamed, merged or revoked; field edges are untouched.
193
+ */
194
+ export function refreshEntityMentions({ libraryId, entity, suppression = null, sessionId = null, operation = 'auto-link-entity' } = {}) {
195
+ const counts = { added: 0, updated: 0, removed: 0, skipped: 0 }
196
+ if (!libraryId || !entity?.id) return counts
197
+ // 'off' means every automatic edge path is closed, including the ones explicit
198
+ // UI actions used to trigger (create/confirm/rename/merge). 'suggest' still
199
+ // maintains edges on an explicit confirmation: the §14 S4 migration flow
200
+ // confirms while the automatic pass is still held back.
201
+ if (getSettings().autoLinkMode === 'off') return counts
202
+ updatePrivateIndex(libraryId, index => {
203
+ const decided = entity.status === 'confirmed'
204
+ ? mentionEdges(eligibleEntries(index), [entity]).filter(edge => !isSuppressed(suppression, edge))
205
+ : []
206
+ const byLink = new Map(decided.map(edge => [`${edge.from}\u0000${edge.to}\u0000${edge.kind}`, edge]))
207
+ for (const [fromId, entry] of Object.entries(index.entries || {})) {
208
+ if (!entry || !Array.isArray(entry.links)) continue
209
+ const next = []
210
+ let changed = false
211
+ for (const link of entry.links) {
212
+ const owned = link && link.source === 'auto' && link.evidence?.rule === 'entity-mention'
213
+ && link.evidence?.entityId === entity.id
214
+ if (!owned) { next.push(link); continue }
215
+ const key = `${fromId}\u0000${link.to}\u0000${link.kind}`
216
+ const edge = byLink.get(key)
217
+ if (edge && sameAsRecord(link, edge)) { byLink.delete(key); next.push(link); continue }
218
+ counts.removed += 1
219
+ changed = true
220
+ }
221
+ if (changed) entry.links = next
222
+ }
223
+ for (const edge of byLink.values()) {
224
+ const from = index.entries[edge.from]
225
+ if (!from) continue
226
+ const links = Array.isArray(from.links) ? from.links : []
227
+ const at = links.findIndex(link => link && link.to === edge.to && link.kind === edge.kind)
228
+ if (at >= 0 && links[at].source !== 'auto') { counts.skipped += 1; continue }
229
+ if (at < 0 && links.length >= 100) { counts.skipped += 1; continue }
230
+ const record_ = recordFor(edge, at >= 0 ? links[at] : null)
231
+ if (at >= 0) { links[at] = record_; counts.updated += 1 }
232
+ else { links.push(record_); counts.added += 1 }
233
+ from.links = links
234
+ }
235
+ })
236
+ if (counts.added || counts.updated || counts.removed) {
237
+ try {
238
+ record({
239
+ kind: 'write', scope: 'private', sessionId, libraryId, ok: true,
240
+ message: `实体提及边重算「${entity.name || entity.id}」:新增 ${counts.added} / 更新 ${counts.updated} / 清理 ${counts.removed}`,
241
+ detail: { op: operation, entityId: entity.id, status: entity.status || null, ...counts },
242
+ refs: [entity.id],
243
+ })
244
+ } catch {}
245
+ }
246
+ return counts
247
+ }
248
+
249
+ export default { applyAutoEdges, refreshMemoryAutoLinks, refreshEntityMentions, AUTO_RULES }
@@ -0,0 +1,155 @@
1
+ // Review-queue builder (DESIGN §9). Candidate terms and legacy entity grades are
2
+ // derived data: they change no entity status and write no edge. The snapshot is
3
+ // persisted next to the index so the panel can render without recomputing, and
4
+ // it is safe to delete/recreate at any time.
5
+
6
+ import fs from 'node:fs'
7
+ import path from 'node:path'
8
+ import { dataDir, indexDir, isSafeId, writeJson } from '../paths.js'
9
+ import { loadPrivateIndex } from '../state.js'
10
+ import { listEntities } from '../graph.js'
11
+ import { loadLexicon } from '../lexicon.js'
12
+ import { AUTOLINK_POLICY_V3, AUTOLINK_POLICY_VERSION } from './policy.js'
13
+ import { eligibleEntries, effectiveEntityStatus } from './decide.js'
14
+ import { buildTermStats, rankCandidates } from './terminology.js'
15
+ import { normalizeForIndex } from './normalize.js'
16
+
17
+ const CACHE = new Map()
18
+
19
+ export function candidatesFile(libraryId) {
20
+ if (!isSafeId(libraryId)) throw new Error('invalid library id')
21
+ return path.join(indexDir(), `${libraryId}.anchor-candidates.json`)
22
+ }
23
+
24
+ function statSignature(libraryId) {
25
+ const files = [
26
+ path.join(indexDir(), `${libraryId}.json`),
27
+ path.join(indexDir(), `${libraryId}.entities.json`),
28
+ path.join(dataDir(), 'lexicon', `${libraryId}.json`),
29
+ ]
30
+ return files.map(file => {
31
+ try {
32
+ const stat = fs.statSync(file)
33
+ return `${stat.mtimeMs}:${stat.size}`
34
+ } catch { return '0:0' }
35
+ }).join('|')
36
+ }
37
+
38
+ function lexiconSignals(libraryId) {
39
+ const user = new Set()
40
+ const model = new Set()
41
+ let terms = {}
42
+ try { terms = loadLexicon(libraryId).terms || {} } catch { return { user, model } }
43
+ for (const entry of Object.values(terms)) {
44
+ if (!entry || entry.status !== 'active') continue
45
+ const userOwned = entry.source === 'user' || Boolean(entry.reviewedBy)
46
+ const target = userOwned ? user : (entry.source === 'model-proposal' ? model : null)
47
+ if (!target) continue
48
+ for (const name of [entry.term, ...(Array.isArray(entry.aliases) ? entry.aliases : [])]) {
49
+ const key = normalizeForIndex(name)
50
+ if (key) target.add(key)
51
+ }
52
+ }
53
+ return { user, model }
54
+ }
55
+
56
+ function entitySurfaceMap(entities) {
57
+ const map = new Map()
58
+ for (const entity of entities) {
59
+ for (const name of [entity.name, ...(Array.isArray(entity.aliases) ? entity.aliases : [])]) {
60
+ const key = normalizeForIndex(name)
61
+ if (key && !map.has(key)) map.set(key, entity)
62
+ }
63
+ }
64
+ return map
65
+ }
66
+
67
+ /**
68
+ * Build (or reuse) one library's review queue. The snapshot never contains
69
+ * memory bodies: rows are terms plus statistics, which the UI already shows.
70
+ */
71
+ export function generateAnchorCandidates({ libraryId, now = Date.now(), force = false, policy = AUTOLINK_POLICY_V3 } = {}) {
72
+ if (!isSafeId(libraryId)) throw new Error('invalid library id')
73
+ const signature = statSignature(libraryId)
74
+ const cached = CACHE.get(libraryId)
75
+ if (!force && cached && cached.signature === signature) return cached.value
76
+ const stored = readStored(libraryId)
77
+ if (!force && stored && stored.revision === signature && Array.isArray(stored?.tiers?.tier1)) {
78
+ CACHE.set(libraryId, { signature, value: stored })
79
+ return stored
80
+ }
81
+
82
+ const index = loadPrivateIndex(libraryId)
83
+ const rows = eligibleEntries(index).map(item => ({
84
+ id: item.id,
85
+ title: String(item.entry?.title || ''),
86
+ text: `${item.entry?.title || ''}\n${item.entry?.content || ''}`,
87
+ }))
88
+ const stats = buildTermStats(rows, policy)
89
+ const { user, model } = lexiconSignals(libraryId)
90
+ const tiers = rankCandidates(rows, stats, { policy, lexiconUser: user, lexiconModel: model })
91
+ const entityItems = listEntities({ libraryId }).items
92
+ const bySurface = entitySurfaceMap(entityItems)
93
+ for (const tier of ['tier1', 'tier2']) {
94
+ for (const row of tiers[tier]) {
95
+ const entity = bySurface.get(normalizeForIndex(row.term))
96
+ if (!entity) continue
97
+ row.entityId = entity.id
98
+ row.entityName = entity.name
99
+ row.entityKind = entity.kind
100
+ row.entityStatus = effectiveEntityStatus(entity)
101
+ }
102
+ }
103
+ const provisional = entityItems
104
+ .filter(entity => effectiveEntityStatus(entity) === 'provisional')
105
+ .map(entity => ({
106
+ id: entity.id, name: entity.name, kind: entity.kind, linked: entity.linked === true,
107
+ origin: entity.origin || null,
108
+ terms: [...tiers.tier1, ...tiers.tier2].filter(row => row.entityId === entity.id).map(row => row.term),
109
+ }))
110
+ .sort((a, b) => (b.terms.length - a.terms.length) || a.name.localeCompare(b.name))
111
+ const confirmed = entityItems
112
+ .filter(entity => effectiveEntityStatus(entity) === 'confirmed')
113
+ .map(entity => ({ id: entity.id, name: entity.name, kind: entity.kind }))
114
+ .sort((a, b) => a.name.localeCompare(b.name))
115
+
116
+ const value = {
117
+ version: 1,
118
+ libraryId,
119
+ revision: signature,
120
+ policyVersion: AUTOLINK_POLICY_VERSION,
121
+ generatedAt: new Date(now).toISOString(),
122
+ totals: { memories: rows.length, entities: entityItems.length, tier1: tiers.tier1.length, tier2: tiers.tier2.length },
123
+ tiers,
124
+ entities: { provisional, confirmed },
125
+ }
126
+ CACHE.set(libraryId, { signature, value })
127
+ try { writeJson(candidatesFile(libraryId), value) } catch {}
128
+ return value
129
+ }
130
+
131
+ function readStored(libraryId) {
132
+ try {
133
+ const raw = fs.readFileSync(candidatesFile(libraryId), 'utf8')
134
+ const value = JSON.parse(raw)
135
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : null
136
+ } catch {
137
+ return null
138
+ }
139
+ }
140
+
141
+ /** Test/ops helper: drop the in-process cache so the next read recomputes. */
142
+ export function resetAnchorCandidatesCache() {
143
+ CACHE.clear()
144
+ }
145
+
146
+ /**
147
+ * The candidate row for one confirmed-able term: the UI either confirms an
148
+ * existing provisional entity or creates a confirmed one. Returns a descriptor;
149
+ * the actual confirm/create stays an explicit user RPC.
150
+ */
151
+ export function candidateConfirmationTarget(candidate) {
152
+ if (candidate?.entityId && candidate.entityStatus === 'provisional') return { kind: 'confirm', entityId: candidate.entityId }
153
+ if (candidate?.entityId && candidate.entityStatus === 'confirmed') return { kind: 'already-confirmed', entityId: candidate.entityId }
154
+ return { kind: 'create', name: String(candidate?.term || '') }
155
+ }