@modusensus/dsh-mneme 0.8.13 → 0.8.15

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 (271) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +655 -626
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +689 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -0
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +263 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/ENTITIES.md +245 -0
  12. package/docs/LOCAL_MODEL.md +222 -0
  13. package/docs/SEMANTIC.md +256 -0
  14. package/docs/SLEEP.md +164 -0
  15. package/docs/STORAGE.md +89 -0
  16. package/lib/api-standalone.js +673 -572
  17. package/lib/api.js +1437 -1433
  18. package/lib/bootstrap.js +211 -211
  19. package/lib/client.js +5444 -5295
  20. package/lib/commands.js +95 -95
  21. package/lib/config.js +880 -836
  22. package/lib/content-hash.js +54 -54
  23. package/lib/continuity.js +220 -220
  24. package/lib/document-index.js +94 -94
  25. package/lib/document.js +303 -303
  26. package/lib/dream/clustering.js +118 -118
  27. package/lib/dream/decisions.js +674 -674
  28. package/lib/dream/narratives.js +44 -44
  29. package/lib/dream/sleep.js +819 -819
  30. package/lib/dream.js +1501 -1501
  31. package/lib/embedding.js +177 -177
  32. package/lib/entities/extractor.js +252 -252
  33. package/lib/graph/anchoring.js +179 -179
  34. package/lib/guide.js +74 -74
  35. package/lib/heat.js +144 -144
  36. package/lib/hot-memory.js +46 -46
  37. package/lib/index.js +535 -671
  38. package/lib/inject.js +464 -450
  39. package/lib/lang.js +248 -229
  40. package/lib/local-embedder.js +358 -358
  41. package/lib/maintenance.js +142 -142
  42. package/lib/mirror.js +330 -330
  43. package/lib/organize.js +450 -450
  44. package/lib/peak-hours.js +117 -117
  45. package/lib/placement.js +13 -0
  46. package/lib/pre-inject-gate.js +340 -0
  47. package/lib/quality-filter.js +126 -126
  48. package/lib/recall-stats.js +175 -175
  49. package/lib/reranker.js +269 -269
  50. package/lib/runtime/adopt.js +176 -176
  51. package/lib/runtime/closure.js +172 -172
  52. package/lib/runtime/download.js +247 -247
  53. package/lib/runtime/layout.js +265 -265
  54. package/lib/runtime/loader.js +252 -252
  55. package/lib/runtime/model-fetch.js +361 -361
  56. package/lib/runtime/provision.js +237 -237
  57. package/lib/runtime/tarball.js +130 -130
  58. package/lib/runtime/verify.js +223 -204
  59. package/lib/scope.js +146 -146
  60. package/lib/search/adaptive.js +60 -60
  61. package/lib/search/bm25.js +96 -96
  62. package/lib/semantic.js +229 -0
  63. package/lib/sensitive-scan.js +209 -209
  64. package/lib/serve.js +215 -0
  65. package/lib/service.js +2663 -2596
  66. package/lib/settings.js +517 -509
  67. package/lib/store.js +3007 -3007
  68. package/lib/summarize.js +891 -856
  69. package/lib/tools.js +743 -737
  70. package/lib/vector-index.js +110 -110
  71. package/lib/version-check.js +122 -122
  72. package/lib/write-admission.js +402 -402
  73. package/locale/en.json +6 -6
  74. package/locale/zh.json +6 -6
  75. package/package.json +8 -4
  76. package/runtime-manifest.json +526 -526
  77. package/scripts/benchmark-embed.js +201 -201
  78. package/scripts/benchmark-recall.js +249 -249
  79. package/scripts/benchmark-rerank.js +166 -166
  80. package/scripts/build-runtime-manifest.mjs +224 -224
  81. package/scripts/changelog-prep.mjs +36 -0
  82. package/scripts/check-sync.js +42 -42
  83. package/scripts/e2e-dsh.js +220 -220
  84. package/scripts/mneme-runtime.mjs +277 -277
  85. package/scripts/stress-dsh.js +255 -255
  86. package/scripts/sync-lib.js +47 -47
  87. package/scripts/sync-test-badge.mjs +69 -69
  88. package/scripts/test-count-sync.mjs +44 -44
  89. package/src/api-standalone.js +673 -572
  90. package/src/api.js +1437 -1433
  91. package/src/bootstrap.js +211 -211
  92. package/src/commands.js +95 -95
  93. package/src/config.js +880 -836
  94. package/src/content-hash.js +54 -54
  95. package/src/continuity.js +220 -220
  96. package/src/document-index.js +94 -94
  97. package/src/document.js +303 -303
  98. package/src/dream/clustering.js +118 -118
  99. package/src/dream/decisions.js +674 -674
  100. package/src/dream/narratives.js +44 -44
  101. package/src/dream/sleep.js +819 -819
  102. package/src/dream.js +1501 -1501
  103. package/src/embedding.js +177 -177
  104. package/src/entities/extractor.js +252 -252
  105. package/src/graph/anchoring.js +179 -179
  106. package/src/guide.js +74 -74
  107. package/src/heat.js +144 -144
  108. package/src/hot-memory.js +46 -46
  109. package/src/index.js +535 -671
  110. package/src/inject.js +464 -450
  111. package/src/lang.js +248 -229
  112. package/src/local-embedder.js +358 -358
  113. package/src/maintenance.js +142 -142
  114. package/src/mirror.js +330 -330
  115. package/src/organize.js +450 -450
  116. package/src/peak-hours.js +117 -117
  117. package/src/placement.js +13 -0
  118. package/src/pre-inject-gate.js +340 -0
  119. package/src/quality-filter.js +126 -126
  120. package/src/recall-stats.js +175 -175
  121. package/src/reranker.js +269 -269
  122. package/src/runtime/adopt.js +176 -176
  123. package/src/runtime/closure.js +172 -172
  124. package/src/runtime/download.js +247 -247
  125. package/src/runtime/layout.js +265 -265
  126. package/src/runtime/loader.js +252 -252
  127. package/src/runtime/model-fetch.js +361 -361
  128. package/src/runtime/provision.js +237 -237
  129. package/src/runtime/tarball.js +130 -130
  130. package/src/runtime/verify.js +223 -204
  131. package/src/scope.js +146 -146
  132. package/src/search/adaptive.js +60 -60
  133. package/src/search/bm25.js +96 -96
  134. package/src/semantic.js +229 -0
  135. package/src/sensitive-scan.js +209 -209
  136. package/src/serve.js +215 -0
  137. package/src/service.js +2663 -2596
  138. package/src/settings.js +517 -509
  139. package/src/store.js +3007 -3007
  140. package/src/summarize.js +891 -856
  141. package/src/tools.js +743 -737
  142. package/src/vector-index.js +110 -110
  143. package/src/version-check.js +122 -122
  144. package/src/write-admission.js +402 -402
  145. package/test/adaptive-inject-budget.test.js +85 -85
  146. package/test/api-routes-gaps.test.js +218 -218
  147. package/test/api.test.js +1702 -1688
  148. package/test/audit.test.js +448 -448
  149. package/test/baseline-persist.test.js +248 -248
  150. package/test/benchmark.test.js +94 -94
  151. package/test/bootstrap.test.js +220 -220
  152. package/test/changelog-prep.test.js +60 -0
  153. package/test/client.test.js +1230 -1169
  154. package/test/clustering.test.js +100 -100
  155. package/test/commands.test.js +106 -106
  156. package/test/config.test.js +66 -66
  157. package/test/conflict-freeze.test.js +300 -300
  158. package/test/content-hash.test.js +204 -204
  159. package/test/continuity.test.js +333 -333
  160. package/test/document-dir.test.js +233 -233
  161. package/test/document.test.js +671 -671
  162. package/test/dream-archive-guardrail.test.js +116 -116
  163. package/test/dream-candidate-hybrid.test.js +281 -281
  164. package/test/dream-coverage-degrade.test.js +86 -86
  165. package/test/dream-failure-backoff.test.js +173 -173
  166. package/test/dream-peak-hours.test.js +194 -194
  167. package/test/dream.test.js +1385 -1383
  168. package/test/embedding-ready.test.js +196 -196
  169. package/test/entities.test.js +627 -547
  170. package/test/entity-recall.test.js +179 -179
  171. package/test/epistemic.test.js +325 -325
  172. package/test/fnew-0112.test.js +311 -311
  173. package/test/fnew-03.test.js +422 -422
  174. package/test/graph-anchoring.test.js +184 -184
  175. package/test/graph-api.test.js +175 -175
  176. package/test/graph-inject-budget.test.js +103 -103
  177. package/test/graph-passive-confirm.test.js +91 -91
  178. package/test/graph-weight-evolution.test.js +104 -104
  179. package/test/heat.test.js +175 -175
  180. package/test/helpers/dream-mock.js +82 -82
  181. package/test/helpers/peer-worker.mjs +25 -25
  182. package/test/helpers/runtime-source.js +60 -60
  183. package/test/helpers/tar-builder.js +80 -80
  184. package/test/helpers/write-admission-samples.js +308 -308
  185. package/test/hot-memory.test.js +145 -145
  186. package/test/inject-content-cap.test.js +91 -91
  187. package/test/inject-first-round-bm25.test.js +89 -89
  188. package/test/inject-heat.test.js +77 -61
  189. package/test/inject-parent-gate.test.js +106 -106
  190. package/test/inject-pools.test.js +194 -194
  191. package/test/inject-recall.test.js +105 -105
  192. package/test/inject-rotation.test.js +161 -161
  193. package/test/inject.test.js +420 -420
  194. package/test/lang.test.js +87 -87
  195. package/test/lastrunat-persist.test.js +101 -101
  196. package/test/lib-smoke.test.js +96 -96
  197. package/test/llm-audit.test.js +598 -598
  198. package/test/llm-message-source.test.js +207 -207
  199. package/test/local-embedder.test.js +292 -292
  200. package/test/maintenance.test.js +391 -391
  201. package/test/mcp-stdio.test.js +385 -385
  202. package/test/mirror-dirty.test.js +424 -424
  203. package/test/mirror-edit-digest.test.js +187 -187
  204. package/test/mirror-generation.test.js +499 -499
  205. package/test/mirror-types.test.js +208 -208
  206. package/test/mirror.test.js +249 -249
  207. package/test/narrative-bars.test.js +162 -162
  208. package/test/organize.test.js +418 -418
  209. package/test/peer-blockers.test.js +193 -193
  210. package/test/placement.test.js +36 -0
  211. package/test/policy-epoch.test.js +259 -259
  212. package/test/pre-inject-gate.test.js +434 -0
  213. package/test/quality-filter.test.js +186 -186
  214. package/test/reasoning-effort.test.js +752 -752
  215. package/test/recall-anti-update.test.js +82 -82
  216. package/test/recall-evals.test.js +253 -253
  217. package/test/recall-layer.test.js +326 -326
  218. package/test/recall-stats.test.js +189 -189
  219. package/test/receipt-chain.test.js +451 -451
  220. package/test/reflection.test.js +226 -226
  221. package/test/reindex-backfill.test.js +62 -62
  222. package/test/reranker-single-logit.test.js +73 -73
  223. package/test/reranker.test.js +197 -197
  224. package/test/resident-status.test.js +83 -83
  225. package/test/runtime-adopt.test.js +206 -206
  226. package/test/runtime-cli.test.js +89 -89
  227. package/test/runtime-closure.test.js +193 -193
  228. package/test/runtime-download.test.js +302 -302
  229. package/test/runtime-layout.test.js +163 -163
  230. package/test/runtime-loader.test.js +255 -255
  231. package/test/runtime-manifest.test.js +159 -159
  232. package/test/runtime-model-fetch.test.js +348 -348
  233. package/test/runtime-provision.test.js +101 -101
  234. package/test/runtime-tarball.test.js +81 -81
  235. package/test/runtime-verify.test.js +319 -279
  236. package/test/scope-candidates.test.js +239 -239
  237. package/test/scope-explicit.test.js +452 -452
  238. package/test/scope-inject-soft.test.js +106 -106
  239. package/test/scope-retrieval.test.js +197 -197
  240. package/test/scope-storage.test.js +255 -255
  241. package/test/scope-strict.test.js +367 -343
  242. package/test/search-fusion.test.js +90 -90
  243. package/test/semantic.test.js +124 -124
  244. package/test/sensitive-scan.test.js +207 -207
  245. package/test/serve-bin.test.js +121 -0
  246. package/test/serve.test.js +196 -0
  247. package/test/service-search.test.js +174 -174
  248. package/test/service.test.js +405 -405
  249. package/test/settings.test.js +261 -261
  250. package/test/skip-invalid-restore.test.js +262 -262
  251. package/test/sleep-action-set.test.js +422 -422
  252. package/test/sleep-heat.test.js +126 -126
  253. package/test/sleep-scheduler-rearm.test.js +89 -89
  254. package/test/sleep.test.js +527 -527
  255. package/test/standalone-api.test.js +751 -544
  256. package/test/store-vector-cache.test.js +98 -98
  257. package/test/store.test.js +396 -396
  258. package/test/stress.test.js +209 -209
  259. package/test/summarize-occurred-at.test.js +127 -0
  260. package/test/summarize-reasoning-effort.test.js +189 -189
  261. package/test/summarize.test.js +1465 -1465
  262. package/test/supersede-state-tracking.test.js +394 -0
  263. package/test/test-count-sync.test.js +60 -60
  264. package/test/tools-dto-schema-matrix.test.js +325 -325
  265. package/test/tools-memory-get-schema.test.js +65 -65
  266. package/test/tools.test.js +428 -374
  267. package/test/updated-at-semantics.test.js +113 -113
  268. package/test/vector-index.test.js +221 -221
  269. package/test/version-check.test.js +152 -152
  270. package/test/webServer-optional.test.js +82 -82
  271. package/test/write-admission.test.js +668 -668
@@ -1,544 +1,751 @@
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
- import { createSettings } from "../src/settings.js";
6
- import { createStandaloneApi } from "../src/api-standalone.js";
7
- import { Config, applyLightModePreset } from "../src/config.js";
8
-
9
- // Real HTTP server on an OS-assigned port (port: 0), driven with fetch.
10
- async function setup() {
11
- const store = createStore(":memory:");
12
- const service = createService({ store, mirror: null, config: {} });
13
- const settings = createSettings(store.db);
14
- const api = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: 0 });
15
- await api.ready;
16
- const base = `http://127.0.0.1:${api.port}`;
17
- const auth = { authorization: `Bearer ${api.token}` };
18
- return {
19
- store,
20
- service,
21
- settings,
22
- api,
23
- base,
24
- auth,
25
- close: () => {
26
- // Drop pooled keep-alive sockets so node --test can drain the loop.
27
- api.server.closeIdleConnections?.();
28
- api.server.close();
29
- store.close();
30
- }
31
- };
32
- }
33
-
34
- // --- auth ---------------------------------------------------------------------
35
-
36
- test("GET /health is open without a token; every other route 401s", async () => {
37
- const { base, close } = await setup();
38
- try {
39
- const health = await fetch(`${base}/health`);
40
- assert.equal(health.status, 200);
41
- assert.deepEqual(await health.json(), { ok: true });
42
-
43
- for (const path of ["/status", "/profile", "/rules", "/memories", "/memories/x", "/search?q=x"]) {
44
- const res = await fetch(`${base}${path}`);
45
- assert.equal(res.status, 401, `${path} requires a token`);
46
- assert.deepEqual(await res.json(), { error: "unauthorized" });
47
- }
48
-
49
- const bad = await fetch(`${base}/status`, { headers: { authorization: "Bearer wrong-token" } });
50
- assert.equal(bad.status, 401, "wrong token rejected");
51
- } finally {
52
- close();
53
- }
54
- });
55
-
56
- test("GET /profile and /rules return saved settings", async () => {
57
- const { base, auth, settings, close } = await setup();
58
- try {
59
- settings.setProfile("我是后端工程师");
60
- settings.setRules(["先验证再修改", "默认使用中文回复"]);
61
-
62
- const profile = await fetch(`${base}/profile`, { headers: auth });
63
- assert.equal(profile.status, 200);
64
- assert.deepEqual(await profile.json(), { profile: "我是后端工程师" });
65
-
66
- const rules = await fetch(`${base}/rules`, { headers: auth });
67
- assert.equal(rules.status, 200);
68
- assert.deepEqual(await rules.json(), { rules: ["先验证再修改", "默认使用中文回复"] });
69
- } finally {
70
- close();
71
- }
72
- });
73
-
74
- test("GET /profile and /rules return empty values when unset", async () => {
75
- const { base, auth, close } = await setup();
76
- try {
77
- const profile = await fetch(`${base}/profile`, { headers: auth });
78
- assert.equal(profile.status, 200);
79
- assert.deepEqual(await profile.json(), { profile: "" });
80
-
81
- const rules = await fetch(`${base}/rules`, { headers: auth });
82
- assert.equal(rules.status, 200);
83
- assert.deepEqual(await rules.json(), { rules: [] });
84
- } finally {
85
- close();
86
- }
87
- });
88
-
89
- test("token is persisted into settings kv and reused across restarts", async () => {
90
- const store = createStore(":memory:");
91
- const service = createService({ store, mirror: null, config: {} });
92
- const settings = createSettings(store.db);
93
- const first = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
94
- await first.ready;
95
- try {
96
- assert.equal(settings.getExternalApi().token, first.token, "generated token persisted");
97
- assert.ok(first.token.length >= 20, "token is a real random value");
98
- const second = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
99
- await second.ready;
100
- assert.equal(second.token, first.token, "restart reuses the persisted token");
101
- second.server.closeIdleConnections?.();
102
- second.server.close();
103
- } finally {
104
- first.server.closeIdleConnections?.();
105
- first.server.close();
106
- store.close();
107
- }
108
- });
109
-
110
- // --- CRUD loop ------------------------------------------------------------------
111
-
112
- test("POST/GET/DELETE /memories round trip", async () => {
113
- const { base, auth, close } = await setup();
114
- try {
115
- const post = await fetch(`${base}/memories`, {
116
- method: "POST",
117
- headers: { ...auth, "content-type": "application/json" },
118
- body: JSON.stringify({ type: "preference", title: "语言", content: "始终用中文回复", importance: 4, tags: ["交流"] })
119
- });
120
- assert.equal(post.status, 201);
121
- const created = await post.json();
122
- assert.ok(created.id, "row id returned");
123
- assert.equal(created.title, "语言");
124
- assert.equal(created.importance, 4);
125
-
126
- const list = await fetch(`${base}/memories?limit=10`, { headers: auth });
127
- assert.equal(list.status, 200);
128
- const listBody = await list.json();
129
- assert.equal(listBody.total, 1);
130
- assert.equal(listBody.items.length, 1);
131
-
132
- const got = await fetch(`${base}/memories/${created.id}`, { headers: auth });
133
- assert.equal(got.status, 200);
134
- assert.equal((await got.json()).content, "始终用中文回复");
135
-
136
- const del = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
137
- assert.equal(del.status, 200);
138
- assert.deepEqual(await del.json(), { ok: true });
139
-
140
- const gone = await fetch(`${base}/memories/${created.id}`, { headers: auth });
141
- assert.equal(gone.status, 404, "deleted row reads back as 404");
142
- const delAgain = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
143
- assert.equal(delAgain.status, 404, "deleting a missing row is 404, not a fake ok");
144
- } finally {
145
- close();
146
- }
147
- });
148
-
149
- test("POST /memories dedupes same title within a type (200 + merged content)", async () => {
150
- const { base, auth, close } = await setup();
151
- try {
152
- const first = await fetch(`${base}/memories`, {
153
- method: "POST",
154
- headers: { ...auth, "content-type": "application/json" },
155
- body: JSON.stringify({ type: "project", title: "mneme", content: "v1 内容" })
156
- });
157
- assert.equal(first.status, 201);
158
- const row1 = await first.json();
159
-
160
- const second = await fetch(`${base}/memories`, {
161
- method: "POST",
162
- headers: { ...auth, "content-type": "application/json" },
163
- body: JSON.stringify({ type: "project", title: "mneme", content: "v2 追加" })
164
- });
165
- assert.equal(second.status, 200, "merge, not a second creation");
166
- const row2 = await second.json();
167
- assert.equal(row2.id, row1.id, "same row reused");
168
- assert.ok(row2.content.includes("v1 内容") && row2.content.includes("v2 追加"), "content appended");
169
-
170
- const list = await fetch(`${base}/memories`, { headers: auth });
171
- assert.equal((await list.json()).total, 1, "no duplicate row created");
172
- } finally {
173
- close();
174
- }
175
- });
176
-
177
- test("POST /memories validation: invalid type, bad JSON, non-array tags → 400", async () => {
178
- const { base, auth, close } = await setup();
179
- try {
180
- const badType = await fetch(`${base}/memories`, {
181
- method: "POST",
182
- headers: { ...auth, "content-type": "application/json" },
183
- body: JSON.stringify({ type: "diary", title: "t", content: "c" })
184
- });
185
- assert.equal(badType.status, 400);
186
- assert.deepEqual(await badType.json(), { error: "invalid-type" });
187
-
188
- const badJson = await fetch(`${base}/memories`, {
189
- method: "POST",
190
- headers: { ...auth, "content-type": "application/json" },
191
- body: "{not json"
192
- });
193
- assert.equal(badJson.status, 400);
194
- assert.deepEqual(await badJson.json(), { error: "invalid-json" });
195
-
196
- const badTags = await fetch(`${base}/memories`, {
197
- method: "POST",
198
- headers: { ...auth, "content-type": "application/json" },
199
- body: JSON.stringify({ type: "project", title: "t", content: "c", tags: "x" })
200
- });
201
- assert.equal(badTags.status, 400);
202
- assert.deepEqual(await badTags.json(), { error: "tags-must-be-an-array" });
203
-
204
- const noTitle = await fetch(`${base}/memories`, {
205
- method: "POST",
206
- headers: { ...auth, "content-type": "application/json" },
207
- body: JSON.stringify({ type: "project", content: "c" })
208
- });
209
- assert.equal(noTitle.status, 400);
210
- assert.deepEqual(await noTitle.json(), { error: "missing-title" });
211
- } finally {
212
- close();
213
- }
214
- });
215
-
216
- // --- list filters / status / search ---------------------------------------------
217
-
218
- test("GET /memories honors type + minImportance filters and paging", async () => {
219
- const { base, auth, service, close } = await setup();
220
- try {
221
- service.saveWithDedupe({ type: "preference", title: "低", content: "i2", importance: 2 });
222
- service.saveWithDedupe({ type: "preference", title: "高", content: "i5", importance: 5 });
223
- service.saveWithDedupe({ type: "project", title: "项目", content: "i4", importance: 4 });
224
-
225
- const byType = await fetch(`${base}/memories?type=preference`, { headers: auth });
226
- assert.equal((await byType.json()).total, 2);
227
-
228
- const byImportance = await fetch(`${base}/memories?minImportance=4`, { headers: auth });
229
- const filtered = await byImportance.json();
230
- assert.equal(filtered.total, 2);
231
- assert.deepEqual(filtered.items.map((m) => m.title).sort(), ["项目", "高"]);
232
-
233
- const paged = await fetch(`${base}/memories?limit=2&offset=0&order=chrono`, { headers: auth });
234
- const page = await paged.json();
235
- assert.equal(page.items.length, 2);
236
- assert.equal(page.total, 3);
237
- } finally {
238
- close();
239
- }
240
- });
241
-
242
- test("GET /status reports version, per-type totals, entities and uptime", async () => {
243
- const { base, auth, service, close } = await setup();
244
- try {
245
- service.saveWithDedupe({ type: "preference", title: "p", content: "c" });
246
- service.saveWithDedupe({ type: "project", title: "j", content: "c" });
247
- service.saveWithDedupe({ type: "project", title: "j2", content: "c" });
248
-
249
- const res = await fetch(`${base}/status`, { headers: auth });
250
- assert.equal(res.status, 200);
251
- const body = await res.json();
252
- assert.equal(body.version, "0.7.12");
253
- assert.equal(body.memories.total, 3);
254
- assert.equal(body.memories.byType.preference, 1);
255
- assert.equal(body.memories.byType.project, 2);
256
- assert.equal(body.entities, 0, "no extraction wired → empty entity table");
257
- assert.ok(Number.isInteger(body.uptime_s));
258
- } finally {
259
- close();
260
- }
261
- });
262
-
263
- test("GET /search finds saved memories; empty q returns empty keyword result", async () => {
264
- const { base, auth, close } = await setup();
265
- try {
266
- await fetch(`${base}/memories`, {
267
- method: "POST",
268
- headers: { ...auth, "content-type": "application/json" },
269
- body: JSON.stringify({ type: "project", title: "记忆插件", content: "SQLite 全文检索" })
270
- });
271
-
272
- const res = await fetch(`${base}/search?q=${encodeURIComponent("全文检索")}&mode=keyword`, { headers: auth });
273
- assert.equal(res.status, 200);
274
- const body = await res.json();
275
- assert.equal(body.mode, "keyword");
276
- assert.equal(body.items.length, 1);
277
- assert.equal(body.items[0].title, "记忆插件");
278
-
279
- const empty = await fetch(`${base}/search?q=`, { headers: auth });
280
- assert.deepEqual(await empty.json(), { items: [], mode: "keyword" });
281
- } finally {
282
- close();
283
- }
284
- });
285
-
286
- test("unknown path returns 404 json", async () => {
287
- const { base, auth, close } = await setup();
288
- try {
289
- const res = await fetch(`${base}/nope`, { headers: auth });
290
- assert.equal(res.status, 404);
291
- assert.deepEqual(await res.json(), { error: "not-found" });
292
- } finally {
293
- close();
294
- }
295
- });
296
-
297
- // --- light-mode preset (applyLightModePreset) ------------------------------------
298
-
299
- const LIGHT_OFF_FIELDS = [
300
- "entityExtractionEnabled",
301
- "autoDream",
302
- "sleepModeEnabled",
303
- "rerankEnabled",
304
- "autoReindexOnBoot",
305
- "hybridInject",
306
- "searchSemanticDedup",
307
- "selectiveInjectEnabled",
308
- "bm25SearchEnabled"
309
- ];
310
-
311
- test("applyLightModePreset turns heavy features off and keeps the core loop", () => {
312
- const cfg = applyLightModePreset(Config({ lightMode: true }));
313
- for (const field of LIGHT_OFF_FIELDS) {
314
- assert.equal(cfg[field], false, `${field} forced off in light mode`);
315
- }
316
- // Core loop preserved.
317
- assert.equal(cfg.autoInject, true);
318
- assert.equal(cfg.autoSummarize, true);
319
- assert.equal(cfg.hotMemoryEnabled, true);
320
- assert.equal(cfg.memoryQualityFilter.enabled, true);
321
- // Unrelated knobs untouched.
322
- assert.equal(cfg.dreamThresholdCount, 10);
323
- assert.equal(cfg.dreamDelayMs, 2000);
324
- assert.equal(cfg.maxInjectedItems, 5);
325
- });
326
-
327
- test("applyLightModePreset keeps explicit non-preset values and is a no-op without lightMode", () => {
328
- const tuned = applyLightModePreset(Config({ lightMode: true, dreamThresholdCount: 30, maxInjectedItems: 8 }));
329
- assert.equal(tuned.dreamThresholdCount, 30, "operator values survive the preset");
330
- assert.equal(tuned.maxInjectedItems, 8);
331
-
332
- const plain = Config({});
333
- assert.equal(applyLightModePreset(plain), plain, "identity when lightMode is unset");
334
- const off = Config({ lightMode: false });
335
- assert.equal(applyLightModePreset(off), off, "identity when lightMode is false");
336
- });
337
-
338
- test("persisted panel_mode=light wins over a bundle config that did not ask for it", () => {
339
- const store = createStore(":memory:");
340
- const settings = createSettings(store.db);
341
- try {
342
- // Panel switched to light in a previous session; bundle config says nothing.
343
- settings.setPanelMode("light");
344
- const rawCfg = Config({});
345
- const lightMode = rawCfg.lightMode === true || settings.getPanelMode() === "light";
346
- const cfg = applyLightModePreset({ ...rawCfg, lightMode });
347
- assert.equal(lightMode, true, "persisted mode forces light");
348
- assert.equal(cfg.autoDream, false);
349
- assert.equal(cfg.entityExtractionEnabled, false);
350
- assert.equal(cfg.autoInject, true, "core injection stays on");
351
-
352
- // standard (default) never forces the preset even with a light bundle flag off.
353
- settings.setPanelMode("standard");
354
- const raw2 = Config({});
355
- assert.equal(raw2.lightMode === true || settings.getPanelMode() === "light", false);
356
- } finally {
357
- store.close();
358
- }
359
- });
360
-
361
- // --- #181:MCP 六件套的 API 面(PUT / save 透传 / archived 与 occurred 窗口)---
362
-
363
- test("PUT /memories/:id patches fields and returns the DTO (unauthorized without token)", async () => {
364
- const { base, auth, service, close } = await setup();
365
- try {
366
- const created = await (await fetch(`${base}/memories`, {
367
- method: "POST",
368
- headers: { ...auth, "content-type": "application/json" },
369
- body: JSON.stringify({ type: "preference", title: "编辑器", content: "用 vim", importance: 3 })
370
- })).json();
371
-
372
- const noAuth = await fetch(`${base}/memories/${created.id}`, {
373
- method: "PUT",
374
- headers: { "content-type": "application/json" },
375
- body: JSON.stringify({ content: "用 nvim" })
376
- });
377
- assert.equal(noAuth.status, 401, "PUT requires the Bearer token");
378
-
379
- const put = await fetch(`${base}/memories/${created.id}`, {
380
- method: "PUT",
381
- headers: { ...auth, "content-type": "application/json" },
382
- body: JSON.stringify({ content: "用 nvim", importance: 4, tags: ["工具"], reason: "用户改用 nvim 了" })
383
- });
384
- assert.equal(put.status, 200);
385
- const { memory } = await put.json();
386
- assert.equal(memory.content, "用 nvim");
387
- assert.equal(memory.importance, 4);
388
- assert.deepEqual(memory.tags, ["工具"]);
389
-
390
- // content 改写按 human_override 入档(与内部面板写路径一致)。
391
- const raw = service.getById(created.id);
392
- assert.equal(raw.content_history?.[0]?.source, "human_override");
393
- assert.equal(raw.content_history?.[0]?.content, "用 vim");
394
- } finally {
395
- close();
396
- }
397
- });
398
-
399
- test("PUT /memories/:id validation: bad fields → 400, empty patch → 400, missing id → 404", async () => {
400
- const { base, auth, close } = await setup();
401
- try {
402
- const put = (body, id = "whatever") => fetch(`${base}/memories/${id}`, {
403
- method: "PUT",
404
- headers: { ...auth, "content-type": "application/json" },
405
- body: JSON.stringify(body)
406
- });
407
- assert.equal((await put({ title: "" })).status, 400);
408
- assert.equal((await put({ importance: 9 })).status, 400);
409
- assert.equal((await put({ tags: "x" })).status, 400);
410
- assert.equal((await put({ type: "nope" })).status, 400);
411
- assert.equal((await put({})).status, 400, "empty patch is no-fields");
412
- assert.equal((await put({ content: "x" }, "missing-id")).status, 404);
413
- assert.equal((await put({ agent_scope: 5 })).status, 400);
414
- } finally {
415
- close();
416
- }
417
- });
418
-
419
- test("PUT /memories/:id surfaces service failures as 500 instead of a hung request", async () => {
420
- const { base, auth, service, close } = await setup();
421
- try {
422
- const created = await (await fetch(`${base}/memories`, {
423
- method: "POST",
424
- headers: { ...auth, "content-type": "application/json" },
425
- body: JSON.stringify({ type: "preference", title: "会抛错", content: "v1" })
426
- })).json();
427
- const original = service.update;
428
- service.update = () => { throw new Error("boom"); };
429
- try {
430
- const res = await fetch(`${base}/memories/${created.id}`, {
431
- method: "PUT",
432
- headers: { ...auth, "content-type": "application/json" },
433
- body: JSON.stringify({ content: "v2" })
434
- });
435
- assert.equal(res.status, 500, "service throw must not strand the request");
436
- assert.deepEqual(await res.json(), { error: "internal" });
437
- } finally {
438
- service.update = original;
439
- }
440
- } finally {
441
- close();
442
- }
443
- });
444
-
445
- test("POST /memories passes through sensitivity/occurred_at/scope and returns action", async () => {
446
- const { base, auth, close } = await setup();
447
- try {
448
- const post = await fetch(`${base}/memories`, {
449
- method: "POST",
450
- headers: { ...auth, "content-type": "application/json" },
451
- body: JSON.stringify({
452
- type: "decision",
453
- title: "迁移",
454
- content: "迁到 sqlite 分支",
455
- sensitivity: "personal",
456
- occurred_at: "2026-01-15T10:00:00Z",
457
- agent_scope: "global"
458
- })
459
- });
460
- assert.equal(post.status, 201);
461
- const created = await post.json();
462
- assert.equal(created.action, "created", "action rides along for tool parity");
463
- assert.equal(created.sensitivity, "personal");
464
- // store 把 ISO 瞬时归一化成完整毫秒形式(2026-01-15T10:00:00Z → …T10:00:00.000Z)。
465
- assert.match(created.occurred_at, /^2026-01-15T10:00:00/);
466
- assert.equal(created.agent_scope, "global");
467
- assert.equal(created.agent_scope_source, "explicit");
468
-
469
- // 合并判据=同 type + 同标题 + 同 sensitivity + 同作用域三元(0.8.0 起去重键
470
- // 含 scope,跨作用域同标题本就分开存):补齐 agent_scope 才 merged。
471
- const merged = await (await fetch(`${base}/memories`, {
472
- method: "POST",
473
- headers: { ...auth, "content-type": "application/json" },
474
- body: JSON.stringify({ type: "decision", title: "迁移", content: "迁到 sqlite 分支(更新)", sensitivity: "personal", agent_scope: "global" })
475
- })).json();
476
- assert.equal(merged.action, "merged", "same dedupe key reports merged");
477
-
478
- const separate = await (await fetch(`${base}/memories`, {
479
- method: "POST",
480
- headers: { ...auth, "content-type": "application/json" },
481
- body: JSON.stringify({ type: "decision", title: "迁移", content: "无标注版本" })
482
- })).json();
483
- assert.equal(separate.action, "created", "no sensitivity/scope → different dedupe key");
484
-
485
- const bad = await fetch(`${base}/memories`, {
486
- method: "POST",
487
- headers: { ...auth, "content-type": "application/json" },
488
- body: JSON.stringify({ type: "decision", title: "x", content: "y", sensitivity: 5 })
489
- });
490
- assert.equal(bad.status, 400);
491
- assert.equal((await bad.json()).error, "invalid-sensitivity");
492
- } finally {
493
- close();
494
- }
495
- });
496
-
497
- test("GET /memories supports include_archived and the occurred_at window", async () => {
498
- const { base, auth, service, close } = await setup();
499
- try {
500
- const save = (title, occurredAt) => fetch(`${base}/memories`, {
501
- method: "POST",
502
- headers: { ...auth, "content-type": "application/json" },
503
- body: JSON.stringify({ type: "history", title, content: `body of ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
504
- });
505
- const january = await (await save("一月的事", "2026-01-15T10:00:00Z")).json();
506
- await save("二月的事", "2026-02-15T10:00:00Z");
507
- await save("无时间戳的事", null);
508
-
509
- const february = await (await fetch(`${base}/memories?occurred_from=2026-02-01`, { headers: auth })).json();
510
- // 「无时间戳的事」按 occurred_at→created_at 回退(写入日 2026-09),落在窗口内。
511
- assert.deepEqual(february.items.map((m) => m.title).sort(), ["二月的事", "无时间戳的事"]);
512
- assert.equal(february.total, 2, "total honors the same window");
513
-
514
- const upToJanuary = await (await fetch(`${base}/memories?occurred_to=2026-01-31`, { headers: auth })).json();
515
- assert.deepEqual(upToJanuary.items.map((m) => m.title), ["一月的事"]);
516
-
517
- service.setArchived(january.id, true);
518
- const active = await (await fetch(`${base}/memories`, { headers: auth })).json();
519
- assert.equal(active.total, 2, "archived rows stay hidden by default");
520
- const withArchived = await (await fetch(`${base}/memories?include_archived=true`, { headers: auth })).json();
521
- assert.equal(withArchived.total, 3, "include_archived=true surfaces archived rows");
522
- } finally {
523
- close();
524
- }
525
- });
526
-
527
- test("GET /search honors the occurred_at window", async () => {
528
- const { base, auth, close } = await setup();
529
- try {
530
- const save = (title, occurredAt) => fetch(`${base}/memories`, {
531
- method: "POST",
532
- headers: { ...auth, "content-type": "application/json" },
533
- body: JSON.stringify({ type: "history", title, content: `记忆星球 ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
534
- });
535
- await save("旧事", "2026-01-15T10:00:00Z");
536
- await save("新事", "2026-03-15T10:00:00Z");
537
-
538
- const hit = await (await fetch(`${base}/search?q=${encodeURIComponent("记忆星球")}&occurred_from=2026-03-01`, { headers: auth })).json();
539
- assert.equal(hit.items.length, 1);
540
- assert.equal(hit.items[0].title, "新事");
541
- } finally {
542
- close();
543
- }
544
- });
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
+ import { createSettings } from "../src/settings.js";
6
+ import { createStandaloneApi } from "../src/api-standalone.js";
7
+ import { PACKAGE_VERSION } from "../src/version-check.js";
8
+ import { Config, applyLightModePreset } from "../src/config.js";
9
+
10
+ // Real HTTP server on an OS-assigned port (port: 0), driven with fetch.
11
+ async function setup({ config = {}, embedder = null, embedTimeoutMs } = {}) {
12
+ const store = createStore(":memory:");
13
+ const service = createService({ store, mirror: null, config });
14
+ const settings = createSettings(store.db);
15
+ const api = createStandaloneApi({ service, store, config, settings, logger: null, port: 0, embedder, embedTimeoutMs });
16
+ await api.ready;
17
+ const base = `http://127.0.0.1:${api.port}`;
18
+ const auth = { authorization: `Bearer ${api.token}` };
19
+ return {
20
+ store,
21
+ service,
22
+ settings,
23
+ api,
24
+ base,
25
+ auth,
26
+ close: () => {
27
+ // Drop pooled keep-alive sockets so node --test can drain the loop.
28
+ api.server.closeIdleConnections?.();
29
+ api.server.close();
30
+ store.close();
31
+ }
32
+ };
33
+ }
34
+
35
+ // --- auth ---------------------------------------------------------------------
36
+
37
+ test("GET /health is open without a token; every other route 401s", async () => {
38
+ const { base, close } = await setup();
39
+ try {
40
+ const health = await fetch(`${base}/health`);
41
+ assert.equal(health.status, 200);
42
+ assert.deepEqual(await health.json(), { ok: true });
43
+
44
+ for (const path of ["/status", "/profile", "/rules", "/memories", "/memories/x", "/search?q=x", "/context"]) {
45
+ const res = await fetch(`${base}${path}`);
46
+ assert.equal(res.status, 401, `${path} requires a token`);
47
+ assert.deepEqual(await res.json(), { error: "unauthorized" });
48
+ }
49
+
50
+ const bad = await fetch(`${base}/status`, { headers: { authorization: "Bearer wrong-token" } });
51
+ assert.equal(bad.status, 401, "wrong token rejected");
52
+ } finally {
53
+ close();
54
+ }
55
+ });
56
+
57
+ test("GET /profile and /rules return saved settings", async () => {
58
+ const { base, auth, settings, close } = await setup();
59
+ try {
60
+ settings.setProfile("我是后端工程师");
61
+ settings.setRules(["先验证再修改", "默认使用中文回复"]);
62
+
63
+ const profile = await fetch(`${base}/profile`, { headers: auth });
64
+ assert.equal(profile.status, 200);
65
+ assert.deepEqual(await profile.json(), { profile: "我是后端工程师" });
66
+
67
+ const rules = await fetch(`${base}/rules`, { headers: auth });
68
+ assert.equal(rules.status, 200);
69
+ assert.deepEqual(await rules.json(), { rules: ["先验证再修改", "默认使用中文回复"] });
70
+ } finally {
71
+ close();
72
+ }
73
+ });
74
+
75
+ test("GET /profile and /rules return empty values when unset", async () => {
76
+ const { base, auth, close } = await setup();
77
+ try {
78
+ const profile = await fetch(`${base}/profile`, { headers: auth });
79
+ assert.equal(profile.status, 200);
80
+ assert.deepEqual(await profile.json(), { profile: "" });
81
+
82
+ const rules = await fetch(`${base}/rules`, { headers: auth });
83
+ assert.equal(rules.status, 200);
84
+ assert.deepEqual(await rules.json(), { rules: [] });
85
+ } finally {
86
+ close();
87
+ }
88
+ });
89
+
90
+ test("token is persisted into settings kv and reused across restarts", async () => {
91
+ const store = createStore(":memory:");
92
+ const service = createService({ store, mirror: null, config: {} });
93
+ const settings = createSettings(store.db);
94
+ const first = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
95
+ await first.ready;
96
+ try {
97
+ assert.equal(settings.getExternalApi().token, first.token, "generated token persisted");
98
+ assert.ok(first.token.length >= 20, "token is a real random value");
99
+ const second = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
100
+ await second.ready;
101
+ assert.equal(second.token, first.token, "restart reuses the persisted token");
102
+ second.server.closeIdleConnections?.();
103
+ second.server.close();
104
+ } finally {
105
+ first.server.closeIdleConnections?.();
106
+ first.server.close();
107
+ store.close();
108
+ }
109
+ });
110
+
111
+ // --- CRUD loop ------------------------------------------------------------------
112
+
113
+ test("POST/GET/DELETE /memories round trip", async () => {
114
+ const { base, auth, close } = await setup();
115
+ try {
116
+ const post = await fetch(`${base}/memories`, {
117
+ method: "POST",
118
+ headers: { ...auth, "content-type": "application/json" },
119
+ body: JSON.stringify({ type: "preference", title: "语言", content: "始终用中文回复", importance: 4, tags: ["交流"] })
120
+ });
121
+ assert.equal(post.status, 201);
122
+ const created = await post.json();
123
+ assert.ok(created.id, "row id returned");
124
+ assert.equal(created.title, "语言");
125
+ assert.equal(created.importance, 4);
126
+
127
+ const list = await fetch(`${base}/memories?limit=10`, { headers: auth });
128
+ assert.equal(list.status, 200);
129
+ const listBody = await list.json();
130
+ assert.equal(listBody.total, 1);
131
+ assert.equal(listBody.items.length, 1);
132
+
133
+ const got = await fetch(`${base}/memories/${created.id}`, { headers: auth });
134
+ assert.equal(got.status, 200);
135
+ assert.equal((await got.json()).content, "始终用中文回复");
136
+
137
+ const del = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
138
+ assert.equal(del.status, 200);
139
+ assert.deepEqual(await del.json(), { ok: true });
140
+
141
+ const gone = await fetch(`${base}/memories/${created.id}`, { headers: auth });
142
+ assert.equal(gone.status, 404, "deleted row reads back as 404");
143
+ const delAgain = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
144
+ assert.equal(delAgain.status, 404, "deleting a missing row is 404, not a fake ok");
145
+ } finally {
146
+ close();
147
+ }
148
+ });
149
+
150
+ test("POST /memories dedupes same title within a type (200 + merged content)", async () => {
151
+ const { base, auth, close } = await setup();
152
+ try {
153
+ const first = await fetch(`${base}/memories`, {
154
+ method: "POST",
155
+ headers: { ...auth, "content-type": "application/json" },
156
+ body: JSON.stringify({ type: "project", title: "mneme", content: "v1 内容" })
157
+ });
158
+ assert.equal(first.status, 201);
159
+ const row1 = await first.json();
160
+
161
+ const second = await fetch(`${base}/memories`, {
162
+ method: "POST",
163
+ headers: { ...auth, "content-type": "application/json" },
164
+ body: JSON.stringify({ type: "project", title: "mneme", content: "v2 追加" })
165
+ });
166
+ assert.equal(second.status, 200, "merge, not a second creation");
167
+ const row2 = await second.json();
168
+ assert.equal(row2.id, row1.id, "same row reused");
169
+ assert.ok(row2.content.includes("v1 内容") && row2.content.includes("v2 追加"), "content appended");
170
+
171
+ const list = await fetch(`${base}/memories`, { headers: auth });
172
+ assert.equal((await list.json()).total, 1, "no duplicate row created");
173
+ } finally {
174
+ close();
175
+ }
176
+ });
177
+
178
+ test("POST /memories validation: invalid type, bad JSON, non-array tags → 400", async () => {
179
+ const { base, auth, close } = await setup();
180
+ try {
181
+ const badType = await fetch(`${base}/memories`, {
182
+ method: "POST",
183
+ headers: { ...auth, "content-type": "application/json" },
184
+ body: JSON.stringify({ type: "diary", title: "t", content: "c" })
185
+ });
186
+ assert.equal(badType.status, 400);
187
+ assert.deepEqual(await badType.json(), { error: "invalid-type" });
188
+
189
+ const badJson = await fetch(`${base}/memories`, {
190
+ method: "POST",
191
+ headers: { ...auth, "content-type": "application/json" },
192
+ body: "{not json"
193
+ });
194
+ assert.equal(badJson.status, 400);
195
+ assert.deepEqual(await badJson.json(), { error: "invalid-json" });
196
+
197
+ const badTags = await fetch(`${base}/memories`, {
198
+ method: "POST",
199
+ headers: { ...auth, "content-type": "application/json" },
200
+ body: JSON.stringify({ type: "project", title: "t", content: "c", tags: "x" })
201
+ });
202
+ assert.equal(badTags.status, 400);
203
+ assert.deepEqual(await badTags.json(), { error: "tags-must-be-an-array" });
204
+
205
+ const noTitle = await fetch(`${base}/memories`, {
206
+ method: "POST",
207
+ headers: { ...auth, "content-type": "application/json" },
208
+ body: JSON.stringify({ type: "project", content: "c" })
209
+ });
210
+ assert.equal(noTitle.status, 400);
211
+ assert.deepEqual(await noTitle.json(), { error: "missing-title" });
212
+ } finally {
213
+ close();
214
+ }
215
+ });
216
+
217
+ // --- list filters / status / search ---------------------------------------------
218
+
219
+ test("GET /memories honors type + minImportance filters and paging", async () => {
220
+ const { base, auth, service, close } = await setup();
221
+ try {
222
+ service.saveWithDedupe({ type: "preference", title: "低", content: "i2", importance: 2 });
223
+ service.saveWithDedupe({ type: "preference", title: "高", content: "i5", importance: 5 });
224
+ service.saveWithDedupe({ type: "project", title: "项目", content: "i4", importance: 4 });
225
+
226
+ const byType = await fetch(`${base}/memories?type=preference`, { headers: auth });
227
+ assert.equal((await byType.json()).total, 2);
228
+
229
+ const byImportance = await fetch(`${base}/memories?minImportance=4`, { headers: auth });
230
+ const filtered = await byImportance.json();
231
+ assert.equal(filtered.total, 2);
232
+ assert.deepEqual(filtered.items.map((m) => m.title).sort(), ["项目", "高"]);
233
+
234
+ const paged = await fetch(`${base}/memories?limit=2&offset=0&order=chrono`, { headers: auth });
235
+ const page = await paged.json();
236
+ assert.equal(page.items.length, 2);
237
+ assert.equal(page.total, 3);
238
+ } finally {
239
+ close();
240
+ }
241
+ });
242
+
243
+ test("GET /status reports version, per-type totals, entities and uptime", async () => {
244
+ const { base, auth, service, close } = await setup();
245
+ try {
246
+ service.saveWithDedupe({ type: "preference", title: "p", content: "c" });
247
+ service.saveWithDedupe({ type: "project", title: "j", content: "c" });
248
+ service.saveWithDedupe({ type: "project", title: "j2", content: "c" });
249
+
250
+ const res = await fetch(`${base}/status`, { headers: auth });
251
+ assert.equal(res.status, 200);
252
+ const body = await res.json();
253
+ // 回归锁:/status 的版本必须来自 package.json(PACKAGE_VERSION),不是散落的
254
+ // 字面量——曾经此处硬编码常量在发版时漏 bump,运行 0.8.13 却对外报 0.7.12。
255
+ assert.equal(body.version, PACKAGE_VERSION);
256
+ assert.equal(body.memories.total, 3);
257
+ assert.equal(body.memories.byType.preference, 1);
258
+ assert.equal(body.memories.byType.project, 2);
259
+ assert.equal(body.entities, 0, "no extraction wired → empty entity table");
260
+ assert.ok(Number.isInteger(body.uptime_s));
261
+ } finally {
262
+ close();
263
+ }
264
+ });
265
+
266
+ test("GET /search finds saved memories; empty q returns empty keyword result", async () => {
267
+ const { base, auth, close } = await setup();
268
+ try {
269
+ await fetch(`${base}/memories`, {
270
+ method: "POST",
271
+ headers: { ...auth, "content-type": "application/json" },
272
+ body: JSON.stringify({ type: "project", title: "记忆插件", content: "SQLite 全文检索" })
273
+ });
274
+
275
+ const res = await fetch(`${base}/search?q=${encodeURIComponent("全文检索")}&mode=keyword`, { headers: auth });
276
+ assert.equal(res.status, 200);
277
+ const body = await res.json();
278
+ assert.equal(body.mode, "keyword");
279
+ assert.equal(body.items.length, 1);
280
+ assert.equal(body.items[0].title, "记忆插件");
281
+
282
+ const empty = await fetch(`${base}/search?q=`, { headers: auth });
283
+ assert.deepEqual(await empty.json(), { items: [], mode: "keyword" });
284
+ } finally {
285
+ close();
286
+ }
287
+ });
288
+
289
+ test("unknown path returns 404 json", async () => {
290
+ const { base, auth, close } = await setup();
291
+ try {
292
+ const res = await fetch(`${base}/nope`, { headers: auth });
293
+ assert.equal(res.status, 404);
294
+ assert.deepEqual(await res.json(), { error: "not-found" });
295
+ } finally {
296
+ close();
297
+ }
298
+ });
299
+
300
+ // --- light-mode preset (applyLightModePreset) ------------------------------------
301
+
302
+ const LIGHT_OFF_FIELDS = [
303
+ "entityExtractionEnabled",
304
+ "autoDream",
305
+ "sleepModeEnabled",
306
+ "rerankEnabled",
307
+ "autoReindexOnBoot",
308
+ "hybridInject",
309
+ "searchSemanticDedup",
310
+ "selectiveInjectEnabled",
311
+ "bm25SearchEnabled"
312
+ ];
313
+
314
+ test("applyLightModePreset turns heavy features off and keeps the core loop", () => {
315
+ const cfg = applyLightModePreset(Config({ lightMode: true }));
316
+ for (const field of LIGHT_OFF_FIELDS) {
317
+ assert.equal(cfg[field], false, `${field} forced off in light mode`);
318
+ }
319
+ // Core loop preserved.
320
+ assert.equal(cfg.autoInject, true);
321
+ assert.equal(cfg.autoSummarize, true);
322
+ assert.equal(cfg.hotMemoryEnabled, true);
323
+ assert.equal(cfg.memoryQualityFilter.enabled, true);
324
+ // Unrelated knobs untouched.
325
+ assert.equal(cfg.dreamThresholdCount, 10);
326
+ assert.equal(cfg.dreamDelayMs, 2000);
327
+ assert.equal(cfg.maxInjectedItems, 5);
328
+ });
329
+
330
+ test("applyLightModePreset keeps explicit non-preset values and is a no-op without lightMode", () => {
331
+ const tuned = applyLightModePreset(Config({ lightMode: true, dreamThresholdCount: 30, maxInjectedItems: 8 }));
332
+ assert.equal(tuned.dreamThresholdCount, 30, "operator values survive the preset");
333
+ assert.equal(tuned.maxInjectedItems, 8);
334
+
335
+ const plain = Config({});
336
+ assert.equal(applyLightModePreset(plain), plain, "identity when lightMode is unset");
337
+ const off = Config({ lightMode: false });
338
+ assert.equal(applyLightModePreset(off), off, "identity when lightMode is false");
339
+ });
340
+
341
+ test("persisted panel_mode=light wins over a bundle config that did not ask for it", () => {
342
+ const store = createStore(":memory:");
343
+ const settings = createSettings(store.db);
344
+ try {
345
+ // Panel switched to light in a previous session; bundle config says nothing.
346
+ settings.setPanelMode("light");
347
+ const rawCfg = Config({});
348
+ const lightMode = rawCfg.lightMode === true || settings.getPanelMode() === "light";
349
+ const cfg = applyLightModePreset({ ...rawCfg, lightMode });
350
+ assert.equal(lightMode, true, "persisted mode forces light");
351
+ assert.equal(cfg.autoDream, false);
352
+ assert.equal(cfg.entityExtractionEnabled, false);
353
+ assert.equal(cfg.autoInject, true, "core injection stays on");
354
+
355
+ // standard (default) never forces the preset even with a light bundle flag off.
356
+ settings.setPanelMode("standard");
357
+ const raw2 = Config({});
358
+ assert.equal(raw2.lightMode === true || settings.getPanelMode() === "light", false);
359
+ } finally {
360
+ store.close();
361
+ }
362
+ });
363
+
364
+ // --- #181:MCP 六件套的 API 面(PUT / save 透传 / archived 与 occurred 窗口)---
365
+
366
+ test("PUT /memories/:id patches fields and returns the DTO (unauthorized without token)", async () => {
367
+ const { base, auth, service, close } = await setup();
368
+ try {
369
+ const created = await (await fetch(`${base}/memories`, {
370
+ method: "POST",
371
+ headers: { ...auth, "content-type": "application/json" },
372
+ body: JSON.stringify({ type: "preference", title: "编辑器", content: "用 vim", importance: 3 })
373
+ })).json();
374
+
375
+ const noAuth = await fetch(`${base}/memories/${created.id}`, {
376
+ method: "PUT",
377
+ headers: { "content-type": "application/json" },
378
+ body: JSON.stringify({ content: "用 nvim" })
379
+ });
380
+ assert.equal(noAuth.status, 401, "PUT requires the Bearer token");
381
+
382
+ const put = await fetch(`${base}/memories/${created.id}`, {
383
+ method: "PUT",
384
+ headers: { ...auth, "content-type": "application/json" },
385
+ body: JSON.stringify({ content: "用 nvim", importance: 4, tags: ["工具"], reason: "用户改用 nvim 了" })
386
+ });
387
+ assert.equal(put.status, 200);
388
+ const { memory } = await put.json();
389
+ assert.equal(memory.content, "用 nvim");
390
+ assert.equal(memory.importance, 4);
391
+ assert.deepEqual(memory.tags, ["工具"]);
392
+
393
+ // content 改写按 human_override 入档(与内部面板写路径一致)。
394
+ const raw = service.getById(created.id);
395
+ assert.equal(raw.content_history?.[0]?.source, "human_override");
396
+ assert.equal(raw.content_history?.[0]?.content, "用 vim");
397
+ } finally {
398
+ close();
399
+ }
400
+ });
401
+
402
+ test("PUT /memories/:id validation: bad fields → 400, empty patch → 400, missing id → 404", async () => {
403
+ const { base, auth, close } = await setup();
404
+ try {
405
+ const put = (body, id = "whatever") => fetch(`${base}/memories/${id}`, {
406
+ method: "PUT",
407
+ headers: { ...auth, "content-type": "application/json" },
408
+ body: JSON.stringify(body)
409
+ });
410
+ assert.equal((await put({ title: "" })).status, 400);
411
+ assert.equal((await put({ importance: 9 })).status, 400);
412
+ assert.equal((await put({ tags: "x" })).status, 400);
413
+ assert.equal((await put({ type: "nope" })).status, 400);
414
+ assert.equal((await put({})).status, 400, "empty patch is no-fields");
415
+ assert.equal((await put({ content: "x" }, "missing-id")).status, 404);
416
+ assert.equal((await put({ agent_scope: 5 })).status, 400);
417
+ } finally {
418
+ close();
419
+ }
420
+ });
421
+
422
+ test("PUT /memories/:id surfaces service failures as 500 instead of a hung request", async () => {
423
+ const { base, auth, service, close } = await setup();
424
+ try {
425
+ const created = await (await fetch(`${base}/memories`, {
426
+ method: "POST",
427
+ headers: { ...auth, "content-type": "application/json" },
428
+ body: JSON.stringify({ type: "preference", title: "会抛错", content: "v1" })
429
+ })).json();
430
+ const original = service.update;
431
+ service.update = () => { throw new Error("boom"); };
432
+ try {
433
+ const res = await fetch(`${base}/memories/${created.id}`, {
434
+ method: "PUT",
435
+ headers: { ...auth, "content-type": "application/json" },
436
+ body: JSON.stringify({ content: "v2" })
437
+ });
438
+ assert.equal(res.status, 500, "service throw must not strand the request");
439
+ assert.deepEqual(await res.json(), { error: "internal" });
440
+ } finally {
441
+ service.update = original;
442
+ }
443
+ } finally {
444
+ close();
445
+ }
446
+ });
447
+
448
+ test("POST /memories passes through sensitivity/occurred_at/scope and returns action", async () => {
449
+ const { base, auth, close } = await setup();
450
+ try {
451
+ const post = await fetch(`${base}/memories`, {
452
+ method: "POST",
453
+ headers: { ...auth, "content-type": "application/json" },
454
+ body: JSON.stringify({
455
+ type: "decision",
456
+ title: "迁移",
457
+ content: "迁到 sqlite 分支",
458
+ sensitivity: "personal",
459
+ occurred_at: "2026-01-15T10:00:00Z",
460
+ agent_scope: "global"
461
+ })
462
+ });
463
+ assert.equal(post.status, 201);
464
+ const created = await post.json();
465
+ assert.equal(created.action, "created", "action rides along for tool parity");
466
+ assert.equal(created.sensitivity, "personal");
467
+ // store 把 ISO 瞬时归一化成完整毫秒形式(2026-01-15T10:00:00Z → …T10:00:00.000Z)。
468
+ assert.match(created.occurred_at, /^2026-01-15T10:00:00/);
469
+ assert.equal(created.agent_scope, "global");
470
+ assert.equal(created.agent_scope_source, "explicit");
471
+
472
+ // 合并判据=同 type + 同标题 + 同 sensitivity + 同作用域三元(0.8.0 起去重键
473
+ // 含 scope,跨作用域同标题本就分开存):补齐 agent_scope 才 merged。
474
+ const merged = await (await fetch(`${base}/memories`, {
475
+ method: "POST",
476
+ headers: { ...auth, "content-type": "application/json" },
477
+ body: JSON.stringify({ type: "decision", title: "迁移", content: "迁到 sqlite 分支(更新)", sensitivity: "personal", agent_scope: "global" })
478
+ })).json();
479
+ assert.equal(merged.action, "merged", "same dedupe key reports merged");
480
+
481
+ const separate = await (await fetch(`${base}/memories`, {
482
+ method: "POST",
483
+ headers: { ...auth, "content-type": "application/json" },
484
+ body: JSON.stringify({ type: "decision", title: "迁移", content: "无标注版本" })
485
+ })).json();
486
+ assert.equal(separate.action, "created", "no sensitivity/scope → different dedupe key");
487
+
488
+ const bad = await fetch(`${base}/memories`, {
489
+ method: "POST",
490
+ headers: { ...auth, "content-type": "application/json" },
491
+ body: JSON.stringify({ type: "decision", title: "x", content: "y", sensitivity: 5 })
492
+ });
493
+ assert.equal(bad.status, 400);
494
+ assert.equal((await bad.json()).error, "invalid-sensitivity");
495
+ } finally {
496
+ close();
497
+ }
498
+ });
499
+
500
+ test("GET /memories supports include_archived and the occurred_at window", async () => {
501
+ const { base, auth, service, close } = await setup();
502
+ try {
503
+ const save = (title, occurredAt) => fetch(`${base}/memories`, {
504
+ method: "POST",
505
+ headers: { ...auth, "content-type": "application/json" },
506
+ body: JSON.stringify({ type: "history", title, content: `body of ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
507
+ });
508
+ const january = await (await save("一月的事", "2026-01-15T10:00:00Z")).json();
509
+ await save("二月的事", "2026-02-15T10:00:00Z");
510
+ await save("无时间戳的事", null);
511
+
512
+ const february = await (await fetch(`${base}/memories?occurred_from=2026-02-01`, { headers: auth })).json();
513
+ // 「无时间戳的事」按 occurred_at→created_at 回退(写入日 2026-09),落在窗口内。
514
+ assert.deepEqual(february.items.map((m) => m.title).sort(), ["二月的事", "无时间戳的事"]);
515
+ assert.equal(february.total, 2, "total honors the same window");
516
+
517
+ const upToJanuary = await (await fetch(`${base}/memories?occurred_to=2026-01-31`, { headers: auth })).json();
518
+ assert.deepEqual(upToJanuary.items.map((m) => m.title), ["一月的事"]);
519
+
520
+ service.setArchived(january.id, true);
521
+ const active = await (await fetch(`${base}/memories`, { headers: auth })).json();
522
+ assert.equal(active.total, 2, "archived rows stay hidden by default");
523
+ const withArchived = await (await fetch(`${base}/memories?include_archived=true`, { headers: auth })).json();
524
+ assert.equal(withArchived.total, 3, "include_archived=true surfaces archived rows");
525
+ } finally {
526
+ close();
527
+ }
528
+ });
529
+
530
+ test("GET /search honors the occurred_at window", async () => {
531
+ const { base, auth, close } = await setup();
532
+ try {
533
+ const save = (title, occurredAt) => fetch(`${base}/memories`, {
534
+ method: "POST",
535
+ headers: { ...auth, "content-type": "application/json" },
536
+ body: JSON.stringify({ type: "history", title, content: `记忆星球 ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
537
+ });
538
+ await save("旧事", "2026-01-15T10:00:00Z");
539
+ await save("新事", "2026-03-15T10:00:00Z");
540
+
541
+ const hit = await (await fetch(`${base}/search?q=${encodeURIComponent("记忆星球")}&occurred_from=2026-03-01`, { headers: auth })).json();
542
+ assert.equal(hit.items.length, 1);
543
+ assert.equal(hit.items[0].title, "新事");
544
+ } finally {
545
+ close();
546
+ }
547
+ });
548
+
549
+ // --- GET /context(issue #370,#363 承诺)---------------------------------------
550
+
551
+ /** /context 用例的省事入库:走 POST /memories,与第三方调用同路径。 */
552
+ async function saveMemory(base, auth, body) {
553
+ const res = await fetch(`${base}/memories`, {
554
+ method: "POST",
555
+ headers: { ...auth, "content-type": "application/json" },
556
+ body: JSON.stringify(body)
557
+ });
558
+ assert.ok(res.status === 201 || res.status === 200, `save ${body.title} → ${res.status}`);
559
+ return res.json();
560
+ }
561
+
562
+ test("GET /search passes a declared scope through (strictScope hard wall on the search face too)", async () => {
563
+ // issue #370:searchMemories 本就收 scope,8790 此前没有入口——透传后第三方
564
+ // 声明身份,A2 软加权与 strictScope 硬过滤在检索面同样成立;不传参数行为
565
+ // 与既往逐字节一致(scopeFromSearchParams 返回 undefined → 不进 options)。
566
+ const { base, auth, close } = await setup({ config: { strictScope: true } });
567
+ try {
568
+ await saveMemory(base, auth, { type: "decision", title: "他域检索", content: "外部线索 abc", importance: 5, agent_scope: "other-agent" });
569
+
570
+ const scoped = await (await fetch(`${base}/search?q=${encodeURIComponent("外部线索")}&agent_scope=me`, { headers: auth })).json();
571
+ assert.ok(!scoped.items.some((m) => m.title === "他域检索"), "explicit foreign agent_scope row is hard-filtered");
572
+
573
+ const unscoped = await (await fetch(`${base}/search?q=${encodeURIComponent("外部线索")}`, { headers: auth })).json();
574
+ assert.ok(unscoped.items.some((m) => m.title === "他域检索"), "no scope declared → gate dormant, behavior unchanged");
575
+ } finally {
576
+ close();
577
+ }
578
+ });
579
+
580
+ test("GET /context returns the injection-shaped aggregate; empty q still serves the rule tier", async () => {
581
+ const { base, auth, settings, close } = await setup();
582
+ try {
583
+ settings.setProfile("我是后端工程师");
584
+ settings.setRules(["先验证再修改"]);
585
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
586
+ await saveMemory(base, auth, { type: "preference", title: "默认中文", content: "回复默认用中文", importance: 4 });
587
+
588
+ const res = await fetch(`${base}/context`, { headers: auth });
589
+ assert.equal(res.status, 200);
590
+ const body = await res.json();
591
+ // 形状锁:四键响应——bridge 等调用方按这四个键渲染,漂移(加塞/漏带)在此变红。
592
+ assert.deepEqual(Object.keys(body).sort(), ["items", "pinnedCount", "profile", "rules"]);
593
+ assert.equal(body.profile, "我是后端工程师");
594
+ assert.deepEqual(body.rules, ["先验证再修改"]);
595
+ assert.equal(body.pinnedCount, 0, "pinnedInjectBudget 默认 0(opt-in 纪律,issue #370 取舍 3)");
596
+ const titles = body.items.map((m) => m.title);
597
+ assert.ok(titles.includes("核心决策") && titles.includes("默认中文"), "empty q → pure rule tier, high-importance rows still served");
598
+ for (const item of body.items) {
599
+ assert.ok(item.id && item.type && item.title && typeof item.content === "string" && Number.isInteger(item.importance));
600
+ }
601
+ } finally {
602
+ close();
603
+ }
604
+ });
605
+
606
+ test("GET /context threshold is an importance gate (not /search's similarity threshold)", async () => {
607
+ // 同名不同义锁(issue #370 点名的文档区分):/context 的 threshold 走
608
+ // injectCandidates 的 importance 门(summary/preference 豁免),与相似度无关
609
+ // ——本用例全程无 embedder/向量,纯规则档即可验证。
610
+ const { base, auth, close } = await setup();
611
+ try {
612
+ await saveMemory(base, auth, { type: "decision", title: "低重要", content: "小事一桩", importance: 3 });
613
+ await saveMemory(base, auth, { type: "decision", title: "高重要", content: "大事记", importance: 5 });
614
+
615
+ const open = await (await fetch(`${base}/context`, { headers: auth })).json();
616
+ const openTitles = open.items.map((m) => m.title);
617
+ assert.ok(openTitles.includes("低重要") && openTitles.includes("高重要"), "default threshold=3 admits both");
618
+
619
+ const gated = await (await fetch(`${base}/context?threshold=4`, { headers: auth })).json();
620
+ const gatedTitles = gated.items.map((m) => m.title);
621
+ assert.ok(gatedTitles.includes("高重要"), "importance 5 survives threshold=4");
622
+ assert.ok(!gatedTitles.includes("低重要"), "importance 3 is gated out at threshold=4");
623
+ } finally {
624
+ close();
625
+ }
626
+ });
627
+
628
+ test("GET /context pins preference rows ahead when pinnedInjectBudget is on", async () => {
629
+ // #249 pin 池经 8790 透出。用 preference 而非 constraint:constraint 属编码
630
+ // 记忆,非编码查询被 codingGate 排除在候选池外,pin 池也够不着它。
631
+ const { base, auth, close } = await setup({ config: { pinnedInjectBudget: 2 } });
632
+ try {
633
+ await saveMemory(base, auth, { type: "preference", title: "pin-偏好", content: "永远先讲结论", importance: 5 });
634
+ await saveMemory(base, auth, { type: "decision", title: "普通决策", content: "先做 A 再做 B", importance: 5 });
635
+
636
+ const body = await (await fetch(`${base}/context`, { headers: auth })).json();
637
+ assert.equal(body.items[0].title, "pin-偏好", "pinned row leads the block");
638
+ assert.equal(body.pinnedCount, 1);
639
+ } finally {
640
+ close();
641
+ }
642
+ });
643
+
644
+ test("GET /context honors a declared scope under strictScope; undeclared stays unfiltered", async () => {
645
+ // scope 语义锁(issue #370):声明身份 → strictScope 硬过滤按 isVisibleInScope
646
+ // 生效;不声明 → scope=null,门不触发(与宿主「会话身份取不到时两维为 null」
647
+ // 同构)。任一维声明而另一维缺省时,缺维按解析不到走 fail-closed。
648
+ const { base, auth, close } = await setup({ config: { strictScope: true } });
649
+ try {
650
+ await saveMemory(base, auth, { type: "decision", title: "他域决策", content: "别的 agent 的事", importance: 5, agent_scope: "other-agent" });
651
+ await saveMemory(base, auth, { type: "decision", title: "全域决策", content: "谁都可见", importance: 5 });
652
+
653
+ const declared = await (await fetch(`${base}/context?agent_scope=me`, { headers: auth })).json();
654
+ const declaredTitles = declared.items.map((m) => m.title);
655
+ assert.ok(!declaredTitles.includes("他域决策"), "explicit foreign agent_scope row is hard-filtered");
656
+ assert.ok(declaredTitles.includes("全域决策"));
657
+
658
+ const undeclared = await (await fetch(`${base}/context`, { headers: auth })).json();
659
+ const undeclaredTitles = undeclared.items.map((m) => m.title);
660
+ assert.ok(undeclaredTitles.includes("他域决策"), "no declared scope → no gate");
661
+ } finally {
662
+ close();
663
+ }
664
+ });
665
+
666
+ test("GET /context embeds the query via the injected embedder (wiring lock)", async () => {
667
+ // embedder 接线锁(issue #370):createStandaloneApi 新增的可选 embedder 必须
668
+ // 真被 /context 用上——宿主与 daemon 传的都是 semantic 装配的同一实例。
669
+ const calls = [];
670
+ const fake = {
671
+ ready: true,
672
+ modelHash: "fake-hash-1",
673
+ dimension: 4,
674
+ embedSingle: async (text) => {
675
+ calls.push(text);
676
+ return [1, 0, 0, 0];
677
+ }
678
+ };
679
+ const { base, auth, close } = await setup({ embedder: fake });
680
+ try {
681
+ const res = await fetch(`${base}/context?q=${encodeURIComponent("语义查询")}`, { headers: auth });
682
+ assert.equal(res.status, 200);
683
+ await res.json();
684
+ assert.deepEqual(calls, ["语义查询"], "the route must hand the query to the injected embedder");
685
+ } finally {
686
+ close();
687
+ }
688
+ });
689
+
690
+ test("GET /context survives a throwing embedder (rule-tier degradation, never 500)", async () => {
691
+ const { base, auth, close } = await setup({
692
+ embedder: { ready: true, embedSingle: async () => { throw new Error("model offline"); } }
693
+ });
694
+ try {
695
+ await saveMemory(base, auth, { type: "decision", title: "降级存照", content: "嵌入挂了也要有注入", importance: 5 });
696
+ const res = await fetch(`${base}/context?q=任意`, { headers: auth });
697
+ assert.equal(res.status, 200, "embed failure must degrade to the rule tier");
698
+ const body = await res.json();
699
+ assert.ok(body.items.some((m) => m.title === "降级存照"));
700
+ } finally {
701
+ close();
702
+ }
703
+ });
704
+
705
+ test("GET /context times out a hung embedder and degrades (embedTimeoutMs guard)", async () => {
706
+ // CodeRabbit on #371:embedder 挂起(不抛错,典型为第三方 ollama/openai 端点
707
+ // 无响应)不能占住 HTTP 连接——超时按嵌入缺失降级规则档。测试用 50ms 短超时
708
+ // 避免慢测试;生产默认 3000 由工厂选项约束(同 strictPort,不进 config schema)。
709
+ const { base, auth, close } = await setup({
710
+ embedTimeoutMs: 50,
711
+ embedder: { ready: true, embedSingle: () => new Promise(() => {}) }
712
+ });
713
+ try {
714
+ await saveMemory(base, auth, { type: "decision", title: "挂起存照", content: "嵌入悬挂也要有注入", importance: 5 });
715
+ const started = Date.now();
716
+ const res = await fetch(`${base}/context?q=任意`, { headers: auth });
717
+ assert.equal(res.status, 200, "hung embedder must not hang the route");
718
+ const body = await res.json();
719
+ assert.ok(body.items.some((m) => m.title === "挂起存照"), "timed-out embed falls back to the rule tier");
720
+ assert.ok(Date.now() - started < 3000, "response must not wait on the hung embedder");
721
+ } finally {
722
+ close();
723
+ }
724
+ });
725
+
726
+ test("strictPort: busy port rejects instead of hopping; default path still hops", async () => {
727
+ // daemon 语义锁(#363):strictPort 下配置端口被占 = 配置错误,明确失败 ——
728
+ // 顺延会让把 URL 写死的第三方客户端静默打到错误端口。占口用裸 net server
729
+ // (OS 分配,不与并行测试抢固定号)。
730
+ const { default: net } = await import("node:net");
731
+ const blocker = net.createServer();
732
+ await new Promise((resolve) => blocker.listen(0, "127.0.0.1", resolve));
733
+ const busyPort = blocker.address().port;
734
+
735
+ const store = createStore(":memory:");
736
+ const service = createService({ store, mirror: null, config: {} });
737
+ const settings = createSettings(store.db);
738
+ try {
739
+ const strict = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: busyPort, strictPort: true });
740
+ await assert.rejects(strict.ready, (err) => err?.code === "EADDRINUSE");
741
+
742
+ // 默认路径(不传 strictPort)行为不变:顺延成功;具体端口不断言(避免抢号)。
743
+ const hopping = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: busyPort });
744
+ await hopping.ready;
745
+ assert.notEqual(hopping.port, busyPort, "default policy hops off a busy port");
746
+ hopping.server.close();
747
+ } finally {
748
+ blocker.close();
749
+ store.close();
750
+ }
751
+ });