dsh-memu-memory 1.2.7 → 1.2.9

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 (106) hide show
  1. package/AGENTS.md +1 -1
  2. package/CHANGELOG.md +472 -0
  3. package/README.md +10 -15
  4. package/README.zh.md +10 -15
  5. package/docs/memory-semantics.md +23 -3
  6. package/lib/backup.js +155 -26
  7. package/lib/binding-diagnostics.js +1 -2
  8. package/lib/budget.js +31 -9
  9. package/lib/client.js +221 -128
  10. package/lib/commitment.js +138 -0
  11. package/lib/consolidation-ledger.js +5 -2
  12. package/lib/consolidation-receipt.js +2 -0
  13. package/lib/consolidation-worker.js +3 -0
  14. package/lib/curator-policy.js +23 -0
  15. package/lib/cycle.js +8 -4
  16. package/lib/embedding-download.js +168 -28
  17. package/lib/embedding-runtime.js +76 -17
  18. package/lib/engine.js +0 -6
  19. package/lib/freshness.js +24 -0
  20. package/lib/graph.js +139 -11
  21. package/lib/index.js +71 -20
  22. package/lib/inject.js +167 -17
  23. package/lib/lexicon.js +62 -17
  24. package/lib/local-vector-service.js +25 -2
  25. package/lib/media.js +49 -12
  26. package/lib/memory.js +1202 -123
  27. package/lib/memu.js +4 -0
  28. package/lib/paths.js +0 -7
  29. package/lib/preset-scope.js +6 -1
  30. package/lib/private.js +50 -10
  31. package/lib/prompts/private-consolidation.mixed.md +2 -2
  32. package/lib/prompts/private-consolidation.rp.md +6 -1
  33. package/lib/prompts/private-policy.rp.md +4 -0
  34. package/lib/prompts/system-guide.rp.md +3 -0
  35. package/lib/prompts.js +0 -7
  36. package/lib/recall-cache.js +10 -2
  37. package/lib/rpc.js +104 -19
  38. package/lib/snippet.js +41 -0
  39. package/lib/state.js +109 -30
  40. package/lib/stats.js +2 -2
  41. package/lib/temporal.js +348 -0
  42. package/lib/text-retrieval.js +191 -44
  43. package/lib/text-similarity.js +205 -24
  44. package/lib/tokenizer-v2.js +0 -24
  45. package/lib/tools.js +81 -4
  46. package/lib/vector-migration.js +15 -0
  47. package/lib/vector-profile.js +81 -8
  48. package/lib/visibility.js +0 -4
  49. package/lib/webui/standalone.css +17 -22
  50. package/lib/webui/standalone.js +27 -9
  51. package/lib/webui.js +4 -4
  52. package/package.json +3 -2
  53. package/scripts/acceptance-local.mjs +2 -2
  54. package/scripts/bench-recall.mjs +2 -2
  55. package/scripts/check-all.mjs +3 -1
  56. package/scripts/check-i18n.mjs +35 -1
  57. package/scripts/check-seed-compat.mjs +1 -1
  58. package/scripts/migrate-visibility.mjs +3 -3
  59. package/scripts/prune-sessions.mjs +34 -0
  60. package/scripts/prune-vectors.mjs +24 -0
  61. package/tests/appendix-b.test.mjs +5 -4
  62. package/tests/audit-batch3.test.mjs +247 -0
  63. package/tests/audit-regression.test.mjs +2 -2
  64. package/tests/backup.test.mjs +85 -85
  65. package/tests/browser.test.mjs +6 -1
  66. package/tests/client-render.test.mjs +2 -2
  67. package/tests/commitment.test.mjs +144 -0
  68. package/tests/consolidation-fork.test.mjs +3 -3
  69. package/tests/curator-clusters.test.mjs +18 -0
  70. package/tests/curator-pairing.test.mjs +59 -16
  71. package/tests/disclosure.test.mjs +34 -17
  72. package/tests/dynamic-rrf.test.mjs +22 -19
  73. package/tests/dynamic-threshold.test.mjs +52 -0
  74. package/tests/fact-version.test.mjs +146 -0
  75. package/tests/fixtures/tokenizer-cases.mjs +27 -0
  76. package/tests/graph-cascade.test.mjs +29 -0
  77. package/tests/graph.test.mjs +45 -0
  78. package/tests/help-page.test.mjs +1 -1
  79. package/tests/inject-conflict.test.mjs +112 -0
  80. package/tests/inject-guide.test.mjs +5 -3
  81. package/tests/inject.test.mjs +2 -2
  82. package/tests/injection-intent-budget.test.mjs +92 -0
  83. package/tests/lexical-bm25.test.mjs +171 -0
  84. package/tests/lexicon-frequency.test.mjs +17 -1
  85. package/tests/lexicon-inject.test.mjs +21 -0
  86. package/tests/lexicon-perf.test.mjs +37 -9
  87. package/tests/lexicon-scope.test.mjs +2 -2
  88. package/tests/lexicon-ui.test.mjs +1 -1
  89. package/tests/managed-memory.test.mjs +19 -0
  90. package/tests/memory-chain.test.mjs +140 -0
  91. package/tests/memory-fields.test.mjs +134 -0
  92. package/tests/memu-resident.test.mjs +33 -0
  93. package/tests/ops-hardening.test.mjs +209 -0
  94. package/tests/package-shipping.test.mjs +4 -0
  95. package/tests/prompt-semantics.test.mjs +51 -0
  96. package/tests/query-decompose.test.mjs +62 -0
  97. package/tests/recall-cache.test.mjs +4 -2
  98. package/tests/recall-intent.test.mjs +123 -0
  99. package/tests/slot-similarity.test.mjs +153 -0
  100. package/tests/speaker-provenance.test.mjs +120 -0
  101. package/tests/state-gc.test.mjs +34 -0
  102. package/tests/state.test.mjs +2 -2
  103. package/tests/temporal.test.mjs +124 -0
  104. package/tests/tokenizer-v2.test.mjs +1 -1
  105. package/tests/vector-gc.test.mjs +37 -0
  106. package/tests/webui.test.mjs +27 -0
package/README.md CHANGED
@@ -23,14 +23,18 @@
23
23
 
24
24
  ---
25
25
 
26
- `dsh-memu-memory` is built for long-form RP and companion chats. It gives a DSH conversation a memory that behaves like memory instead of a log: three retention layers that fade, a first-turn anchor plus at most one per-turn recall, provenance that cannot be quietly upgraded from "I inferred it" to "they said it", contradictions that wait for a decision instead of both being read as true, near-identical facts collapse to one entry and one recall seat, and an optional relationship graph with evidence. Speakers, characters, worlds and story branches form hard boundaries, and what a character is allowed to know stays separate from what actually happened.
26
+ `dsh-memu-memory` is built for long-form RP and companion chats. It gives a DSH conversation a memory that behaves like memory instead of a log: three retention layers that fade, a first-turn anchor plus at most one per-turn recall, provenance that cannot be quietly upgraded from "I inferred it" to "they said it", contradictions that either wait for a decision or — when explicitly versioned — stay side by side with a conflict card instead of being silently merged, near-identical facts collapse to one entry and one recall seat, and an optional relationship graph with evidence. Speakers, characters, worlds and story branches form hard boundaries, and what a character is allowed to know stays separate from what actually happened.
27
27
 
28
28
  It is **local-first by default**. The default `agent` backend stores full text in JSON indexes and recalls lexically — no Python, no embedding service, no API key. The `api` backend switches recall to the optional, pinned MemU engine (vector search). MemU is a plugin for people who want it, not a requirement for the plugin to start.
29
29
 
30
30
  > [!WARNING]
31
31
  > **Early-stage software.** This plugin is still early and may contain unforeseen errors, bugs or breaking changes. Back up your data, and please [report an issue](https://github.com/Tkingxiao/dsh-memu-memory/issues) or send a pull request — feedback helps the project improve.
32
32
 
33
- > **Status:** 1.2.6. The first public release was 1.0.0. The manual now lives in [`docs/`](docs/), with [`AGENTS.md`](AGENTS.md) as a short index. Back up `~/.dsh/dsh-memu-memory` before upgrades, and read [Compatibility & limits](#compatibility--limits) before storing data you cannot re-create.
33
+ > **Status:** 1.2.9. The first public release was 1.0.0. The manual now lives in [`docs/`](docs/), with [`AGENTS.md`](AGENTS.md) as a short index. Back up `~/.dsh/dsh-memu-memory` before upgrades, and read [Compatibility & limits](#compatibility--limits) before storing data you cannot re-create.
34
+
35
+ ## Benchmark
36
+
37
+ The public [chat-memory-benchmark](https://github.com/Ornn8/chat-memory-benchmark) full 714-question run (2026-11-06, `dys-router / deepseek-v4.1-flash`, high reasoning) passed **653 / 714 (91.46%)**. The run's actual measured memory cost was **¥16.05**; the full run, including non-memory overhead, cost **¥24.45** (75,517,851 tokens total, at the provider's off-peak rate) — measured end to end, not extrapolated from a single session.
34
38
 
35
39
  ## Screenshots
36
40
 
@@ -60,10 +64,10 @@ All screenshots are the real WebUI on isolated example data, not anyone's memori
60
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.
61
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.
62
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.
63
- - **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. A memory that says "tomorrow" is stored as the dated form, so an appointment does not come back every year.
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.
64
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.
65
- - **Provenance is a fact, not a style.** Every entry carries `source` (`user_said` / `inferred` / `imagined` / `told`), `confidence`, `accuracy`, and disclosure rules. A vague recollection cannot impersonate a quote.
66
- - **Contradictions wait.** A write that rewrites or contradicts an existing entry lands as `pending_review`: it is not injected, not recalled, and appears in a review queue until someone accepts or rejects it.
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.
70
+ - **Contradictions do not get silently merged.** An ordinary contradiction still lands as `pending_review`: it is not injected, not recalled, and appears in a review queue until someone accepts or rejects it. When the writer explicitly marks two statements as versions of one fact (`conflicts_with`), both stay active, are recalled together and surface as a conflict card; an explicit `supersedes` retires the old row without deleting its text.
67
71
  - **Secrets stay excluded.** `secret` visibility, group-chat channels, characters, worlds, branches and `knownBy` all constrain reads and edits. Automatic recall never injects a `secret` memory, and a `secret` is still readable by an explicit recall from the same folder — it hides a memory from the prompt, it is not a lock. What actually separates two conversations in one folder is the `context` scope (`channelId` / `characterId` / `worldId` / `branchId`); a blank scope on both sides means one shared scope, which is the point of a folder. The old `visibility: 'session'` level is gone — reading turns it into `shared` with its `context` untouched, and `node scripts/migrate-visibility.mjs` rewrites libraries that still store it (`--apply`, backs up first).
68
72
  - **People and stories are structured.** Group chat uses stable `speakerId` / `channelId`, not display names. RP uses `characterId` / `worldId` / `branchId`. Relationships are edges with a note and confidence, entities can be renamed without rewriting memory bodies, and the current relationship state (familiarity, trust, warmth, boundaries, promises) is a snapshot that keeps its history and evidence.
69
73
  - **Images are pointers and captions, not pretend vision.** Attachments are deduplicated by SHA-256, quota-limited and tiered; an image without a description is remembered as "received an image", never as a scene the model did not see.
@@ -86,16 +90,7 @@ Four real long sessions from this machine were replayed read-only (no new chat)
86
90
 
87
91
  Below-threshold turns on the two small sessions can still wake through starvation; on the 2,000+ event sessions they do not. None of the four had new human input after its real cursor, so none would fork again immediately.
88
92
 
89
- Provider-reported usage from real forks: one consolidation costs about **41k–217k input tokens** (including cache reads; it depends on memory-tool steps) and **0.8k–3.4k output**. At one 4-hour long session per day and 2–6 effective consolidations:
90
-
91
- | Consolidations/day | Monthly input | Monthly output |
92
- |---|---:|---:|
93
- | 2 | ~5.6M | ~0.11M |
94
- | 4 | ~11M | ~0.23M |
95
- | 6 | ~17M | ~0.34M |
96
- | 6 (worst measured fork each) | ~39M | ~0.7M |
97
-
98
- For scale, the whole 4-hour session tree measured here consumed 132M input and 1.28M output in one day, so active-memory forks are about **0.2%–1%** of the total. These are token counts, not money; cache reads are usually billed at a lower rate. The exact figure depends on turn count, memory-tool steps and how often the session actually goes idle.
93
+ End-to-end accuracy and the measured cost of the 714-question run are in [Benchmark](#benchmark).
99
94
 
100
95
  ## One WebUI
101
96
 
package/README.zh.md CHANGED
@@ -23,14 +23,18 @@
23
23
 
24
24
  ---
25
25
 
26
- `dsh-memu-memory` 面向长篇 RP 与陪伴对话,给 DSH 一份「像记忆」的记忆,而不是一本日志:三种留存层会淡;首轮有锚点,之后每个用户回合最多召回一次;来源不能被悄悄从「我推断」升级成「对方说过」;互相矛盾的记忆会挂起等待裁决,而不是两条都被当成真的;几乎相同的事实只入一条、召回时同簇只占一席;关系可以是一条带证据的边。说话人、角色、世界线与剧情分支构成硬边界,角色「知道什么」与实际发生过什么分开保存。
26
+ `dsh-memu-memory` 面向长篇 RP 与陪伴对话,给 DSH 一份「像记忆」的记忆,而不是一本日志:三种留存层会淡;首轮有锚点,之后每个用户回合最多召回一次;来源不能被悄悄从「我推断」升级成「对方说过」;互相矛盾的记忆会挂起等待裁决,明确标成同一事实的两个版本则并排保留并给出冲突卡,而不是被悄悄合并;几乎相同的事实只入一条、召回时同簇只占一席;关系可以是一条带证据的边。说话人、角色、世界线与剧情分支构成硬边界,角色「知道什么」与实际发生过什么分开保存。
27
27
 
28
28
  默认**本地优先**。`agent` 后端把完整正文放在 JSON 索引里、用词法检索——不需要 Python、embedding 服务或 API key。`api` 后端才把检索交给可选的、锁定版本的 MemU 引擎(向量)。MemU 是「想要就用」的后端,不是插件能否启动的前提。
29
29
 
30
30
  > [!WARNING]
31
31
  > **早期版本提示。** 本插件仍处于早期阶段,可能存在无法预见的错误、bug 或不兼容变更。请先备份数据;欢迎[提交 Issue](https://github.com/Tkingxiao/dsh-memu-memory/issues) 或 PR 帮助改进。
32
32
 
33
- > **状态:** 1.2.6。首个公开发布版本为 1.0.0。细节文档已迁到 [`docs/`](docs/),[`AGENTS.md`](AGENTS.md) 只做索引。升级前请备份 `~/.dsh/dsh-memu-memory`;如果要存无法重建的数据,请先读[兼容性与边界](#兼容性与边界)。
33
+ > **状态:** 1.2.9。首个公开发布版本为 1.0.0。细节文档已迁到 [`docs/`](docs/),[`AGENTS.md`](AGENTS.md) 只做索引。升级前请备份 `~/.dsh/dsh-memu-memory`;如果要存无法重建的数据,请先读[兼容性与边界](#兼容性与边界)。
34
+
35
+ ## 基准测试
36
+
37
+ 公开的 [chat-memory-benchmark](https://github.com/Ornn8/chat-memory-benchmark) 714 题完整卷(2026-11-06,`dys-router / deepseek-v4.1-flash`,high 思考强度)通过 **653 / 714(91.46%)**。同一轮**实测记忆成本为 ¥16.05**;包含非记忆开销的总成本为 **¥24.45**(总 token 75,517,851,谷价),均为端到端实测,不是按单次会话外推。
34
38
 
35
39
  ## 界面
36
40
 
@@ -58,10 +62,10 @@
58
62
 
59
63
  - **三层,一条时间线。** `short_term` 草稿默认 72 小时到期;`long_term` 是记忆主体;`must_remember` 需要理由与来源,按 365 天半衰并带 0.35 强度地板,可以**边缘化**,但不会为腾名额被自动删除。
60
64
  - **召回是一个瞬间,不是一次倾倒。** 新会话或压缩后的第一个回合得到锚点块(pin / core / global 分段预算);之后每个用户回合最多一次召回。去重与 token 预算由代码执行,不交给提示词自觉。
61
- - **日期要么是纪念日,要么是一天。** `MM-DD` 每年复发(生日);`YYYY-MM-DD` 在前一天和当天各响一次,之后就算用过了。说「明天」的记忆存成带年份的日期,不会变成每年都冒出来的周年。
65
+ - **日期要么是纪念日,要么是一天。** `MM-DD` 每年复发(生日);`YYYY-MM-DD` 在前一天和当天各响一次,之后就算用过了。说「今天 / 明天 / 下周X / 月底」的相对日期会按这一轮的场景时间换算成绝对日期再存;说「明天」的记忆存成带年份的日期,不会变成每年都冒出来的周年。
62
66
  - **记忆会不均匀地淡。** 新近、访问次数、峰终、首因、习惯化、闪光灯记忆的准确度共同参与强度。情绪用四项构成(joy / anger / sorrow / fear,和为 1)加唤醒度 `arousal`(强度)与掌控感 `dominance` 描述;「嫉妒」这类复合情绪是四项的具名混合比例,不是新维度。情绪只影响召回排序:不进注入文本,也不改记忆正文。门控是三条独立条件的 OR——主导项占比 ≥ 0.35、`|arousal − 0.35| ≥ 0.1`、`|dominance| ≥ 0.25`;三条都不满足时两项乘数恒为 1。旧条目没有 emotion 时继续走原来的 valence 路径,不从旧 valence 反推四轴。一条生动但可能记错的记忆会显示「细节未必准」,而不是假装确定。
63
- - **来源是事实,不是文风。** 每条记忆带 `source`(`user_said` / `inferred` / `imagined` / `told`)、`confidence`、`accuracy` 与说出口径。模糊的推断不能冒充原话。
64
- - **矛盾先挂起。** 与已有记忆同题改写或说法相反的新条进入 `pending_review`:不注入、不召回,只出现在复核队列,等人或整理作业裁决。
67
+ - **来源是事实,不是文风。** 每条记忆带 `source` / `source_kind`(`user_said` / `assistant_said` / `told` / `imagined` / `inferred` / `tool`)、`speaker_id`、`confidence`、`accuracy` 与说出口径。模糊的推断不能冒充原话,助手自己的承诺和计划也不能记成用户说的。
68
+ - **矛盾不会被悄悄合并。** 普通矛盾仍进入 `pending_review`:不注入、不召回,只出现在复核队列,等人或整理作业裁决。写入方明确把两种说法标成同一事实的版本(`conflicts_with`)时,两条都保持 active、一起召回并注入一张冲突卡;显式 `supersedes` 才退休旧条,正文不删。
65
69
  - **秘密不进自动召回。** `secret`、群聊频道、角色、世界线、剧情分支与 `knownBy` 共同约束读写;`secret` 永远不会被自动注入,但同文件夹里**主动检索仍然读得到**——它挡的是「自己冒出来」,不是保险箱。真正把同一文件夹里的两段对话隔开的是 `context` 作用域(`channelId` / `characterId` / `worldId` / `branchId`);两边都没填就是同一个作用域,这正是「文件夹」的含义。旧的 `visibility: 'session'` 级别已删除:读到就按 `shared` 处理、`context` 原样保留,仍存着该级别的库用 `node scripts/migrate-visibility.mjs` 重写(`--apply` 才写,先备份)。
66
70
  - **人与故事是有结构的。** 群聊用稳定的 `speakerId` / `channelId`,不拿显示名当身份;RP 用 `characterId` / `worldId` / `branchId` 隔离知识。关系边有理由和置信度,实体改名不动记忆正文,关系当前状态(熟悉、信任、温度、边界、承诺)是带证据和历史快照。
67
71
  - **图片是指针加描述,不是假装能看图。** 附件按 SHA-256 去重、有配额、分三级留存;没有描述时只记「收到一张图片」,绝不编造画面。
@@ -84,16 +88,7 @@
84
88
 
85
89
  两条小会话的未达分数回合仍可能因饥饿唤醒;2000 条事件以上的大会话不会。四个会话在真实游标之后都没有新的真人输入,因此不会立即再 fork。
86
90
 
87
- 从真实 fork 的 provider usage 汇总:一次整理约 **4.1 万~21.7 万 input tokens**(含缓存读,取决于记忆工具步数)+ **0.8k~3.4k output**。按每天一次 4 小时长会话、每天有效整理 2~6 次:
88
-
89
- | 每天整理次数 | 每月 input | 每月 output |
90
- |---|---:|---:|
91
- | 2 次 | ~5.6M | ~0.11M |
92
- | 4 次 | ~11M | ~0.23M |
93
- | 6 次 | ~17M | ~0.34M |
94
- | 6 次(都按实测最贵的单次) | ~39M | ~0.7M |
95
-
96
- 作为参照,今天这棵 4 小时会话树实测 132M input + 1.28M output/日,主动记忆整理约占 **0.2%~1%**。以上是 token 量,不是金额;缓存读通常按更低单价计费。实际取决于回合数、记忆工具步数和会话真正空闲的次数。
91
+ 714 题完整卷的通过率与实测成本见[基准测试](#基准测试)。
97
92
 
98
93
  ## 一个 WebUI
99
94
 
@@ -20,7 +20,7 @@
20
20
  - 移出永久记忆 = **边缘化**:`marginalized=true`、`strength × 0.2`、召回排序里 `marginalized` 乘以 0.35(`recallPenalty` 字段仅作历史记录,当前不参与排序),**不删除**;条目仍在库里,`marginalReason` 在侧边栏可见(替代人类闸门的**事后**监督)。
21
21
  - **unpin 由模型自己判断,侧边栏没有标记按钮、用户不参与。** 三重护栏:① `reason` 必填、第一人称、去空白后 ≥ 20 字符;② 每会话配额 `unpinBudgetPerSession`(默认 2);③ 冷却 `unpinCooldownMinutes`(默认 3)。放行后记 `unpinnedBy: model`、`unpinnedAt`、`originalPinSource`(保留原 pinSource 以便复 pin)。
22
22
  - 正当的 unpin 只有两种:想起它本身正在伤人;它已经不再是我的一部分。不正当的:inconvenient、不想面对、用户这轮没提、永久记忆快满了。**这个区别要写进提示词。**
23
- - 矛盾检测:同库同题改写或说法相反 → 新条挂 `pending_review` + `reviewReason` + `conflictingWith`,**不进注入不进召回**,等 `listReviews` / `resolveReview` 裁决(§3.9)。
23
+ - 矛盾检测:同库同题改写或说法相反 → 新条挂 `pending_review` + `reviewReason` + `conflictingWith`,**不进注入不进召回**,等 `listReviews` / `resolveReview` 裁决(§3.9)。写入方显式用 `conflicts_with`(或同一显式 `fact_key` 再次写入)声明“同一事实的两个版本”时是例外:两条都保持 active、互指并成对召回,注入为冲突卡(§8.17);明确取代用 `supersedes`。
24
24
 
25
25
  ### 8.3 全局记忆
26
26
 
@@ -40,7 +40,7 @@
40
40
 
41
41
  - 静态 guide 与动态记忆都走 plugin 消息;当前版本不再注册本插件的 system prompt 段。所有会话(含 `persona` `complete: true`)统一由 `lib/inject.js` 的 `ensureUnifiedGuide` 在**回合首步**投放一条 `<memory-guide rules="…">` 插件消息;`rulesKey` 由协议版本、domain 和实际渲染正文计算,domain/覆盖/默认稿变化或压缩丢失(`guideLost`)时在下一个合法首步替换,同一规则不逐回合重复。旧 binding 只有 `guideMessageAt`、没有 `guideRulesKey` 时视为旧版,补投一次;失败 fail-open,不写新版本。
42
42
  - 首轮锚点 + 每用户回合最多一次;长工具回合仅有新的真实人类消息批次时追加一次,普通工具步骤不触发。私有优先、全局补充;冲突时私有胜。
43
- - **锚点和本回合召回只放标题卡**(1.2.2):`formatPrivateTitle` / `formatGlobalTitle` 输出 `[id]`、标题、`source`、owner、layer、日期/年龄、marginalized/open_loop、accuracy/uncertainty/disclosure 与附件计数,**不输出正文与附件 caption**。工具返回、记忆抽屉与浏览器仍是全文;要正文就按标题关键词或方括号里的 id 调 `memu_private_recall` / `memu_global_recall`。标题为空时回退正文前 40 字;`imagined`、`never_say` 等语义标签不能因为标题化而丢失。跨库召回开启时(§8.15),private 标题卡可能来自其它同领域库;id 仍全局唯一,按 id 取正文仍走 `memu_private_recall`,写入仍只落在当前库。
43
+ - **锚点和本回合召回只放标题卡**(1.2.2):`formatPrivateTitle` / `formatGlobalTitle` 输出 `[id]`、标题、`source`、owner、layer、日期/年龄、marginalized/open_loop、accuracy/uncertainty/disclosure 与附件计数,**不输出正文与附件 caption**。工具返回、记忆抽屉与浏览器仍是全文;要正文就按标题关键词或方括号里的 id 调 `memu_private_recall` / `memu_global_recall`。标题为空时回退正文前 40 字;`imagined` 等语义标签不能因为标题化而丢失。`never_say` 不进入自动注入面,`only_if_asked` 只在 boundary 查询里自动放行(§8.17);显式召回仍可读两者。跨库召回开启时(§8.15),private 标题卡可能来自其它同领域库;id 仍全局唯一,按 id 取正文仍走 `memu_private_recall`,写入仍只落在当前库。
44
44
  - **条件式时效提示(工单 D)**:本回合召回块已经生成后,若其中至少一条真正进入文本的条目带时间敏感信号——`salientDate` 是已过去的 `YYYY-MM-DD`(年度 `MM-DD` 不算)、标题/正文命中固定词表 `最新|最近|现在|目前|今年|版本|价格|天气|新闻|比分|汇率`、或 `updatedAt||createdAt` 距现在 ≥ `freshnessDays`(`owner=about_project` 的工程事实不算年龄)——且 `freshnessHint !== false`、用户文本长度 ≥ `minUserChars`,就在最后一个 `</memory-context>` 之后追加**一个** `<memory-freshness>` 块,N 为去重后的 stale 条数。提示与召回共用 `turnTokens` 预算:放不下就丢弃提示,召回本身仍成功(fail-open,计算异常只 `warn`)。它只说「若你的会话里有可用的搜索工具就先核实」,**不声称** `web_search` 一定存在(工具面不确定性见 `docs/host-api.md` §6.8),也不改 `<memory-guide>`/`rulesKey`。`freshnessDays` 默认 30,范围 `[1,3650]`;`freshnessHint` 默认开。
45
45
  - **rule 是前言,不是页脚**:`buildAnchor` 先输出锚点头与 `[rule]`,再输出 private/global/short_term 各段;inbound 路径的锚点之后直接衔接 `<memory-context>`,中间不再隔一条规则。
46
46
  - **`injectedIds` 只能记真正进入文本的条目**,否则从未展示的记忆被白白压制 8 轮。
@@ -79,7 +79,7 @@
79
79
  | 附件像素 | ✅ | ❌(`hidden: true`;`never_say` 的 caption 也不回显) |
80
80
 
81
81
  - 所以 `secret` 的实际边界是「**不被自动注入、不当回响源、附件不出像素**」;同一文件夹里另一个会话**主动检索时照样能拿到**。它挡的是「自己冒出来」,不是「别人查到」。要「跨会话绝不外泄」,靠 §8.7 的上下文边界,不是 `secret`。
82
- - 「只有我知道」= `disclosure: never_say`(不许说出口)+ `secret`(不许自动浮现)两个字段的组合,不是加密。侧边栏和记忆墙始终能看到正文——这是**事后监督**的设计,不是疏漏。
82
+ - 「只有我知道」= `disclosure: never_say`(不进入任何自动注入面,显式召回仍可读)+ `secret`(不自动浮现、附件不出像素)两个字段的组合,不是加密。侧边栏和记忆墙始终能看到正文——这是**事后监督**的设计,不是疏漏。
83
83
  - 全局 curator 读的是会话日志与全局库,不读私有库条目(`compactGlobalIndex`),所以 `secret` 不会被复制进「每会话都注入」的全局记忆;跨文件夹(不同库)之间的私有召回**默认隔离**,只有显式打开 `crossLibraryRecall` 才会合并同领域库,且只读——见 §8.15。
84
84
 
85
85
  ### 8.7 上下文作用域:`channelId / characterId / worldId / branchId` + `knownBy`
@@ -201,3 +201,23 @@
201
201
 
202
202
  ---
203
203
 
204
+
205
+ ---
206
+
207
+ ### 8.17 1.2.8:时间、版本、来源、承诺与召回意图
208
+
209
+ 这一节只描述新增字段与策略,不改原有三层、可见范围与注入纪律。所有字段对旧数据都是**可选**:缺字段按空处理,不强制迁移,写入时补齐。
210
+
211
+ **时间**:写入时按这一轮的逻辑时间解析相对日期,落在 `event_time` / `observed_at`(ISO)、`absolute_date`(YYYY-MM-DD)、`date_precision`(`day|month|year|unknown`)、`date_source`(`explicit|relative`)。逻辑时间优先 `context.occurredAt`,其次会话 `sceneTime`,最后才是墙上时钟;解析失败不猜,只有确实出现相对时间词时才标 `date_precision=unknown`。原文保留在 `content`,不改写用户原话。`valid_from` / `valid_to` 是可选的有效窗口(`valid_from <= 今天 <= valid_to`),缺字段的旧条目照常召回;旧复核路径写的 `validFrom/validTo` 也会被识别。召回查询里的“明天/下周三/月底”同样先解析成绝对日期再检索,时间题注入按 `absolute_date` 最近优先排序。
212
+
213
+ **版本与冲突**:每条新记忆都有 `fact_key`(显式传入或由 `owner + 标题` 归一化)与 `version`。显式 `conflicts_with` 或“同一显式 fact_key 的再次写入”会让新旧两条都保持 `active`、互指 `conflicts_with`,召回命中一侧时另一侧成对带回,注入成一张 200 字内的冲突卡(“未确认哪版为准”)。显式 `supersedes` 才是取代:旧条 `status=superseded`、`valid_to` 落日期、正文与标题不删不改。兼容补充仍走 `memu_private_update`,保留原 id,不增加版本。旧的无关系字段的冲突仍按原路径进入 `pending_review`,行为不变。
214
+
215
+ **来源**:新增 `speaker_id`、`source_kind`(`user_said|assistant_said|told|imagined|inferred|tool`)、`quote_span`(`{seq, turn, textHash}`)、`storyline_id`、`branch_id`、`known_by`。`speaker_id` 显式 > `context.speakerId` > 按 `source_kind` 的 `user/assistant/tool/unknown`;不猜。助手自己的承诺、计划、事实用 `assistant_said`,不能记成用户说的。查询“我说过/你说过/他说的”时按说话人过滤:只排除明确属于别人的条目,缺 speaker 的旧条目保留。注入标题卡会显示非默认的 `speaker=`。
216
+
217
+ **承诺**:`commitment = {counterparty, action, due_at, status, closed_by, evidence_seq}`,`status` 是 `open|done|cancelled|expired`,也是权威;`open_loop` 只做兼容并随 `status` 同步。`open_loop=true` 的旧写法会派生一条 `open` 承诺,`due_at` 取本轮已解析日期。到期/临期(逾期、今天、明天)的未完成承诺最多 3 条、按 `due_at` 升序进一张 `[commitment]` 小卡;远期承诺不占每回合预算。`dueOpenLoops` 也优先看 `commitment.status` 与 `due_at`。
218
+
219
+ **召回意图**:`lib/text-retrieval.js` 的 `detectQueryIntent` / `decomposeQuery` 把查询分成 `date|entity|conflict|commitment|boundary|general`;日期与引号/`@`/已知实体名会被拆成可检索词。各意图的候选上限见 `lib/budget.js` 的 `RECALL_INTENT_TOPK`(general 5、date/entity 8、conflict 6、commitment/boundary 5),调用方显式给的更大 topK 不被压低,封顶 20。命中条目沿 `links` 扩展一跳(最多 2 条,实体题 3 条),只沿显式关系走。`disclosure` 现在是“何时能自动出现”的门:`never_say` 不进任何自动注入面(锚点、自动召回、提醒),`only_if_asked` 只在 `boundary` 意图的查询里自动放行;显式 `memu_private_recall` 仍可读两者。
220
+
221
+ **可观测性**:`getState` 增加 `recallCache` 段(`hits/misses/evictions/errors/staleSkipped/generations/...`);`staleSkipped` 统计 TTL 过期、代数清理与按 query 失效时被丢弃的缓存条目。
222
+
223
+ 守卫:`tests/temporal.test.mjs`、`tests/memory-fields.test.mjs`、`tests/fact-version.test.mjs`、`tests/inject-conflict.test.mjs`、`tests/speaker-provenance.test.mjs`、`tests/commitment.test.mjs`、`tests/query-decompose.test.mjs`、`tests/recall-intent.test.mjs`、`tests/injection-intent-budget.test.mjs`、`tests/memory-chain.test.mjs`。
package/lib/backup.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import crypto from 'node:crypto'
2
2
  import fs from 'node:fs'
3
3
  import path from 'node:path'
4
- import { spawnSync } from 'node:child_process'
4
+ import { spawn } from 'node:child_process'
5
5
  import {
6
6
  backupsDir, dataDir, ensureDir, indexDir, isSafeId, librariesDir,
7
7
  readJson, warn, withFileLock, writeJson,
8
8
  } from './paths.js'
9
9
 
10
10
  /**
11
- * 本地向量施工文档 §14.9 - safe latest-three backup retention.
11
+ * Local-vector backup policy - safe latest-three backup retention.
12
12
  *
13
13
  * One rule, one place. Every managed backup of the current data root is created
14
14
  * by createBackup(), published atomically, and only then may the oldest
@@ -113,14 +113,69 @@ function hasSqliteHeader(file) {
113
113
 
114
114
  // ---------------------------------------------------------------- lock & leases
115
115
 
116
+ // 同进程可重入的锁集合。paths.js 的 withFileLock 是纯同步的(try { return action() }
117
+ // finally 立刻删锁文件):直接把 async action 传进去,锁会在第一个 await 之前
118
+ // 就释放,restore 的 safety backup 与 prune 便失去互斥。这里自己管理同一把
119
+ // .backup.lock,持锁直到 action 的 Promise 完成;同步 action 仍返回同步结果。
120
+ const heldBackupLocks = new Set()
121
+
122
+ function acquireBackupLock() {
123
+ const lock = path.resolve(lockAnchor()) + '.lock'
124
+ if (heldBackupLocks.has(lock)) return () => {}
125
+ ensureDir(backupsDir())
126
+ const until = Date.now() + 500
127
+ let fd
128
+ while (fd === undefined) {
129
+ try {
130
+ fd = fs.openSync(lock, 'wx', 0o600)
131
+ fs.writeFileSync(fd, String(process.pid))
132
+ } catch (error) {
133
+ if (error?.code !== 'EEXIST') throw error
134
+ try {
135
+ const owner = Number(fs.readFileSync(lock, 'utf8'))
136
+ if (Number.isSafeInteger(owner) && owner > 0 && !pidAlive(owner)) { fs.unlinkSync(lock); continue }
137
+ } catch {}
138
+ if (Date.now() >= until) {
139
+ const busy = new Error('memory store is busy: backup; retry the operation')
140
+ busy.code = 'DSH_MEMU_STORE_BUSY'
141
+ throw busy
142
+ }
143
+ pause(10)
144
+ }
145
+ }
146
+ heldBackupLocks.add(lock)
147
+ return () => {
148
+ heldBackupLocks.delete(lock)
149
+ try { fs.closeSync(fd) } catch {}
150
+ for (let attempt = 0; ; attempt += 1) {
151
+ try { fs.unlinkSync(lock); break } catch (error) {
152
+ if (error?.code === 'ENOENT') break
153
+ if (['EPERM', 'EBUSY', 'EACCES'].includes(error?.code) && attempt < 5) { pause(RETRY_MS * (attempt + 1)); continue }
154
+ warn('backups: could not release backup lock (' + (error?.code || 'io error') + ')')
155
+ break
156
+ }
157
+ }
158
+ }
159
+ }
160
+
116
161
  /**
117
162
  * The one lock that coordinates create/delete/restore/prune. It is reentrant
118
- * inside this process (withFileLock keeps a held set), so a restore may create
119
- * its own safety backup and prune while still holding it.
163
+ * inside this process, so a restore may create its own safety backup and prune
164
+ * while still holding it. A synchronous action returns its value synchronously;
165
+ * an async action returns a Promise and the lock stays held until it settles.
120
166
  */
121
167
  export function withBackupLock(action) {
122
- ensureDir(backupsDir())
123
- return withFileLock(lockAnchor(), action)
168
+ const release = acquireBackupLock()
169
+ let result
170
+ try {
171
+ result = action()
172
+ } catch (error) {
173
+ release()
174
+ throw error
175
+ }
176
+ if (result && typeof result.then === 'function') return Promise.resolve(result).finally(release)
177
+ release()
178
+ return result
124
179
  }
125
180
 
126
181
  function pidAlive(pid) {
@@ -274,14 +329,81 @@ let enginePythonCache = null
274
329
  /** Forget the cached interpreter probe (tests use this between scenarios). */
275
330
  export function resetBackupPythonProbe() { enginePythonCache = null }
276
331
 
332
+ /**
333
+ * spawn + Promise 版的解释器运行器:不再用 spawnSync 冻结事件循环(S-3)。
334
+ * 超时先软终止,5s 后硬杀并主动 reject,不等 'close';Windows 用
335
+ * taskkill /T /F 连带杀掉子进程树。maxBuffer 超限走同一条终止路径。
336
+ */
337
+ function spawnPython(cmd, args, { timeout, maxBuffer }) {
338
+ return new Promise((resolve, reject) => {
339
+ let child
340
+ try {
341
+ child = spawn(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
342
+ } catch (error) {
343
+ reject(error)
344
+ return
345
+ }
346
+ let settled = false
347
+ let stdout = ''
348
+ let stderr = ''
349
+ let timeoutTimer = null
350
+ let killTimer = null
351
+ const signalChild = force => {
352
+ if (!child || child.exitCode !== null) return
353
+ if (process.platform === 'win32') {
354
+ try { spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }) } catch {}
355
+ } else {
356
+ try { child.kill(force ? 'SIGKILL' : 'SIGTERM') } catch {}
357
+ }
358
+ }
359
+ const finish = (error, value) => {
360
+ if (settled) return
361
+ settled = true
362
+ if (timeoutTimer) clearTimeout(timeoutTimer)
363
+ if (killTimer) clearTimeout(killTimer)
364
+ if (error) reject(error)
365
+ else resolve(value)
366
+ }
367
+ const abort = reason => {
368
+ if (settled || killTimer) return
369
+ if (timeoutTimer) { clearTimeout(timeoutTimer); timeoutTimer = null }
370
+ signalChild(false)
371
+ killTimer = setTimeout(() => {
372
+ signalChild(true)
373
+ finish(reason, null) // 主动结束,不依赖 'close'
374
+ }, 5000)
375
+ killTimer.unref?.()
376
+ }
377
+ if (Number.isFinite(timeout) && timeout > 0) {
378
+ timeoutTimer = setTimeout(() => abort(Object.assign(new Error('python process timed out'), { code: 'ETIMEDOUT' })), timeout)
379
+ timeoutTimer.unref?.()
380
+ }
381
+ try { child.stdout?.setEncoding?.('utf8') } catch {}
382
+ try { child.stderr?.setEncoding?.('utf8') } catch {}
383
+ child.stdout?.on?.('data', chunk => {
384
+ if (settled) return
385
+ stdout += chunk
386
+ if (Buffer.byteLength(stdout) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
387
+ })
388
+ child.stderr?.on?.('data', chunk => {
389
+ if (settled) return
390
+ stderr += chunk
391
+ if (Buffer.byteLength(stderr) > maxBuffer) abort(Object.assign(new Error('maxBuffer exceeded'), { code: 'ENOBUFS' }))
392
+ })
393
+ child.on?.('error', error => finish(error, null))
394
+ child.on?.('close', (code, signal) => finish(null, { status: code, signal, stdout, stderr }))
395
+ })
396
+ }
397
+
277
398
  /**
278
399
  * Runs an interpreter. `exec` is a seam for tests only (a fake interpreter);
279
400
  * production always spawns the verified venv binary and nothing else.
401
+ * 兼容同步的测试 seam:await 一个普通返回值也照常拿到结果。
280
402
  */
281
- function runPython(exec, cmd, args, timeout) {
282
- const runner = typeof exec === 'function' ? exec : spawnSync
403
+ async function runPython(exec, cmd, args, timeout) {
404
+ const runner = typeof exec === 'function' ? exec : spawnPython
283
405
  try {
284
- return runner(cmd, args, { timeout, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })
406
+ return await runner(cmd, args, { timeout, windowsHide: true, encoding: 'utf8', maxBuffer: 4 * 1024 * 1024 })
285
407
  } catch (error) {
286
408
  return { error, status: null, stdout: '', stderr: '' }
287
409
  }
@@ -298,7 +420,7 @@ function jsonOutcome(result) {
298
420
  * none. Never falls back to a global interpreter: a missing, foreign or broken
299
421
  * venv is a refusal, not a downgrade.
300
422
  */
301
- function enginePythonForBackup(exec) {
423
+ async function enginePythonForBackup(exec) {
302
424
  const disabled = process.env.DSH_MEMU_BACKUP_NO_PYTHON === '1'
303
425
  const root = engineRoot()
304
426
  const candidates = disabled ? [] : engineVenvCandidates()
@@ -315,7 +437,7 @@ function enginePythonForBackup(exec) {
315
437
  value.rejected.push(candidate.source + ': outside ' + root)
316
438
  continue
317
439
  }
318
- const probe = runPython(exec, python, ['-c', PYTHON_PROBE_SCRIPT], PROBE_TIMEOUT_MS)
440
+ const probe = await runPython(exec, python, ['-c', PYTHON_PROBE_SCRIPT], PROBE_TIMEOUT_MS)
319
441
  const outcome = jsonOutcome(probe)
320
442
  if (!outcome || outcome.ok !== true) {
321
443
  const reason = outcome?.error || probe?.error?.message || (probe?.status != null ? 'exited ' + probe.status : 'no answer')
@@ -355,8 +477,8 @@ function removeQuietly(file) {
355
477
  * snapshot. Anything short of a clean `quick_check` is a failure, never a
356
478
  * reason to copy the bytes ourselves.
357
479
  */
358
- function pythonSnapshot(exec, python, from, to) {
359
- const result = runPython(exec, python.cmd, ['-c', SQLITE_SNAPSHOT_SCRIPT, from, to], PYTHON_TIMEOUT_MS)
480
+ async function pythonSnapshot(exec, python, from, to) {
481
+ const result = await runPython(exec, python.cmd, ['-c', SQLITE_SNAPSHOT_SCRIPT, from, to], PYTHON_TIMEOUT_MS)
360
482
  if (result?.error) return { ok: false, error: String(result.error.message || result.error) }
361
483
  if (result?.status !== 0) {
362
484
  return { ok: false, error: String(result?.stderr || ('engine interpreter exited ' + result?.status)).trim().slice(0, 400) }
@@ -379,7 +501,7 @@ function pythonSnapshot(exec, python, from, to) {
379
501
  * directory. Two outcomes only: a snapshot the engine proved consistent, or a
380
502
  * thrown refusal that aborts the whole backup.
381
503
  */
382
- function snapshotDatabase(from, to, exec) {
504
+ async function snapshotDatabase(from, to, exec) {
383
505
  const before = statOrNull(from)
384
506
  if (!before) return { mode: 'missing' }
385
507
  if (before.isSymbolicLink()) throw new Error('backup refuses symbolic links')
@@ -397,7 +519,7 @@ function snapshotDatabase(from, to, exec) {
397
519
  + ': it is neither an empty placeholder nor a SQLite database, so its contents cannot be verified'
398
520
  + (walContent ? ' (it has a non-empty WAL)' : ''))
399
521
  }
400
- const resolved = enginePythonForBackup(exec)
522
+ const resolved = await enginePythonForBackup(exec)
401
523
  const python = resolved.python
402
524
  if (!python) {
403
525
  const why = resolved.rejected.length ? ' (' + resolved.rejected.join('; ') + ')' : ''
@@ -406,7 +528,7 @@ function snapshotDatabase(from, to, exec) {
406
528
  + engineRoot() + why + '. Install or repair the engine, then retry. '
407
529
  + 'Nothing was copied: a live database copied by hand can restore as silent corruption.')
408
530
  }
409
- const snapshot = pythonSnapshot(exec, python, from, to)
531
+ const snapshot = await pythonSnapshot(exec, python, from, to)
410
532
  if (!snapshot.ok) {
411
533
  removeQuietly(to)
412
534
  removeQuietly(to + '-wal')
@@ -516,7 +638,7 @@ function engineSummary() {
516
638
  * `exec` only exists so tests can stand in for the engine interpreter; the
517
639
  * default path spawns the verified venv binary and nothing else.
518
640
  */
519
- function writeStores(staging, exec) {
641
+ async function writeStores(staging, exec) {
520
642
  ensureDir(path.join(staging, 'libraries'))
521
643
  ensureDir(path.join(staging, 'index'))
522
644
  ensureDir(path.join(staging, 'prompts'))
@@ -525,7 +647,9 @@ function writeStores(staging, exec) {
525
647
  // backup/restore so a restored install does not re-fork work it already did.
526
648
  copyRegular(path.join(dataDir(), 'consolidation.json'), path.join(staging, 'consolidation.json'))
527
649
  for (const name of readdirSafe(indexDir())) {
528
- if (name.endsWith('.json')) copyRegular(path.join(indexDir(), name), path.join(staging, 'index', name))
650
+ // Local deleted-memory stashes are a time-boxed undo buffer, not library
651
+ // data: they must never leak permanently deleted bodies into a backup.
652
+ if (name.endsWith('.json') && !name.endsWith('.deleted.json')) copyRegular(path.join(indexDir(), name), path.join(staging, 'index', name))
529
653
  }
530
654
  // 词典:data/lexicon/<libraryId>.json 与索引同权进备份清单。只收安全 id
531
655
  // 命名的 JSON(restore 侧 allowlist 用同一规则拒绝越界);目录还不存在(这个
@@ -550,7 +674,7 @@ function writeStores(staging, exec) {
550
674
  for (const database of databases) {
551
675
  const target = path.join(staging, database.rel.split('/').join(path.sep))
552
676
  ensureDir(path.dirname(target))
553
- const result = snapshotDatabase(database.src, target, exec)
677
+ const result = await snapshotDatabase(database.src, target, exec)
554
678
  snapshots.push({
555
679
  file: database.rel,
556
680
  mode: result.mode,
@@ -607,8 +731,8 @@ function cleanupStaging() {
607
731
  * throw happens before anything is published, so no partial or torn backup can
608
732
  * ever appear in backups/.
609
733
  */
610
- export function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
611
- return withBackupLock(() => {
734
+ export async function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState = null, pythonExec = null } = {}) {
735
+ return withBackupLock(async () => {
612
736
  ensureDir(backupsDir())
613
737
  cleanupStaging()
614
738
  const name = nextBackupName()
@@ -618,7 +742,7 @@ export function createBackup({ label = 'auto', keep = BACKUP_KEEP, flushState =
618
742
  // Plugin state is flushed first: a backup must never capture the pending
619
743
  // bookkeeping edits that are still only in memory.
620
744
  if (typeof flushState === 'function') flushState()
621
- const snapshots = writeStores(staging, pythonExec)
745
+ const snapshots = await writeStores(staging, pythonExec)
622
746
  const files = collectFiles(staging)
623
747
  const totals = { files: 0, bytes: 0 }
624
748
  for (const rel of Object.keys(files)) {
@@ -923,6 +1047,7 @@ function liveTargetFor(rel) {
923
1047
  if (head === 'global.sqlite3-shm') return globalDbFile() + '-shm'
924
1048
  }
925
1049
  if ((head === 'index' || head === 'libraries') && parts.length === 2) {
1050
+ if (parts[1].endsWith('.deleted.json')) throw new Error('backup contains a deleted-memory stash that must not be restored: ' + rel)
926
1051
  return path.join(head === 'index' ? indexDir() : librariesDir(), parts[1])
927
1052
  }
928
1053
  if (head === 'lexicon' && parts.length === 2) {
@@ -991,6 +1116,10 @@ function verifyInventory(found) {
991
1116
  const rels = []
992
1117
  for (const rel of Object.keys(manifest.files)) {
993
1118
  if (!isSafeRelative(rel)) throw new Error('invalid backup manifest path')
1119
+ // Backups made before stashes were excluded still list them. Skip rather
1120
+ // than fail, so restoring an older backup neither breaks nor resurrects
1121
+ // permanently deleted text.
1122
+ if (/^index\/[^/]+\.deleted\.json$/.test(rel)) continue
994
1123
  const full = path.join(found.dir, rel.split('/').join(path.sep))
995
1124
  const info = statOrNull(full)
996
1125
  if (!info || info.isSymbolicLink() || !info.isFile()) throw new Error('backup is incomplete: ' + rel + ' is missing')
@@ -1072,17 +1201,17 @@ function retireVectorActive(reason) {
1072
1201
  * A failure after that point is recoverable: the safety backup holds the state
1073
1202
  * that was replaced, and it is protected from this operation's prune.
1074
1203
  */
1075
- export function restoreFromBackup(name, { beforeRestore = null, flushState = null, clearCaches = null, keep = BACKUP_KEEP } = {}) {
1076
- return withBackupLock(() => {
1204
+ export async function restoreFromBackup(name, { beforeRestore = null, flushState = null, clearCaches = null, keep = BACKUP_KEEP } = {}) {
1205
+ return withBackupLock(async () => {
1077
1206
  const found = findBackup(name)
1078
1207
  const plan = verifyInventory(found)
1079
1208
  const vector = planVectorActive(found, plan.rels)
1080
1209
  writeLease(found.name, { pid: process.pid, at: Date.now(), kind: 'restore' })
1081
1210
  let safety = null
1082
1211
  try {
1083
- const created = typeof beforeRestore === 'function'
1212
+ const created = await (typeof beforeRestore === 'function'
1084
1213
  ? beforeRestore()
1085
- : createBackup({ label: 'before-restore', flushState })
1214
+ : createBackup({ label: 'before-restore', flushState }))
1086
1215
  safety = typeof created === 'string' ? created : (created && created.dir ? created.dir : null)
1087
1216
  const rels = restoreOrder(plan.rels.filter(rel => rel !== 'index/vector-active.json' || vector.restore))
1088
1217
  for (const rel of rels) {
@@ -56,7 +56,7 @@ export const RUNTIME_STATE = Object.freeze([
56
56
  { layer: 'temporary-map', file: 'lib/media.js:19', name: 'captures', keyedBy: 'sessionId', clearedBy: 'capture settle' },
57
57
  { layer: 'temporary-map', file: 'lib/private.js:535', name: 'inFlight', keyedBy: 'sessionId', clearedBy: 'consolidation settle' },
58
58
  { layer: 'temporary-map', file: 'lib/curator.js:50', name: 'jobs', keyedBy: 'job id', clearedBy: 'curation settle' },
59
- { layer: 'cache', file: 'lib/state.js:1186', name: 'indexCache', keyedBy: 'libraryId', clearedBy: 'next load / external write' },
59
+ { layer: 'cache', file: 'lib/state.js:1201', 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' },
61
61
  ])
62
62
 
@@ -75,7 +75,6 @@ const UNKNOWN = Object.freeze({
75
75
  BINDINGS_NOT_OBJECT: 'bindings-not-an-object',
76
76
  UNBOUND_BASIS_UNKNOWN: 'unbound-basis-unknown',
77
77
  })
78
- export const UNKNOWN_CODES = Object.freeze(UNKNOWN)
79
78
 
80
79
  function isObject(value) {
81
80
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
package/lib/budget.js CHANGED
@@ -33,15 +33,6 @@ export function estTokens(text) {
33
33
  return Math.ceil(wide + narrow / LATIN_CHARS_PER_TOKEN)
34
34
  }
35
35
 
36
- /** How many characters of a text shaped like `sample` fit in `tokens`. */
37
- export function charsForTokens(tokens, sample = '') {
38
- const budget = Number(tokens)
39
- if (!Number.isFinite(budget) || budget <= 0) return 0
40
- const ratio = cjkRatio(sample)
41
- const perChar = ratio + (1 - ratio) / LATIN_CHARS_PER_TOKEN
42
- return Math.max(1, Math.floor(budget / perChar))
43
- }
44
-
45
36
  /**
46
37
  * Cut `text` so its estimate stays within `maxTokens`. Prefers the last newline
47
38
  * before the cut so entries are not sliced mid-line.
@@ -94,3 +85,34 @@ export function packToBudget(items, maxTokens, render) {
94
85
  }
95
86
  return { lines, ids, used, omitted: Math.max(0, items.length - ids.length) }
96
87
  }
88
+
89
+ // S6 意图预算:不同问题需要的候选数不同。时间/实体题需要更大的时间线或实体卡
90
+ // 面(8),冲突题 6 条成对,承诺/边界 5 条。用户显式设置的更大值不会被压低,
91
+ // 但也不会超过 20 条。
92
+ export const RECALL_INTENT_TOPK = Object.freeze({
93
+ general: 5,
94
+ date: 8,
95
+ entity: 8,
96
+ conflict: 6,
97
+ commitment: 5,
98
+ boundary: 5,
99
+ })
100
+
101
+ export function intentTopK(intent, requested) {
102
+ const preset = RECALL_INTENT_TOPK[intent] ?? RECALL_INTENT_TOPK.general
103
+ const asked = Number(requested)
104
+ const hasAsked = Number.isFinite(asked) && asked > 0
105
+ // general 尊重调用方显式设置的更小值;专项意图(时间/实体/冲突…)需要更多证据,
106
+ // 只升不降,但同样封顶 20。
107
+ const wanted = !RECALL_INTENT_TOPK[intent] || intent === 'general'
108
+ ? (hasAsked ? asked : preset)
109
+ : Math.max(hasAsked ? asked : 0, preset)
110
+ return Math.max(1, Math.min(20, wanted))
111
+ }
112
+
113
+ export function recallIntentBudget(intent, settings = {}) {
114
+ return {
115
+ intent: RECALL_INTENT_TOPK[intent] ? intent : 'general',
116
+ topK: intentTopK(intent, settings.privateTopK),
117
+ }
118
+ }