@modusensus/dsh-mneme 0.8.6 → 0.8.8

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 (68) hide show
  1. package/README.md +19 -148
  2. package/bin/cli.mjs +689 -603
  3. package/lib/api-standalone.js +57 -1
  4. package/lib/api.js +34 -11
  5. package/lib/client.js +349 -61
  6. package/lib/config.js +118 -7
  7. package/lib/content-hash.js +54 -0
  8. package/lib/continuity.js +220 -0
  9. package/lib/document-index.js +94 -0
  10. package/lib/document.js +93 -11
  11. package/lib/dream.js +138 -39
  12. package/lib/guide.js +18 -0
  13. package/lib/index.js +87 -12
  14. package/lib/inject.js +6 -2
  15. package/lib/lang.js +15 -4
  16. package/lib/maintenance.js +142 -0
  17. package/lib/mirror.js +147 -15
  18. package/lib/peak-hours.js +117 -0
  19. package/lib/recall-stats.js +52 -2
  20. package/lib/scope.js +34 -6
  21. package/lib/service.js +86 -7
  22. package/lib/settings.js +16 -2
  23. package/lib/store.js +318 -21
  24. package/lib/summarize.js +52 -113
  25. package/lib/tools.js +37 -11
  26. package/lib/write-admission.js +259 -0
  27. package/package.json +4 -4
  28. package/src/api-standalone.js +57 -1
  29. package/src/api.js +34 -11
  30. package/src/config.js +118 -7
  31. package/src/content-hash.js +54 -0
  32. package/src/continuity.js +220 -0
  33. package/src/document-index.js +94 -0
  34. package/src/document.js +93 -11
  35. package/src/dream.js +138 -39
  36. package/src/guide.js +18 -0
  37. package/src/index.js +87 -12
  38. package/src/inject.js +6 -2
  39. package/src/lang.js +15 -4
  40. package/src/maintenance.js +142 -0
  41. package/src/mirror.js +147 -15
  42. package/src/peak-hours.js +117 -0
  43. package/src/recall-stats.js +52 -2
  44. package/src/scope.js +34 -6
  45. package/src/service.js +86 -7
  46. package/src/settings.js +16 -2
  47. package/src/store.js +318 -21
  48. package/src/summarize.js +52 -113
  49. package/src/tools.js +37 -11
  50. package/src/write-admission.js +259 -0
  51. package/test/api.test.js +21 -3
  52. package/test/client.test.js +103 -6
  53. package/test/content-hash.test.js +204 -0
  54. package/test/continuity.test.js +333 -0
  55. package/test/document-dir.test.js +233 -0
  56. package/test/document.test.js +151 -3
  57. package/test/dream-failure-backoff.test.js +173 -0
  58. package/test/dream-peak-hours.test.js +194 -0
  59. package/test/inject-parent-gate.test.js +106 -0
  60. package/test/inject-pools.test.js +8 -3
  61. package/test/llm-audit.test.js +42 -0
  62. package/test/maintenance.test.js +391 -0
  63. package/test/mirror-types.test.js +208 -0
  64. package/test/reasoning-effort.test.js +6 -0
  65. package/test/recall-evals.test.js +18 -0
  66. package/test/recall-stats.test.js +66 -0
  67. package/test/summarize-reasoning-effort.test.js +189 -0
  68. package/test/write-admission.test.js +345 -0
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
3
3
  import { readFileSync, existsSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { dirname, join } from "node:path";
6
+ import { spawnSync } from "node:child_process";
6
7
 
7
8
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
8
9
  const clientSource = readFileSync(join(root, "lib/client.js"), "utf8");
@@ -25,6 +26,15 @@ test("client bundle is lib-only with no src counterpart", () => {
25
26
  assert.equal(existsSync(join(root, "lib/client.js")), true, "lib/client.js must exist");
26
27
  });
27
28
 
29
+ // 归档侧第五指标(#275)自己按「归档区为空就整段省略」门控,但整卡还有一道 hasData 门:
30
+ // 那道门只认召回回执与活跃僵尸行时,「全归档 + 窗口内无回执」的库会直接 return null,
31
+ // 指标永远不显示(自动评审 #312 指出的回归)。这里锁死 hasData 必须把 archive.total 计进来。
32
+ test("status card: hasData counts the archive metric", () => {
33
+ const m = clientSource.match(/const hasData =[^;]+;/);
34
+ assert.ok(m, "the status card must declare hasData");
35
+ assert.match(m[0], /d\.archive\?\.total/, "hasData must count archive.total, not just runs/active rows");
36
+ });
37
+
28
38
  // The memory entry lives at the sidebar foot, not in the settings modal: the
29
39
  // migration must register into `sidebar.footer.action` (the list slot the
30
40
  // sidebar shell renders beside Settings) and must not keep a `settings.section`
@@ -208,8 +218,8 @@ test("entry tracks native class, inherits native sizing, and lifts the toolbar d
208
218
  "the entry must use the native button width, which reserves its horizontal margins"
209
219
  );
210
220
  assert.ok(
211
- clientSource.includes(".mneme-topentry{display:flex;flex-direction:column}"),
212
- "the entry wrapper must stretch the native button within a column flex layout"
221
+ clientSource.includes(".mneme-topentry{display:flex;flex-direction:column;position:relative}"),
222
+ "the entry wrapper must stretch the native button within a column flex layout (position:relative hosts the #177 badge)"
213
223
  );
214
224
  assert.equal(
215
225
  clientSource.includes(".mneme-topentry-native .mneme-topentry-label{flex:1;min-width:0;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}"),
@@ -313,6 +323,35 @@ test("graph toggle uses a node-graph glyph, not the share icon", () => {
313
323
  );
314
324
  });
315
325
 
326
+ // #287 跨代图标守卫:primitives 在 0.1.7 把归档图标从「像素后缀」改名成「字重后缀」
327
+ // (IconArchiveOutline20 → …OutlineRegular / …OutlineMedium),旧名不留别名,而
328
+ // peerDependencies 仍同时覆盖 0.1.6 与 0.1.7 两代宿主。只认某一代的名字,另一代就会
329
+ // 把 undefined 交给 h(),落成 slot entry 里的 React #130(该 entry 整块崩),因此必须
330
+ // 探测两代名字、并在全缺时降级为不渲染图标。
331
+ test("#287: archive glyph probes both naming generations and degrades to no glyph", () => {
332
+ assert.ok(
333
+ /primitives\.IconArchiveOutline20\s*\?\?\s*primitives\.IconArchiveOutlineRegular\s*\?\?\s*primitives\.IconArchiveOutlineMedium/.test(clientSource),
334
+ "the glyph must probe the 0.1.6 pixel name before the 0.1.7 weight names"
335
+ );
336
+ assert.equal(
337
+ /h\(IconArchiveOutline20/.test(clientSource),
338
+ false,
339
+ "the raw constant must never reach h() — on a host lacking that name it renders undefined (React #130)"
340
+ );
341
+ assert.ok(
342
+ /const renderArchiveIcon = \(props\) => \(IconArchive \? h\(IconArchive, props\) : null\)/.test(clientSource),
343
+ "the glyph must render through a null-guarded helper so a missing icon degrades to nothing"
344
+ );
345
+ for (const site of [
346
+ "renderArchiveIcon({ size: 15 })", // 浮层标题栏
347
+ "renderArchiveIcon({ size: wide ? 16 : 18 })", // 侧栏 trigger
348
+ "renderArchiveIcon({ size: wide ? 15 : 18 })", // portal 到宿主原生侧栏的入口
349
+ "renderArchiveIcon({ size })" // better-sidebar tab 图标
350
+ ]) {
351
+ assert.ok(clientSource.includes(site), `every render site must go through the helper: ${site}`);
352
+ }
353
+ });
354
+
316
355
  // 方案 A:查询收敛。状态页只做仪表盘(小页预览 + 服务端 total + 查看全部),
317
356
  // 沉淀/归档的完整浏览走记忆库的 deposited/archived 筛选视图(chip 预置 +
318
357
  // 状态页入口跳转),详情抽屉给归档记忆一个反向的「恢复」。
@@ -665,7 +704,7 @@ test("settings feedback card: prefilled issue + mailto + browse, version from /i
665
704
  );
666
705
  // 2. GitHub 新建 issue:issues/new?title=&body= 预填环境信息(当前仓库无模板)
667
706
  assert.ok(
668
- clientSource.includes("https://github.com/slow-stack/dsh-mneme/issues/new?title="),
707
+ clientSource.includes("https://github.com/slow-stack/mneme/issues/new?title="),
669
708
  "the issue link must prefill title+body on issues/new"
670
709
  );
671
710
  assert.ok(
@@ -679,7 +718,7 @@ test("settings feedback card: prefilled issue + mailto + browse, version from /i
679
718
  );
680
719
  // 4. 浏览已知问题:跳仓库 issues 列表页(去重前置步骤)
681
720
  assert.ok(
682
- clientSource.includes('href: "https://github.com/slow-stack/dsh-mneme/issues"'),
721
+ clientSource.includes('href: "https://github.com/slow-stack/mneme/issues"'),
683
722
  "the browse link must open the repo issues list"
684
723
  );
685
724
  // 5. 双语 i18n
@@ -844,8 +883,55 @@ test("a11y: entity graph svg exposes a count summary", () => {
844
883
  }
845
884
  });
846
885
 
847
- // --- issue #179:注入预览(状态页卡片 + /inject-preview 端点透传的旁路快照) ---
886
+ // --- issue #177:冲突队列交互与视觉重做 ---
848
887
 
888
+ // 相似度进度条:只从「相似度 X / similarity X」锚定短语回收数字(防把年份当
889
+ // 相似度),A/B 卡片带侧色类,冻结徽章替代预裁决阶段的「已归档」徽章。
890
+ test("conflict queue: similarity bar, side colors and frozen badge", () => {
891
+ assert.ok(clientSource.includes("similarityOf(it.reason)"), "reason must be parsed for similarity");
892
+ assert.ok(clientSource.includes("/(?:相似度|similarity)\\s*([01](?:\\.\\d+)?)/i"), "parse must anchor on the similarity phrase");
893
+ for (const key of ["memory.status.conflictQueue.similarity", "memory.status.conflictQueue.frozenBadge"]) {
894
+ const occurrences = clientSource.split(`"${key}"`).length - 1;
895
+ assert.ok(occurrences >= 2, `i18n key ${key} must exist in both zh and en (got ${occurrences})`);
896
+ }
897
+ assert.ok(clientSource.includes('"mneme-conflict-side--a"'), "side A must carry the A color class");
898
+ assert.ok(clientSource.includes('"mneme-conflict-side--b"'), "side B must carry the B color class");
899
+ assert.ok(!/s\.archived && h\("span", \{ className: "mneme-badge mneme-badge--archived"/.test(clientSource),
900
+ "the pre-ruling archived badge must be replaced by the frozen badge");
901
+ assert.ok(clientSource.includes("mneme-badge--frozen"), "frozen badge class must exist");
902
+ });
903
+
904
+ // 词级 diff:LCS 对齐是纯函数,锁它的存在、上限护栏与渲染接线(无损性由
905
+ // difftest 独立验证,此处只锁形状)。
906
+ test("conflict queue: word diff is wired with size guards", () => {
907
+ assert.ok(clientSource.includes("function wordDiff(aText, bText)"), "wordDiff must exist");
908
+ assert.ok(clientSource.includes("mneme-conflict-mark--del"), "del highlight class must exist");
909
+ assert.ok(clientSource.includes("mneme-conflict-mark--ins"), "ins highlight class must exist");
910
+ assert.ok(clientSource.includes("n > 800 || m > 800"), "DP must bail on oversized inputs");
911
+ });
912
+
913
+ // 空态教育卡:0 冲突时也渲染(原来整块 return null),解释冻结是什么。
914
+ test("conflict queue: empty-state explainer card", () => {
915
+ assert.ok(!/if \(!items \|\| items\.length === 0\) return null;/.test(clientSource),
916
+ "empty queue must render the explainer instead of nothing");
917
+ for (const key of ["memory.status.conflictQueue.emptyTitle", "memory.status.conflictQueue.emptyBody"]) {
918
+ const occurrences = clientSource.split(`"${key}"`).length - 1;
919
+ assert.ok(occurrences >= 2, `i18n key ${key} must exist in both zh and en (got ${occurrences})`);
920
+ }
921
+ });
922
+
923
+ // 状态卡待处理高亮 + 侧边栏入口 badge(挂 portal 与回退两个按钮)。
924
+ test("conflict queue: actionable status card and sidebar entry badge", () => {
925
+ assert.ok(clientSource.includes('"mneme-conflict-jump"'), "pending>0 card must carry the highlight class");
926
+ assert.ok(clientSource.includes("mneme-statuscard--actionable"), "highlight CSS must exist");
927
+ assert.ok((clientSource.match(/h\(ConflictBadge, \{ pending \}\)/g) || []).length === 2,
928
+ "badge must be wired into both entry buttons");
929
+ assert.ok((clientSource.match(/= useConflictBadgeCount\(t\)/g) || []).length === 2,
930
+ "both entry components must subscribe to the badge count");
931
+ assert.ok(clientSource.includes('"/api/dsh-mneme/dream-status"'), "badge must reuse the dream-status endpoint");
932
+ });
933
+
934
+ // --- issue #179:注入预览(状态页卡片 + /inject-preview 端点透传的旁路快照) ---
849
935
  test("a11y+preview: inject preview card is wired on the status tab", () => {
850
936
  assert.ok(clientSource.includes('"/api/dsh-mneme/inject-preview"'), "card must fetch the preview endpoint");
851
937
  assert.ok(clientSource.includes("h(InjectPreviewCard, { t })"), "status grid must render the preview card");
@@ -858,4 +944,15 @@ test("a11y+preview: inject preview card is wired on the status tab", () => {
858
944
  const occurrences = clientSource.split(`"${key}"`).length - 1;
859
945
  assert.ok(occurrences >= 2, `i18n key ${key} must exist in both zh and en (got ${occurrences})`);
860
946
  }
861
- });
947
+ });
948
+ // 面板 bundle 在本文件里只被当**文本**读(上面的断言全是正则/字符串包含),
949
+ // 而仓库的 CI 里没有任何一步**解析**它:于是重复声明这类语法错误能一路绿灯进
950
+ // 主干,后果却是整个面板加载失败(__ModuleLoader__ 拿到的模块一执行就抛
951
+ // SyntaxError)。lib/client.js 无 src 对应物、不参与 sync,也就没有别的闸门
952
+ // 覆盖它——这里补一道解析闸(PR #320 rebase 时真实踩到:与上游新增的
953
+ // summarizeSub 撞名,node --check 报 "Identifier 'summarizeSub' has already
954
+ // been declared",而当时 CI 全绿)。
955
+ test("client bundle parses: 面板产物必须是合法 JS(无重复声明等语法错误)", () => {
956
+ const result = spawnSync(process.execPath, ["--check", join(root, "lib/client.js")], { encoding: "utf8" });
957
+ assert.equal(result.status, 0, `lib/client.js 解析失败:\n${result.stderr || result.stdout}`);
958
+ });
@@ -0,0 +1,204 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { DatabaseSync } from "node:sqlite";
4
+ import { mkdtempSync, rmSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { createStore } from "../src/store.js";
8
+ import { contentHashOf, normalizeForHash } from "../src/content-hash.js";
9
+
10
+ // #254 内容哈希(写入准入的确定性计量锚)。
11
+ // 这批用例锁三件事:归一化口径(只差格式不算两次)、派生列随内容走(insert/update/
12
+ // CAS 三处都得重算,漏一处标记就在说谎)、以及老库打开时的迁移顺序(索引必须在加列
13
+ // 之后建,否则 exec(SCHEMA) 直接报 no such column,插件整树加载失败)。
14
+
15
+ test("归一化口径:大小写/空白/标点/全角差异落在同一个键上", () => {
16
+ assert.equal(normalizeForHash("Hello, World!\n"), "hello world");
17
+ assert.equal(normalizeForHash("hello world"), "hello world", "NFKC 折全角");
18
+ assert.equal(
19
+ contentHashOf({ title: "Task A", content: "Line1.\n\nLine2" }),
20
+ contentHashOf({ title: "task a", content: "line1 line2" })
21
+ );
22
+ // 分隔符防拼接歧义:('ab','c') 与 ('a','bc') 不能同键
23
+ assert.notEqual(contentHashOf({ title: "ab", content: "c" }), contentHashOf({ title: "a", content: "bc" }));
24
+ assert.notEqual(contentHashOf({ title: "t", content: "同一件事" }), contentHashOf({ title: "t", content: "另一件事" }));
25
+ });
26
+
27
+ test("归一化口径:同义词与词序不折叠(哈希只认逐字节相同)", () => {
28
+ assert.notEqual(contentHashOf({ title: "t", content: "a b" }), contentHashOf({ title: "t", content: "b a" }));
29
+ });
30
+
31
+ test("已知等价类:去标点让 3.5 与 35 同键(口径选择的结果,不是判据出错)", () => {
32
+ // 这条把「已知会误报」的样子钉住,防止有人把文件头的「命中即精确重复」当承诺、
33
+ // 进而以为这是个 bug 去改归一化——改口径要带存量重算(见 content-hash.js 文件头)。
34
+ assert.equal(contentHashOf({ title: "t", content: "版本 3.5" }), contentHashOf({ title: "t", content: "版本 35" }));
35
+ assert.equal(contentHashOf({ title: "t", content: "a-b" }), contentHashOf({ title: "t", content: "ab" }));
36
+ // 但数字本身没被折叠:不同数值不落同一键
37
+ assert.notEqual(contentHashOf({ title: "t", content: "3.5" }), contentHashOf({ title: "t", content: "3.6" }));
38
+ });
39
+
40
+ test("空标题空正文没有可比内容 → null(不互相匹配成「全是重复」)", () => {
41
+ assert.equal(contentHashOf({ title: "", content: "" }), null);
42
+ assert.equal(contentHashOf({ title: " ", content: "\n\t" }), null);
43
+ assert.equal(contentHashOf({}), null);
44
+ assert.ok(contentHashOf({ title: "只有标题" }));
45
+ });
46
+
47
+ test("save 落 content_hash,findContentHashMatches 按 type + scope 收窄", () => {
48
+ const store = createStore(":memory:");
49
+ const a = store.save({ type: "project", title: "同一件事", content: "正文", agent_scope: "A" });
50
+ assert.equal(a.content_hash, contentHashOf({ title: "同一件事", content: "正文" }));
51
+
52
+ const sameScope = store.findContentHashMatches({ type: "project", hash: a.content_hash, agent_scope: "A" });
53
+ assert.deepEqual(sameScope.map((m) => m.id), [a.id]);
54
+
55
+ // 跨 scope 永不互判(与 saveWithDedupe 的三维去重键同口径)
56
+ const otherScope = store.findContentHashMatches({ type: "project", hash: a.content_hash, agent_scope: "B" });
57
+ assert.equal(otherScope.length, 0);
58
+ const unannotated = store.findContentHashMatches({ type: "project", hash: a.content_hash });
59
+ assert.equal(unannotated.length, 0, "已标注行不与未标注行匹配");
60
+
61
+ // 入参先按 store 自己的口径归一,免得调用方传 " A " 就漏配
62
+ assert.equal(store.findContentHashMatches({ type: "project", hash: a.content_hash, agent_scope: " A " }).length, 1);
63
+ // type 不同不互判
64
+ assert.equal(store.findContentHashMatches({ type: "preference", hash: a.content_hash, agent_scope: "A" }).length, 0);
65
+ store.close();
66
+ });
67
+
68
+ test("归档行在候选集内(#275 分界:出口止体积、不止重复)", () => {
69
+ const store = createStore(":memory:");
70
+ const saved = store.save({ type: "project", title: "被归档的事实", content: "同样的正文" });
71
+ store.setArchived(saved.id, true);
72
+ const hits = store.findContentHashMatches({ type: "project", hash: saved.content_hash });
73
+ assert.deepEqual(hits, [{ id: saved.id, archived: true, forgotten: false }]);
74
+ store.close();
75
+ });
76
+
77
+ test("同键命中超过窗口宽度时,活跃行仍在窗口内(归档动作会顶 updated_at)", () => {
78
+ // 回归(自动评审 #311 store.js:1055):LIMIT 先于调用方的「活区优先」执行。若只按
79
+ // updated_at 倒序,第 11 条起写下的归档行会把更早的活跃行挤出窗口,调用方只能看见
80
+ // 归档命中,把「活跃重复」错记成「归档重复」——正是 dup 信号要分流的两类。
81
+ const store = createStore(":memory:");
82
+ const live = store.save({ type: "project", title: "窗口内", content: "同一段正文" });
83
+ assert.ok(live.content_hash, "写入即落 content_hash");
84
+ const sinks = [];
85
+ for (let i = 0; i < 10; i++) {
86
+ sinks.push(store.save({ type: "project", title: "窗口内", content: "同一段正文" }));
87
+ }
88
+ for (const row of sinks) store.setArchived(row.id, true);
89
+ const hits = store.findContentHashMatches({ type: "project", hash: live.content_hash });
90
+ assert.equal(hits.length, 10, "窗口宽度不变");
91
+ assert.deepEqual(hits[0], { id: live.id, archived: false, forgotten: false });
92
+ store.close();
93
+ });
94
+
95
+ test("update 与 compareAndUpdate 都重算 content_hash", () => {
96
+ const store = createStore(":memory:");
97
+ const saved = store.save({ type: "project", title: "T", content: "旧正文" });
98
+ assert.equal(store.findContentHashMatches({ type: "project", hash: contentHashOf({ title: "T", content: "旧正文" }) }).length, 1);
99
+
100
+ const updated = store.update(saved.id, { content: "新正文" });
101
+ assert.equal(updated.content_hash, contentHashOf({ title: "T", content: "新正文" }));
102
+ assert.equal(
103
+ store.findContentHashMatches({ type: "project", hash: contentHashOf({ title: "T", content: "旧正文" }) }).length,
104
+ 0,
105
+ "旧内容的锚必须失效"
106
+ );
107
+
108
+ const cas = store.compareAndUpdate(updated.id, updated.updated_at, { title: "T2" });
109
+ assert.equal(cas.content_hash, contentHashOf({ title: "T2", content: "新正文" }));
110
+ assert.equal(
111
+ store.findContentHashMatches({ type: "project", hash: contentHashOf({ title: "T", content: "新正文" }) }).length,
112
+ 0,
113
+ "CAS 路径漏重算的话标记会指向不再存在的内容"
114
+ );
115
+ store.close();
116
+ });
117
+
118
+ test("demoteToSummary 与 restoreContent 也重算 content_hash", () => {
119
+ const store = createStore(":memory:");
120
+ const saved = store.save({ type: "project", title: "T", content: "完整正文" });
121
+ const demoted = store.demoteToSummary(saved.id, "摘要行");
122
+ assert.equal(demoted.content_hash, contentHashOf({ title: "T", content: "摘要行" }));
123
+ assert.equal(
124
+ store.findContentHashMatches({ type: "project", hash: contentHashOf({ title: "T", content: "完整正文" }) }).length,
125
+ 0,
126
+ "降级后的行装的是摘要,锚不能还指着完整正文"
127
+ );
128
+
129
+ const restored = store.restoreContent(saved.id);
130
+ assert.equal(restored.content_hash, contentHashOf({ title: "T", content: "完整正文" }));
131
+ store.close();
132
+ });
133
+
134
+ test("老库打开:加列 + 建索引 + 存量回填(索引顺序错会直接开不起来)", () => {
135
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-hash-migrate-"));
136
+ const dbPath = join(dir, "legacy.db");
137
+ try {
138
+ const legacy = new DatabaseSync(dbPath);
139
+ legacy.exec(`CREATE TABLE memories (
140
+ id TEXT PRIMARY KEY, type TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL,
141
+ tags TEXT NOT NULL DEFAULT '[]', importance INTEGER NOT NULL DEFAULT 3,
142
+ forgotten INTEGER NOT NULL DEFAULT 0, archived INTEGER NOT NULL DEFAULT 0,
143
+ source TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
144
+ );`);
145
+ legacy
146
+ .prepare(
147
+ "INSERT INTO memories (id, type, title, content, tags, importance, forgotten, archived, source, created_at, updated_at) VALUES (?, ?, ?, ?, '[]', 3, 0, ?, NULL, ?, ?)"
148
+ )
149
+ .run("legacy-1", "project", "老库事实", "同一件事的正文", 0, "2026-01-01T00:00:00.000Z", "2026-01-01T00:00:00.000Z");
150
+ legacy
151
+ .prepare(
152
+ "INSERT INTO memories (id, type, title, content, tags, importance, forgotten, archived, source, created_at, updated_at) VALUES (?, ?, ?, ?, '[]', 3, 0, ?, NULL, ?, ?)"
153
+ )
154
+ .run("legacy-2", "project", "被归档的老事实", "归档区里同一件事的正文", 1, "2026-01-02T00:00:00.000Z", "2026-01-02T00:00:00.000Z");
155
+ legacy.close();
156
+
157
+ const store = createStore(dbPath);
158
+ const index = store.db
159
+ .prepare("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_memories_content_hash'")
160
+ .get();
161
+ assert.ok(index, "老库也要建上索引(候选集靠它 seek,否则每次写入都是全表扫)");
162
+
163
+ // 索引不只是「存在」:回填的 NULL 扫描与准入的候选集查询都得真的走它。列序写反
164
+ // (type 打头)时前者退化成全表扫——每次打开都要把全部正文读一遍。
165
+ const planOf = (sql, ...params) =>
166
+ store.db.prepare(`EXPLAIN QUERY PLAN ${sql}`).all(...params).map((r) => r.detail).join(" | ");
167
+ assert.match(
168
+ planOf("SELECT id, title, content FROM memories WHERE content_hash IS NULL"),
169
+ /idx_memories_content_hash/,
170
+ "存量回填走索引"
171
+ );
172
+ assert.match(
173
+ planOf("SELECT id FROM memories WHERE type = ? AND content_hash = ?", "project", "x"),
174
+ /idx_memories_content_hash/,
175
+ "候选集查询走索引"
176
+ );
177
+
178
+ const backfilled = store.getById("legacy-1");
179
+ assert.equal(backfilled.content_hash, contentHashOf({ title: "老库事实", content: "同一件事的正文" }));
180
+ assert.deepEqual(
181
+ store.findContentHashMatches({ type: "project", hash: backfilled.content_hash }).map((m) => m.id),
182
+ ["legacy-1"]
183
+ );
184
+ const archivedBackfilled = store.getById("legacy-2");
185
+ assert.deepEqual(
186
+ store.findContentHashMatches({ type: "project", hash: archivedBackfilled.content_hash }),
187
+ [{ id: "legacy-2", archived: true, forgotten: false }],
188
+ "存量归档行回填后也要在候选集里(不然这条信号在老库上量不到归档区)"
189
+ );
190
+
191
+ // 回填后仍能正常写入(幂等迁移没有把表锁死)
192
+ const fresh = store.save({ type: "project", title: "新行", content: "新正文" });
193
+ assert.ok(fresh.content_hash);
194
+ const firstPassHash = archivedBackfilled.content_hash;
195
+ store.close();
196
+
197
+ // 再开一次:只算 NULL 行,已有锚原样保留
198
+ const again = createStore(dbPath);
199
+ assert.equal(again.getById("legacy-2").content_hash, firstPassHash, "重复打开不得改写已有锚");
200
+ again.close();
201
+ } finally {
202
+ rmSync(dir, { recursive: true, force: true });
203
+ }
204
+ });