@modusensus/dsh-mneme 0.8.3 → 0.8.4

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 (193) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +718 -636
  3. package/bin/cli.mjs +0 -0
  4. package/bin/dsh-mneme-mcp.mjs +502 -0
  5. package/cordis.patch.yml +21 -21
  6. package/lib/api-standalone.js +495 -316
  7. package/lib/api.js +1382 -1316
  8. package/lib/bootstrap.js +211 -0
  9. package/lib/client.js +4475 -4366
  10. package/lib/commands.js +95 -95
  11. package/lib/config.js +533 -510
  12. package/lib/dream/clustering.js +118 -118
  13. package/lib/dream/decisions.js +658 -658
  14. package/lib/dream/narratives.js +44 -0
  15. package/lib/dream/sleep.js +700 -700
  16. package/lib/dream.js +1319 -1216
  17. package/lib/embedding.js +177 -177
  18. package/lib/entities/extractor.js +249 -249
  19. package/lib/heat.js +142 -136
  20. package/lib/hot-memory.js +46 -46
  21. package/lib/index.js +515 -515
  22. package/lib/inject.js +299 -295
  23. package/lib/lang.js +202 -179
  24. package/lib/local-embedder.js +320 -320
  25. package/lib/mirror.js +198 -198
  26. package/lib/quality-filter.js +126 -126
  27. package/lib/recall-stats.js +103 -0
  28. package/lib/reranker.js +269 -269
  29. package/lib/runtime/adopt.js +176 -176
  30. package/lib/runtime/closure.js +172 -172
  31. package/lib/runtime/download.js +247 -247
  32. package/lib/runtime/layout.js +235 -235
  33. package/lib/runtime/loader.js +249 -249
  34. package/lib/runtime/model-fetch.js +361 -361
  35. package/lib/runtime/provision.js +237 -237
  36. package/lib/runtime/tarball.js +130 -130
  37. package/lib/runtime/verify.js +191 -191
  38. package/lib/scope.js +118 -118
  39. package/lib/search/adaptive.js +22 -22
  40. package/lib/search/bm25.js +96 -96
  41. package/lib/service.js +2171 -2087
  42. package/lib/settings.js +430 -420
  43. package/lib/store.js +2448 -2367
  44. package/lib/summarize.js +575 -449
  45. package/lib/tools.js +574 -574
  46. package/lib/vector-index.js +110 -110
  47. package/lib/version-check.js +122 -122
  48. package/package.json +109 -108
  49. package/runtime-manifest.json +596 -596
  50. package/scripts/benchmark-embed.js +201 -201
  51. package/scripts/benchmark-recall.js +199 -199
  52. package/scripts/benchmark-rerank.js +166 -166
  53. package/scripts/build-runtime-manifest.mjs +217 -217
  54. package/scripts/check-sync.js +42 -42
  55. package/scripts/e2e-dsh.js +220 -220
  56. package/scripts/mneme-runtime.mjs +277 -277
  57. package/scripts/stress-dsh.js +255 -255
  58. package/scripts/sync-lib.js +47 -47
  59. package/scripts/sync-test-badge.mjs +61 -61
  60. package/src/api-standalone.js +495 -316
  61. package/src/api.js +1382 -1316
  62. package/src/bootstrap.js +211 -0
  63. package/src/commands.js +95 -95
  64. package/src/config.js +533 -510
  65. package/src/dream/clustering.js +118 -118
  66. package/src/dream/decisions.js +658 -658
  67. package/src/dream/narratives.js +44 -0
  68. package/src/dream/sleep.js +700 -700
  69. package/src/dream.js +1319 -1216
  70. package/src/embedding.js +177 -177
  71. package/src/entities/extractor.js +249 -249
  72. package/src/heat.js +142 -136
  73. package/src/hot-memory.js +46 -46
  74. package/src/index.js +515 -515
  75. package/src/inject.js +299 -295
  76. package/src/lang.js +202 -179
  77. package/src/local-embedder.js +320 -320
  78. package/src/mirror.js +198 -198
  79. package/src/quality-filter.js +126 -126
  80. package/src/recall-stats.js +103 -0
  81. package/src/reranker.js +269 -269
  82. package/src/runtime/adopt.js +176 -176
  83. package/src/runtime/closure.js +172 -172
  84. package/src/runtime/download.js +247 -247
  85. package/src/runtime/layout.js +235 -235
  86. package/src/runtime/loader.js +249 -249
  87. package/src/runtime/model-fetch.js +361 -361
  88. package/src/runtime/provision.js +237 -237
  89. package/src/runtime/tarball.js +130 -130
  90. package/src/runtime/verify.js +191 -191
  91. package/src/scope.js +118 -118
  92. package/src/search/adaptive.js +22 -22
  93. package/src/search/bm25.js +96 -96
  94. package/src/service.js +2171 -2087
  95. package/src/settings.js +430 -420
  96. package/src/store.js +2448 -2367
  97. package/src/summarize.js +575 -449
  98. package/src/tools.js +574 -574
  99. package/src/vector-index.js +110 -110
  100. package/src/version-check.js +122 -122
  101. package/test/api-routes-gaps.test.js +218 -218
  102. package/test/api.test.js +1578 -1482
  103. package/test/audit.test.js +448 -448
  104. package/test/benchmark.test.js +94 -94
  105. package/test/bootstrap.test.js +220 -0
  106. package/test/client.test.js +799 -736
  107. package/test/clustering.test.js +100 -100
  108. package/test/commands.test.js +106 -106
  109. package/test/config.test.js +66 -66
  110. package/test/conflict-freeze.test.js +300 -300
  111. package/test/dream-archive-guardrail.test.js +116 -116
  112. package/test/dream-candidate-hybrid.test.js +281 -281
  113. package/test/dream-coverage-degrade.test.js +86 -86
  114. package/test/dream.test.js +1257 -1254
  115. package/test/embedding-ready.test.js +196 -196
  116. package/test/entities.test.js +547 -547
  117. package/test/entity-recall.test.js +179 -0
  118. package/test/epistemic.test.js +298 -298
  119. package/test/fnew-0112.test.js +311 -311
  120. package/test/fnew-03.test.js +422 -422
  121. package/test/graph-api.test.js +175 -175
  122. package/test/heat.test.js +175 -148
  123. package/test/helpers/dream-mock.js +82 -82
  124. package/test/helpers/peer-worker.mjs +25 -25
  125. package/test/helpers/runtime-source.js +60 -60
  126. package/test/helpers/tar-builder.js +80 -80
  127. package/test/hot-memory.test.js +145 -145
  128. package/test/inject-content-cap.test.js +89 -0
  129. package/test/inject-first-round-bm25.test.js +89 -89
  130. package/test/inject-heat.test.js +61 -0
  131. package/test/inject-rotation.test.js +161 -161
  132. package/test/inject.test.js +249 -249
  133. package/test/lang.test.js +87 -87
  134. package/test/lib-smoke.test.js +96 -96
  135. package/test/llm-audit.test.js +309 -309
  136. package/test/llm-message-source.test.js +177 -177
  137. package/test/local-embedder.test.js +249 -249
  138. package/test/mcp-stdio.test.js +385 -0
  139. package/test/mirror-dirty.test.js +424 -424
  140. package/test/mirror-edit-digest.test.js +187 -187
  141. package/test/mirror-generation.test.js +499 -499
  142. package/test/mirror.test.js +249 -249
  143. package/test/narrative-bars.test.js +162 -0
  144. package/test/peer-blockers.test.js +193 -193
  145. package/test/policy-epoch.test.js +259 -259
  146. package/test/quality-filter.test.js +186 -186
  147. package/test/reasoning-effort.test.js +746 -746
  148. package/test/recall-evals.test.js +235 -235
  149. package/test/recall-layer.test.js +326 -326
  150. package/test/recall-stats.test.js +117 -0
  151. package/test/receipt-chain.test.js +451 -451
  152. package/test/reflection.test.js +226 -226
  153. package/test/reindex-backfill.test.js +62 -62
  154. package/test/reranker-single-logit.test.js +73 -73
  155. package/test/reranker.test.js +197 -197
  156. package/test/resident-status.test.js +83 -0
  157. package/test/runtime-adopt.test.js +206 -206
  158. package/test/runtime-cli.test.js +89 -89
  159. package/test/runtime-closure.test.js +193 -193
  160. package/test/runtime-download.test.js +302 -302
  161. package/test/runtime-layout.test.js +163 -163
  162. package/test/runtime-loader.test.js +237 -237
  163. package/test/runtime-manifest.test.js +158 -158
  164. package/test/runtime-model-fetch.test.js +348 -348
  165. package/test/runtime-provision.test.js +101 -101
  166. package/test/runtime-tarball.test.js +81 -81
  167. package/test/runtime-verify.test.js +214 -214
  168. package/test/scope-candidates.test.js +239 -239
  169. package/test/scope-explicit.test.js +452 -452
  170. package/test/scope-retrieval.test.js +197 -197
  171. package/test/scope-storage.test.js +255 -255
  172. package/test/scope-strict.test.js +231 -231
  173. package/test/search-fusion.test.js +90 -90
  174. package/test/semantic.test.js +124 -124
  175. package/test/service-search.test.js +174 -174
  176. package/test/service.test.js +405 -405
  177. package/test/settings.test.js +261 -261
  178. package/test/skip-invalid-restore.test.js +262 -262
  179. package/test/sleep-action-set.test.js +422 -422
  180. package/test/sleep-heat.test.js +126 -125
  181. package/test/sleep-scheduler-rearm.test.js +89 -89
  182. package/test/sleep.test.js +373 -373
  183. package/test/standalone-api.test.js +544 -359
  184. package/test/store-vector-cache.test.js +98 -98
  185. package/test/store.test.js +383 -383
  186. package/test/stress.test.js +209 -209
  187. package/test/summarize.test.js +884 -575
  188. package/test/tools-memory-get-schema.test.js +65 -65
  189. package/test/tools.test.js +341 -341
  190. package/test/updated-at-semantics.test.js +113 -113
  191. package/test/vector-index.test.js +221 -221
  192. package/test/version-check.test.js +152 -152
  193. package/test/webServer-optional.test.js +82 -82
@@ -1,309 +1,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
- // --- 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
+ // --- 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
+ });