dsh-memu-memory 1.3.11 → 1.3.13

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,33 @@
1
1
  # 更新日志 / Changelog
2
2
 
3
+ ## [1.3.13] - 2026-11-21
4
+
5
+ > 诊断体系:插件内部故障有了自己的出口(诊断页 + 启动弹窗 + 自动/手动修复),并修掉三类会让召回静默降级的真实故障——摘要把镜像元数据算成"制品已变"、运行时目录失效、0 字节遗留锁永不自愈。
6
+
7
+ - **诊断存储(与活动日志分开)**:新增 `lib/diagnostics.js`,写 `diagnostics/events.jsonl`(2MB 轮转)+ `acknowledged.json`,内存环形 500 条;同 `(scope, code, message)` 60 秒内只累加 `count`;`detail` 统一脱敏。`KNOWN_CODES` 把故障码映射成「哪一层坏了 / 能不能自动修 / 修之前会不会丢数据」。
8
+ - **诊断页(设置 → 诊断,`#/settings/diagnostics`)**:上半张环境自检(数据目录、遗留锁、引擎、向量 profile、运行时、模型、worker),每项给证据与建议并配按钮(可自动修的给按钮,破坏性的标"需手动");下半张按 level/关键词过滤诊断记录,可整页复制。独立 WebUI 的 `PAGE_NAMES` 同步。
9
+ - **启动检查 + 主页弹窗**:启动 6 秒后跑一次自检,error/warn 项落诊断(`ENV_*`);主页顶部弹出提醒卡(`getDiagnosticAlerts`,最多 4 条按 code 汇总),点"稍后/打开诊断"即 `acknowledgeDiagnostics`,同一问题不再天天弹、再次发生才重新提醒。
10
+ - **修复:自动只做安全项**:`SAFE_REPAIRS`=释放可证明遗弃的锁(`release-stale-locks`)、重签摘要(`resign-vector-profile`)、重指运行时目录(`repoint-runtime-dir`),受 `autoInstallEngine` 开关约束;`MANUAL_REPAIRS`=重装运行时/模型、重建向量代际、重装引擎,只能手动、且 `confirmed === true`。每步无论成败都记 `MEMU_DIAGNOSTIC_REPAIRED` / `MEMU_DIAGNOSTIC_REPAIR_FAILED`。
11
+ - **锁加固**:`withFileLock` 载荷改成 `pid\nISO`(兼容旧的一行裸 pid),EEXIST 时先判定遗弃(无法解析且≥10s / 自身 pid 但无事务且≥10s / 死 pid 立即 / ≥60s 超龄),遗弃则就地释放重试并发 `MEMU_LOCK_BROKEN` 事件。真实事故:0 字节 `consolidation.json.lock` 里 `Number('')===0` 永不满足清理条件,整理连败 84 次。
12
+ - **摘要改成身份视图**:`manifestDigest` 只摘 `runtime` 的身份字段(engine/abi/version/os/arch 与制品 name/version/sha256/integrity),镜像源与文案(`sources`/`label`/`displayName`/`summary`)不再入摘要,字典与数组两种制品形态都剥;老算法继续接受;`manifestDrift` 区分"只有元数据漂移(warn 一次、继续用)"与"身份变了(抛错、要重建)";逐字段一致却摘要对不上仍按不可信处理。
13
+ - **重签与重指**:`resignVectorProfile` 拒绝身份变更,改前备份 `vector-active.json.bak-resign-*`;`repointVectorRuntimeDir` 备份 `.bak-runtimedir-*`,候选目录同时扫 `downloads/embeddings/runtime`(真实布局)与旧 `downloads/runtime`,且要求 `onnxruntime-node/package.json` 真在(只剩 `bin/` 的空壳不算候选)。
14
+ - **整理收尾失败带原因**:worker 收尾 followup 失败原先只写 `consolidation wrapup followup failed`,诊断页照着查不到任何东西;现在带 `code: message`(`describeError`),并在 `lib/binding-diagnostics.js` 的 `RUNTIME_STATE` 里同步 `inFlight` 的源码位置。
15
+ - **worker 可观测**:`local-embedding-manager` 不再丢弃子进程 stderr(脱敏后保留末 4000 字),失败时挂 `error.embedding = {stderrTail, modelDir, runtimeDir}` 并通过 `setEmbeddingFailureSink` 写诊断——「worker exited before it became ready」从此带原因。
16
+ - **读盘修复**:`ensureLoaded` 只有在真的从中间截断时才丢第一行;此前无条件 `shift()`,导致"落盘了但重启后诊断页永远空白"。
17
+ - 守卫:`tests/diagnostics.test.mjs`(去重/独立落盘/脱敏/确认后不再弹/修复双向记账/锁四判据/三算法兼容/drift 分类/重启后可读)、`tests/environment-check.test.mjs`(检查项形状、遗弃锁可见、`confirmed` 门禁、失败也记账、安全名单不可越界、运行时目录发现)、`tests/client-render.test.mjs` 逐页探针 13 → 14 页。
18
+ - 文档同步:`docs/contributing.md` §5.4.1(诊断/修复扩展点)、`docs/troubleshooting.md` §3.29(三类真实故障的症状→根因→诊断码→修复动作)。
19
+
20
+ ## [1.3.12] - 2026-11-20
21
+
22
+ > 全局记忆生命周期与私有同权:记忆墙全局块多选批量归档/恢复/删除、抽屉与全局记忆页的归档/恢复/两段确认永久删除补齐;内容仍由 curator 书写。
23
+
24
+ - **管理面 RPC(不新增方法)**:既有 `archiveMemory` / `updateMemory` / `deleteMemory` 支持显式 `scope:'global'`。全局 `updateMemory` 只接受 `{status:'active'}` 恢复补丁,其余字段一律拒绝(内容写入仍归 curator,硬规则 2 不变);`scope:'global'` 与 `libraryId` 同现是作用域冲突,鉴权层直接拒。鉴权与全局复核队列同口径:embedded 要活绑定,standalone 走 `libraryId=null` 的 `review.manage` capability。
25
+ - **归档即生效**:`globalSetStatus` 只改 status——召回/锚点/注入统一过 `isMemoryEligible`,archived 立即自动排除,不动向量行(与 privateArchive 同口径)。`pending_review` 必须先走复核队列;`superseded` 可归档但不能直接恢复。
26
+ - **永久删除**:只开放 archived/suppressed/expired,需显式确认 + 删除前整库备份;先删引擎/向量行再单事务删行,级联清他条 `links[].to` 与 `duplicateOf/relatedTo/conflictingWith/supersededBy/absorbedBy` 指针。合并稿(带 `absorbedFrom`)与活跃合并的来源拒删——`absorbSnapshot` 是撤销合并的唯一依据。全局删除没有 preview/restore 撤销缓冲(明确报错,不静默)。
27
+ - **UI 统一**:记忆墙全局块启用多选(批量归档/恢复/两段删除,逐条失败一次性报错口径与私有一致);抽屉全局条目内容只读但生命周期按钮齐全(待复核条目不显示归档,走复核裁决);全局记忆页每条带状态 Tag 与归档/恢复/两段删除。侧栏会话视图保持只读。
28
+ - 守卫:`tests/global-lifecycle.test.mjs`(状态机/召回排除/级联/合并守卫/管理视图/私有回归)、`tests/webui-auth.test.mjs` 全局生命周期凭据矩阵、`tests/client-render.test.mjs` 全局块多选与抽屉两段删除;`tests/webui.test.mjs` 抽屉删除静态守卫更新为双作用域形状。
29
+ - 文档同步:README(中英)抽屉口径、`docs/memory-semantics.md` §8.3 生命周期管理面、`docs/troubleshooting.md` §3.42。
30
+
3
31
  ## [1.3.11] - 2026-11-20
4
32
 
5
33
  > 隐藏记忆不再经词法统计挤掉可见召回;必写候选核验改为保守证据比对,同日不同事/极性相反/数值改变不再被误判「已覆盖」。
package/README.md CHANGED
@@ -60,7 +60,7 @@ All screenshots are the real WebUI on isolated example data, not anyone's memori
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
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.
62
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.
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
+ - **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). New names proposed by a model must appear as complete quoted, introduced or delimited names in the source memory; a substring or the link note alone is insufficient. Existing names and aliases remain reusable, and rejected links leave no new entity.
64
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.
65
65
  - **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.
66
66
  - **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.
@@ -93,9 +93,9 @@ The sidebar has exactly **one** entry: **MemU WebUI**. The memory wall and all s
93
93
 
94
94
  **Private / global groups with multi-select.** The "Memories" page splits into **Private** and **Global** blocks (private first, default). The private block supports **multi-select**: bulk archive, restore and permanent delete (two-step confirm) — one failed row never eats the rest. Every row on the Global memory page has a "View" action that jumps straight to that entry on the wall.
95
95
 
96
- **In-place work.** Clicking a memory card opens a right-side drawer with the full text and the fields that decide how it behaves — title, content, tags, disclosure, confidence, open loop — plus save, archive, restore and "open in the browser" for heavier work. Archived memories can be deleted in the same drawer; the first click only arms it and the second confirms. Global memories are read-only in the drawer and link to their own page. Filters and scroll position stay where they were. Cards that carry images use the first usable attachment as a cover, and the drawer opens the full gallery; `secret` and `never_say` entries never receive a pixel URL, so they show a label instead.
96
+ **In-place work.** Clicking a memory card opens a right-side drawer with the full text and the fields that decide how it behaves — title, content, tags, disclosure, confidence, open loop — plus save, archive, restore and "open in the browser" for heavier work. Archived memories can be deleted in the same drawer; the first click only arms it and the second confirms. Global memories keep their curator-written content read-only in the drawer, but archive, restore and two-step permanent delete work there just like private ones, and link to their own page. Filters and scroll position stay where they were. Cards that carry images use the first usable attachment as a cover, and the drawer opens the full gallery; `secret` and `never_say` entries never receive a pixel URL, so they show a label instead.
97
97
 
98
- **One page for the graph.** **Relations** is its own full-screen page in the WebUI (`#/settings/graph`): the canvas on the left, the inspector on the right, and a **Manage** tab for the list view with the same filters. Source (all / automatic only / manual only), rule, library and search all narrow one shared dataset instead of switching modes, and Settings → Relations is a single button that opens that page. The scope selector still carries a **Global memory** entry: nodes are global entries and edges are `related/refines/supports`; the global view is read-only, and edges are removed from the global memory list.
98
+ **One page for the graph.** **Relations** is its own full-screen page in the WebUI (`#/settings/graph`): the canvas on the left, the inspector on the right, and a **Manage** tab using the same domain and search filters. **All libraries** combines private libraries with separate identities for same-id nodes and follows 200-node pages through trailing entities; the canvas retains every loaded node. The editable **Domain** filter accepts built-in or custom domains (for example `coding` or `project:travel`), matches the full normalized name, and shows all domains when empty. Missing memory domains count as `general`; a filtered entity appears when linked to a matching memory. Source and rule filters narrow displayed edges. Settings → Relations opens this page; graph browsing retains the existing library and session authorization boundaries.
99
99
 
100
100
  The graph runs on a **self-written continuous force engine** — no third-party runtime is bundled. It stays alive while you work, preserves node positions and the camera across background data refreshes, and stops requesting frames the moment it cools down, so an open graph costs no idle GPU. Dragging pins a node exactly where you drop it (release never yanks it back), and only the cluster you touched keeps simulating: frozen clusters act as obstacles the moving one cannot slide through. Repulsion, link distance and centering are adjustable in the panel, labels avoid collisions, and the minimap repaints only after the canvas does. Zoomed all the way out the nodes necessarily merge on screen — separation lives in world coordinates, so spread clusters with repulsion/link distance instead of the zoom. Settings → Relations is a single button that opens the full-screen graph page in the WebUI, where you can also add, edit and delete nodes, and filter edges by the rule that produced them. The layout only visualizes recorded links: it never infers or writes relationships. The graph page also lists **entity merge candidates** (same kind, contained or near-identical spellings) — suggestions only, confirmed by two clicks, and merging redirects links and folds aliases into the main node without deleting any memory.
101
101
 
package/README.zh.md CHANGED
@@ -92,7 +92,7 @@
92
92
 
93
93
  **私有 / 全局分组与多选。** 「MemU 记忆」页按 **私有 / 全局** 分块(默认私有),私有块支持**多选**:批量归档、恢复、彻底删除(两段确认),一条失败不影响其余成果。「全局记忆」页每条记忆带「查看此记忆」,点击直达 MemU 记忆页对应条目。
94
94
 
95
- **原地操作。** 点记忆卡片会从右侧滑出详情抽屉:完整正文,以及决定它行为的字段——标题、正文、标签、说出口径、置信度、未了之事——外加保存、归档、恢复,以及需要重编辑时的「在记忆浏览中打开」。已归档的记忆可以直接在抽屉里删除:第一次点击只是准备,第二次才真正删除。全局记忆在抽屉里只读,并给出跳转。筛选条件与滚动位置保持不动。带图片的卡片会把第一张可用附件作为封面,抽屉里展开完整图片组;`secret` 与 `never_say` 条目不会拿到像素 URL,只显示标签占位。
95
+ **原地操作。** 点记忆卡片会从右侧滑出详情抽屉:完整正文,以及决定它行为的字段——标题、正文、标签、说出口径、置信度、未了之事——外加保存、归档、恢复,以及需要重编辑时的「在记忆浏览中打开」。已归档的记忆可以直接在抽屉里删除:第一次点击只是准备,第二次才真正删除。全局记忆的正文仍由整理器书写、在抽屉里只读,但归档、恢复与两段确认的永久删除与私有记忆同权,并给出跳转。筛选条件与滚动位置保持不动。带图片的卡片会把第一张可用附件作为封面,抽屉里展开完整图片组;`secret` 与 `never_say` 条目不会拿到像素 URL,只显示标签占位。
96
96
 
97
97
  **图谱单独一页。** 「关系图谱」是 WebUI 里一个全屏页面(`#/settings/graph`):左边画布、右边检视面板,列表视图在同页的**管理**页签下,用的是同一套筛选。来源(全部 / 仅自动 / 仅手动)、规则、记忆库与搜索都在收窄同一份数据,不是要记得切换的模式;设置里的「关系图谱」只有一个按钮,点了直达这一页。范围选择器仍然带一项**全局记忆**:节点是全局条目、边是 `related/refines/supports`,全局视图只读,移除边仍在全局记忆列表里完成。
98
98
 
@@ -78,9 +78,9 @@ npm run check # node --check + i18n 键对齐 + package.j
78
78
 
79
79
  ### 5.3 新增一个 RPC 方法
80
80
 
81
- <!-- rpc-method-count: 102 -->
81
+ <!-- rpc-method-count: 109 -->
82
82
 
83
- 1. `lib/rpc.js` 的 `switch` 加 case(共 102 个方法,按功能分组,别乱插)。
83
+ 1. `lib/rpc.js` 的 `switch` 加 case(共 109 个方法,按功能分组,别乱插)。
84
84
  2. 返回**形状稳定**:客户端 `call()` 直接解构,列表类给 `{items, total}` 而不是裸数组。
85
85
  3. `revisionOnly` 分支只回 `{revision, stamp}`、**不要求 sessionId**(三端轮询,设置页与独立页没会话)、**不塞业务数据**(每 2.5 秒一次);顺带 `noteMemoryBeat()`,`memu_status` 靠它分「没写」与「没人轮询」。
86
86
  4. 写成功后 `bumpMemoryRevision()`/`notifyMemoryWrite()`(§7);能让 `state.json` 或索引落盘的写,`state.js` 自动记写事件供 `memu_status` 展示。
@@ -94,6 +94,18 @@ npm run check # node --check + i18n 键对齐 + package.j
94
94
  4. 独立页(`lib/webui/`)要同步显示就走 `BroadcastChannel` 的 `memory-write`,并让 WebUI `settingRow` 读同一份 `getSettingsState`。
95
95
  5. **新增整页**:`PAGE` 加键 → `pageDefs` → `pageBlocks` → 导航图标 → 两处文案 → 渲染探针(`tests/client-render.test.mjs` 逐页渲染)。
96
96
 
97
+ ### 5.4.1 新增一条诊断 / 一个修复动作
98
+
99
+ 诊断是**插件自己的体检**,与活动日志(`logs/activity.jsonl`,记"发生了什么")刻意分开:活动日志给用户看流程,诊断记"哪里坏了、能怎么修"。
100
+
101
+ 1. **记一条**:`recordDiagnostic({level, scope, code, message, detail, hint, repair})`(`lib/diagnostics.js`)。`code` 用大写下划线常量,同一个 `(scope, code, message)` 在 60 秒窗口内只累加 `count`,不会刷屏;`detail` 里的 secret 会被 `redactSecrets`(`lib/paths.js:63`)脱敏——**宁可少记,不可记明文 key**。
102
+ 2. **让报错自动进来**:抛错路径统一走 `recordErrorDiagnostic(error, {source, detail})`;`error.code` 命中 `KNOWN_CODES` 表就自动带上 scope / 修复动作 / hint。
103
+ 3. **登记故障码**:`KNOWN_CODES`(`lib/diagnostics.js`)里给 `{scope, repair, manual, hint}`。`repair` 必须是 `lib/environment-check.js` 里 `REPAIRS` 的键,否则诊断页只显示"无可用修复"。
104
+ 4. **新增修复动作**:在 `lib/environment-check.js` 的 `REPAIRS` 加一项 `{label, run}`,同时决定它进 `SAFE_REPAIRS`(启动时自动跑、幂等、不删用户数据)还是 `MANUAL_REPAIRS`(必须用户点、可能重建索引或重装引擎)。**破坏性动作永远不进 SAFE**。
105
+ 5. **每一项修复都要 `recordRepair({action, ok, detail})`**——失败也要进诊断,否则"修了但没修好"无从判断。
106
+ 6. **检查项**:`runEnvironmentCheck` 的 items 形如 `{id, level, ok, title, detail, hint, repair}`,诊断页与启动弹窗都只认这个形状;加检查项记得在 `tests/environment-check.test.mjs` 里加一条"缺什么报什么"的用例。
107
+ 7. 前端:诊断页 `diagnosticsBlock`(`lib/client.js`)已把"环境自检 + 诊断记录"两块渲染完,新动作不用改前端,只要出现在 `getRepairOptions` 里就会长出按钮。
108
+
97
109
  ### 5.5 新增一个提示词变体 / 类型页
98
110
 
99
111
  1. 变体命名 `<name>.<domain>.md`,与基础稿同在 `lib/prompts/`。**只有三个 key 支持分域**:`system-guide`、`private-policy`、`private-consolidation`;`global-curator` 不分域(职责就是跨域整理)。
@@ -26,6 +26,8 @@
26
26
 
27
27
  只有 curator 写,主 agent 只读。domain:`universal / coding / rp / project:<name> / tooling / personal`,**RP 与 coding 冲突分域存,不合并**。RP 剧情事实、关系进度、临时情绪**不写全局**;每条必须有 `evidence` + `confidence`。
28
28
 
29
+ **生命周期管理面(1.3.12)**:内容仍由 curator 书写,但用户管理面与私有同权——记忆墙全局块支持多选批量归档/恢复/删除,抽屉与全局记忆页提供归档、恢复、两段确认永久删除。RPC 走既有 `archiveMemory` / `updateMemory` / `deleteMemory` 加显式 `scope:'global'`(不新增方法):全局 `updateMemory` 只接受 `{status:'active'}` 恢复补丁,其余字段一律拒绝;鉴权与全局复核队列同口径(embedded 要活绑定,standalone 走 `libraryId=null` 的 `review.manage`),`scope:'global'` 与 `libraryId` 同现是作用域冲突。归档只改 status——召回/锚点/注入统一过 `isMemoryEligible`,archived 立即自动排除,不动向量行;`pending_review` 必须先走复核队列,`superseded` 不能直接恢复。永久删除只开放 archived/suppressed/expired,需显式确认 + 删除前整库备份,单事务级联清他条 `links[].to` 与 `duplicateOf/relatedTo/conflictingWith/supersededBy/absorbedBy` 指针;合并稿(带 `absorbedFrom`)与活跃合并的来源拒删——`absorbSnapshot` 是撤销合并的唯一依据。全局删除没有 preview/restore 撤销缓冲。守卫:`tests/global-lifecycle.test.mjs`、`tests/webui-auth.test.mjs`(全局生命周期凭据矩阵)、`tests/client-render.test.mjs`(全局块多选与抽屉两段删除)。
30
+
29
31
  **审核模式(`curatorReviewMode`)**:`auto`(默认)= 有落地证据的提炼结果自动通过;`review-all` = 提炼产物一律进待复核。`conflict`(说法矛盾)与无证据的条目在任何模式下都进人审;rewrite 类操作(merge/supersede/absorb)在 auto 下风险 ≥0.70 也暂扣。每条都带 `reviewRisk/reviewRiskReasons` 供审计与复核排序。
30
32
 
31
33
  **证据落地(grounding)**:evidence 的 quote 必须是本次策划所含会话转录的规范化子串(≥6 字,省略号分段校验,先脱敏)——模型编造的"原话"进不了库;未落地恒 pending 或不落库。
@@ -163,9 +165,9 @@
163
165
 
164
166
  **私有自动关联(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` 的候选排序。
165
167
 
166
- **实体生命周期。** `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 边同样写抑制键,后续重算不会复活。
168
+ **实体生命周期。** `provisional`(默认)不产生任何边,`confirmed` 才允许 R1,`archived` 视同不可用。手工创建(UI/RPC)直接 confirmed;worker 经 `memu_private_link` 点名只创建 provisional 实体与一条非 auto 边;新实体名必须在来源记忆的标题或正文中以完整引号、名字引导加右边界、或两侧分隔的表面出现,不能由词语子串、代词或 link note 推出。已有实体/别名按 NFKC 与大小写复用;名称、来源可见性、边类型、理由、置信度与数量限制先校验,再创建新实体(`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 边同样写抑制键,后续重算不会复活。
167
169
 
168
- **候选队列与迁移。** `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`。
170
+ **候选队列与迁移。** `anchor-candidates.json` 是派生物:CJK 2–4gram / Latin token 的 df/titleDf/边界/凝聚/PMI/LLR 只用于排序;Tier 1 是有完整表面证据(引号/名字引导/标识符/用户维护词典)的候选,完整引号或名字引导不再给内部的短 n-gram 背书;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`。
169
171
 
170
172
  **召回治理与失败隔离。** `recallRelations` 的 top-2 扩展显式排除 `evidence.rule === 'entity-mention'`——提及是事实索引不是关系,`confidence=1.0` 不能挤掉手动边与字段证据;字段证据边照常参与。判定层纯函数、无 IO/时钟/随机;写库失败只 warn,绝不让已经成功的整理失败;`links[]` 仍只是元数据,不改正文、不写向量、不删记忆。worker 写工具为 remember/remember_batch/update/link/link_suggest(2026-11-15 起 link 两件挂回:auto-link 的不确定候选留给整理回合逐条裁决),读工具为空(记忆目录与本地召回由插件在任务包开头注入),但「有没有写能力」仍只由 remember/update 判定。
171
173
 
@@ -37,12 +37,15 @@
37
37
  worker 前置依赖 / 完整包超限 / usage 未知 → §3.39
38
38
  整理输出截断 / 改预算后同快照仍冻结 → §3.40
39
39
  隐藏记忆增加后可见结果消失 / 必写候选误结算 → §3.41
40
+ 全局记忆归档/删除不生效或越权 / 合并稿被误删 → §3.42
40
41
  聊很久一条记忆都没写 → §3.18
41
42
  人格预设会话里完全没有记忆 → §3.19
42
43
  鉴权 / 401/403 行为说不清 → §3.20
43
44
  本地向量模型装不上 / 切不过去 / 召回 400 → §3.25
44
45
  整理超时(fork 预算不够)→ §3.26
45
46
  图谱改了没生效 / 缩到最小打架 / 导航被掰竖 → §3.27
47
+ 全部库图谱缺绿色实体 / 按域筛选 → §3.43
48
+ 自动出现「忆组件 / 主人一 / 人一 / 主人一说」等碎片实体 → §3.44
46
49
  WebUI 开着 GPU 占用高 / 时钟钉高档 → §3.28
47
50
  长链跑批库不增长 / 考试大面积「不知道」→ §3.29
48
51
  同一条用户消息每轮注入两次 / 第二次召回 0 条 → §3.30
@@ -365,6 +368,28 @@ S8 展示回写 client.js 面板 + useMemoryBeat 心跳 + rpc.js allowed + tool
365
368
  **守卫**:`tests/webui.test.mjs` 的 `the shell keeps no always-on compositor drivers`(无限动画只许出现在 boot;ambient 不许 will-change/animation;backdrop-filter 只许 topbar/boot-card;共享 UI 不许全屏模糊;缩略图不许轮询)+ `scripts/check-idle-compositing.mjs` 真机数帧。
366
369
 
367
370
 
371
+ ### 3.29 诊断页:插件内部到底哪儿坏了(1.3.13 起)
372
+
373
+ **症状**:召回突然降级成"只有关键词命中"、写入报 `VECTOR_PROFILE_MANIFEST_CHANGED` / `the local embedding worker exited before it became ready`、整理任务一直说 `the consolidation lease could not be persisted`,但设置页一切正常、活动日志里只有一行警告。
374
+
375
+ **落点**:这类故障以前**没有出口**——`logs/activity.jsonl` 记的是流程(谁在什么时候召回了几条),而"哪个文件坏了、能不能修"无处可看;活动日志里那一行 `logger.warn` 还是被 `fail-open` 吞掉之后的残渣。2026-11 这三类真实故障就是这样坏了 9 天才被发现(同一句 manifest 报错在活动日志里出现 661 次,最早的 2026-11-12):
376
+
377
+ | 症状 | 真实根因 | 诊断里的 code | 修复动作 |
378
+ |---|---|---|---|
379
+ | 召回降级 661 次 | catalog 的 `runtime.sources` 加了国内镜像元数据,摘要却把整个 `runtime` 算进身份 → 向量空间被误判为"制品清单已变" | `VECTOR_PROFILE_MANIFEST_CHANGED` | `resign-vector-profile`(重签摘要,不动 25 条向量) |
380
+ | 写入/召回报 worker exited | `vector-active.json` 的 `runtimeDir` 指向一个已不存在的 UUID 目录(`onnxruntime-node` MODULE_NOT_FOUND,而这行 stderr 被旧代码 `() => {}` 丢掉了) | `LOCAL_VECTOR_RUNTIME_UNAVAILABLE` | `repoint-runtime-dir` |
381
+ | 整理 84 次 `lease could not be persisted` | `consolidation.json.lock` 是 0 字节(写锁时崩在 `writeFileSync` 之前),旧 `withFileLock` 把锁内容当 pid,`Number('')===0` 永远进不了清理分支 → 每次都等到超时 | `DSH_MEMU_STORE_BUSY` | `release-stale-locks` |
382
+
383
+ **现在**:
384
+ - **诊断页**:设置 → 诊断(`#/settings/diagnostics`),或独立 WebUI 的「诊断」。上半张是**环境自检**(数据目录可写 / 遗留锁 / 引擎 python / 向量 profile 摘要 / 向量运行时 / 模型目录 / embedding worker),每项给状态、证据、怎么办,能自动修的给按钮、破坏性的标"需手动";下半张是**诊断记录**,按 level 与关键词过滤,`detail` 里是结构化证据(脱敏后的 stderr 尾巴、路径、changedFields),可整页复制。
385
+ - **主页启动弹窗**:启动引导自检发现 error/warn 级问题时,主页顶部弹一张卡(最多 4 条,按 code 汇总"×N")。点"稍后"或"打开诊断"都会 `acknowledgeDiagnostics`,**同一问题不再天天弹**,只有再次发生(count 增长)才重新提醒。
386
+ - **启动自动修复**:`autoInstallEngine` 打开时,启动 6 秒后跑一次自检,只自动执行**安全且幂等**的三件事(清遗弃锁 / 重签摘要 / 重指运行时目录);重建索引、重装运行时/模型/引擎一律留手动入口——它们会动用户数据或几十 MB 下载,不该静默发生。
387
+ - **落盘位置**:`~/.dsh/dsh-memu-memory/diagnostics/events.jsonl`(2MB 轮转到 `events.1.jsonl`),与 `logs/activity.jsonl` 分开;同一 `(scope, code, message)` 60 秒内只累加 `count`,维修动作无论成功失败都记一行 `MEMU_DIAGNOSTIC_REPAIRED` / `MEMU_DIAGNOSTIC_REPAIR_FAILED`。
388
+
389
+ **自己查的顺序**:先看诊断页环境自检的红项(它们决定"能不能修"),再看诊断记录里最新一条的 `detail`——`stderrTail` / `changedFields` / `busy.owner`+`busy.ageMs` 通常直接点名坏在哪。锁类问题不要手动删 `*.lock`:诊断页的「释放遗留锁」会先核对 pid 是否还活着、锁是否超过 60 秒,只清能证明是遗弃的(手动删可能拆掉另一个插件副本正在用的事务)。
390
+
391
+ **守卫**:`tests/diagnostics.test.mjs`(去重计数、独立落盘、脱敏、告警确认后不再弹、修复双向记账、锁四种遗弃判据、三种摘要算法兼容、镜像漂移 vs 身份变更)、`tests/environment-check.test.mjs`(缺什么报什么、安全/手动分组、`confirmed` 门禁)、`tests/client-render.test.mjs` 的逐页探针(14 页)。
392
+
368
393
  ## 守卫索引表
369
394
 
370
395
  正文只留「症状 + 落点」;拦复发的测试与信号集中在这里。
@@ -407,7 +432,7 @@ S8 展示回写 client.js 面板 + useMemoryBeat 心跳 + rpc.js allowed + tool
407
432
 
408
433
  ### 2.1 模块地图
409
434
 
410
- <!-- rpc-method-count: 102 -->
435
+ <!-- rpc-method-count: 109 -->
411
436
 
412
437
  | 文件 | 职责 / 什么时候碰它 |
413
438
  |---|---|
@@ -730,3 +755,29 @@ grep tests 里的硬编码清单。守卫:全量 `npm test` 1676/1674 pass / 0
730
755
  **落点:** `lib/memory.js` 的私库纯词法与混合召回词法支路在建 BM25 语料前应用会话、自动资格、披露与说话人过滤。只在最终排序时过滤会让隐藏条目污染词频,甚至触发高频词裁剪。显式精确 id 读取维持原资格规则;全局路由不扩大可见范围。`lib/private.js` 的 `candidateCovered` 不能仅凭日期相同或两个相邻字片段就结算候选。
731
756
 
732
757
  **守卫:** `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,避免冲突题仅命中一方就被误读为完整覆盖。
758
+
759
+ ### 3.42 全局记忆生命周期管理面
760
+
761
+ **症状:** 全局块没有多选/归档/删除按钮(1.3.12 前的旧版);或归档后全局记忆仍被召回;或带 `sessionId` 的全局写被拒/越权;或合并稿、活跃合并的来源被永久删除后撤销合并悬空。
762
+
763
+ **落点:** 全局生命周期走既有 `archiveMemory` / `updateMemory` / `deleteMemory` 加显式 `scope:'global'`(`lib/rpc.js`),鉴权与全局复核队列同口径(`authorizeGlobalReviewRoute`:embedded 要活绑定,standalone 走 `libraryId=null` 的 `review.manage`);`scope:'global'` 与 `libraryId` 同现在鉴权层就拒。`lib/memory.js` 的 `globalSetStatus` 只改 status(召回/锚点/注入统一过 `isMemoryEligible`,archived 立即排除,不动向量行);全局 `updateMemory` 只接受 `{status:'active'}`。`globalDelete` 只开放 archived/suppressed/expired + 显式确认 + 删除前 `backupDatabases`,单事务级联清他条 `links[].to` 与 `duplicateOf/relatedTo/conflictingWith/supersededBy/absorbedBy`;带 `absorbedFrom` 的合并稿与活跃合并的来源拒删。前端:记忆墙全局块多选与私有同权(`lib/client.js` MemoryWallPanel),抽屉全局条目内容只读但生命周期按钮齐全,全局记忆页每条带归档/恢复/两段删除。
764
+
765
+ **守卫:** `tests/global-lifecycle.test.mjs`(归档即排除召回/恢复即回来、状态机边界、内容补丁拒绝、删除级联与合并守卫、管理视图仍见 archived、私有路径回归);`tests/webui-auth.test.mjs` 的「global lifecycle」凭据矩阵(活绑定/悬空会话/作用域冲突/review.manage 四态);`tests/client-render.test.mjs` 的全局块多选批量归档与抽屉两段删除(注意 harness 的 hook 游标全局递增:同一棵树只能 walk 一遍)。
766
+
767
+ ### 3.43 全部库图谱缺绿色实体与域筛选
768
+
769
+ **症状**:选择全部库后,后面库的绿色实体不见,或大库只剩记忆节点。
770
+
771
+ **原因与修复**:旧接口每库先取 200 个节点,实体排在记忆后;前端合并时用裸 id 去重,画布又把合并输入截到 200。现在私有图谱无焦点浏览显式传 `offset` 分页,按返回的 `nextOffset` 读完;跨页边保留端点,跨库显示 id 由库和原始 id 组成,管理操作仍用原始 id 写回所属库。画布不再重复截断输入。旧接口默认页上限与焦点邻域仍保留,分页不扩大会话可访问库。读取失败会显示库名,不再静默吞掉。
772
+
773
+ **筛选**:顶部域输入框可输入完整自定义域,或选择已有域;NFKC、首尾空白和大小写规范化后精确匹配,清空显示全部域。缺失域按 `general`,实体随匹配记忆出现,图与管理列表共用结果。仅更改大小写或空白不会清空画布。
774
+
775
+ **守卫**:`tests/graph.test.mjs` 覆盖分页、跨页边、域与权限;`tests/client-render.test.mjs` 覆盖 204 节点跨库分页、同 id 隔离、域切换、原始 id 编辑与部分失败;`tests/graph-view.test.mjs` 覆盖超过 200 节点的尾部实体与实际 bundle。改引擎后执行 `npm run build:graph`。
776
+
777
+ ### 3.44 自动实体把词语片段当成人名
778
+
779
+ **症状**:自动整理或候选队列出现「忆组件」「主人一」「人一」「主人一说」等被截断的人物节点;无效的关联请求报错后还可能留下孤立实体。
780
+
781
+ **原因与修复**:旧候选提取把完整引号或名字引导后的文本再次拆成 n-gram,内部片段也继承表面证据。新候选只给完整称呼背书,并过滤没有独立边界的子片段。模型通过 `memu_private_link` 创建未知实体时,来源记忆本身必须包含完整引号、名字引导加右边界、或两侧分隔的名称,link note 不算来源证据;先校验来源、边类型、理由、置信度和数量限制,再创建 provisional 实体,普通参数错误不再遗留孤立节点。既有实体和别名仍可复用,手动创建与已确认实体的提及匹配保持原规则。
782
+
783
+ **守卫与旧数据**:`tests/tools.test.mjs` 覆盖四种碎片、虚构理由、Latin 子串、完整姓名/昵称/别名与失败不留节点;`tests/auto-link-candidates.test.mjs` 覆盖完整表面、内部片段和派生缓存。不能仅按字符串把历史节点自动删除或归并——「主人一」也可能是真实昵称;先核对原始记忆,再在关系图中按证据改名、合并或删除。此修复不改写现有记忆或实体。
@@ -15,6 +15,7 @@ import { buildTermStats, rankCandidates } from './terminology.js'
15
15
  import { normalizeForIndex } from './normalize.js'
16
16
 
17
17
  const CACHE = new Map()
18
+ const CANDIDATE_VERSION = 2
18
19
 
19
20
  export function candidatesFile(libraryId) {
20
21
  if (!isSafeId(libraryId)) throw new Error('invalid library id')
@@ -71,11 +72,13 @@ function entitySurfaceMap(entities) {
71
72
  export function generateAnchorCandidates({ libraryId, now = Date.now(), force = false, policy = AUTOLINK_POLICY_V3 } = {}) {
72
73
  if (!isSafeId(libraryId)) throw new Error('invalid library id')
73
74
  const signature = statSignature(libraryId)
75
+ const policyKey = JSON.stringify(Object.entries(policy).sort(([a], [b]) => a.localeCompare(b)))
74
76
  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 })
77
+ if (!force && cached?.signature === signature && cached.policyKey === policyKey) return cached.value
78
+ const stored = force ? null : readStored(libraryId)
79
+ if (stored?.candidateVersion === CANDIDATE_VERSION && stored.revision === signature
80
+ && stored.policyKey === policyKey && Array.isArray(stored.tiers?.tier1)) {
81
+ CACHE.set(libraryId, { signature, policyKey, value: stored })
79
82
  return stored
80
83
  }
81
84
 
@@ -115,15 +118,17 @@ export function generateAnchorCandidates({ libraryId, now = Date.now(), force =
115
118
 
116
119
  const value = {
117
120
  version: 1,
121
+ candidateVersion: CANDIDATE_VERSION,
118
122
  libraryId,
119
123
  revision: signature,
120
124
  policyVersion: AUTOLINK_POLICY_VERSION,
125
+ policyKey,
121
126
  generatedAt: new Date(now).toISOString(),
122
127
  totals: { memories: rows.length, entities: entityItems.length, tier1: tiers.tier1.length, tier2: tiers.tier2.length },
123
128
  tiers,
124
129
  entities: { provisional, confirmed },
125
130
  }
126
- CACHE.set(libraryId, { signature, value })
131
+ CACHE.set(libraryId, { signature, policyKey, value })
127
132
  try { writeJson(candidatesFile(libraryId), value) } catch {}
128
133
  return value
129
134
  }
@@ -14,8 +14,11 @@ const FUNCTION_CHARS = new Set('的了是和与也就都很又还你我他她它
14
14
  // Measure-word templates: 一条/两只/这个/那些… A name never starts with one.
15
15
  const MEASURE_PREFIX = /^(一|两|三|几|每|这|那|半)?[条只把张个位次件场顿盘杯碗袋包串支根颗头匹群套双对份页篇段句声口]/
16
16
 
17
- const QUOTE_RE = /[「『《"']([^」』》"']{1,20})[」』》"']/g
18
- const INTRO_RE = /(?:叫|名叫|名字(?:是|叫|为)?|称呼(?:是|为)?|自称|username|nickname)([^\n。]{0,6})/gi
17
+ const QUOTED_SURFACE = /「([^」\n]+)」|『([^』\n]+)』|《([^》\n]+)》|“([^”\n]+)”|‘([^’\n]+)’|"([^"\n]+)"|'([^'\n]+)'/g
18
+ const INTRO_RE = /(?:名叫|名字(?:是|叫|为)?|称呼(?:是|为)?|自称|叫|\busername\b|\bnickname\b)[ \t]*:?[ \t]*/g
19
+ const SURFACE_RUN = /[\p{L}\p{N}_]+(?:[.-][\p{L}\p{N}_]+)*/gu
20
+ const START_SURFACE = new RegExp('^' + SURFACE_RUN.source, 'u')
21
+ const WHOLE_SURFACE = /^(?:[\u3400-\u9fff\uf900-\ufaff]+|[a-z0-9][a-z0-9._-]*)$/
19
22
 
20
23
  /** Terms whose surface shape cannot be a name on its own (ranking hint only). */
21
24
  export function looksGeneric(token) {
@@ -30,31 +33,43 @@ function isLatinTerm(term) {
30
33
  return /^[a-z0-9]/.test(term) && !/[\u3400-\u9fff\uf900-\ufaff]/.test(term)
31
34
  }
32
35
 
33
- function addNgrams(set, text, policy) {
34
- const value = String(text || '').normalize('NFKC').toLowerCase()
35
- for (const run of value.match(CJK_RUN) || []) {
36
+ // Keep weak statistics for the entire corpus, but give strong evidence only to
37
+ // an exact surface. Record CJK fragments even when the parent itself is longer
38
+ // than the statistical n-gram cap.
39
+ function collectSurface(value, evidence, fragments, policy) {
40
+ const surface = value.trim()
41
+ if (WHOLE_SURFACE.test(surface)) evidence.add(surface)
42
+ for (const run of surface.match(CJK_RUN) || []) {
36
43
  for (let size = policy.ngramCjkMin; size <= Math.min(policy.ngramCjkMax, run.length); size += 1) {
37
- for (let i = 0; i + size <= run.length; i += 1) set.add(run.slice(i, i + size))
44
+ for (let i = 0; i + size <= run.length; i += 1) {
45
+ const fragment = run.slice(i, i + size)
46
+ if (fragment !== surface) fragments.add(fragment)
47
+ }
38
48
  }
39
49
  }
40
- for (const token of value.match(LATIN_RUN) || []) {
41
- if (token.length >= policy.latinMin && token.length <= policy.latinMax) set.add(token)
42
- }
43
50
  }
44
51
 
45
- /** Quoted spans and name-intro neighbours, collected once per library. */
46
52
  function surfaceEvidence(docs, policy) {
47
53
  const quoted = new Set()
48
54
  const intro = new Set()
55
+ const fragments = new Set()
56
+ const fullRuns = new Set()
49
57
  for (const { text } of docs) {
50
- const source = String(text || '')
51
- let match
52
- QUOTE_RE.lastIndex = 0
53
- while ((match = QUOTE_RE.exec(source))) addNgrams(quoted, match[1], policy)
54
- INTRO_RE.lastIndex = 0
55
- while ((match = INTRO_RE.exec(source))) addNgrams(intro, match[1], policy)
58
+ const source = String(text || '').normalize('NFKC').toLowerCase()
59
+ const quotesByStart = new Map()
60
+ for (const match of source.matchAll(QUOTED_SURFACE)) {
61
+ const value = match.slice(1).find(part => part !== undefined)
62
+ quotesByStart.set(match.index, value)
63
+ collectSurface(value, quoted, fragments, policy)
64
+ }
65
+ for (const match of source.matchAll(INTRO_RE)) {
66
+ const start = match.index + match[0].length
67
+ const value = quotesByStart.get(start) ?? source.slice(start).match(START_SURFACE)?.[0]
68
+ if (value) collectSurface(value, intro, fragments, policy)
69
+ }
70
+ for (const run of source.match(SURFACE_RUN) || []) fullRuns.add(run)
56
71
  }
57
- return { quoted, intro }
72
+ return { quoted, intro, fragments, fullRuns }
58
73
  }
59
74
 
60
75
  function llrFor(term, tf, unigram, ngramTotals) {
@@ -213,7 +228,7 @@ function scoreOf(stat, { size, quoted, mixed, intro, titleBoost, lexiconTier1, l
213
228
  */
214
229
  export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, lexiconUser = new Set(), lexiconModel = new Set() } = {}) {
215
230
  const docs = entries.map(({ text, title }) => ({ text: `${title || ''}\n${text || ''}` }))
216
- const { quoted, intro } = surfaceEvidence(docs, policy)
231
+ const { quoted, intro, fragments, fullRuns } = surfaceEvidence(docs, policy)
217
232
  const size = Math.max(1, entries.length)
218
233
  const tier1 = []
219
234
  const tier2 = []
@@ -232,6 +247,7 @@ export function rankCandidates(entries, stats, { policy = AUTOLINK_POLICY_V3, le
232
247
  const isIntro = intro.has(term)
233
248
  const lexiconTier1 = lexiconUser.has(normalized)
234
249
  const lexiconModelHit = !lexiconTier1 && lexiconModel.has(normalized)
250
+ if (fragments.has(term) && !isQuoted && !isIntro && !lexiconTier1 && !fullRuns.has(term)) continue
235
251
  const titleBoost = stat.titleDf >= policy.minTitleDf
236
252
  const row = {
237
253
  term,
@@ -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:1028', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
57
+ { layer: 'temporary-map', file: 'lib/private.js:1040', 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' },