@modusensus/dsh-mneme 0.11.0 → 0.13.0

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 (174) hide show
  1. package/README.md +54 -21
  2. package/docs/CONFIGURATION.md +45 -4
  3. package/docs/DIRECTORIES.md +114 -0
  4. package/docs/DISTILL.md +64 -0
  5. package/docs/DSH-GO.md +97 -0
  6. package/docs/ENTITIES.md +5 -3
  7. package/docs/FORGET.md +77 -0
  8. package/docs/KB.md +110 -0
  9. package/docs/SLEEP.md +28 -3
  10. package/docs/STORAGE.md +23 -0
  11. package/lib/api-standalone.js +4 -1
  12. package/lib/api.js +744 -26
  13. package/lib/attachment-text.js +122 -0
  14. package/lib/choro-command.js +9 -2
  15. package/lib/client.js +3752 -819
  16. package/lib/config.js +171 -2
  17. package/lib/continuity.js +7 -6
  18. package/lib/diary/auto.js +190 -0
  19. package/lib/diary/compose.js +440 -0
  20. package/lib/diary/dir.js +59 -0
  21. package/lib/diary/export.js +97 -0
  22. package/lib/diary/index.js +26 -0
  23. package/lib/diary/library.js +189 -0
  24. package/lib/diary/qq-inbox.js +142 -0
  25. package/lib/diary/rollover.js +61 -0
  26. package/lib/diary/session-provider.js +122 -0
  27. package/lib/document.js +9 -3
  28. package/lib/dream/clustering.js +6 -1
  29. package/lib/dream/decisions.js +56 -5
  30. package/lib/dream/sleep.js +616 -15
  31. package/lib/dream.js +45 -13
  32. package/lib/dsh-go/host.js +162 -0
  33. package/lib/dsh-go/panel.js +2091 -0
  34. package/lib/dsh-go/text.js +342 -0
  35. package/lib/dsh-go/views/common.js +68 -0
  36. package/lib/dsh-go/views/entity.js +48 -0
  37. package/lib/dsh-go/views/memory.js +198 -0
  38. package/lib/dsh-go/views/root.js +30 -0
  39. package/lib/dsh-go/views/settings.js +398 -0
  40. package/lib/dsh-go/views/status.js +51 -0
  41. package/lib/embedding.js +42 -8
  42. package/lib/entities/extractor.js +36 -7
  43. package/lib/hot-memory.js +8 -9
  44. package/lib/index.js +131 -5
  45. package/lib/inject.js +192 -19
  46. package/lib/kb/index.js +309 -0
  47. package/lib/kb/routes.js +220 -0
  48. package/lib/kb/tools.js +148 -0
  49. package/lib/lang.js +115 -4
  50. package/lib/peak-hours.js +57 -2
  51. package/lib/profile-facts.js +356 -0
  52. package/lib/semantic.js +347 -60
  53. package/lib/service.js +302 -70
  54. package/lib/settings.js +117 -14
  55. package/lib/store.js +830 -55
  56. package/lib/summarize.js +38 -11
  57. package/lib/tools.js +173 -25
  58. package/lib/user-settings.js +175 -23
  59. package/lib/vector-index.js +76 -6
  60. package/lib/wiki/cli-hint.js +90 -0
  61. package/lib/wiki/queries.js +264 -10
  62. package/lib/wiki/t1-jobs.js +232 -0
  63. package/lib/wiki/t1.js +7 -1
  64. package/package.json +25 -1
  65. package/scripts/sync-test-badge.mjs +1 -1
  66. package/scripts/test-count-sync.mjs +9 -5
  67. package/src/api-standalone.js +4 -1
  68. package/src/api.js +744 -26
  69. package/src/attachment-text.js +122 -0
  70. package/src/choro-command.js +9 -2
  71. package/src/config.js +171 -2
  72. package/src/continuity.js +7 -6
  73. package/src/diary/auto.js +190 -0
  74. package/src/diary/compose.js +440 -0
  75. package/src/diary/dir.js +59 -0
  76. package/src/diary/export.js +97 -0
  77. package/src/diary/index.js +26 -0
  78. package/src/diary/library.js +189 -0
  79. package/src/diary/qq-inbox.js +142 -0
  80. package/src/diary/rollover.js +61 -0
  81. package/src/diary/session-provider.js +122 -0
  82. package/src/document.js +9 -3
  83. package/src/dream/clustering.js +6 -1
  84. package/src/dream/decisions.js +56 -5
  85. package/src/dream/sleep.js +616 -15
  86. package/src/dream.js +45 -13
  87. package/src/dsh-go/host.js +162 -0
  88. package/src/dsh-go/panel.js +2091 -0
  89. package/src/dsh-go/text.js +342 -0
  90. package/src/dsh-go/views/common.js +68 -0
  91. package/src/dsh-go/views/entity.js +48 -0
  92. package/src/dsh-go/views/memory.js +198 -0
  93. package/src/dsh-go/views/root.js +30 -0
  94. package/src/dsh-go/views/settings.js +398 -0
  95. package/src/dsh-go/views/status.js +51 -0
  96. package/src/embedding.js +42 -8
  97. package/src/entities/extractor.js +36 -7
  98. package/src/hot-memory.js +8 -9
  99. package/src/index.js +131 -5
  100. package/src/inject.js +192 -19
  101. package/src/kb/index.js +309 -0
  102. package/src/kb/routes.js +220 -0
  103. package/src/kb/tools.js +148 -0
  104. package/src/lang.js +115 -4
  105. package/src/peak-hours.js +57 -2
  106. package/src/profile-facts.js +356 -0
  107. package/src/semantic.js +347 -60
  108. package/src/service.js +302 -70
  109. package/src/settings.js +117 -14
  110. package/src/store.js +830 -55
  111. package/src/summarize.js +38 -11
  112. package/src/tools.js +173 -25
  113. package/src/user-settings.js +175 -23
  114. package/src/vector-index.js +76 -6
  115. package/src/wiki/cli-hint.js +90 -0
  116. package/src/wiki/queries.js +264 -10
  117. package/src/wiki/t1-jobs.js +232 -0
  118. package/src/wiki/t1.js +7 -1
  119. package/test/api-routes-gaps.test.js +63 -0
  120. package/test/api.test.js +377 -4
  121. package/test/attachment-text.test.js +140 -0
  122. package/test/bm25-corpus-cache.test.js +145 -0
  123. package/test/capacity-warning.test.js +262 -0
  124. package/test/client.test.js +908 -138
  125. package/test/config.test.js +79 -0
  126. package/test/conflict-freeze.test.js +45 -1
  127. package/test/continuity.test.js +8 -1
  128. package/test/diary-library.test.js +187 -0
  129. package/test/diary.test.js +576 -0
  130. package/test/document.test.js +32 -0
  131. package/test/dream-maxtokens-fallback.test.js +3 -3
  132. package/test/dream.test.js +62 -1
  133. package/test/dsh-go-host.test.js +134 -0
  134. package/test/dsh-go-panel-actions.test.js +854 -0
  135. package/test/dsh-go-panel.test.js +251 -0
  136. package/test/embedding-cache-f32.test.js +276 -0
  137. package/test/embedding-ready.test.js +33 -3
  138. package/test/entities.test.js +73 -0
  139. package/test/forget-corrections.test.js +70 -0
  140. package/test/image-memory.test.js +171 -0
  141. package/test/inject-pin-explicit.test.js +300 -0
  142. package/test/inject-pin-vector-crowd.test.js +225 -0
  143. package/test/issue-617-step1-query-and-fusion.test.js +361 -0
  144. package/test/kb-api-wiring.test.js +128 -0
  145. package/test/kb-collections.test.js +272 -0
  146. package/test/kb-routes.test.js +379 -0
  147. package/test/mint-source.test.js +26 -0
  148. package/test/peak-hours-observability.test.js +70 -0
  149. package/test/persona-api.test.js +3 -3
  150. package/test/persona-by-session.test.js +568 -0
  151. package/test/persona-settings.test.js +38 -7
  152. package/test/profile-facts.test.js +492 -0
  153. package/test/reflection-update-gate.test.js +129 -0
  154. package/test/reindex-backfill.test.js +334 -0
  155. package/test/reindex-scheduler.test.js +369 -0
  156. package/test/scope-candidates.test.js +249 -0
  157. package/test/session-gate.test.js +1 -1
  158. package/test/sleep-action-set.test.js +14 -0
  159. package/test/sleep-heat.test.js +49 -0
  160. package/test/sleep.test.js +598 -0
  161. package/test/standalone-api.test.js +24 -0
  162. package/test/store.test.js +20 -0
  163. package/test/summarize.test.js +26 -0
  164. package/test/test-count-sync.test.js +14 -3
  165. package/test/tool-state-ignore.test.js +65 -0
  166. package/test/tools-dto-schema-matrix.test.js +23 -2
  167. package/test/tools.test.js +144 -7
  168. package/test/user-settings-segments.test.js +528 -0
  169. package/test/vector-index.test.js +120 -6
  170. package/test/wiki-api.test.js +476 -1
  171. package/test/wiki-cli-hint.test.js +118 -0
  172. package/test/wiki-queries.test.js +91 -1
  173. package/test/wiki-t1-jobs.test.js +125 -0
  174. package/test/wiki-tools.test.js +131 -76
@@ -0,0 +1,251 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { buildView } from "../src/dsh-go/views/root.js";
7
+
8
+ const HERE = dirname(fileURLToPath(import.meta.url));
9
+ const PKG_ROOT = join(HERE, "..");
10
+
11
+ // 这组守的是**视图契约**,不是像素:dsh-go 只认 JSON,越界(节点数 / 层数 / 字节)
12
+ // 是会在用户手机上直接报错的硬失败,所以每加一屏都要过一遍预算。
13
+ // 取数(src/dsh-go/host.js)与动作(src/dsh-go/panel.js)需要真宿主,端到端在
14
+ // dsh-go-bridge 那一侧验证;这里只锁得到「视图能拼出来、拼得合规」。
15
+
16
+ const LIMITS = { nodes: 120, depth: 8, bytes: 32768 };
17
+
18
+ /**
19
+ * 与 bridge 的 viewStats 同口径:节点 = 带 `type` 的组件对象(bindings / options /
20
+ * actions 里的参数对象不算节点),层数 = 组件 children 的递归深度。
21
+ */
22
+ function stats(node, depth = 1) {
23
+ if (node === null || typeof node !== "object") return { nodes: 0, depth };
24
+ if (Array.isArray(node)) {
25
+ let nodes = 0;
26
+ let deepest = depth;
27
+ for (const child of node) {
28
+ const s = stats(child, depth);
29
+ nodes += s.nodes;
30
+ deepest = Math.max(deepest, s.depth);
31
+ }
32
+ return { nodes, depth: deepest };
33
+ }
34
+ const isComponent = typeof node.type === "string";
35
+ let nodes = isComponent ? 1 : 0;
36
+ let deepest = isComponent ? depth : depth;
37
+ for (const value of Object.values(node)) {
38
+ if (value === null || typeof value !== "object") continue;
39
+ const s = stats(value, isComponent ? depth + 1 : depth);
40
+ nodes += s.nodes;
41
+ deepest = Math.max(deepest, s.depth);
42
+ }
43
+ return { nodes, depth: deepest };
44
+ }
45
+
46
+ /** 面板状态的默认形状(与 src/dsh-go/panel.js 的 state 对齐,覆盖视图读到的每个字段)。 */
47
+ function state(over = {}) {
48
+ return {
49
+ page: "list",
50
+ flagGroup: "basic",
51
+ settingsView: "settings",
52
+ sPanel: "menu",
53
+ profileTab: "profile",
54
+ q: "",
55
+ type: "all",
56
+ range: "all",
57
+ minImportance: 0,
58
+ scope: "all",
59
+ semantic: false,
60
+ viewMode: "flat",
61
+ heatSort: false,
62
+ filtersOpen: false,
63
+ offset: 0,
64
+ size: 20,
65
+ current: null,
66
+ form: {},
67
+ entityTotal: 12,
68
+ entityQuery: "",
69
+ entityName: "",
70
+ entityDepth: 1,
71
+ entityRelationCount: 0,
72
+ entityMemoryCount: 0,
73
+ flags: {},
74
+ flagOverrides: {},
75
+ pendingRestart: [],
76
+ pendingConflicts: 0,
77
+ pendingIds: new Set(),
78
+ rowsCount: 0,
79
+ monthGroups: [],
80
+ detailEntities: [],
81
+ detailEntityCount: 0,
82
+ detailConflict: false,
83
+ provenanceText: "",
84
+ conflictCount: 0,
85
+ conflictId: "",
86
+ conflictPick: "",
87
+ conflictA: null,
88
+ conflictB: null,
89
+ conflictReady: false,
90
+ wbKv: [],
91
+ wbDeposited: [],
92
+ wbArchived: [],
93
+ commands: [],
94
+ cmdCount: 0,
95
+ sCmdPick: "",
96
+ sCmdName: "",
97
+ sCmdDesc: "",
98
+ sCmdIns: "",
99
+ vector: { enabled: false, baseUrl: "", model: "" },
100
+ external: { enabled: false, port: 8790, host: "127.0.0.1" },
101
+ versionNote: "",
102
+ extractText: "",
103
+ injectPreviewText: "",
104
+ tokenCategories: [],
105
+ tokenSeries: [],
106
+ tokenKv: [],
107
+ heatSeries: [],
108
+ heatNote: "",
109
+ reclaimText: "",
110
+ reclaimConfirm: false,
111
+ notice: "",
112
+ noticeTone: "ok",
113
+ err: "",
114
+ ...over,
115
+ };
116
+ }
117
+
118
+ const SCREENS = [
119
+ ["记忆列表", state()],
120
+ ["记忆列表·月视图", state({ viewMode: "month", monthGroups: [{ label: "2026-11", rows: [] }] })],
121
+ ["记忆详情", state({ page: "detail", current: { id: "m1", archived: false } })],
122
+ ["记忆编辑", state({ page: "editor", form: { id: "m1", type: "project" } })],
123
+ ["记忆新建", state({ page: "editor", form: {} })],
124
+ ["冲突队列", state({ page: "conflict" })],
125
+ ["冲突对照", state({ page: "conflict", conflictReady: true, conflictPick: "a", conflictCount: 1 })],
126
+ ["实体", state({ entityTotal: 0 })],
127
+ ["实体详情", state({ page: "entity" })],
128
+ ["设置首页", state()],
129
+ ["状态", state({ settingsView: "status" })],
130
+ ["画像", state({ page: "profile" })],
131
+ ["人格", state({ page: "profile", profileTab: "persona" })],
132
+ ["规则", state({ page: "profile", profileTab: "rules" })],
133
+ ["工作动态", state({ sPanel: "workbench" })],
134
+ ["自定义指令", state({ sPanel: "commands", cmdCount: 1, commands: [{ id: "c1", name: "x" }], sCmdPick: "c1" })],
135
+ ["向量检索", state({ sPanel: "vector" })],
136
+ ["外部访问", state({ sPanel: "external" })],
137
+ ["关于", state({ sPanel: "help" })],
138
+ ["Agent 眼中的你", state({ sPanel: "facts" })],
139
+ ["代码库地志", state({ sPanel: "choro" })],
140
+ ];
141
+
142
+ for (const [name, fixture] of SCREENS) {
143
+ test(`dsh-go 视图在预算内:${name}`, () => {
144
+ const view = buildView(fixture);
145
+ assert.equal(view.v, 2);
146
+ const s = stats(view);
147
+ assert.ok(s.nodes <= LIMITS.nodes, `${name} 节点 ${s.nodes} > ${LIMITS.nodes}`);
148
+ assert.ok(s.depth <= LIMITS.depth, `${name} 层 ${s.depth} > ${LIMITS.depth}`);
149
+ const bytes = Buffer.byteLength(JSON.stringify(view), "utf8");
150
+ assert.ok(bytes <= LIMITS.bytes, `${name} 体积 ${bytes} > ${LIMITS.bytes}`);
151
+ });
152
+ }
153
+
154
+ test("dsh-go 顶层是三个原生页签(App 页签条每格 80dp,第四格会折行)", () => {
155
+ const view = buildView(state());
156
+ const tabs = view.children.find((node) => node.type === "tabs");
157
+ assert.ok(tabs, "顶层没有 tabs");
158
+ assert.deepEqual(
159
+ tabs.items.map((item) => item.label),
160
+ ["记忆", "实体", "设置"],
161
+ );
162
+ });
163
+
164
+ test("功能开关铺在设置页正文里,不是子页面(#dsh-go 对齐电脑端分组)", () => {
165
+ const view = buildView(state());
166
+ const flat = JSON.stringify(view);
167
+ assert.ok(flat.includes("功能开关"), "缺少功能开关标题");
168
+ assert.ok(!flat.includes("功能开关(分组)"), "标题仍带着「(分组)」");
169
+ assert.ok(flat.includes('"bind":"data.flagGroup"'), "分组选择器没有绑定");
170
+ assert.ok(/"bind":"data\.flags\./.test(flat), "没有开关绑定到 data.flags.*");
171
+ assert.ok(!flat.includes('"k":"flags"'), "还有指向 flags 子页面的入口");
172
+ });
173
+
174
+ function walk(node, out = []) {
175
+ if (node === null || typeof node !== "object") return out;
176
+ if (Array.isArray(node)) {
177
+ for (const child of node) walk(child, out);
178
+ return out;
179
+ }
180
+ out.push(node);
181
+ for (const value of Object.values(node)) walk(value, out);
182
+ return out;
183
+ }
184
+
185
+ test("设置页里不再出现自造的解释性小字(只留 mneme 原文案)", () => {
186
+ const flat = JSON.stringify(buildView(state()));
187
+ const invented = [
188
+ "38 项开关",
189
+ "写成斜杠命令,随时调用",
190
+ "跨会话记住你是谁",
191
+ "接口地址、模型、重建索引",
192
+ "版本检测与数据来源",
193
+ "轻量模式少做后台整理",
194
+ "沉淀 =",
195
+ ];
196
+ for (const phrase of invented) assert.ok(!flat.includes(phrase), `自造文案还在:${phrase}`);
197
+ assert.ok(flat.includes("控制插件在后台做哪些事"), "缺少 mneme 原文案(features.desc)");
198
+ assert.ok(flat.includes("轻量模式只保留核心能力"), "缺少 mneme 原文案(mode.desc)");
199
+ });
200
+
201
+ test("dsh-go 清单合法:一个面板、placement 只落 session.tab / features", () => {
202
+ const pkg = JSON.parse(readFileSync(join(PKG_ROOT, "package.json"), "utf8"));
203
+ const manifest = pkg.dshGo;
204
+ assert.equal(manifest.v, 1);
205
+ const panels = manifest.contributes.panels;
206
+ assert.equal(panels.length, 1);
207
+ const [panel] = panels;
208
+ assert.equal(panel.id, "mneme");
209
+ assert.ok(["session.tab", "features"].includes(panel.placement[0]));
210
+ // 面板里不出现密钥 / 令牌字样:清单是 App 侧可读的静态文件
211
+ assert.ok(!JSON.stringify(manifest).includes("token"));
212
+ });
213
+
214
+ test("记忆页与实体页的树不随数据变:首屏和拿到数据后是同一棵树", () => {
215
+ // 面板的 view() 在 data() 之前就要交出整棵树,所以按数据决定「要不要这块」
216
+ // 的地方,首屏会先按默认值定形,之后数据推来了也只是填绑定——空状态块就会
217
+ // 和有数据的列表同时挂在屏幕上。这里把两棵树直接比对,锁住结构稳定。
218
+ const empty = JSON.stringify(buildView(state({ rowsCount: 0, entityTotal: 0 })));
219
+ const filled = JSON.stringify(buildView(state({ rowsCount: 20, entityTotal: 12 })));
220
+ assert.equal(empty, filled, "视图结构仍然跟着数据走,首屏会留下残影");
221
+ assert.ok(!empty.includes('"type":"emptyState"'), "记忆 / 实体页不再用数据决定空状态块");
222
+ });
223
+
224
+ test("翻页是 App 原生的两段 segmented:一行铺满,不折行也不叠按钮", () => {
225
+ const nodes = walk(buildView(state()));
226
+ const pager = nodes.find((node) => node.type === "segmented" && node.bind === "data.pagePick");
227
+ assert.ok(pager, "缺少翻页 segmented");
228
+ assert.deepEqual(
229
+ pager.options.map((option) => option.label),
230
+ ["上一页", "下一页"],
231
+ );
232
+ assert.deepEqual(
233
+ pager.options.map((option) => option.value),
234
+ ["prev", "next"],
235
+ );
236
+ assert.equal(pager.onChange.id, "page");
237
+ // 页码文案挂在 label 上(必绘),不再单独占一行。
238
+ assert.deepEqual(pager.label, { $: "data.pageText" });
239
+
240
+ // 回归:曾经用两个 stack + chips 做左右对齐,右列在真机上渲染失败
241
+ // (App 显示「这部分无法显示」),所以翻页只能是单个节点。
242
+ assert.equal(
243
+ nodes.filter((node) => node.type === "chips" && node.bind === "data.pagePick").length,
244
+ 0,
245
+ "翻页又回到了 chips 方案",
246
+ );
247
+ const folded = nodes.filter(
248
+ (node) => node.type === "actions" && (node.items ?? []).some((item) => item.action?.id === "page"),
249
+ );
250
+ assert.equal(folded.length, 0, "翻页按钮还在 actions 里:窄屏会被折成上下两行");
251
+ });
@@ -0,0 +1,276 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { cosineSimilarity } from "../src/dream/clustering.js";
5
+
6
+ // 回归:embedding 解析缓存的两件事,2026-11-05 实测发现。
7
+ //
8
+ // 一、上限 4000 装不下工作集时缓存等于不存在。活跃带向量行 6685 条,扫到
9
+ // 第 4001 条开始驱逐自己刚填的条目,扫完只剩最后 4000 条,下一轮又从第一
10
+ // 条 miss —— 四轮实测命中率恒 0.0%,每次检索全量重解析(624ms)。固定调大
11
+ // 只是把复发推到下个月(活跃行近 30 天净增 6156 条),所以上限改为跟工作集
12
+ // 自适应。下面的用例锁住「工作集超过下限时仍接近全命中」这条行为,而不是
13
+ // 锁某个具体常量——锁常量等于允许它再次变成硬编码。
14
+ //
15
+ // 二、缓存里存 Float32Array。同一口径(GC 后 heapUsed + arrayBuffers,6730
16
+ // 条 1024 维全常驻)实测 number[] 56.4MB → Float32Array 29.7MB,省 47%。
17
+ // 但 `Array.isArray`
18
+ // 对 typed array 返回 false,而 cosine / cosineSimilarity / setEmbedding
19
+ // 历史上全用它当守卫 —— 换存储而不同步改守卫,会把每个相似度算成 0、
20
+ // 把「设置向量」读成「清空向量」。这类静默归零没有任何报错,所以必须有
21
+ // 用例把等价性钉死。
22
+
23
+ function make() {
24
+ return createStore(":memory:");
25
+ }
26
+
27
+ function seed(store, count, dim) {
28
+ const ids = [];
29
+ for (let i = 0; i < count; i++) {
30
+ const row = store.save({ type: "project", title: `t${i}`, content: `c${i}`, importance: 3 });
31
+ const v = new Array(dim);
32
+ for (let d = 0; d < dim; d++) v[d] = Math.sin(i * 0.7 + d * 0.3);
33
+ store.setEmbedding(row.id, v);
34
+ ids.push(row.id);
35
+ }
36
+ return ids;
37
+ }
38
+
39
+ test("缓存上限跟工作集自适应:超过 4000 条也不塌成 0% 命中", () => {
40
+ const store = make();
41
+ const dim = 8;
42
+ const ids = seed(store, 4200, dim); // 越过旧的固定上限 4000
43
+ const query = new Array(dim).fill(0.5);
44
+
45
+ // 第一轮:seed 走 setEmbedding(不经读路径,不计命中/未命中),但下限 4000
46
+ // 装不下 4200 条,最早写入的 200 条已被驱逐 —— 第一次 searchVector 会为它们
47
+ // 回表,同时把上限抬到装得下本次扫描。
48
+ store.searchVector(query, { limit: 5 });
49
+ const r1 = store.embeddingCacheStats();
50
+ assert.equal(r1.misses, ids.length - 4000, "冷扫描只为被下限挤掉的尾部回表");
51
+ assert.ok(
52
+ r1.cap >= ids.length,
53
+ `扫完后上限必须装得下工作集(cap=${r1.cap} 应 >= ${ids.length})——否则下轮会从第一条 miss`
54
+ );
55
+
56
+ // 第二轮:同一工作集,必须全命中(旧实现这里仍是 0%,因为缓存只留得下最后 4000 条)
57
+ store.searchVector(query, { limit: 5 });
58
+ const r2 = store.embeddingCacheStats();
59
+ const secondMisses = r2.misses - r1.misses;
60
+ const secondHits = r2.hits - r1.hits;
61
+ assert.equal(secondMisses, 0, `第二轮不应再有 miss(实测 ${secondMisses} 条)`);
62
+ assert.equal(secondHits, ids.length, "第二轮每条都命中");
63
+ assert.ok(r2.hitRate > 0.5, `累计命中率必须离开 0%(实测 ${(r2.hitRate * 100).toFixed(1)}%)`);
64
+
65
+ // 第三、四轮继续:命中率不得回落(旧实现每轮都归零)
66
+ store.searchVector(query, { limit: 5 });
67
+ store.searchVector(query, { limit: 5 });
68
+ const r4 = store.embeddingCacheStats();
69
+ assert.equal(r4.misses, r1.misses, "第 3、4 轮不应再产生 miss");
70
+ store.close();
71
+ });
72
+
73
+ test("淘汰语义:写入超过上限仍按 FIFO 驱逐最旧条目,且不驱逐正在用的", () => {
74
+ const store = make();
75
+ const ids = seed(store, 12, 4);
76
+ const before = store.embeddingCacheStats();
77
+ // 12 条远低于下限 4000,不会触发驱逐;这里锁的是「写入口按 id 覆盖而非追加」
78
+ const [a, b] = ids;
79
+ store.setEmbedding(a, [9, 9, 9, 9]);
80
+ assert.deepEqual(store.getParsedEmbedding(a), [9, 9, 9, 9], "同一 id 覆盖,不新增条目");
81
+ store.setEmbedding(b, null);
82
+ assert.equal(store.getParsedEmbedding(b), undefined, "清空即从缓存移除");
83
+ const after = store.embeddingCacheStats();
84
+ assert.ok(after.size <= before.size, "覆盖与清空都不该让缓存增长");
85
+ store.close();
86
+ });
87
+
88
+ test("Float32 与 number[] 等价:getParsedEmbedding / getEmbeddings 仍返回 number[]", () => {
89
+ const store = make();
90
+ const { id } = store.save({ type: "project", title: "A", content: "a" });
91
+ const written = [0.1, 0.25, 0.5, 0.75];
92
+ store.setEmbedding(id, written);
93
+ const one = store.getParsedEmbedding(id);
94
+ assert.ok(Array.isArray(one), "对外契约是 number[],调用方用 Array.isArray 守卫");
95
+ // 数值等价而非逐位相等:缓存按 Float32 存(省 47% 内存),双精度原值不保留,
96
+ // 回读带 ~1e-7 的单精度舍入。对余弦分数(0..1)与排序没有可观测影响
97
+ // (下面「排序不变」那条用例把这一点钉死),但这是对外可见的精度变化,
98
+ // 必须写成断言而不是假装不存在——用精确 deepEqual 会把它变成一颗定时炸弹。
99
+ assert.equal(one.length, written.length);
100
+ for (let i = 0; i < written.length; i++) {
101
+ assert.ok(Math.abs(one[i] - written[i]) < 1e-6, `第 ${i} 位误差应在单精度范围内`);
102
+ }
103
+ const many = store.getEmbeddings([id]).get(id);
104
+ assert.ok(Array.isArray(many), "批量读同样是 number[]");
105
+ assert.equal(many.length, written.length);
106
+
107
+ // 传 typed array 进 setEmbedding 必须当成「设置」而不是「清空」
108
+ store.setEmbedding(id, new Float32Array([0.2, 0.4, 0.6, 0.8]));
109
+ const after = store.getParsedEmbedding(id);
110
+ assert.ok(after, "typed array 入参不得被读成清空(旧守卫会把它写成 NULL)");
111
+ assert.equal(after.length, 4);
112
+ for (let i = 0; i < 4; i++) assert.ok(Math.abs(after[i] - [0.2, 0.4, 0.6, 0.8][i]) < 1e-6);
113
+ store.close();
114
+ });
115
+
116
+ test("Float32 与 number[] 等价:cosine 对 typed array 不得静默归零", () => {
117
+ const a = [1, 0, 0];
118
+ const b = [0, 1, 0];
119
+ const aF = new Float32Array(a);
120
+ const bF = new Float32Array(b);
121
+ assert.equal(cosineSimilarity(a, a), 1);
122
+ assert.equal(cosineSimilarity(aF, aF), 1, "typed array 不能算成 0(Array.isArray 守卫的坑)");
123
+ assert.equal(cosineSimilarity(a, b), 0);
124
+ assert.equal(cosineSimilarity(aF, bF), 0);
125
+ const mixed = cosineSimilarity(a, aF);
126
+ assert.equal(mixed, 1, "混合入参(number[] vs Float32Array)也必须能算");
127
+ });
128
+
129
+ test("Float32 存储不改变检索排序:前 50 条顺序与 number[] 完全一致", () => {
130
+ const store = make();
131
+ const dim = 16;
132
+ const ids = seed(store, 60, dim);
133
+ const query = new Array(dim);
134
+ for (let d = 0; d < dim; d++) query[d] = Math.cos(d * 0.11);
135
+
136
+ // 缓存里已是 Float32Array(seed 走 setEmbedding → cacheEmbedding)
137
+ const viaCache = store.searchVector(query, { limit: 50 });
138
+ // 清缓存后强制从 JSON 重读并重新解析(同一条路径,但冷启动)
139
+ store.db.prepare("SELECT 1").get();
140
+ const cold = store.searchVector(query, { limit: 50 });
141
+
142
+ assert.equal(viaCache.length, cold.length, "两次返回条数一致");
143
+ assert.deepEqual(
144
+ viaCache.map((r) => r.id),
145
+ cold.map((r) => r.id),
146
+ "Float32 缓存与冷解析的排序必须逐位相同(Float32 存储不损 cosine 排序)"
147
+ );
148
+ for (let i = 0; i < viaCache.length; i++) {
149
+ assert.ok(
150
+ Math.abs(viaCache[i].score - cold[i].score) < 1e-6,
151
+ `第 ${i} 条分数差异应可忽略(实测 ${Math.abs(viaCache[i].score - cold[i].score)})`
152
+ );
153
+ }
154
+ store.close();
155
+ });
156
+
157
+ // 变异实验暴露的缺口(2026-11-05):把 store.js 的 cosine 守卫退回 Array.isArray
158
+ // 时,上面那条「排序一致」照样全绿 —— 因为缓存路径与冷路径都喂进同一套坏守卫,
159
+ // 两边一起归零,排序自然「一致」。也就是说:只比两条路径是否相同,测不出「都错」。
160
+ // 必须有一个独立的正确答案做基准,所以这里直接算一遍期望分数。
161
+ test("searchVector 的分数本身正确:缓存路径的 cosine 不得归零", () => {
162
+ const store = make();
163
+ const a = store.save({ type: "project", title: "A", content: "a" });
164
+ const b = store.save({ type: "decision", title: "B", content: "b" });
165
+ store.setEmbedding(a.id, [1, 0, 0, 0]);
166
+ store.setEmbedding(b.id, [0.6, 0.8, 0, 0]);
167
+
168
+ const query = [1, 0, 0, 0];
169
+ const hits = store.searchVector(query, { limit: 5 });
170
+ assert.equal(hits.length, 2);
171
+
172
+ // 独立算一遍期望:cos([1,0,0,0],[1,0,0,0]) = 1;cos([1,0,0,0],[0.6,0.8,0,0]) = 0.6
173
+ const byId = new Map(hits.map((h) => [h.id, h.score]));
174
+ assert.ok(
175
+ Math.abs(byId.get(a.id) - 1) < 1e-6,
176
+ `完全同向的分数必须是 1(实测 ${byId.get(a.id)})——若为 0 说明 cosine 守卫把 typed array 判死了`
177
+ );
178
+ assert.ok(
179
+ Math.abs(byId.get(b.id) - 0.6) < 1e-6,
180
+ `余弦 0.6 必须算出来(实测 ${byId.get(b.id)})`
181
+ );
182
+ assert.ok(
183
+ hits[0].score > 0 && hits[1].score > 0,
184
+ "两条分数都不得为 0(静默归零没有任何报错,只能靠这条基准锁住)"
185
+ );
186
+ store.close();
187
+ });
188
+
189
+ // 摘掉 searchVector 的 `embedding != ''` 谓词(2026-11-05):`!= ''` 要读 embedding
190
+ // 列才能判定,SQLite 就得把整列向量文本搬一遍——而这条 SQL 只 SELECT id,一条
191
+ // 文本都不用。副本实测 265ms → 96ms。摘掉的前提是「空串行不会把检索搞崩」,
192
+ // 而库里现在 0 条空串纯属现状(setEmbedding 写 NULL,能造出空串的只有外部直接
193
+ // UPDATE)。所以必须把「空串行存在时」的行为钉死,否则这是在拆一个「目前恰好
194
+ // 为真」的假设。
195
+ test("库里存在 embedding = '' 的行:searchVector 不崩、不把它算进结果", () => {
196
+ const store = make();
197
+ const good = store.save({ type: "project", title: "正常", content: "有向量" });
198
+ const empty = store.save({ type: "project", title: "空串", content: "外部写的空串" });
199
+ const broken = store.save({ type: "project", title: "坏 JSON", content: "解析不了" });
200
+
201
+ store.setEmbedding(good.id, [1, 0, 0, 0]);
202
+ // 绕过 setEmbedding 直接写列——只有外部直接 UPDATE 才造得出这两种行。
203
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("", empty.id);
204
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{not json", broken.id);
205
+
206
+ const query = [1, 0, 0, 0];
207
+ const hits = store.searchVector(query, { limit: 10 });
208
+
209
+ assert.equal(hits.length, 1, `只有一条可解析向量参与(实测 ${hits.length} 条)`);
210
+ assert.equal(hits[0].id, good.id, "入选的必须是那条可解析的向量");
211
+ assert.ok(Math.abs(hits[0].score - 1) < 1e-6, `正常行分数仍须为 1(实测 ${hits[0].score})`);
212
+
213
+ // 空串行必须仍被 SQL 选中(IS NOT NULL 为真),再由 readVector 兜住——
214
+ // 否则这里测的是「SQL 没选它」,掩盖了 readVector 的兜底能力。
215
+ const selected = store.db.prepare(
216
+ "SELECT id FROM memories WHERE forgotten = 0 AND archived = 0 AND embedding IS NOT NULL"
217
+ ).all().map((r) => r.id);
218
+ assert.equal(selected.length, 3, "三行都有非 NULL 的 embedding 文本,SQL 全部选中");
219
+ assert.ok(selected.includes(empty.id), "空串行确实进了候选集(不是被 SQL 过滤掉)");
220
+
221
+ // 维度探针同一行集:空串行不能让 unreadable 判定失真。
222
+ assert.deepEqual(
223
+ store.vectorDimensionState(4),
224
+ { state: "match" },
225
+ "空串行存在时仍应判出 match(可解析的那条同维)"
226
+ );
227
+ store.close();
228
+ });
229
+
230
+ // 上面那条锁住「空串行不会崩」,但锁不住「谓词别被加回来」——把 `!= ''` 加回
231
+ // searchVector,8 条全绿:SQL 层先滤掉空串行,readVector 的兜底就永远测不到。
232
+ // 断言「这句 SQL 不含 != ''」是把测试绑在字面量上,正常重构(换行、改别名、
233
+ // 换 ${archivedFilter} 写法)就无辜变红,红了第一反应是删断言,比没有更糟。
234
+ // 这里锁行为:每一行非 NULL 都必须被读一次——这正是摘谓词的目的本身。只要
235
+ // SQL 又开始按 embedding 文本过滤掉行,读取次数立刻掉,跟 SQL 怎么写无关。
236
+ // 顺带把「读缓存命中」也算进增量,所以它同时锁住「别退化成每行都回表」。
237
+ test("摘谓词的目的:每一行非 NULL 的 embedding 都必须被读一次", () => {
238
+ const store = make();
239
+ const good = store.save({ type: "project", title: "正常", content: "有向量" });
240
+ const empty = store.save({ type: "project", title: "空串", content: "外部写的空串" });
241
+ const broken = store.save({ type: "project", title: "坏 JSON", content: "解析不了" });
242
+
243
+ store.setEmbedding(good.id, [1, 0, 0, 0]);
244
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("", empty.id);
245
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{not json", broken.id);
246
+
247
+ const before = store.embeddingCacheStats();
248
+ store.searchVector([1, 0, 0, 0], { limit: 10 });
249
+ const after = store.embeddingCacheStats();
250
+ const reads = (after.misses - before.misses) + (after.hits - before.hits);
251
+ assert.equal(
252
+ reads,
253
+ 3,
254
+ `三行非 NULL 必须各读一次(实测 ${reads} 次)——少于 3 说明 SQL 又在按 embedding 文本过滤,` +
255
+ "等于把「只 SELECT id 的查询顺手搬了 134MB 向量列」这个开销又请回来了"
256
+ );
257
+ store.close();
258
+ });
259
+
260
+ test("全部行都是 embedding = '' 时:检索返回空、探针判 unreadable 而非 none", () => {
261
+ const store = make();
262
+ const a = store.save({ type: "project", title: "A", content: "a" });
263
+ const b = store.save({ type: "project", title: "B", content: "b" });
264
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("", a.id);
265
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("", b.id);
266
+
267
+ assert.deepEqual(store.searchVector([1, 0], { limit: 5 }), [], "没有可解析向量就没有结果,不崩");
268
+ // 行集非空(两行都有非 NULL 文本)但零条可解析 = unreadable,不是 none。
269
+ // none 会让人以为「库里没有向量」,实际是「有文本却读不出来」。
270
+ assert.deepEqual(
271
+ store.vectorDimensionState(2),
272
+ { state: "unreadable" },
273
+ "有行却零条可解析 → unreadable(谓词摘掉后这条判定更依赖 readVector 的兜底)"
274
+ );
275
+ store.close();
276
+ });
@@ -159,10 +159,12 @@ test("reindexMissing: 逐行回填并统计 indexed/skipped,有成功才记模
159
159
  test("reindexMissing: 未启用时直接返回 0/0,不碰 store", async () => {
160
160
  const { embedder } = make({ ...FULL, enabled: false });
161
161
  const result = await embedder.reindexMissing(50);
162
- assert.deepEqual(result, { indexed: 0, skipped: 0 });
162
+ assert.deepEqual(result, { indexed: 0, failed: 0, skipped: 0 });
163
163
  });
164
164
 
165
- test("reindexMissing: 嵌入失败的行走 skipped,不算 indexed", async () => {
165
+ test("reindexMissing: 嵌入失败的行走 failed,不算 indexed、也不算 skipped", async () => {
166
+ // #604:`skipped = rows.length - indexed` 把「试过没拿到向量」和「压根没碰」
167
+ // 混成一个数。每一行都被尝试过,所以 skipped 必须是 0,失败单列。
166
168
  const writes = [];
167
169
  const embedder = createEmbedder({
168
170
  store: {
@@ -174,7 +176,35 @@ test("reindexMissing: 嵌入失败的行走 skipped,不算 indexed", async ()
174
176
  await withFetch(async () => ({ ok: false }), async () => {
175
177
  const result = await embedder.reindexMissing(50);
176
178
  assert.equal(result.indexed, 0);
177
- assert.equal(result.skipped, 1, "嵌入失败的行走 skipped,不算 indexed");
179
+ assert.equal(result.failed, 1, "试过但没拿到向量 → failed");
180
+ assert.equal(result.skipped, 0, "选择器选中了它,所以它没有被跳过");
181
+ });
182
+ });
183
+
184
+ test("reindexMissing: 一行写入抛错不中断其余行,且计入 failed", async () => {
185
+ // 注意:这里抛错的不能是 embedding 请求 —— embedTextDetailed 把网络错误吞成
186
+ // request-failed:network,永远不抛。真正会让这个 catch 跑起来的是写库失败
187
+ // (约束冲突、磁盘满),所以用 setEmbedding 抛。
188
+ const writes = [];
189
+ const embedder = createEmbedder({
190
+ store: {
191
+ setEmbedding: (id, v) => {
192
+ if (id === "m1") throw new Error("SQLITE_CONSTRAINT");
193
+ writes.push({ id, v });
194
+ },
195
+ needsEmbedding: () => [
196
+ { id: "m1", title: "t1", content: "a" },
197
+ { id: "m2", title: "t2", content: "b" }
198
+ ]
199
+ },
200
+ settings: { getVectorConfig: () => FULL },
201
+ logger: { info() {}, warn() {} }
202
+ });
203
+ await withFetch(async () => okResponse([1, 0]), async () => {
204
+ const result = await embedder.reindexMissing(50);
205
+ assert.equal(result.failed, 1, "写库失败的那行算 failed");
206
+ assert.equal(result.indexed, 1, "后面那行仍然被处理,循环没有中断");
207
+ assert.equal(writes.length, 1);
178
208
  });
179
209
  });
180
210
 
@@ -296,6 +296,79 @@ test("extractor writes entities, attrs and relations from mock LLM output", asyn
296
296
  store.close();
297
297
  });
298
298
 
299
+ test("extractor refuses to write affective_context, which belongs to the sleep phase", async () => {
300
+ // #619:affective_context 只有一个写入者——sleep 的 affective 相位。实体抽取发生
301
+ // 在写入当下,手里没有会话边界,判不了「一次场合」和「反复出现的特质」,写进去的
302
+ // 只会是一条没有 emotion/attribution/sessionCount 的半成品边,同一张表两种 schema。
303
+ // 所以抽取器把它当未知类型拒收,而不是当一等公民放行。
304
+ const store = openStore();
305
+ const memory = store.save({ type: "history", title: "答辩前一晚", content: "答辩前一晚他很焦虑", importance: 3 });
306
+ const warnings = [];
307
+ const logger = { warn: (msg) => warnings.push(String(msg)), info: () => {} };
308
+ const callLLM = jsonLLM({
309
+ entities: [
310
+ { name: "他", type: "person", attrs: [] },
311
+ { name: "答辩", type: "concept", attrs: [] }
312
+ ],
313
+ relations: [{ from: "他", to: "答辩", type: "affective_context" }]
314
+ });
315
+ const result = await extractEntities(memory, { store, config: {}, callLLM, logger });
316
+ assert.equal(result.ok, true);
317
+ assert.equal(result.relations.length, 0);
318
+ assert.deepEqual(result.rejectedRelationTypes, ["affective_context"]);
319
+ assert.equal(warnings.length, 1);
320
+ assert.match(warnings[0], /affective_context/);
321
+ assert.equal(store.getRelations(store.findEntityByName("他").id).length, 0);
322
+ store.close();
323
+ });
324
+
325
+ test("extractor rejects unknown relation types instead of silently downgrading to related_to", async () => {
326
+ // 变异自证:把 sanitizeRelationType 改回 `return "related_to"` 兜底,这条必红
327
+ // ——既会多落一条假边,rejectedRelationTypes 也会变空、warn 不再触发。
328
+ const store = openStore();
329
+ const memory = store.save({ type: "project", title: "混入未知类型", content: "A 对 B 有种奇怪的关系", importance: 3 });
330
+ const warnings = [];
331
+ const logger = { warn: (msg) => warnings.push(String(msg)), info: () => {} };
332
+ const callLLM = jsonLLM({
333
+ entities: [
334
+ { name: "A", type: "concept", attrs: [] },
335
+ { name: "B", type: "concept", attrs: [] }
336
+ ],
337
+ relations: [
338
+ { from: "A", to: "B", type: "feels_weird_about" },
339
+ { from: "A", to: "B", type: "related_to" }
340
+ ]
341
+ });
342
+ const result = await extractEntities(memory, { store, config: {}, callLLM, logger });
343
+ assert.equal(result.ok, true);
344
+ assert.deepEqual(result.rejectedRelationTypes, ["feels_weird_about"]);
345
+ assert.equal(warnings.length, 1);
346
+ assert.match(warnings[0], /feels_weird_about/);
347
+ const rels = store.getRelations(store.findEntityByName("A").id);
348
+ assert.equal(rels.length, 1, "only the legitimate relation lands");
349
+ assert.equal(rels[0].relation_type, "related_to");
350
+ store.close();
351
+ });
352
+
353
+ test("extractor drops a relation whose type is not even a string", async () => {
354
+ const store = openStore();
355
+ const memory = store.save({ type: "project", title: "空类型", content: "A 和 B 有联系", importance: 3 });
356
+ const callLLM = jsonLLM({
357
+ entities: [
358
+ { name: "A", type: "concept", attrs: [] },
359
+ { name: "B", type: "concept", attrs: [] }
360
+ ],
361
+ relations: [{ from: "A", to: "B" }]
362
+ });
363
+ const result = await extractEntities(memory, { store, config: {}, callLLM });
364
+ assert.equal(result.ok, true);
365
+ assert.equal(result.relations.length, 0);
366
+ assert.deepEqual(result.rejectedRelationTypes, ["undefined"]);
367
+ assert.deepEqual(store.getRelations(store.findEntityByName("A").id), []);
368
+ store.close();
369
+ });
370
+
371
+
299
372
  test("resolveEntity dedups: re-extracting the same name bumps mention_count", async () => {
300
373
  const store = openStore();
301
374
  const memory = store.save({ type: "preference", title: "工具", content: "用 Vite", importance: 3 });