@modusensus/dsh-mneme 0.12.0 → 0.14.0-beta.1

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 (182) hide show
  1. package/README.md +51 -20
  2. package/bin/dsh-mneme-choro.mjs +9 -1
  3. package/docs/CONFIGURATION.md +47 -6
  4. package/docs/DIRECTORIES.md +114 -0
  5. package/docs/DISTILL.md +64 -0
  6. package/docs/DSH-GO.md +97 -0
  7. package/docs/ENTITIES.md +5 -3
  8. package/docs/FORGET.md +77 -0
  9. package/docs/KB.md +110 -0
  10. package/docs/SLEEP.md +28 -3
  11. package/docs/STORAGE.md +23 -0
  12. package/lib/api-standalone.js +4 -1
  13. package/lib/api.js +788 -30
  14. package/lib/attachment-text.js +122 -0
  15. package/lib/choro-command.js +9 -2
  16. package/lib/client.js +4627 -1409
  17. package/lib/config.js +166 -1
  18. package/lib/continuity.js +7 -6
  19. package/lib/diary/auto.js +190 -0
  20. package/lib/diary/compose.js +440 -0
  21. package/lib/diary/dir.js +59 -0
  22. package/lib/diary/export.js +97 -0
  23. package/lib/diary/index.js +26 -0
  24. package/lib/diary/library.js +189 -0
  25. package/lib/diary/qq-inbox.js +142 -0
  26. package/lib/diary/rollover.js +61 -0
  27. package/lib/diary/session-provider.js +122 -0
  28. package/lib/dream/decisions.js +95 -6
  29. package/lib/dream/sleep.js +760 -19
  30. package/lib/dream/triage.js +139 -0
  31. package/lib/dream.js +168 -21
  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 +22 -11
  44. package/lib/index.js +123 -3
  45. package/lib/inject.js +203 -20
  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 +98 -4
  50. package/lib/peak-hours.js +57 -2
  51. package/lib/semantic.js +347 -60
  52. package/lib/service.js +268 -69
  53. package/lib/settings.js +128 -15
  54. package/lib/store.js +585 -26
  55. package/lib/summarize.js +38 -11
  56. package/lib/tools.js +35 -4
  57. package/lib/user-settings.js +128 -32
  58. package/lib/vector-index.js +76 -6
  59. package/lib/wiki/claims.js +267 -0
  60. package/lib/wiki/cli-hint.js +90 -0
  61. package/lib/wiki/queries.js +282 -2
  62. package/lib/wiki/render.js +74 -0
  63. package/lib/wiki/t0.js +43 -6
  64. package/lib/wiki/t1-jobs.js +232 -0
  65. package/lib/wiki/t1.js +145 -32
  66. package/package.json +39 -1
  67. package/scripts/release-docs.mjs +7 -1
  68. package/scripts/release-notes.mjs +4 -1
  69. package/src/api-standalone.js +4 -1
  70. package/src/api.js +788 -30
  71. package/src/attachment-text.js +122 -0
  72. package/src/choro-command.js +9 -2
  73. package/src/config.js +166 -1
  74. package/src/continuity.js +7 -6
  75. package/src/diary/auto.js +190 -0
  76. package/src/diary/compose.js +440 -0
  77. package/src/diary/dir.js +59 -0
  78. package/src/diary/export.js +97 -0
  79. package/src/diary/index.js +26 -0
  80. package/src/diary/library.js +189 -0
  81. package/src/diary/qq-inbox.js +142 -0
  82. package/src/diary/rollover.js +61 -0
  83. package/src/diary/session-provider.js +122 -0
  84. package/src/dream/decisions.js +95 -6
  85. package/src/dream/sleep.js +760 -19
  86. package/src/dream/triage.js +139 -0
  87. package/src/dream.js +168 -21
  88. package/src/dsh-go/host.js +162 -0
  89. package/src/dsh-go/panel.js +2091 -0
  90. package/src/dsh-go/text.js +342 -0
  91. package/src/dsh-go/views/common.js +68 -0
  92. package/src/dsh-go/views/entity.js +48 -0
  93. package/src/dsh-go/views/memory.js +198 -0
  94. package/src/dsh-go/views/root.js +30 -0
  95. package/src/dsh-go/views/settings.js +398 -0
  96. package/src/dsh-go/views/status.js +51 -0
  97. package/src/embedding.js +42 -8
  98. package/src/entities/extractor.js +36 -7
  99. package/src/hot-memory.js +22 -11
  100. package/src/index.js +123 -3
  101. package/src/inject.js +203 -20
  102. package/src/kb/index.js +309 -0
  103. package/src/kb/routes.js +220 -0
  104. package/src/kb/tools.js +148 -0
  105. package/src/lang.js +98 -4
  106. package/src/peak-hours.js +57 -2
  107. package/src/semantic.js +347 -60
  108. package/src/service.js +268 -69
  109. package/src/settings.js +128 -15
  110. package/src/store.js +585 -26
  111. package/src/summarize.js +38 -11
  112. package/src/tools.js +35 -4
  113. package/src/user-settings.js +128 -32
  114. package/src/vector-index.js +76 -6
  115. package/src/wiki/claims.js +267 -0
  116. package/src/wiki/cli-hint.js +90 -0
  117. package/src/wiki/queries.js +282 -2
  118. package/src/wiki/render.js +74 -0
  119. package/src/wiki/t0.js +43 -6
  120. package/src/wiki/t1-jobs.js +232 -0
  121. package/src/wiki/t1.js +145 -32
  122. package/test/api-routes-gaps.test.js +63 -0
  123. package/test/api.test.js +385 -4
  124. package/test/attachment-text.test.js +140 -0
  125. package/test/bm25-corpus-cache.test.js +145 -0
  126. package/test/capacity-warning.test.js +262 -0
  127. package/test/client.test.js +1051 -185
  128. package/test/conflict-freeze.test.js +45 -1
  129. package/test/conflict-ledger-enforce.test.js +452 -0
  130. package/test/conflict-ledger.test.js +242 -0
  131. package/test/continuity.test.js +8 -1
  132. package/test/contrast.test.js +124 -12
  133. package/test/diary-library.test.js +187 -0
  134. package/test/diary.test.js +576 -0
  135. package/test/dream-baseline-clamp.test.js +174 -0
  136. package/test/dream-maxtokens-fallback.test.js +3 -3
  137. package/test/dream.test.js +62 -1
  138. package/test/dsh-go-host.test.js +134 -0
  139. package/test/dsh-go-panel-actions.test.js +854 -0
  140. package/test/dsh-go-panel.test.js +251 -0
  141. package/test/embedding-ready.test.js +33 -3
  142. package/test/entities.test.js +73 -0
  143. package/test/forget-corrections.test.js +70 -0
  144. package/test/graph-api.test.js +124 -0
  145. package/test/hot-memory.test.js +48 -0
  146. package/test/image-memory.test.js +171 -0
  147. package/test/inject-parent-gate.test.js +6 -3
  148. package/test/inject.test.js +59 -0
  149. package/test/issue-617-step1-query-and-fusion.test.js +361 -0
  150. package/test/kb-api-wiring.test.js +128 -0
  151. package/test/kb-collections.test.js +272 -0
  152. package/test/kb-routes.test.js +379 -0
  153. package/test/mint-source.test.js +26 -0
  154. package/test/panel-chart-scale.test.js +90 -0
  155. package/test/panel-tokens.test.js +245 -0
  156. package/test/peak-hours-observability.test.js +70 -0
  157. package/test/persona-api.test.js +3 -3
  158. package/test/persona-by-session.test.js +568 -0
  159. package/test/persona-settings.test.js +7 -7
  160. package/test/reflection-update-gate.test.js +129 -0
  161. package/test/reindex-backfill.test.js +334 -0
  162. package/test/reindex-scheduler.test.js +369 -0
  163. package/test/release-docs.test.js +20 -0
  164. package/test/release-notes.test.js +25 -0
  165. package/test/scope-candidates.test.js +249 -0
  166. package/test/security-doc.test.js +10 -0
  167. package/test/sleep-action-set.test.js +14 -0
  168. package/test/sleep-heat.test.js +49 -0
  169. package/test/sleep.test.js +635 -0
  170. package/test/standalone-api.test.js +24 -0
  171. package/test/store.test.js +20 -0
  172. package/test/summarize.test.js +26 -0
  173. package/test/user-settings-segments.test.js +528 -0
  174. package/test/vector-index.test.js +120 -6
  175. package/test/wiki-api.test.js +463 -1
  176. package/test/wiki-claims.test.js +194 -0
  177. package/test/wiki-cli-hint.test.js +118 -0
  178. package/test/wiki-provenance.test.js +202 -0
  179. package/test/wiki-queries.test.js +128 -0
  180. package/test/wiki-t0.test.js +77 -1
  181. package/test/wiki-t1-jobs.test.js +125 -0
  182. package/test/wiki-t1.test.js +226 -1
@@ -0,0 +1,145 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { createService } from "../src/service.js";
5
+
6
+ // #617 审计 O2 回归:BM25 语料索引按 mirror_state.generation 缓存。
7
+ //
8
+ // 断言观测点选 store.list({ limit: 500 }) 的调用次数,不选耗时——耗时在 CI 上
9
+ // 抖动大,而「这一轮到底有没有重新取语料重建索引」是确定性事实。
10
+ //
11
+ // 一正一反两把尺子:正向锁「缓存真的命中了」,反向(写入 / 归档 / 开关)锁
12
+ // 「该失效的时候真的失效了」——只有正向会让「永不失效」的实现也全绿。
13
+
14
+ function setup(over = {}) {
15
+ const store = createStore(":memory:");
16
+ const config = { entitySearchEnabled: false, bm25SearchEnabled: true, ...over };
17
+ const service = createService({ store, mirror: null, config, logger: null });
18
+ // 只数语料取数:searchMemories 里还有别的 list 调用,按 limit 精确匹配。
19
+ let corpusLoads = 0;
20
+ const origList = store.list.bind(store);
21
+ store.list = (opts) => {
22
+ if (opts?.limit === 500) corpusLoads += 1;
23
+ return origList(opts);
24
+ };
25
+ return { store, service, loads: () => corpusLoads };
26
+ }
27
+
28
+ // auto 且不装 embedder:向量路不启动,词法结果按 blend 的 auto 分支领位后由
29
+ // BM25 补位——这条路径下 BM25 命中真的会进返回值,断言才钉在用户可见的行为上,
30
+ // 而不是「索引建了但没人用」。
31
+ const recall = (service, q) => service.searchMemories(q, { mode: "auto", topK: 5, useRerank: false, recordRecall: false });
32
+
33
+ test("#617-O2: 同一水位下多条查询共用一份语料索引,不重复重建", async () => {
34
+ const { store, service, loads } = setup();
35
+ store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
36
+
37
+ const first = await recall(service, "rust 异步");
38
+ assert.equal(loads(), 1, "首查要建一次索引");
39
+ assert.ok(first.length > 0, "夹具前提:这条查询本来就有命中");
40
+
41
+ // 换一条查询:索引是按语料缓存的,不该因为 query 变了就重建。
42
+ await recall(service, "tokio");
43
+ await recall(service, "完全不相干的词");
44
+ assert.equal(loads(), 1, "语料没变,三次查询只该取一次语料");
45
+ });
46
+
47
+ test("#617-O2: 写入新记忆后索引失效,新行立刻可召回", async () => {
48
+ const { store, service, loads } = setup();
49
+ store.save({ type: "project", title: "夜间 ETL 脚本", content: "离线批处理", importance: 3 });
50
+ await recall(service, "离线批处理");
51
+ assert.equal(loads(), 1);
52
+
53
+ const fresh = store.save({ type: "project", title: "令牌桶限流", content: "ratelimit 令牌桶", importance: 3 });
54
+ const ids = (await recall(service, "令牌桶")).map((r) => r.id);
55
+ assert.equal(loads(), 2, "写了新行,语料变了,必须重建");
56
+ assert.ok(ids.includes(fresh.id), "重建后新行必须能被词法召回(陈旧索引会漏掉它)");
57
+ });
58
+
59
+ test("#617-O2: 归档后索引失效,归档行退出词法召回", async () => {
60
+ const { store, service, loads } = setup();
61
+ const m = store.save({ type: "project", title: "令牌桶限流", content: "ratelimit 令牌桶", importance: 3 });
62
+ assert.ok((await recall(service, "令牌桶")).some((r) => r.id === m.id), "夹具前提:归档前能召回");
63
+
64
+ store.setArchived(m.id, true);
65
+ const ids = (await recall(service, "令牌桶")).map((r) => r.id);
66
+ assert.equal(loads(), 2, "可见性变了要重建");
67
+ assert.ok(!ids.includes(m.id), "归档行不得留在索引里");
68
+ });
69
+
70
+ test("#617-O2: 触达与重嵌不改语料,不该让索引失效", async () => {
71
+ const { store, service, loads } = setup();
72
+ const m = store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
73
+ await recall(service, "rust 异步");
74
+ assert.equal(loads(), 1);
75
+
76
+ // 这两类写入刻意不 bump generation(store.js:reads must not mark the mirror
77
+ // dirty),也不改 title+content。缓存若跟着它们失效,就等于每轮注入都白重建
78
+ // ——正是 O2 要消除的成本。
79
+ store.touchLastAccess(m.id);
80
+ store.setEmbedding(m.id, [0.1, 0.2, 0.3]);
81
+ await recall(service, "rust 异步");
82
+ assert.equal(loads(), 1, "触达 / 重嵌不构成语料变化");
83
+ });
84
+
85
+ test("#617-O2: bm25SearchEnabled=false 时根本不取语料", async () => {
86
+ const { store, service, loads } = setup({ bm25SearchEnabled: false });
87
+ store.save({ type: "project", title: "异步并发模式", content: "async runtime 选用 tokio", importance: 3 });
88
+ const rows = await recall(service, "rust 异步");
89
+ assert.equal(loads(), 0, "开关关着连语料都不该取");
90
+ assert.ok(!rows.some((r) => r.source === "bm25"));
91
+ });
92
+
93
+ test("#617-O2: 空库不缓存空索引,后续写入仍可召回", async () => {
94
+ const { store, service, loads } = setup();
95
+ assert.deepEqual(await recall(service, "令牌桶"), [], "夹具前提:空库没有命中");
96
+
97
+ const m = store.save({ type: "project", title: "令牌桶限流", content: "ratelimit 令牌桶", importance: 3 });
98
+ const ids = (await recall(service, "令牌桶")).map((r) => r.id);
99
+ assert.ok(ids.includes(m.id), "空库那一轮不得留下「空索引」这种缓存");
100
+ assert.equal(loads(), 2);
101
+ });
102
+
103
+ test("#617-O2: 水位偶发读不到时,不拿旧索引冒充当前语料", async () => {
104
+ const { store, service, loads } = setup();
105
+ store.save({ type: "project", title: "夜间 ETL 脚本", content: "离线批处理", importance: 3 });
106
+ await recall(service, "离线批处理");
107
+ assert.equal(loads(), 1, "夹具前提:正常路径已经缓存了一份索引");
108
+
109
+ // 模拟 mirror_state 读不出来(库锁 / 迁移窗口)。此时无法证明缓存新鲜,必须
110
+ // 退回重建,而不是把 generation 当成 null 去和缓存里的旧值比对后命中。
111
+ const realGet = store.getMirrorState.bind(store);
112
+ store.getMirrorState = () => { throw new Error("mirror_state unavailable"); };
113
+ const fresh = store.save({ type: "project", title: "令牌桶限流", content: "ratelimit 令牌桶", importance: 3 });
114
+ const ids = (await recall(service, "令牌桶")).map((r) => r.id);
115
+ assert.ok(ids.includes(fresh.id), "水位不可读时仍要看到新写入的行");
116
+ assert.equal(loads(), 2);
117
+
118
+ // 恢复可读:期间确实写过,水位已经变了,于是再重建一次拿到的才是与水位对齐
119
+ // 的索引——宁可多建一次,也不能让缓存条目声称自己代表某个它没见过的版本。
120
+ store.getMirrorState = realGet;
121
+ await recall(service, "令牌桶");
122
+ assert.equal(loads(), 3, "水位已前进,恢复后须重建一次把条目对齐到新水位");
123
+
124
+ // 对齐之后再查就不该再重建了。
125
+ await recall(service, "离线批处理");
126
+ assert.equal(loads(), 3, "对齐后回到正常缓存路径");
127
+ });
128
+
129
+ test("#617-O2: 水位读不到但期间没有写入时,恢复后直接命中旧索引", async () => {
130
+ const { store, service, loads } = setup();
131
+ store.save({ type: "project", title: "夜间 ETL 脚本", content: "离线批处理", importance: 3 });
132
+ await recall(service, "离线批处理");
133
+ assert.equal(loads(), 1);
134
+
135
+ // 读失败但语料没变:此时丢掉缓存纯属白干。保留上一份「已知有效 generation」
136
+ // 的条目,恢复后水位一致就直接命中。
137
+ const realGet = store.getMirrorState.bind(store);
138
+ store.getMirrorState = () => { throw new Error("mirror_state unavailable"); };
139
+ await recall(service, "离线批处理");
140
+ assert.equal(loads(), 2, "读不到水位只能重建(无法证明缓存新鲜)");
141
+
142
+ store.getMirrorState = realGet;
143
+ await recall(service, "离线批处理");
144
+ assert.equal(loads(), 2, "期间无写入,恢复后不该再白建一次");
145
+ });
@@ -0,0 +1,262 @@
1
+ // #275 容量预警(空间维度)回归:store 行数口径 → service 判级与 fail-safe →
2
+ // /health 的 capacity 挂载。三层各锁各的:
3
+ // store.capacityStats —— 活跃/归档两格,setArchived 翻位即反映;
4
+ // getCapacityHealth —— 阈值判级(>= 过线、0 = 关)、:memory: 的缺席语义、
5
+ // fail-safe(读坏显式 unknown,绝不伪装 ok);
6
+ // /health —— capacity 与 mirror 同面但互相独立,且不带库文件路径(半张对外面
7
+ // 不泄露本机布局)。
8
+ // 面板卡在 lib/client.js(无 src 对应物),由 test/client.test.js 的字符串锁兜住。
9
+ // 阈值配置一律在 createService 时传入:createService 闭包持有 config,事后改
10
+ // service.config 属性够不着判级读的那份(闭包变量),改了也是假绿。
11
+ // 判级用例用裸 config({}):memoryQualityFilter 解析默认开,短正文样例会被静默
12
+ // 归档,行数断言就全歪了——裸 config 下该闸不参与,这正是这些用例要的写入面。
13
+ import test from "node:test";
14
+ import assert from "node:assert/strict";
15
+ import { mkdtempSync, rmSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { EventEmitter } from "node:events";
19
+ import { createStore } from "../src/store.js";
20
+ import { createService } from "../src/service.js";
21
+ import { createApi } from "../src/api.js";
22
+ import { createSettings } from "../src/settings.js";
23
+ import { Config, CAPACITY_WARNING_DEFAULTS } from "../src/config.js";
24
+
25
+ function seed(service, n) {
26
+ const ids = [];
27
+ for (let i = 0; i < n; i++) {
28
+ const res = service.saveWithDedupe({
29
+ type: "project", title: `容量样例 ${i}`, content: `容量样例正文 ${i},长度足够不被过滤`, importance: 3
30
+ });
31
+ ids.push(res.memory.id);
32
+ }
33
+ return ids;
34
+ }
35
+
36
+ // ── store.capacityStats ───────────────────────────────────────────────────────
37
+
38
+ test("capacityStats 分活跃/归档两格;归档与还原都即时反映", () => {
39
+ const store = createStore(":memory:");
40
+ const service = createService({ store, mirror: null, config: {} });
41
+ try {
42
+ const ids = seed(service, 3);
43
+ assert.deepEqual(store.capacityStats(), { active: 3, archived: 0 });
44
+ store.setArchived(ids[0], true);
45
+ store.setArchived(ids[1], true);
46
+ assert.deepEqual(store.capacityStats(), { active: 1, archived: 2 });
47
+ // 还原(memory_archive 的出口)回到活跃:占比口径要跟着翻回去
48
+ store.setArchived(ids[0], false);
49
+ assert.deepEqual(store.capacityStats(), { active: 2, archived: 1 });
50
+ } finally {
51
+ store.close();
52
+ }
53
+ });
54
+
55
+ // ── schema:阈值默认值与边界 ──────────────────────────────────────────────────
56
+
57
+ test("capacityWarning schema:默认值锚定议题形态区间,边界与部分覆盖语义钉死", () => {
58
+ const cfg = Config({});
59
+ assert.deepEqual(
60
+ { ...cfg.capacityWarning },
61
+ { dbSizeWarnMb: 256, archivedRowsWarn: 5000, archivedRatioWarn: 0.95 },
62
+ "解析默认必须与 CAPACITY_WARNING_DEFAULTS 一致(service 的裸 config 回退也用这份)"
63
+ );
64
+ assert.deepEqual(
65
+ { ...CAPACITY_WARNING_DEFAULTS },
66
+ { dbSizeWarnMb: 256, archivedRowsWarn: 5000, archivedRatioWarn: 0.95 }
67
+ );
68
+ // 部分覆盖时其余键落默认(.default({}) 的内层默认语义)
69
+ assert.equal(Config({ capacityWarning: { dbSizeWarnMb: 0 } }).capacityWarning.archivedRowsWarn, 5000);
70
+ // 越界一律拒(负数、浮点 MB、占比 > 1)
71
+ assert.throws(() => Config({ capacityWarning: { dbSizeWarnMb: -1 } }));
72
+ assert.throws(() => Config({ capacityWarning: { dbSizeWarnMb: 1.5 } }));
73
+ assert.throws(() => Config({ capacityWarning: { archivedRowsWarn: -3 } }));
74
+ assert.throws(() => Config({ capacityWarning: { archivedRatioWarn: 1.5 } }));
75
+ });
76
+
77
+ // ── service.getCapacityHealth ────────────────────────────────────────────────
78
+
79
+ test("getCapacityHealth ok 态:检查齐全、占比归零;:memory: 库无体积检查(缺席≠伪装 ok)", () => {
80
+ const store = createStore(":memory:");
81
+ const service = createService({ store, mirror: null, config: {} });
82
+ try {
83
+ seed(service, 1);
84
+ const cap = service.getCapacityHealth();
85
+ assert.equal(cap.status, "ok");
86
+ // :memory: 没有磁盘足迹:file_bytes 为 null,db_size 检查**缺席**而不是 ok
87
+ assert.equal(cap.file_bytes, null);
88
+ assert.equal(cap.checks.some((c) => c.key === "db_size"), false);
89
+ // 行数与占比检查在(total > 0)
90
+ assert.equal(cap.active_rows, 1);
91
+ assert.equal(cap.archived_rows, 0);
92
+ assert.equal(cap.archived_ratio, 0);
93
+ const rows = cap.checks.find((c) => c.key === "archived_rows");
94
+ assert.equal(rows.status, "ok");
95
+ assert.equal(rows.value, 0);
96
+ assert.equal(rows.threshold, 5000, "裸 config(未解析)也要落到同一份默认阈值");
97
+ const ratio = cap.checks.find((c) => c.key === "archived_ratio");
98
+ assert.equal(ratio.status, "ok");
99
+ // freelist 是页数 × 页大小::memory: 也有页,给数字而不是 null
100
+ assert.equal(typeof cap.freelist_bytes, "number");
101
+ assert.ok(cap.freelist_bytes >= 0);
102
+ } finally {
103
+ store.close();
104
+ }
105
+ });
106
+
107
+ test("getCapacityHealth 判级:archived_rows 到阈值 → warn,值/阈值能对上;低一格回 ok", () => {
108
+ const store = createStore(":memory:");
109
+ try {
110
+ const mk = (threshold) => createService({
111
+ store, mirror: null,
112
+ config: { capacityWarning: { dbSizeWarnMb: 0, archivedRowsWarn: threshold, archivedRatioWarn: 0 } }
113
+ });
114
+ const ids = seed(mk(2), 3);
115
+ store.setArchived(ids[0], true);
116
+ store.setArchived(ids[1], true);
117
+ // 0 = 显式关掉另外两条,只剩条数检查——每条检查能被独立开关是判级的前提
118
+ const cap = mk(2).getCapacityHealth();
119
+ assert.equal(cap.status, "warn");
120
+ assert.deepEqual(cap.checks.map((c) => c.key), ["archived_rows"]);
121
+ assert.equal(cap.checks[0].status, "warn");
122
+ assert.equal(cap.checks[0].value, 2);
123
+ assert.equal(cap.checks[0].threshold, 2);
124
+ // 阈值之下一格就回到 ok
125
+ assert.equal(mk(3).getCapacityHealth().status, "ok");
126
+ } finally {
127
+ store.close();
128
+ }
129
+ });
130
+
131
+ test("getCapacityHealth 判级:archived_ratio 过线 → warn,值按千分位取整", () => {
132
+ const store = createStore(":memory:");
133
+ const service = createService({
134
+ store, mirror: null,
135
+ config: { capacityWarning: { dbSizeWarnMb: 0, archivedRowsWarn: 0, archivedRatioWarn: 0.5 } }
136
+ });
137
+ try {
138
+ const ids = seed(service, 3);
139
+ store.setArchived(ids[0], true);
140
+ store.setArchived(ids[1], true);
141
+ const cap = service.getCapacityHealth();
142
+ assert.equal(cap.status, "warn");
143
+ const ratio = cap.checks.find((c) => c.key === "archived_ratio");
144
+ assert.equal(ratio.status, "warn");
145
+ assert.equal(ratio.value, 0.667, "2/3 取整到千分位");
146
+ assert.equal(ratio.threshold, 0.5);
147
+ } finally {
148
+ store.close();
149
+ }
150
+ });
151
+
152
+ test("getCapacityHealth 判级:db_size 过线 → warn(文件库,足迹含主文件 + WAL)", () => {
153
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-cap-"));
154
+ try {
155
+ const store = createStore(join(dir, "memory.db"));
156
+ const service = createService({
157
+ store, mirror: null,
158
+ config: { capacityWarning: { dbSizeWarnMb: 1, archivedRowsWarn: 0, archivedRatioWarn: 0 } }
159
+ });
160
+ // 单条 2MB 正文把库顶过 1 MB 预警线——dbSizeWarnMb 是整数 MB,比它小的只有关 (0)
161
+ service.saveWithDedupe({ type: "project", title: "大块头", content: "x".repeat(2 * 1048576), importance: 3 });
162
+ const cap = service.getCapacityHealth();
163
+ assert.equal(cap.status, "warn");
164
+ const size = cap.checks.find((c) => c.key === "db_size");
165
+ assert.equal(size.status, "warn");
166
+ assert.ok(size.value_bytes >= size.threshold_bytes, "file_bytes 含主文件 + WAL,必须真的过线");
167
+ assert.equal(size.threshold_bytes, 1048576);
168
+ store.close();
169
+ } finally {
170
+ rmSync(dir, { recursive: true, force: true });
171
+ }
172
+ });
173
+
174
+ test("getCapacityHealth fail-safe:store 关掉后不抛、显式 unknown、绝不伪装 ok", () => {
175
+ const store = createStore(":memory:");
176
+ const warns = [];
177
+ const service = createService({ store, mirror: null, config: {}, logger: { warn: (...a) => warns.push(a) } });
178
+ seed(service, 1);
179
+ store.close();
180
+ const cap = service.getCapacityHealth();
181
+ assert.equal(cap.status, "unknown");
182
+ assert.equal(cap.file_bytes, null);
183
+ assert.equal(cap.archived_rows, null);
184
+ assert.deepEqual(cap.checks, []);
185
+ assert.ok(warns.some((w) => String(w[0]).includes("getCapacityHealth failed")), "失败必须走 logger.warn");
186
+ });
187
+
188
+ // ── /health 挂载 ─────────────────────────────────────────────────────────────
189
+
190
+ class FakeRes extends EventEmitter {
191
+ constructor() { super(); this.statusCode = 200; this.body = ""; }
192
+ writeHead(code, headers) { this.statusCode = code; this.headers = headers; return this; }
193
+ end(text) { this.body = text ?? ""; this.emit("end"); return this; }
194
+ }
195
+
196
+ function makeHealthRoute(store, service) {
197
+ const settings = createSettings(store.db);
198
+ const commands = {
199
+ add: (def) => settings.addCommand(def),
200
+ remove: (id) => settings.removeCommand(id),
201
+ list: () => settings.listCommands()
202
+ };
203
+ const routes = [];
204
+ const ctx = { webServer: { register(route) { routes.push(route); return () => {}; } } };
205
+ createApi(ctx, service, settings, commands, undefined, undefined, "");
206
+ const route = routes.find((r) => r.path === "/api/dsh-mneme/health");
207
+ assert.ok(route, "必须注册 /health 路由");
208
+ return route;
209
+ }
210
+
211
+ test("/health 挂 capacity:与 mirror 同面、数字可读、不带库文件路径", async () => {
212
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-cap-"));
213
+ try {
214
+ const store = createStore(join(dir, "memory.db"));
215
+ const service = createService({ store, mirror: null, config: {} });
216
+ seed(service, 1);
217
+ const route = makeHealthRoute(store, service);
218
+ const res = new FakeRes();
219
+ await route.handler({ url: "/api/dsh-mneme/health", method: "GET", headers: {} }, res);
220
+ assert.equal(res.statusCode, 200);
221
+ const body = JSON.parse(res.body);
222
+ assert.ok(body.mirror, "镜像块不动");
223
+ assert.ok(body.capacity, "capacity 块必须在");
224
+ assert.equal(body.capacity.status, "ok");
225
+ assert.equal(typeof body.capacity.file_bytes, "number", "文件库要给磁盘足迹");
226
+ assert.equal(body.capacity.active_rows, 1);
227
+ assert.ok(Array.isArray(body.capacity.checks) && body.capacity.checks.length === 3, "文件库三道检查齐全");
228
+ // /health 是半张对外面:数字可以给,本机文件系统布局不能给
229
+ assert.ok(!res.body.includes(dir), "响应不得携带临时目录路径");
230
+ assert.ok(!res.body.includes("memory.db"), "响应不得携带库文件名");
231
+ // 库关掉后两个半张各自 fail-closed:mirror 既有语义不动,capacity 显式 unknown
232
+ store.close();
233
+ const resBroken = new FakeRes();
234
+ await route.handler({ url: "/api/dsh-mneme/health", method: "GET", headers: {} }, resBroken);
235
+ const broken = JSON.parse(resBroken.body);
236
+ assert.equal(broken.mirror.status, "unknown");
237
+ assert.equal(broken.capacity.status, "unknown");
238
+ } finally {
239
+ rmSync(dir, { recursive: true, force: true });
240
+ }
241
+ });
242
+
243
+ test("/health:没接线 getCapacityHealth 的 service → capacity 显式 null,不编造形状", async () => {
244
+ const store = createStore(":memory:");
245
+ const service = createService({ store, mirror: null, config: {} });
246
+ try {
247
+ seed(service, 1);
248
+ const route = makeHealthRoute(store, service);
249
+ const res = new FakeRes();
250
+ await route.handler({ url: "/api/dsh-mneme/health", method: "GET", headers: {} }, res);
251
+ assert.equal(JSON.parse(res.body).capacity.status, "ok");
252
+ // 老 mock / 旧版本 service 没有这个方法:handler 不得炸,capacity 落 null
253
+ // (面板渲染成「未知」,不冒充正常)
254
+ delete service.getCapacityHealth;
255
+ const resOld = new FakeRes();
256
+ await route.handler({ url: "/api/dsh-mneme/health", method: "GET", headers: {} }, resOld);
257
+ assert.equal(resOld.statusCode, 200);
258
+ assert.equal(JSON.parse(resOld.body).capacity, null);
259
+ } finally {
260
+ store.close();
261
+ }
262
+ });