@modusensus/dsh-mneme 0.2.10 → 0.3.0
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 +23 -4
- package/lib/config.js +14 -0
- package/lib/dream/decisions.js +39 -7
- package/lib/dream.js +1 -1
- package/lib/entities/extractor.js +242 -0
- package/lib/index.js +40 -0
- package/lib/service.js +114 -4
- package/lib/store.js +292 -0
- package/package.json +1 -1
- package/src/config.js +14 -0
- package/src/dream/decisions.js +39 -7
- package/src/dream.js +1 -1
- package/src/entities/extractor.js +242 -0
- package/src/index.js +40 -0
- package/src/service.js +114 -4
- package/src/store.js +292 -0
- package/test/entities.test.js +522 -0
- package/test/fnew-0112.test.js +316 -0
|
@@ -0,0 +1,522 @@
|
|
|
1
|
+
// v0.3.0 entity gene(记忆基因)测试。
|
|
2
|
+
// 测试点由 Kimi K2.7 设计(maas_client → kimi-k2.7-code),
|
|
3
|
+
// 再映射到本插件的真实 API 名(store/service/extractor/applyDecisions)。
|
|
4
|
+
// 覆盖:Schema / 实体 CRUD / 属性时间轴(valid_until) / findMemoriesByAttr
|
|
5
|
+
// (含空 value 契约修复)/ 抽取器 / entity:/attr: 前缀搜索 / autoDream / fail-safe。
|
|
6
|
+
import test from "node:test";
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import { DatabaseSync } from "node:sqlite";
|
|
9
|
+
import { mkdtempSync, rmSync } from "node:fs";
|
|
10
|
+
import { tmpdir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { createStore } from "../src/store.js";
|
|
13
|
+
import { createService } from "../src/service.js";
|
|
14
|
+
import { extractEntities } from "../src/entities/extractor.js";
|
|
15
|
+
import { applyDecisions } from "../src/dream/decisions.js";
|
|
16
|
+
|
|
17
|
+
function openStore() {
|
|
18
|
+
return createStore(":memory:");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function makeService(config = {}) {
|
|
22
|
+
const store = createStore(":memory:");
|
|
23
|
+
const service = createService({ store, mirror: null, config });
|
|
24
|
+
return { store, service };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function seedAttr(store, service, { entityName, type = "person", key, value, title, content = "记忆内容" }) {
|
|
28
|
+
let entity = store.findEntityByName(entityName);
|
|
29
|
+
if (!entity) entity = store.createEntity({ name: entityName, type });
|
|
30
|
+
const mem = service.saveWithDedupe({ type: "preference", title, content, importance: 3 });
|
|
31
|
+
store.saveAttr({ entity_id: entity.id, attr_key: key, attr_value: value, memory_id: mem.memory.id });
|
|
32
|
+
return { entity, mem: mem.memory };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// mock LLM 输出:抽取器约定 callLLM(messages, options) => Promise<string>
|
|
36
|
+
const jsonLLM = (payload) => async () => JSON.stringify(payload);
|
|
37
|
+
|
|
38
|
+
// ============================================================ Schema
|
|
39
|
+
|
|
40
|
+
test("createStore creates the three entity tables alongside memories", () => {
|
|
41
|
+
const store = openStore();
|
|
42
|
+
for (const t of ["memories", "entities", "entity_attrs", "entity_relations"]) {
|
|
43
|
+
const row = store.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t);
|
|
44
|
+
assert.ok(row, `${t} table exists`);
|
|
45
|
+
}
|
|
46
|
+
store.close();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("entity tables carry the expected indexes", () => {
|
|
50
|
+
const store = openStore();
|
|
51
|
+
const names = new Set(store.db.prepare("SELECT name FROM sqlite_master WHERE type='index'").all().map((r) => r.name));
|
|
52
|
+
for (const i of [
|
|
53
|
+
"idx_entities_name", "idx_entities_type",
|
|
54
|
+
"idx_attrs_entity", "idx_attrs_key", "idx_attrs_valid", "idx_attrs_memory",
|
|
55
|
+
"idx_relations_from", "idx_relations_to", "idx_relations_type"
|
|
56
|
+
]) {
|
|
57
|
+
assert.ok(names.has(i), `index ${i} exists`);
|
|
58
|
+
}
|
|
59
|
+
store.close();
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("legacy database without entity tables auto-creates them (idempotent)", () => {
|
|
63
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-entity-"));
|
|
64
|
+
const path = join(dir, "legacy.db");
|
|
65
|
+
try {
|
|
66
|
+
const legacy = new DatabaseSync(path);
|
|
67
|
+
legacy.exec(`CREATE TABLE memories (
|
|
68
|
+
id TEXT PRIMARY KEY, type TEXT NOT NULL, title TEXT NOT NULL, content TEXT NOT NULL,
|
|
69
|
+
tags TEXT NOT NULL DEFAULT '[]', importance INTEGER NOT NULL DEFAULT 3,
|
|
70
|
+
forgotten INTEGER NOT NULL DEFAULT 0, source TEXT, created_at TEXT NOT NULL, updated_at TEXT NOT NULL
|
|
71
|
+
);`);
|
|
72
|
+
legacy.close();
|
|
73
|
+
// 打开即自动建实体三表
|
|
74
|
+
const store = createStore(path);
|
|
75
|
+
for (const t of ["entities", "entity_attrs", "entity_relations"]) {
|
|
76
|
+
assert.ok(store.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name=?").get(t), `${t} auto-created`);
|
|
77
|
+
}
|
|
78
|
+
store.close();
|
|
79
|
+
// 幂等:重复打开不会报错,且可正常写入实体
|
|
80
|
+
const store2 = createStore(path);
|
|
81
|
+
store2.createEntity({ name: "幂等实体", type: "concept" });
|
|
82
|
+
assert.ok(store2.findEntityByName("幂等实体"), "reopen is writable");
|
|
83
|
+
store2.close();
|
|
84
|
+
} finally {
|
|
85
|
+
rmSync(dir, { recursive: true, force: true });
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// ============================================================ 实体 CRUD
|
|
90
|
+
|
|
91
|
+
test("createEntity records first_seen/last_seen and mention_count=1", () => {
|
|
92
|
+
const store = openStore();
|
|
93
|
+
const ent = store.createEntity({ name: "React", type: "technology" });
|
|
94
|
+
assert.ok(ent.id, "has id");
|
|
95
|
+
assert.equal(ent.name, "React");
|
|
96
|
+
assert.equal(ent.type, "technology");
|
|
97
|
+
assert.equal(ent.mention_count, 1);
|
|
98
|
+
assert.ok(ent.first_seen, "has first_seen");
|
|
99
|
+
assert.equal(ent.last_seen, ent.first_seen);
|
|
100
|
+
assert.equal(store.findEntityByName("React").id, ent.id);
|
|
101
|
+
store.close();
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test("findEntityByName / findEntityById resolve; unknown returns undefined", () => {
|
|
105
|
+
const store = openStore();
|
|
106
|
+
const ent = store.createEntity({ name: "Node", type: "technology" });
|
|
107
|
+
assert.equal(store.findEntityByName("Node").id, ent.id);
|
|
108
|
+
assert.equal(store.findEntityById(ent.id).name, "Node");
|
|
109
|
+
assert.equal(store.findEntityByName("不存在"), undefined);
|
|
110
|
+
assert.equal(store.findEntityById("ghost"), undefined);
|
|
111
|
+
store.close();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
test("updateEntity bumps mention_count and refreshes last_seen", () => {
|
|
115
|
+
const store = openStore();
|
|
116
|
+
const ent = store.createEntity({ name: "Vite", type: "technology" });
|
|
117
|
+
const updated = store.updateEntity(ent.id, {});
|
|
118
|
+
assert.equal(updated.mention_count, 2, "empty patch = a fresh sighting");
|
|
119
|
+
assert.ok(updated.last_seen > ent.last_seen, "last_seen advances");
|
|
120
|
+
assert.equal(updated.name, "Vite", "name preserved");
|
|
121
|
+
assert.equal(updated.type, "technology");
|
|
122
|
+
store.close();
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
test("updateEntity applies partial patch and honors explicit mention_count", () => {
|
|
126
|
+
const store = openStore();
|
|
127
|
+
const ent = store.createEntity({ name: "Rust", type: "technology" });
|
|
128
|
+
const updated = store.updateEntity(ent.id, { type: "language", mention_count: 5 });
|
|
129
|
+
assert.equal(updated.type, "language");
|
|
130
|
+
assert.equal(updated.mention_count, 5, "explicit mention_count wins");
|
|
131
|
+
assert.equal(updated.name, "Rust", "untouched field preserved");
|
|
132
|
+
assert.equal(store.updateEntity("ghost", {}), undefined);
|
|
133
|
+
store.close();
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// ============================================================ 属性时间轴 (valid_until)
|
|
137
|
+
|
|
138
|
+
test("saveAttr persists key/value/confidence/source/memory_id with valid_until null", () => {
|
|
139
|
+
const store = openStore();
|
|
140
|
+
const mem = store.save({ type: "preference", title: "助手", content: "用 Kimi", importance: 3 });
|
|
141
|
+
const ent = store.createEntity({ name: "Kimi", type: "person" });
|
|
142
|
+
const attr = store.saveAttr({
|
|
143
|
+
entity_id: ent.id, attr_key: "role", attr_value: "测试助手",
|
|
144
|
+
memory_id: mem.id, confidence: 0.8, source: "llm_extract"
|
|
145
|
+
});
|
|
146
|
+
assert.ok(attr.id, "has id");
|
|
147
|
+
assert.equal(attr.attr_key, "role");
|
|
148
|
+
assert.equal(attr.attr_value, "测试助手");
|
|
149
|
+
assert.equal(attr.confidence, 0.8);
|
|
150
|
+
assert.equal(attr.source, "llm_extract");
|
|
151
|
+
assert.equal(attr.memory_id, mem.id);
|
|
152
|
+
assert.ok(attr.valid_from, "has valid_from");
|
|
153
|
+
assert.equal(attr.valid_until, undefined, "new row is live");
|
|
154
|
+
store.close();
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
test("saveAttr twice invalidates the old row; only the newest stays current", () => {
|
|
158
|
+
const store = openStore();
|
|
159
|
+
const ent = store.createEntity({ name: "X", type: "concept" });
|
|
160
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "k", attr_value: "v1" });
|
|
161
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "k", attr_value: "v2" });
|
|
162
|
+
const current = store.getCurrentAttrs(ent.id);
|
|
163
|
+
assert.equal(current.length, 1, "one current row per entity+key");
|
|
164
|
+
assert.equal(current[0].attr_value, "v2");
|
|
165
|
+
assert.equal(current[0].valid_until, undefined);
|
|
166
|
+
store.close();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
test("getCurrentAttrs only live rows; getAttrHistory all rows oldest-first", () => {
|
|
170
|
+
const store = openStore();
|
|
171
|
+
const ent = store.createEntity({ name: "Y", type: "concept" });
|
|
172
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "k", attr_value: "v1" });
|
|
173
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "k", attr_value: "v2" });
|
|
174
|
+
const history = store.getAttrHistory(ent.id);
|
|
175
|
+
assert.equal(history.length, 2, "history keeps the superseded row");
|
|
176
|
+
assert.equal(history[0].attr_value, "v1");
|
|
177
|
+
assert.ok(history[0].valid_until, "old row closed with valid_until");
|
|
178
|
+
assert.equal(history[1].attr_value, "v2");
|
|
179
|
+
assert.equal(history[1].valid_until, undefined);
|
|
180
|
+
assert.equal(store.getCurrentAttrs(ent.id).length, 1);
|
|
181
|
+
store.close();
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
test("getAttrsByMemory returns the attrs referencing a given memory", () => {
|
|
185
|
+
const store = openStore();
|
|
186
|
+
const ent = store.createEntity({ name: "Z", type: "concept" });
|
|
187
|
+
const m1 = store.save({ type: "decision", title: "决定一", content: "c" });
|
|
188
|
+
const m2 = store.save({ type: "decision", title: "决定二", content: "c" });
|
|
189
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "a", attr_value: "1", memory_id: m1.id });
|
|
190
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "a", attr_value: "2", memory_id: m2.id });
|
|
191
|
+
const for1 = store.getAttrsByMemory(m1.id);
|
|
192
|
+
assert.equal(for1.length, 1);
|
|
193
|
+
assert.equal(for1[0].attr_value, "1");
|
|
194
|
+
assert.equal(for1[0].memory_id, m1.id);
|
|
195
|
+
assert.equal(store.getAttrsByMemory(m2.id).length, 1);
|
|
196
|
+
assert.equal(store.getAttrsByMemory("ghost").length, 0);
|
|
197
|
+
store.close();
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
test("invalidateOldAttr closes live rows and returns the count", () => {
|
|
201
|
+
const store = openStore();
|
|
202
|
+
const ent = store.createEntity({ name: "W", type: "concept" });
|
|
203
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "k", attr_value: "v1" });
|
|
204
|
+
assert.equal(store.invalidateOldAttr(ent.id, "k", new Date().toISOString()), 1);
|
|
205
|
+
assert.equal(store.getCurrentAttrs(ent.id).length, 0, "no live rows left");
|
|
206
|
+
assert.equal(store.invalidateOldAttr(ent.id, "k", new Date().toISOString()), 0, "second pass is a no-op");
|
|
207
|
+
store.close();
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
// ============================================================ findMemoriesByAttr
|
|
211
|
+
|
|
212
|
+
test("findMemoriesByAttr exact key=value match, deduped across entities", () => {
|
|
213
|
+
const store = openStore();
|
|
214
|
+
const m = store.save({ type: "preference", title: "记忆", content: "c" });
|
|
215
|
+
const e1 = store.createEntity({ name: "实体A", type: "concept" });
|
|
216
|
+
store.saveAttr({ entity_id: e1.id, attr_key: "tag", attr_value: "tech", memory_id: m.id });
|
|
217
|
+
const e2 = store.createEntity({ name: "实体B", type: "concept" });
|
|
218
|
+
store.saveAttr({ entity_id: e2.id, attr_key: "tag", attr_value: "tech", memory_id: m.id });
|
|
219
|
+
const rows = store.findMemoriesByAttr("tag", "tech");
|
|
220
|
+
assert.equal(rows.length, 1, "same memory via two entities still returns once");
|
|
221
|
+
assert.equal(rows[0].id, m.id);
|
|
222
|
+
store.close();
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
test("findMemoriesByAttr empty value returns ALL current memories for the key", () => {
|
|
226
|
+
const store = openStore();
|
|
227
|
+
const m1 = store.save({ type: "preference", title: "甲", content: "c" });
|
|
228
|
+
const m2 = store.save({ type: "preference", title: "乙", content: "c" });
|
|
229
|
+
// 同一 entity+key 的第二次 saveAttr 会失效前一行,因此用两个实体各存一条当前值
|
|
230
|
+
const e1 = store.createEntity({ name: "设备甲", type: "concept" });
|
|
231
|
+
const e2 = store.createEntity({ name: "设备乙", type: "concept" });
|
|
232
|
+
store.saveAttr({ entity_id: e1.id, attr_key: "brand", attr_value: "apple", memory_id: m1.id });
|
|
233
|
+
store.saveAttr({ entity_id: e2.id, attr_key: "brand", attr_value: "huawei", memory_id: m2.id });
|
|
234
|
+
for (const empty of ["", undefined, null]) {
|
|
235
|
+
const rows = store.findMemoriesByAttr("brand", empty);
|
|
236
|
+
assert.equal(rows.length, 2, `empty=${String(empty)} returns all current`);
|
|
237
|
+
assert.deepEqual(new Set(rows.map((r) => r.id)), new Set([m1.id, m2.id]));
|
|
238
|
+
}
|
|
239
|
+
store.close();
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
test("findMemoriesByAttr only matches live rows; expired values are excluded", () => {
|
|
243
|
+
const store = openStore();
|
|
244
|
+
const m1 = store.save({ type: "preference", title: "旧记忆", content: "c" });
|
|
245
|
+
const m2 = store.save({ type: "preference", title: "新记忆", content: "c" });
|
|
246
|
+
const e = store.createEntity({ name: "E", type: "concept" });
|
|
247
|
+
store.saveAttr({ entity_id: e.id, attr_key: "state", attr_value: "old", memory_id: m1.id });
|
|
248
|
+
store.saveAttr({ entity_id: e.id, attr_key: "state", attr_value: "new", memory_id: m2.id });
|
|
249
|
+
assert.deepEqual(store.findMemoriesByAttr("state", "old").map((r) => r.id), [], "superseded value not matched");
|
|
250
|
+
assert.deepEqual(store.findMemoriesByAttr("state", "new").map((r) => r.id), [m2.id]);
|
|
251
|
+
assert.deepEqual(store.findMemoriesByAttr("state", "").map((r) => r.id), [m2.id], "empty value still filters to live rows");
|
|
252
|
+
store.close();
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
test("findMemoriesByAttr unknown key returns []", () => {
|
|
256
|
+
const store = openStore();
|
|
257
|
+
const m = store.save({ type: "preference", title: "m", content: "c" });
|
|
258
|
+
const e = store.createEntity({ name: "F", type: "concept" });
|
|
259
|
+
store.saveAttr({ entity_id: e.id, attr_key: "real", attr_value: "x", memory_id: m.id });
|
|
260
|
+
assert.deepEqual(store.findMemoriesByAttr("nope", "x"), []);
|
|
261
|
+
assert.deepEqual(store.findMemoriesByAttr("nope", ""), []);
|
|
262
|
+
store.close();
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
// ============================================================ 抽取器
|
|
266
|
+
|
|
267
|
+
test("extractor writes entities, attrs and relations from mock LLM output", async () => {
|
|
268
|
+
const store = openStore();
|
|
269
|
+
const memory = store.save({ type: "preference", title: "技术栈", content: "我用 React 和 Node", importance: 3 });
|
|
270
|
+
const callLLM = jsonLLM({
|
|
271
|
+
entities: [
|
|
272
|
+
{ name: "React", type: "technology", attrs: [{ key: "category", value: "前端框架", confidence: 0.95 }] },
|
|
273
|
+
{ name: "Node", type: "technology", attrs: [{ key: "category", value: "运行时", confidence: 0.9 }] }
|
|
274
|
+
],
|
|
275
|
+
relations: [{ from: "React", to: "Node", type: "depends_on" }]
|
|
276
|
+
});
|
|
277
|
+
const result = await extractEntities(memory, { store, config: {}, callLLM });
|
|
278
|
+
assert.equal(result.ok, true);
|
|
279
|
+
assert.equal(result.entities.length, 2);
|
|
280
|
+
assert.equal(result.attrs.length, 2);
|
|
281
|
+
assert.equal(result.relations.length, 1);
|
|
282
|
+
|
|
283
|
+
const react = store.findEntityByName("React");
|
|
284
|
+
assert.ok(react, "entity row created");
|
|
285
|
+
assert.equal(react.type, "technology");
|
|
286
|
+
assert.equal(react.mention_count, 1);
|
|
287
|
+
const current = store.getCurrentAttrs(react.id);
|
|
288
|
+
assert.equal(current.length, 1);
|
|
289
|
+
assert.equal(current[0].attr_value, "前端框架");
|
|
290
|
+
assert.equal(current[0].source, "llm_extract");
|
|
291
|
+
assert.equal(current[0].memory_id, memory.id);
|
|
292
|
+
const rels = store.getRelations(react.id);
|
|
293
|
+
assert.equal(rels.length, 1);
|
|
294
|
+
assert.equal(rels[0].relation_type, "depends_on");
|
|
295
|
+
assert.equal(rels[0].to_entity, store.findEntityByName("Node").id);
|
|
296
|
+
store.close();
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
test("resolveEntity dedups: re-extracting the same name bumps mention_count", async () => {
|
|
300
|
+
const store = openStore();
|
|
301
|
+
const memory = store.save({ type: "preference", title: "工具", content: "用 Vite", importance: 3 });
|
|
302
|
+
const callLLM = jsonLLM({ entities: [{ name: "Vite", type: "technology", attrs: [] }], relations: [] });
|
|
303
|
+
await extractEntities(memory, { store, config: {}, callLLM });
|
|
304
|
+
const first = store.findEntityByName("Vite");
|
|
305
|
+
assert.equal(first.mention_count, 1);
|
|
306
|
+
const second = await extractEntities(memory, { store, config: {}, callLLM });
|
|
307
|
+
assert.equal(second.ok, true);
|
|
308
|
+
assert.equal(second.entities[0].entity_id, first.id, "reuses the same entity id");
|
|
309
|
+
assert.equal(store.findEntityByName("Vite").mention_count, 2, "mention_count incremented, no duplicate row");
|
|
310
|
+
assert.equal(store.db.prepare("SELECT count(*) AS c FROM entities WHERE name='Vite'").get().c, 1);
|
|
311
|
+
store.close();
|
|
312
|
+
});
|
|
313
|
+
|
|
314
|
+
test("extractor fails safe on garbage JSON → {ok:false} without throwing", async () => {
|
|
315
|
+
const store = openStore();
|
|
316
|
+
const memory = store.save({ type: "preference", title: "坏输出", content: "x" });
|
|
317
|
+
const result = await extractEntities(memory, {
|
|
318
|
+
store,
|
|
319
|
+
config: {},
|
|
320
|
+
callLLM: async () => "这不是 JSON,完全是乱写。"
|
|
321
|
+
});
|
|
322
|
+
assert.equal(result.ok, false);
|
|
323
|
+
assert.ok(result.error, "carries an error reason");
|
|
324
|
+
assert.equal(store.db.prepare("SELECT count(*) AS c FROM entities").get().c, 0, "nothing half-written");
|
|
325
|
+
store.close();
|
|
326
|
+
});
|
|
327
|
+
|
|
328
|
+
test("entityExtractionEnabled gate: hook fires only when enabled", () => {
|
|
329
|
+
// enabled → fires
|
|
330
|
+
const { store, service } = makeService({ entityExtractionEnabled: true });
|
|
331
|
+
let calls = 0;
|
|
332
|
+
service.setEntityExtractor(() => { calls++; return Promise.resolve({ ok: true }); });
|
|
333
|
+
service.saveWithDedupe({ type: "preference", title: "触发", content: "x" });
|
|
334
|
+
assert.equal(calls, 1, "hook invoked after a created write when enabled");
|
|
335
|
+
store.close();
|
|
336
|
+
|
|
337
|
+
// disabled → never fires even with a hook installed
|
|
338
|
+
const { store: s2, service: sv2 } = makeService({ entityExtractionEnabled: false });
|
|
339
|
+
let calls2 = 0;
|
|
340
|
+
sv2.setEntityExtractor(() => { calls2++; return Promise.resolve({ ok: true }); });
|
|
341
|
+
sv2.saveWithDedupe({ type: "preference", title: "不触发", content: "x" });
|
|
342
|
+
assert.equal(calls2, 0, "hook skipped when entityExtractionEnabled=false");
|
|
343
|
+
s2.close();
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
// ============================================================ entity:/attr: 前缀搜索
|
|
347
|
+
|
|
348
|
+
test("searchMemories entity: prefix → attr exact (1.0) sorts before keyword (0.7)", async () => {
|
|
349
|
+
const { store, service } = makeService({ entitySearchEnabled: true });
|
|
350
|
+
const { mem } = seedAttr(store, service, { entityName: "阿尔托", key: "国籍", value: "芬兰", title: "建筑师" });
|
|
351
|
+
const kw = service.saveWithDedupe({ type: "history", title: "阿尔托大学", content: "位于赫尔辛基" });
|
|
352
|
+
const rows = await service.searchMemories("entity:阿尔托", { topK: 10 });
|
|
353
|
+
const byId = new Map(rows.map((r) => [r.id, r]));
|
|
354
|
+
assert.equal(byId.get(mem.id)._score, 1.0, "attr-linked memory is the exact hit");
|
|
355
|
+
assert.equal(byId.get(mem.id)._source, "entity_attr");
|
|
356
|
+
assert.equal(byId.get(kw.memory.id)._score, 0.7, "keyword mention is the fill");
|
|
357
|
+
assert.equal(rows[0].id, mem.id, "attr exact leads the result order");
|
|
358
|
+
store.close();
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
test("searchMemories attr:key=value routes to exact attr match", async () => {
|
|
362
|
+
const { store, service } = makeService({ entitySearchEnabled: true });
|
|
363
|
+
const { mem } = seedAttr(store, service, { entityName: "柯布", key: "国籍", value: "法国", title: "马赛公寓" });
|
|
364
|
+
const other = service.saveWithDedupe({ type: "preference", title: "无关", content: "别的" });
|
|
365
|
+
const rows = await service.searchMemories("attr:国籍=法国", { topK: 10 });
|
|
366
|
+
assert.deepEqual(rows.map((r) => r.id), [mem.id]);
|
|
367
|
+
assert.ok(!rows.some((r) => r.id === other.memory.id));
|
|
368
|
+
store.close();
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
test("searchMemories attr:key without =value returns all current for the key", async () => {
|
|
372
|
+
const { store, service } = makeService({ entitySearchEnabled: true });
|
|
373
|
+
seedAttr(store, service, { entityName: "设备一", type: "concept", key: "brand", value: "apple", title: "笔记本" });
|
|
374
|
+
seedAttr(store, service, { entityName: "设备二", type: "concept", key: "brand", value: "huawei", title: "手机" });
|
|
375
|
+
const rows = await service.searchMemories("attr:brand", { topK: 10 });
|
|
376
|
+
assert.equal(rows.length, 2, "attr:key with no value covers every live value");
|
|
377
|
+
assert.deepEqual(new Set(rows.map((r) => r.title)), new Set(["笔记本", "手机"]));
|
|
378
|
+
// topK trims
|
|
379
|
+
const capped = await service.searchMemories("attr:brand", { topK: 1 });
|
|
380
|
+
assert.equal(capped.length, 1);
|
|
381
|
+
store.close();
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
test("searchMemories entitySearchEnabled=false does not route entity:/attr: prefixes", async () => {
|
|
385
|
+
const { store, service } = makeService({ entitySearchEnabled: false });
|
|
386
|
+
seedAttr(store, service, { entityName: "阿尔托", key: "国籍", value: "芬兰", title: "建筑师" });
|
|
387
|
+
// 前缀被当作普通关键词搜索:"entity:阿尔托" 字面串无命中 → 空
|
|
388
|
+
const rows = await service.searchMemories("entity:阿尔托", { topK: 10 });
|
|
389
|
+
assert.equal(rows.length, 0, "entity: prefix falls through to plain keyword");
|
|
390
|
+
const attrRows = await service.searchMemories("attr:国籍", { topK: 10 });
|
|
391
|
+
assert.equal(attrRows.length, 0, "attr: prefix falls through to plain keyword");
|
|
392
|
+
store.close();
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// ============================================================ autoDream(实体基因联动)
|
|
396
|
+
|
|
397
|
+
test("applyUpdate writes supersedes self-relations for the updated memory's attrs", () => {
|
|
398
|
+
const { store, service } = makeService({});
|
|
399
|
+
const mem = service.saveWithDedupe({ type: "decision", title: "旧方案", content: "用方案A", importance: 4 });
|
|
400
|
+
const ent = store.createEntity({ name: "项目X", type: "project" });
|
|
401
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "approach", attr_value: "A", memory_id: mem.memory.id });
|
|
402
|
+
|
|
403
|
+
const { applied, conflicts, failures } = applyDecisions(
|
|
404
|
+
[{ action: "update", ids: [mem.memory.id], content: "改用方案B" }],
|
|
405
|
+
service, null, null, { entityExtractionEnabled: true }
|
|
406
|
+
);
|
|
407
|
+
assert.equal(applied, 1);
|
|
408
|
+
assert.equal(conflicts.length, 0);
|
|
409
|
+
assert.equal(failures.length, 0);
|
|
410
|
+
const supersedes = store.getRelations(ent.id).filter((r) => r.relation_type === "supersedes");
|
|
411
|
+
assert.equal(supersedes.length, 1, "one supersedes relation per attr");
|
|
412
|
+
assert.equal(supersedes[0].from_entity, ent.id, "self-referencing from");
|
|
413
|
+
assert.equal(supersedes[0].to_entity, ent.id, "self-referencing to");
|
|
414
|
+
assert.equal(supersedes[0].memory_id, mem.memory.id);
|
|
415
|
+
assert.equal(supersedes[0].metadata.attr_key, "approach");
|
|
416
|
+
assert.equal(supersedes[0].metadata.old_value, "A");
|
|
417
|
+
store.close();
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
test("applyMerge migrates loser attrs to the keeper memory", () => {
|
|
421
|
+
const { store, service } = makeService({});
|
|
422
|
+
const loser = service.saveWithDedupe({ type: "project", title: "旧项目", content: "旧内容" });
|
|
423
|
+
const keeper = service.saveWithDedupe({ type: "project", title: "新项目", content: "新内容" });
|
|
424
|
+
const ent = store.createEntity({ name: "项目X", type: "project" });
|
|
425
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "status", attr_value: "active", memory_id: loser.memory.id });
|
|
426
|
+
|
|
427
|
+
const { applied } = applyDecisions(
|
|
428
|
+
[{ action: "merge", ids: [loser.memory.id, keeper.memory.id], keepSource: keeper.memory.id, title: "合并项目", content: "合并内容" }],
|
|
429
|
+
service, null, null, { entityExtractionEnabled: true }
|
|
430
|
+
);
|
|
431
|
+
assert.equal(applied, 1);
|
|
432
|
+
const keeperAttrs = store.getAttrsByMemory(keeper.memory.id);
|
|
433
|
+
assert.equal(keeperAttrs.length, 1, "loser attr re-pointed to keeper");
|
|
434
|
+
assert.equal(keeperAttrs[0].attr_value, "active");
|
|
435
|
+
assert.equal(store.getAttrsByMemory(loser.memory.id).length, 0, "no attrs left on the loser");
|
|
436
|
+
store.close();
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
test("applyMerge invalidates the loser attr when the keeper already holds the same entity+key live", () => {
|
|
440
|
+
const { store, service } = makeService({});
|
|
441
|
+
const loser = service.saveWithDedupe({ type: "decision", title: "D旧", content: "旧" });
|
|
442
|
+
const keeper = service.saveWithDedupe({ type: "decision", title: "D新", content: "新" });
|
|
443
|
+
const ent = store.createEntity({ name: "目标", type: "concept" });
|
|
444
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "state", attr_value: "done", memory_id: loser.memory.id });
|
|
445
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "state", attr_value: "wip", memory_id: keeper.memory.id });
|
|
446
|
+
|
|
447
|
+
const { applied } = applyDecisions(
|
|
448
|
+
[{ action: "merge", ids: [loser.memory.id, keeper.memory.id], keepSource: keeper.memory.id, title: "D合并", content: "合并" }],
|
|
449
|
+
service, null, null, { entityExtractionEnabled: true }
|
|
450
|
+
);
|
|
451
|
+
assert.equal(applied, 1);
|
|
452
|
+
const current = store.getCurrentAttrs(ent.id);
|
|
453
|
+
assert.equal(current.length, 1);
|
|
454
|
+
assert.equal(current[0].attr_value, "wip", "keeper value wins");
|
|
455
|
+
assert.equal(current[0].memory_id, keeper.memory.id);
|
|
456
|
+
const history = store.getAttrHistory(ent.id);
|
|
457
|
+
const doneRow = history.find((a) => a.attr_value === "done");
|
|
458
|
+
assert.ok(doneRow.valid_until, "loser row invalidated, not re-pointed");
|
|
459
|
+
assert.equal(doneRow.memory_id, loser.memory.id);
|
|
460
|
+
store.close();
|
|
461
|
+
});
|
|
462
|
+
|
|
463
|
+
test("applyUpdate/applyMerge skip entity side-effects when entityExtractionEnabled=false", () => {
|
|
464
|
+
const { store, service } = makeService({});
|
|
465
|
+
const mem = service.saveWithDedupe({ type: "decision", title: "方案", content: "旧内容", importance: 4 });
|
|
466
|
+
const ent = store.createEntity({ name: "项目X", type: "project" });
|
|
467
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "approach", attr_value: "A", memory_id: mem.memory.id });
|
|
468
|
+
|
|
469
|
+
const r = applyDecisions(
|
|
470
|
+
[{ action: "update", ids: [mem.memory.id], content: "新内容" }],
|
|
471
|
+
service, null, null, { entityExtractionEnabled: false }
|
|
472
|
+
);
|
|
473
|
+
assert.equal(r.applied, 1, "update itself still applies");
|
|
474
|
+
assert.equal(store.getRelations(ent.id).filter((x) => x.relation_type === "supersedes").length, 0, "no supersedes recorded");
|
|
475
|
+
|
|
476
|
+
const loser = service.saveWithDedupe({ type: "project", title: "L项目", content: "旧" });
|
|
477
|
+
const keeper = service.saveWithDedupe({ type: "project", title: "K项目", content: "新" });
|
|
478
|
+
store.saveAttr({ entity_id: ent.id, attr_key: "status", attr_value: "active", memory_id: loser.memory.id });
|
|
479
|
+
const m = applyDecisions(
|
|
480
|
+
[{ action: "merge", ids: [loser.memory.id, keeper.memory.id], keepSource: keeper.memory.id, title: "M合并", content: "合并" }],
|
|
481
|
+
service, null, null, { entityExtractionEnabled: false }
|
|
482
|
+
);
|
|
483
|
+
assert.equal(m.applied, 1, "merge itself still applies");
|
|
484
|
+
assert.equal(store.getAttrsByMemory(keeper.memory.id).length, 0, "attrs not migrated when disabled");
|
|
485
|
+
store.close();
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
// ============================================================ fail-safe
|
|
489
|
+
|
|
490
|
+
test("throwing / rejecting entityExtractor never breaks the memory write", () => {
|
|
491
|
+
const { store, service } = makeService({ entityExtractionEnabled: true });
|
|
492
|
+
service.setEntityExtractor(() => { throw new Error("sync boom"); });
|
|
493
|
+
const r1 = service.saveWithDedupe({ type: "preference", title: "安全一", content: "写入不受影响" });
|
|
494
|
+
assert.equal(r1.action, "created");
|
|
495
|
+
assert.ok(r1.memory.id);
|
|
496
|
+
service.setEntityExtractor(() => Promise.reject(new Error("async boom")));
|
|
497
|
+
const r2 = service.saveWithDedupe({ type: "preference", title: "安全二", content: "写入不受影响" });
|
|
498
|
+
assert.equal(r2.action, "created");
|
|
499
|
+
assert.ok(r2.memory.id);
|
|
500
|
+
store.close();
|
|
501
|
+
});
|
|
502
|
+
|
|
503
|
+
test("extractor fails safe on missing content → {ok:false}", async () => {
|
|
504
|
+
const store = openStore();
|
|
505
|
+
const result = await extractEntities({ id: "ghost", content: "" }, { store, config: {}, callLLM: async () => "{}" });
|
|
506
|
+
assert.equal(result.ok, false);
|
|
507
|
+
assert.ok(result.error);
|
|
508
|
+
store.close();
|
|
509
|
+
});
|
|
510
|
+
|
|
511
|
+
test("extractor fails safe when callLLM rejects → {ok:false}", async () => {
|
|
512
|
+
const store = openStore();
|
|
513
|
+
const memory = store.save({ type: "preference", title: "LLM 故障", content: "x" });
|
|
514
|
+
const result = await extractEntities(memory, {
|
|
515
|
+
store,
|
|
516
|
+
config: {},
|
|
517
|
+
callLLM: async () => { throw new Error("llm down"); }
|
|
518
|
+
});
|
|
519
|
+
assert.equal(result.ok, false);
|
|
520
|
+
assert.ok(result.error);
|
|
521
|
+
store.close();
|
|
522
|
+
});
|