@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.
- package/LICENSE +21 -21
- package/README.md +727 -636
- package/bin/cli.mjs +0 -0
- package/bin/dsh-mneme-mcp.mjs +510 -0
- package/cordis.patch.yml +21 -21
- package/lib/api-standalone.js +506 -316
- package/lib/api.js +1403 -1316
- package/lib/bootstrap.js +211 -0
- package/lib/client.js +4657 -4366
- package/lib/commands.js +95 -95
- package/lib/config.js +615 -510
- package/lib/document.js +221 -0
- package/lib/dream/clustering.js +118 -118
- package/lib/dream/decisions.js +658 -658
- package/lib/dream/narratives.js +44 -0
- package/lib/dream/sleep.js +702 -700
- package/lib/dream.js +147 -16
- package/lib/embedding.js +177 -177
- package/lib/entities/extractor.js +249 -249
- package/lib/guide.js +44 -0
- package/lib/heat.js +144 -136
- package/lib/hot-memory.js +46 -46
- package/lib/index.js +515 -515
- package/lib/inject.js +375 -295
- package/lib/lang.js +208 -179
- package/lib/local-embedder.js +320 -320
- package/lib/mirror.js +198 -198
- package/lib/organize.js +450 -0
- package/lib/quality-filter.js +126 -126
- package/lib/recall-stats.js +125 -0
- package/lib/reranker.js +269 -269
- package/lib/runtime/adopt.js +176 -176
- package/lib/runtime/closure.js +172 -172
- package/lib/runtime/download.js +247 -247
- package/lib/runtime/layout.js +265 -235
- package/lib/runtime/loader.js +252 -249
- package/lib/runtime/model-fetch.js +361 -361
- package/lib/runtime/provision.js +237 -237
- package/lib/runtime/tarball.js +130 -130
- package/lib/runtime/verify.js +204 -191
- package/lib/scope.js +118 -118
- package/lib/search/adaptive.js +60 -22
- package/lib/search/bm25.js +96 -96
- package/lib/service.js +2324 -2087
- package/lib/settings.js +459 -420
- package/lib/store.js +2549 -2367
- package/lib/summarize.js +820 -449
- package/lib/tools.js +702 -574
- package/lib/vector-index.js +110 -110
- package/lib/version-check.js +122 -122
- package/package.json +109 -108
- package/runtime-manifest.json +526 -596
- package/scripts/benchmark-embed.js +201 -201
- package/scripts/benchmark-recall.js +199 -199
- package/scripts/benchmark-rerank.js +166 -166
- package/scripts/build-runtime-manifest.mjs +224 -217
- package/scripts/check-sync.js +42 -42
- package/scripts/e2e-dsh.js +220 -220
- package/scripts/mneme-runtime.mjs +277 -277
- package/scripts/stress-dsh.js +255 -255
- package/scripts/sync-lib.js +47 -47
- package/scripts/sync-test-badge.mjs +67 -61
- package/src/api-standalone.js +506 -316
- package/src/api.js +1403 -1316
- package/src/bootstrap.js +211 -0
- package/src/commands.js +95 -95
- package/src/config.js +615 -510
- package/src/document.js +221 -0
- package/src/dream/clustering.js +118 -118
- package/src/dream/decisions.js +658 -658
- package/src/dream/narratives.js +44 -0
- package/src/dream/sleep.js +702 -700
- package/src/dream.js +147 -16
- package/src/embedding.js +177 -177
- package/src/entities/extractor.js +249 -249
- package/src/guide.js +44 -0
- package/src/heat.js +144 -136
- package/src/hot-memory.js +46 -46
- package/src/index.js +515 -515
- package/src/inject.js +375 -295
- package/src/lang.js +208 -179
- package/src/local-embedder.js +320 -320
- package/src/mirror.js +198 -198
- package/src/organize.js +450 -0
- package/src/quality-filter.js +126 -126
- package/src/recall-stats.js +125 -0
- package/src/reranker.js +269 -269
- package/src/runtime/adopt.js +176 -176
- package/src/runtime/closure.js +172 -172
- package/src/runtime/download.js +247 -247
- package/src/runtime/layout.js +265 -235
- package/src/runtime/loader.js +252 -249
- package/src/runtime/model-fetch.js +361 -361
- package/src/runtime/provision.js +237 -237
- package/src/runtime/tarball.js +130 -130
- package/src/runtime/verify.js +204 -191
- package/src/scope.js +118 -118
- package/src/search/adaptive.js +60 -22
- package/src/search/bm25.js +96 -96
- package/src/service.js +2324 -2087
- package/src/settings.js +459 -420
- package/src/store.js +2549 -2367
- package/src/summarize.js +820 -449
- package/src/tools.js +702 -574
- package/src/vector-index.js +110 -110
- package/src/version-check.js +122 -122
- package/test/adaptive-inject-budget.test.js +85 -0
- package/test/api-routes-gaps.test.js +218 -218
- package/test/api.test.js +1640 -1482
- package/test/audit.test.js +448 -448
- package/test/benchmark.test.js +94 -94
- package/test/bootstrap.test.js +220 -0
- package/test/client.test.js +860 -736
- package/test/clustering.test.js +100 -100
- package/test/commands.test.js +106 -106
- package/test/config.test.js +66 -66
- package/test/conflict-freeze.test.js +300 -300
- package/test/document.test.js +523 -0
- package/test/dream-archive-guardrail.test.js +116 -116
- package/test/dream-candidate-hybrid.test.js +281 -281
- package/test/dream-coverage-degrade.test.js +86 -86
- package/test/dream.test.js +1308 -1254
- package/test/embedding-ready.test.js +196 -196
- package/test/entities.test.js +547 -547
- package/test/entity-recall.test.js +179 -0
- package/test/epistemic.test.js +298 -298
- package/test/fnew-0112.test.js +311 -311
- package/test/fnew-03.test.js +422 -422
- package/test/graph-api.test.js +175 -175
- package/test/heat.test.js +175 -148
- package/test/helpers/dream-mock.js +82 -82
- package/test/helpers/peer-worker.mjs +25 -25
- package/test/helpers/runtime-source.js +60 -60
- package/test/helpers/tar-builder.js +80 -80
- package/test/hot-memory.test.js +145 -145
- package/test/inject-content-cap.test.js +91 -0
- package/test/inject-first-round-bm25.test.js +89 -89
- package/test/inject-heat.test.js +61 -0
- package/test/inject-pools.test.js +170 -0
- package/test/inject-recall.test.js +105 -0
- package/test/inject-rotation.test.js +161 -161
- package/test/inject.test.js +283 -249
- package/test/lang.test.js +87 -87
- package/test/lib-smoke.test.js +96 -96
- package/test/llm-audit.test.js +462 -309
- package/test/llm-message-source.test.js +177 -177
- package/test/local-embedder.test.js +249 -249
- package/test/mcp-stdio.test.js +385 -0
- package/test/mirror-dirty.test.js +424 -424
- package/test/mirror-edit-digest.test.js +187 -187
- package/test/mirror-generation.test.js +499 -499
- package/test/mirror.test.js +249 -249
- package/test/narrative-bars.test.js +162 -0
- package/test/organize.test.js +418 -0
- package/test/peer-blockers.test.js +193 -193
- package/test/policy-epoch.test.js +259 -259
- package/test/quality-filter.test.js +186 -186
- package/test/reasoning-effort.test.js +746 -746
- package/test/recall-evals.test.js +235 -235
- package/test/recall-layer.test.js +326 -326
- package/test/recall-stats.test.js +123 -0
- package/test/receipt-chain.test.js +451 -451
- package/test/reflection.test.js +226 -226
- package/test/reindex-backfill.test.js +62 -62
- package/test/reranker-single-logit.test.js +73 -73
- package/test/reranker.test.js +197 -197
- package/test/resident-status.test.js +83 -0
- package/test/runtime-adopt.test.js +206 -206
- package/test/runtime-cli.test.js +89 -89
- package/test/runtime-closure.test.js +193 -193
- package/test/runtime-download.test.js +302 -302
- package/test/runtime-layout.test.js +163 -163
- package/test/runtime-loader.test.js +255 -237
- package/test/runtime-manifest.test.js +159 -158
- package/test/runtime-model-fetch.test.js +348 -348
- package/test/runtime-provision.test.js +101 -101
- package/test/runtime-tarball.test.js +81 -81
- package/test/runtime-verify.test.js +279 -214
- package/test/scope-candidates.test.js +239 -239
- package/test/scope-explicit.test.js +452 -452
- package/test/scope-retrieval.test.js +197 -197
- package/test/scope-storage.test.js +255 -255
- package/test/scope-strict.test.js +231 -231
- package/test/search-fusion.test.js +90 -90
- package/test/semantic.test.js +124 -124
- package/test/service-search.test.js +174 -174
- package/test/service.test.js +405 -405
- package/test/settings.test.js +261 -261
- package/test/skip-invalid-restore.test.js +262 -262
- package/test/sleep-action-set.test.js +422 -422
- package/test/sleep-heat.test.js +126 -125
- package/test/sleep-scheduler-rearm.test.js +89 -89
- package/test/sleep.test.js +410 -373
- package/test/standalone-api.test.js +544 -359
- package/test/store-vector-cache.test.js +98 -98
- package/test/store.test.js +396 -383
- package/test/stress.test.js +209 -209
- package/test/summarize.test.js +1288 -575
- package/test/tools-dto-schema-matrix.test.js +325 -0
- package/test/tools-memory-get-schema.test.js +65 -65
- package/test/tools.test.js +374 -341
- package/test/updated-at-semantics.test.js +113 -113
- package/test/vector-index.test.js +221 -221
- package/test/version-check.test.js +152 -152
- package/test/webServer-optional.test.js +82 -82
package/test/llm-audit.test.js
CHANGED
|
@@ -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
|
-
// ---
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
function
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
const
|
|
294
|
-
|
|
295
|
-
const
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
assert.equal(
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
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
|
+
});
|