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

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 (543) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +830 -830
  3. package/assets/icon.svg +3 -3
  4. package/bin/cli.mjs +964 -964
  5. package/bin/dsh-mneme-choro.mjs +262 -262
  6. package/bin/dsh-mneme-mcp.mjs +510 -510
  7. package/bin/dsh-mneme-serve.mjs +151 -151
  8. package/cordis.patch.yml +21 -21
  9. package/docs/CONFIGURATION.md +407 -404
  10. package/docs/CONTINUITY.md +139 -139
  11. package/docs/DAEMON.md +57 -57
  12. package/docs/DIRECTORIES.md +114 -114
  13. package/docs/DISTILL.md +397 -371
  14. package/docs/DSH-GO.md +97 -97
  15. package/docs/ENTITIES.md +247 -247
  16. package/docs/FORGET.md +77 -77
  17. package/docs/KB.md +110 -110
  18. package/docs/LOCAL_MODEL.md +222 -222
  19. package/docs/SEMANTIC.md +256 -256
  20. package/docs/SHARE.md +552 -552
  21. package/docs/SLEEP.md +202 -202
  22. package/docs/STORAGE.md +122 -122
  23. package/docs/WORKFLOWS.md +366 -366
  24. package/lib/api-standalone.js +1007 -1007
  25. package/lib/api.js +3600 -3600
  26. package/lib/attachment-text.js +122 -122
  27. package/lib/bootstrap-http.js +105 -105
  28. package/lib/bootstrap.js +215 -215
  29. package/lib/candidates.js +454 -454
  30. package/lib/capabilities.js +819 -819
  31. package/lib/choro-command.js +111 -111
  32. package/lib/client.js +14420 -14322
  33. package/lib/commands.js +95 -95
  34. package/lib/config-keys.js +144 -144
  35. package/lib/config.js +1361 -1344
  36. package/lib/content-hash.js +54 -54
  37. package/lib/continuity.js +258 -258
  38. package/lib/date-hint.js +32 -0
  39. package/lib/diary/auto.js +190 -190
  40. package/lib/diary/compose.js +440 -440
  41. package/lib/diary/dir.js +59 -59
  42. package/lib/diary/export.js +97 -97
  43. package/lib/diary/index.js +26 -26
  44. package/lib/diary/library.js +189 -189
  45. package/lib/diary/qq-inbox.js +142 -142
  46. package/lib/diary/rollover.js +61 -61
  47. package/lib/diary/session-provider.js +122 -122
  48. package/lib/document-index.js +94 -94
  49. package/lib/document.js +322 -322
  50. package/lib/dream/clustering.js +123 -123
  51. package/lib/dream/decisions.js +945 -945
  52. package/lib/dream/narratives.js +44 -44
  53. package/lib/dream/sleep.js +2027 -2027
  54. package/lib/dream/triage.js +139 -139
  55. package/lib/dream.js +1879 -1879
  56. package/lib/dsh-go/host.js +162 -162
  57. package/lib/dsh-go/panel.js +2091 -2091
  58. package/lib/dsh-go/text.js +342 -342
  59. package/lib/dsh-go/views/common.js +68 -68
  60. package/lib/dsh-go/views/entity.js +48 -48
  61. package/lib/dsh-go/views/memory.js +198 -198
  62. package/lib/dsh-go/views/root.js +30 -30
  63. package/lib/dsh-go/views/settings.js +398 -398
  64. package/lib/dsh-go/views/status.js +51 -51
  65. package/lib/embedding.js +342 -342
  66. package/lib/entities/extractor.js +285 -285
  67. package/lib/fence.js +24 -24
  68. package/lib/graph/anchoring.js +184 -184
  69. package/lib/guide.js +74 -74
  70. package/lib/heat.js +144 -144
  71. package/lib/hot-memory.js +119 -119
  72. package/lib/image-describe.js +158 -0
  73. package/lib/index.js +852 -852
  74. package/lib/inject.js +656 -651
  75. package/lib/kb/index.js +309 -309
  76. package/lib/kb/routes.js +219 -219
  77. package/lib/kb/tools.js +148 -148
  78. package/lib/lang.js +607 -595
  79. package/lib/local-embedder.js +358 -358
  80. package/lib/maintenance.js +162 -162
  81. package/lib/memory-source.js +9 -9
  82. package/lib/mirror.js +330 -330
  83. package/lib/organize.js +456 -456
  84. package/lib/peak-hours.js +172 -172
  85. package/lib/pipeline-activities.js +178 -178
  86. package/lib/pipeline-attribution.js +165 -165
  87. package/lib/pipeline-command.js +279 -279
  88. package/lib/pipeline-confirm.js +142 -142
  89. package/lib/pipeline-exec.js +174 -174
  90. package/lib/pipeline-nudge-auto.js +129 -129
  91. package/lib/pipeline-nudge.js +1623 -1623
  92. package/lib/pipeline-observations.js +181 -181
  93. package/lib/pipeline-observe.js +133 -133
  94. package/lib/pipeline-runner.js +361 -361
  95. package/lib/pipeline-runs.js +442 -442
  96. package/lib/pipeline.js +716 -716
  97. package/lib/placement.js +13 -13
  98. package/lib/pre-inject-gate.js +354 -354
  99. package/lib/profile-extract.js +164 -164
  100. package/lib/profile-facts.js +356 -356
  101. package/lib/provenance-http.js +251 -251
  102. package/lib/quality-filter.js +162 -162
  103. package/lib/recall-stats.js +190 -190
  104. package/lib/reclaim-http.js +150 -150
  105. package/lib/reranker.js +269 -269
  106. package/lib/runtime/adopt.js +176 -176
  107. package/lib/runtime/closure.js +172 -172
  108. package/lib/runtime/download.js +247 -247
  109. package/lib/runtime/layout.js +265 -265
  110. package/lib/runtime/loader.js +252 -252
  111. package/lib/runtime/model-fetch.js +361 -361
  112. package/lib/runtime/provision.js +237 -237
  113. package/lib/runtime/tarball.js +130 -130
  114. package/lib/runtime/verify.js +223 -223
  115. package/lib/safe-slice.js +18 -18
  116. package/lib/scope-state.js +277 -277
  117. package/lib/scope.js +187 -187
  118. package/lib/search/adaptive.js +60 -60
  119. package/lib/search/bm25.js +96 -96
  120. package/lib/semantic.js +572 -572
  121. package/lib/sensitive-scan.js +209 -209
  122. package/lib/serve.js +228 -228
  123. package/lib/service.js +3268 -3268
  124. package/lib/session-gate.js +91 -91
  125. package/lib/session-usage.js +350 -350
  126. package/lib/settings.js +827 -817
  127. package/lib/share-http.js +281 -281
  128. package/lib/share-import.js +234 -234
  129. package/lib/share.js +335 -335
  130. package/lib/store.js +5895 -5895
  131. package/lib/summarize.js +1388 -1343
  132. package/lib/tools.js +1370 -1356
  133. package/lib/user-settings.js +230 -230
  134. package/lib/vector-index.js +180 -180
  135. package/lib/version-check.js +122 -122
  136. package/lib/wiki/claims.js +267 -267
  137. package/lib/wiki/cli-hint.js +90 -90
  138. package/lib/wiki/inject.js +164 -164
  139. package/lib/wiki/partition.js +200 -200
  140. package/lib/wiki/plan.js +214 -214
  141. package/lib/wiki/queries.js +640 -640
  142. package/lib/wiki/render.js +261 -261
  143. package/lib/wiki/scan.js +371 -371
  144. package/lib/wiki/t0.js +500 -500
  145. package/lib/wiki/t1-jobs.js +232 -232
  146. package/lib/wiki/t1.js +609 -609
  147. package/lib/write-admission.js +404 -404
  148. package/locale/en.json +6 -6
  149. package/locale/zh.json +6 -6
  150. package/package.json +1 -1
  151. package/runtime-manifest.json +526 -526
  152. package/scripts/benchmark-embed.js +201 -201
  153. package/scripts/benchmark-recall.js +249 -249
  154. package/scripts/benchmark-rerank.js +166 -166
  155. package/scripts/build-runtime-manifest.mjs +224 -224
  156. package/scripts/changelog-prep.mjs +91 -91
  157. package/scripts/check-sync.js +44 -44
  158. package/scripts/e2e-dsh.js +220 -220
  159. package/scripts/mneme-runtime.mjs +277 -277
  160. package/scripts/publish-gate.mjs +197 -197
  161. package/scripts/release-docs.mjs +210 -210
  162. package/scripts/release-notes.mjs +164 -164
  163. package/scripts/stress-dsh.js +255 -255
  164. package/scripts/sync-lib.js +47 -47
  165. package/scripts/sync-test-badge.mjs +69 -69
  166. package/scripts/test-count-sync.mjs +48 -48
  167. package/src/api-standalone.js +1007 -1007
  168. package/src/api.js +3600 -3600
  169. package/src/attachment-text.js +122 -122
  170. package/src/bootstrap-http.js +105 -105
  171. package/src/bootstrap.js +215 -215
  172. package/src/candidates.js +454 -454
  173. package/src/capabilities.js +819 -819
  174. package/src/choro-command.js +111 -111
  175. package/src/commands.js +95 -95
  176. package/src/config-keys.js +144 -144
  177. package/src/config.js +1361 -1344
  178. package/src/content-hash.js +54 -54
  179. package/src/continuity.js +258 -258
  180. package/src/date-hint.js +32 -0
  181. package/src/diary/auto.js +190 -190
  182. package/src/diary/compose.js +440 -440
  183. package/src/diary/dir.js +59 -59
  184. package/src/diary/export.js +97 -97
  185. package/src/diary/index.js +26 -26
  186. package/src/diary/library.js +189 -189
  187. package/src/diary/qq-inbox.js +142 -142
  188. package/src/diary/rollover.js +61 -61
  189. package/src/diary/session-provider.js +122 -122
  190. package/src/document-index.js +94 -94
  191. package/src/document.js +322 -322
  192. package/src/dream/clustering.js +123 -123
  193. package/src/dream/decisions.js +945 -945
  194. package/src/dream/narratives.js +44 -44
  195. package/src/dream/sleep.js +2027 -2027
  196. package/src/dream/triage.js +139 -139
  197. package/src/dream.js +1879 -1879
  198. package/src/dsh-go/host.js +162 -162
  199. package/src/dsh-go/panel.js +2091 -2091
  200. package/src/dsh-go/text.js +342 -342
  201. package/src/dsh-go/views/common.js +68 -68
  202. package/src/dsh-go/views/entity.js +48 -48
  203. package/src/dsh-go/views/memory.js +198 -198
  204. package/src/dsh-go/views/root.js +30 -30
  205. package/src/dsh-go/views/settings.js +398 -398
  206. package/src/dsh-go/views/status.js +51 -51
  207. package/src/embedding.js +342 -342
  208. package/src/entities/extractor.js +285 -285
  209. package/src/fence.js +24 -24
  210. package/src/graph/anchoring.js +184 -184
  211. package/src/guide.js +74 -74
  212. package/src/heat.js +144 -144
  213. package/src/hot-memory.js +119 -119
  214. package/src/image-describe.js +158 -0
  215. package/src/index.js +852 -852
  216. package/src/inject.js +656 -651
  217. package/src/kb/index.js +309 -309
  218. package/src/kb/routes.js +219 -219
  219. package/src/kb/tools.js +148 -148
  220. package/src/lang.js +607 -595
  221. package/src/local-embedder.js +358 -358
  222. package/src/maintenance.js +162 -162
  223. package/src/memory-source.js +9 -9
  224. package/src/mirror.js +330 -330
  225. package/src/organize.js +456 -456
  226. package/src/peak-hours.js +172 -172
  227. package/src/pipeline-activities.js +178 -178
  228. package/src/pipeline-attribution.js +165 -165
  229. package/src/pipeline-command.js +279 -279
  230. package/src/pipeline-confirm.js +142 -142
  231. package/src/pipeline-exec.js +174 -174
  232. package/src/pipeline-nudge-auto.js +129 -129
  233. package/src/pipeline-nudge.js +1623 -1623
  234. package/src/pipeline-observations.js +181 -181
  235. package/src/pipeline-observe.js +133 -133
  236. package/src/pipeline-runner.js +361 -361
  237. package/src/pipeline-runs.js +442 -442
  238. package/src/pipeline.js +716 -716
  239. package/src/placement.js +13 -13
  240. package/src/pre-inject-gate.js +354 -354
  241. package/src/profile-extract.js +164 -164
  242. package/src/profile-facts.js +356 -356
  243. package/src/provenance-http.js +251 -251
  244. package/src/quality-filter.js +162 -162
  245. package/src/recall-stats.js +190 -190
  246. package/src/reclaim-http.js +150 -150
  247. package/src/reranker.js +269 -269
  248. package/src/runtime/adopt.js +176 -176
  249. package/src/runtime/closure.js +172 -172
  250. package/src/runtime/download.js +247 -247
  251. package/src/runtime/layout.js +265 -265
  252. package/src/runtime/loader.js +252 -252
  253. package/src/runtime/model-fetch.js +361 -361
  254. package/src/runtime/provision.js +237 -237
  255. package/src/runtime/tarball.js +130 -130
  256. package/src/runtime/verify.js +223 -223
  257. package/src/safe-slice.js +18 -18
  258. package/src/scope-state.js +277 -277
  259. package/src/scope.js +187 -187
  260. package/src/search/adaptive.js +60 -60
  261. package/src/search/bm25.js +96 -96
  262. package/src/semantic.js +572 -572
  263. package/src/sensitive-scan.js +209 -209
  264. package/src/serve.js +228 -228
  265. package/src/service.js +3268 -3268
  266. package/src/session-gate.js +91 -91
  267. package/src/session-usage.js +350 -350
  268. package/src/settings.js +827 -817
  269. package/src/share-http.js +281 -281
  270. package/src/share-import.js +234 -234
  271. package/src/share.js +335 -335
  272. package/src/store.js +5895 -5895
  273. package/src/summarize.js +1388 -1343
  274. package/src/tools.js +1370 -1356
  275. package/src/user-settings.js +230 -230
  276. package/src/vector-index.js +180 -180
  277. package/src/version-check.js +122 -122
  278. package/src/wiki/claims.js +267 -267
  279. package/src/wiki/cli-hint.js +90 -90
  280. package/src/wiki/inject.js +164 -164
  281. package/src/wiki/partition.js +200 -200
  282. package/src/wiki/plan.js +214 -214
  283. package/src/wiki/queries.js +640 -640
  284. package/src/wiki/render.js +261 -261
  285. package/src/wiki/scan.js +371 -371
  286. package/src/wiki/t0.js +500 -500
  287. package/src/wiki/t1-jobs.js +232 -232
  288. package/src/wiki/t1.js +609 -609
  289. package/src/write-admission.js +404 -404
  290. package/test/adaptive-inject-budget.test.js +85 -85
  291. package/test/api-hardening.test.js +173 -173
  292. package/test/api-nudge-route.test.js +259 -259
  293. package/test/api-routes-gaps.test.js +1092 -1092
  294. package/test/api.test.js +3007 -2998
  295. package/test/attachment-text.test.js +139 -139
  296. package/test/audit.test.js +448 -448
  297. package/test/baseline-persist.test.js +248 -248
  298. package/test/benchmark.test.js +94 -94
  299. package/test/bm25-corpus-cache.test.js +145 -145
  300. package/test/bootstrap.test.js +228 -228
  301. package/test/candidates.test.js +345 -345
  302. package/test/capabilities.test.js +577 -577
  303. package/test/capacity-warning.test.js +262 -262
  304. package/test/changelog-prep.test.js +125 -125
  305. package/test/choro-command.test.js +218 -218
  306. package/test/cli-enums.test.js +37 -37
  307. package/test/cli-flag-value.test.js +86 -86
  308. package/test/cli-receive.test.js +390 -390
  309. package/test/cli-share.test.js +437 -437
  310. package/test/client-share.test.js +225 -225
  311. package/test/client.test.js +4595 -4425
  312. package/test/clustering.test.js +100 -100
  313. package/test/commands.test.js +106 -106
  314. package/test/config-keys-routes.test.js +233 -233
  315. package/test/config.test.js +153 -153
  316. package/test/conflict-freeze.test.js +344 -344
  317. package/test/conflict-ledger-enforce.test.js +452 -452
  318. package/test/conflict-ledger.test.js +242 -242
  319. package/test/conflict-reviewed.test.js +79 -79
  320. package/test/content-hash.test.js +204 -204
  321. package/test/continuity.test.js +452 -452
  322. package/test/contrast.test.js +432 -432
  323. package/test/date-hint.test.js +156 -0
  324. package/test/dedupe-candidate-window.test.js +180 -180
  325. package/test/dependency-overrides.test.js +78 -78
  326. package/test/diary-library.test.js +187 -187
  327. package/test/diary.test.js +576 -576
  328. package/test/differentiate-feedback.test.js +248 -248
  329. package/test/distill-tx-embed-gap.test.js +110 -110
  330. package/test/docs-config-keys.test.js +65 -65
  331. package/test/document-dir.test.js +233 -233
  332. package/test/document.test.js +703 -703
  333. package/test/dream-archive-guardrail.test.js +116 -116
  334. package/test/dream-baseline-clamp.test.js +174 -174
  335. package/test/dream-candidate-hybrid.test.js +281 -281
  336. package/test/dream-coverage-degrade.test.js +86 -86
  337. package/test/dream-decision-evidence.test.js +314 -314
  338. package/test/dream-failure-backoff.test.js +173 -173
  339. package/test/dream-fence.test.js +207 -207
  340. package/test/dream-maxtokens-fallback.test.js +132 -132
  341. package/test/dream-merge-guardrail.test.js +219 -219
  342. package/test/dream-peak-hours.test.js +194 -194
  343. package/test/dream.test.js +1528 -1528
  344. package/test/dsh-go-host.test.js +134 -134
  345. package/test/dsh-go-panel-actions.test.js +854 -854
  346. package/test/dsh-go-panel.test.js +251 -251
  347. package/test/embed-ready-poll.test.js +94 -94
  348. package/test/embed-text-reasons.test.js +112 -112
  349. package/test/embedding-cache-f32.test.js +276 -276
  350. package/test/embedding-ready.test.js +226 -226
  351. package/test/entities.test.js +711 -711
  352. package/test/entity-recall.test.js +179 -179
  353. package/test/epistemic.test.js +325 -325
  354. package/test/failure-query.test.js +147 -147
  355. package/test/failure-retention.test.js +105 -105
  356. package/test/fnew-0112.test.js +311 -311
  357. package/test/fnew-03.test.js +422 -422
  358. package/test/forget-corrections.test.js +70 -70
  359. package/test/graph-anchoring.test.js +184 -184
  360. package/test/graph-api.test.js +333 -333
  361. package/test/graph-boosted-relations.test.js +189 -189
  362. package/test/graph-inject-budget.test.js +103 -103
  363. package/test/graph-multipath.test.js +269 -269
  364. package/test/graph-passive-confirm.test.js +91 -91
  365. package/test/graph-weight-evolution.test.js +104 -104
  366. package/test/heat.test.js +175 -175
  367. package/test/helpers/dream-mock.js +86 -86
  368. package/test/helpers/peer-worker.mjs +25 -25
  369. package/test/helpers/runtime-source.js +60 -60
  370. package/test/helpers/tar-builder.js +80 -80
  371. package/test/helpers/write-admission-samples.js +312 -312
  372. package/test/hot-memory.test.js +259 -259
  373. package/test/image-description.test.js +271 -0
  374. package/test/image-memory.test.js +170 -170
  375. package/test/inject-content-cap.test.js +91 -91
  376. package/test/inject-first-round-bm25.test.js +89 -89
  377. package/test/inject-heat.test.js +77 -77
  378. package/test/inject-parent-gate.test.js +134 -109
  379. package/test/inject-pin-explicit.test.js +300 -300
  380. package/test/inject-pin-vector-crowd.test.js +225 -225
  381. package/test/inject-pools.test.js +195 -195
  382. package/test/inject-recall.test.js +172 -172
  383. package/test/inject-rotation.test.js +161 -161
  384. package/test/inject.test.js +553 -553
  385. package/test/issue-617-step1-query-and-fusion.test.js +361 -361
  386. package/test/kb-api-wiring.test.js +128 -128
  387. package/test/kb-collections.test.js +272 -272
  388. package/test/kb-routes.test.js +379 -379
  389. package/test/lang.test.js +98 -98
  390. package/test/lastrunat-persist.test.js +101 -101
  391. package/test/lib-smoke.test.js +116 -116
  392. package/test/llm-audit.test.js +815 -815
  393. package/test/llm-message-source.test.js +207 -207
  394. package/test/local-embedder.test.js +292 -292
  395. package/test/maintenance.test.js +501 -501
  396. package/test/mcp-stdio.test.js +385 -385
  397. package/test/mint-source.test.js +311 -311
  398. package/test/mirror-dirty.test.js +424 -424
  399. package/test/mirror-edit-digest.test.js +187 -187
  400. package/test/mirror-generation.test.js +499 -499
  401. package/test/mirror-types.test.js +208 -208
  402. package/test/mirror.test.js +249 -249
  403. package/test/narrative-bars.test.js +162 -162
  404. package/test/organize-tool.test.js +232 -232
  405. package/test/organize.test.js +418 -418
  406. package/test/panel-chart-scale.test.js +90 -90
  407. package/test/panel-tokens.test.js +245 -245
  408. package/test/peak-hours-observability.test.js +70 -70
  409. package/test/peer-blockers.test.js +193 -193
  410. package/test/persona-addressing.test.js +83 -83
  411. package/test/persona-api.test.js +172 -172
  412. package/test/persona-by-session.test.js +568 -568
  413. package/test/persona-flag.test.js +36 -36
  414. package/test/persona-inject.test.js +145 -145
  415. package/test/persona-settings.test.js +198 -198
  416. package/test/pipeline-activities.test.js +155 -155
  417. package/test/pipeline-attribution.test.js +175 -175
  418. package/test/pipeline-command.test.js +243 -243
  419. package/test/pipeline-confirm.test.js +148 -148
  420. package/test/pipeline-exec.test.js +172 -172
  421. package/test/pipeline-nudge-auto.test.js +248 -248
  422. package/test/pipeline-nudge.test.js +1278 -1278
  423. package/test/pipeline-observations.test.js +157 -157
  424. package/test/pipeline-observe.test.js +127 -127
  425. package/test/pipeline-r1r2.test.js +278 -278
  426. package/test/pipeline-runner.test.js +468 -468
  427. package/test/pipeline-runs.test.js +767 -767
  428. package/test/pipeline.test.js +636 -636
  429. package/test/placement.test.js +36 -36
  430. package/test/policy-epoch.test.js +259 -259
  431. package/test/pre-inject-gate.test.js +444 -444
  432. package/test/profile-extract.test.js +269 -269
  433. package/test/profile-facts.test.js +492 -492
  434. package/test/prompt-stance.test.js +128 -128
  435. package/test/provenance-http.test.js +367 -367
  436. package/test/publish-gate.test.js +272 -272
  437. package/test/quality-backfill.test.js +290 -290
  438. package/test/quality-filter.test.js +295 -295
  439. package/test/readme-claims.test.js +113 -113
  440. package/test/reasoning-effort.test.js +752 -752
  441. package/test/recall-anti-update.test.js +82 -82
  442. package/test/recall-evals.test.js +253 -253
  443. package/test/recall-layer.test.js +326 -326
  444. package/test/recall-retention.test.js +128 -128
  445. package/test/recall-stats.test.js +274 -274
  446. package/test/receipt-chain.test.js +451 -451
  447. package/test/reclaim-http.test.js +209 -209
  448. package/test/reflection-update-gate.test.js +129 -129
  449. package/test/reflection.test.js +226 -226
  450. package/test/reindex-backfill.test.js +475 -475
  451. package/test/reindex-scheduler.test.js +369 -369
  452. package/test/release-docs.test.js +156 -156
  453. package/test/release-notes.test.js +265 -265
  454. package/test/release-workflow.test.js +93 -93
  455. package/test/reranker-single-logit.test.js +73 -73
  456. package/test/reranker.test.js +197 -197
  457. package/test/resident-status.test.js +83 -83
  458. package/test/route-policy.test.js +113 -113
  459. package/test/runtime-adopt.test.js +206 -206
  460. package/test/runtime-cli.test.js +89 -89
  461. package/test/runtime-closure.test.js +193 -193
  462. package/test/runtime-download.test.js +302 -302
  463. package/test/runtime-layout.test.js +163 -163
  464. package/test/runtime-loader.test.js +255 -255
  465. package/test/runtime-manifest.test.js +159 -159
  466. package/test/runtime-model-fetch.test.js +348 -348
  467. package/test/runtime-provision.test.js +101 -101
  468. package/test/runtime-tarball.test.js +81 -81
  469. package/test/runtime-verify.test.js +319 -319
  470. package/test/scope-candidates.test.js +491 -491
  471. package/test/scope-distill-stamp.test.js +134 -134
  472. package/test/scope-explicit.test.js +452 -452
  473. package/test/scope-inject-soft.test.js +106 -106
  474. package/test/scope-optional-service.test.js +110 -110
  475. package/test/scope-retrieval.test.js +197 -197
  476. package/test/scope-state.test.js +610 -610
  477. package/test/scope-storage.test.js +255 -255
  478. package/test/scope-strict.test.js +367 -367
  479. package/test/search-fusion.test.js +90 -90
  480. package/test/security-doc.test.js +188 -188
  481. package/test/semantic.test.js +124 -124
  482. package/test/sensitive-scan.test.js +251 -251
  483. package/test/serve-bin.test.js +121 -121
  484. package/test/serve.test.js +258 -258
  485. package/test/service-search.test.js +174 -174
  486. package/test/service.test.js +410 -410
  487. package/test/session-gate.test.js +264 -264
  488. package/test/session-usage.test.js +317 -317
  489. package/test/settings.test.js +273 -273
  490. package/test/share-foreign-rows.test.js +144 -144
  491. package/test/share-http.test.js +144 -144
  492. package/test/share-import.test.js +577 -577
  493. package/test/share-imported-guard.test.js +311 -311
  494. package/test/share-imported-identity.test.js +111 -111
  495. package/test/share-pack.test.js +511 -511
  496. package/test/share-receive-http.test.js +756 -756
  497. package/test/share-routes.test.js +337 -337
  498. package/test/share-store.test.js +133 -133
  499. package/test/share-validate.test.js +101 -101
  500. package/test/skip-invalid-restore.test.js +262 -262
  501. package/test/sleep-action-set.test.js +441 -441
  502. package/test/sleep-catchup.test.js +315 -315
  503. package/test/sleep-failure-backoff.test.js +156 -156
  504. package/test/sleep-heat.test.js +174 -174
  505. package/test/sleep-scheduler-rearm.test.js +89 -89
  506. package/test/sleep.test.js +1455 -1455
  507. package/test/standalone-api.test.js +1344 -1344
  508. package/test/store-vector-cache.test.js +98 -98
  509. package/test/store-write-path-columns.test.js +191 -191
  510. package/test/store.test.js +744 -744
  511. package/test/stress.test.js +209 -209
  512. package/test/summarize-occurred-at.test.js +127 -127
  513. package/test/summarize-parse-diagnostics.test.js +75 -75
  514. package/test/summarize-reasoning-effort.test.js +189 -189
  515. package/test/summarize.test.js +2251 -2251
  516. package/test/supersede-state-tracking.test.js +394 -394
  517. package/test/test-count-sync.test.js +71 -71
  518. package/test/tool-state-ignore.test.js +65 -65
  519. package/test/tools-dto-schema-matrix.test.js +398 -398
  520. package/test/tools-memory-get-schema.test.js +65 -65
  521. package/test/tools.test.js +585 -585
  522. package/test/updated-at-semantics.test.js +113 -113
  523. package/test/user-settings-preview.test.js +127 -127
  524. package/test/user-settings-segments.test.js +527 -527
  525. package/test/vector-index.test.js +334 -334
  526. package/test/version-check.test.js +152 -152
  527. package/test/webServer-optional.test.js +82 -82
  528. package/test/wiki-api.test.js +734 -734
  529. package/test/wiki-claims.test.js +194 -194
  530. package/test/wiki-cli-hint.test.js +118 -118
  531. package/test/wiki-inject.test.js +265 -265
  532. package/test/wiki-partition.test.js +112 -112
  533. package/test/wiki-plan.test.js +80 -80
  534. package/test/wiki-provenance.test.js +202 -202
  535. package/test/wiki-queries.test.js +398 -398
  536. package/test/wiki-scan.test.js +208 -208
  537. package/test/wiki-store.test.js +190 -190
  538. package/test/wiki-t0.test.js +456 -456
  539. package/test/wiki-t1-jobs.test.js +125 -125
  540. package/test/wiki-t1.test.js +460 -460
  541. package/test/wiki-tools.test.js +176 -176
  542. package/test/workflow-guards.test.js +155 -155
  543. package/test/write-admission.test.js +668 -668
@@ -1,1344 +1,1344 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { readFileSync } from "node:fs";
4
- import { createStore } from "../src/store.js";
5
- import { createService } from "../src/service.js";
6
- import { createSettings } from "../src/settings.js";
7
- import { createStandaloneApi, CONTEXT_DEGRADE_REASONS } from "../src/api-standalone.js";
8
- import { PACKAGE_VERSION } from "../src/version-check.js";
9
- import { Config, applyLightModePreset } from "../src/config.js";
10
-
11
- // Real HTTP server on an OS-assigned port (port: 0), driven with fetch.
12
- // `logger` 可传(默认 null):#383 的降级原因只进 daemon stderr 那行 warn、不进响应体,
13
- // 不接住 logger 就观测不到它——而「日志值 ∈ 枚举」正是 #508 Minor 唯一的可观测效应,
14
- // 也是它当初能溜进来的原因(没有任何测试看过那行日志)。
15
- async function setup({ config = {}, embedder = null, embedTimeoutMs, logger = null } = {}) {
16
- const store = createStore(":memory:");
17
- const service = createService({ store, mirror: null, config });
18
- const settings = createSettings(store.db);
19
- const api = createStandaloneApi({ service, store, config, settings, logger, port: 0, embedder, embedTimeoutMs });
20
- await api.ready;
21
- const base = `http://127.0.0.1:${api.port}`;
22
- const auth = { authorization: `Bearer ${api.token}` };
23
- return {
24
- store,
25
- service,
26
- settings,
27
- api,
28
- base,
29
- auth,
30
- close: () => {
31
- // Drop pooled keep-alive sockets so node --test can drain the loop.
32
- api.server.closeIdleConnections?.();
33
- api.server.close();
34
- store.close();
35
- }
36
- };
37
- }
38
-
39
- // --- auth ---------------------------------------------------------------------
40
-
41
- test("GET /health is open without a token; every other route 401s", async () => {
42
- const { base, close } = await setup();
43
- try {
44
- const health = await fetch(`${base}/health`);
45
- assert.equal(health.status, 200);
46
- assert.deepEqual(await health.json(), { ok: true });
47
-
48
- for (const path of ["/status", "/profile", "/rules", "/memories", "/memories/x", "/search?q=x", "/context"]) {
49
- const res = await fetch(`${base}${path}`);
50
- assert.equal(res.status, 401, `${path} requires a token`);
51
- assert.deepEqual(await res.json(), { error: "unauthorized" });
52
- }
53
-
54
- const bad = await fetch(`${base}/status`, { headers: { authorization: "Bearer wrong-token" } });
55
- assert.equal(bad.status, 401, "wrong token rejected");
56
- } finally {
57
- close();
58
- }
59
- });
60
-
61
- test("GET /profile and /rules return saved settings", async () => {
62
- const { base, auth, settings, close } = await setup();
63
- try {
64
- settings.setProfile("我是后端工程师");
65
- settings.setRules(["先验证再修改", "默认使用中文回复"]);
66
-
67
- const profile = await fetch(`${base}/profile`, { headers: auth });
68
- assert.equal(profile.status, 200);
69
- assert.deepEqual(await profile.json(), { profile: "我是后端工程师" });
70
-
71
- const rules = await fetch(`${base}/rules`, { headers: auth });
72
- assert.equal(rules.status, 200);
73
- assert.deepEqual(await rules.json(), { rules: ["先验证再修改", "默认使用中文回复"] });
74
- } finally {
75
- close();
76
- }
77
- });
78
-
79
- test("GET /profile and /rules return empty values when unset", async () => {
80
- const { base, auth, close } = await setup();
81
- try {
82
- const profile = await fetch(`${base}/profile`, { headers: auth });
83
- assert.equal(profile.status, 200);
84
- assert.deepEqual(await profile.json(), { profile: "" });
85
-
86
- const rules = await fetch(`${base}/rules`, { headers: auth });
87
- assert.equal(rules.status, 200);
88
- assert.deepEqual(await rules.json(), { rules: [] });
89
- } finally {
90
- close();
91
- }
92
- });
93
-
94
- test("token is persisted into settings kv and reused across restarts", async () => {
95
- const store = createStore(":memory:");
96
- const service = createService({ store, mirror: null, config: {} });
97
- const settings = createSettings(store.db);
98
- const first = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
99
- await first.ready;
100
- try {
101
- assert.equal(settings.getExternalApi().token, first.token, "generated token persisted");
102
- assert.ok(first.token.length >= 20, "token is a real random value");
103
- const second = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
104
- await second.ready;
105
- assert.equal(second.token, first.token, "restart reuses the persisted token");
106
- second.server.closeIdleConnections?.();
107
- second.server.close();
108
- } finally {
109
- first.server.closeIdleConnections?.();
110
- first.server.close();
111
- store.close();
112
- }
113
- });
114
-
115
- // --- CRUD loop ------------------------------------------------------------------
116
-
117
- test("POST/GET/DELETE /memories round trip", async () => {
118
- const { base, auth, close } = await setup();
119
- try {
120
- const post = await fetch(`${base}/memories`, {
121
- method: "POST",
122
- headers: { ...auth, "content-type": "application/json" },
123
- body: JSON.stringify({ type: "preference", title: "语言", content: "始终用中文回复", importance: 4, tags: ["交流"] })
124
- });
125
- assert.equal(post.status, 201);
126
- const created = await post.json();
127
- assert.ok(created.id, "row id returned");
128
- assert.equal(created.title, "语言");
129
- assert.equal(created.importance, 4);
130
-
131
- const list = await fetch(`${base}/memories?limit=10`, { headers: auth });
132
- assert.equal(list.status, 200);
133
- const listBody = await list.json();
134
- assert.equal(listBody.total, 1);
135
- assert.equal(listBody.items.length, 1);
136
-
137
- const got = await fetch(`${base}/memories/${created.id}`, { headers: auth });
138
- assert.equal(got.status, 200);
139
- assert.equal((await got.json()).content, "始终用中文回复");
140
-
141
- const del = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
142
- assert.equal(del.status, 200);
143
- assert.deepEqual(await del.json(), { ok: true });
144
-
145
- const gone = await fetch(`${base}/memories/${created.id}`, { headers: auth });
146
- assert.equal(gone.status, 404, "deleted row reads back as 404");
147
- const delAgain = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
148
- assert.equal(delAgain.status, 404, "deleting a missing row is 404, not a fake ok");
149
- } finally {
150
- close();
151
- }
152
- });
153
-
154
- test("POST /memories dedupes same title within a type (200 + merged content)", async () => {
155
- const { base, auth, close } = await setup();
156
- try {
157
- const first = await fetch(`${base}/memories`, {
158
- method: "POST",
159
- headers: { ...auth, "content-type": "application/json" },
160
- body: JSON.stringify({ type: "project", title: "mneme", content: "v1 内容" })
161
- });
162
- assert.equal(first.status, 201);
163
- const row1 = await first.json();
164
-
165
- const second = await fetch(`${base}/memories`, {
166
- method: "POST",
167
- headers: { ...auth, "content-type": "application/json" },
168
- body: JSON.stringify({ type: "project", title: "mneme", content: "v2 追加" })
169
- });
170
- assert.equal(second.status, 200, "merge, not a second creation");
171
- const row2 = await second.json();
172
- assert.equal(row2.id, row1.id, "same row reused");
173
- assert.ok(row2.content.includes("v1 内容") && row2.content.includes("v2 追加"), "content appended");
174
-
175
- const list = await fetch(`${base}/memories`, { headers: auth });
176
- assert.equal((await list.json()).total, 1, "no duplicate row created");
177
- } finally {
178
- close();
179
- }
180
- });
181
-
182
- test("POST /memories validation: invalid type, bad JSON, non-array tags → 400", async () => {
183
- const { base, auth, close } = await setup();
184
- try {
185
- const badType = await fetch(`${base}/memories`, {
186
- method: "POST",
187
- headers: { ...auth, "content-type": "application/json" },
188
- body: JSON.stringify({ type: "diary", title: "t", content: "c" })
189
- });
190
- assert.equal(badType.status, 400);
191
- assert.deepEqual(await badType.json(), { error: "invalid-type" });
192
-
193
- const badJson = await fetch(`${base}/memories`, {
194
- method: "POST",
195
- headers: { ...auth, "content-type": "application/json" },
196
- body: "{not json"
197
- });
198
- assert.equal(badJson.status, 400);
199
- assert.deepEqual(await badJson.json(), { error: "invalid-json" });
200
-
201
- const badTags = await fetch(`${base}/memories`, {
202
- method: "POST",
203
- headers: { ...auth, "content-type": "application/json" },
204
- body: JSON.stringify({ type: "project", title: "t", content: "c", tags: "x" })
205
- });
206
- assert.equal(badTags.status, 400);
207
- assert.deepEqual(await badTags.json(), { error: "tags-must-be-an-array" });
208
-
209
- const noTitle = await fetch(`${base}/memories`, {
210
- method: "POST",
211
- headers: { ...auth, "content-type": "application/json" },
212
- body: JSON.stringify({ type: "project", content: "c" })
213
- });
214
- assert.equal(noTitle.status, 400);
215
- assert.deepEqual(await noTitle.json(), { error: "missing-title" });
216
- } finally {
217
- close();
218
- }
219
- });
220
-
221
- // --- list filters / status / search ---------------------------------------------
222
-
223
- test("GET /memories honors type + minImportance filters and paging", async () => {
224
- const { base, auth, service, close } = await setup();
225
- try {
226
- service.saveWithDedupe({ type: "preference", title: "低", content: "i2", importance: 2 });
227
- service.saveWithDedupe({ type: "preference", title: "高", content: "i5", importance: 5 });
228
- service.saveWithDedupe({ type: "project", title: "项目", content: "i4", importance: 4 });
229
-
230
- const byType = await fetch(`${base}/memories?type=preference`, { headers: auth });
231
- assert.equal((await byType.json()).total, 2);
232
-
233
- const byImportance = await fetch(`${base}/memories?minImportance=4`, { headers: auth });
234
- const filtered = await byImportance.json();
235
- assert.equal(filtered.total, 2);
236
- assert.deepEqual(filtered.items.map((m) => m.title).sort(), ["项目", "高"]);
237
-
238
- const paged = await fetch(`${base}/memories?limit=2&offset=0&order=chrono`, { headers: auth });
239
- const page = await paged.json();
240
- assert.equal(page.items.length, 2);
241
- assert.equal(page.total, 3);
242
- } finally {
243
- close();
244
- }
245
- });
246
-
247
- test("GET /status reports version, per-type totals, entities and uptime", async () => {
248
- const { base, auth, service, close } = await setup();
249
- try {
250
- service.saveWithDedupe({ type: "preference", title: "p", content: "c" });
251
- service.saveWithDedupe({ type: "project", title: "j", content: "c" });
252
- service.saveWithDedupe({ type: "project", title: "j2", content: "c" });
253
-
254
- const res = await fetch(`${base}/status`, { headers: auth });
255
- assert.equal(res.status, 200);
256
- const body = await res.json();
257
- // 回归锁:/status 的版本必须来自 package.json(PACKAGE_VERSION),不是散落的
258
- // 字面量——曾经此处硬编码常量在发版时漏 bump,运行 0.8.13 却对外报 0.7.12。
259
- assert.equal(body.version, PACKAGE_VERSION);
260
- assert.equal(body.memories.total, 3);
261
- assert.equal(body.memories.byType.preference, 1);
262
- assert.equal(body.memories.byType.project, 2);
263
- assert.equal(body.entities, 0, "no extraction wired → empty entity table");
264
- assert.ok(Number.isInteger(body.uptime_s));
265
- } finally {
266
- close();
267
- }
268
- });
269
-
270
- test("GET /search finds saved memories; empty q returns empty keyword result", async () => {
271
- const { base, auth, close } = await setup();
272
- try {
273
- await fetch(`${base}/memories`, {
274
- method: "POST",
275
- headers: { ...auth, "content-type": "application/json" },
276
- body: JSON.stringify({ type: "project", title: "记忆插件", content: "SQLite 全文检索" })
277
- });
278
-
279
- const res = await fetch(`${base}/search?q=${encodeURIComponent("全文检索")}&mode=keyword`, { headers: auth });
280
- assert.equal(res.status, 200);
281
- const body = await res.json();
282
- assert.equal(body.mode, "keyword");
283
- assert.equal(body.items.length, 1);
284
- assert.equal(body.items[0].title, "记忆插件");
285
-
286
- const empty = await fetch(`${base}/search?q=`, { headers: auth });
287
- assert.deepEqual(await empty.json(), { items: [], mode: "keyword" });
288
- } finally {
289
- close();
290
- }
291
- });
292
-
293
- test("unknown path returns 404 json", async () => {
294
- const { base, auth, close } = await setup();
295
- try {
296
- const res = await fetch(`${base}/nope`, { headers: auth });
297
- assert.equal(res.status, 404);
298
- assert.deepEqual(await res.json(), { error: "not-found" });
299
- } finally {
300
- close();
301
- }
302
- });
303
-
304
- // --- light-mode preset (applyLightModePreset) ------------------------------------
305
-
306
- const LIGHT_OFF_FIELDS = [
307
- "entityExtractionEnabled",
308
- "autoDream",
309
- "sleepModeEnabled",
310
- "rerankEnabled",
311
- "autoReindexOnBoot",
312
- "hybridInject",
313
- "searchSemanticDedup",
314
- "selectiveInjectEnabled",
315
- "bm25SearchEnabled"
316
- ];
317
-
318
- test("applyLightModePreset turns heavy features off and keeps the core loop", () => {
319
- const cfg = applyLightModePreset(Config({ lightMode: true }));
320
- for (const field of LIGHT_OFF_FIELDS) {
321
- assert.equal(cfg[field], false, `${field} forced off in light mode`);
322
- }
323
- // Core loop preserved.
324
- assert.equal(cfg.autoInject, true);
325
- assert.equal(cfg.autoSummarize, true);
326
- assert.equal(cfg.hotMemoryEnabled, true);
327
- assert.equal(cfg.memoryQualityFilter.enabled, true);
328
- // Unrelated knobs untouched.
329
- assert.equal(cfg.dreamThresholdCount, 10);
330
- assert.equal(cfg.dreamDelayMs, 2000);
331
- assert.equal(cfg.maxInjectedItems, 5);
332
- });
333
-
334
- test("applyLightModePreset keeps explicit non-preset values and is a no-op without lightMode", () => {
335
- const tuned = applyLightModePreset(Config({ lightMode: true, dreamThresholdCount: 30, maxInjectedItems: 8 }));
336
- assert.equal(tuned.dreamThresholdCount, 30, "operator values survive the preset");
337
- assert.equal(tuned.maxInjectedItems, 8);
338
-
339
- const plain = Config({});
340
- assert.equal(applyLightModePreset(plain), plain, "identity when lightMode is unset");
341
- const off = Config({ lightMode: false });
342
- assert.equal(applyLightModePreset(off), off, "identity when lightMode is false");
343
- });
344
-
345
- test("persisted panel_mode=light wins over a bundle config that did not ask for it", () => {
346
- const store = createStore(":memory:");
347
- const settings = createSettings(store.db);
348
- try {
349
- // Panel switched to light in a previous session; bundle config says nothing.
350
- settings.setPanelMode("light");
351
- const rawCfg = Config({});
352
- const lightMode = rawCfg.lightMode === true || settings.getPanelMode() === "light";
353
- const cfg = applyLightModePreset({ ...rawCfg, lightMode });
354
- assert.equal(lightMode, true, "persisted mode forces light");
355
- assert.equal(cfg.autoDream, false);
356
- assert.equal(cfg.entityExtractionEnabled, false);
357
- assert.equal(cfg.autoInject, true, "core injection stays on");
358
-
359
- // standard (default) never forces the preset even with a light bundle flag off.
360
- settings.setPanelMode("standard");
361
- const raw2 = Config({});
362
- assert.equal(raw2.lightMode === true || settings.getPanelMode() === "light", false);
363
- } finally {
364
- store.close();
365
- }
366
- });
367
-
368
- // --- #181:MCP 六件套的 API 面(PUT / save 透传 / archived 与 occurred 窗口)---
369
-
370
- test("PUT /memories/:id patches fields and returns the DTO (unauthorized without token)", async () => {
371
- const { base, auth, service, close } = await setup();
372
- try {
373
- const created = await (await fetch(`${base}/memories`, {
374
- method: "POST",
375
- headers: { ...auth, "content-type": "application/json" },
376
- body: JSON.stringify({ type: "preference", title: "编辑器", content: "用 vim", importance: 3 })
377
- })).json();
378
-
379
- const noAuth = await fetch(`${base}/memories/${created.id}`, {
380
- method: "PUT",
381
- headers: { "content-type": "application/json" },
382
- body: JSON.stringify({ content: "用 nvim" })
383
- });
384
- assert.equal(noAuth.status, 401, "PUT requires the Bearer token");
385
-
386
- const put = await fetch(`${base}/memories/${created.id}`, {
387
- method: "PUT",
388
- headers: { ...auth, "content-type": "application/json" },
389
- body: JSON.stringify({ content: "用 nvim", importance: 4, tags: ["工具"], reason: "用户改用 nvim 了" })
390
- });
391
- assert.equal(put.status, 200);
392
- const { memory } = await put.json();
393
- assert.equal(memory.content, "用 nvim");
394
- assert.equal(memory.importance, 4);
395
- assert.deepEqual(memory.tags, ["工具"]);
396
-
397
- // content 改写按 human_override 入档(与内部面板写路径一致)。
398
- const raw = service.getById(created.id);
399
- assert.equal(raw.content_history?.[0]?.source, "human_override");
400
- assert.equal(raw.content_history?.[0]?.content, "用 vim");
401
- } finally {
402
- close();
403
- }
404
- });
405
-
406
- test("PUT /memories/:id validation: bad fields → 400, empty patch → 400, missing id → 404", async () => {
407
- const { base, auth, close } = await setup();
408
- try {
409
- const put = (body, id = "whatever") => fetch(`${base}/memories/${id}`, {
410
- method: "PUT",
411
- headers: { ...auth, "content-type": "application/json" },
412
- body: JSON.stringify(body)
413
- });
414
- assert.equal((await put({ title: "" })).status, 400);
415
- assert.equal((await put({ importance: 9 })).status, 400);
416
- assert.equal((await put({ tags: "x" })).status, 400);
417
- assert.equal((await put({ type: "nope" })).status, 400);
418
- assert.equal((await put({})).status, 400, "empty patch is no-fields");
419
- assert.equal((await put({ content: "x" }, "missing-id")).status, 404);
420
- assert.equal((await put({ agent_scope: 5 })).status, 400);
421
- } finally {
422
- close();
423
- }
424
- });
425
-
426
- test("PUT /memories/:id surfaces service failures as 500 instead of a hung request", async () => {
427
- const { base, auth, service, close } = await setup();
428
- try {
429
- const created = await (await fetch(`${base}/memories`, {
430
- method: "POST",
431
- headers: { ...auth, "content-type": "application/json" },
432
- body: JSON.stringify({ type: "preference", title: "会抛错", content: "v1" })
433
- })).json();
434
- const original = service.update;
435
- service.update = () => { throw new Error("boom"); };
436
- try {
437
- const res = await fetch(`${base}/memories/${created.id}`, {
438
- method: "PUT",
439
- headers: { ...auth, "content-type": "application/json" },
440
- body: JSON.stringify({ content: "v2" })
441
- });
442
- assert.equal(res.status, 500, "service throw must not strand the request");
443
- assert.deepEqual(await res.json(), { error: "internal" });
444
- } finally {
445
- service.update = original;
446
- }
447
- } finally {
448
- close();
449
- }
450
- });
451
-
452
- test("POST /memories passes through sensitivity/occurred_at/scope and returns action", async () => {
453
- const { base, auth, close } = await setup();
454
- try {
455
- const post = await fetch(`${base}/memories`, {
456
- method: "POST",
457
- headers: { ...auth, "content-type": "application/json" },
458
- body: JSON.stringify({
459
- type: "decision",
460
- title: "迁移",
461
- content: "迁到 sqlite 分支",
462
- sensitivity: "personal",
463
- occurred_at: "2026-01-15T10:00:00Z",
464
- agent_scope: "global"
465
- })
466
- });
467
- assert.equal(post.status, 201);
468
- const created = await post.json();
469
- assert.equal(created.action, "created", "action rides along for tool parity");
470
- assert.equal(created.sensitivity, "personal");
471
- // store 把 ISO 瞬时归一化成完整毫秒形式(2026-01-15T10:00:00Z → …T10:00:00.000Z)。
472
- assert.match(created.occurred_at, /^2026-01-15T10:00:00/);
473
- assert.equal(created.agent_scope, "global");
474
- assert.equal(created.agent_scope_source, "explicit");
475
-
476
- // 合并判据=同 type + 同标题 + 同 sensitivity + 同作用域三元(0.8.0 起去重键
477
- // 含 scope,跨作用域同标题本就分开存):补齐 agent_scope 才 merged。
478
- const merged = await (await fetch(`${base}/memories`, {
479
- method: "POST",
480
- headers: { ...auth, "content-type": "application/json" },
481
- body: JSON.stringify({ type: "decision", title: "迁移", content: "迁到 sqlite 分支(更新)", sensitivity: "personal", agent_scope: "global" })
482
- })).json();
483
- assert.equal(merged.action, "merged", "same dedupe key reports merged");
484
-
485
- const separate = await (await fetch(`${base}/memories`, {
486
- method: "POST",
487
- headers: { ...auth, "content-type": "application/json" },
488
- body: JSON.stringify({ type: "decision", title: "迁移", content: "无标注版本" })
489
- })).json();
490
- assert.equal(separate.action, "created", "no sensitivity/scope → different dedupe key");
491
-
492
- const bad = await fetch(`${base}/memories`, {
493
- method: "POST",
494
- headers: { ...auth, "content-type": "application/json" },
495
- body: JSON.stringify({ type: "decision", title: "x", content: "y", sensitivity: 5 })
496
- });
497
- assert.equal(bad.status, 400);
498
- assert.equal((await bad.json()).error, "invalid-sensitivity");
499
- } finally {
500
- close();
501
- }
502
- });
503
-
504
- test("GET /memories supports include_archived and the occurred_at window", async () => {
505
- const { base, auth, service, close } = await setup();
506
- try {
507
- const save = (title, occurredAt) => fetch(`${base}/memories`, {
508
- method: "POST",
509
- headers: { ...auth, "content-type": "application/json" },
510
- body: JSON.stringify({ type: "history", title, content: `body of ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
511
- });
512
- const january = await (await save("一月的事", "2026-01-15T10:00:00Z")).json();
513
- await save("二月的事", "2026-02-15T10:00:00Z");
514
- await save("无时间戳的事", null);
515
-
516
- const february = await (await fetch(`${base}/memories?occurred_from=2026-02-01`, { headers: auth })).json();
517
- // 「无时间戳的事」按 occurred_at→created_at 回退(写入日 2026-09),落在窗口内。
518
- assert.deepEqual(february.items.map((m) => m.title).sort(), ["二月的事", "无时间戳的事"]);
519
- assert.equal(february.total, 2, "total honors the same window");
520
-
521
- const upToJanuary = await (await fetch(`${base}/memories?occurred_to=2026-01-31`, { headers: auth })).json();
522
- assert.deepEqual(upToJanuary.items.map((m) => m.title), ["一月的事"]);
523
-
524
- service.setArchived(january.id, true);
525
- const active = await (await fetch(`${base}/memories`, { headers: auth })).json();
526
- assert.equal(active.total, 2, "archived rows stay hidden by default");
527
- const withArchived = await (await fetch(`${base}/memories?include_archived=true`, { headers: auth })).json();
528
- assert.equal(withArchived.total, 3, "include_archived=true surfaces archived rows");
529
- } finally {
530
- close();
531
- }
532
- });
533
-
534
- test("GET /memories carries typeCounts: the full distribution without the type filter (#597)", async () => {
535
- const { base, auth, service, close } = await setup();
536
- try {
537
- service.saveWithDedupe({ type: "preference", title: "p", content: "c" });
538
- service.saveWithDedupe({ type: "project", title: "j1", content: "c" });
539
- service.saveWithDedupe({ type: "project", title: "j2", content: "c" });
540
-
541
- // total 跟着 type 筛;typeCounts 是同一份筛选、**不带 type** 的分布——
542
- // 选中一类时其它类的数字仍在(面板分类栏不再塌剩两枚)。
543
- const filtered = await (await fetch(`${base}/memories?type=project`, { headers: auth })).json();
544
- assert.equal(filtered.total, 2, "total honors the type filter");
545
- assert.deepEqual(filtered.typeCounts, { preference: 1, project: 2 }, "distribution ignores the type filter");
546
-
547
- const all = await (await fetch(`${base}/memories`, { headers: auth })).json();
548
- assert.equal(
549
- Object.keys(all.typeCounts).reduce((n, k) => n + all.typeCounts[k], 0),
550
- all.total,
551
- "distribution sums to the unfiltered total"
552
- );
553
- } finally {
554
- close();
555
- }
556
- });
557
-
558
- test("GET /search honors the occurred_at window", async () => {
559
- const { base, auth, close } = await setup();
560
- try {
561
- const save = (title, occurredAt) => fetch(`${base}/memories`, {
562
- method: "POST",
563
- headers: { ...auth, "content-type": "application/json" },
564
- body: JSON.stringify({ type: "history", title, content: `记忆星球 ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
565
- });
566
- await save("旧事", "2026-01-15T10:00:00Z");
567
- await save("新事", "2026-03-15T10:00:00Z");
568
-
569
- const hit = await (await fetch(`${base}/search?q=${encodeURIComponent("记忆星球")}&occurred_from=2026-03-01`, { headers: auth })).json();
570
- assert.equal(hit.items.length, 1);
571
- assert.equal(hit.items[0].title, "新事");
572
- } finally {
573
- close();
574
- }
575
- });
576
-
577
- // --- GET /context(issue #370,#363 承诺)---------------------------------------
578
-
579
- /** /context 用例的省事入库:走 POST /memories,与第三方调用同路径。 */
580
- async function saveMemory(base, auth, body) {
581
- const res = await fetch(`${base}/memories`, {
582
- method: "POST",
583
- headers: { ...auth, "content-type": "application/json" },
584
- body: JSON.stringify(body)
585
- });
586
- assert.ok(res.status === 201 || res.status === 200, `save ${body.title} → ${res.status}`);
587
- return res.json();
588
- }
589
-
590
- test("GET /search passes a declared scope through (strictScope hard wall on the search face too)", async () => {
591
- // issue #370:searchMemories 本就收 scope,8790 此前没有入口——透传后第三方
592
- // 声明身份,A2 软加权与 strictScope 硬过滤在检索面同样成立;不传参数行为
593
- // 与既往逐字节一致(scopeFromSearchParams 返回 undefined → 不进 options)。
594
- const { base, auth, close } = await setup({ config: { strictScope: true } });
595
- try {
596
- await saveMemory(base, auth, { type: "decision", title: "他域检索", content: "外部线索 abc", importance: 5, agent_scope: "other-agent" });
597
-
598
- const scoped = await (await fetch(`${base}/search?q=${encodeURIComponent("外部线索")}&agent_scope=me`, { headers: auth })).json();
599
- assert.ok(!scoped.items.some((m) => m.title === "他域检索"), "explicit foreign agent_scope row is hard-filtered");
600
-
601
- const unscoped = await (await fetch(`${base}/search?q=${encodeURIComponent("外部线索")}`, { headers: auth })).json();
602
- assert.ok(unscoped.items.some((m) => m.title === "他域检索"), "no scope declared → gate dormant, behavior unchanged");
603
- } finally {
604
- close();
605
- }
606
- });
607
-
608
- test("GET /context returns the injection-shaped aggregate; empty q still serves the rule tier", async () => {
609
- const { base, auth, settings, close } = await setup();
610
- try {
611
- settings.setProfile("我是后端工程师");
612
- settings.setRules(["先验证再修改"]);
613
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
614
- await saveMemory(base, auth, { type: "preference", title: "默认中文", content: "回复默认用中文", importance: 4 });
615
-
616
- const res = await fetch(`${base}/context`, { headers: auth });
617
- assert.equal(res.status, 200);
618
- const body = await res.json();
619
- // 形状锁:五键响应——bridge 等调用方按这些键渲染,漂移(加塞/漏带)在此变红。
620
- // #383 新增 tier(档位信号);空 q 时语义路未启用,报 unknown 而不是 full。
621
- // 注意 unknown **不只**是空 q:#508 之后「维度探针没跑成」与「有行但一条向量都读
622
- // 不出来」也落这里(判不出来就不宣称 full)——三态不变,unknown 的生产者多了两个。
623
- assert.deepEqual(Object.keys(body).sort(), ["items", "pinnedCount", "profile", "rules", "tier"]);
624
- assert.equal(typeof body.tier, "string", "tier 必填");
625
- assert.equal(body.tier, "unknown", "空 q = 语义路未启用,不宣称档位(fail-closed,不报 full)");
626
- assert.equal(body.profile, "我是后端工程师");
627
- assert.deepEqual(body.rules, ["先验证再修改"]);
628
- assert.equal(body.pinnedCount, 0, "pinnedInjectBudget 默认 0(opt-in 纪律,issue #370 取舍 3)");
629
- const titles = body.items.map((m) => m.title);
630
- assert.ok(titles.includes("核心决策") && titles.includes("默认中文"), "empty q → pure rule tier, high-importance rows still served");
631
- for (const item of body.items) {
632
- assert.ok(item.id && item.type && item.title && typeof item.content === "string" && Number.isInteger(item.importance));
633
- }
634
- } finally {
635
- close();
636
- }
637
- });
638
-
639
- test("GET /context threshold is an importance gate (not /search's similarity threshold)", async () => {
640
- // 同名不同义锁(issue #370 点名的文档区分):/context 的 threshold 走
641
- // injectCandidates 的 importance 门(summary/preference 豁免),与相似度无关
642
- // ——本用例全程无 embedder/向量,纯规则档即可验证。
643
- const { base, auth, close } = await setup();
644
- try {
645
- await saveMemory(base, auth, { type: "decision", title: "低重要", content: "小事一桩", importance: 3 });
646
- await saveMemory(base, auth, { type: "decision", title: "高重要", content: "大事记", importance: 5 });
647
-
648
- const open = await (await fetch(`${base}/context`, { headers: auth })).json();
649
- const openTitles = open.items.map((m) => m.title);
650
- assert.ok(openTitles.includes("低重要") && openTitles.includes("高重要"), "default threshold=3 admits both");
651
-
652
- const gated = await (await fetch(`${base}/context?threshold=4`, { headers: auth })).json();
653
- const gatedTitles = gated.items.map((m) => m.title);
654
- assert.ok(gatedTitles.includes("高重要"), "importance 5 survives threshold=4");
655
- assert.ok(!gatedTitles.includes("低重要"), "importance 3 is gated out at threshold=4");
656
- } finally {
657
- close();
658
- }
659
- });
660
-
661
- test("GET /context pins preference rows ahead when pinnedInjectBudget is on", async () => {
662
- // #249 pin 池经 8790 透出。用 preference 而非 constraint:constraint 属编码
663
- // 记忆,非编码查询被 codingGate 排除在候选池外,pin 池也够不着它。
664
- const { base, auth, close } = await setup({ config: { pinnedInjectBudget: 2 } });
665
- try {
666
- await saveMemory(base, auth, { type: "preference", title: "pin-偏好", content: "永远先讲结论", importance: 5 });
667
- await saveMemory(base, auth, { type: "decision", title: "普通决策", content: "先做 A 再做 B", importance: 5 });
668
-
669
- const body = await (await fetch(`${base}/context`, { headers: auth })).json();
670
- assert.equal(body.items[0].title, "pin-偏好", "pinned row leads the block");
671
- assert.equal(body.pinnedCount, 1);
672
- } finally {
673
- close();
674
- }
675
- });
676
-
677
- test("GET /context honors a declared scope under strictScope; undeclared stays unfiltered", async () => {
678
- // scope 语义锁(issue #370):声明身份 → strictScope 硬过滤按 isVisibleInScope
679
- // 生效;不声明 → scope=null,门不触发(与宿主「会话身份取不到时两维为 null」
680
- // 同构)。任一维声明而另一维缺省时,缺维按解析不到走 fail-closed。
681
- const { base, auth, close } = await setup({ config: { strictScope: true } });
682
- try {
683
- await saveMemory(base, auth, { type: "decision", title: "他域决策", content: "别的 agent 的事", importance: 5, agent_scope: "other-agent" });
684
- await saveMemory(base, auth, { type: "decision", title: "全域决策", content: "谁都可见", importance: 5 });
685
-
686
- const declared = await (await fetch(`${base}/context?agent_scope=me`, { headers: auth })).json();
687
- const declaredTitles = declared.items.map((m) => m.title);
688
- assert.ok(!declaredTitles.includes("他域决策"), "explicit foreign agent_scope row is hard-filtered");
689
- assert.ok(declaredTitles.includes("全域决策"));
690
-
691
- const undeclared = await (await fetch(`${base}/context`, { headers: auth })).json();
692
- const undeclaredTitles = undeclared.items.map((m) => m.title);
693
- assert.ok(undeclaredTitles.includes("他域决策"), "no declared scope → no gate");
694
- } finally {
695
- close();
696
- }
697
- });
698
-
699
- test("GET /context embeds the query via the injected embedder (wiring lock)", async () => {
700
- // embedder 接线锁(issue #370):createStandaloneApi 新增的可选 embedder 必须
701
- // 真被 /context 用上——宿主与 daemon 传的都是 semantic 装配的同一实例。
702
- const calls = [];
703
- const fake = {
704
- ready: true,
705
- modelHash: "fake-hash-1",
706
- dimension: 4,
707
- embedSingle: async (text) => {
708
- calls.push(text);
709
- return [1, 0, 0, 0];
710
- }
711
- };
712
- const { base, auth, close } = await setup({ embedder: fake });
713
- try {
714
- const res = await fetch(`${base}/context?q=${encodeURIComponent("语义查询")}`, { headers: auth });
715
- assert.equal(res.status, 200);
716
- await res.json();
717
- assert.deepEqual(calls, ["语义查询"], "the route must hand the query to the injected embedder");
718
- } finally {
719
- close();
720
- }
721
- });
722
-
723
- test("GET /context survives a throwing embedder (rule-tier degradation, never 500)", async () => {
724
- const { base, auth, close } = await setup({
725
- embedder: { ready: true, embedSingle: async () => { throw new Error("model offline"); } }
726
- });
727
- try {
728
- await saveMemory(base, auth, { type: "decision", title: "降级存照", content: "嵌入挂了也要有注入", importance: 5 });
729
- const res = await fetch(`${base}/context?q=任意`, { headers: auth });
730
- assert.equal(res.status, 200, "embed failure must degrade to the rule tier");
731
- const body = await res.json();
732
- assert.ok(body.items.some((m) => m.title === "降级存照"));
733
- } finally {
734
- close();
735
- }
736
- });
737
-
738
- test("GET /context times out a hung embedder and degrades (embedTimeoutMs guard)", async () => {
739
- // CodeRabbit on #371:embedder 挂起(不抛错,典型为第三方 ollama/openai 端点
740
- // 无响应)不能占住 HTTP 连接——超时按嵌入缺失降级规则档。测试用 50ms 短超时
741
- // 避免慢测试;生产默认 3000 由工厂选项约束(同 strictPort,不进 config schema)。
742
- const { base, auth, close } = await setup({
743
- embedTimeoutMs: 50,
744
- embedder: { ready: true, embedSingle: () => new Promise(() => {}) }
745
- });
746
- try {
747
- await saveMemory(base, auth, { type: "decision", title: "挂起存照", content: "嵌入悬挂也要有注入", importance: 5 });
748
- const started = Date.now();
749
- const res = await fetch(`${base}/context?q=任意`, { headers: auth });
750
- assert.equal(res.status, 200, "hung embedder must not hang the route");
751
- const body = await res.json();
752
- assert.ok(body.items.some((m) => m.title === "挂起存照"), "timed-out embed falls back to the rule tier");
753
- assert.ok(Date.now() - started < 3000, "response must not wait on the hung embedder");
754
- } finally {
755
- close();
756
- }
757
- });
758
-
759
- test("strictPort: busy port rejects instead of hopping; default path still hops", async () => {
760
- // daemon 语义锁(#363):strictPort 下配置端口被占 = 配置错误,明确失败 ——
761
- // 顺延会让把 URL 写死的第三方客户端静默打到错误端口。占口用裸 net server
762
- // (OS 分配,不与并行测试抢固定号)。
763
- const { default: net } = await import("node:net");
764
- const blocker = net.createServer();
765
- await new Promise((resolve) => blocker.listen(0, "127.0.0.1", resolve));
766
- const busyPort = blocker.address().port;
767
-
768
- const store = createStore(":memory:");
769
- const service = createService({ store, mirror: null, config: {} });
770
- const settings = createSettings(store.db);
771
- try {
772
- const strict = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: busyPort, strictPort: true });
773
- await assert.rejects(strict.ready, (err) => err?.code === "EADDRINUSE");
774
-
775
- // 默认路径(不传 strictPort)行为不变:顺延成功;具体端口不断言(避免抢号)。
776
- const hopping = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: busyPort });
777
- await hopping.ready;
778
- assert.notEqual(hopping.port, busyPort, "default policy hops off a busy port");
779
- hopping.server.close();
780
- } finally {
781
- blocker.close();
782
- store.close();
783
- }
784
- });
785
-
786
- // --- GET /context 的档位信号(issue #383)---------------------------------------
787
- // 嵌入降级在调用方视角是完全静默的:items 看起来正常,只是召回质量悄悄变差。
788
- // 外部集成方(Mneme Bridge 的 remote 模式)无法据此降级自己的期望或打日志。
789
- // 三态 fail-closed:判不出来报 unknown,不报 full。
790
-
791
- /** 可用的 embedder:任何查询都回一个固定向量。 */
792
- const okEmbedder = { embedSingle: async () => [1, 0, 0], embed: async () => [1, 0, 0] };
793
-
794
- test("GET /context tier=full when the query embedding succeeds", async () => {
795
- const { base, auth, close } = await setup({ embedder: okEmbedder });
796
- try {
797
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
798
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
799
- assert.equal(body.tier, "full", "嵌入成功 → 语义档");
800
- } finally {
801
- close();
802
- }
803
- });
804
-
805
- test("GET /context tier=degraded when no embedder is injected", async () => {
806
- // 缺省(不传 embedder):daemon 与宿主都可能走到这条——embedder 未装配。
807
- const { base, auth, close } = await setup();
808
- try {
809
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
810
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
811
- assert.equal(body.tier, "degraded", "无 embedder → 降级到规则档,且必须说出来");
812
- } finally {
813
- close();
814
- }
815
- });
816
-
817
- test("GET /context tier=degraded when the query embedding times out", async () => {
818
- // embedder 挂起(不抛错)时由 withEmbedTimeout 兜底——这是最难自查的一种降级,
819
- // 因为接口是好的、只是没有响应。
820
- const hanging = { embedSingle: () => new Promise(() => {}), embed: () => new Promise(() => {}) };
821
- const { base, auth, close } = await setup({ embedder: hanging, embedTimeoutMs: 30 });
822
- try {
823
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
824
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
825
- assert.equal(body.tier, "degraded", "嵌入超时 → 降级到规则档");
826
- } finally {
827
- close();
828
- }
829
- });
830
-
831
- test("GET /context tier=degraded when the embedder returns an unusable vector", async () => {
832
- // 空数组 / 非数组同样让语义路走不通(embedQueryVector 的既有兜底),一并报降级。
833
- const empty = { embedSingle: async () => [], embed: async () => [] };
834
- const { base, auth, close } = await setup({ embedder: empty });
835
- try {
836
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
837
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
838
- assert.equal(body.tier, "degraded", "不可用向量 → 降级到规则档");
839
- } finally {
840
- close();
841
- }
842
- });
843
-
844
- test("GET /context tier=degraded when the query vector's dimension differs from the stored one", async () => {
845
- // #383 点名的那一种「悄悄退化」,也是 #508 评审里问「维度不符去哪了」的那一档:
846
- // 嵌入接口一切正常(真的返回了向量),但库里躺着旧维度的向量——searchVector 对
847
- // `v.length !== vector.length` 的行直接跳过,不抛错、只是命中为零,于是召回静默
848
- // 退回 BM25/规则档。没有这个读数时,调用方看到的是 tier=full 加一份看着正常的
849
- // items,而语义召回其实整条是死的。
850
- const { base, auth, close, store, service } = await setup({ embedder: okEmbedder });
851
- try {
852
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
853
- // 手工塞一个 4 维向量:模拟「换了嵌入模型,旧向量还没重建索引」。okEmbedder 出
854
- // 来的是 3 维,所以这一行的维度与查询向量不可比。
855
- const memory = service.all().find((m) => m.title === "核心决策");
856
- store.setEmbedding(memory.id, [1, 0, 0, 0]);
857
- assert.deepEqual(store.vectorDimensionState(3), { state: "mismatch" }, "夹具前置:库里有向量,但没有一条与 3 维查询同维");
858
-
859
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
860
- assert.equal(body.tier, "degraded", "维度不符 → 语义召回实际不可用,报降级而不是 full");
861
- } finally {
862
- close();
863
- }
864
- });
865
-
866
- test("GET /context:库里还没有向量时不算维度不符(两种空的读数必须分开)", async () => {
867
- // 「没有东西可比」与「维度对不上」是两件事:前者是全新库(或还没建索引),
868
- // 语义路只是还没有内容,不是坏了。探针回 none 时必须继续报 full,否则每个新装
869
- // 用户的第一次 /context 都是 degraded。
870
- const { base, auth, close, store } = await setup({ embedder: okEmbedder });
871
- try {
872
- assert.deepEqual(store.vectorDimensionState(3), { state: "none" }, "夹具前置:行集为空,库里没有任何向量");
873
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
874
- assert.equal(body.tier, "full", "没有已存向量 → 不是维度不符");
875
- } finally {
876
- close();
877
- }
878
- });
879
-
880
- // --- 降级原因契约(issue #508 Minor #1)----------------------------------------
881
- // 缺陷本身:非空 q 但没有装配 embedder 时 diag.reason 不赋值,日志靠兜底表达式拼出
882
- // `no-embedder`,而文档声明的枚举里没有这个值;同一表达式里还躺着第二个越界字面量
883
- // `embed-failed`。按枚举解析日志的运维程序会整条漏掉这一种**已测试**的降级路径。
884
- // 根因是「日志契约没有测试锁」:setup() 曾把 logger 硬编码成 null,全仓没有任何一条
885
- // 测试观测过那行 warn 的内容。下面把三侧钉在一起——代码导出的枚举、六条降级路径的实吐
886
- // 值、两份文档声明的集合。
887
-
888
- const DEGRADE_LOG_PREFIX = "dsh-mneme: /context degraded to the rule tier (";
889
-
890
- /** 从抓到的 warn 行里抽出括号内的 reason 令牌,顺带锁前缀字面量(两份文档都写了它)。 */
891
- function degradedReason(logs) {
892
- const line = logs.find((l) => l.startsWith(DEGRADE_LOG_PREFIX));
893
- assert.ok(line, `必须打出降级 warn(前缀 ${DEGRADE_LOG_PREFIX}),实际:${JSON.stringify(logs)}`);
894
- const token = line.slice(DEGRADE_LOG_PREFIX.length, -1);
895
- assert.ok(token.length > 0, "reason 令牌不许为空(兜底默认值已删,漏记账会在这里露出 (undefined))");
896
- return token;
897
- }
898
-
899
- test("降级原因枚举:代码导出、README、docs/DAEMON 三侧同一个集合", () => {
900
- // 枚举从常量派生,不把字符串再抄一遍——新增第七个值时必须改这一个常量 + 两份文档,
901
- // 漏一边这里就红。
902
- assert.ok(Object.isFrozen(CONTEXT_DEGRADE_REASONS), "枚举必须是 frozen 常量");
903
- const docTokens = new Set();
904
- for (const file of ["README.md", "docs/DAEMON.md"]) {
905
- const text = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
906
- // 只收降级原因形状的反引号令牌:`embed-<suffix>` 或 `no-embedder`。bare `embed`、
907
- // `--embed off` 不是枚举成员,别收进来。注意「embedder」是一个词,所以匹配必须是
908
- // `^(?:embed-|no-embed)`——写成 `embed-[a-z]+` 会把 no-embedder 整条漏掉,而那正是
909
- // #508 Minor 漏掉它的同一种手法。
910
- for (const m of text.matchAll(/`([a-z][a-z-]*)`/g)) {
911
- if (/^(?:embed-|no-embed)/.test(m[1])) docTokens.add(m[1]);
912
- }
913
- }
914
- assert.deepEqual(
915
- [...docTokens].sort(),
916
- [...CONTEXT_DEGRADE_REASONS].sort(),
917
- "两份文档声明的降级原因必须与代码导出的枚举同集合(改一边忘另一边会红)"
918
- );
919
- });
920
-
921
- test("每条降级路径写进日志的 reason 都是枚举成员(#508 的日志契约)", async () => {
922
- // 六条路径逐个抓 warn 行抽 reason。embed-dimension 那条要夹具(库里得有旧维度向量),
923
- // 其余五条纯 embedder 形状。每条都断言令牌 ∈ CONTEXT_DEGRADE_REASONS——枚举外的值
924
- // 在这里变红,这正是当初漏掉 no-embedder 的那道门。
925
- const paths = [
926
- {
927
- name: "没装配 embedder(daemon --embed off / lightMode)",
928
- embedder: null,
929
- reason: "no-embedder",
930
- note: "预期态不是故障,所以它必须是枚举里一个有自己的名字,而不是并进 embed-unavailable"
931
- },
932
- {
933
- name: "embedder 对象上没有 embedSingle / embed",
934
- embedder: {},
935
- reason: "embed-unavailable"
936
- },
937
- {
938
- name: "接口返回空数组",
939
- embedder: { embedSingle: async () => [], embed: async () => [] },
940
- reason: "embed-empty"
941
- },
942
- {
943
- name: "接口挂起,被超时护栏按缺失处理",
944
- embedder: { embedSingle: () => new Promise(() => {}), embed: () => new Promise(() => {}) },
945
- embedTimeoutMs: 30,
946
- reason: "embed-timeout"
947
- },
948
- {
949
- name: "接口抛错",
950
- embedder: { embedSingle: async () => { throw new Error("model offline"); } },
951
- reason: "embed-error"
952
- }
953
- ];
954
- for (const path of paths) {
955
- const logs = [];
956
- const { base, auth, close } = await setup({
957
- embedder: path.embedder,
958
- embedTimeoutMs: path.embedTimeoutMs,
959
- logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
960
- });
961
- try {
962
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
963
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
964
- assert.equal(body.tier, "degraded", `${path.name} → 降级档`);
965
- const reason = degradedReason(logs);
966
- assert.equal(reason, path.reason, `${path.name} → reason${path.note ? `(${path.note})` : ""}`);
967
- assert.ok(CONTEXT_DEGRADE_REASONS.includes(reason), `${reason} 必须 ∈ 导出的枚举`);
968
- } finally {
969
- close();
970
- }
971
- }
972
- });
973
-
974
- test("维度不符写进日志的 reason 是 embed-dimension(枚举成员)", async () => {
975
- const logs = [];
976
- const { base, auth, close, store, service } = await setup({
977
- embedder: okEmbedder,
978
- logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
979
- });
980
- try {
981
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
982
- const memory = service.all().find((m) => m.title === "核心决策");
983
- store.setEmbedding(memory.id, [1, 0, 0, 0]);
984
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
985
- assert.equal(body.tier, "degraded");
986
- assert.equal(degradedReason(logs), "embed-dimension");
987
- } finally {
988
- close();
989
- }
990
- });
991
-
992
- // --- 维度探针(issue #508 Major + Minor #2)------------------------------------
993
- // Major:LIMIT 1 拿任意一条向量代表全库,混合维度库里两个方向都错。抽到与查询不符的那条
994
- // → 明明有可比的向量却误报 degraded;首条恰好解析失败 → 其余有效向量都不匹配时又漏报成
995
- // full。判据换成存在性:有没有一条活跃向量的维度等于查询维度。
996
- // Minor #2:探针自身抛异常(库被锁 / 半开)会掉进最终 .catch(),把已经算好的 items 丢掉
997
- // 并回 500——违反 fail-closed。隔离在调用侧,tier 留 unknown。
998
-
999
- /** 库内插入序的 id(探针的行集顺序即插入序,无 ORDER BY 的全表扫)。 */
1000
- function insertedIds(store) {
1001
- return store.db.prepare("SELECT id FROM memories ORDER BY rowid").all().map((r) => r.id);
1002
- }
1003
-
1004
- test("混合维度库:有一条与查询同维的活跃向量 → full,不误报 degraded(#508 Major 场景一)", async () => {
1005
- // LIMIT 1 时代这条是红的:先插入的旧维度行被抽中 → 判「维度不符」,而库里明明躺着
1006
- // 一条可比的 3 维向量,语义召回并没有死。
1007
- const { base, auth, close, store } = await setup({ embedder: okEmbedder });
1008
- try {
1009
- await saveMemory(base, auth, { type: "decision", title: "旧维度行", content: "四维向量", importance: 5 });
1010
- await saveMemory(base, auth, { type: "decision", title: "新维度行", content: "三维向量", importance: 5 });
1011
- const [oldId, newId] = insertedIds(store);
1012
- store.setEmbedding(oldId, [1, 0, 0, 0]); // 先插入 = 旧维度
1013
- store.setEmbedding(newId, [1, 0, 0]); // 后插入 = 与查询同维
1014
- assert.deepEqual(store.vectorDimensionState(3), { state: "match" }, "夹具前置:库里有一条 3 维活跃向量");
1015
-
1016
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1017
- assert.equal(body.tier, "full", "有可比向量 → 语义路通,不能因为抽到 4 维那条就误报降级");
1018
- } finally {
1019
- close();
1020
- }
1021
- });
1022
-
1023
- test("首条向量损坏、其余有效向量都不匹配 → degraded,不误报 full(#508 Major 场景二)", async () => {
1024
- // LIMIT 1 时代这条也是红的:首条解析失败 → 探针回 null → 走「库里没有向量」分支 → full,
1025
- // 而语义召回其实整条是死的。
1026
- const { base, auth, close, store } = await setup({ embedder: okEmbedder });
1027
- try {
1028
- await saveMemory(base, auth, { type: "decision", title: "损坏行", content: "向量文本损坏", importance: 5 });
1029
- await saveMemory(base, auth, { type: "decision", title: "旧维度行", content: "四维向量", importance: 5 });
1030
- const [brokenId, oldDimId] = insertedIds(store);
1031
- // 直接改列,不走 setEmbedding(那条路会归一成 JSON.stringify(array),造不出损坏文本)。
1032
- store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{not json", brokenId);
1033
- store.setEmbedding(oldDimId, [1, 0, 0, 0]);
1034
- assert.deepEqual(store.vectorDimensionState(3), { state: "mismatch" }, "夹具前置:有向量、没有一条与 3 维查询同维");
1035
-
1036
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1037
- assert.equal(body.tier, "degraded", "首条损坏不该把 mismatch 洗成 full");
1038
- } finally {
1039
- close();
1040
- }
1041
- });
1042
-
1043
- test("有行但一条向量都读不出来 → unknown,不是 full(两种空必须分开)", async () => {
1044
- // 「还没有内容」(none → full)与「内容在那儿却读不出来」(unreadable)是两种空。
1045
- // 后者判不出来,按 fail-closed 报 unknown,绝不因为读不到就宣称 full。
1046
- const logs = [];
1047
- const { base, auth, close, store } = await setup({
1048
- embedder: okEmbedder,
1049
- logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
1050
- });
1051
- try {
1052
- await saveMemory(base, auth, { type: "decision", title: "损坏行", content: "向量文本损坏", importance: 5 });
1053
- const [brokenId] = insertedIds(store);
1054
- store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{not json", brokenId);
1055
- assert.deepEqual(store.vectorDimensionState(3), { state: "unreadable" }, "夹具前置:行集非空但零条可解析");
1056
-
1057
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1058
- assert.equal(body.tier, "unknown", "读不出任何向量 → 判不出来,不宣称 full");
1059
- assert.ok(body.items.length > 0, "items 照常返回");
1060
- // unknown 在响应体里只有一个键,分不出「空 q」与「判不出来」;留痕只能走日志,
1061
- // 否则调用方对 unknown 的策略是「不告警」时,这条故障就从运维面上整个消失。
1062
- assert.ok(
1063
- logs.some((l) => l.startsWith("dsh-mneme: /context tier left unknown: no comparable vector readable (unreadable)")),
1064
- `判不出来必须留痕(不是降级原因枚举的一员),实际:${JSON.stringify(logs)}`
1065
- );
1066
- } finally {
1067
- close();
1068
- }
1069
- });
1070
-
1071
- test("维度探针抛异常 → tier=unknown 且 items 不丢,绝不 500(#508 Minor #2)", async () => {
1072
- const logs = [];
1073
- const { base, auth, close, service } = await setup({
1074
- embedder: okEmbedder,
1075
- logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
1076
- });
1077
- try {
1078
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1079
- // 仓内惯用的故障注入(同 test/audit.test.js / test/conflict-freeze.test.js)。
1080
- service.vectorDimensionState = () => { throw new Error("database is locked"); };
1081
-
1082
- const res = await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth });
1083
- assert.equal(res.status, 200, "探针异常不许把已经算好的 items 变成 500");
1084
- const body = await res.json();
1085
- assert.equal(body.tier, "unknown", "判不出来 → unknown,不宣称 full");
1086
- assert.ok(body.items.length > 0, "已经算好的 items 不许被丢掉");
1087
- assert.ok(
1088
- logs.some((l) => l.startsWith("dsh-mneme: /context tier left unknown: dimension probe failed (Error: database is locked)")),
1089
- `探针故障必须留痕,实际:${JSON.stringify(logs)}`
1090
- );
1091
- assert.ok(!logs.some((l) => l.startsWith(DEGRADE_LOG_PREFIX)), "tier 不是 degraded,不该打降级 warn");
1092
- } finally {
1093
- close();
1094
- }
1095
- });
1096
-
1097
- test("探针没跑成(方法缺失 / 返回垃圾 / 异步漂移)一律 unknown,不宣称 full", async () => {
1098
- // typeof 守卫与 sentinel 都要 fail-closed:旧实现里这三种都落到「不是 number」分支
1099
- // 报 full。异步漂移那条是纪律锁——try/catch 只能同步包住一个同步调用,探针一旦被
1100
- // 改成异步,抛错就重新变成 rejection 落回最终 .catch()。
1101
- const shapes = [
1102
- { name: "方法缺失(旧装配)", patch: (s) => { delete s.vectorDimensionState; } },
1103
- { name: "返回字符串", patch: (s) => { s.vectorDimensionState = () => "3"; } },
1104
- { name: "返回 undefined", patch: (s) => { s.vectorDimensionState = () => undefined; } },
1105
- { name: "返回 Promise(异步漂移)", patch: (s) => { s.vectorDimensionState = () => Promise.resolve({ state: "match" }); } }
1106
- ];
1107
- for (const shape of shapes) {
1108
- const { base, auth, close, service } = await setup({ embedder: okEmbedder });
1109
- try {
1110
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1111
- shape.patch(service);
1112
- const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1113
- assert.equal(body.tier, "unknown", `${shape.name} → 判不出来,不宣称 full`);
1114
- } finally {
1115
- close();
1116
- }
1117
- }
1118
- });
1119
-
1120
- test("探针失败与降级 warn 自身抛错也不许把响应变成 500(logger 来自宿主,warn 会抛)", async () => {
1121
- // `logger?.warn?.()` 只防 logger 缺失,防不了 warn 自己抛错(宿主 stdout 管道断裂时
1122
- // 真实可发生)。items 算好之后,日志通道坏了不是丢掉它的理由。
1123
- const logs = [];
1124
- const logger = { info: () => {}, warn: (m) => { logs.push(String(m)); throw new Error("stderr broken"); } };
1125
- const { base, auth, close, service } = await setup({ embedder: okEmbedder, logger });
1126
- try {
1127
- await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1128
- service.vectorDimensionState = () => { throw new Error("boom"); };
1129
- const res = await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth });
1130
- assert.equal(res.status, 200, "warn 自身抛错 + 探针抛错 → 仍然 200");
1131
- assert.equal((await res.json()).tier, "unknown");
1132
-
1133
- // 降级路径同样:warn 抛错被自己的 try/catch 吃掉,tier 与 items 不受影响。
1134
- service.vectorDimensionState = () => ({ state: "mismatch" });
1135
- const degraded = await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth });
1136
- assert.equal(degraded.status, 200, "降级 warn 抛错也不许 500");
1137
- assert.equal((await degraded.json()).tier, "degraded");
1138
- } finally {
1139
- close();
1140
- }
1141
- });
1142
-
1143
- test("维度探针状态机:五种读数各自归位(含 invalid 的 fail-closed 兜底)", async () => {
1144
- // 直接锁 store 的状态机:match / mismatch / none / unreadable / invalid。
1145
- // invalid 当前 /context 不可达(embedQueryVector 保证返回非空数组),但它不许落到
1146
- // full 上——「判不了」与「没有东西可比」不是同一个读数。
1147
- const { store, close } = await setup();
1148
- try {
1149
- assert.deepEqual(store.vectorDimensionState(3), { state: "none" }, "空库 → 行集为空");
1150
- assert.deepEqual(store.vectorDimensionState(0), { state: "invalid" });
1151
- assert.deepEqual(store.vectorDimensionState(-1), { state: "invalid" });
1152
- assert.deepEqual(store.vectorDimensionState(2.5), { state: "invalid" });
1153
- assert.deepEqual(store.vectorDimensionState("3"), { state: "invalid" });
1154
-
1155
- const a = store.save({ type: "decision", title: "同维", content: "c", importance: 4 });
1156
- const b = store.save({ type: "decision", title: "异维", content: "c", importance: 4 });
1157
- store.setEmbedding(a.id, [1, 0, 0]);
1158
- store.setEmbedding(b.id, [1, 0, 0, 0]);
1159
- assert.deepEqual(store.vectorDimensionState(3), { state: "match" }, "有一条同维 → match(短路,不看完)");
1160
- assert.deepEqual(store.vectorDimensionState(5), { state: "mismatch" }, "有向量但没有一条同维 → mismatch");
1161
-
1162
- // 清掉解析缓存再写坏列(getParsedEmbedding 只缓存成功解析,缓存在的话直接改列看不见)。
1163
- store.setEmbedding(a.id, null);
1164
- store.setEmbedding(b.id, null);
1165
- store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{oops", a.id);
1166
- store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("[]", b.id);
1167
- assert.deepEqual(store.vectorDimensionState(3), { state: "unreadable" }, "有行但零条可解析 → unreadable(不是 none)");
1168
- } finally {
1169
- close();
1170
- }
1171
- });
1172
-
1173
- // --- GET /memory/provenance:记忆级溯源读出口(#399 写、#421 读)-------------
1174
- // daemon 侧此前和宿主内 API 一样只有写入路径:库里有答案,外部拿不到。
1175
- //
1176
- // #509 评审整改:这个面吃 distillRecords.enabled(与写侧同一个开关、同一个判据),
1177
- // 关着时 409 {error:"distill-records-disabled"}。createStandaloneApi 的 config 缺省
1178
- // {},而 {} 在这道门上的含义就是「关」(fail-closed)——所以下面的用例必须显式把
1179
- // 开关打开,没有一个「默认开」的路径。
1180
- const RECORDS_ON = { distillRecords: { enabled: true } };
1181
-
1182
- test("GET /memory/provenance returns windows with their original rows", async () => {
1183
- const { base, auth, store, close } = await setup({ config: RECORDS_ON });
1184
- try {
1185
- const saved = await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1186
- const memoryId = saved.memory?.id ?? saved.id;
1187
- store.saveMemoryProvenance({
1188
- memoryId, sessionId: "s1", seqStart: 10, seqEnd: 11, createdAt: "2026-10-23T00:00:00Z"
1189
- });
1190
- store.saveDistillRecords([
1191
- { sessionId: "s1", seq: 10, role: "user", text: "第一句原文", windowId: "w1", distilledAt: "2026-10-23T00:00:00Z" },
1192
- { sessionId: "s1", seq: 11, role: "assistant", text: "第二句原文", windowId: "w1", distilledAt: "2026-10-23T00:00:00Z" }
1193
- ]);
1194
-
1195
- const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(memoryId)}`, { headers: auth });
1196
- assert.equal(res.status, 200);
1197
- const body = await res.json();
1198
- assert.equal(body.memoryId, memoryId);
1199
- assert.equal(body.windows.length, 1);
1200
- assert.equal(body.windows[0].session_id, "s1");
1201
- assert.deepEqual(body.windows[0].records.map((r) => r.text), ["第一句原文", "第二句原文"], "原文按 seq 升序");
1202
- } finally {
1203
- close();
1204
- }
1205
- });
1206
-
1207
- test("GET /memory/provenance: a memory with no link answers with empty windows, not an error", async () => {
1208
- const { base, auth, close } = await setup({ config: RECORDS_ON });
1209
- try {
1210
- const saved = await saveMemory(base, auth, { type: "preference", title: "语言", content: "中文" });
1211
- const memoryId = saved.memory?.id ?? saved.id;
1212
- const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(memoryId)}`, { headers: auth });
1213
- assert.equal(res.status, 200);
1214
- assert.deepEqual((await res.json()).windows, [], "「不是蒸馏来的」是有效答案,不是错误");
1215
- } finally {
1216
- close();
1217
- }
1218
- });
1219
-
1220
- test("GET /memory/provenance is auth-gated and 400s on a missing id", async () => {
1221
- const { base, auth, close } = await setup({ config: RECORDS_ON });
1222
- try {
1223
- const noToken = await fetch(`${base}/memory/provenance?id=x`);
1224
- assert.equal(noToken.status, 401, "只读端点也在 apiToken 之下(与 /memories 同口径)");
1225
-
1226
- const missing = await fetch(`${base}/memory/provenance`, { headers: auth });
1227
- assert.equal(missing.status, 400);
1228
- } finally {
1229
- close();
1230
- }
1231
- });
1232
-
1233
- test("GET /memory/provenance: distillRecords.enabled off answers 409, not 404 and not empty windows", async () => {
1234
- // #509 评审整改。四个刻度必须分开:401 没鉴权 / 400 缺 id / 409 用户关了 /
1235
- // 503 装配没接线 / 200 空 windows = 「这条记忆不是蒸馏来的」。把「关了」报成 404,
1236
- // 调用方会按本仓既有的「404 = 命名的东西不存在」(/memories/:id)读成「这条记忆
1237
- // 不存在」——而这两种误读的后续动作完全不同(一个去开开关,一个去查这条记忆)。
1238
- const { base, auth, close } = await setup({ config: { distillRecords: { enabled: false } } });
1239
- try {
1240
- const saved = await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1241
- const memoryId = saved.memory?.id ?? saved.id;
1242
- const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(memoryId)}`, { headers: auth });
1243
- assert.equal(res.status, 409);
1244
- assert.deepEqual(await res.json(), { error: "distill-records-disabled" }, "body 只准 error 一个键");
1245
- } finally {
1246
- close();
1247
- }
1248
- });
1249
-
1250
- test("GET /memory/provenance: no config at all is fail-closed (409)", async () => {
1251
- // 构造时不传 config(createStandaloneApi 的默认 {}):这个端点返回逐字原文,
1252
- // 默认方向必须是「不读」。别把 409 当 bug 修成默认开。
1253
- const { base, auth, close } = await setup();
1254
- try {
1255
- const res = await fetch(`${base}/memory/provenance?id=m1`, { headers: auth });
1256
- assert.equal(res.status, 409);
1257
- assert.deepEqual(await res.json(), { error: "distill-records-disabled" });
1258
- } finally {
1259
- close();
1260
- }
1261
- });
1262
-
1263
- test("GET /memory/provenance: 400 beats 409 and 409 is not an existence oracle", async () => {
1264
- const { base, auth, close } = await setup({ config: { distillRecords: { enabled: false } } });
1265
- try {
1266
- const missing = await fetch(`${base}/memory/provenance`, { headers: auth });
1267
- assert.equal(missing.status, 400, "缺 id 是语法畸形,排在功能开关之前");
1268
-
1269
- // 关着时已知 id 与未知 id 同一个答案,否则这个端点能用来枚举「哪些记忆有原文」。
1270
- const saved = await saveMemory(base, auth, { type: "preference", title: "语言", content: "中文" });
1271
- const known = saved.memory?.id ?? saved.id;
1272
- for (const id of [known, "nope"]) {
1273
- const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(id)}`, { headers: auth });
1274
- assert.equal(res.status, 409, `${id} → 409`);
1275
- assert.deepEqual(await res.json(), { error: "distill-records-disabled" });
1276
- }
1277
- } finally {
1278
- close();
1279
- }
1280
- });
1281
-
1282
- test("GET /memory/provenance: 409 beats 503 — feature off is more specific than unwired", async () => {
1283
- // 关着 + service 上连 distillRecordsFor 都没有(旧装配 / headless):报 503 会让人
1284
- // 去查一个没坏的部署。与 api.js:525-526 立的两段式同构。
1285
- const { base, auth, service, close } = await setup({ config: { distillRecords: { enabled: false } } });
1286
- try {
1287
- delete service.distillRecordsFor;
1288
- const res = await fetch(`${base}/memory/provenance?id=x`, { headers: auth });
1289
- assert.equal(res.status, 409);
1290
- assert.equal((await res.json()).error, "distill-records-disabled");
1291
- } finally {
1292
- close();
1293
- }
1294
- });
1295
-
1296
- // --- #524 方向 2:?sessionId=<sid> 列该会话的蒸馏窗口 -----------------------
1297
- // 与宿主内 API 是同一份口径(共用 provenance-http.js),这里只钉两张皮的那条差
1298
- // 异之外的部分真的走通了:一行一窗口、按 seq_start 排、truncated 说出来。
1299
- test("GET /memory/provenance?sessionId= lists a session's distill windows", async () => {
1300
- const { base, auth, store, close } = await setup({ config: RECORDS_ON });
1301
- try {
1302
- const a = await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite", importance: 5 });
1303
- const b = await saveMemory(base, auth, { type: "decision", title: "备选", content: "JSON 文件", importance: 3 });
1304
- const idA = a.memory?.id ?? a.id;
1305
- const idB = b.memory?.id ?? b.id;
1306
- // 同一窗口派生两条记忆:答复里必须并成一行(link_count=2),不是两行。
1307
- store.saveMemoryProvenance({ memoryId: idA, sessionId: "s1", seqStart: 10, seqEnd: 12, createdAt: "t2" });
1308
- store.saveMemoryProvenance({ memoryId: idB, sessionId: "s1", seqStart: 10, seqEnd: 12, createdAt: "t2" });
1309
- store.saveMemoryProvenance({ memoryId: idA, sessionId: "s1", seqStart: 1, seqEnd: 3, createdAt: "t1" });
1310
- store.saveMemoryProvenance({ memoryId: idA, sessionId: "s2", seqStart: 50, seqEnd: 51, createdAt: "t3" });
1311
-
1312
- const res = await fetch(`${base}/memory/provenance?sessionId=s1`, { headers: auth });
1313
- assert.equal(res.status, 200);
1314
- const body = await res.json();
1315
- assert.equal(body.sessionId, "s1");
1316
- assert.equal(body.memoryId, undefined, "两个方向的认领键不许同时出现");
1317
- assert.equal(body.truncated, false);
1318
- assert.deepEqual(body.windows.map((w) => [w.seq_start, w.seq_end]), [[1, 3], [10, 12]],
1319
- "同一 (seq_start, seq_end) 并成一行,按 seq_start 升序;别的会话的窗口不出现");
1320
- assert.deepEqual(body.windows.map((w) => w.link_count), [1, 2]);
1321
- } finally {
1322
- close();
1323
- }
1324
- });
1325
-
1326
- test("GET /memory/provenance: both selectors at once is 400, and limit is bounded", async () => {
1327
- const { base, auth, close } = await setup({ config: RECORDS_ON });
1328
- try {
1329
- const both = await fetch(`${base}/memory/provenance?id=m1&sessionId=s1`, { headers: auth });
1330
- assert.equal(both.status, 400, "两个主键都给不许静默择一");
1331
- assert.equal((await both.json()).error, "ambiguous-id");
1332
-
1333
- for (const bad of ["0", "-1", "1.5", "abc", "1e3", "101"]) {
1334
- const res = await fetch(`${base}/memory/provenance?sessionId=s1&limit=${bad}`, { headers: auth });
1335
- assert.equal(res.status, 400, `limit=${bad} 必须 400`);
1336
- assert.equal((await res.json()).error, "invalid-limit");
1337
- }
1338
-
1339
- const missing = await fetch(`${base}/memory/provenance`, { headers: auth });
1340
- assert.equal(missing.status, 400, "两个主键都缺仍是 400 missing-id");
1341
- } finally {
1342
- close();
1343
- }
1344
- });
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync } from "node:fs";
4
+ import { createStore } from "../src/store.js";
5
+ import { createService } from "../src/service.js";
6
+ import { createSettings } from "../src/settings.js";
7
+ import { createStandaloneApi, CONTEXT_DEGRADE_REASONS } from "../src/api-standalone.js";
8
+ import { PACKAGE_VERSION } from "../src/version-check.js";
9
+ import { Config, applyLightModePreset } from "../src/config.js";
10
+
11
+ // Real HTTP server on an OS-assigned port (port: 0), driven with fetch.
12
+ // `logger` 可传(默认 null):#383 的降级原因只进 daemon stderr 那行 warn、不进响应体,
13
+ // 不接住 logger 就观测不到它——而「日志值 ∈ 枚举」正是 #508 Minor 唯一的可观测效应,
14
+ // 也是它当初能溜进来的原因(没有任何测试看过那行日志)。
15
+ async function setup({ config = {}, embedder = null, embedTimeoutMs, logger = null } = {}) {
16
+ const store = createStore(":memory:");
17
+ const service = createService({ store, mirror: null, config });
18
+ const settings = createSettings(store.db);
19
+ const api = createStandaloneApi({ service, store, config, settings, logger, port: 0, embedder, embedTimeoutMs });
20
+ await api.ready;
21
+ const base = `http://127.0.0.1:${api.port}`;
22
+ const auth = { authorization: `Bearer ${api.token}` };
23
+ return {
24
+ store,
25
+ service,
26
+ settings,
27
+ api,
28
+ base,
29
+ auth,
30
+ close: () => {
31
+ // Drop pooled keep-alive sockets so node --test can drain the loop.
32
+ api.server.closeIdleConnections?.();
33
+ api.server.close();
34
+ store.close();
35
+ }
36
+ };
37
+ }
38
+
39
+ // --- auth ---------------------------------------------------------------------
40
+
41
+ test("GET /health is open without a token; every other route 401s", async () => {
42
+ const { base, close } = await setup();
43
+ try {
44
+ const health = await fetch(`${base}/health`);
45
+ assert.equal(health.status, 200);
46
+ assert.deepEqual(await health.json(), { ok: true });
47
+
48
+ for (const path of ["/status", "/profile", "/rules", "/memories", "/memories/x", "/search?q=x", "/context"]) {
49
+ const res = await fetch(`${base}${path}`);
50
+ assert.equal(res.status, 401, `${path} requires a token`);
51
+ assert.deepEqual(await res.json(), { error: "unauthorized" });
52
+ }
53
+
54
+ const bad = await fetch(`${base}/status`, { headers: { authorization: "Bearer wrong-token" } });
55
+ assert.equal(bad.status, 401, "wrong token rejected");
56
+ } finally {
57
+ close();
58
+ }
59
+ });
60
+
61
+ test("GET /profile and /rules return saved settings", async () => {
62
+ const { base, auth, settings, close } = await setup();
63
+ try {
64
+ settings.setProfile("我是后端工程师");
65
+ settings.setRules(["先验证再修改", "默认使用中文回复"]);
66
+
67
+ const profile = await fetch(`${base}/profile`, { headers: auth });
68
+ assert.equal(profile.status, 200);
69
+ assert.deepEqual(await profile.json(), { profile: "我是后端工程师" });
70
+
71
+ const rules = await fetch(`${base}/rules`, { headers: auth });
72
+ assert.equal(rules.status, 200);
73
+ assert.deepEqual(await rules.json(), { rules: ["先验证再修改", "默认使用中文回复"] });
74
+ } finally {
75
+ close();
76
+ }
77
+ });
78
+
79
+ test("GET /profile and /rules return empty values when unset", async () => {
80
+ const { base, auth, close } = await setup();
81
+ try {
82
+ const profile = await fetch(`${base}/profile`, { headers: auth });
83
+ assert.equal(profile.status, 200);
84
+ assert.deepEqual(await profile.json(), { profile: "" });
85
+
86
+ const rules = await fetch(`${base}/rules`, { headers: auth });
87
+ assert.equal(rules.status, 200);
88
+ assert.deepEqual(await rules.json(), { rules: [] });
89
+ } finally {
90
+ close();
91
+ }
92
+ });
93
+
94
+ test("token is persisted into settings kv and reused across restarts", async () => {
95
+ const store = createStore(":memory:");
96
+ const service = createService({ store, mirror: null, config: {} });
97
+ const settings = createSettings(store.db);
98
+ const first = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
99
+ await first.ready;
100
+ try {
101
+ assert.equal(settings.getExternalApi().token, first.token, "generated token persisted");
102
+ assert.ok(first.token.length >= 20, "token is a real random value");
103
+ const second = createStandaloneApi({ service, store, config: {}, settings, port: 0 });
104
+ await second.ready;
105
+ assert.equal(second.token, first.token, "restart reuses the persisted token");
106
+ second.server.closeIdleConnections?.();
107
+ second.server.close();
108
+ } finally {
109
+ first.server.closeIdleConnections?.();
110
+ first.server.close();
111
+ store.close();
112
+ }
113
+ });
114
+
115
+ // --- CRUD loop ------------------------------------------------------------------
116
+
117
+ test("POST/GET/DELETE /memories round trip", async () => {
118
+ const { base, auth, close } = await setup();
119
+ try {
120
+ const post = await fetch(`${base}/memories`, {
121
+ method: "POST",
122
+ headers: { ...auth, "content-type": "application/json" },
123
+ body: JSON.stringify({ type: "preference", title: "语言", content: "始终用中文回复", importance: 4, tags: ["交流"] })
124
+ });
125
+ assert.equal(post.status, 201);
126
+ const created = await post.json();
127
+ assert.ok(created.id, "row id returned");
128
+ assert.equal(created.title, "语言");
129
+ assert.equal(created.importance, 4);
130
+
131
+ const list = await fetch(`${base}/memories?limit=10`, { headers: auth });
132
+ assert.equal(list.status, 200);
133
+ const listBody = await list.json();
134
+ assert.equal(listBody.total, 1);
135
+ assert.equal(listBody.items.length, 1);
136
+
137
+ const got = await fetch(`${base}/memories/${created.id}`, { headers: auth });
138
+ assert.equal(got.status, 200);
139
+ assert.equal((await got.json()).content, "始终用中文回复");
140
+
141
+ const del = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
142
+ assert.equal(del.status, 200);
143
+ assert.deepEqual(await del.json(), { ok: true });
144
+
145
+ const gone = await fetch(`${base}/memories/${created.id}`, { headers: auth });
146
+ assert.equal(gone.status, 404, "deleted row reads back as 404");
147
+ const delAgain = await fetch(`${base}/memories/${created.id}`, { method: "DELETE", headers: auth });
148
+ assert.equal(delAgain.status, 404, "deleting a missing row is 404, not a fake ok");
149
+ } finally {
150
+ close();
151
+ }
152
+ });
153
+
154
+ test("POST /memories dedupes same title within a type (200 + merged content)", async () => {
155
+ const { base, auth, close } = await setup();
156
+ try {
157
+ const first = await fetch(`${base}/memories`, {
158
+ method: "POST",
159
+ headers: { ...auth, "content-type": "application/json" },
160
+ body: JSON.stringify({ type: "project", title: "mneme", content: "v1 内容" })
161
+ });
162
+ assert.equal(first.status, 201);
163
+ const row1 = await first.json();
164
+
165
+ const second = await fetch(`${base}/memories`, {
166
+ method: "POST",
167
+ headers: { ...auth, "content-type": "application/json" },
168
+ body: JSON.stringify({ type: "project", title: "mneme", content: "v2 追加" })
169
+ });
170
+ assert.equal(second.status, 200, "merge, not a second creation");
171
+ const row2 = await second.json();
172
+ assert.equal(row2.id, row1.id, "same row reused");
173
+ assert.ok(row2.content.includes("v1 内容") && row2.content.includes("v2 追加"), "content appended");
174
+
175
+ const list = await fetch(`${base}/memories`, { headers: auth });
176
+ assert.equal((await list.json()).total, 1, "no duplicate row created");
177
+ } finally {
178
+ close();
179
+ }
180
+ });
181
+
182
+ test("POST /memories validation: invalid type, bad JSON, non-array tags → 400", async () => {
183
+ const { base, auth, close } = await setup();
184
+ try {
185
+ const badType = await fetch(`${base}/memories`, {
186
+ method: "POST",
187
+ headers: { ...auth, "content-type": "application/json" },
188
+ body: JSON.stringify({ type: "diary", title: "t", content: "c" })
189
+ });
190
+ assert.equal(badType.status, 400);
191
+ assert.deepEqual(await badType.json(), { error: "invalid-type" });
192
+
193
+ const badJson = await fetch(`${base}/memories`, {
194
+ method: "POST",
195
+ headers: { ...auth, "content-type": "application/json" },
196
+ body: "{not json"
197
+ });
198
+ assert.equal(badJson.status, 400);
199
+ assert.deepEqual(await badJson.json(), { error: "invalid-json" });
200
+
201
+ const badTags = await fetch(`${base}/memories`, {
202
+ method: "POST",
203
+ headers: { ...auth, "content-type": "application/json" },
204
+ body: JSON.stringify({ type: "project", title: "t", content: "c", tags: "x" })
205
+ });
206
+ assert.equal(badTags.status, 400);
207
+ assert.deepEqual(await badTags.json(), { error: "tags-must-be-an-array" });
208
+
209
+ const noTitle = await fetch(`${base}/memories`, {
210
+ method: "POST",
211
+ headers: { ...auth, "content-type": "application/json" },
212
+ body: JSON.stringify({ type: "project", content: "c" })
213
+ });
214
+ assert.equal(noTitle.status, 400);
215
+ assert.deepEqual(await noTitle.json(), { error: "missing-title" });
216
+ } finally {
217
+ close();
218
+ }
219
+ });
220
+
221
+ // --- list filters / status / search ---------------------------------------------
222
+
223
+ test("GET /memories honors type + minImportance filters and paging", async () => {
224
+ const { base, auth, service, close } = await setup();
225
+ try {
226
+ service.saveWithDedupe({ type: "preference", title: "低", content: "i2", importance: 2 });
227
+ service.saveWithDedupe({ type: "preference", title: "高", content: "i5", importance: 5 });
228
+ service.saveWithDedupe({ type: "project", title: "项目", content: "i4", importance: 4 });
229
+
230
+ const byType = await fetch(`${base}/memories?type=preference`, { headers: auth });
231
+ assert.equal((await byType.json()).total, 2);
232
+
233
+ const byImportance = await fetch(`${base}/memories?minImportance=4`, { headers: auth });
234
+ const filtered = await byImportance.json();
235
+ assert.equal(filtered.total, 2);
236
+ assert.deepEqual(filtered.items.map((m) => m.title).sort(), ["项目", "高"]);
237
+
238
+ const paged = await fetch(`${base}/memories?limit=2&offset=0&order=chrono`, { headers: auth });
239
+ const page = await paged.json();
240
+ assert.equal(page.items.length, 2);
241
+ assert.equal(page.total, 3);
242
+ } finally {
243
+ close();
244
+ }
245
+ });
246
+
247
+ test("GET /status reports version, per-type totals, entities and uptime", async () => {
248
+ const { base, auth, service, close } = await setup();
249
+ try {
250
+ service.saveWithDedupe({ type: "preference", title: "p", content: "c" });
251
+ service.saveWithDedupe({ type: "project", title: "j", content: "c" });
252
+ service.saveWithDedupe({ type: "project", title: "j2", content: "c" });
253
+
254
+ const res = await fetch(`${base}/status`, { headers: auth });
255
+ assert.equal(res.status, 200);
256
+ const body = await res.json();
257
+ // 回归锁:/status 的版本必须来自 package.json(PACKAGE_VERSION),不是散落的
258
+ // 字面量——曾经此处硬编码常量在发版时漏 bump,运行 0.8.13 却对外报 0.7.12。
259
+ assert.equal(body.version, PACKAGE_VERSION);
260
+ assert.equal(body.memories.total, 3);
261
+ assert.equal(body.memories.byType.preference, 1);
262
+ assert.equal(body.memories.byType.project, 2);
263
+ assert.equal(body.entities, 0, "no extraction wired → empty entity table");
264
+ assert.ok(Number.isInteger(body.uptime_s));
265
+ } finally {
266
+ close();
267
+ }
268
+ });
269
+
270
+ test("GET /search finds saved memories; empty q returns empty keyword result", async () => {
271
+ const { base, auth, close } = await setup();
272
+ try {
273
+ await fetch(`${base}/memories`, {
274
+ method: "POST",
275
+ headers: { ...auth, "content-type": "application/json" },
276
+ body: JSON.stringify({ type: "project", title: "记忆插件", content: "SQLite 全文检索" })
277
+ });
278
+
279
+ const res = await fetch(`${base}/search?q=${encodeURIComponent("全文检索")}&mode=keyword`, { headers: auth });
280
+ assert.equal(res.status, 200);
281
+ const body = await res.json();
282
+ assert.equal(body.mode, "keyword");
283
+ assert.equal(body.items.length, 1);
284
+ assert.equal(body.items[0].title, "记忆插件");
285
+
286
+ const empty = await fetch(`${base}/search?q=`, { headers: auth });
287
+ assert.deepEqual(await empty.json(), { items: [], mode: "keyword" });
288
+ } finally {
289
+ close();
290
+ }
291
+ });
292
+
293
+ test("unknown path returns 404 json", async () => {
294
+ const { base, auth, close } = await setup();
295
+ try {
296
+ const res = await fetch(`${base}/nope`, { headers: auth });
297
+ assert.equal(res.status, 404);
298
+ assert.deepEqual(await res.json(), { error: "not-found" });
299
+ } finally {
300
+ close();
301
+ }
302
+ });
303
+
304
+ // --- light-mode preset (applyLightModePreset) ------------------------------------
305
+
306
+ const LIGHT_OFF_FIELDS = [
307
+ "entityExtractionEnabled",
308
+ "autoDream",
309
+ "sleepModeEnabled",
310
+ "rerankEnabled",
311
+ "autoReindexOnBoot",
312
+ "hybridInject",
313
+ "searchSemanticDedup",
314
+ "selectiveInjectEnabled",
315
+ "bm25SearchEnabled"
316
+ ];
317
+
318
+ test("applyLightModePreset turns heavy features off and keeps the core loop", () => {
319
+ const cfg = applyLightModePreset(Config({ lightMode: true }));
320
+ for (const field of LIGHT_OFF_FIELDS) {
321
+ assert.equal(cfg[field], false, `${field} forced off in light mode`);
322
+ }
323
+ // Core loop preserved.
324
+ assert.equal(cfg.autoInject, true);
325
+ assert.equal(cfg.autoSummarize, true);
326
+ assert.equal(cfg.hotMemoryEnabled, true);
327
+ assert.equal(cfg.memoryQualityFilter.enabled, true);
328
+ // Unrelated knobs untouched.
329
+ assert.equal(cfg.dreamThresholdCount, 10);
330
+ assert.equal(cfg.dreamDelayMs, 2000);
331
+ assert.equal(cfg.maxInjectedItems, 5);
332
+ });
333
+
334
+ test("applyLightModePreset keeps explicit non-preset values and is a no-op without lightMode", () => {
335
+ const tuned = applyLightModePreset(Config({ lightMode: true, dreamThresholdCount: 30, maxInjectedItems: 8 }));
336
+ assert.equal(tuned.dreamThresholdCount, 30, "operator values survive the preset");
337
+ assert.equal(tuned.maxInjectedItems, 8);
338
+
339
+ const plain = Config({});
340
+ assert.equal(applyLightModePreset(plain), plain, "identity when lightMode is unset");
341
+ const off = Config({ lightMode: false });
342
+ assert.equal(applyLightModePreset(off), off, "identity when lightMode is false");
343
+ });
344
+
345
+ test("persisted panel_mode=light wins over a bundle config that did not ask for it", () => {
346
+ const store = createStore(":memory:");
347
+ const settings = createSettings(store.db);
348
+ try {
349
+ // Panel switched to light in a previous session; bundle config says nothing.
350
+ settings.setPanelMode("light");
351
+ const rawCfg = Config({});
352
+ const lightMode = rawCfg.lightMode === true || settings.getPanelMode() === "light";
353
+ const cfg = applyLightModePreset({ ...rawCfg, lightMode });
354
+ assert.equal(lightMode, true, "persisted mode forces light");
355
+ assert.equal(cfg.autoDream, false);
356
+ assert.equal(cfg.entityExtractionEnabled, false);
357
+ assert.equal(cfg.autoInject, true, "core injection stays on");
358
+
359
+ // standard (default) never forces the preset even with a light bundle flag off.
360
+ settings.setPanelMode("standard");
361
+ const raw2 = Config({});
362
+ assert.equal(raw2.lightMode === true || settings.getPanelMode() === "light", false);
363
+ } finally {
364
+ store.close();
365
+ }
366
+ });
367
+
368
+ // --- #181:MCP 六件套的 API 面(PUT / save 透传 / archived 与 occurred 窗口)---
369
+
370
+ test("PUT /memories/:id patches fields and returns the DTO (unauthorized without token)", async () => {
371
+ const { base, auth, service, close } = await setup();
372
+ try {
373
+ const created = await (await fetch(`${base}/memories`, {
374
+ method: "POST",
375
+ headers: { ...auth, "content-type": "application/json" },
376
+ body: JSON.stringify({ type: "preference", title: "编辑器", content: "用 vim", importance: 3 })
377
+ })).json();
378
+
379
+ const noAuth = await fetch(`${base}/memories/${created.id}`, {
380
+ method: "PUT",
381
+ headers: { "content-type": "application/json" },
382
+ body: JSON.stringify({ content: "用 nvim" })
383
+ });
384
+ assert.equal(noAuth.status, 401, "PUT requires the Bearer token");
385
+
386
+ const put = await fetch(`${base}/memories/${created.id}`, {
387
+ method: "PUT",
388
+ headers: { ...auth, "content-type": "application/json" },
389
+ body: JSON.stringify({ content: "用 nvim", importance: 4, tags: ["工具"], reason: "用户改用 nvim 了" })
390
+ });
391
+ assert.equal(put.status, 200);
392
+ const { memory } = await put.json();
393
+ assert.equal(memory.content, "用 nvim");
394
+ assert.equal(memory.importance, 4);
395
+ assert.deepEqual(memory.tags, ["工具"]);
396
+
397
+ // content 改写按 human_override 入档(与内部面板写路径一致)。
398
+ const raw = service.getById(created.id);
399
+ assert.equal(raw.content_history?.[0]?.source, "human_override");
400
+ assert.equal(raw.content_history?.[0]?.content, "用 vim");
401
+ } finally {
402
+ close();
403
+ }
404
+ });
405
+
406
+ test("PUT /memories/:id validation: bad fields → 400, empty patch → 400, missing id → 404", async () => {
407
+ const { base, auth, close } = await setup();
408
+ try {
409
+ const put = (body, id = "whatever") => fetch(`${base}/memories/${id}`, {
410
+ method: "PUT",
411
+ headers: { ...auth, "content-type": "application/json" },
412
+ body: JSON.stringify(body)
413
+ });
414
+ assert.equal((await put({ title: "" })).status, 400);
415
+ assert.equal((await put({ importance: 9 })).status, 400);
416
+ assert.equal((await put({ tags: "x" })).status, 400);
417
+ assert.equal((await put({ type: "nope" })).status, 400);
418
+ assert.equal((await put({})).status, 400, "empty patch is no-fields");
419
+ assert.equal((await put({ content: "x" }, "missing-id")).status, 404);
420
+ assert.equal((await put({ agent_scope: 5 })).status, 400);
421
+ } finally {
422
+ close();
423
+ }
424
+ });
425
+
426
+ test("PUT /memories/:id surfaces service failures as 500 instead of a hung request", async () => {
427
+ const { base, auth, service, close } = await setup();
428
+ try {
429
+ const created = await (await fetch(`${base}/memories`, {
430
+ method: "POST",
431
+ headers: { ...auth, "content-type": "application/json" },
432
+ body: JSON.stringify({ type: "preference", title: "会抛错", content: "v1" })
433
+ })).json();
434
+ const original = service.update;
435
+ service.update = () => { throw new Error("boom"); };
436
+ try {
437
+ const res = await fetch(`${base}/memories/${created.id}`, {
438
+ method: "PUT",
439
+ headers: { ...auth, "content-type": "application/json" },
440
+ body: JSON.stringify({ content: "v2" })
441
+ });
442
+ assert.equal(res.status, 500, "service throw must not strand the request");
443
+ assert.deepEqual(await res.json(), { error: "internal" });
444
+ } finally {
445
+ service.update = original;
446
+ }
447
+ } finally {
448
+ close();
449
+ }
450
+ });
451
+
452
+ test("POST /memories passes through sensitivity/occurred_at/scope and returns action", async () => {
453
+ const { base, auth, close } = await setup();
454
+ try {
455
+ const post = await fetch(`${base}/memories`, {
456
+ method: "POST",
457
+ headers: { ...auth, "content-type": "application/json" },
458
+ body: JSON.stringify({
459
+ type: "decision",
460
+ title: "迁移",
461
+ content: "迁到 sqlite 分支",
462
+ sensitivity: "personal",
463
+ occurred_at: "2026-01-15T10:00:00Z",
464
+ agent_scope: "global"
465
+ })
466
+ });
467
+ assert.equal(post.status, 201);
468
+ const created = await post.json();
469
+ assert.equal(created.action, "created", "action rides along for tool parity");
470
+ assert.equal(created.sensitivity, "personal");
471
+ // store 把 ISO 瞬时归一化成完整毫秒形式(2026-01-15T10:00:00Z → …T10:00:00.000Z)。
472
+ assert.match(created.occurred_at, /^2026-01-15T10:00:00/);
473
+ assert.equal(created.agent_scope, "global");
474
+ assert.equal(created.agent_scope_source, "explicit");
475
+
476
+ // 合并判据=同 type + 同标题 + 同 sensitivity + 同作用域三元(0.8.0 起去重键
477
+ // 含 scope,跨作用域同标题本就分开存):补齐 agent_scope 才 merged。
478
+ const merged = await (await fetch(`${base}/memories`, {
479
+ method: "POST",
480
+ headers: { ...auth, "content-type": "application/json" },
481
+ body: JSON.stringify({ type: "decision", title: "迁移", content: "迁到 sqlite 分支(更新)", sensitivity: "personal", agent_scope: "global" })
482
+ })).json();
483
+ assert.equal(merged.action, "merged", "same dedupe key reports merged");
484
+
485
+ const separate = await (await fetch(`${base}/memories`, {
486
+ method: "POST",
487
+ headers: { ...auth, "content-type": "application/json" },
488
+ body: JSON.stringify({ type: "decision", title: "迁移", content: "无标注版本" })
489
+ })).json();
490
+ assert.equal(separate.action, "created", "no sensitivity/scope → different dedupe key");
491
+
492
+ const bad = await fetch(`${base}/memories`, {
493
+ method: "POST",
494
+ headers: { ...auth, "content-type": "application/json" },
495
+ body: JSON.stringify({ type: "decision", title: "x", content: "y", sensitivity: 5 })
496
+ });
497
+ assert.equal(bad.status, 400);
498
+ assert.equal((await bad.json()).error, "invalid-sensitivity");
499
+ } finally {
500
+ close();
501
+ }
502
+ });
503
+
504
+ test("GET /memories supports include_archived and the occurred_at window", async () => {
505
+ const { base, auth, service, close } = await setup();
506
+ try {
507
+ const save = (title, occurredAt) => fetch(`${base}/memories`, {
508
+ method: "POST",
509
+ headers: { ...auth, "content-type": "application/json" },
510
+ body: JSON.stringify({ type: "history", title, content: `body of ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
511
+ });
512
+ const january = await (await save("一月的事", "2026-01-15T10:00:00Z")).json();
513
+ await save("二月的事", "2026-02-15T10:00:00Z");
514
+ await save("无时间戳的事", null);
515
+
516
+ const february = await (await fetch(`${base}/memories?occurred_from=2026-02-01`, { headers: auth })).json();
517
+ // 「无时间戳的事」按 occurred_at→created_at 回退(写入日 2026-09),落在窗口内。
518
+ assert.deepEqual(february.items.map((m) => m.title).sort(), ["二月的事", "无时间戳的事"]);
519
+ assert.equal(february.total, 2, "total honors the same window");
520
+
521
+ const upToJanuary = await (await fetch(`${base}/memories?occurred_to=2026-01-31`, { headers: auth })).json();
522
+ assert.deepEqual(upToJanuary.items.map((m) => m.title), ["一月的事"]);
523
+
524
+ service.setArchived(january.id, true);
525
+ const active = await (await fetch(`${base}/memories`, { headers: auth })).json();
526
+ assert.equal(active.total, 2, "archived rows stay hidden by default");
527
+ const withArchived = await (await fetch(`${base}/memories?include_archived=true`, { headers: auth })).json();
528
+ assert.equal(withArchived.total, 3, "include_archived=true surfaces archived rows");
529
+ } finally {
530
+ close();
531
+ }
532
+ });
533
+
534
+ test("GET /memories carries typeCounts: the full distribution without the type filter (#597)", async () => {
535
+ const { base, auth, service, close } = await setup();
536
+ try {
537
+ service.saveWithDedupe({ type: "preference", title: "p", content: "c" });
538
+ service.saveWithDedupe({ type: "project", title: "j1", content: "c" });
539
+ service.saveWithDedupe({ type: "project", title: "j2", content: "c" });
540
+
541
+ // total 跟着 type 筛;typeCounts 是同一份筛选、**不带 type** 的分布——
542
+ // 选中一类时其它类的数字仍在(面板分类栏不再塌剩两枚)。
543
+ const filtered = await (await fetch(`${base}/memories?type=project`, { headers: auth })).json();
544
+ assert.equal(filtered.total, 2, "total honors the type filter");
545
+ assert.deepEqual(filtered.typeCounts, { preference: 1, project: 2 }, "distribution ignores the type filter");
546
+
547
+ const all = await (await fetch(`${base}/memories`, { headers: auth })).json();
548
+ assert.equal(
549
+ Object.keys(all.typeCounts).reduce((n, k) => n + all.typeCounts[k], 0),
550
+ all.total,
551
+ "distribution sums to the unfiltered total"
552
+ );
553
+ } finally {
554
+ close();
555
+ }
556
+ });
557
+
558
+ test("GET /search honors the occurred_at window", async () => {
559
+ const { base, auth, close } = await setup();
560
+ try {
561
+ const save = (title, occurredAt) => fetch(`${base}/memories`, {
562
+ method: "POST",
563
+ headers: { ...auth, "content-type": "application/json" },
564
+ body: JSON.stringify({ type: "history", title, content: `记忆星球 ${title}`, ...(occurredAt ? { occurred_at: occurredAt } : {}) })
565
+ });
566
+ await save("旧事", "2026-01-15T10:00:00Z");
567
+ await save("新事", "2026-03-15T10:00:00Z");
568
+
569
+ const hit = await (await fetch(`${base}/search?q=${encodeURIComponent("记忆星球")}&occurred_from=2026-03-01`, { headers: auth })).json();
570
+ assert.equal(hit.items.length, 1);
571
+ assert.equal(hit.items[0].title, "新事");
572
+ } finally {
573
+ close();
574
+ }
575
+ });
576
+
577
+ // --- GET /context(issue #370,#363 承诺)---------------------------------------
578
+
579
+ /** /context 用例的省事入库:走 POST /memories,与第三方调用同路径。 */
580
+ async function saveMemory(base, auth, body) {
581
+ const res = await fetch(`${base}/memories`, {
582
+ method: "POST",
583
+ headers: { ...auth, "content-type": "application/json" },
584
+ body: JSON.stringify(body)
585
+ });
586
+ assert.ok(res.status === 201 || res.status === 200, `save ${body.title} → ${res.status}`);
587
+ return res.json();
588
+ }
589
+
590
+ test("GET /search passes a declared scope through (strictScope hard wall on the search face too)", async () => {
591
+ // issue #370:searchMemories 本就收 scope,8790 此前没有入口——透传后第三方
592
+ // 声明身份,A2 软加权与 strictScope 硬过滤在检索面同样成立;不传参数行为
593
+ // 与既往逐字节一致(scopeFromSearchParams 返回 undefined → 不进 options)。
594
+ const { base, auth, close } = await setup({ config: { strictScope: true } });
595
+ try {
596
+ await saveMemory(base, auth, { type: "decision", title: "他域检索", content: "外部线索 abc", importance: 5, agent_scope: "other-agent" });
597
+
598
+ const scoped = await (await fetch(`${base}/search?q=${encodeURIComponent("外部线索")}&agent_scope=me`, { headers: auth })).json();
599
+ assert.ok(!scoped.items.some((m) => m.title === "他域检索"), "explicit foreign agent_scope row is hard-filtered");
600
+
601
+ const unscoped = await (await fetch(`${base}/search?q=${encodeURIComponent("外部线索")}`, { headers: auth })).json();
602
+ assert.ok(unscoped.items.some((m) => m.title === "他域检索"), "no scope declared → gate dormant, behavior unchanged");
603
+ } finally {
604
+ close();
605
+ }
606
+ });
607
+
608
+ test("GET /context returns the injection-shaped aggregate; empty q still serves the rule tier", async () => {
609
+ const { base, auth, settings, close } = await setup();
610
+ try {
611
+ settings.setProfile("我是后端工程师");
612
+ settings.setRules(["先验证再修改"]);
613
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
614
+ await saveMemory(base, auth, { type: "preference", title: "默认中文", content: "回复默认用中文", importance: 4 });
615
+
616
+ const res = await fetch(`${base}/context`, { headers: auth });
617
+ assert.equal(res.status, 200);
618
+ const body = await res.json();
619
+ // 形状锁:五键响应——bridge 等调用方按这些键渲染,漂移(加塞/漏带)在此变红。
620
+ // #383 新增 tier(档位信号);空 q 时语义路未启用,报 unknown 而不是 full。
621
+ // 注意 unknown **不只**是空 q:#508 之后「维度探针没跑成」与「有行但一条向量都读
622
+ // 不出来」也落这里(判不出来就不宣称 full)——三态不变,unknown 的生产者多了两个。
623
+ assert.deepEqual(Object.keys(body).sort(), ["items", "pinnedCount", "profile", "rules", "tier"]);
624
+ assert.equal(typeof body.tier, "string", "tier 必填");
625
+ assert.equal(body.tier, "unknown", "空 q = 语义路未启用,不宣称档位(fail-closed,不报 full)");
626
+ assert.equal(body.profile, "我是后端工程师");
627
+ assert.deepEqual(body.rules, ["先验证再修改"]);
628
+ assert.equal(body.pinnedCount, 0, "pinnedInjectBudget 默认 0(opt-in 纪律,issue #370 取舍 3)");
629
+ const titles = body.items.map((m) => m.title);
630
+ assert.ok(titles.includes("核心决策") && titles.includes("默认中文"), "empty q → pure rule tier, high-importance rows still served");
631
+ for (const item of body.items) {
632
+ assert.ok(item.id && item.type && item.title && typeof item.content === "string" && Number.isInteger(item.importance));
633
+ }
634
+ } finally {
635
+ close();
636
+ }
637
+ });
638
+
639
+ test("GET /context threshold is an importance gate (not /search's similarity threshold)", async () => {
640
+ // 同名不同义锁(issue #370 点名的文档区分):/context 的 threshold 走
641
+ // injectCandidates 的 importance 门(summary/preference 豁免),与相似度无关
642
+ // ——本用例全程无 embedder/向量,纯规则档即可验证。
643
+ const { base, auth, close } = await setup();
644
+ try {
645
+ await saveMemory(base, auth, { type: "decision", title: "低重要", content: "小事一桩", importance: 3 });
646
+ await saveMemory(base, auth, { type: "decision", title: "高重要", content: "大事记", importance: 5 });
647
+
648
+ const open = await (await fetch(`${base}/context`, { headers: auth })).json();
649
+ const openTitles = open.items.map((m) => m.title);
650
+ assert.ok(openTitles.includes("低重要") && openTitles.includes("高重要"), "default threshold=3 admits both");
651
+
652
+ const gated = await (await fetch(`${base}/context?threshold=4`, { headers: auth })).json();
653
+ const gatedTitles = gated.items.map((m) => m.title);
654
+ assert.ok(gatedTitles.includes("高重要"), "importance 5 survives threshold=4");
655
+ assert.ok(!gatedTitles.includes("低重要"), "importance 3 is gated out at threshold=4");
656
+ } finally {
657
+ close();
658
+ }
659
+ });
660
+
661
+ test("GET /context pins preference rows ahead when pinnedInjectBudget is on", async () => {
662
+ // #249 pin 池经 8790 透出。用 preference 而非 constraint:constraint 属编码
663
+ // 记忆,非编码查询被 codingGate 排除在候选池外,pin 池也够不着它。
664
+ const { base, auth, close } = await setup({ config: { pinnedInjectBudget: 2 } });
665
+ try {
666
+ await saveMemory(base, auth, { type: "preference", title: "pin-偏好", content: "永远先讲结论", importance: 5 });
667
+ await saveMemory(base, auth, { type: "decision", title: "普通决策", content: "先做 A 再做 B", importance: 5 });
668
+
669
+ const body = await (await fetch(`${base}/context`, { headers: auth })).json();
670
+ assert.equal(body.items[0].title, "pin-偏好", "pinned row leads the block");
671
+ assert.equal(body.pinnedCount, 1);
672
+ } finally {
673
+ close();
674
+ }
675
+ });
676
+
677
+ test("GET /context honors a declared scope under strictScope; undeclared stays unfiltered", async () => {
678
+ // scope 语义锁(issue #370):声明身份 → strictScope 硬过滤按 isVisibleInScope
679
+ // 生效;不声明 → scope=null,门不触发(与宿主「会话身份取不到时两维为 null」
680
+ // 同构)。任一维声明而另一维缺省时,缺维按解析不到走 fail-closed。
681
+ const { base, auth, close } = await setup({ config: { strictScope: true } });
682
+ try {
683
+ await saveMemory(base, auth, { type: "decision", title: "他域决策", content: "别的 agent 的事", importance: 5, agent_scope: "other-agent" });
684
+ await saveMemory(base, auth, { type: "decision", title: "全域决策", content: "谁都可见", importance: 5 });
685
+
686
+ const declared = await (await fetch(`${base}/context?agent_scope=me`, { headers: auth })).json();
687
+ const declaredTitles = declared.items.map((m) => m.title);
688
+ assert.ok(!declaredTitles.includes("他域决策"), "explicit foreign agent_scope row is hard-filtered");
689
+ assert.ok(declaredTitles.includes("全域决策"));
690
+
691
+ const undeclared = await (await fetch(`${base}/context`, { headers: auth })).json();
692
+ const undeclaredTitles = undeclared.items.map((m) => m.title);
693
+ assert.ok(undeclaredTitles.includes("他域决策"), "no declared scope → no gate");
694
+ } finally {
695
+ close();
696
+ }
697
+ });
698
+
699
+ test("GET /context embeds the query via the injected embedder (wiring lock)", async () => {
700
+ // embedder 接线锁(issue #370):createStandaloneApi 新增的可选 embedder 必须
701
+ // 真被 /context 用上——宿主与 daemon 传的都是 semantic 装配的同一实例。
702
+ const calls = [];
703
+ const fake = {
704
+ ready: true,
705
+ modelHash: "fake-hash-1",
706
+ dimension: 4,
707
+ embedSingle: async (text) => {
708
+ calls.push(text);
709
+ return [1, 0, 0, 0];
710
+ }
711
+ };
712
+ const { base, auth, close } = await setup({ embedder: fake });
713
+ try {
714
+ const res = await fetch(`${base}/context?q=${encodeURIComponent("语义查询")}`, { headers: auth });
715
+ assert.equal(res.status, 200);
716
+ await res.json();
717
+ assert.deepEqual(calls, ["语义查询"], "the route must hand the query to the injected embedder");
718
+ } finally {
719
+ close();
720
+ }
721
+ });
722
+
723
+ test("GET /context survives a throwing embedder (rule-tier degradation, never 500)", async () => {
724
+ const { base, auth, close } = await setup({
725
+ embedder: { ready: true, embedSingle: async () => { throw new Error("model offline"); } }
726
+ });
727
+ try {
728
+ await saveMemory(base, auth, { type: "decision", title: "降级存照", content: "嵌入挂了也要有注入", importance: 5 });
729
+ const res = await fetch(`${base}/context?q=任意`, { headers: auth });
730
+ assert.equal(res.status, 200, "embed failure must degrade to the rule tier");
731
+ const body = await res.json();
732
+ assert.ok(body.items.some((m) => m.title === "降级存照"));
733
+ } finally {
734
+ close();
735
+ }
736
+ });
737
+
738
+ test("GET /context times out a hung embedder and degrades (embedTimeoutMs guard)", async () => {
739
+ // CodeRabbit on #371:embedder 挂起(不抛错,典型为第三方 ollama/openai 端点
740
+ // 无响应)不能占住 HTTP 连接——超时按嵌入缺失降级规则档。测试用 50ms 短超时
741
+ // 避免慢测试;生产默认 3000 由工厂选项约束(同 strictPort,不进 config schema)。
742
+ const { base, auth, close } = await setup({
743
+ embedTimeoutMs: 50,
744
+ embedder: { ready: true, embedSingle: () => new Promise(() => {}) }
745
+ });
746
+ try {
747
+ await saveMemory(base, auth, { type: "decision", title: "挂起存照", content: "嵌入悬挂也要有注入", importance: 5 });
748
+ const started = Date.now();
749
+ const res = await fetch(`${base}/context?q=任意`, { headers: auth });
750
+ assert.equal(res.status, 200, "hung embedder must not hang the route");
751
+ const body = await res.json();
752
+ assert.ok(body.items.some((m) => m.title === "挂起存照"), "timed-out embed falls back to the rule tier");
753
+ assert.ok(Date.now() - started < 3000, "response must not wait on the hung embedder");
754
+ } finally {
755
+ close();
756
+ }
757
+ });
758
+
759
+ test("strictPort: busy port rejects instead of hopping; default path still hops", async () => {
760
+ // daemon 语义锁(#363):strictPort 下配置端口被占 = 配置错误,明确失败 ——
761
+ // 顺延会让把 URL 写死的第三方客户端静默打到错误端口。占口用裸 net server
762
+ // (OS 分配,不与并行测试抢固定号)。
763
+ const { default: net } = await import("node:net");
764
+ const blocker = net.createServer();
765
+ await new Promise((resolve) => blocker.listen(0, "127.0.0.1", resolve));
766
+ const busyPort = blocker.address().port;
767
+
768
+ const store = createStore(":memory:");
769
+ const service = createService({ store, mirror: null, config: {} });
770
+ const settings = createSettings(store.db);
771
+ try {
772
+ const strict = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: busyPort, strictPort: true });
773
+ await assert.rejects(strict.ready, (err) => err?.code === "EADDRINUSE");
774
+
775
+ // 默认路径(不传 strictPort)行为不变:顺延成功;具体端口不断言(避免抢号)。
776
+ const hopping = createStandaloneApi({ service, store, config: {}, settings, logger: null, port: busyPort });
777
+ await hopping.ready;
778
+ assert.notEqual(hopping.port, busyPort, "default policy hops off a busy port");
779
+ hopping.server.close();
780
+ } finally {
781
+ blocker.close();
782
+ store.close();
783
+ }
784
+ });
785
+
786
+ // --- GET /context 的档位信号(issue #383)---------------------------------------
787
+ // 嵌入降级在调用方视角是完全静默的:items 看起来正常,只是召回质量悄悄变差。
788
+ // 外部集成方(Mneme Bridge 的 remote 模式)无法据此降级自己的期望或打日志。
789
+ // 三态 fail-closed:判不出来报 unknown,不报 full。
790
+
791
+ /** 可用的 embedder:任何查询都回一个固定向量。 */
792
+ const okEmbedder = { embedSingle: async () => [1, 0, 0], embed: async () => [1, 0, 0] };
793
+
794
+ test("GET /context tier=full when the query embedding succeeds", async () => {
795
+ const { base, auth, close } = await setup({ embedder: okEmbedder });
796
+ try {
797
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
798
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
799
+ assert.equal(body.tier, "full", "嵌入成功 → 语义档");
800
+ } finally {
801
+ close();
802
+ }
803
+ });
804
+
805
+ test("GET /context tier=degraded when no embedder is injected", async () => {
806
+ // 缺省(不传 embedder):daemon 与宿主都可能走到这条——embedder 未装配。
807
+ const { base, auth, close } = await setup();
808
+ try {
809
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
810
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
811
+ assert.equal(body.tier, "degraded", "无 embedder → 降级到规则档,且必须说出来");
812
+ } finally {
813
+ close();
814
+ }
815
+ });
816
+
817
+ test("GET /context tier=degraded when the query embedding times out", async () => {
818
+ // embedder 挂起(不抛错)时由 withEmbedTimeout 兜底——这是最难自查的一种降级,
819
+ // 因为接口是好的、只是没有响应。
820
+ const hanging = { embedSingle: () => new Promise(() => {}), embed: () => new Promise(() => {}) };
821
+ const { base, auth, close } = await setup({ embedder: hanging, embedTimeoutMs: 30 });
822
+ try {
823
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
824
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
825
+ assert.equal(body.tier, "degraded", "嵌入超时 → 降级到规则档");
826
+ } finally {
827
+ close();
828
+ }
829
+ });
830
+
831
+ test("GET /context tier=degraded when the embedder returns an unusable vector", async () => {
832
+ // 空数组 / 非数组同样让语义路走不通(embedQueryVector 的既有兜底),一并报降级。
833
+ const empty = { embedSingle: async () => [], embed: async () => [] };
834
+ const { base, auth, close } = await setup({ embedder: empty });
835
+ try {
836
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
837
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
838
+ assert.equal(body.tier, "degraded", "不可用向量 → 降级到规则档");
839
+ } finally {
840
+ close();
841
+ }
842
+ });
843
+
844
+ test("GET /context tier=degraded when the query vector's dimension differs from the stored one", async () => {
845
+ // #383 点名的那一种「悄悄退化」,也是 #508 评审里问「维度不符去哪了」的那一档:
846
+ // 嵌入接口一切正常(真的返回了向量),但库里躺着旧维度的向量——searchVector 对
847
+ // `v.length !== vector.length` 的行直接跳过,不抛错、只是命中为零,于是召回静默
848
+ // 退回 BM25/规则档。没有这个读数时,调用方看到的是 tier=full 加一份看着正常的
849
+ // items,而语义召回其实整条是死的。
850
+ const { base, auth, close, store, service } = await setup({ embedder: okEmbedder });
851
+ try {
852
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
853
+ // 手工塞一个 4 维向量:模拟「换了嵌入模型,旧向量还没重建索引」。okEmbedder 出
854
+ // 来的是 3 维,所以这一行的维度与查询向量不可比。
855
+ const memory = service.all().find((m) => m.title === "核心决策");
856
+ store.setEmbedding(memory.id, [1, 0, 0, 0]);
857
+ assert.deepEqual(store.vectorDimensionState(3), { state: "mismatch" }, "夹具前置:库里有向量,但没有一条与 3 维查询同维");
858
+
859
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
860
+ assert.equal(body.tier, "degraded", "维度不符 → 语义召回实际不可用,报降级而不是 full");
861
+ } finally {
862
+ close();
863
+ }
864
+ });
865
+
866
+ test("GET /context:库里还没有向量时不算维度不符(两种空的读数必须分开)", async () => {
867
+ // 「没有东西可比」与「维度对不上」是两件事:前者是全新库(或还没建索引),
868
+ // 语义路只是还没有内容,不是坏了。探针回 none 时必须继续报 full,否则每个新装
869
+ // 用户的第一次 /context 都是 degraded。
870
+ const { base, auth, close, store } = await setup({ embedder: okEmbedder });
871
+ try {
872
+ assert.deepEqual(store.vectorDimensionState(3), { state: "none" }, "夹具前置:行集为空,库里没有任何向量");
873
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
874
+ assert.equal(body.tier, "full", "没有已存向量 → 不是维度不符");
875
+ } finally {
876
+ close();
877
+ }
878
+ });
879
+
880
+ // --- 降级原因契约(issue #508 Minor #1)----------------------------------------
881
+ // 缺陷本身:非空 q 但没有装配 embedder 时 diag.reason 不赋值,日志靠兜底表达式拼出
882
+ // `no-embedder`,而文档声明的枚举里没有这个值;同一表达式里还躺着第二个越界字面量
883
+ // `embed-failed`。按枚举解析日志的运维程序会整条漏掉这一种**已测试**的降级路径。
884
+ // 根因是「日志契约没有测试锁」:setup() 曾把 logger 硬编码成 null,全仓没有任何一条
885
+ // 测试观测过那行 warn 的内容。下面把三侧钉在一起——代码导出的枚举、六条降级路径的实吐
886
+ // 值、两份文档声明的集合。
887
+
888
+ const DEGRADE_LOG_PREFIX = "dsh-mneme: /context degraded to the rule tier (";
889
+
890
+ /** 从抓到的 warn 行里抽出括号内的 reason 令牌,顺带锁前缀字面量(两份文档都写了它)。 */
891
+ function degradedReason(logs) {
892
+ const line = logs.find((l) => l.startsWith(DEGRADE_LOG_PREFIX));
893
+ assert.ok(line, `必须打出降级 warn(前缀 ${DEGRADE_LOG_PREFIX}),实际:${JSON.stringify(logs)}`);
894
+ const token = line.slice(DEGRADE_LOG_PREFIX.length, -1);
895
+ assert.ok(token.length > 0, "reason 令牌不许为空(兜底默认值已删,漏记账会在这里露出 (undefined))");
896
+ return token;
897
+ }
898
+
899
+ test("降级原因枚举:代码导出、README、docs/DAEMON 三侧同一个集合", () => {
900
+ // 枚举从常量派生,不把字符串再抄一遍——新增第七个值时必须改这一个常量 + 两份文档,
901
+ // 漏一边这里就红。
902
+ assert.ok(Object.isFrozen(CONTEXT_DEGRADE_REASONS), "枚举必须是 frozen 常量");
903
+ const docTokens = new Set();
904
+ for (const file of ["README.md", "docs/DAEMON.md"]) {
905
+ const text = readFileSync(new URL(`../${file}`, import.meta.url), "utf8");
906
+ // 只收降级原因形状的反引号令牌:`embed-<suffix>` 或 `no-embedder`。bare `embed`、
907
+ // `--embed off` 不是枚举成员,别收进来。注意「embedder」是一个词,所以匹配必须是
908
+ // `^(?:embed-|no-embed)`——写成 `embed-[a-z]+` 会把 no-embedder 整条漏掉,而那正是
909
+ // #508 Minor 漏掉它的同一种手法。
910
+ for (const m of text.matchAll(/`([a-z][a-z-]*)`/g)) {
911
+ if (/^(?:embed-|no-embed)/.test(m[1])) docTokens.add(m[1]);
912
+ }
913
+ }
914
+ assert.deepEqual(
915
+ [...docTokens].sort(),
916
+ [...CONTEXT_DEGRADE_REASONS].sort(),
917
+ "两份文档声明的降级原因必须与代码导出的枚举同集合(改一边忘另一边会红)"
918
+ );
919
+ });
920
+
921
+ test("每条降级路径写进日志的 reason 都是枚举成员(#508 的日志契约)", async () => {
922
+ // 六条路径逐个抓 warn 行抽 reason。embed-dimension 那条要夹具(库里得有旧维度向量),
923
+ // 其余五条纯 embedder 形状。每条都断言令牌 ∈ CONTEXT_DEGRADE_REASONS——枚举外的值
924
+ // 在这里变红,这正是当初漏掉 no-embedder 的那道门。
925
+ const paths = [
926
+ {
927
+ name: "没装配 embedder(daemon --embed off / lightMode)",
928
+ embedder: null,
929
+ reason: "no-embedder",
930
+ note: "预期态不是故障,所以它必须是枚举里一个有自己的名字,而不是并进 embed-unavailable"
931
+ },
932
+ {
933
+ name: "embedder 对象上没有 embedSingle / embed",
934
+ embedder: {},
935
+ reason: "embed-unavailable"
936
+ },
937
+ {
938
+ name: "接口返回空数组",
939
+ embedder: { embedSingle: async () => [], embed: async () => [] },
940
+ reason: "embed-empty"
941
+ },
942
+ {
943
+ name: "接口挂起,被超时护栏按缺失处理",
944
+ embedder: { embedSingle: () => new Promise(() => {}), embed: () => new Promise(() => {}) },
945
+ embedTimeoutMs: 30,
946
+ reason: "embed-timeout"
947
+ },
948
+ {
949
+ name: "接口抛错",
950
+ embedder: { embedSingle: async () => { throw new Error("model offline"); } },
951
+ reason: "embed-error"
952
+ }
953
+ ];
954
+ for (const path of paths) {
955
+ const logs = [];
956
+ const { base, auth, close } = await setup({
957
+ embedder: path.embedder,
958
+ embedTimeoutMs: path.embedTimeoutMs,
959
+ logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
960
+ });
961
+ try {
962
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
963
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
964
+ assert.equal(body.tier, "degraded", `${path.name} → 降级档`);
965
+ const reason = degradedReason(logs);
966
+ assert.equal(reason, path.reason, `${path.name} → reason${path.note ? `(${path.note})` : ""}`);
967
+ assert.ok(CONTEXT_DEGRADE_REASONS.includes(reason), `${reason} 必须 ∈ 导出的枚举`);
968
+ } finally {
969
+ close();
970
+ }
971
+ }
972
+ });
973
+
974
+ test("维度不符写进日志的 reason 是 embed-dimension(枚举成员)", async () => {
975
+ const logs = [];
976
+ const { base, auth, close, store, service } = await setup({
977
+ embedder: okEmbedder,
978
+ logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
979
+ });
980
+ try {
981
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
982
+ const memory = service.all().find((m) => m.title === "核心决策");
983
+ store.setEmbedding(memory.id, [1, 0, 0, 0]);
984
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
985
+ assert.equal(body.tier, "degraded");
986
+ assert.equal(degradedReason(logs), "embed-dimension");
987
+ } finally {
988
+ close();
989
+ }
990
+ });
991
+
992
+ // --- 维度探针(issue #508 Major + Minor #2)------------------------------------
993
+ // Major:LIMIT 1 拿任意一条向量代表全库,混合维度库里两个方向都错。抽到与查询不符的那条
994
+ // → 明明有可比的向量却误报 degraded;首条恰好解析失败 → 其余有效向量都不匹配时又漏报成
995
+ // full。判据换成存在性:有没有一条活跃向量的维度等于查询维度。
996
+ // Minor #2:探针自身抛异常(库被锁 / 半开)会掉进最终 .catch(),把已经算好的 items 丢掉
997
+ // 并回 500——违反 fail-closed。隔离在调用侧,tier 留 unknown。
998
+
999
+ /** 库内插入序的 id(探针的行集顺序即插入序,无 ORDER BY 的全表扫)。 */
1000
+ function insertedIds(store) {
1001
+ return store.db.prepare("SELECT id FROM memories ORDER BY rowid").all().map((r) => r.id);
1002
+ }
1003
+
1004
+ test("混合维度库:有一条与查询同维的活跃向量 → full,不误报 degraded(#508 Major 场景一)", async () => {
1005
+ // LIMIT 1 时代这条是红的:先插入的旧维度行被抽中 → 判「维度不符」,而库里明明躺着
1006
+ // 一条可比的 3 维向量,语义召回并没有死。
1007
+ const { base, auth, close, store } = await setup({ embedder: okEmbedder });
1008
+ try {
1009
+ await saveMemory(base, auth, { type: "decision", title: "旧维度行", content: "四维向量", importance: 5 });
1010
+ await saveMemory(base, auth, { type: "decision", title: "新维度行", content: "三维向量", importance: 5 });
1011
+ const [oldId, newId] = insertedIds(store);
1012
+ store.setEmbedding(oldId, [1, 0, 0, 0]); // 先插入 = 旧维度
1013
+ store.setEmbedding(newId, [1, 0, 0]); // 后插入 = 与查询同维
1014
+ assert.deepEqual(store.vectorDimensionState(3), { state: "match" }, "夹具前置:库里有一条 3 维活跃向量");
1015
+
1016
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1017
+ assert.equal(body.tier, "full", "有可比向量 → 语义路通,不能因为抽到 4 维那条就误报降级");
1018
+ } finally {
1019
+ close();
1020
+ }
1021
+ });
1022
+
1023
+ test("首条向量损坏、其余有效向量都不匹配 → degraded,不误报 full(#508 Major 场景二)", async () => {
1024
+ // LIMIT 1 时代这条也是红的:首条解析失败 → 探针回 null → 走「库里没有向量」分支 → full,
1025
+ // 而语义召回其实整条是死的。
1026
+ const { base, auth, close, store } = await setup({ embedder: okEmbedder });
1027
+ try {
1028
+ await saveMemory(base, auth, { type: "decision", title: "损坏行", content: "向量文本损坏", importance: 5 });
1029
+ await saveMemory(base, auth, { type: "decision", title: "旧维度行", content: "四维向量", importance: 5 });
1030
+ const [brokenId, oldDimId] = insertedIds(store);
1031
+ // 直接改列,不走 setEmbedding(那条路会归一成 JSON.stringify(array),造不出损坏文本)。
1032
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{not json", brokenId);
1033
+ store.setEmbedding(oldDimId, [1, 0, 0, 0]);
1034
+ assert.deepEqual(store.vectorDimensionState(3), { state: "mismatch" }, "夹具前置:有向量、没有一条与 3 维查询同维");
1035
+
1036
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1037
+ assert.equal(body.tier, "degraded", "首条损坏不该把 mismatch 洗成 full");
1038
+ } finally {
1039
+ close();
1040
+ }
1041
+ });
1042
+
1043
+ test("有行但一条向量都读不出来 → unknown,不是 full(两种空必须分开)", async () => {
1044
+ // 「还没有内容」(none → full)与「内容在那儿却读不出来」(unreadable)是两种空。
1045
+ // 后者判不出来,按 fail-closed 报 unknown,绝不因为读不到就宣称 full。
1046
+ const logs = [];
1047
+ const { base, auth, close, store } = await setup({
1048
+ embedder: okEmbedder,
1049
+ logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
1050
+ });
1051
+ try {
1052
+ await saveMemory(base, auth, { type: "decision", title: "损坏行", content: "向量文本损坏", importance: 5 });
1053
+ const [brokenId] = insertedIds(store);
1054
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{not json", brokenId);
1055
+ assert.deepEqual(store.vectorDimensionState(3), { state: "unreadable" }, "夹具前置:行集非空但零条可解析");
1056
+
1057
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1058
+ assert.equal(body.tier, "unknown", "读不出任何向量 → 判不出来,不宣称 full");
1059
+ assert.ok(body.items.length > 0, "items 照常返回");
1060
+ // unknown 在响应体里只有一个键,分不出「空 q」与「判不出来」;留痕只能走日志,
1061
+ // 否则调用方对 unknown 的策略是「不告警」时,这条故障就从运维面上整个消失。
1062
+ assert.ok(
1063
+ logs.some((l) => l.startsWith("dsh-mneme: /context tier left unknown: no comparable vector readable (unreadable)")),
1064
+ `判不出来必须留痕(不是降级原因枚举的一员),实际:${JSON.stringify(logs)}`
1065
+ );
1066
+ } finally {
1067
+ close();
1068
+ }
1069
+ });
1070
+
1071
+ test("维度探针抛异常 → tier=unknown 且 items 不丢,绝不 500(#508 Minor #2)", async () => {
1072
+ const logs = [];
1073
+ const { base, auth, close, service } = await setup({
1074
+ embedder: okEmbedder,
1075
+ logger: { info: () => {}, warn: (m) => logs.push(String(m)) }
1076
+ });
1077
+ try {
1078
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1079
+ // 仓内惯用的故障注入(同 test/audit.test.js / test/conflict-freeze.test.js)。
1080
+ service.vectorDimensionState = () => { throw new Error("database is locked"); };
1081
+
1082
+ const res = await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth });
1083
+ assert.equal(res.status, 200, "探针异常不许把已经算好的 items 变成 500");
1084
+ const body = await res.json();
1085
+ assert.equal(body.tier, "unknown", "判不出来 → unknown,不宣称 full");
1086
+ assert.ok(body.items.length > 0, "已经算好的 items 不许被丢掉");
1087
+ assert.ok(
1088
+ logs.some((l) => l.startsWith("dsh-mneme: /context tier left unknown: dimension probe failed (Error: database is locked)")),
1089
+ `探针故障必须留痕,实际:${JSON.stringify(logs)}`
1090
+ );
1091
+ assert.ok(!logs.some((l) => l.startsWith(DEGRADE_LOG_PREFIX)), "tier 不是 degraded,不该打降级 warn");
1092
+ } finally {
1093
+ close();
1094
+ }
1095
+ });
1096
+
1097
+ test("探针没跑成(方法缺失 / 返回垃圾 / 异步漂移)一律 unknown,不宣称 full", async () => {
1098
+ // typeof 守卫与 sentinel 都要 fail-closed:旧实现里这三种都落到「不是 number」分支
1099
+ // 报 full。异步漂移那条是纪律锁——try/catch 只能同步包住一个同步调用,探针一旦被
1100
+ // 改成异步,抛错就重新变成 rejection 落回最终 .catch()。
1101
+ const shapes = [
1102
+ { name: "方法缺失(旧装配)", patch: (s) => { delete s.vectorDimensionState; } },
1103
+ { name: "返回字符串", patch: (s) => { s.vectorDimensionState = () => "3"; } },
1104
+ { name: "返回 undefined", patch: (s) => { s.vectorDimensionState = () => undefined; } },
1105
+ { name: "返回 Promise(异步漂移)", patch: (s) => { s.vectorDimensionState = () => Promise.resolve({ state: "match" }); } }
1106
+ ];
1107
+ for (const shape of shapes) {
1108
+ const { base, auth, close, service } = await setup({ embedder: okEmbedder });
1109
+ try {
1110
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1111
+ shape.patch(service);
1112
+ const body = await (await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth })).json();
1113
+ assert.equal(body.tier, "unknown", `${shape.name} → 判不出来,不宣称 full`);
1114
+ } finally {
1115
+ close();
1116
+ }
1117
+ }
1118
+ });
1119
+
1120
+ test("探针失败与降级 warn 自身抛错也不许把响应变成 500(logger 来自宿主,warn 会抛)", async () => {
1121
+ // `logger?.warn?.()` 只防 logger 缺失,防不了 warn 自己抛错(宿主 stdout 管道断裂时
1122
+ // 真实可发生)。items 算好之后,日志通道坏了不是丢掉它的理由。
1123
+ const logs = [];
1124
+ const logger = { info: () => {}, warn: (m) => { logs.push(String(m)); throw new Error("stderr broken"); } };
1125
+ const { base, auth, close, service } = await setup({ embedder: okEmbedder, logger });
1126
+ try {
1127
+ await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1128
+ service.vectorDimensionState = () => { throw new Error("boom"); };
1129
+ const res = await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth });
1130
+ assert.equal(res.status, 200, "warn 自身抛错 + 探针抛错 → 仍然 200");
1131
+ assert.equal((await res.json()).tier, "unknown");
1132
+
1133
+ // 降级路径同样:warn 抛错被自己的 try/catch 吃掉,tier 与 items 不受影响。
1134
+ service.vectorDimensionState = () => ({ state: "mismatch" });
1135
+ const degraded = await fetch(`${base}/context?q=${encodeURIComponent("数据库选型")}`, { headers: auth });
1136
+ assert.equal(degraded.status, 200, "降级 warn 抛错也不许 500");
1137
+ assert.equal((await degraded.json()).tier, "degraded");
1138
+ } finally {
1139
+ close();
1140
+ }
1141
+ });
1142
+
1143
+ test("维度探针状态机:五种读数各自归位(含 invalid 的 fail-closed 兜底)", async () => {
1144
+ // 直接锁 store 的状态机:match / mismatch / none / unreadable / invalid。
1145
+ // invalid 当前 /context 不可达(embedQueryVector 保证返回非空数组),但它不许落到
1146
+ // full 上——「判不了」与「没有东西可比」不是同一个读数。
1147
+ const { store, close } = await setup();
1148
+ try {
1149
+ assert.deepEqual(store.vectorDimensionState(3), { state: "none" }, "空库 → 行集为空");
1150
+ assert.deepEqual(store.vectorDimensionState(0), { state: "invalid" });
1151
+ assert.deepEqual(store.vectorDimensionState(-1), { state: "invalid" });
1152
+ assert.deepEqual(store.vectorDimensionState(2.5), { state: "invalid" });
1153
+ assert.deepEqual(store.vectorDimensionState("3"), { state: "invalid" });
1154
+
1155
+ const a = store.save({ type: "decision", title: "同维", content: "c", importance: 4 });
1156
+ const b = store.save({ type: "decision", title: "异维", content: "c", importance: 4 });
1157
+ store.setEmbedding(a.id, [1, 0, 0]);
1158
+ store.setEmbedding(b.id, [1, 0, 0, 0]);
1159
+ assert.deepEqual(store.vectorDimensionState(3), { state: "match" }, "有一条同维 → match(短路,不看完)");
1160
+ assert.deepEqual(store.vectorDimensionState(5), { state: "mismatch" }, "有向量但没有一条同维 → mismatch");
1161
+
1162
+ // 清掉解析缓存再写坏列(getParsedEmbedding 只缓存成功解析,缓存在的话直接改列看不见)。
1163
+ store.setEmbedding(a.id, null);
1164
+ store.setEmbedding(b.id, null);
1165
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("{oops", a.id);
1166
+ store.db.prepare("UPDATE memories SET embedding = ? WHERE id = ?").run("[]", b.id);
1167
+ assert.deepEqual(store.vectorDimensionState(3), { state: "unreadable" }, "有行但零条可解析 → unreadable(不是 none)");
1168
+ } finally {
1169
+ close();
1170
+ }
1171
+ });
1172
+
1173
+ // --- GET /memory/provenance:记忆级溯源读出口(#399 写、#421 读)-------------
1174
+ // daemon 侧此前和宿主内 API 一样只有写入路径:库里有答案,外部拿不到。
1175
+ //
1176
+ // #509 评审整改:这个面吃 distillRecords.enabled(与写侧同一个开关、同一个判据),
1177
+ // 关着时 409 {error:"distill-records-disabled"}。createStandaloneApi 的 config 缺省
1178
+ // {},而 {} 在这道门上的含义就是「关」(fail-closed)——所以下面的用例必须显式把
1179
+ // 开关打开,没有一个「默认开」的路径。
1180
+ const RECORDS_ON = { distillRecords: { enabled: true } };
1181
+
1182
+ test("GET /memory/provenance returns windows with their original rows", async () => {
1183
+ const { base, auth, store, close } = await setup({ config: RECORDS_ON });
1184
+ try {
1185
+ const saved = await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1186
+ const memoryId = saved.memory?.id ?? saved.id;
1187
+ store.saveMemoryProvenance({
1188
+ memoryId, sessionId: "s1", seqStart: 10, seqEnd: 11, createdAt: "2026-10-23T00:00:00Z"
1189
+ });
1190
+ store.saveDistillRecords([
1191
+ { sessionId: "s1", seq: 10, role: "user", text: "第一句原文", windowId: "w1", distilledAt: "2026-10-23T00:00:00Z" },
1192
+ { sessionId: "s1", seq: 11, role: "assistant", text: "第二句原文", windowId: "w1", distilledAt: "2026-10-23T00:00:00Z" }
1193
+ ]);
1194
+
1195
+ const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(memoryId)}`, { headers: auth });
1196
+ assert.equal(res.status, 200);
1197
+ const body = await res.json();
1198
+ assert.equal(body.memoryId, memoryId);
1199
+ assert.equal(body.windows.length, 1);
1200
+ assert.equal(body.windows[0].session_id, "s1");
1201
+ assert.deepEqual(body.windows[0].records.map((r) => r.text), ["第一句原文", "第二句原文"], "原文按 seq 升序");
1202
+ } finally {
1203
+ close();
1204
+ }
1205
+ });
1206
+
1207
+ test("GET /memory/provenance: a memory with no link answers with empty windows, not an error", async () => {
1208
+ const { base, auth, close } = await setup({ config: RECORDS_ON });
1209
+ try {
1210
+ const saved = await saveMemory(base, auth, { type: "preference", title: "语言", content: "中文" });
1211
+ const memoryId = saved.memory?.id ?? saved.id;
1212
+ const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(memoryId)}`, { headers: auth });
1213
+ assert.equal(res.status, 200);
1214
+ assert.deepEqual((await res.json()).windows, [], "「不是蒸馏来的」是有效答案,不是错误");
1215
+ } finally {
1216
+ close();
1217
+ }
1218
+ });
1219
+
1220
+ test("GET /memory/provenance is auth-gated and 400s on a missing id", async () => {
1221
+ const { base, auth, close } = await setup({ config: RECORDS_ON });
1222
+ try {
1223
+ const noToken = await fetch(`${base}/memory/provenance?id=x`);
1224
+ assert.equal(noToken.status, 401, "只读端点也在 apiToken 之下(与 /memories 同口径)");
1225
+
1226
+ const missing = await fetch(`${base}/memory/provenance`, { headers: auth });
1227
+ assert.equal(missing.status, 400);
1228
+ } finally {
1229
+ close();
1230
+ }
1231
+ });
1232
+
1233
+ test("GET /memory/provenance: distillRecords.enabled off answers 409, not 404 and not empty windows", async () => {
1234
+ // #509 评审整改。四个刻度必须分开:401 没鉴权 / 400 缺 id / 409 用户关了 /
1235
+ // 503 装配没接线 / 200 空 windows = 「这条记忆不是蒸馏来的」。把「关了」报成 404,
1236
+ // 调用方会按本仓既有的「404 = 命名的东西不存在」(/memories/:id)读成「这条记忆
1237
+ // 不存在」——而这两种误读的后续动作完全不同(一个去开开关,一个去查这条记忆)。
1238
+ const { base, auth, close } = await setup({ config: { distillRecords: { enabled: false } } });
1239
+ try {
1240
+ const saved = await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite 单文件库", importance: 5 });
1241
+ const memoryId = saved.memory?.id ?? saved.id;
1242
+ const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(memoryId)}`, { headers: auth });
1243
+ assert.equal(res.status, 409);
1244
+ assert.deepEqual(await res.json(), { error: "distill-records-disabled" }, "body 只准 error 一个键");
1245
+ } finally {
1246
+ close();
1247
+ }
1248
+ });
1249
+
1250
+ test("GET /memory/provenance: no config at all is fail-closed (409)", async () => {
1251
+ // 构造时不传 config(createStandaloneApi 的默认 {}):这个端点返回逐字原文,
1252
+ // 默认方向必须是「不读」。别把 409 当 bug 修成默认开。
1253
+ const { base, auth, close } = await setup();
1254
+ try {
1255
+ const res = await fetch(`${base}/memory/provenance?id=m1`, { headers: auth });
1256
+ assert.equal(res.status, 409);
1257
+ assert.deepEqual(await res.json(), { error: "distill-records-disabled" });
1258
+ } finally {
1259
+ close();
1260
+ }
1261
+ });
1262
+
1263
+ test("GET /memory/provenance: 400 beats 409 and 409 is not an existence oracle", async () => {
1264
+ const { base, auth, close } = await setup({ config: { distillRecords: { enabled: false } } });
1265
+ try {
1266
+ const missing = await fetch(`${base}/memory/provenance`, { headers: auth });
1267
+ assert.equal(missing.status, 400, "缺 id 是语法畸形,排在功能开关之前");
1268
+
1269
+ // 关着时已知 id 与未知 id 同一个答案,否则这个端点能用来枚举「哪些记忆有原文」。
1270
+ const saved = await saveMemory(base, auth, { type: "preference", title: "语言", content: "中文" });
1271
+ const known = saved.memory?.id ?? saved.id;
1272
+ for (const id of [known, "nope"]) {
1273
+ const res = await fetch(`${base}/memory/provenance?id=${encodeURIComponent(id)}`, { headers: auth });
1274
+ assert.equal(res.status, 409, `${id} → 409`);
1275
+ assert.deepEqual(await res.json(), { error: "distill-records-disabled" });
1276
+ }
1277
+ } finally {
1278
+ close();
1279
+ }
1280
+ });
1281
+
1282
+ test("GET /memory/provenance: 409 beats 503 — feature off is more specific than unwired", async () => {
1283
+ // 关着 + service 上连 distillRecordsFor 都没有(旧装配 / headless):报 503 会让人
1284
+ // 去查一个没坏的部署。与 api.js:525-526 立的两段式同构。
1285
+ const { base, auth, service, close } = await setup({ config: { distillRecords: { enabled: false } } });
1286
+ try {
1287
+ delete service.distillRecordsFor;
1288
+ const res = await fetch(`${base}/memory/provenance?id=x`, { headers: auth });
1289
+ assert.equal(res.status, 409);
1290
+ assert.equal((await res.json()).error, "distill-records-disabled");
1291
+ } finally {
1292
+ close();
1293
+ }
1294
+ });
1295
+
1296
+ // --- #524 方向 2:?sessionId=<sid> 列该会话的蒸馏窗口 -----------------------
1297
+ // 与宿主内 API 是同一份口径(共用 provenance-http.js),这里只钉两张皮的那条差
1298
+ // 异之外的部分真的走通了:一行一窗口、按 seq_start 排、truncated 说出来。
1299
+ test("GET /memory/provenance?sessionId= lists a session's distill windows", async () => {
1300
+ const { base, auth, store, close } = await setup({ config: RECORDS_ON });
1301
+ try {
1302
+ const a = await saveMemory(base, auth, { type: "decision", title: "核心决策", content: "选定 SQLite", importance: 5 });
1303
+ const b = await saveMemory(base, auth, { type: "decision", title: "备选", content: "JSON 文件", importance: 3 });
1304
+ const idA = a.memory?.id ?? a.id;
1305
+ const idB = b.memory?.id ?? b.id;
1306
+ // 同一窗口派生两条记忆:答复里必须并成一行(link_count=2),不是两行。
1307
+ store.saveMemoryProvenance({ memoryId: idA, sessionId: "s1", seqStart: 10, seqEnd: 12, createdAt: "t2" });
1308
+ store.saveMemoryProvenance({ memoryId: idB, sessionId: "s1", seqStart: 10, seqEnd: 12, createdAt: "t2" });
1309
+ store.saveMemoryProvenance({ memoryId: idA, sessionId: "s1", seqStart: 1, seqEnd: 3, createdAt: "t1" });
1310
+ store.saveMemoryProvenance({ memoryId: idA, sessionId: "s2", seqStart: 50, seqEnd: 51, createdAt: "t3" });
1311
+
1312
+ const res = await fetch(`${base}/memory/provenance?sessionId=s1`, { headers: auth });
1313
+ assert.equal(res.status, 200);
1314
+ const body = await res.json();
1315
+ assert.equal(body.sessionId, "s1");
1316
+ assert.equal(body.memoryId, undefined, "两个方向的认领键不许同时出现");
1317
+ assert.equal(body.truncated, false);
1318
+ assert.deepEqual(body.windows.map((w) => [w.seq_start, w.seq_end]), [[1, 3], [10, 12]],
1319
+ "同一 (seq_start, seq_end) 并成一行,按 seq_start 升序;别的会话的窗口不出现");
1320
+ assert.deepEqual(body.windows.map((w) => w.link_count), [1, 2]);
1321
+ } finally {
1322
+ close();
1323
+ }
1324
+ });
1325
+
1326
+ test("GET /memory/provenance: both selectors at once is 400, and limit is bounded", async () => {
1327
+ const { base, auth, close } = await setup({ config: RECORDS_ON });
1328
+ try {
1329
+ const both = await fetch(`${base}/memory/provenance?id=m1&sessionId=s1`, { headers: auth });
1330
+ assert.equal(both.status, 400, "两个主键都给不许静默择一");
1331
+ assert.equal((await both.json()).error, "ambiguous-id");
1332
+
1333
+ for (const bad of ["0", "-1", "1.5", "abc", "1e3", "101"]) {
1334
+ const res = await fetch(`${base}/memory/provenance?sessionId=s1&limit=${bad}`, { headers: auth });
1335
+ assert.equal(res.status, 400, `limit=${bad} 必须 400`);
1336
+ assert.equal((await res.json()).error, "invalid-limit");
1337
+ }
1338
+
1339
+ const missing = await fetch(`${base}/memory/provenance`, { headers: auth });
1340
+ assert.equal(missing.status, 400, "两个主键都缺仍是 400 missing-id");
1341
+ } finally {
1342
+ close();
1343
+ }
1344
+ });