@modusensus/dsh-mneme 0.8.14 → 0.8.16

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 (279) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +660 -654
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +691 -689
  5. package/bin/dsh-mneme-mcp.mjs +510 -510
  6. package/bin/dsh-mneme-serve.mjs +151 -151
  7. package/cordis.patch.yml +21 -21
  8. package/docs/CONFIGURATION.md +275 -0
  9. package/docs/CONTINUITY.md +124 -0
  10. package/docs/DAEMON.md +46 -0
  11. package/docs/DISTILL.md +162 -0
  12. package/docs/ENTITIES.md +245 -0
  13. package/docs/LOCAL_MODEL.md +222 -0
  14. package/docs/SEMANTIC.md +256 -0
  15. package/docs/SLEEP.md +164 -0
  16. package/docs/STORAGE.md +98 -0
  17. package/lib/api-standalone.js +656 -673
  18. package/lib/api.js +1605 -1433
  19. package/lib/bootstrap.js +211 -211
  20. package/lib/client.js +6354 -5296
  21. package/lib/commands.js +95 -95
  22. package/lib/config.js +947 -843
  23. package/lib/content-hash.js +54 -54
  24. package/lib/continuity.js +220 -220
  25. package/lib/document-index.js +94 -94
  26. package/lib/document.js +303 -303
  27. package/lib/dream/clustering.js +118 -118
  28. package/lib/dream/decisions.js +694 -674
  29. package/lib/dream/narratives.js +44 -44
  30. package/lib/dream/sleep.js +819 -819
  31. package/lib/dream.js +1503 -1501
  32. package/lib/embedding.js +177 -177
  33. package/lib/entities/extractor.js +252 -252
  34. package/lib/graph/anchoring.js +179 -179
  35. package/lib/guide.js +74 -74
  36. package/lib/heat.js +144 -144
  37. package/lib/hot-memory.js +108 -46
  38. package/lib/index.js +552 -503
  39. package/lib/inject.js +428 -450
  40. package/lib/lang.js +248 -229
  41. package/lib/local-embedder.js +358 -358
  42. package/lib/maintenance.js +162 -142
  43. package/lib/mirror.js +330 -330
  44. package/lib/organize.js +450 -450
  45. package/lib/peak-hours.js +117 -117
  46. package/lib/placement.js +13 -0
  47. package/lib/pre-inject-gate.js +340 -0
  48. package/lib/quality-filter.js +126 -126
  49. package/lib/recall-stats.js +190 -175
  50. package/lib/reclaim-http.js +150 -0
  51. package/lib/reranker.js +269 -269
  52. package/lib/runtime/adopt.js +176 -176
  53. package/lib/runtime/closure.js +172 -172
  54. package/lib/runtime/download.js +247 -247
  55. package/lib/runtime/layout.js +265 -265
  56. package/lib/runtime/loader.js +252 -252
  57. package/lib/runtime/model-fetch.js +361 -361
  58. package/lib/runtime/provision.js +237 -237
  59. package/lib/runtime/tarball.js +130 -130
  60. package/lib/runtime/verify.js +223 -204
  61. package/lib/safe-slice.js +18 -0
  62. package/lib/scope.js +146 -146
  63. package/lib/search/adaptive.js +60 -60
  64. package/lib/search/bm25.js +96 -96
  65. package/lib/semantic.js +229 -229
  66. package/lib/sensitive-scan.js +209 -209
  67. package/lib/serve.js +215 -215
  68. package/lib/service.js +2688 -2605
  69. package/lib/settings.js +528 -511
  70. package/lib/store.js +3196 -3007
  71. package/lib/summarize.js +1039 -856
  72. package/lib/tools.js +743 -737
  73. package/lib/vector-index.js +110 -110
  74. package/lib/version-check.js +122 -122
  75. package/lib/write-admission.js +402 -402
  76. package/locale/en.json +6 -6
  77. package/locale/zh.json +6 -6
  78. package/package.json +118 -118
  79. package/runtime-manifest.json +526 -526
  80. package/scripts/benchmark-embed.js +201 -201
  81. package/scripts/benchmark-recall.js +249 -249
  82. package/scripts/benchmark-rerank.js +166 -166
  83. package/scripts/build-runtime-manifest.mjs +224 -224
  84. package/scripts/changelog-prep.mjs +36 -36
  85. package/scripts/check-sync.js +42 -42
  86. package/scripts/e2e-dsh.js +220 -220
  87. package/scripts/mneme-runtime.mjs +277 -277
  88. package/scripts/stress-dsh.js +255 -255
  89. package/scripts/sync-lib.js +47 -47
  90. package/scripts/sync-test-badge.mjs +69 -69
  91. package/scripts/test-count-sync.mjs +44 -44
  92. package/src/api-standalone.js +656 -673
  93. package/src/api.js +1605 -1433
  94. package/src/bootstrap.js +211 -211
  95. package/src/commands.js +95 -95
  96. package/src/config.js +947 -843
  97. package/src/content-hash.js +54 -54
  98. package/src/continuity.js +220 -220
  99. package/src/document-index.js +94 -94
  100. package/src/document.js +303 -303
  101. package/src/dream/clustering.js +118 -118
  102. package/src/dream/decisions.js +694 -674
  103. package/src/dream/narratives.js +44 -44
  104. package/src/dream/sleep.js +819 -819
  105. package/src/dream.js +1503 -1501
  106. package/src/embedding.js +177 -177
  107. package/src/entities/extractor.js +252 -252
  108. package/src/graph/anchoring.js +179 -179
  109. package/src/guide.js +74 -74
  110. package/src/heat.js +144 -144
  111. package/src/hot-memory.js +108 -46
  112. package/src/index.js +552 -503
  113. package/src/inject.js +428 -450
  114. package/src/lang.js +248 -229
  115. package/src/local-embedder.js +358 -358
  116. package/src/maintenance.js +162 -142
  117. package/src/mirror.js +330 -330
  118. package/src/organize.js +450 -450
  119. package/src/peak-hours.js +117 -117
  120. package/src/placement.js +13 -0
  121. package/src/pre-inject-gate.js +340 -0
  122. package/src/quality-filter.js +126 -126
  123. package/src/recall-stats.js +190 -175
  124. package/src/reclaim-http.js +150 -0
  125. package/src/reranker.js +269 -269
  126. package/src/runtime/adopt.js +176 -176
  127. package/src/runtime/closure.js +172 -172
  128. package/src/runtime/download.js +247 -247
  129. package/src/runtime/layout.js +265 -265
  130. package/src/runtime/loader.js +252 -252
  131. package/src/runtime/model-fetch.js +361 -361
  132. package/src/runtime/provision.js +237 -237
  133. package/src/runtime/tarball.js +130 -130
  134. package/src/runtime/verify.js +223 -204
  135. package/src/safe-slice.js +18 -0
  136. package/src/scope.js +146 -146
  137. package/src/search/adaptive.js +60 -60
  138. package/src/search/bm25.js +96 -96
  139. package/src/semantic.js +229 -229
  140. package/src/sensitive-scan.js +209 -209
  141. package/src/serve.js +215 -215
  142. package/src/service.js +2688 -2605
  143. package/src/settings.js +528 -511
  144. package/src/store.js +3196 -3007
  145. package/src/summarize.js +1039 -856
  146. package/src/tools.js +743 -737
  147. package/src/vector-index.js +110 -110
  148. package/src/version-check.js +122 -122
  149. package/src/write-admission.js +402 -402
  150. package/test/adaptive-inject-budget.test.js +85 -85
  151. package/test/api-routes-gaps.test.js +899 -218
  152. package/test/api.test.js +1725 -1690
  153. package/test/audit.test.js +448 -448
  154. package/test/baseline-persist.test.js +248 -248
  155. package/test/benchmark.test.js +94 -94
  156. package/test/bootstrap.test.js +220 -220
  157. package/test/changelog-prep.test.js +60 -60
  158. package/test/client.test.js +1582 -1169
  159. package/test/clustering.test.js +100 -100
  160. package/test/commands.test.js +106 -106
  161. package/test/config.test.js +66 -66
  162. package/test/conflict-freeze.test.js +300 -300
  163. package/test/content-hash.test.js +204 -204
  164. package/test/continuity.test.js +333 -333
  165. package/test/contrast.test.js +314 -0
  166. package/test/document-dir.test.js +233 -233
  167. package/test/document.test.js +671 -671
  168. package/test/dream-archive-guardrail.test.js +116 -116
  169. package/test/dream-candidate-hybrid.test.js +281 -281
  170. package/test/dream-coverage-degrade.test.js +86 -86
  171. package/test/dream-failure-backoff.test.js +173 -173
  172. package/test/dream-merge-guardrail.test.js +219 -0
  173. package/test/dream-peak-hours.test.js +194 -194
  174. package/test/dream.test.js +1385 -1383
  175. package/test/embedding-ready.test.js +196 -196
  176. package/test/entities.test.js +627 -547
  177. package/test/entity-recall.test.js +179 -179
  178. package/test/epistemic.test.js +325 -325
  179. package/test/fnew-0112.test.js +311 -311
  180. package/test/fnew-03.test.js +422 -422
  181. package/test/graph-anchoring.test.js +184 -184
  182. package/test/graph-api.test.js +175 -175
  183. package/test/graph-inject-budget.test.js +103 -103
  184. package/test/graph-passive-confirm.test.js +91 -91
  185. package/test/graph-weight-evolution.test.js +104 -104
  186. package/test/heat.test.js +175 -175
  187. package/test/helpers/dream-mock.js +82 -82
  188. package/test/helpers/peer-worker.mjs +25 -25
  189. package/test/helpers/runtime-source.js +60 -60
  190. package/test/helpers/tar-builder.js +80 -80
  191. package/test/helpers/write-admission-samples.js +308 -308
  192. package/test/hot-memory.test.js +211 -145
  193. package/test/inject-content-cap.test.js +91 -91
  194. package/test/inject-first-round-bm25.test.js +89 -89
  195. package/test/inject-heat.test.js +77 -77
  196. package/test/inject-parent-gate.test.js +106 -106
  197. package/test/inject-pools.test.js +194 -194
  198. package/test/inject-recall.test.js +144 -105
  199. package/test/inject-rotation.test.js +161 -161
  200. package/test/inject.test.js +443 -420
  201. package/test/lang.test.js +87 -87
  202. package/test/lastrunat-persist.test.js +101 -101
  203. package/test/lib-smoke.test.js +96 -96
  204. package/test/llm-audit.test.js +696 -598
  205. package/test/llm-message-source.test.js +207 -207
  206. package/test/local-embedder.test.js +292 -292
  207. package/test/maintenance.test.js +501 -391
  208. package/test/mcp-stdio.test.js +385 -385
  209. package/test/mirror-dirty.test.js +424 -424
  210. package/test/mirror-edit-digest.test.js +187 -187
  211. package/test/mirror-generation.test.js +499 -499
  212. package/test/mirror-types.test.js +208 -208
  213. package/test/mirror.test.js +249 -249
  214. package/test/narrative-bars.test.js +162 -162
  215. package/test/organize.test.js +418 -418
  216. package/test/peer-blockers.test.js +193 -193
  217. package/test/placement.test.js +36 -0
  218. package/test/policy-epoch.test.js +259 -259
  219. package/test/pre-inject-gate.test.js +444 -0
  220. package/test/quality-filter.test.js +186 -186
  221. package/test/reasoning-effort.test.js +752 -752
  222. package/test/recall-anti-update.test.js +82 -82
  223. package/test/recall-evals.test.js +253 -253
  224. package/test/recall-layer.test.js +326 -326
  225. package/test/recall-stats.test.js +274 -189
  226. package/test/receipt-chain.test.js +451 -451
  227. package/test/reclaim-http.test.js +209 -0
  228. package/test/reflection.test.js +226 -226
  229. package/test/reindex-backfill.test.js +62 -62
  230. package/test/reranker-single-logit.test.js +73 -73
  231. package/test/reranker.test.js +197 -197
  232. package/test/resident-status.test.js +83 -83
  233. package/test/runtime-adopt.test.js +206 -206
  234. package/test/runtime-cli.test.js +89 -89
  235. package/test/runtime-closure.test.js +193 -193
  236. package/test/runtime-download.test.js +302 -302
  237. package/test/runtime-layout.test.js +163 -163
  238. package/test/runtime-loader.test.js +255 -255
  239. package/test/runtime-manifest.test.js +159 -159
  240. package/test/runtime-model-fetch.test.js +348 -348
  241. package/test/runtime-provision.test.js +101 -101
  242. package/test/runtime-tarball.test.js +81 -81
  243. package/test/runtime-verify.test.js +319 -279
  244. package/test/scope-candidates.test.js +239 -239
  245. package/test/scope-explicit.test.js +452 -452
  246. package/test/scope-inject-soft.test.js +106 -106
  247. package/test/scope-retrieval.test.js +197 -197
  248. package/test/scope-storage.test.js +255 -255
  249. package/test/scope-strict.test.js +367 -367
  250. package/test/search-fusion.test.js +90 -90
  251. package/test/semantic.test.js +124 -124
  252. package/test/sensitive-scan.test.js +207 -207
  253. package/test/serve-bin.test.js +121 -121
  254. package/test/serve.test.js +196 -196
  255. package/test/service-search.test.js +174 -174
  256. package/test/service.test.js +410 -405
  257. package/test/settings.test.js +269 -261
  258. package/test/skip-invalid-restore.test.js +262 -262
  259. package/test/sleep-action-set.test.js +422 -422
  260. package/test/sleep-heat.test.js +126 -126
  261. package/test/sleep-scheduler-rearm.test.js +89 -89
  262. package/test/sleep.test.js +527 -527
  263. package/test/standalone-api.test.js +751 -751
  264. package/test/store-vector-cache.test.js +98 -98
  265. package/test/store.test.js +504 -396
  266. package/test/stress.test.js +209 -209
  267. package/test/summarize-occurred-at.test.js +127 -0
  268. package/test/summarize-reasoning-effort.test.js +189 -189
  269. package/test/summarize.test.js +1639 -1465
  270. package/test/supersede-state-tracking.test.js +394 -0
  271. package/test/test-count-sync.test.js +60 -60
  272. package/test/tools-dto-schema-matrix.test.js +325 -325
  273. package/test/tools-memory-get-schema.test.js +65 -65
  274. package/test/tools.test.js +428 -374
  275. package/test/updated-at-semantics.test.js +113 -113
  276. package/test/vector-index.test.js +221 -221
  277. package/test/version-check.test.js +152 -152
  278. package/test/webServer-optional.test.js +82 -82
  279. package/test/write-admission.test.js +668 -668
@@ -1,673 +1,656 @@
1
- // Standalone HTTP API: a plain node:http server for ecosystem
2
- // integrations that live outside the DSH host and cannot reach the plugin's
3
- // internal webServer routes (/api/dsh-mneme/*). Mirrors the JSON semantics of
4
- // those routes but with mandatory Bearer-token auth on everything except
5
- // GET /health, so the store can be exposed safely on loopback.
6
- //
7
- // #181 (MCP stdio server, bin/dsh-mneme-mcp.mjs) rides on these routes as its
8
- // data plane: the six-tool surface (memory_save/search/list/get/update/delete)
9
- // is fully served here — PUT /memories/:id, the save passthrough fields
10
- // (sensitivity / occurred_at / explicit scope) and the list/search archived +
11
- // occurred-window filters exist for that parity, with tool-identical semantics.
12
- //
13
- // Security: the default bind host is 127.0.0.1. Pointing externalApiHost at a
14
- // non-loopback address exposes the whole memory store to the network — that is
15
- // the operator's explicit responsibility (documented in README).
16
- import { createServer } from "node:http";
17
- import { randomBytes, timingSafeEqual } from "node:crypto";
18
- import { TYPES } from "./store.js";
19
- import { bootstrapFromDirectory } from "./bootstrap.js";
20
- import { PACKAGE_VERSION } from "./version-check.js";
21
-
22
- const DEFAULT_PORT = 8790;
23
- const DEFAULT_HOST = "127.0.0.1";
24
- const MAX_PORT_ATTEMPTS = 20;
25
-
26
- /**
27
- * Listen with automatic EADDRINUSE recovery. Tries the configured port, then
28
- * the next MAX_PORT_ATTEMPTS-1 ports, and finally falls back to port 0 so the
29
- * OS assigns a free port. Multiple DSH profiles/instances sharing the default
30
- * port no longer leave the standalone API permanently unavailable.
31
- *
32
- * strictPort opts out of that recovery (dsh-mneme-serve daemon, #363): a
33
- * long-lived third-party integration pins the URL, so silently hopping ports
34
- * would make clients talk to nothing (or, worse, to a future different data
35
- * plane). A busy configured port is a configuration error there — fail loud.
36
- */
37
- function listenWithRetry(server, startPort, host, logger, strictPort = false) {
38
- return new Promise((resolve, reject) => {
39
- let attempt = 0;
40
- const tryListen = (port) => {
41
- const onListening = () => {
42
- server.off("error", onError);
43
- const address = server.address();
44
- resolve(address && typeof address === "object" ? address.port : port);
45
- };
46
- const onError = (error) => {
47
- server.off("listening", onListening);
48
- if (error?.code === "EADDRINUSE" && strictPort) {
49
- reject(error);
50
- return;
51
- }
52
- if (error?.code === "EADDRINUSE" && attempt < MAX_PORT_ATTEMPTS - 1) {
53
- attempt++;
54
- const next = startPort + attempt;
55
- logger?.warn?.(`[dsh-mneme] standalone API port ${port} in use, retrying ${next}`);
56
- tryListen(next);
57
- return;
58
- }
59
- if (error?.code === "EADDRINUSE") {
60
- logger?.warn?.(`[dsh-mneme] standalone API port ${port} still in use, falling back to OS-assigned port`);
61
- tryListen(0);
62
- return;
63
- }
64
- reject(error);
65
- };
66
- server.once("listening", onListening);
67
- server.once("error", onError);
68
- server.listen(port, host);
69
- };
70
- tryListen(startPort);
71
- });
72
- }
73
-
74
- function sendJson(res, status, payload) {
75
- res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
76
- res.end(JSON.stringify(payload));
77
- }
78
-
79
- /** True when the request carries the configured token. */
80
- function isAuthorized(req, apiToken) {
81
- const raw = req.headers?.authorization ?? req.headers?.["x-dsh-mneme-token"] ?? "";
82
- const token = raw.startsWith("Bearer ") ? raw.slice(7).trim() : raw.trim();
83
- if (token === "" || token.length !== apiToken.length) return false;
84
- // Constant-time comparison: no timing oracle on the token.
85
- return timingSafeEqual(Buffer.from(token), Buffer.from(apiToken));
86
- }
87
-
88
- /** Collect the request body as text (tolerant of transport errors). */
89
- function readBody(req) {
90
- return new Promise((resolve) => {
91
- let body = "";
92
- req.on("data", (chunk) => { body += chunk; });
93
- req.on("end", () => resolve(body));
94
- req.on("error", () => resolve(""));
95
- });
96
- }
97
-
98
- /**
99
- * PUT /memories/:id 的请求体处理(模块级函数便于在调用点被 try/catch 包住:
100
- * service 抛错绝不能变成未处理拒绝或悬着不回的请求)。校验与内部
101
- * /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默纠正;
102
- * content 改写按 human_override 入档;scope 修正归一化在 service 层做
103
- * (null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
104
- */
105
- async function handlePutBody(res, service, logger, id, text) {
106
- let body;
107
- try {
108
- body = JSON.parse(text || "{}");
109
- } catch {
110
- sendJson(res, 400, { error: "invalid-json" });
111
- return;
112
- }
113
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
114
- sendJson(res, 400, { error: "invalid-body" });
115
- return;
116
- }
117
- const patch = {};
118
- if (body.title !== undefined) {
119
- if (typeof body.title !== "string" || !body.title.trim()) {
120
- sendJson(res, 400, { error: "invalid-title" });
121
- return;
122
- }
123
- patch.title = body.title.trim();
124
- }
125
- if (body.content !== undefined) {
126
- if (typeof body.content !== "string" || !body.content.trim()) {
127
- sendJson(res, 400, { error: "invalid-content" });
128
- return;
129
- }
130
- patch.content = body.content.trim();
131
- }
132
- if (body.type !== undefined) {
133
- if (!TYPES.has(body.type)) {
134
- sendJson(res, 400, { error: "invalid-type" });
135
- return;
136
- }
137
- patch.type = body.type;
138
- }
139
- if (body.importance !== undefined) {
140
- if (!Number.isInteger(body.importance) || body.importance < 1 || body.importance > 5) {
141
- sendJson(res, 400, { error: "invalid-importance" });
142
- return;
143
- }
144
- patch.importance = body.importance;
145
- }
146
- if (body.tags !== undefined) {
147
- if (!Array.isArray(body.tags) || !body.tags.every((t) => typeof t === "string")) {
148
- sendJson(res, 400, { error: "invalid-tags" });
149
- return;
150
- }
151
- patch.tags = body.tags;
152
- }
153
- if (body.agent_scope !== undefined && body.agent_scope !== null && typeof body.agent_scope !== "string") {
154
- sendJson(res, 400, { error: "invalid-agent-scope" });
155
- return;
156
- }
157
- if (body.workspace_scope !== undefined && body.workspace_scope !== null && typeof body.workspace_scope !== "string") {
158
- sendJson(res, 400, { error: "invalid-workspace-scope" });
159
- return;
160
- }
161
- if (body.agent_scope !== undefined) patch.agent_scope = body.agent_scope;
162
- if (body.workspace_scope !== undefined) patch.workspace_scope = body.workspace_scope;
163
- if (body.reason !== undefined && (typeof body.reason !== "string" || !body.reason.trim())) {
164
- sendJson(res, 400, { error: "invalid-reason" });
165
- return;
166
- }
167
- if (Object.keys(patch).length === 0) {
168
- sendJson(res, 400, { error: "no-fields" });
169
- return;
170
- }
171
- const existing = service.getById(id);
172
- if (!existing) {
173
- sendJson(res, 404, { error: "not-found" });
174
- return;
175
- }
176
- if (patch.type === "document" && existing.type !== "document") {
177
- // #230 写入权分离:type 不许改入 document(铸造口唯一),干净 400。
178
- sendJson(res, 400, { error: "document-requires-register" });
179
- return;
180
- }
181
- // 内容被改写时旧版本先入档(human_override),与内部面板写路径一致。
182
- if (patch.content !== undefined && patch.content !== existing.content) {
183
- const history = Array.isArray(existing.content_history) ? existing.content_history : [];
184
- patch.content_history = [
185
- { content: existing.content ?? "", source: "human_override", updated_at: new Date().toISOString() },
186
- ...history
187
- ].slice(0, 20);
188
- }
189
- service.update(id, patch, {
190
- actor: "tool",
191
- ...(typeof body.reason === "string" && body.reason.trim() ? { query: body.reason.trim() } : {})
192
- });
193
- sendJson(res, 200, { memory: service.toApiList([service.getById(id)])[0] });
194
- }
195
-
196
- /**
197
- * /context 的查询嵌入:best-effort,embedder 接口宽容与 searchMemories 同款
198
- * (embedSingle 优先,兼容 embed-only 的 OpenAI 兼容客户端,issue #10)。
199
- * 调用方负责 catch——嵌入失败降级规则档,绝不因此 500。
200
- */
201
- async function embedQueryVector(embedder, q) {
202
- const embedSingle = typeof embedder.embedSingle === "function"
203
- ? embedder.embedSingle.bind(embedder)
204
- : typeof embedder.embed === "function"
205
- ? embedder.embed.bind(embedder)
206
- : null;
207
- if (!embedSingle) return undefined;
208
- const vector = await embedSingle(q);
209
- return Array.isArray(vector) && vector.length ? vector : undefined;
210
- }
211
-
212
- /**
213
- * /context 查询嵌入的超时护栏(CodeRabbit on #371):embedder 挂起(不抛错,
214
- * 典型如第三方 ollama/openai 端点无响应)时不能让 HTTP 连接被无限占住——超时
215
- * 按嵌入缺失处理,降级规则档。输掉的 embed promise 无法取消、自行结束后被丢弃,
216
- * 无害;挂起的主要成本是一个泄漏的挂起任务,可接受。嵌入先完成时清掉定时器
217
- * (CodeRabbit 同轮 Minor:别让每个请求都留一枚要等满超时的计时器)。
218
- */
219
- function withEmbedTimeout(promise, timeoutMs) {
220
- let timer;
221
- const timeout = new Promise((resolve) => {
222
- timer = setTimeout(() => resolve(undefined), timeoutMs);
223
- });
224
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
225
- }
226
-
227
- /**
228
- * scope 查询参数(/context 与 /search 同口径,issue #370):两参全缺 = 返回
229
- * undefined(调用方不传 scope 走各自默认,行为与既往逐字节一致);任一给出则
230
- * 缺的一维按「解析不到」(null)走 isVisibleInScope 的 fail-closed——身份不明
231
- * 的维度只见全局,不冒认,与宿主会话 scope 解析器同构。
232
- */
233
- function scopeFromSearchParams(url) {
234
- const agentScope = url.searchParams.get("agent_scope");
235
- const workspaceScope = url.searchParams.get("workspace_scope");
236
- if (agentScope === null && workspaceScope === null) return undefined;
237
- return { agent_scope: agentScope, workspace_scope: workspaceScope };
238
- }
239
-
240
- /**
241
- * Create (and start) the standalone API server.
242
- * Accepts { service, store, config, logger, settings, port, host, embedder }:
243
- * - token: persisted settings kv "external_api" wins; auto-generated
244
- * (crypto.randomBytes(24).toString("base64url")) and persisted when empty.
245
- * - port: explicit arg > persisted settings > config.externalApiPort > 8790.
246
- * - host: explicit arg > config.externalApiHost > "127.0.0.1".
247
- * - strictPort: EADDRINUSE rejects instead of hopping ports (daemon mode;
248
- * default false keeps the in-host sidecar recovery described above).
249
- * - embedder: query-embedding handle for GET /context (issue #370) — same
250
- * instance the caller handed to service.setEmbedder; null degrades /context
251
- * to the rule + BM25 tier. Best-effort: embed failures never fail the route.
252
- * - embedTimeoutMs: /context query-embed guard (default 3000) — a hung
253
- * embedder must not hold the HTTP connection; timeout degrades to the rule
254
- * tier. Factory option (like strictPort), not a user config key.
255
- * Returns { server, port, host, token, ready }: `port` is the effective bound
256
- * port (updated to the OS-assigned one after `ready` resolves when asked to
257
- * bind port 0), `ready` resolves once listening and rejects if the bind fails.
258
- */
259
- export function createStandaloneApi({ service, store, config = {}, logger, settings, port, host, maintenance, strictPort = false, embedder = null, embedTimeoutMs = 3000 }) {
260
- const persisted = settings?.getExternalApi?.() ?? {};
261
-
262
- let token = typeof persisted.token === "string" ? persisted.token : "";
263
- if (!token) {
264
- token = randomBytes(24).toString("base64url");
265
- // Persist only the token; enabled/port keys stay as they are (merge).
266
- try {
267
- settings?.setExternalApi?.({ token });
268
- } catch (error) {
269
- logger?.warn?.(`[dsh-mneme] standalone API token persistence failed: ${String(error)}`);
270
- }
271
- }
272
-
273
- // Persisted host (set from the panel) wins over the bundle config, same
274
- // precedence as port; the explicit argument still wins over both.
275
- const boundHost = host
276
- ?? (typeof persisted.host === "string" && persisted.host ? persisted.host : undefined)
277
- ?? config.externalApiHost
278
- ?? DEFAULT_HOST;
279
- const persistedPort = Number(persisted.port);
280
- const boundPort = port
281
- ?? (Number.isInteger(persistedPort) && persistedPort > 0 ? persistedPort : undefined)
282
- ?? config.externalApiPort
283
- ?? DEFAULT_PORT;
284
-
285
- const server = createServer((req, res) => {
286
- try {
287
- const url = new URL(req.url ?? "/", "http://localhost");
288
- const pathname = url.pathname;
289
-
290
- // Health is the single unauthenticated probe (monitor checks).
291
- if (req.method === "GET" && pathname === "/health") {
292
- sendJson(res, 200, { ok: true });
293
- return;
294
- }
295
-
296
- // Everything else requires the Bearer token.
297
- if (!isAuthorized(req, token)) {
298
- sendJson(res, 401, { error: "unauthorized" });
299
- return;
300
- }
301
-
302
- // --- GET /status: version + store shape + uptime -----------------------
303
- if (req.method === "GET" && pathname === "/status") {
304
- const byType = {};
305
- for (const type of TYPES) byType[type] = service.count(type);
306
- let entities = 0;
307
- try {
308
- entities = store.db.prepare("SELECT count(*) AS c FROM entities").get().c;
309
- } catch { /* entities storage unavailable → 0 */ }
310
- sendJson(res, 200, {
311
- version: PACKAGE_VERSION,
312
- memories: { total: service.count(), byType },
313
- entities,
314
- uptime_s: Math.floor(process.uptime())
315
- });
316
- return;
317
- }
318
-
319
- // --- GET /profile: user self-description -------------------------------
320
- if (req.method === "GET" && pathname === "/profile") {
321
- sendJson(res, 200, { profile: settings?.getProfile?.() ?? "" });
322
- return;
323
- }
324
-
325
- // --- GET /rules: agent behavior rules -----------------------------------
326
- if (req.method === "GET" && pathname === "/rules") {
327
- sendJson(res, 200, { rules: settings?.getRules?.() ?? [] });
328
- return;
329
- }
330
-
331
- // --- GET /memories: paged + filtered list (same semantics as the
332
- // internal /api/dsh-mneme/list) ------------------------------------
333
- if (req.method === "GET" && pathname === "/memories") {
334
- const type = url.searchParams.get("type") ?? undefined;
335
- const limit = Number(url.searchParams.get("limit") ?? 50);
336
- const offset = Number(url.searchParams.get("offset") ?? 0);
337
- const order = url.searchParams.get("order") ?? undefined;
338
- const minRaw = url.searchParams.get("minImportance");
339
- const minImportance = minRaw !== null && minRaw !== "" && !Number.isNaN(Number(minRaw))
340
- ? Number(minRaw)
341
- : undefined;
342
- const source = url.searchParams.get("source") || undefined;
343
- // include_archived + occurred 时间窗:与 memory_list 工具同口径(工具
344
- // 面六件套经 8790 全量可用,#181);缺省行为与既有调用方逐字节一致。
345
- const includeArchived = url.searchParams.get("include_archived") === "true";
346
- const occurredFrom = url.searchParams.get("occurred_from") ?? undefined;
347
- const occurredTo = url.searchParams.get("occurred_to") ?? undefined;
348
- const listFilters = { includeArchived, ...(occurredFrom ? { occurredFrom } : {}), ...(occurredTo ? { occurredTo } : {}) };
349
- const items = service.toApiList(service.list({ type, limit, offset, order, minImportance, source, ...listFilters }));
350
- // Total honors the same filters so pager math stays correct.
351
- sendJson(res, 200, { items, total: service.count(type, { minImportance, source, ...listFilters }) });
352
- return;
353
- }
354
-
355
- // --- GET/PUT/DELETE /memories/:id --------------------------------------
356
- const idMatch = pathname.match(/^\/memories\/([^/]+)$/);
357
- if (idMatch) {
358
- let id = idMatch[1];
359
- try { id = decodeURIComponent(id); } catch { /* keep raw */ }
360
- if (req.method === "GET") {
361
- const row = service.getById(id);
362
- if (!row) {
363
- sendJson(res, 404, { error: "not-found" });
364
- return;
365
- }
366
- sendJson(res, 200, service.toApiList([row])[0]);
367
- return;
368
- }
369
- if (req.method === "DELETE") {
370
- // store.remove deletes silently — precheck for a distinguishable 404.
371
- if (!service.getById(id)) {
372
- sendJson(res, 404, { error: "not-found" });
373
- return;
374
- }
375
- service.remove(id);
376
- sendJson(res, 200, { ok: true });
377
- return;
378
- }
379
- // --- PUT: field patch(memory_update 工具的外部通道,#181)。字段校验
380
- // 与内部 /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默
381
- // 纠正;content 改写按 human_override 入档;scope 修正归一化在 service
382
- // 层做(null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
383
- // 整个异步回调套 try/catch:service 抛错不能变成未处理拒绝(Node 默认
384
- // 策略下会终止宿主进程)或悬着不回的请求(外层同步 try 捕不到这里)。
385
- if (req.method === "PUT") {
386
- void readBody(req).then(async (text) => {
387
- try {
388
- await handlePutBody(res, service, logger, id, text);
389
- } catch (error) {
390
- logger?.warn?.(`[dsh-mneme] standalone API update failed: ${String(error)}`);
391
- sendJson(res, 500, { error: "internal" });
392
- }
393
- });
394
- return;
395
- }
396
- sendJson(res, 404, { error: "not-found" });
397
- return;
398
- }
399
-
400
- // --- POST /memories: save with title-dedupe (safer than raw save) ------
401
- if (req.method === "POST" && pathname === "/memories") {
402
- void readBody(req).then((text) => {
403
- let body;
404
- try {
405
- body = JSON.parse(text || "{}");
406
- } catch {
407
- sendJson(res, 400, { error: "invalid-json" });
408
- return;
409
- }
410
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
411
- sendJson(res, 400, { error: "invalid-body" });
412
- return;
413
- }
414
- // Pre-validate what store.save would throw on, so clients get a
415
- // clean 400 instead of a leaked SQLite error.
416
- if (!TYPES.has(body.type)) {
417
- sendJson(res, 400, { error: "invalid-type" });
418
- return;
419
- }
420
- if (body.type === "document") {
421
- // #230 写入权分离:document 行铸造口唯一(registerDocument)。
422
- // 这里给干净 400,不让它落进 saveWithDedupe 的守卫变 500。
423
- sendJson(res, 400, { error: "document-requires-register" });
424
- return;
425
- }
426
- if (typeof body.title !== "string" || !body.title.trim()) {
427
- sendJson(res, 400, { error: "missing-title" });
428
- return;
429
- }
430
- if (typeof body.content !== "string") {
431
- sendJson(res, 400, { error: "missing-content" });
432
- return;
433
- }
434
- if (body.tags !== undefined && !Array.isArray(body.tags)) {
435
- sendJson(res, 400, { error: "tags-must-be-an-array" });
436
- return;
437
- }
438
- // memory_save 工具的其余可选字段(#181):sensitivity / occurred_at /
439
- // 显式 scope。scope 仅收显式声明(standalone API 无会话上下文,自动
440
- // 标注无从解析,语义与工具的显式参数一致);形状不对宁 400 不静默丢。
441
- for (const key of ["sensitivity", "occurred_at", "agent_scope", "workspace_scope"]) {
442
- if (body[key] !== undefined && (typeof body[key] !== "string" || !body[key].trim())) {
443
- sendJson(res, 400, { error: `invalid-${key.replace(/_/g, "-")}` });
444
- return;
445
- }
446
- }
447
- try {
448
- const result = service.saveWithDedupe({
449
- type: body.type,
450
- title: body.title,
451
- content: body.content,
452
- importance: body.importance,
453
- tags: body.tags,
454
- source: body.source,
455
- ...(body.sensitivity !== undefined ? { sensitivity: body.sensitivity } : {}),
456
- ...(body.occurred_at !== undefined ? { occurred_at: body.occurred_at } : {}),
457
- ...(body.agent_scope !== undefined ? { agent_scope: body.agent_scope, agent_scope_source: "explicit" } : {}),
458
- ...(body.workspace_scope !== undefined ? { workspace_scope: body.workspace_scope, workspace_scope_source: "explicit" } : {})
459
- });
460
- const { action } = result;
461
- // #254 写入准入:这条 HTTP 路径今天不带会话身份,evaluate 在无 sessionKey
462
- // 时直接早退,所以拦不到;仍然显式分支——将来真接上会话身份时,落到
463
- // `toApiList([null])` 上会变成 500,把「被拒」伪装成「服务器出错」,而
464
- // 这两件事对调用方的处置完全不同(改内容 vs 重试)。
465
- if (action === "denied") {
466
- sendJson(res, 422, { error: "write-rejected", reason: result.reason });
467
- return;
468
- }
469
- const { memory } = result;
470
- // action 随行透出(created/merged):memory_save 工具语义对齐所需,
471
- // 附加键对既有消费方(CLI add 等)向后兼容。
472
- sendJson(res, action === "created" ? 201 : 200, { ...service.toApiList([memory])[0], action });
473
- } catch (error) {
474
- logger?.warn?.(`[dsh-mneme] standalone API save failed: ${String(error)}`);
475
- sendJson(res, 500, { error: "internal" });
476
- }
477
- });
478
- return;
479
- }
480
-
481
- // --- POST /maintenance/reclaim: 无损回收(#275 第一批,手动入口)-------
482
- // 默认 dry-run:只有显式 confirm:true 才真改数据。这两步都是不可逆的内容丢弃
483
- // (历史 run 的输入快照置空、归档行向量置空),所以不给「带 body 就执行」这种
484
- // 省事路径——确认必须建立在看得见的数字上。
485
- if (req.method === "POST" && pathname === "/maintenance/reclaim") {
486
- void readBody(req).then((text) => {
487
- let body;
488
- try {
489
- body = JSON.parse(text || "{}");
490
- } catch {
491
- sendJson(res, 400, { error: "invalid-json" });
492
- return;
493
- }
494
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
495
- sendJson(res, 400, { error: "invalid-body" });
496
- return;
497
- }
498
- if (!maintenance) {
499
- sendJson(res, 503, { error: "maintenance-unavailable" });
500
- return;
501
- }
502
- const dryRun = body.dryRun !== false;
503
- // 只收 JSON 数字:`Number()` 会把 ""/[]/false 都化成 0,而 0 在这里是
504
- // 「清掉全部快照」——最坏解释绝不能让一个畸形输入静默拿到。
505
- const olderThanDays = body.olderThanDays === undefined || body.olderThanDays === null
506
- ? undefined
507
- : body.olderThanDays;
508
- if (olderThanDays !== undefined && (!Number.isInteger(olderThanDays) || olderThanDays < 0)) {
509
- sendJson(res, 400, { error: "invalid-older-than-days" });
510
- return;
511
- }
512
- if (body.vacuum !== undefined && typeof body.vacuum !== "boolean") {
513
- sendJson(res, 400, { error: "invalid-vacuum" });
514
- return;
515
- }
516
- if (!dryRun && body.confirm !== true) {
517
- // 拒执行,但把 dry-run 报告一并回给调用方:确认的依据就是这份数字。报告
518
- // 必须描述**将要执行的那个动作**,所以 vacuum 原样带上——否则调用方看到
519
- // 的是「不 VACUUM」的数字,却带着 vacuum 去执行。
520
- sendJson(res, 400, {
521
- error: "confirm-required",
522
- hint: "先看 dry-run 报告,确认后带 {\"dryRun\":false,\"confirm\":true} 再发",
523
- report: maintenance.reclaim({ olderThanDays, vacuum: body.vacuum === true, dryRun: true })
524
- });
525
- return;
526
- }
527
- try {
528
- sendJson(res, 200, maintenance.reclaim({ olderThanDays, vacuum: body.vacuum === true, dryRun }));
529
- } catch (error) {
530
- logger?.warn?.(`[dsh-mneme] storage reclaim failed: ${String(error)}`);
531
- sendJson(res, 500, { error: "internal" });
532
- }
533
- });
534
- return;
535
- }
536
-
537
- // --- POST /bootstrap: cold-start memories from repo files (#220) -------
538
- // 显式收 dir(插件没有工作区根目录概念,不猜路径);确定性解析零 LLM;
539
- // 幂等骑 saveWithDedupe 的 (type, title, scope) 去重 + _overwrite 刷新。
540
- if (req.method === "POST" && pathname === "/bootstrap") {
541
- void readBody(req).then((text) => {
542
- let body;
543
- try {
544
- body = JSON.parse(text || "{}");
545
- } catch {
546
- sendJson(res, 400, { error: "invalid-json" });
547
- return;
548
- }
549
- if (body === null || typeof body !== "object" || Array.isArray(body)) {
550
- sendJson(res, 400, { error: "invalid-body" });
551
- return;
552
- }
553
- if (typeof body.dir !== "string" || !body.dir.trim()) {
554
- sendJson(res, 400, { error: "missing-dir" });
555
- return;
556
- }
557
- bootstrapFromDirectory({ service, dir: body.dir, logger })
558
- .then((summary) => sendJson(res, 200, summary))
559
- .catch((error) => {
560
- if (error?.code) {
561
- sendJson(res, 400, { error: error.code });
562
- return;
563
- }
564
- logger?.warn?.(`[dsh-mneme] standalone API bootstrap failed: ${String(error)}`);
565
- sendJson(res, 500, { error: "internal" });
566
- });
567
- });
568
- return;
569
- }
570
-
571
- // --- GET /search: unified recall pipeline (keyword + vector + BM25) ----
572
- if (req.method === "GET" && pathname === "/search") {
573
- const q = url.searchParams.get("q") ?? "";
574
- const limit = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 20);
575
- const mode = url.searchParams.get("mode") ?? "auto";
576
- const rerank = url.searchParams.get("rerank") !== "false";
577
- const occurredFrom = url.searchParams.get("occurred_from") ?? null;
578
- const occurredTo = url.searchParams.get("occurred_to") ?? null;
579
- // scope 透传(issue #370):searchMemories 本就收 scope,此前 8790 没有
580
- // 入口——第三方(daemon 桥接侧)声明身份后,A2 软加权与 strictScope 硬
581
- // 过滤才在检索面同样成立;与 /context 同口径(scopeFromSearchParams)。
582
- const scope = scopeFromSearchParams(url);
583
- const query = q.trim();
584
- if (!query) {
585
- sendJson(res, 200, { items: [], mode: "keyword" });
586
- return;
587
- }
588
- // Any vector/rerank failure degrades to keyword inside searchMemories.
589
- void Promise.resolve(
590
- service.searchMemories(query, {
591
- mode,
592
- topK: limit,
593
- useRerank: rerank,
594
- ...(scope ? { scope } : {}),
595
- ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
596
- })
597
- ).then((rows) => {
598
- const used = rows.some((m) => m.vector === true) ? "vector" : "keyword";
599
- sendJson(res, 200, { items: service.toApiList(rows), mode: used });
600
- }).catch(() => {
601
- sendJson(res, 200, { items: service.toApiList(service.search(query, { limit })), mode: "keyword" });
602
- });
603
- return;
604
- }
605
-
606
- // --- GET /context: 注入候选一站式聚合(issue #370,#363 承诺)------------
607
- // 给定话题返回「宿主此刻会注入什么」的数据等价物:injectCandidates 全语义
608
- // (优先级分层 / 编码门控 / heat / scope 软加权 / hybrid 语义路 / pin 前置,
609
- // service.js:1494)+ 画像 + 规则。结构化条目、不含渲染文本——语言 / 时间
610
- // 前缀 / 热记忆是宿主会话概念,调用方(Mneme Bridge 等网页端桥接)自行渲染。
611
- // 与宿主注入的两点差异都是 HTTP 面的有意为之:① 首次调用即走语义路(宿主
612
- // 渲染必须同步,查询向量只能异步 prefetch 给下一轮,inject.js Bug4;这里
613
- // 没有该约束);② 不做跨轮轮换(daemon 无会话状态,调用方自管)。
614
- // recall_runs 记账随 injectCandidates 内建(#217:注入是曝光型访问事件,
615
- // mode='inject' 与检索命中同表分账)——宿主注入同样记,/context 自动同口径。
616
- if (req.method === "GET" && pathname === "/context") {
617
- const q = (url.searchParams.get("q") ?? "").trim();
618
- const maxItemsRaw = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 5);
619
- const maxItems = Number.isInteger(maxItemsRaw) && maxItemsRaw > 0 ? maxItemsRaw : 5;
620
- // threshold 是 importance 阈值(injectCandidates 语义),与 /search 的
621
- // 相似度 threshold 同名不同义——文档已点名,勿混。
622
- const thresholdRaw = Number(url.searchParams.get("threshold") ?? 3);
623
- const threshold = Number.isFinite(thresholdRaw) ? thresholdRaw : 3;
624
- const scope = scopeFromSearchParams(url);
625
- void Promise.resolve(q && embedder ? withEmbedTimeout(embedQueryVector(embedder, q), embedTimeoutMs) : undefined)
626
- .catch(() => undefined) // 查询嵌入失败降级规则档(与 searchMemories 同口径)
627
- .then((queryVector) => {
628
- const pinnedStats = {};
629
- const items = service.injectCandidates({ query: q, maxItems, threshold, queryVector, scope, pinnedStats });
630
- sendJson(res, 200, {
631
- profile: (settings?.getProfile?.() ?? "").trim(),
632
- rules: settings?.getRules?.() ?? [],
633
- items: service.toApiList(items),
634
- pinnedCount: pinnedStats.shown ?? 0
635
- });
636
- })
637
- .catch(() => {
638
- sendJson(res, 500, { error: "internal" });
639
- });
640
- return;
641
- }
642
-
643
- sendJson(res, 404, { error: "not-found" });
644
- } catch {
645
- sendJson(res, 500, { error: "internal" });
646
- }
647
- });
648
-
649
- // A permanent error listener keeps an EADDRINUSE / runtime socket error from
650
- // crashing the host process; `ready` still surfaces the first bind failure.
651
- server.on("error", (error) => {
652
- logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
653
- });
654
- const ready = new Promise((resolve, reject) => {
655
- // listening handled by listenWithRetry
656
- listenWithRetry(server, boundPort, boundHost, logger, strictPort).then(resolve, reject);
657
- });
658
- // server.listen is called inside listenWithRetry
659
- ready.then(() => {
660
- const address = server.address();
661
- if (address && typeof address === "object") {
662
- logger?.info?.(`[dsh-mneme] standalone API listening on http://${address.address}:${address.port}`);
663
- }
664
- }).catch(() => { /* already logged by the error handler above */ });
665
-
666
- const api = { server, port: boundPort, host: boundHost, token, ready };
667
- // After the OS assigns the real port (bind port 0), reflect it for callers.
668
- ready.then(() => {
669
- const address = server.address();
670
- if (address && typeof address === "object") api.port = address.port;
671
- }).catch(() => { /* bind failed: port stays as configured */ });
672
- return api;
673
- }
1
+ // Standalone HTTP API: a plain node:http server for ecosystem
2
+ // integrations that live outside the DSH host and cannot reach the plugin's
3
+ // internal webServer routes (/api/dsh-mneme/*). Mirrors the JSON semantics of
4
+ // those routes but with mandatory Bearer-token auth on everything except
5
+ // GET /health, so the store can be exposed safely on loopback.
6
+ //
7
+ // #181 (MCP stdio server, bin/dsh-mneme-mcp.mjs) rides on these routes as its
8
+ // data plane: the six-tool surface (memory_save/search/list/get/update/delete)
9
+ // is fully served here — PUT /memories/:id, the save passthrough fields
10
+ // (sensitivity / occurred_at / explicit scope) and the list/search archived +
11
+ // occurred-window filters exist for that parity, with tool-identical semantics.
12
+ //
13
+ // Security: the default bind host is 127.0.0.1. Pointing externalApiHost at a
14
+ // non-loopback address exposes the whole memory store to the network — that is
15
+ // the operator's explicit responsibility (documented in README).
16
+ import { createServer } from "node:http";
17
+ import { randomBytes, timingSafeEqual } from "node:crypto";
18
+ import { TYPES } from "./store.js";
19
+ import { bootstrapFromDirectory } from "./bootstrap.js";
20
+ import { PACKAGE_VERSION } from "./version-check.js";
21
+ import { parseReclaimJson, readReclaimFields, reclaimReply, RECLAIM_UNAVAILABLE } from "./reclaim-http.js";
22
+
23
+ const DEFAULT_PORT = 8790;
24
+ const DEFAULT_HOST = "127.0.0.1";
25
+ const MAX_PORT_ATTEMPTS = 20;
26
+
27
+ /**
28
+ * Listen with automatic EADDRINUSE recovery. Tries the configured port, then
29
+ * the next MAX_PORT_ATTEMPTS-1 ports, and finally falls back to port 0 so the
30
+ * OS assigns a free port. Multiple DSH profiles/instances sharing the default
31
+ * port no longer leave the standalone API permanently unavailable.
32
+ *
33
+ * strictPort opts out of that recovery (dsh-mneme-serve daemon, #363): a
34
+ * long-lived third-party integration pins the URL, so silently hopping ports
35
+ * would make clients talk to nothing (or, worse, to a future different data
36
+ * plane). A busy configured port is a configuration error there — fail loud.
37
+ */
38
+ function listenWithRetry(server, startPort, host, logger, strictPort = false) {
39
+ return new Promise((resolve, reject) => {
40
+ let attempt = 0;
41
+ const tryListen = (port) => {
42
+ const onListening = () => {
43
+ server.off("error", onError);
44
+ const address = server.address();
45
+ resolve(address && typeof address === "object" ? address.port : port);
46
+ };
47
+ const onError = (error) => {
48
+ server.off("listening", onListening);
49
+ if (error?.code === "EADDRINUSE" && strictPort) {
50
+ reject(error);
51
+ return;
52
+ }
53
+ if (error?.code === "EADDRINUSE" && attempt < MAX_PORT_ATTEMPTS - 1) {
54
+ attempt++;
55
+ const next = startPort + attempt;
56
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} in use, retrying ${next}`);
57
+ tryListen(next);
58
+ return;
59
+ }
60
+ if (error?.code === "EADDRINUSE") {
61
+ logger?.warn?.(`[dsh-mneme] standalone API port ${port} still in use, falling back to OS-assigned port`);
62
+ tryListen(0);
63
+ return;
64
+ }
65
+ reject(error);
66
+ };
67
+ server.once("listening", onListening);
68
+ server.once("error", onError);
69
+ server.listen(port, host);
70
+ };
71
+ tryListen(startPort);
72
+ });
73
+ }
74
+
75
+ function sendJson(res, status, payload) {
76
+ res.writeHead(status, { "Content-Type": "application/json; charset=utf-8" });
77
+ res.end(JSON.stringify(payload));
78
+ }
79
+
80
+ /** True when the request carries the configured token. */
81
+ function isAuthorized(req, apiToken) {
82
+ const raw = req.headers?.authorization ?? req.headers?.["x-dsh-mneme-token"] ?? "";
83
+ const token = raw.startsWith("Bearer ") ? raw.slice(7).trim() : raw.trim();
84
+ if (token === "" || token.length !== apiToken.length) return false;
85
+ // Constant-time comparison: no timing oracle on the token.
86
+ return timingSafeEqual(Buffer.from(token), Buffer.from(apiToken));
87
+ }
88
+
89
+ /** Collect the request body as text (tolerant of transport errors). */
90
+ function readBody(req) {
91
+ return new Promise((resolve) => {
92
+ let body = "";
93
+ req.on("data", (chunk) => { body += chunk; });
94
+ req.on("end", () => resolve(body));
95
+ req.on("error", () => resolve(""));
96
+ });
97
+ }
98
+
99
+ /**
100
+ * PUT /memories/:id 的请求体处理(模块级函数便于在调用点被 try/catch 包住:
101
+ * service 抛错绝不能变成未处理拒绝或悬着不回的请求)。校验与内部
102
+ * /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默纠正;
103
+ * content 改写按 human_override 入档;scope 修正归一化在 service 层做
104
+ * (null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
105
+ */
106
+ async function handlePutBody(res, service, logger, id, text) {
107
+ let body;
108
+ try {
109
+ body = JSON.parse(text || "{}");
110
+ } catch {
111
+ sendJson(res, 400, { error: "invalid-json" });
112
+ return;
113
+ }
114
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
115
+ sendJson(res, 400, { error: "invalid-body" });
116
+ return;
117
+ }
118
+ const patch = {};
119
+ if (body.title !== undefined) {
120
+ if (typeof body.title !== "string" || !body.title.trim()) {
121
+ sendJson(res, 400, { error: "invalid-title" });
122
+ return;
123
+ }
124
+ patch.title = body.title.trim();
125
+ }
126
+ if (body.content !== undefined) {
127
+ if (typeof body.content !== "string" || !body.content.trim()) {
128
+ sendJson(res, 400, { error: "invalid-content" });
129
+ return;
130
+ }
131
+ patch.content = body.content.trim();
132
+ }
133
+ if (body.type !== undefined) {
134
+ if (!TYPES.has(body.type)) {
135
+ sendJson(res, 400, { error: "invalid-type" });
136
+ return;
137
+ }
138
+ patch.type = body.type;
139
+ }
140
+ if (body.importance !== undefined) {
141
+ if (!Number.isInteger(body.importance) || body.importance < 1 || body.importance > 5) {
142
+ sendJson(res, 400, { error: "invalid-importance" });
143
+ return;
144
+ }
145
+ patch.importance = body.importance;
146
+ }
147
+ if (body.tags !== undefined) {
148
+ if (!Array.isArray(body.tags) || !body.tags.every((t) => typeof t === "string")) {
149
+ sendJson(res, 400, { error: "invalid-tags" });
150
+ return;
151
+ }
152
+ patch.tags = body.tags;
153
+ }
154
+ if (body.agent_scope !== undefined && body.agent_scope !== null && typeof body.agent_scope !== "string") {
155
+ sendJson(res, 400, { error: "invalid-agent-scope" });
156
+ return;
157
+ }
158
+ if (body.workspace_scope !== undefined && body.workspace_scope !== null && typeof body.workspace_scope !== "string") {
159
+ sendJson(res, 400, { error: "invalid-workspace-scope" });
160
+ return;
161
+ }
162
+ if (body.agent_scope !== undefined) patch.agent_scope = body.agent_scope;
163
+ if (body.workspace_scope !== undefined) patch.workspace_scope = body.workspace_scope;
164
+ if (body.reason !== undefined && (typeof body.reason !== "string" || !body.reason.trim())) {
165
+ sendJson(res, 400, { error: "invalid-reason" });
166
+ return;
167
+ }
168
+ if (Object.keys(patch).length === 0) {
169
+ sendJson(res, 400, { error: "no-fields" });
170
+ return;
171
+ }
172
+ const existing = service.getById(id);
173
+ if (!existing) {
174
+ sendJson(res, 404, { error: "not-found" });
175
+ return;
176
+ }
177
+ if (patch.type === "document" && existing.type !== "document") {
178
+ // #230 写入权分离:type 不许改入 document(铸造口唯一),干净 400。
179
+ sendJson(res, 400, { error: "document-requires-register" });
180
+ return;
181
+ }
182
+ // 内容被改写时旧版本先入档(human_override),与内部面板写路径一致。
183
+ if (patch.content !== undefined && patch.content !== existing.content) {
184
+ const history = Array.isArray(existing.content_history) ? existing.content_history : [];
185
+ patch.content_history = [
186
+ { content: existing.content ?? "", source: "human_override", updated_at: new Date().toISOString() },
187
+ ...history
188
+ ].slice(0, 20);
189
+ }
190
+ service.update(id, patch, {
191
+ actor: "tool",
192
+ ...(typeof body.reason === "string" && body.reason.trim() ? { query: body.reason.trim() } : {})
193
+ });
194
+ sendJson(res, 200, { memory: service.toApiList([service.getById(id)])[0] });
195
+ }
196
+
197
+ /**
198
+ * /context 的查询嵌入:best-effort,embedder 接口宽容与 searchMemories 同款
199
+ * (embedSingle 优先,兼容 embed-only 的 OpenAI 兼容客户端,issue #10)。
200
+ * 调用方负责 catch——嵌入失败降级规则档,绝不因此 500。
201
+ */
202
+ async function embedQueryVector(embedder, q) {
203
+ const embedSingle = typeof embedder.embedSingle === "function"
204
+ ? embedder.embedSingle.bind(embedder)
205
+ : typeof embedder.embed === "function"
206
+ ? embedder.embed.bind(embedder)
207
+ : null;
208
+ if (!embedSingle) return undefined;
209
+ const vector = await embedSingle(q);
210
+ return Array.isArray(vector) && vector.length ? vector : undefined;
211
+ }
212
+
213
+ /**
214
+ * /context 查询嵌入的超时护栏(CodeRabbit on #371):embedder 挂起(不抛错,
215
+ * 典型如第三方 ollama/openai 端点无响应)时不能让 HTTP 连接被无限占住——超时
216
+ * 按嵌入缺失处理,降级规则档。输掉的 embed promise 无法取消、自行结束后被丢弃,
217
+ * 无害;挂起的主要成本是一个泄漏的挂起任务,可接受。嵌入先完成时清掉定时器
218
+ * (CodeRabbit 同轮 Minor:别让每个请求都留一枚要等满超时的计时器)。
219
+ */
220
+ function withEmbedTimeout(promise, timeoutMs) {
221
+ let timer;
222
+ const timeout = new Promise((resolve) => {
223
+ timer = setTimeout(() => resolve(undefined), timeoutMs);
224
+ });
225
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
226
+ }
227
+
228
+ /**
229
+ * scope 查询参数(/context 与 /search 同口径,issue #370):两参全缺 = 返回
230
+ * undefined(调用方不传 scope 走各自默认,行为与既往逐字节一致);任一给出则
231
+ * 缺的一维按「解析不到」(null)走 isVisibleInScope 的 fail-closed——身份不明
232
+ * 的维度只见全局,不冒认,与宿主会话 scope 解析器同构。
233
+ */
234
+ function scopeFromSearchParams(url) {
235
+ const agentScope = url.searchParams.get("agent_scope");
236
+ const workspaceScope = url.searchParams.get("workspace_scope");
237
+ if (agentScope === null && workspaceScope === null) return undefined;
238
+ return { agent_scope: agentScope, workspace_scope: workspaceScope };
239
+ }
240
+
241
+ /**
242
+ * Create (and start) the standalone API server.
243
+ * Accepts { service, store, config, logger, settings, port, host, embedder }:
244
+ * - token: persisted settings kv "external_api" wins; auto-generated
245
+ * (crypto.randomBytes(24).toString("base64url")) and persisted when empty.
246
+ * - port: explicit arg > persisted settings > config.externalApiPort > 8790.
247
+ * - host: explicit arg > config.externalApiHost > "127.0.0.1".
248
+ * - strictPort: EADDRINUSE rejects instead of hopping ports (daemon mode;
249
+ * default false keeps the in-host sidecar recovery described above).
250
+ * - embedder: query-embedding handle for GET /context (issue #370) — same
251
+ * instance the caller handed to service.setEmbedder; null degrades /context
252
+ * to the rule + BM25 tier. Best-effort: embed failures never fail the route.
253
+ * - embedTimeoutMs: /context query-embed guard (default 3000) — a hung
254
+ * embedder must not hold the HTTP connection; timeout degrades to the rule
255
+ * tier. Factory option (like strictPort), not a user config key.
256
+ * Returns { server, port, host, token, ready }: `port` is the effective bound
257
+ * port (updated to the OS-assigned one after `ready` resolves when asked to
258
+ * bind port 0), `ready` resolves once listening and rejects if the bind fails.
259
+ */
260
+ export function createStandaloneApi({ service, store, config = {}, logger, settings, port, host, maintenance, strictPort = false, embedder = null, embedTimeoutMs = 3000 }) {
261
+ const persisted = settings?.getExternalApi?.() ?? {};
262
+
263
+ let token = typeof persisted.token === "string" ? persisted.token : "";
264
+ if (!token) {
265
+ token = randomBytes(24).toString("base64url");
266
+ // Persist only the token; enabled/port keys stay as they are (merge).
267
+ try {
268
+ settings?.setExternalApi?.({ token });
269
+ } catch (error) {
270
+ logger?.warn?.(`[dsh-mneme] standalone API token persistence failed: ${String(error)}`);
271
+ }
272
+ }
273
+
274
+ // Persisted host (set from the panel) wins over the bundle config, same
275
+ // precedence as port; the explicit argument still wins over both.
276
+ const boundHost = host
277
+ ?? (typeof persisted.host === "string" && persisted.host ? persisted.host : undefined)
278
+ ?? config.externalApiHost
279
+ ?? DEFAULT_HOST;
280
+ const persistedPort = Number(persisted.port);
281
+ const boundPort = port
282
+ ?? (Number.isInteger(persistedPort) && persistedPort > 0 ? persistedPort : undefined)
283
+ ?? config.externalApiPort
284
+ ?? DEFAULT_PORT;
285
+
286
+ const server = createServer((req, res) => {
287
+ try {
288
+ const url = new URL(req.url ?? "/", "http://localhost");
289
+ const pathname = url.pathname;
290
+
291
+ // Health is the single unauthenticated probe (monitor checks).
292
+ if (req.method === "GET" && pathname === "/health") {
293
+ sendJson(res, 200, { ok: true });
294
+ return;
295
+ }
296
+
297
+ // Everything else requires the Bearer token.
298
+ if (!isAuthorized(req, token)) {
299
+ sendJson(res, 401, { error: "unauthorized" });
300
+ return;
301
+ }
302
+
303
+ // --- GET /status: version + store shape + uptime -----------------------
304
+ if (req.method === "GET" && pathname === "/status") {
305
+ const byType = {};
306
+ for (const type of TYPES) byType[type] = service.count(type);
307
+ let entities = 0;
308
+ try {
309
+ entities = store.db.prepare("SELECT count(*) AS c FROM entities").get().c;
310
+ } catch { /* entities storage unavailable → 0 */ }
311
+ sendJson(res, 200, {
312
+ version: PACKAGE_VERSION,
313
+ memories: { total: service.count(), byType },
314
+ entities,
315
+ uptime_s: Math.floor(process.uptime())
316
+ });
317
+ return;
318
+ }
319
+
320
+ // --- GET /profile: user self-description -------------------------------
321
+ if (req.method === "GET" && pathname === "/profile") {
322
+ sendJson(res, 200, { profile: settings?.getProfile?.() ?? "" });
323
+ return;
324
+ }
325
+
326
+ // --- GET /rules: agent behavior rules -----------------------------------
327
+ if (req.method === "GET" && pathname === "/rules") {
328
+ sendJson(res, 200, { rules: settings?.getRules?.() ?? [] });
329
+ return;
330
+ }
331
+
332
+ // --- GET /memories: paged + filtered list (same semantics as the
333
+ // internal /api/dsh-mneme/list) ------------------------------------
334
+ if (req.method === "GET" && pathname === "/memories") {
335
+ const type = url.searchParams.get("type") ?? undefined;
336
+ const limit = Number(url.searchParams.get("limit") ?? 50);
337
+ const offset = Number(url.searchParams.get("offset") ?? 0);
338
+ const order = url.searchParams.get("order") ?? undefined;
339
+ const minRaw = url.searchParams.get("minImportance");
340
+ const minImportance = minRaw !== null && minRaw !== "" && !Number.isNaN(Number(minRaw))
341
+ ? Number(minRaw)
342
+ : undefined;
343
+ const source = url.searchParams.get("source") || undefined;
344
+ // include_archived + occurred 时间窗:与 memory_list 工具同口径(工具
345
+ // 面六件套经 8790 全量可用,#181);缺省行为与既有调用方逐字节一致。
346
+ const includeArchived = url.searchParams.get("include_archived") === "true";
347
+ const occurredFrom = url.searchParams.get("occurred_from") ?? undefined;
348
+ const occurredTo = url.searchParams.get("occurred_to") ?? undefined;
349
+ const listFilters = { includeArchived, ...(occurredFrom ? { occurredFrom } : {}), ...(occurredTo ? { occurredTo } : {}) };
350
+ const items = service.toApiList(service.list({ type, limit, offset, order, minImportance, source, ...listFilters }));
351
+ // Total honors the same filters so pager math stays correct.
352
+ sendJson(res, 200, { items, total: service.count(type, { minImportance, source, ...listFilters }) });
353
+ return;
354
+ }
355
+
356
+ // --- GET/PUT/DELETE /memories/:id --------------------------------------
357
+ const idMatch = pathname.match(/^\/memories\/([^/]+)$/);
358
+ if (idMatch) {
359
+ let id = idMatch[1];
360
+ try { id = decodeURIComponent(id); } catch { /* keep raw */ }
361
+ if (req.method === "GET") {
362
+ const row = service.getById(id);
363
+ if (!row) {
364
+ sendJson(res, 404, { error: "not-found" });
365
+ return;
366
+ }
367
+ sendJson(res, 200, service.toApiList([row])[0]);
368
+ return;
369
+ }
370
+ if (req.method === "DELETE") {
371
+ // store.remove deletes silently — precheck for a distinguishable 404.
372
+ if (!service.getById(id)) {
373
+ sendJson(res, 404, { error: "not-found" });
374
+ return;
375
+ }
376
+ service.remove(id);
377
+ sendJson(res, 200, { ok: true });
378
+ return;
379
+ }
380
+ // --- PUT: field patch(memory_update 工具的外部通道,#181)。字段校验
381
+ // 与内部 /api/dsh-mneme/update 同风格:字段出现就必须合法,宁 400 不静默
382
+ // 纠正;content 改写按 human_override 入档;scope 修正归一化在 service
383
+ // 层做(null=放宽到全局,字符串=收窄/改标),审计 actor 记 "tool"。
384
+ // 整个异步回调套 try/catch:service 抛错不能变成未处理拒绝(Node 默认
385
+ // 策略下会终止宿主进程)或悬着不回的请求(外层同步 try 捕不到这里)。
386
+ if (req.method === "PUT") {
387
+ void readBody(req).then(async (text) => {
388
+ try {
389
+ await handlePutBody(res, service, logger, id, text);
390
+ } catch (error) {
391
+ logger?.warn?.(`[dsh-mneme] standalone API update failed: ${String(error)}`);
392
+ sendJson(res, 500, { error: "internal" });
393
+ }
394
+ });
395
+ return;
396
+ }
397
+ sendJson(res, 404, { error: "not-found" });
398
+ return;
399
+ }
400
+
401
+ // --- POST /memories: save with title-dedupe (safer than raw save) ------
402
+ if (req.method === "POST" && pathname === "/memories") {
403
+ void readBody(req).then((text) => {
404
+ let body;
405
+ try {
406
+ body = JSON.parse(text || "{}");
407
+ } catch {
408
+ sendJson(res, 400, { error: "invalid-json" });
409
+ return;
410
+ }
411
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
412
+ sendJson(res, 400, { error: "invalid-body" });
413
+ return;
414
+ }
415
+ // Pre-validate what store.save would throw on, so clients get a
416
+ // clean 400 instead of a leaked SQLite error.
417
+ if (!TYPES.has(body.type)) {
418
+ sendJson(res, 400, { error: "invalid-type" });
419
+ return;
420
+ }
421
+ if (body.type === "document") {
422
+ // #230 写入权分离:document 行铸造口唯一(registerDocument)。
423
+ // 这里给干净 400,不让它落进 saveWithDedupe 的守卫变 500。
424
+ sendJson(res, 400, { error: "document-requires-register" });
425
+ return;
426
+ }
427
+ if (typeof body.title !== "string" || !body.title.trim()) {
428
+ sendJson(res, 400, { error: "missing-title" });
429
+ return;
430
+ }
431
+ if (typeof body.content !== "string") {
432
+ sendJson(res, 400, { error: "missing-content" });
433
+ return;
434
+ }
435
+ if (body.tags !== undefined && !Array.isArray(body.tags)) {
436
+ sendJson(res, 400, { error: "tags-must-be-an-array" });
437
+ return;
438
+ }
439
+ // memory_save 工具的其余可选字段(#181):sensitivity / occurred_at /
440
+ // 显式 scope。scope 仅收显式声明(standalone API 无会话上下文,自动
441
+ // 标注无从解析,语义与工具的显式参数一致);形状不对宁 400 不静默丢。
442
+ for (const key of ["sensitivity", "occurred_at", "agent_scope", "workspace_scope"]) {
443
+ if (body[key] !== undefined && (typeof body[key] !== "string" || !body[key].trim())) {
444
+ sendJson(res, 400, { error: `invalid-${key.replace(/_/g, "-")}` });
445
+ return;
446
+ }
447
+ }
448
+ try {
449
+ const result = service.saveWithDedupe({
450
+ type: body.type,
451
+ title: body.title,
452
+ content: body.content,
453
+ importance: body.importance,
454
+ tags: body.tags,
455
+ source: body.source,
456
+ ...(body.sensitivity !== undefined ? { sensitivity: body.sensitivity } : {}),
457
+ ...(body.occurred_at !== undefined ? { occurred_at: body.occurred_at } : {}),
458
+ ...(body.agent_scope !== undefined ? { agent_scope: body.agent_scope, agent_scope_source: "explicit" } : {}),
459
+ ...(body.workspace_scope !== undefined ? { workspace_scope: body.workspace_scope, workspace_scope_source: "explicit" } : {})
460
+ });
461
+ const { action } = result;
462
+ // #254 写入准入:这条 HTTP 路径今天不带会话身份,evaluate 在无 sessionKey
463
+ // 时直接早退,所以拦不到;仍然显式分支——将来真接上会话身份时,落到
464
+ // `toApiList([null])` 上会变成 500,把「被拒」伪装成「服务器出错」,而
465
+ // 这两件事对调用方的处置完全不同(改内容 vs 重试)。
466
+ if (action === "denied") {
467
+ sendJson(res, 422, { error: "write-rejected", reason: result.reason });
468
+ return;
469
+ }
470
+ const { memory } = result;
471
+ // action 随行透出(created/merged):memory_save 工具语义对齐所需,
472
+ // 附加键对既有消费方(CLI add 等)向后兼容。
473
+ sendJson(res, action === "created" ? 201 : 200, { ...service.toApiList([memory])[0], action });
474
+ } catch (error) {
475
+ logger?.warn?.(`[dsh-mneme] standalone API save failed: ${String(error)}`);
476
+ sendJson(res, 500, { error: "internal" });
477
+ }
478
+ });
479
+ return;
480
+ }
481
+
482
+ // --- POST /maintenance/reclaim: 无损回收(#275 第一批,手动入口)-------
483
+ // 默认 dry-run:只有显式 confirm:true 才真改数据。这两步都是不可逆的内容丢弃
484
+ // (历史 run 的输入快照置空、归档行向量置空),所以不给「带 body 就执行」这种
485
+ // 省事路径——确认必须建立在看得见的数字上。
486
+ //
487
+ // 口径(错误码字符串、默认值、报告形状)不在这里写:与宿主内的面板路由
488
+ // /api/dsh-mneme/maintenance/reclaim 共用 src/reclaim-http.js,两张皮只有鉴权
489
+ // 与路径不同。这条曾经是整段复制的,于是面板侧修好之后这边还停在旧形态(#411)。
490
+ if (req.method === "POST" && pathname === "/maintenance/reclaim") {
491
+ void readBody(req).then((text) => {
492
+ const parsed = parseReclaimJson(text);
493
+ if (!parsed.ok) {
494
+ sendJson(res, 400, { error: parsed.error });
495
+ return;
496
+ }
497
+ // 顺序敏感:端点整个没接线时报「窗口不合法」是误导,503 必须赢过字段校验。
498
+ if (!maintenance) {
499
+ sendJson(res, 503, { error: RECLAIM_UNAVAILABLE });
500
+ return;
501
+ }
502
+ const fields = readReclaimFields(parsed.body);
503
+ if (!fields.ok) {
504
+ sendJson(res, 400, { error: fields.error });
505
+ return;
506
+ }
507
+ const { status, body } = reclaimReply({
508
+ maintenance,
509
+ dryRun: fields.dryRun,
510
+ olderThanDays: fields.olderThanDays,
511
+ vacuum: fields.vacuum,
512
+ confirm: fields.confirm,
513
+ warn: (msg) => logger?.warn?.(msg)
514
+ });
515
+ sendJson(res, status, body);
516
+ });
517
+ return;
518
+ }
519
+
520
+ // --- POST /bootstrap: cold-start memories from repo files (#220) -------
521
+ // 显式收 dir(插件没有工作区根目录概念,不猜路径);确定性解析零 LLM;
522
+ // 幂等骑 saveWithDedupe 的 (type, title, scope) 去重 + _overwrite 刷新。
523
+ if (req.method === "POST" && pathname === "/bootstrap") {
524
+ void readBody(req).then((text) => {
525
+ let body;
526
+ try {
527
+ body = JSON.parse(text || "{}");
528
+ } catch {
529
+ sendJson(res, 400, { error: "invalid-json" });
530
+ return;
531
+ }
532
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
533
+ sendJson(res, 400, { error: "invalid-body" });
534
+ return;
535
+ }
536
+ if (typeof body.dir !== "string" || !body.dir.trim()) {
537
+ sendJson(res, 400, { error: "missing-dir" });
538
+ return;
539
+ }
540
+ bootstrapFromDirectory({ service, dir: body.dir, logger })
541
+ .then((summary) => sendJson(res, 200, summary))
542
+ .catch((error) => {
543
+ if (error?.code) {
544
+ sendJson(res, 400, { error: error.code });
545
+ return;
546
+ }
547
+ logger?.warn?.(`[dsh-mneme] standalone API bootstrap failed: ${String(error)}`);
548
+ sendJson(res, 500, { error: "internal" });
549
+ });
550
+ });
551
+ return;
552
+ }
553
+
554
+ // --- GET /search: unified recall pipeline (keyword + vector + BM25) ----
555
+ if (req.method === "GET" && pathname === "/search") {
556
+ const q = url.searchParams.get("q") ?? "";
557
+ const limit = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 20);
558
+ const mode = url.searchParams.get("mode") ?? "auto";
559
+ const rerank = url.searchParams.get("rerank") !== "false";
560
+ const occurredFrom = url.searchParams.get("occurred_from") ?? null;
561
+ const occurredTo = url.searchParams.get("occurred_to") ?? null;
562
+ // scope 透传(issue #370):searchMemories 本就收 scope,此前 8790 没有
563
+ // 入口——第三方(daemon 桥接侧)声明身份后,A2 软加权与 strictScope 硬
564
+ // 过滤才在检索面同样成立;与 /context 同口径(scopeFromSearchParams)。
565
+ const scope = scopeFromSearchParams(url);
566
+ const query = q.trim();
567
+ if (!query) {
568
+ sendJson(res, 200, { items: [], mode: "keyword" });
569
+ return;
570
+ }
571
+ // Any vector/rerank failure degrades to keyword inside searchMemories.
572
+ void Promise.resolve(
573
+ service.searchMemories(query, {
574
+ mode,
575
+ topK: limit,
576
+ useRerank: rerank,
577
+ ...(scope ? { scope } : {}),
578
+ ...(occurredFrom !== null || occurredTo !== null ? { occurredFrom, occurredTo } : {})
579
+ })
580
+ ).then((rows) => {
581
+ const used = rows.some((m) => m.vector === true) ? "vector" : "keyword";
582
+ sendJson(res, 200, { items: service.toApiList(rows), mode: used });
583
+ }).catch(() => {
584
+ sendJson(res, 200, { items: service.toApiList(service.search(query, { limit })), mode: "keyword" });
585
+ });
586
+ return;
587
+ }
588
+
589
+ // --- GET /context: 注入候选一站式聚合(issue #370,#363 承诺)------------
590
+ // 给定话题返回「宿主此刻会注入什么」的数据等价物:injectCandidates 全语义
591
+ // (优先级分层 / 编码门控 / heat / scope 软加权 / hybrid 语义路 / pin 前置,
592
+ // service.js:1494)+ 画像 + 规则。结构化条目、不含渲染文本——语言 / 时间
593
+ // 前缀 / 热记忆是宿主会话概念,调用方(Mneme Bridge 等网页端桥接)自行渲染。
594
+ // 与宿主注入的两点差异都是 HTTP 面的有意为之:① 首次调用即走语义路(宿主
595
+ // 渲染必须同步,查询向量只能异步 prefetch 给下一轮,inject.js Bug4;这里
596
+ // 没有该约束);② 不做跨轮轮换(daemon 无会话状态,调用方自管)。
597
+ // recall_runs 记账随 injectCandidates 内建(#217:注入是曝光型访问事件,
598
+ // mode='inject' 与检索命中同表分账)——宿主注入同样记,/context 自动同口径。
599
+ if (req.method === "GET" && pathname === "/context") {
600
+ const q = (url.searchParams.get("q") ?? "").trim();
601
+ const maxItemsRaw = Number(url.searchParams.get("topK") ?? url.searchParams.get("limit") ?? 5);
602
+ const maxItems = Number.isInteger(maxItemsRaw) && maxItemsRaw > 0 ? maxItemsRaw : 5;
603
+ // threshold 是 importance 阈值(injectCandidates 语义),与 /search 的
604
+ // 相似度 threshold 同名不同义——文档已点名,勿混。
605
+ const thresholdRaw = Number(url.searchParams.get("threshold") ?? 3);
606
+ const threshold = Number.isFinite(thresholdRaw) ? thresholdRaw : 3;
607
+ const scope = scopeFromSearchParams(url);
608
+ void Promise.resolve(q && embedder ? withEmbedTimeout(embedQueryVector(embedder, q), embedTimeoutMs) : undefined)
609
+ .catch(() => undefined) // 查询嵌入失败降级规则档(与 searchMemories 同口径)
610
+ .then((queryVector) => {
611
+ const pinnedStats = {};
612
+ const items = service.injectCandidates({ query: q, maxItems, threshold, queryVector, scope, pinnedStats });
613
+ sendJson(res, 200, {
614
+ profile: (settings?.getProfile?.() ?? "").trim(),
615
+ rules: settings?.getRules?.() ?? [],
616
+ items: service.toApiList(items),
617
+ pinnedCount: pinnedStats.shown ?? 0
618
+ });
619
+ })
620
+ .catch(() => {
621
+ sendJson(res, 500, { error: "internal" });
622
+ });
623
+ return;
624
+ }
625
+
626
+ sendJson(res, 404, { error: "not-found" });
627
+ } catch {
628
+ sendJson(res, 500, { error: "internal" });
629
+ }
630
+ });
631
+
632
+ // A permanent error listener keeps an EADDRINUSE / runtime socket error from
633
+ // crashing the host process; `ready` still surfaces the first bind failure.
634
+ server.on("error", (error) => {
635
+ logger?.warn?.(`[dsh-mneme] standalone API error: ${String(error)}`);
636
+ });
637
+ const ready = new Promise((resolve, reject) => {
638
+ // listening handled by listenWithRetry
639
+ listenWithRetry(server, boundPort, boundHost, logger, strictPort).then(resolve, reject);
640
+ });
641
+ // server.listen is called inside listenWithRetry
642
+ ready.then(() => {
643
+ const address = server.address();
644
+ if (address && typeof address === "object") {
645
+ logger?.info?.(`[dsh-mneme] standalone API listening on http://${address.address}:${address.port}`);
646
+ }
647
+ }).catch(() => { /* already logged by the error handler above */ });
648
+
649
+ const api = { server, port: boundPort, host: boundHost, token, ready };
650
+ // After the OS assigns the real port (bind port 0), reflect it for callers.
651
+ ready.then(() => {
652
+ const address = server.address();
653
+ if (address && typeof address === "object") api.port = address.port;
654
+ }).catch(() => { /* bind failed: port stays as configured */ });
655
+ return api;
656
+ }