@modusensus/dsh-mneme 0.8.14 → 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 -654
  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 -151
  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 -673
  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 -843
  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 -503
  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 -229
  63. package/lib/sensitive-scan.js +209 -209
  64. package/lib/serve.js +215 -215
  65. package/lib/service.js +2663 -2605
  66. package/lib/settings.js +517 -511
  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 +118 -118
  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 -36
  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 -673
  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 -843
  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 -503
  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 -229
  135. package/src/sensitive-scan.js +209 -209
  136. package/src/serve.js +215 -215
  137. package/src/service.js +2663 -2605
  138. package/src/settings.js +517 -511
  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 -1690
  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 -60
  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 -77
  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 -367
  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 -121
  246. package/test/serve.test.js +196 -196
  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 -751
  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,673 +1,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
-
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
+
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
+ }