@modusensus/dsh-mneme 0.4.4 → 0.4.6
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/README.md +27 -0
- package/lib/api.js +40 -2
- package/lib/config.js +53 -0
- package/lib/dream/decisions.js +43 -2
- package/lib/dream.js +86 -6
- package/lib/embedding.js +59 -2
- package/lib/index.js +68 -1
- package/lib/inject.js +84 -4
- package/lib/quality-filter.js +123 -0
- package/lib/service.js +355 -14
- package/lib/store.js +366 -5
- package/lib/summarize.js +65 -7
- package/lib/vector-index.js +12 -2
- package/package.json +1 -1
- package/src/api.js +40 -2
- package/src/config.js +53 -0
- package/src/dream/decisions.js +43 -2
- package/src/dream.js +86 -6
- package/src/embedding.js +59 -2
- package/src/index.js +68 -1
- package/src/inject.js +84 -4
- package/src/quality-filter.js +123 -0
- package/src/service.js +355 -14
- package/src/store.js +366 -5
- package/src/summarize.js +65 -7
- package/src/vector-index.js +12 -2
- package/test/api.test.js +84 -0
- package/test/dream.test.js +52 -0
- package/test/epistemic.test.js +298 -0
- package/test/inject.test.js +21 -0
- package/test/llm-audit.test.js +279 -0
- package/test/mirror-edit-digest.test.js +3 -1
- package/test/quality-filter.test.js +118 -0
- package/test/recall-evals.test.js +235 -0
- package/test/service.test.js +133 -2
- package/test/vector-index.test.js +22 -6
package/test/api.test.js
CHANGED
|
@@ -5,6 +5,7 @@ import { createStore } from "../src/store.js";
|
|
|
5
5
|
import { createService } from "../src/service.js";
|
|
6
6
|
import { createApi } from "../src/api.js";
|
|
7
7
|
import { createSettings } from "../src/settings.js";
|
|
8
|
+
import { createVectorIndex } from "../src/vector-index.js";
|
|
8
9
|
|
|
9
10
|
class FakeRes extends EventEmitter {
|
|
10
11
|
constructor() { super(); this.statusCode = 200; this.body = ""; }
|
|
@@ -383,3 +384,86 @@ test("no apiToken configured keeps all endpoints open", async () => {
|
|
|
383
384
|
await vec.handler(req("/api/dsh-mneme/vector-config"), res);
|
|
384
385
|
assert.equal(res.statusCode, 200, "open when apiToken is unset");
|
|
385
386
|
});
|
|
387
|
+
|
|
388
|
+
// --- Bug8: llm-audit API (pagination + stats) --------------------------------
|
|
389
|
+
|
|
390
|
+
test("GET /api/dsh-mneme/semantic/llm-audit returns paginated rows", async () => {
|
|
391
|
+
const { routes, service } = setup();
|
|
392
|
+
for (let i = 0; i < 5; i++) {
|
|
393
|
+
service.saveLlmAudit({ trigger_source: "autoDream", operation_type: "dream_consolidate", model_id: "m1", input_tokens: 10, output_tokens: 5, status: "success", related_memory_ids: [] });
|
|
394
|
+
}
|
|
395
|
+
const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit");
|
|
396
|
+
const res = new FakeRes();
|
|
397
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit?page=2&pageSize=2"), res);
|
|
398
|
+
assert.equal(res.statusCode, 200);
|
|
399
|
+
const data = JSON.parse(res.body);
|
|
400
|
+
assert.equal(data.total, 5);
|
|
401
|
+
assert.equal(data.page, 2);
|
|
402
|
+
assert.equal(data.pageSize, 2);
|
|
403
|
+
assert.equal(data.items.length, 2, "second page of 2");
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
test("GET /api/dsh-mneme/semantic/llm-audit filters by source", async () => {
|
|
407
|
+
const { routes, service } = setup();
|
|
408
|
+
service.saveLlmAudit({ trigger_source: "autoDream", operation_type: "dream_consolidate", model_id: "m1", status: "success" });
|
|
409
|
+
service.saveLlmAudit({ trigger_source: "autoSummarize", operation_type: "summarize_compress", model_id: "m2", status: "success" });
|
|
410
|
+
const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit");
|
|
411
|
+
const res = new FakeRes();
|
|
412
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit?source=autoSummarize"), res);
|
|
413
|
+
const data = JSON.parse(res.body);
|
|
414
|
+
assert.equal(data.total, 1);
|
|
415
|
+
assert.equal(data.items[0].operation_type, "summarize_compress");
|
|
416
|
+
});
|
|
417
|
+
|
|
418
|
+
test("GET /api/dsh-mneme/semantic/llm-audit/stats aggregates tokens by source and status", async () => {
|
|
419
|
+
const { routes, service } = setup();
|
|
420
|
+
service.saveLlmAudit({
|
|
421
|
+
trigger_source: "autoDream", operation_type: "dream_consolidate", model_id: "m1",
|
|
422
|
+
input_tokens: 100, output_tokens: 50, total_tokens: 150, duration_ms: 12, status: "success", related_memory_ids: []
|
|
423
|
+
});
|
|
424
|
+
service.saveLlmAudit({
|
|
425
|
+
trigger_source: "autoSummarize", operation_type: "summarize_compress", model_id: "m2",
|
|
426
|
+
input_tokens: 20, output_tokens: 10, total_tokens: 30, duration_ms: 5, status: "error", error_message: "boom", related_memory_ids: []
|
|
427
|
+
});
|
|
428
|
+
const route = routes.find((r) => r.path === "/api/dsh-mneme/semantic/llm-audit/stats");
|
|
429
|
+
const res = new FakeRes();
|
|
430
|
+
await route.handler(req("/api/dsh-mneme/semantic/llm-audit/stats?days=7"), res);
|
|
431
|
+
assert.equal(res.statusCode, 200);
|
|
432
|
+
const data = JSON.parse(res.body);
|
|
433
|
+
assert.equal(data.total_calls, 2);
|
|
434
|
+
assert.equal(data.input_tokens, 120);
|
|
435
|
+
assert.equal(data.output_tokens, 60);
|
|
436
|
+
assert.equal(data.total_tokens, 180);
|
|
437
|
+
assert.equal(data.total_duration_ms, 17);
|
|
438
|
+
assert.ok(data.by_source.some((s) => s.source === "autoDream" && s.total_tokens === 150), "autoDream aggregate present");
|
|
439
|
+
assert.ok(data.by_status.some((s) => s.status === "error" && s.c === 1), "error status counted");
|
|
440
|
+
});
|
|
441
|
+
|
|
442
|
+
// --- issue #10: vector-reindex with an embed-only OpenAI-compatible embedder --
|
|
443
|
+
|
|
444
|
+
test("Bug10: vector-reindex with an embed-only OpenAI-compatible embedder returns the real count and records the model fingerprint", async () => {
|
|
445
|
+
const store = createStore(":memory:");
|
|
446
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
447
|
+
const settings = createSettings(store.db);
|
|
448
|
+
const vectorIndex = createVectorIndex({ store });
|
|
449
|
+
const embedder = {
|
|
450
|
+
embed: async (text) => [0.1, 0.2, 0.3], // OpenAI-compatible single-text embed
|
|
451
|
+
modelHash: "text-embedding-3#abc",
|
|
452
|
+
dimension: 3
|
|
453
|
+
};
|
|
454
|
+
// A pre-index row written before the embedder is attached (so it still has no vector).
|
|
455
|
+
service.saveWithDedupe({ type: "project", title: "待回填", content: "缺少向量的存量记忆" });
|
|
456
|
+
const routes = [];
|
|
457
|
+
const ctx = { webServer: { register(route) { routes.push(route); return () => {}; } } };
|
|
458
|
+
createApi(ctx, service, settings, { add() {}, remove() {}, list() { return []; } }, embedder, { vectorIndex }, "");
|
|
459
|
+
const route = routes.find((r) => r.path === "/api/dsh-mneme/vector-reindex");
|
|
460
|
+
const res = new FakeRes();
|
|
461
|
+
await route.handler(req("/api/dsh-mneme/vector-reindex"), res);
|
|
462
|
+
assert.equal(res.statusCode, 200);
|
|
463
|
+
const data = JSON.parse(res.body);
|
|
464
|
+
assert.equal(data.indexed, 1, "actual indexed count, not 0");
|
|
465
|
+
assert.equal(data.skipped, 0);
|
|
466
|
+
assert.equal(vectorIndex.modelHash(), "text-embedding-3#abc", "model_hash written to vector_meta");
|
|
467
|
+
assert.equal(vectorIndex.dimension(), 3, "dimension written to vector_meta");
|
|
468
|
+
assert.equal(vectorIndex.getEmbedding(service.all()[0].id).length, 3, "embedding persisted");
|
|
469
|
+
});
|
package/test/dream.test.js
CHANGED
|
@@ -847,3 +847,55 @@ test("consolidation prompt pins the decision schema (action field, single-string
|
|
|
847
847
|
assert.match(systemText, /决策 JSON 示例/, "prompt includes a canonical example block");
|
|
848
848
|
store.close();
|
|
849
849
|
});
|
|
850
|
+
|
|
851
|
+
// --- Bug8: llm_audit_logs trail ----------------------------------------------
|
|
852
|
+
|
|
853
|
+
test("Bug8: runDream records llm_audit_logs rows for consolidation and summary", async () => {
|
|
854
|
+
const { store, service } = dreamSetup();
|
|
855
|
+
service.saveWithDedupe({ type: "project", title: "旧1", content: "第一段内容" });
|
|
856
|
+
service.saveWithDedupe({ type: "project", title: "旧2", content: "第二段内容" });
|
|
857
|
+
const ctx = mockCtx({
|
|
858
|
+
onConsolidation: (listText) => JSON.stringify([{ action: "keep", ids: [listText.match(/id=([^\s|]+)/)[1]] }])
|
|
859
|
+
});
|
|
860
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
861
|
+
const result = await dream.runDream(ctx, service, { dreamProvider: "deepseek", dreamModel: "deepseek-chat" });
|
|
862
|
+
assert.equal(result.ok, true, "run succeeds");
|
|
863
|
+
const rows = store.listLlmAudits();
|
|
864
|
+
assert.equal(rows.length, 2, "consolidation + summary both audited");
|
|
865
|
+
assert.deepEqual(rows.map((r) => r.trigger_source), ["autoDream", "autoDream"]);
|
|
866
|
+
assert.deepEqual(rows.map((r) => r.operation_type).sort(), ["dream_consolidate", "dream_summarize"]);
|
|
867
|
+
const consolidate = rows.find((r) => r.operation_type === "dream_consolidate");
|
|
868
|
+
assert.equal(consolidate.related_memory_ids.length, 2, "consolidation audit links the snapshot ids");
|
|
869
|
+
const summarize = rows.find((r) => r.operation_type === "dream_summarize");
|
|
870
|
+
assert.deepEqual(summarize.related_memory_ids, [], "summary audit has no related ids");
|
|
871
|
+
for (const row of rows) {
|
|
872
|
+
assert.equal(row.status, "success");
|
|
873
|
+
assert.equal(row.model_id, "mock:stress-model");
|
|
874
|
+
assert.ok(Number.isInteger(row.duration_ms) && row.duration_ms >= 0, "duration recorded");
|
|
875
|
+
assert.equal(row.input_tokens, 0);
|
|
876
|
+
assert.equal(row.output_tokens, 0);
|
|
877
|
+
}
|
|
878
|
+
store.close();
|
|
879
|
+
});
|
|
880
|
+
|
|
881
|
+
test("Bug8: a failed LLM call is recorded with status=error and does not block the run", async () => {
|
|
882
|
+
const { store, service } = dreamSetup();
|
|
883
|
+
service.saveWithDedupe({ type: "project", title: "主题", content: "内容" });
|
|
884
|
+
const ctx = {
|
|
885
|
+
logger: { warn: () => {} },
|
|
886
|
+
llm: {
|
|
887
|
+
stream: async function* () {
|
|
888
|
+
yield { type: "finish", reason: { kind: "error" } };
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
};
|
|
892
|
+
const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
|
|
893
|
+
const result = await dream.runDream(ctx, service, { dreamProvider: "deepseek", dreamModel: "deepseek-chat" });
|
|
894
|
+
assert.equal(result.ok, false, "failed run reported");
|
|
895
|
+
const rows = store.listLlmAudits();
|
|
896
|
+
assert.equal(rows.length, 1, "one audit row for the failed consolidation call");
|
|
897
|
+
assert.equal(rows[0].operation_type, "dream_consolidate");
|
|
898
|
+
assert.equal(rows[0].status, "error", "LLM failure status=error");
|
|
899
|
+
assert.ok(rows[0].error_message, "error message recorded");
|
|
900
|
+
store.close();
|
|
901
|
+
});
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { createStore } from "../src/store.js";
|
|
8
|
+
import { createService } from "../src/service.js";
|
|
9
|
+
import { createVectorIndex } from "../src/vector-index.js";
|
|
10
|
+
import { createInjector } from "../src/inject.js";
|
|
11
|
+
import { createSettings } from "../src/settings.js";
|
|
12
|
+
import { applyDecisions } from "../src/dream.js";
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------- schema / legacy compat
|
|
15
|
+
|
|
16
|
+
test("default epistemic_status is subjective (legacy-compatible)", () => {
|
|
17
|
+
const store = createStore(":memory:");
|
|
18
|
+
const saved = store.save({ type: "preference", title: "语言", content: "用户用中文交流" });
|
|
19
|
+
assert.equal(saved.epistemic_status, "subjective", "no signal -> default subjective");
|
|
20
|
+
assert.equal(store.getById(saved.id).epistemic_status, "subjective");
|
|
21
|
+
store.close();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test("legacy DB without the column is migrated, old rows read back as subjective", () => {
|
|
25
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-epistemic-"));
|
|
26
|
+
const dbPath = join(dir, "memory.db");
|
|
27
|
+
try {
|
|
28
|
+
const old = new DatabaseSync(dbPath);
|
|
29
|
+
old.exec(`
|
|
30
|
+
CREATE TABLE memories (
|
|
31
|
+
id TEXT PRIMARY KEY, type TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL,
|
|
32
|
+
tags TEXT NOT NULL DEFAULT '[]', importance INTEGER NOT NULL DEFAULT 3, forgotten INTEGER NOT NULL DEFAULT 0,
|
|
33
|
+
source TEXT, embedding TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
|
34
|
+
);
|
|
35
|
+
INSERT INTO memories (id, type, title, content, tags, importance, forgotten, created_at, updated_at)
|
|
36
|
+
VALUES ('legacy', 'preference', '旧偏好', '用户以前说过', '[]', 3, 0, 't', 't');
|
|
37
|
+
`);
|
|
38
|
+
old.close();
|
|
39
|
+
|
|
40
|
+
const store = createStore(dbPath);
|
|
41
|
+
const cols = store.db.prepare("PRAGMA table_info(memories)").all().map((c) => c.name);
|
|
42
|
+
assert.ok(cols.includes("epistemic_status"), "column added by migration");
|
|
43
|
+
const legacy = store.getById("legacy");
|
|
44
|
+
assert.equal(legacy.title, "旧偏好", "legacy row preserved");
|
|
45
|
+
assert.equal(legacy.epistemic_status, "subjective", "legacy row defaults to subjective");
|
|
46
|
+
// New writes on the migrated DB still work with the column.
|
|
47
|
+
const saved = store.save({ type: "preference", title: "新", content: "实测结果可用" });
|
|
48
|
+
assert.equal(saved.epistemic_status, "observation");
|
|
49
|
+
store.close();
|
|
50
|
+
} finally {
|
|
51
|
+
rmSync(dir, { recursive: true, force: true });
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// ---------------------------------------------------------------- write inference
|
|
56
|
+
|
|
57
|
+
test("content-based inference: subjective markers -> subjective", () => {
|
|
58
|
+
const store = createStore(":memory:");
|
|
59
|
+
const a = store.save({ type: "preference", title: "天气", content: "我推测明天可能会下雨" });
|
|
60
|
+
const b = store.save({ type: "preference", title: "口味", content: "我觉得用户喜欢甜的" });
|
|
61
|
+
assert.equal(a.epistemic_status, "subjective");
|
|
62
|
+
assert.equal(b.epistemic_status, "subjective");
|
|
63
|
+
store.close();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("content-based inference: observation markers -> observation", () => {
|
|
67
|
+
const store = createStore(":memory:");
|
|
68
|
+
const a = store.save({ type: "project", title: "温度", content: "实测温度为35度,数据显示稳定" });
|
|
69
|
+
const b = store.save({ type: "project", title: "观察", content: "观察到用户总是先点保存" });
|
|
70
|
+
assert.equal(a.epistemic_status, "observation");
|
|
71
|
+
assert.equal(b.epistemic_status, "observation");
|
|
72
|
+
store.close();
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("content-based inference: inference markers -> inferred", () => {
|
|
76
|
+
const store = createStore(":memory:");
|
|
77
|
+
const a = store.save({ type: "decision", title: "喜好", content: "根据历史记录推断他喜欢猫" });
|
|
78
|
+
const b = store.save({ type: "decision", title: "趋势", content: "综上,结论是可推断的" });
|
|
79
|
+
assert.equal(a.epistemic_status, "inferred");
|
|
80
|
+
assert.equal(b.epistemic_status, "inferred");
|
|
81
|
+
store.close();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("AI-generated types (summary/pattern) are always inferred", () => {
|
|
85
|
+
const store = createStore(":memory:");
|
|
86
|
+
const s = store.save({ type: "summary", title: "总览", content: "实测数据汇总" });
|
|
87
|
+
const p = store.save({ type: "pattern", title: "模式", content: "用户反复这样操作" });
|
|
88
|
+
assert.equal(s.epistemic_status, "inferred");
|
|
89
|
+
assert.equal(p.epistemic_status, "inferred");
|
|
90
|
+
store.close();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("explicit epistemic_status wins over content inference", () => {
|
|
94
|
+
const store = createStore(":memory:");
|
|
95
|
+
const saved = store.save({ type: "preference", title: "x", content: "我觉得可能", epistemic_status: "observation" });
|
|
96
|
+
assert.equal(saved.epistemic_status, "observation", "explicit value respected");
|
|
97
|
+
store.close();
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("update re-infers when content changes, keeps status otherwise", () => {
|
|
101
|
+
const store = createStore(":memory:");
|
|
102
|
+
const saved = store.save({ type: "preference", title: "x", content: "我觉得可能" });
|
|
103
|
+
assert.equal(saved.epistemic_status, "subjective");
|
|
104
|
+
// content unchanged -> status kept
|
|
105
|
+
const untouched = store.update(saved.id, { title: "y" });
|
|
106
|
+
assert.equal(untouched.epistemic_status, "subjective");
|
|
107
|
+
// content changed to observation -> status re-inferred
|
|
108
|
+
const reInferred = store.update(saved.id, { content: "实测结果显示没问题" });
|
|
109
|
+
assert.equal(reInferred.epistemic_status, "observation");
|
|
110
|
+
store.close();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
test("update re-infers when TYPE changes to summary/pattern (regression)", () => {
|
|
114
|
+
const store = createStore(":memory:");
|
|
115
|
+
const saved = store.save({ type: "project", title: "x", content: "我觉得可能" });
|
|
116
|
+
assert.equal(saved.epistemic_status, "subjective");
|
|
117
|
+
// type -> summary: summary/pattern are always inferred, so status must flip
|
|
118
|
+
const asSummary = store.update(saved.id, { type: "summary" });
|
|
119
|
+
assert.equal(asSummary.epistemic_status, "inferred");
|
|
120
|
+
store.close();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------- retrieval ranking
|
|
124
|
+
|
|
125
|
+
const embedder = {
|
|
126
|
+
embedSingle: async () => [1, 0, 0],
|
|
127
|
+
embed: async () => [1, 0, 0],
|
|
128
|
+
schedule: () => {},
|
|
129
|
+
modelHash: "mock#1",
|
|
130
|
+
dimension: 3
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
test("retrieval ranking: switch off leaves scores and order untouched", async () => {
|
|
134
|
+
const store = createStore(":memory:");
|
|
135
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
136
|
+
const a = service.saveWithDedupe({ type: "preference", title: "猫A", content: "我觉得猫很可爱", importance: 5 });
|
|
137
|
+
const b = service.saveWithDedupe({ type: "preference", title: "猫B", content: "实测猫很可爱", importance: 3 });
|
|
138
|
+
assert.equal(a.memory.epistemic_status, "subjective");
|
|
139
|
+
assert.equal(b.memory.epistemic_status, "observation");
|
|
140
|
+
|
|
141
|
+
const rows = await service.searchMemories("猫", { mode: "keyword", topK: 10 });
|
|
142
|
+
assert.equal(rows[0].id, a.memory.id, "subjective first under default importance order");
|
|
143
|
+
assert.equal(rows[0].score, 1.0, "subjective keeps its raw score (1.0) when off");
|
|
144
|
+
assert.equal(rows[1].score, 0.8, "observation keeps its raw score (0.8) when off");
|
|
145
|
+
store.close();
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test("retrieval ranking: switch on re-weights and re-orders mixed recall", async () => {
|
|
149
|
+
const store = createStore(":memory:");
|
|
150
|
+
const service = createService({ store, mirror: null, config: { trustEpistemicWeighting: true } });
|
|
151
|
+
const vi = createVectorIndex({ store });
|
|
152
|
+
service.setEmbedder(embedder);
|
|
153
|
+
service.setVectorIndex(vi);
|
|
154
|
+
const subj = service.saveWithDedupe({ type: "preference", title: "量子计算", content: "我觉得量子计算很难", importance: 5 });
|
|
155
|
+
const obs = service.saveWithDedupe({ type: "preference", title: "量子计算实践", content: "实测量子计算简单", importance: 3 });
|
|
156
|
+
vi.saveEmbedding(subj.memory.id, [1, 0, 0]);
|
|
157
|
+
vi.saveEmbedding(obs.memory.id, [1, 0, 0]);
|
|
158
|
+
assert.equal(subj.memory.epistemic_status, "subjective");
|
|
159
|
+
assert.equal(obs.memory.epistemic_status, "observation");
|
|
160
|
+
|
|
161
|
+
// hybrid blend (default 0.6/0.4): subjective 1.0*0.6+1.0*0.4=1.0;
|
|
162
|
+
// observation 1.0*0.6+0.8*0.4=0.92. After weighting: 1.0*0.7=0.7 vs 0.92*1.0=0.92.
|
|
163
|
+
const rows = await service.searchMemories("量子计算", { mode: "hybrid", topK: 10 });
|
|
164
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
165
|
+
assert.equal(byId.get(subj.memory.id).score, 0.7, "subjective weighted to 0.7");
|
|
166
|
+
assert.equal(byId.get(obs.memory.id).score, 0.92, "observation weighted to 0.92");
|
|
167
|
+
assert.equal(rows[0].id, obs.memory.id, "observation outranks subjective when weighting is on");
|
|
168
|
+
store.close();
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
// ---------------------------------------------------------------- injection marking
|
|
172
|
+
|
|
173
|
+
function setupInjector(over = {}) {
|
|
174
|
+
const store = createStore(":memory:");
|
|
175
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
176
|
+
const settings = createSettings(store.db);
|
|
177
|
+
const contexts = [];
|
|
178
|
+
const ctx = {
|
|
179
|
+
systemPrompt: {
|
|
180
|
+
context(def) {
|
|
181
|
+
contexts.push(def);
|
|
182
|
+
return () => {};
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
const config = { maxInjectedItems: 3, importanceThreshold: 3, ...over };
|
|
187
|
+
createInjector(ctx, service, settings, config);
|
|
188
|
+
return { store, service, contexts };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
test("injection marks observation memories [verified] only when enabled", () => {
|
|
192
|
+
const { service, contexts } = setupInjector({ trustEpistemicWeighting: true });
|
|
193
|
+
service.saveWithDedupe({ type: "preference", title: "偏好实测", content: "实测用户喜欢用命令行", importance: 5 });
|
|
194
|
+
service.saveWithDedupe({ type: "preference", title: "偏好推测", content: "我觉得用户可能喜欢GUI", importance: 5 });
|
|
195
|
+
const text = contexts[0].text({});
|
|
196
|
+
assert.ok(text.includes("[verified] 偏好实测"), "observation memory is flagged");
|
|
197
|
+
assert.ok(!text.includes("[verified] 偏好推测"), "subjective memory is not flagged");
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("injection never adds [verified] when the switch is off", () => {
|
|
201
|
+
const { service, contexts } = setupInjector({});
|
|
202
|
+
service.saveWithDedupe({ type: "preference", title: "偏好实测", content: "实测用户喜欢用命令行", importance: 5 });
|
|
203
|
+
const text = contexts[0].text({});
|
|
204
|
+
assert.ok(text.includes("偏好实测"), "memory still injected");
|
|
205
|
+
assert.ok(!text.includes("[verified]"), "no verified marker when off");
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
// ---------------------------------------------------------------- decision priority
|
|
209
|
+
|
|
210
|
+
test("merge keepSource prefers observation when enabled", () => {
|
|
211
|
+
const store = createStore(":memory:");
|
|
212
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
213
|
+
const config = { trustEpistemicWeighting: true };
|
|
214
|
+
const a = service.saveWithDedupe({ type: "project", title: "插件甲", content: "我觉得应该用A方案", importance: 3 });
|
|
215
|
+
const b = service.saveWithDedupe({ type: "project", title: "插件乙", content: "实测结果显示B方案更好", importance: 4 });
|
|
216
|
+
assert.equal(a.memory.epistemic_status, "subjective");
|
|
217
|
+
assert.equal(b.memory.epistemic_status, "observation");
|
|
218
|
+
|
|
219
|
+
const { committed } = applyDecisions(
|
|
220
|
+
[{ action: "merge", ids: [a.memory.id, b.memory.id], title: "插件总览", content: "合并", keepSource: a.memory.id }],
|
|
221
|
+
service, null, null, config
|
|
222
|
+
);
|
|
223
|
+
assert.equal(committed[0].keepSource, b.memory.id, "keepSource switched to the observation memory");
|
|
224
|
+
assert.equal(store.getById(b.memory.id).archived, false, "observation keeper stays live");
|
|
225
|
+
assert.equal(store.getById(a.memory.id).archived, true, "subjective source archived");
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("merge keepSource keeps the LLM choice when disabled", () => {
|
|
229
|
+
const store = createStore(":memory:");
|
|
230
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
231
|
+
const a = service.saveWithDedupe({ type: "project", title: "插件甲", content: "我觉得应该用A方案", importance: 3 });
|
|
232
|
+
const b = service.saveWithDedupe({ type: "project", title: "插件乙", content: "实测结果显示B方案更好", importance: 4 });
|
|
233
|
+
const { committed } = applyDecisions(
|
|
234
|
+
[{ action: "merge", ids: [a.memory.id, b.memory.id], title: "插件总览", content: "合并", keepSource: a.memory.id }],
|
|
235
|
+
service
|
|
236
|
+
);
|
|
237
|
+
assert.equal(committed[0].keepSource, a.memory.id, "LLM keepSource respected when off");
|
|
238
|
+
assert.equal(store.getById(a.memory.id).archived, false);
|
|
239
|
+
assert.equal(store.getById(b.memory.id).archived, true);
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
test("merge never promotes an ARCHIVED observation to keeper when enabled (regression)", () => {
|
|
243
|
+
const store = createStore(":memory:");
|
|
244
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
245
|
+
const config = { trustEpistemicWeighting: true };
|
|
246
|
+
// a = live subjective (LLM's keepSource), b = live observation,
|
|
247
|
+
// c = ARCHIVED observation. Pre-fix pickBestKeeper would pick c (highest
|
|
248
|
+
// priority, no archived check) as keeper, hit the archived-keeper guard in
|
|
249
|
+
// applyMerge and silently drop the merge — the live b never merges.
|
|
250
|
+
const a = service.saveWithDedupe({ type: "project", title: "甲", content: "我觉得A方案", importance: 3 });
|
|
251
|
+
const b = service.saveWithDedupe({ type: "project", title: "乙", content: "实测B方案更好", importance: 4 });
|
|
252
|
+
const c = service.saveWithDedupe({ type: "project", title: "丙", content: "实测C方案最好", importance: 4 });
|
|
253
|
+
service.setArchived(c.memory.id, true);
|
|
254
|
+
|
|
255
|
+
const { committed } = applyDecisions(
|
|
256
|
+
[{ action: "merge", ids: [a.memory.id, b.memory.id, c.memory.id], title: "合并", content: "合并", keepSource: a.memory.id }],
|
|
257
|
+
service, null, null, config
|
|
258
|
+
);
|
|
259
|
+
// c (archived) must NOT be promoted; the live observation b becomes keeper,
|
|
260
|
+
// and the merge actually lands.
|
|
261
|
+
assert.equal(committed.length, 1, "merge actually committed (not silently skipped)");
|
|
262
|
+
assert.equal(committed[0].keepSource, b.memory.id, "live observation promoted over archived one");
|
|
263
|
+
assert.equal(store.getById(b.memory.id).archived, false, "observation keeper stays live");
|
|
264
|
+
assert.equal(store.getById(a.memory.id).archived, true, "subjective source archived");
|
|
265
|
+
assert.equal(store.getById(c.memory.id).archived, true, "archived c stays archived");
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
test("conflict resolution prefers the observation side as winner when enabled", () => {
|
|
269
|
+
const store = createStore(":memory:");
|
|
270
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
271
|
+
const config = { trustEpistemicWeighting: true };
|
|
272
|
+
const w = service.saveWithDedupe({ type: "decision", title: "截止1", content: "我觉得截止是8月20日", importance: 4 });
|
|
273
|
+
const l = service.saveWithDedupe({ type: "decision", title: "截止2", content: "实测截止是8月15日", importance: 4 });
|
|
274
|
+
assert.equal(w.memory.epistemic_status, "subjective");
|
|
275
|
+
assert.equal(l.memory.epistemic_status, "observation");
|
|
276
|
+
|
|
277
|
+
const { committed } = applyDecisions(
|
|
278
|
+
[{ action: "conflict", winner: w.memory.id, loser: l.memory.id, reason: "日期更新" }],
|
|
279
|
+
service, null, null, config
|
|
280
|
+
);
|
|
281
|
+
assert.equal(committed[0].winner, l.memory.id, "winner swapped to the observation memory");
|
|
282
|
+
assert.equal(store.getById(l.memory.id).archived, false, "observation winner stays live");
|
|
283
|
+
assert.equal(store.getById(w.memory.id).archived, true, "subjective loser archived");
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
test("conflict resolution keeps the LLM winner when disabled", () => {
|
|
287
|
+
const store = createStore(":memory:");
|
|
288
|
+
const service = createService({ store, mirror: null, config: {} });
|
|
289
|
+
const w = service.saveWithDedupe({ type: "decision", title: "截止1", content: "我觉得截止是8月20日", importance: 4 });
|
|
290
|
+
const l = service.saveWithDedupe({ type: "decision", title: "截止2", content: "实测截止是8月15日", importance: 4 });
|
|
291
|
+
const { committed } = applyDecisions(
|
|
292
|
+
[{ action: "conflict", winner: w.memory.id, loser: l.memory.id, reason: "日期更新" }],
|
|
293
|
+
service
|
|
294
|
+
);
|
|
295
|
+
assert.equal(committed[0].winner, w.memory.id, "LLM winner respected when off");
|
|
296
|
+
assert.equal(store.getById(w.memory.id).archived, false);
|
|
297
|
+
assert.equal(store.getById(l.memory.id).archived, true);
|
|
298
|
+
});
|
package/test/inject.test.js
CHANGED
|
@@ -80,3 +80,24 @@ test("user-settings context precedes memory block (order 85 < 90)", () => {
|
|
|
80
80
|
const settingsCtx = contexts.find((c) => c.name === "user-settings");
|
|
81
81
|
assert.ok(settingsCtx.order < contexts.find((c) => c.name === "memory").order);
|
|
82
82
|
});
|
|
83
|
+
|
|
84
|
+
test("Bug6: long content is truncated to ~300 chars with an ellipsis", () => {
|
|
85
|
+
const { contexts, service } = setup();
|
|
86
|
+
const longContent = "这是一段非常长的记忆正文".repeat(200); // ~2600 chars
|
|
87
|
+
service.saveWithDedupe({ type: "preference", title: "长记忆", content: longContent, importance: 5 });
|
|
88
|
+
const text = contexts[0].text({});
|
|
89
|
+
assert.ok(text.includes("长记忆"), "memory still rendered");
|
|
90
|
+
assert.ok(text.includes("…"), "ellipsis marks the truncation");
|
|
91
|
+
assert.ok(!text.includes(longContent.slice(300)), "full body not injected verbatim");
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
test("Bug6: injected block stays within the ~1500 char budget, later entries collapse", () => {
|
|
95
|
+
const { contexts, service } = setup({ maxInjectedItems: 8 });
|
|
96
|
+
for (let i = 0; i < 8; i++) {
|
|
97
|
+
service.saveWithDedupe({ type: "preference", title: `长标题记忆${i}`, content: "这是一段".repeat(100), importance: 5 });
|
|
98
|
+
}
|
|
99
|
+
const text = contexts[0].text({});
|
|
100
|
+
assert.ok(text.length <= 1600, `memory block bounded near budget, got ${text.length} chars`);
|
|
101
|
+
// The first entries render full bodies; every entry is present by title.
|
|
102
|
+
for (let i = 0; i < 8; i++) assert.ok(text.includes(`长标题记忆${i}`), `entry ${i} present`);
|
|
103
|
+
});
|