@modusensus/dsh-mneme 0.8.3 → 0.8.5

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 (205) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +727 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +510 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +506 -316
  7. package/lib/api.js +1403 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4657 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +615 -510
  12. package/lib/document.js +221 -0
  13. package/lib/dream/clustering.js +118 -118
  14. package/lib/dream/decisions.js +658 -658
  15. package/lib/dream/narratives.js +44 -0
  16. package/lib/dream/sleep.js +702 -700
  17. package/lib/dream.js +147 -16
  18. package/lib/embedding.js +177 -177
  19. package/lib/entities/extractor.js +249 -249
  20. package/lib/guide.js +44 -0
  21. package/lib/heat.js +144 -136
  22. package/lib/hot-memory.js +46 -46
  23. package/lib/index.js +515 -515
  24. package/lib/inject.js +375 -295
  25. package/lib/lang.js +208 -179
  26. package/lib/local-embedder.js +320 -320
  27. package/lib/mirror.js +198 -198
  28. package/lib/organize.js +450 -0
  29. package/lib/quality-filter.js +126 -126
  30. package/lib/recall-stats.js +125 -0
  31. package/lib/reranker.js +269 -269
  32. package/lib/runtime/adopt.js +176 -176
  33. package/lib/runtime/closure.js +172 -172
  34. package/lib/runtime/download.js +247 -247
  35. package/lib/runtime/layout.js +265 -235
  36. package/lib/runtime/loader.js +252 -249
  37. package/lib/runtime/model-fetch.js +361 -361
  38. package/lib/runtime/provision.js +237 -237
  39. package/lib/runtime/tarball.js +130 -130
  40. package/lib/runtime/verify.js +204 -191
  41. package/lib/scope.js +118 -118
  42. package/lib/search/adaptive.js +60 -22
  43. package/lib/search/bm25.js +96 -96
  44. package/lib/service.js +2324 -2087
  45. package/lib/settings.js +459 -420
  46. package/lib/store.js +2549 -2367
  47. package/lib/summarize.js +820 -449
  48. package/lib/tools.js +702 -574
  49. package/lib/vector-index.js +110 -110
  50. package/lib/version-check.js +122 -122
  51. package/package.json +109 -108
  52. package/runtime-manifest.json +526 -596
  53. package/scripts/benchmark-embed.js +201 -201
  54. package/scripts/benchmark-recall.js +199 -199
  55. package/scripts/benchmark-rerank.js +166 -166
  56. package/scripts/build-runtime-manifest.mjs +224 -217
  57. package/scripts/check-sync.js +42 -42
  58. package/scripts/e2e-dsh.js +220 -220
  59. package/scripts/mneme-runtime.mjs +277 -277
  60. package/scripts/stress-dsh.js +255 -255
  61. package/scripts/sync-lib.js +47 -47
  62. package/scripts/sync-test-badge.mjs +67 -61
  63. package/src/api-standalone.js +506 -316
  64. package/src/api.js +1403 -1316
  65. package/src/bootstrap.js +211 -0
  66. package/src/commands.js +95 -95
  67. package/src/config.js +615 -510
  68. package/src/document.js +221 -0
  69. package/src/dream/clustering.js +118 -118
  70. package/src/dream/decisions.js +658 -658
  71. package/src/dream/narratives.js +44 -0
  72. package/src/dream/sleep.js +702 -700
  73. package/src/dream.js +147 -16
  74. package/src/embedding.js +177 -177
  75. package/src/entities/extractor.js +249 -249
  76. package/src/guide.js +44 -0
  77. package/src/heat.js +144 -136
  78. package/src/hot-memory.js +46 -46
  79. package/src/index.js +515 -515
  80. package/src/inject.js +375 -295
  81. package/src/lang.js +208 -179
  82. package/src/local-embedder.js +320 -320
  83. package/src/mirror.js +198 -198
  84. package/src/organize.js +450 -0
  85. package/src/quality-filter.js +126 -126
  86. package/src/recall-stats.js +125 -0
  87. package/src/reranker.js +269 -269
  88. package/src/runtime/adopt.js +176 -176
  89. package/src/runtime/closure.js +172 -172
  90. package/src/runtime/download.js +247 -247
  91. package/src/runtime/layout.js +265 -235
  92. package/src/runtime/loader.js +252 -249
  93. package/src/runtime/model-fetch.js +361 -361
  94. package/src/runtime/provision.js +237 -237
  95. package/src/runtime/tarball.js +130 -130
  96. package/src/runtime/verify.js +204 -191
  97. package/src/scope.js +118 -118
  98. package/src/search/adaptive.js +60 -22
  99. package/src/search/bm25.js +96 -96
  100. package/src/service.js +2324 -2087
  101. package/src/settings.js +459 -420
  102. package/src/store.js +2549 -2367
  103. package/src/summarize.js +820 -449
  104. package/src/tools.js +702 -574
  105. package/src/vector-index.js +110 -110
  106. package/src/version-check.js +122 -122
  107. package/test/adaptive-inject-budget.test.js +85 -0
  108. package/test/api-routes-gaps.test.js +218 -218
  109. package/test/api.test.js +1640 -1482
  110. package/test/audit.test.js +448 -448
  111. package/test/benchmark.test.js +94 -94
  112. package/test/bootstrap.test.js +220 -0
  113. package/test/client.test.js +860 -736
  114. package/test/clustering.test.js +100 -100
  115. package/test/commands.test.js +106 -106
  116. package/test/config.test.js +66 -66
  117. package/test/conflict-freeze.test.js +300 -300
  118. package/test/document.test.js +523 -0
  119. package/test/dream-archive-guardrail.test.js +116 -116
  120. package/test/dream-candidate-hybrid.test.js +281 -281
  121. package/test/dream-coverage-degrade.test.js +86 -86
  122. package/test/dream.test.js +1308 -1254
  123. package/test/embedding-ready.test.js +196 -196
  124. package/test/entities.test.js +547 -547
  125. package/test/entity-recall.test.js +179 -0
  126. package/test/epistemic.test.js +298 -298
  127. package/test/fnew-0112.test.js +311 -311
  128. package/test/fnew-03.test.js +422 -422
  129. package/test/graph-api.test.js +175 -175
  130. package/test/heat.test.js +175 -148
  131. package/test/helpers/dream-mock.js +82 -82
  132. package/test/helpers/peer-worker.mjs +25 -25
  133. package/test/helpers/runtime-source.js +60 -60
  134. package/test/helpers/tar-builder.js +80 -80
  135. package/test/hot-memory.test.js +145 -145
  136. package/test/inject-content-cap.test.js +91 -0
  137. package/test/inject-first-round-bm25.test.js +89 -89
  138. package/test/inject-heat.test.js +61 -0
  139. package/test/inject-pools.test.js +170 -0
  140. package/test/inject-recall.test.js +105 -0
  141. package/test/inject-rotation.test.js +161 -161
  142. package/test/inject.test.js +283 -249
  143. package/test/lang.test.js +87 -87
  144. package/test/lib-smoke.test.js +96 -96
  145. package/test/llm-audit.test.js +462 -309
  146. package/test/llm-message-source.test.js +177 -177
  147. package/test/local-embedder.test.js +249 -249
  148. package/test/mcp-stdio.test.js +385 -0
  149. package/test/mirror-dirty.test.js +424 -424
  150. package/test/mirror-edit-digest.test.js +187 -187
  151. package/test/mirror-generation.test.js +499 -499
  152. package/test/mirror.test.js +249 -249
  153. package/test/narrative-bars.test.js +162 -0
  154. package/test/organize.test.js +418 -0
  155. package/test/peer-blockers.test.js +193 -193
  156. package/test/policy-epoch.test.js +259 -259
  157. package/test/quality-filter.test.js +186 -186
  158. package/test/reasoning-effort.test.js +746 -746
  159. package/test/recall-evals.test.js +235 -235
  160. package/test/recall-layer.test.js +326 -326
  161. package/test/recall-stats.test.js +123 -0
  162. package/test/receipt-chain.test.js +451 -451
  163. package/test/reflection.test.js +226 -226
  164. package/test/reindex-backfill.test.js +62 -62
  165. package/test/reranker-single-logit.test.js +73 -73
  166. package/test/reranker.test.js +197 -197
  167. package/test/resident-status.test.js +83 -0
  168. package/test/runtime-adopt.test.js +206 -206
  169. package/test/runtime-cli.test.js +89 -89
  170. package/test/runtime-closure.test.js +193 -193
  171. package/test/runtime-download.test.js +302 -302
  172. package/test/runtime-layout.test.js +163 -163
  173. package/test/runtime-loader.test.js +255 -237
  174. package/test/runtime-manifest.test.js +159 -158
  175. package/test/runtime-model-fetch.test.js +348 -348
  176. package/test/runtime-provision.test.js +101 -101
  177. package/test/runtime-tarball.test.js +81 -81
  178. package/test/runtime-verify.test.js +279 -214
  179. package/test/scope-candidates.test.js +239 -239
  180. package/test/scope-explicit.test.js +452 -452
  181. package/test/scope-retrieval.test.js +197 -197
  182. package/test/scope-storage.test.js +255 -255
  183. package/test/scope-strict.test.js +231 -231
  184. package/test/search-fusion.test.js +90 -90
  185. package/test/semantic.test.js +124 -124
  186. package/test/service-search.test.js +174 -174
  187. package/test/service.test.js +405 -405
  188. package/test/settings.test.js +261 -261
  189. package/test/skip-invalid-restore.test.js +262 -262
  190. package/test/sleep-action-set.test.js +422 -422
  191. package/test/sleep-heat.test.js +126 -125
  192. package/test/sleep-scheduler-rearm.test.js +89 -89
  193. package/test/sleep.test.js +410 -373
  194. package/test/standalone-api.test.js +544 -359
  195. package/test/store-vector-cache.test.js +98 -98
  196. package/test/store.test.js +396 -383
  197. package/test/stress.test.js +209 -209
  198. package/test/summarize.test.js +1288 -575
  199. package/test/tools-dto-schema-matrix.test.js +325 -0
  200. package/test/tools-memory-get-schema.test.js +65 -65
  201. package/test/tools.test.js +374 -341
  202. package/test/updated-at-semantics.test.js +113 -113
  203. package/test/vector-index.test.js +221 -221
  204. package/test/version-check.test.js +152 -152
  205. package/test/webServer-optional.test.js +82 -82
@@ -1,309 +1,462 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { EventEmitter } from "node:events";
4
- import { createStore } from "../src/store.js";
5
- import { createService } from "../src/service.js";
6
- import { createDreamScheduler } from "../src/dream.js";
7
- import { createSummarizer } from "../src/summarize.js";
8
- import { createApi } from "../src/api.js";
9
- import { createSettings } from "../src/settings.js";
10
- import { mockCtx } from "./helpers/dream-mock.js";
11
-
12
- // Bug8: LLM audit trail. Every background LLM call (autoDream consolidation +
13
- // summary, autoSummarize compression) records tokens/time/status into
14
- // llm_audit_logs. Failures are captured as status='error' and never block the
15
- // calling feature. Read back through the API (/llm-audit + /llm-audit/stats).
16
- // Gating: runDream treats llmAudit.enabled === false as off; summarize treats
17
- // llmAudit.enabled !== false as on.
18
-
19
- function dreamSetup(over = {}) {
20
- const store = createStore(":memory:");
21
- const service = createService({ store, mirror: null, config: {} });
22
- return {
23
- store,
24
- service,
25
- config: { dreamProvider: "deepseek", dreamModel: "deepseek-chat", llmAudit: { enabled: true }, ...over }
26
- };
27
- }
28
-
29
- test("autoDream writes llm_audit_logs rows for consolidation and summary", async () => {
30
- const { store, service, config } = dreamSetup();
31
- service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
32
- service.saveWithDedupe({ type: "project", title: "旧2", content: "第二段内容" });
33
- const ctx = mockCtx({
34
- onConsolidation: (listText) => {
35
- const ids = [...listText.matchAll(/id=([^\s|]+)\s*\|\s*type=\w+\s*\|\s*importance=\d+/g)].map((m) => m[1]);
36
- return JSON.stringify(ids.map((id) => ({ action: "keep", ids: [id] })));
37
- }
38
- });
39
- const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
40
- const result = await dream.runDream(ctx, service, config);
41
- assert.equal(result.ok, true);
42
-
43
- const rows = service.listLlmAudits();
44
- assert.equal(rows.length, 2, "one consolidation + one summary audit row");
45
- const consolidate = rows.find((r) => r.operation_type === "dream_consolidate");
46
- const summarize = rows.find((r) => r.operation_type === "dream_summarize");
47
- assert.ok(consolidate, "dream_consolidate row present");
48
- assert.ok(summarize, "dream_summarize row present");
49
- assert.equal(consolidate.trigger_source, "autoDream");
50
- assert.equal(summarize.trigger_source, "autoDream");
51
- assert.equal(consolidate.status, "success");
52
- assert.equal(summarize.status, "success");
53
- // config-first (Issue #25): dreamSetup sets dreamProvider/dreamModel, so it
54
- // wins over mockCtx's agentDefaultModel (mock:stress-model) — assert the
55
- // actually-used config route.
56
- assert.equal(consolidate.model_id, "deepseek:deepseek-chat");
57
- assert.equal(summarize.model_id, "deepseek:deepseek-chat");
58
- assert.ok(Array.isArray(consolidate.related_memory_ids) && consolidate.related_memory_ids.length === 2,
59
- "consolidation audit records the snapshot ids");
60
- assert.ok(consolidate.total_tokens >= 0 && summarize.total_tokens >= 0);
61
- assert.ok(typeof consolidate.duration_ms === "number" && consolidate.duration_ms >= 0);
62
- store.close();
63
- });
64
-
65
- test("autoDream LLM failure is audited as status=error and never blocks the run", async () => {
66
- const { store, service, config } = dreamSetup();
67
- service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
68
- // Consolidation stream finishes with kind "error" → streamText returns
69
- // undefined → the run fails safe; runAuditedLlm must still leave an
70
- // error audit row before the failure propagates.
71
- const ctx = {
72
- logger: { warn: () => {} },
73
- llm: {
74
- async *stream() {
75
- yield { type: "text-delta", index: 0, text: "" };
76
- yield { type: "finish", reason: { kind: "error" } };
77
- }
78
- }
79
- };
80
- const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
81
- const result = await dream.runDream(ctx, service, config);
82
- assert.equal(result.ok, false, "aborted/errored stream fails the run");
83
- const rows = service.listLlmAudits();
84
- assert.equal(rows.length, 1, "failed consolidation still audited");
85
- assert.equal(rows[0].operation_type, "dream_consolidate");
86
- assert.equal(rows[0].status, "error");
87
- assert.ok(rows[0].error_message, "error message recorded");
88
- // the audit write did not block the failure path
89
- assert.equal(result.error, "llm failed");
90
- store.close();
91
- });
92
-
93
- test("autoDream throwing LLM is audited as status=error", async () => {
94
- const { store, service, config } = dreamSetup();
95
- service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
96
- const ctx = {
97
- logger: { warn: () => {} },
98
- llm: {
99
- async *stream() {
100
- throw new Error("network down");
101
- }
102
- }
103
- };
104
- const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
105
- const result = await dream.runDream(ctx, service, config);
106
- assert.equal(result.ok, false);
107
- const rows = service.listLlmAudits();
108
- assert.equal(rows.length, 1, "throwing call still audited");
109
- assert.equal(rows[0].status, "error");
110
- assert.match(rows[0].error_message, /network down/);
111
- store.close();
112
- });
113
-
114
- test("autoDream parse failure is audited as status=error, not fake success", async () => {
115
- const { store, service, config } = dreamSetup();
116
- service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
117
- // Stream completes fine but returns no JSON array — the run fails, and the
118
- // audit must NOT claim success (the old bug: llm_audit said dream_consolidate
119
- // success while the run recorded failed).
120
- const warnings = [];
121
- const ctx = {
122
- logger: { warn: (m) => warnings.push(m) },
123
- llm: {
124
- async *stream() {
125
- yield { type: "text-delta", index: 0, text: "抱歉,我无法解析成 JSON。" };
126
- yield { type: "finish", reason: { kind: "stop" } };
127
- }
128
- }
129
- };
130
- const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
131
- const result = await dream.runDream(ctx, service, config);
132
- assert.equal(result.ok, false);
133
- assert.equal(result.error, "no json array in llm output");
134
- const rows = service.listLlmAudits();
135
- assert.equal(rows.length, 1, "failed consolidation still audited");
136
- assert.equal(rows[0].operation_type, "dream_consolidate");
137
- assert.equal(rows[0].status, "error", "stream succeeded but output unusable → audit error");
138
- assert.match(rows[0].error_message, /no json array in llm output/);
139
- assert.ok(warnings.some((m) => m.includes("head: 抱歉,我无法解析成")), "raw output head logged for diagnosis");
140
- store.close();
141
- });
142
-
143
- test("autoDream audit is skipped when llmAudit.enabled === false", async () => {
144
- const { store, service, config } = dreamSetup({ llmAudit: { enabled: false } });
145
- service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
146
- const ctx = mockCtx();
147
- const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
148
- await dream.runDream(ctx, service, config);
149
- assert.equal(service.listLlmAudits().length, 0, "no audit rows when disabled");
150
- store.close();
151
- });
152
-
153
- test("autoSummarize writes an llm_audit_logs row (trigger_source autoSummarize)", async () => {
154
- const store = createStore(":memory:");
155
- const service = createService({ store, mirror: null, config: {} });
156
- const events = [];
157
- const ctx = {
158
- on(name, fn) {
159
- events.push({ name, fn });
160
- return () => {};
161
- },
162
- logger: { warn: () => {} },
163
- llm: {
164
- async *stream() {
165
- yield { type: "text-delta", index: 0, text: JSON.stringify([
166
- { type: "decision", title: "选型", content: "确定用 node:sqlite", importance: 4 }
167
- ]) };
168
- yield { type: "finish", reason: { kind: "stop" } };
169
- }
170
- }
171
- };
172
- const config = {
173
- autoSummarize: true,
174
- summarizeProvider: "deepseek",
175
- summarizeModel: "deepseek-chat",
176
- llmAudit: { enabled: true }
177
- };
178
- createSummarizer(ctx, service, config);
179
- const handler = events.find((e) => e.name === "session/event").fn;
180
- const session = {
181
- id: "s1",
182
- requestHeader: () => ({ config: {} }),
183
- events: [
184
- { type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "帮我选型" }] } },
185
- { seq: 2, type: "turn/end" }
186
- ]
187
- };
188
- await handler(session, { seq: 2, type: "turn/end" });
189
- const rows = service.listLlmAudits();
190
- assert.equal(rows.length, 1, "one autoSummarize audit row");
191
- assert.equal(rows[0].trigger_source, "autoSummarize");
192
- assert.equal(rows[0].operation_type, "summarize_compress");
193
- assert.equal(rows[0].model_id, "deepseek:deepseek-chat");
194
- assert.equal(rows[0].status, "success");
195
- store.close();
196
- });
197
-
198
- // --- API surface ------------------------------------------------------------
199
-
200
- class FakeRes extends EventEmitter {
201
- constructor() { super(); this.statusCode = 200; this.body = ""; }
202
- writeHead(code, headers) { this.statusCode = code; this.headers = headers; return this; }
203
- end(text) { this.body = text ?? ""; this.emit("end"); return this; }
204
- }
205
-
206
- function req(path) {
207
- const r = new EventEmitter();
208
- r.url = path;
209
- r.method = "GET";
210
- r.headers = {};
211
- return r;
212
- }
213
-
214
- function apiSetup() {
215
- const store = createStore(":memory:");
216
- const service = createService({ store, mirror: null, config: {} });
217
- const settings = createSettings(store.db);
218
- const routes = [];
219
- const ctx = {
220
- webServer: {
221
- register(route) {
222
- routes.push(route);
223
- return () => {};
224
- }
225
- }
226
- };
227
- createApi(ctx, service, settings, { add: () => {}, remove: () => false, list: () => [] });
228
- return { store, service, routes };
229
- }
230
-
231
- test("GET /api/dsh-mneme/semantic/llm-audit paginates and filters by source", async () => {
232
- const { store, service, routes } = apiSetup();
233
- for (let i = 0; i < 3; i++) {
234
- service.saveLlmAudit({
235
- trigger_source: "autoDream",
236
- operation_type: "dream_consolidate",
237
- model_id: "deepseek:deepseek-chat",
238
- input_tokens: 10, output_tokens: 5, status: "success"
239
- });
240
- }
241
- service.saveLlmAudit({
242
- trigger_source: "autoSummarize",
243
- operation_type: "summarize_compress",
244
- model_id: "deepseek:deepseek-chat",
245
- input_tokens: 3, output_tokens: 1, status: "success"
246
- });
247
- const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit");
248
-
249
- // full page
250
- let res = new FakeRes();
251
- await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=1&pageSize=2"), res);
252
- let data = JSON.parse(res.body);
253
- assert.equal(res.statusCode, 200);
254
- assert.equal(data.total, 4);
255
- assert.equal(data.page, 1);
256
- assert.equal(data.pageSize, 2);
257
- assert.equal(data.items.length, 2);
258
-
259
- // second page
260
- res = new FakeRes();
261
- await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=2&pageSize=2"), res);
262
- data = JSON.parse(res.body);
263
- assert.equal(data.items.length, 2, "page 2 has the remaining rows");
264
- assert.equal(data.total, 4);
265
-
266
- // source filter
267
- res = new FakeRes();
268
- await route.handler(req("/api/dsh-mneme/semantic/llm-audit?source=autoSummarize"), res);
269
- data = JSON.parse(res.body);
270
- assert.equal(data.total, 1);
271
- assert.equal(data.items[0].trigger_source, "autoSummarize");
272
- store.close();
273
- });
274
-
275
- test("GET /api/dsh-mneme/semantic/llm-audit/stats aggregates by source and status", async () => {
276
- const { store, service, routes } = apiSetup();
277
- service.saveLlmAudit({
278
- timestamp: new Date().toISOString(),
279
- trigger_source: "autoDream", operation_type: "dream_consolidate",
280
- model_id: "m", input_tokens: 100, output_tokens: 40, duration_ms: 25, status: "success"
281
- });
282
- service.saveLlmAudit({
283
- timestamp: new Date().toISOString(),
284
- trigger_source: "autoDream", operation_type: "dream_summarize",
285
- model_id: "m", input_tokens: 30, output_tokens: 10, duration_ms: 8, status: "success"
286
- });
287
- service.saveLlmAudit({
288
- timestamp: new Date().toISOString(),
289
- trigger_source: "autoSummarize", operation_type: "summarize_compress",
290
- model_id: "m", input_tokens: 5, output_tokens: 2, duration_ms: 4, status: "error"
291
- });
292
- const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit/stats");
293
- const res = new FakeRes();
294
- await route.handler(req("/api/dsh-mneme/semantic/llm-audit/stats?days=7"), res);
295
- const stats = JSON.parse(res.body);
296
- assert.equal(res.statusCode, 200);
297
- assert.equal(stats.days, 7);
298
- assert.equal(stats.total_calls, 3);
299
- assert.equal(stats.input_tokens, 135);
300
- assert.equal(stats.output_tokens, 52);
301
- assert.equal(stats.total_tokens, 187);
302
- assert.equal(stats.total_duration_ms, 37);
303
- const bySource = stats.by_source.find((s) => s.source === "autoDream");
304
- assert.equal(bySource.c, 2);
305
- assert.equal(bySource.total_tokens, 180);
306
- const errStatus = stats.by_status.find((s) => s.status === "error");
307
- assert.equal(errStatus.c, 1);
308
- store.close();
309
- });
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { EventEmitter } from "node:events";
4
+ import { createStore } from "../src/store.js";
5
+ import { createService } from "../src/service.js";
6
+ import { createDreamScheduler } from "../src/dream.js";
7
+ import { createSummarizer } from "../src/summarize.js";
8
+ import { createApi } from "../src/api.js";
9
+ import { createSettings } from "../src/settings.js";
10
+ import { mockCtx } from "./helpers/dream-mock.js";
11
+
12
+ // Bug8: LLM audit trail. Every background LLM call (autoDream consolidation +
13
+ // summary, autoSummarize compression) records tokens/time/status into
14
+ // llm_audit_logs. Failures are captured as status='error' and never block the
15
+ // calling feature. Read back through the API (/llm-audit + /llm-audit/stats).
16
+ // Gating: runDream treats llmAudit.enabled === false as off; summarize treats
17
+ // llmAudit.enabled !== false as on.
18
+
19
+ function dreamSetup(over = {}) {
20
+ const store = createStore(":memory:");
21
+ const service = createService({ store, mirror: null, config: {} });
22
+ return {
23
+ store,
24
+ service,
25
+ config: { dreamProvider: "deepseek", dreamModel: "deepseek-chat", llmAudit: { enabled: true }, ...over }
26
+ };
27
+ }
28
+
29
+ test("autoDream writes llm_audit_logs rows for consolidation and summary", async () => {
30
+ const { store, service, config } = dreamSetup();
31
+ service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
32
+ service.saveWithDedupe({ type: "project", title: "旧2", content: "第二段内容" });
33
+ const ctx = mockCtx({
34
+ onConsolidation: (listText) => {
35
+ const ids = [...listText.matchAll(/id=([^\s|]+)\s*\|\s*type=\w+\s*\|\s*importance=\d+/g)].map((m) => m[1]);
36
+ return JSON.stringify(ids.map((id) => ({ action: "keep", ids: [id] })));
37
+ }
38
+ });
39
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
40
+ const result = await dream.runDream(ctx, service, config);
41
+ assert.equal(result.ok, true);
42
+
43
+ const rows = service.listLlmAudits();
44
+ assert.equal(rows.length, 2, "one consolidation + one summary audit row");
45
+ const consolidate = rows.find((r) => r.operation_type === "dream_consolidate");
46
+ const summarize = rows.find((r) => r.operation_type === "dream_summarize");
47
+ assert.ok(consolidate, "dream_consolidate row present");
48
+ assert.ok(summarize, "dream_summarize row present");
49
+ assert.equal(consolidate.trigger_source, "autoDream");
50
+ assert.equal(summarize.trigger_source, "autoDream");
51
+ assert.equal(consolidate.status, "success");
52
+ assert.equal(summarize.status, "success");
53
+ // config-first (Issue #25): dreamSetup sets dreamProvider/dreamModel, so it
54
+ // wins over mockCtx's agentDefaultModel (mock:stress-model) — assert the
55
+ // actually-used config route.
56
+ assert.equal(consolidate.model_id, "deepseek:deepseek-chat");
57
+ assert.equal(summarize.model_id, "deepseek:deepseek-chat");
58
+ assert.ok(Array.isArray(consolidate.related_memory_ids) && consolidate.related_memory_ids.length === 2,
59
+ "consolidation audit records the snapshot ids");
60
+ assert.ok(consolidate.total_tokens >= 0 && summarize.total_tokens >= 0);
61
+ assert.ok(typeof consolidate.duration_ms === "number" && consolidate.duration_ms >= 0);
62
+ store.close();
63
+ });
64
+
65
+ test("autoDream LLM failure is audited as status=error and never blocks the run", async () => {
66
+ const { store, service, config } = dreamSetup();
67
+ service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
68
+ // Consolidation stream finishes with kind "error" → streamText returns
69
+ // undefined → the run fails safe; runAuditedLlm must still leave an
70
+ // error audit row before the failure propagates.
71
+ const ctx = {
72
+ logger: { warn: () => {} },
73
+ llm: {
74
+ async *stream() {
75
+ yield { type: "text-delta", index: 0, text: "" };
76
+ yield { type: "finish", reason: { kind: "error" } };
77
+ }
78
+ }
79
+ };
80
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
81
+ const result = await dream.runDream(ctx, service, config);
82
+ assert.equal(result.ok, false, "aborted/errored stream fails the run");
83
+ const rows = service.listLlmAudits();
84
+ assert.equal(rows.length, 1, "failed consolidation still audited");
85
+ assert.equal(rows[0].operation_type, "dream_consolidate");
86
+ assert.equal(rows[0].status, "error");
87
+ assert.ok(rows[0].error_message, "error message recorded");
88
+ // the audit write did not block the failure path
89
+ assert.equal(result.error, "llm failed");
90
+ store.close();
91
+ });
92
+
93
+ test("autoDream throwing LLM is audited as status=error", async () => {
94
+ const { store, service, config } = dreamSetup();
95
+ service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
96
+ const ctx = {
97
+ logger: { warn: () => {} },
98
+ llm: {
99
+ async *stream() {
100
+ throw new Error("network down");
101
+ }
102
+ }
103
+ };
104
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
105
+ const result = await dream.runDream(ctx, service, config);
106
+ assert.equal(result.ok, false);
107
+ const rows = service.listLlmAudits();
108
+ assert.equal(rows.length, 1, "throwing call still audited");
109
+ assert.equal(rows[0].status, "error");
110
+ assert.match(rows[0].error_message, /network down/);
111
+ store.close();
112
+ });
113
+
114
+ test("autoDream parse failure is audited as status=error, not fake success", async () => {
115
+ const { store, service, config } = dreamSetup();
116
+ service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
117
+ // Stream completes fine but returns no JSON array — the run fails, and the
118
+ // audit must NOT claim success (the old bug: llm_audit said dream_consolidate
119
+ // success while the run recorded failed).
120
+ const warnings = [];
121
+ const ctx = {
122
+ logger: { warn: (m) => warnings.push(m) },
123
+ llm: {
124
+ async *stream() {
125
+ yield { type: "text-delta", index: 0, text: "抱歉,我无法解析成 JSON。" };
126
+ yield { type: "finish", reason: { kind: "stop" } };
127
+ }
128
+ }
129
+ };
130
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
131
+ const result = await dream.runDream(ctx, service, config);
132
+ assert.equal(result.ok, false);
133
+ assert.equal(result.error, "no json array in llm output");
134
+ const rows = service.listLlmAudits();
135
+ assert.equal(rows.length, 1, "failed consolidation still audited");
136
+ assert.equal(rows[0].operation_type, "dream_consolidate");
137
+ assert.equal(rows[0].status, "error", "stream succeeded but output unusable → audit error");
138
+ assert.match(rows[0].error_message, /no json array in llm output/);
139
+ assert.ok(warnings.some((m) => m.includes("head: 抱歉,我无法解析成")), "raw output head logged for diagnosis");
140
+ store.close();
141
+ });
142
+
143
+ test("autoDream audit is skipped when llmAudit.enabled === false", async () => {
144
+ const { store, service, config } = dreamSetup({ llmAudit: { enabled: false } });
145
+ service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
146
+ const ctx = mockCtx();
147
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
148
+ await dream.runDream(ctx, service, config);
149
+ assert.equal(service.listLlmAudits().length, 0, "no audit rows when disabled");
150
+ store.close();
151
+ });
152
+
153
+ test("autoSummarize writes an llm_audit_logs row (trigger_source autoSummarize)", async () => {
154
+ const store = createStore(":memory:");
155
+ const service = createService({ store, mirror: null, config: {} });
156
+ const events = [];
157
+ const ctx = {
158
+ on(name, fn) {
159
+ events.push({ name, fn });
160
+ return () => {};
161
+ },
162
+ logger: { warn: () => {} },
163
+ llm: {
164
+ async *stream() {
165
+ yield { type: "text-delta", index: 0, text: JSON.stringify([
166
+ { type: "decision", title: "选型", content: "确定用 node:sqlite", importance: 4 }
167
+ ]) };
168
+ yield { type: "finish", reason: { kind: "stop" } };
169
+ }
170
+ }
171
+ };
172
+ const config = {
173
+ autoSummarize: true,
174
+ summarizeProvider: "deepseek",
175
+ summarizeModel: "deepseek-chat",
176
+ llmAudit: { enabled: true }
177
+ };
178
+ createSummarizer(ctx, service, config);
179
+ const handler = events.find((e) => e.name === "session/event").fn;
180
+ const session = {
181
+ id: "s1",
182
+ requestHeader: () => ({ config: {} }),
183
+ events: [
184
+ { type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "帮我选型" }] } },
185
+ { seq: 2, type: "turn/end" }
186
+ ]
187
+ };
188
+ await handler(session, { seq: 2, type: "turn/end" });
189
+ const rows = service.listLlmAudits();
190
+ assert.equal(rows.length, 1, "one autoSummarize audit row");
191
+ assert.equal(rows[0].trigger_source, "autoSummarize");
192
+ assert.equal(rows[0].operation_type, "summarize_compress");
193
+ assert.equal(rows[0].model_id, "deepseek:deepseek-chat");
194
+ assert.equal(rows[0].status, "success");
195
+ store.close();
196
+ });
197
+
198
+ // --- token 记账:用量嵌在 chunk.usage 下 -------------------------------------
199
+ // 真实 dsh-llm 协议的用量形状是 { type:"usage", usage: TokenUsage }(TokenUsage
200
+ // = { inputTokens, outputTokens, … }),chunk 顶层没有 token 字段。把整个 chunk
201
+ // 当用量对象读取会让 input/output 恒为 undefined,审计行落 0:本机实测 7 天 49
202
+ // 次 success 调用 total_tokens 全 0,面板「LLM 消耗」永远显示 0。下面三例锁住
203
+ // 真实形状,并保留用量平铺在顶层的兼容分支。
204
+
205
+ /** 在 base ctx 的流末尾(finish 之前)插入一个 usage chunk。 */
206
+ function withUsageChunk(base, usageChunk) {
207
+ return {
208
+ ...base,
209
+ llm: {
210
+ async *stream(options) {
211
+ for await (const chunk of base.llm.stream(options)) {
212
+ if (chunk.type === "finish") yield usageChunk;
213
+ yield chunk;
214
+ }
215
+ }
216
+ }
217
+ };
218
+ }
219
+
220
+ /** consolidation 决策:全部 keep,保证 run 成功且无需解析语义。 */
221
+ const keepAllDecisions = (listText) => {
222
+ const ids = [...listText.matchAll(/id=([^\s|]+)\s*\|\s*type=\w+\s*\|\s*importance=\d+/g)].map((m) => m[1]);
223
+ return JSON.stringify(ids.map((id) => ({ action: "keep", ids: [id] })));
224
+ };
225
+
226
+ test("autoDream records tokens from the nested usage chunk (chunk.usage)", async () => {
227
+ const { store, service, config } = dreamSetup();
228
+ service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
229
+ const ctx = withUsageChunk(
230
+ mockCtx({ onConsolidation: keepAllDecisions }),
231
+ { type: "usage", usage: { inputTokens: 1200, outputTokens: 300, totalTokens: 1500 } }
232
+ );
233
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
234
+ const result = await dream.runDream(ctx, service, config);
235
+ assert.equal(result.ok, true);
236
+
237
+ const rows = service.listLlmAudits();
238
+ const consolidate = rows.find((r) => r.operation_type === "dream_consolidate");
239
+ assert.equal(consolidate.input_tokens, 1200, "input tokens come from chunk.usage");
240
+ assert.equal(consolidate.output_tokens, 300, "output tokens come from chunk.usage");
241
+ assert.equal(consolidate.total_tokens, 1500);
242
+ const summary = rows.find((r) => r.operation_type === "dream_summarize");
243
+ assert.equal(summary.total_tokens, 1500, "the dream summary call is accounted too");
244
+ store.close();
245
+ });
246
+
247
+ test("autoSummarize records tokens from the nested usage chunk (chunk.usage)", async () => {
248
+ const store = createStore(":memory:");
249
+ const service = createService({ store, mirror: null, config: {} });
250
+ const events = [];
251
+ const ctx = withUsageChunk({
252
+ on(name, fn) {
253
+ events.push({ name, fn });
254
+ return () => {};
255
+ },
256
+ logger: { warn: () => {} },
257
+ llm: {
258
+ async *stream() {
259
+ yield { type: "text-delta", index: 0, text: JSON.stringify([
260
+ { type: "decision", title: "选型", content: "确定用 node:sqlite", importance: 4 }
261
+ ]) };
262
+ yield { type: "finish", reason: { kind: "stop" } };
263
+ }
264
+ }
265
+ }, { type: "usage", usage: { inputTokens: 800, outputTokens: 200, totalTokens: 1000 } });
266
+ const config = {
267
+ autoSummarize: true,
268
+ summarizeProvider: "deepseek",
269
+ summarizeModel: "deepseek-chat",
270
+ llmAudit: { enabled: true }
271
+ };
272
+ createSummarizer(ctx, service, config);
273
+ const handler = events.find((e) => e.name === "session/event").fn;
274
+ const session = {
275
+ id: "s1",
276
+ requestHeader: () => ({ config: {} }),
277
+ events: [
278
+ { type: "user/message", data: { source: { kind: "user" }, content: [{ type: "text", text: "帮我选型" }] } },
279
+ { seq: 2, type: "turn/end" }
280
+ ]
281
+ };
282
+ await handler(session, { seq: 2, type: "turn/end" });
283
+
284
+ const rows = service.listLlmAudits();
285
+ assert.equal(rows.length, 1);
286
+ assert.equal(rows[0].input_tokens, 800, "input tokens come from chunk.usage");
287
+ assert.equal(rows[0].output_tokens, 200, "output tokens come from chunk.usage");
288
+ assert.equal(rows[0].total_tokens, 1000);
289
+ store.close();
290
+ });
291
+
292
+ test("flat top-level usage shape still records tokens", async () => {
293
+ const { store, service, config } = dreamSetup();
294
+ service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
295
+ const ctx = withUsageChunk(
296
+ mockCtx({ onConsolidation: keepAllDecisions }),
297
+ { type: "usage", inputTokens: 40, outputTokens: 10 }
298
+ );
299
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
300
+ await dream.runDream(ctx, service, config);
301
+ const consolidate = service.listLlmAudits().find((r) => r.operation_type === "dream_consolidate");
302
+ assert.equal(consolidate.total_tokens, 50, "flat shape is still readable");
303
+ store.close();
304
+ });
305
+
306
+ // --- token 记账的边界语义 ----------------------------------------------------
307
+ // 上面三例锁的是「有 usage chunk 且形状正确」。契约的另一半是「没有用量时的
308
+ // 行为」:未知不等于错误,记 0(不崩,也不凭空编数),同时保留协议演进时
309
+ // 用量平铺在 chunk 根的读法。
310
+
311
+ test("no usage chunk at all still writes 0 tokens and never crashes", async () => {
312
+ const { store, service, config } = dreamSetup();
313
+ service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
314
+ // 桩的原始形状就是不发 usage chunk:适配器未上报用量的情形走这条路径。
315
+ const ctx = mockCtx({ onConsolidation: keepAllDecisions });
316
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
317
+ const result = await dream.runDream(ctx, service, config);
318
+ assert.equal(result.ok, true, "缺少用量不该让巩固本身失败");
319
+ const rows = service.listLlmAudits();
320
+ assert.ok(rows.length >= 1, "巩固那行仍然要写下");
321
+ for (const row of rows) {
322
+ assert.equal(row.input_tokens, 0, "未知用量记 0,不编数");
323
+ assert.equal(row.output_tokens, 0);
324
+ assert.equal(row.total_tokens, 0);
325
+ }
326
+ store.close();
327
+ });
328
+
329
+ test("root-level flattened usage fields still record tokens (protocol fallback)", async () => {
330
+ const { store, service, config } = dreamSetup();
331
+ service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
332
+ // 用量数字直接挂在 chunk 根、没有嵌套 usage 对象,命中的是 `chunk.usage ?? chunk`
333
+ // 的兜底分支;这里用 snake_case,锁住读取端的别名链。
334
+ const ctx = withUsageChunk(
335
+ mockCtx({ onConsolidation: keepAllDecisions }),
336
+ { type: "usage", input_tokens: 9, output_tokens: 3 }
337
+ );
338
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
339
+ const result = await dream.runDream(ctx, service, config);
340
+ assert.equal(result.ok, true);
341
+ const rows = service.listLlmAudits();
342
+ assert.ok(rows.length >= 1);
343
+ for (const row of rows) {
344
+ assert.equal(row.input_tokens, 9, "根级平铺字段仍可读");
345
+ assert.equal(row.output_tokens, 3);
346
+ assert.equal(row.total_tokens, 12);
347
+ }
348
+ store.close();
349
+ });
350
+
351
+ // --- API surface ------------------------------------------------------------
352
+
353
+ class FakeRes extends EventEmitter {
354
+ constructor() { super(); this.statusCode = 200; this.body = ""; }
355
+ writeHead(code, headers) { this.statusCode = code; this.headers = headers; return this; }
356
+ end(text) { this.body = text ?? ""; this.emit("end"); return this; }
357
+ }
358
+
359
+ function req(path) {
360
+ const r = new EventEmitter();
361
+ r.url = path;
362
+ r.method = "GET";
363
+ r.headers = {};
364
+ return r;
365
+ }
366
+
367
+ function apiSetup() {
368
+ const store = createStore(":memory:");
369
+ const service = createService({ store, mirror: null, config: {} });
370
+ const settings = createSettings(store.db);
371
+ const routes = [];
372
+ const ctx = {
373
+ webServer: {
374
+ register(route) {
375
+ routes.push(route);
376
+ return () => {};
377
+ }
378
+ }
379
+ };
380
+ createApi(ctx, service, settings, { add: () => {}, remove: () => false, list: () => [] });
381
+ return { store, service, routes };
382
+ }
383
+
384
+ test("GET /api/dsh-mneme/semantic/llm-audit paginates and filters by source", async () => {
385
+ const { store, service, routes } = apiSetup();
386
+ for (let i = 0; i < 3; i++) {
387
+ service.saveLlmAudit({
388
+ trigger_source: "autoDream",
389
+ operation_type: "dream_consolidate",
390
+ model_id: "deepseek:deepseek-chat",
391
+ input_tokens: 10, output_tokens: 5, status: "success"
392
+ });
393
+ }
394
+ service.saveLlmAudit({
395
+ trigger_source: "autoSummarize",
396
+ operation_type: "summarize_compress",
397
+ model_id: "deepseek:deepseek-chat",
398
+ input_tokens: 3, output_tokens: 1, status: "success"
399
+ });
400
+ const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit");
401
+
402
+ // full page
403
+ let res = new FakeRes();
404
+ await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=1&pageSize=2"), res);
405
+ let data = JSON.parse(res.body);
406
+ assert.equal(res.statusCode, 200);
407
+ assert.equal(data.total, 4);
408
+ assert.equal(data.page, 1);
409
+ assert.equal(data.pageSize, 2);
410
+ assert.equal(data.items.length, 2);
411
+
412
+ // second page
413
+ res = new FakeRes();
414
+ await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=2&pageSize=2"), res);
415
+ data = JSON.parse(res.body);
416
+ assert.equal(data.items.length, 2, "page 2 has the remaining rows");
417
+ assert.equal(data.total, 4);
418
+
419
+ // source filter
420
+ res = new FakeRes();
421
+ await route.handler(req("/api/dsh-mneme/semantic/llm-audit?source=autoSummarize"), res);
422
+ data = JSON.parse(res.body);
423
+ assert.equal(data.total, 1);
424
+ assert.equal(data.items[0].trigger_source, "autoSummarize");
425
+ store.close();
426
+ });
427
+
428
+ test("GET /api/dsh-mneme/semantic/llm-audit/stats aggregates by source and status", async () => {
429
+ const { store, service, routes } = apiSetup();
430
+ service.saveLlmAudit({
431
+ timestamp: new Date().toISOString(),
432
+ trigger_source: "autoDream", operation_type: "dream_consolidate",
433
+ model_id: "m", input_tokens: 100, output_tokens: 40, duration_ms: 25, status: "success"
434
+ });
435
+ service.saveLlmAudit({
436
+ timestamp: new Date().toISOString(),
437
+ trigger_source: "autoDream", operation_type: "dream_summarize",
438
+ model_id: "m", input_tokens: 30, output_tokens: 10, duration_ms: 8, status: "success"
439
+ });
440
+ service.saveLlmAudit({
441
+ timestamp: new Date().toISOString(),
442
+ trigger_source: "autoSummarize", operation_type: "summarize_compress",
443
+ model_id: "m", input_tokens: 5, output_tokens: 2, duration_ms: 4, status: "error"
444
+ });
445
+ const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit/stats");
446
+ const res = new FakeRes();
447
+ await route.handler(req("/api/dsh-mneme/semantic/llm-audit/stats?days=7"), res);
448
+ const stats = JSON.parse(res.body);
449
+ assert.equal(res.statusCode, 200);
450
+ assert.equal(stats.days, 7);
451
+ assert.equal(stats.total_calls, 3);
452
+ assert.equal(stats.input_tokens, 135);
453
+ assert.equal(stats.output_tokens, 52);
454
+ assert.equal(stats.total_tokens, 187);
455
+ assert.equal(stats.total_duration_ms, 37);
456
+ const bySource = stats.by_source.find((s) => s.source === "autoDream");
457
+ assert.equal(bySource.c, 2);
458
+ assert.equal(bySource.total_tokens, 180);
459
+ const errStatus = stats.by_status.find((s) => s.status === "error");
460
+ assert.equal(errStatus.c, 1);
461
+ store.close();
462
+ });