@modusensus/dsh-mneme 0.2.4 → 0.2.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.
Files changed (46) hide show
  1. package/README.md +10 -9
  2. package/lib/client.js +2 -2
  3. package/lib/config.js +5 -2
  4. package/lib/dream/decisions.js +174 -62
  5. package/lib/dream.js +30 -5
  6. package/lib/index.js +3 -1
  7. package/lib/mirror.js +7 -1
  8. package/lib/service.js +117 -3
  9. package/lib/store.js +40 -0
  10. package/lib/tools.js +47 -4
  11. package/package.json +3 -1
  12. package/scripts/benchmark-embed.js +201 -0
  13. package/scripts/benchmark-rerank.js +166 -0
  14. package/scripts/e2e-dsh.js +216 -0
  15. package/scripts/stress-dsh.js +255 -0
  16. package/scripts/sync-lib.js +47 -0
  17. package/src/config.js +5 -2
  18. package/src/dream/decisions.js +174 -62
  19. package/src/dream.js +30 -5
  20. package/src/index.js +3 -1
  21. package/src/mirror.js +7 -1
  22. package/src/service.js +117 -3
  23. package/src/store.js +40 -0
  24. package/src/tools.js +47 -4
  25. package/test/api.test.js +385 -0
  26. package/test/audit.test.js +290 -0
  27. package/test/client.test.js +44 -0
  28. package/test/clustering.test.js +100 -0
  29. package/test/commands.test.js +69 -0
  30. package/test/config.test.js +31 -0
  31. package/test/dream.test.js +526 -0
  32. package/test/helpers/dream-mock.js +82 -0
  33. package/test/inject.test.js +82 -0
  34. package/test/local-embedder.test.js +227 -0
  35. package/test/mirror.test.js +249 -0
  36. package/test/reflection.test.js +226 -0
  37. package/test/reranker.test.js +197 -0
  38. package/test/semantic.test.js +123 -0
  39. package/test/service-search.test.js +169 -0
  40. package/test/service.test.js +198 -0
  41. package/test/settings.test.js +101 -0
  42. package/test/store.test.js +293 -0
  43. package/test/stress.test.js +209 -0
  44. package/test/summarize.test.js +156 -0
  45. package/test/tools.test.js +265 -0
  46. package/test/vector-index.test.js +205 -0
@@ -0,0 +1,82 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createStore } from "../src/store.js";
4
+ import { createService } from "../src/service.js";
5
+ import { createInjector } from "../src/inject.js";
6
+ import { createSettings } from "../src/settings.js";
7
+
8
+ function setup(over = {}) {
9
+ const store = createStore(":memory:");
10
+ const service = createService({ store, mirror: null, config: {} });
11
+ const settings = createSettings(store.db);
12
+ const contexts = [];
13
+ const disposers = [];
14
+ const ctx = {
15
+ systemPrompt: {
16
+ context(def) {
17
+ contexts.push(def);
18
+ const dispose = () => disposers.push(def.name);
19
+ return dispose;
20
+ }
21
+ }
22
+ };
23
+ const config = { maxInjectedItems: 3, importanceThreshold: 3, ...over };
24
+ const injector = createInjector(ctx, service, settings, config);
25
+ return { store, service, contexts, injector, settings };
26
+ }
27
+
28
+ test("registers memory and user-settings contexts", () => {
29
+ const { contexts } = setup();
30
+ assert.equal(contexts.length, 2);
31
+ assert.equal(contexts[0].name, "memory");
32
+ assert.equal(contexts[1].name, "user-settings");
33
+ });
34
+
35
+ test("context text renders injected memories as markdown block", () => {
36
+ const { contexts, service } = setup();
37
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "用户用中文交流", importance: 5 });
38
+ service.saveWithDedupe({ type: "project", title: "记忆插件", content: "SQLite+Markdown", importance: 4 });
39
+ const text = contexts[0].text({});
40
+ assert.ok(text.includes("[记忆库]"), "has header");
41
+ assert.ok(text.includes("语言"), "includes preference");
42
+ assert.ok(text.includes("记忆插件"), "includes high-importance project");
43
+ });
44
+
45
+ test("returns empty text when nothing qualifies", () => {
46
+ const { contexts } = setup();
47
+ const text = contexts[0].text({});
48
+ assert.equal(text, "");
49
+ });
50
+
51
+ test("renders summary block first when summary candidate exists", () => {
52
+ const { contexts, service } = setup();
53
+ service.saveWithDedupe({ type: "summary", title: "记忆库总览", content: "这是总览摘要", importance: 5 });
54
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "中文", importance: 5 });
55
+ const text = contexts[0].text({});
56
+ const summaryIdx = text.indexOf("这是总览摘要");
57
+ const prefIdx = text.indexOf("语言");
58
+ assert.ok(summaryIdx !== -1, "summary present");
59
+ assert.ok(prefIdx !== -1, "preference present");
60
+ assert.ok(summaryIdx < prefIdx, "summary rendered first");
61
+ });
62
+
63
+ test("user-settings context renders profile and rules, empty when unset", () => {
64
+ const { contexts, settings } = setup();
65
+ const settingsCtx = contexts.find((c) => c.name === "user-settings");
66
+ assert.ok(settingsCtx, "user-settings context registered");
67
+ assert.equal(settingsCtx.text({}), "", "empty when no profile/rules");
68
+ settings.setProfile("我叫小明,是一名前端开发者");
69
+ settings.setRules(["回答时先给结论", "使用简体中文"]);
70
+ const text = settingsCtx.text({});
71
+ assert.ok(text.includes("用户画像"), "has profile header");
72
+ assert.ok(text.includes("前端开发者"), "includes profile");
73
+ assert.ok(text.includes("先给结论"), "includes rule");
74
+ assert.ok(text.includes("简体中文"), "includes second rule");
75
+ });
76
+
77
+ test("user-settings context precedes memory block (order 85 < 90)", () => {
78
+ const { contexts, settings } = setup();
79
+ settings.setProfile("画像");
80
+ const settingsCtx = contexts.find((c) => c.name === "user-settings");
81
+ assert.ok(settingsCtx.order < contexts.find((c) => c.name === "memory").order);
82
+ });
@@ -0,0 +1,227 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import {
4
+ LocalEmbedder,
5
+ OllamaEmbedder,
6
+ OpenAIEmbedder,
7
+ createEmbedderByProvider
8
+ } from "../src/local-embedder.js";
9
+
10
+ /** Build a transformers.js-like Tensor: [rows x dim] flat data + dims. */
11
+ function fakeTensor(rows) {
12
+ const flat = Float32Array.from(rows.flat());
13
+ return { data: flat, dims: rows.length ? [rows.length, rows[0].length] : [0] };
14
+ }
15
+
16
+ /** Fake extractor: deterministic [batch, dim], records option passthrough. */
17
+ function makeFakeExtractor(dim, calls = []) {
18
+ const fn = async (texts, opts) => {
19
+ calls.push({ count: texts.length, opts });
20
+ return fakeTensor(
21
+ texts.map((_, i) => Array.from({ length: dim }, (__, j) => (i + 1) * 0.1 + j * 0.01))
22
+ );
23
+ };
24
+ fn.dispose = () => {
25
+ fn.disposed = true;
26
+ };
27
+ return fn;
28
+ }
29
+
30
+ /** Stub globalThis.fetch, returning the original on restore. */
31
+ function stubFetch(handler) {
32
+ const real = globalThis.fetch;
33
+ globalThis.fetch = async (url, init) => handler(url, init);
34
+ return () => {
35
+ globalThis.fetch = real;
36
+ };
37
+ }
38
+
39
+ function okJson(status, body) {
40
+ return {
41
+ ok: status >= 200 && status < 300,
42
+ status,
43
+ json: async () => body
44
+ };
45
+ }
46
+
47
+ test("LocalEmbedder init loads via injected engineFactory with cache_dir", async () => {
48
+ let seen = null;
49
+ const loader = async (task, model, options) => {
50
+ seen = { task, model, options };
51
+ return makeFakeExtractor(512);
52
+ };
53
+ const e = new LocalEmbedder({ cacheDir: "/tmp/model-cache", engineFactory: loader });
54
+ await e.init();
55
+ assert.equal(seen.task, "feature-extraction");
56
+ assert.equal(seen.model, "Xenova/bge-small-zh-v1.5");
57
+ assert.equal(seen.options.cache_dir, "/tmp/model-cache");
58
+ assert.equal(seen.options.dtype, "q8");
59
+ assert.equal(seen.options.device, "cpu");
60
+ });
61
+
62
+ test("LocalEmbedder embed returns [n, dim] with mean pooling and chunking", async () => {
63
+ const calls = [];
64
+ const e = new LocalEmbedder({
65
+ model: "Xenova/bge-small-zh-v1.5",
66
+ batchSize: 2,
67
+ engineFactory: async () => makeFakeExtractor(512, calls)
68
+ });
69
+ await e.init();
70
+ const vecs = await e.embed(["你好", "hello world", "测试文本"]);
71
+ assert.equal(vecs.length, 3);
72
+ for (const v of vecs) {
73
+ assert.equal(v.length, 512);
74
+ assert.ok(v.every(Number.isFinite));
75
+ }
76
+ // 3 texts at batchSize 2 -> two extractor calls.
77
+ assert.deepEqual(calls.map((c) => c.count), [2, 1]);
78
+ assert.deepEqual(calls[0].opts, { pooling: "mean", normalize: true });
79
+ });
80
+
81
+ test("LocalEmbedder embedSingle returns a single vector", async () => {
82
+ const e = new LocalEmbedder({ engineFactory: async () => makeFakeExtractor(384) });
83
+ await e.init();
84
+ const v = await e.embedSingle("single");
85
+ assert.equal(v.length, 384);
86
+ });
87
+
88
+ test("LocalEmbedder dimension and modelHash are stable", () => {
89
+ const a = new LocalEmbedder({ model: "Xenova/bge-small-zh-v1.5" });
90
+ const b = new LocalEmbedder({ model: "Xenova/bge-small-zh-v1.5" });
91
+ assert.equal(a.dimension, 512);
92
+ assert.equal(a.modelHash, b.modelHash);
93
+ assert.match(a.modelHash, /^Xenova\/bge-small-zh-v1\.5#[0-9a-f]+$/);
94
+ // Different model -> different hash.
95
+ assert.notEqual(a.modelHash, new LocalEmbedder({ model: "other/model" }).modelHash);
96
+ });
97
+
98
+ test("LocalEmbedder throws before init and after dispose", async () => {
99
+ const e = new LocalEmbedder({ engineFactory: async () => makeFakeExtractor(512) });
100
+ await assert.rejects(() => e.embed(["x"]), /not initialized/);
101
+ await e.init();
102
+ const disposed = makeFakeExtractor(512);
103
+ e.dispose();
104
+ assert.ok(disposed.disposed || e.extractor === null);
105
+ await assert.rejects(() => e.embed(["x"]), /not initialized/);
106
+ });
107
+
108
+ test("OllamaEmbedder init probes server and infers dimension", async () => {
109
+ const restore = stubFetch(async (url, init) => {
110
+ assert.equal(url, "http://localhost:11434/api/embeddings");
111
+ assert.equal(init.method, "POST");
112
+ const body = JSON.parse(init.body);
113
+ assert.equal(body.model, "nomic-embed-text");
114
+ assert.equal(body.prompt, "ping");
115
+ return okJson(200, { embedding: Array.from({ length: 768 }, (_, i) => i / 768) });
116
+ });
117
+ try {
118
+ const e = new OllamaEmbedder({ baseUrl: "http://localhost:11434", model: "nomic-embed-text" });
119
+ await e.init();
120
+ assert.equal(e.dimension, 768);
121
+ } finally {
122
+ restore();
123
+ }
124
+ });
125
+
126
+ test("OllamaEmbedder embed loops single requests", async () => {
127
+ const prompts = [];
128
+ const restore = stubFetch(async (url, init) => {
129
+ const body = JSON.parse(init.body);
130
+ prompts.push(body.prompt);
131
+ return okJson(200, { embedding: [0.5, 0.25, 0.125] });
132
+ });
133
+ try {
134
+ const e = new OllamaEmbedder({});
135
+ await e.init();
136
+ const vecs = await e.embed(["one", "two"]);
137
+ assert.deepEqual(prompts, ["ping", "one", "two"]);
138
+ assert.equal(vecs.length, 2);
139
+ assert.deepEqual(vecs[0], [0.5, 0.25, 0.125]);
140
+ assert.equal(e.dimension, 3);
141
+ } finally {
142
+ restore();
143
+ }
144
+ });
145
+
146
+ test("OllamaEmbedder init throws when unreachable", async () => {
147
+ const restore = stubFetch(async () => {
148
+ throw new Error("ECONNREFUSED");
149
+ });
150
+ try {
151
+ const e = new OllamaEmbedder({});
152
+ await assert.rejects(() => e.init(), /ECONNREFUSED/);
153
+ } finally {
154
+ restore();
155
+ }
156
+ });
157
+
158
+ test("OllamaEmbedder embed throws on HTTP error", async () => {
159
+ const restore = stubFetch(async () => okJson(404, { error: "model not found" }));
160
+ try {
161
+ const e = new OllamaEmbedder({});
162
+ await assert.rejects(() => e.embedSingle("x"), /HTTP 404/);
163
+ } finally {
164
+ restore();
165
+ }
166
+ });
167
+
168
+ test("OllamaEmbedder modelHash is stable", () => {
169
+ const a = new OllamaEmbedder({ model: "nomic-embed-text" });
170
+ const b = new OllamaEmbedder({ model: "nomic-embed-text" });
171
+ assert.equal(a.modelHash, b.modelHash);
172
+ assert.notEqual(a.modelHash, new OllamaEmbedder({ model: "bge-m3" }).modelHash);
173
+ });
174
+
175
+ test("OpenAIEmbedder init requires config and calls /embeddings", async () => {
176
+ const e = new OpenAIEmbedder({ baseUrl: "http://localhost:8000/v1", apiKey: "k", model: "m" });
177
+ assert.equal(e._url, "http://localhost:8000/v1/embeddings");
178
+ await e.init();
179
+
180
+ const bad = new OpenAIEmbedder({ baseUrl: "", apiKey: "", model: "" });
181
+ await assert.rejects(() => bad.init(), /requires baseUrl, apiKey and model/);
182
+ });
183
+
184
+ test("OpenAIEmbedder embed batch posts array and parses data", async () => {
185
+ let captured = null;
186
+ const restore = stubFetch(async (url, init) => {
187
+ captured = { url, init };
188
+ return okJson(200, {
189
+ data: [
190
+ { embedding: [0.1, 0.2, 0.3] },
191
+ { embedding: [0.4, 0.5, 0.6] }
192
+ ]
193
+ });
194
+ });
195
+ try {
196
+ const e = new OpenAIEmbedder({ baseUrl: "https://x/v1", apiKey: "sk-abc", model: "text-embed" });
197
+ await e.init();
198
+ const vecs = await e.embed(["a", "b"]);
199
+ assert.equal(captured.url, "https://x/v1/embeddings");
200
+ assert.equal(captured.init.headers.Authorization, "Bearer sk-abc");
201
+ const body = JSON.parse(captured.init.body);
202
+ assert.equal(body.model, "text-embed");
203
+ assert.deepEqual(body.input, ["a", "b"]);
204
+ assert.equal(vecs.length, 2);
205
+ assert.equal(e.dimension, 3);
206
+ } finally {
207
+ restore();
208
+ }
209
+ });
210
+
211
+ test("OpenAIEmbedder throws on non-ok response", async () => {
212
+ const restore = stubFetch(async () => okJson(500, {}));
213
+ try {
214
+ const e = new OpenAIEmbedder({ baseUrl: "https://x/v1", apiKey: "k", model: "m" });
215
+ await assert.rejects(() => e.embed(["x"]), /HTTP 500/);
216
+ } finally {
217
+ restore();
218
+ }
219
+ });
220
+
221
+ test("createEmbedderByProvider returns the right class per provider", () => {
222
+ assert.ok(createEmbedderByProvider("local") instanceof LocalEmbedder);
223
+ assert.ok(createEmbedderByProvider("ollama") instanceof OllamaEmbedder);
224
+ assert.ok(createEmbedderByProvider("openai") instanceof OpenAIEmbedder);
225
+ assert.ok(createEmbedderByProvider("LOCAL") instanceof LocalEmbedder);
226
+ assert.throws(() => createEmbedderByProvider("watson"), /Unknown embedding provider/);
227
+ });
@@ -0,0 +1,249 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, readFileSync, writeFileSync, rmSync, existsSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createMirror } from "../src/mirror.js";
7
+ import { createStore } from "../src/store.js";
8
+ import { createService } from "../src/service.js";
9
+
10
+ const TYPE_FILE = { preference: "preferences.md", project: "projects.md", decision: "decisions.md", history: "history.md" };
11
+
12
+ function tempDir() {
13
+ return mkdtempSync(join(tmpdir(), "dsh-mneme-mirror-"));
14
+ }
15
+
16
+ function sampleMemory(type, over = {}) {
17
+ return {
18
+ id: "m1", type, title: "标题", content: "内容",
19
+ tags: ["a"], importance: 3, forgotten: false,
20
+ source: undefined, created_at: "2026-01-01T00:00:00.000Z",
21
+ updated_at: "2026-01-01T00:00:00.000Z", ...over
22
+ };
23
+ }
24
+
25
+ test("mirror writes one markdown file per type on sync", () => {
26
+ const dir = tempDir();
27
+ try {
28
+ const mirror = createMirror(dir);
29
+ mirror.sync([
30
+ sampleMemory("preference"),
31
+ sampleMemory("project")
32
+ ]);
33
+ assert.ok(mirror.filePath("preference").endsWith("preferences.md"));
34
+ for (const type of ["preference", "project"]) {
35
+ const text = readFileSync(join(dir, TYPE_FILE[type]), "utf8");
36
+ assert.ok(text.includes("m1"), `${type} file contains id`);
37
+ assert.ok(text.includes("标题"), `${type} file contains title`);
38
+ assert.ok(text.includes("内容"), `${type} file contains content`);
39
+ }
40
+ assert.ok(mirror.filePath("decision").includes("decisions"));
41
+ } finally {
42
+ rmSync(dir, { recursive: true, force: true });
43
+ }
44
+ });
45
+
46
+ test("mirror groups multiple memories newest-first with header", () => {
47
+ const dir = tempDir();
48
+ try {
49
+ const mirror = createMirror(dir);
50
+ mirror.sync([
51
+ sampleMemory("project", { id: "old", updated_at: "2026-01-01T00:00:00.000Z" }),
52
+ sampleMemory("project", { id: "new", updated_at: "2026-02-01T00:00:00.000Z" })
53
+ ]);
54
+ const text = readFileSync(join(dir, "projects.md"), "utf8");
55
+ const iNew = text.indexOf("new");
56
+ const iOld = text.indexOf("old");
57
+ assert.ok(iNew !== -1 && iOld !== -1 && iNew < iOld, "newest first");
58
+ } finally {
59
+ rmSync(dir, { recursive: true, force: true });
60
+ }
61
+ });
62
+
63
+ test("human edit wins on next sync (bidirectional, human-first)", () => {
64
+ const dir = tempDir();
65
+ try {
66
+ const mirror = createMirror(dir);
67
+ mirror.sync([sampleMemory("preference", { id: "m1", content: "机器内容" })]);
68
+ // human edits the mirror file
69
+ const file = join(dir, "preferences.md");
70
+ const edited = readFileSync(file, "utf8").replace("机器内容", "人类编辑内容");
71
+ writeFileSync(file, edited, "utf8");
72
+ const humanEdits = mirror.readHumanEdits();
73
+ assert.ok(Array.isArray(humanEdits));
74
+ const m1 = humanEdits.find((e) => e.id === "m1");
75
+ assert.ok(m1, "detects human edit for m1");
76
+ assert.equal(m1.content, "人类编辑内容");
77
+ } finally {
78
+ rmSync(dir, { recursive: true, force: true });
79
+ }
80
+ });
81
+
82
+ test("readHumanEdits content is not polluted by file header", () => {
83
+ const dir = tempDir();
84
+ try {
85
+ const mirror = createMirror(dir);
86
+ mirror.sync([sampleMemory("preference", { id: "m1", content: "机器内容" })]);
87
+ const m1 = mirror.readHumanEdits("preference").find((e) => e.id === "m1");
88
+ assert.ok(m1, "detects m1");
89
+ assert.equal(m1.content, "机器内容");
90
+ assert.ok(!m1.content.includes("#"), "no H1 header in content");
91
+ assert.ok(!m1.content.includes("dsh-mneme 镜像"), "no mirror banner in content");
92
+ assert.ok(!m1.content.includes("<!--"), "no html comment in content");
93
+ } finally {
94
+ rmSync(dir, { recursive: true, force: true });
95
+ }
96
+ });
97
+
98
+ test("body containing '---' survives round-trip (no silent truncation)", () => {
99
+ const dir = tempDir();
100
+ try {
101
+ const mirror = createMirror(dir);
102
+ const content = "第一段\n\n---\n\n第二段";
103
+ mirror.sync([sampleMemory("project", { id: "p1", content })]);
104
+ const p1 = mirror.readHumanEdits("project").find((e) => e.id === "p1");
105
+ assert.ok(p1, "detects p1");
106
+ assert.equal(p1.content, content);
107
+ } finally {
108
+ rmSync(dir, { recursive: true, force: true });
109
+ }
110
+ });
111
+
112
+ test("body lines resembling metadata are preserved", () => {
113
+ const dir = tempDir();
114
+ try {
115
+ const mirror = createMirror(dir);
116
+ const content = "- **ID**: 假条目\n- **重要性**: 5(正文里写的)";
117
+ mirror.sync([sampleMemory("preference", { id: "m1", content })]);
118
+ const m1 = mirror.readHumanEdits("preference").find((e) => e.id === "m1");
119
+ assert.ok(m1, "detects m1");
120
+ assert.equal(m1.content, content);
121
+ } finally {
122
+ rmSync(dir, { recursive: true, force: true });
123
+ }
124
+ });
125
+
126
+ test("body line in machine ID format does not split entry or create ghost entry", () => {
127
+ const dir = tempDir();
128
+ try {
129
+ const mirror = createMirror(dir);
130
+ const content = "- **ID**: `phantom`\n- **重要性**: 5(正文里写的)";
131
+ mirror.sync([sampleMemory("preference", { id: "m1", content })]);
132
+ const edits = mirror.readHumanEdits("preference");
133
+ const m1 = edits.find((e) => e.id === "m1");
134
+ assert.ok(m1, "detects m1");
135
+ assert.equal(m1.content, content);
136
+ assert.ok(!edits.some((e) => e.id === "phantom"), "no ghost entry for phantom");
137
+ } finally {
138
+ rmSync(dir, { recursive: true, force: true });
139
+ }
140
+ });
141
+
142
+ test("sync with empty array deletes stale mirror files", () => {
143
+ const dir = tempDir();
144
+ try {
145
+ const mirror = createMirror(dir);
146
+ mirror.sync([
147
+ sampleMemory("preference"),
148
+ sampleMemory("project"),
149
+ sampleMemory("decision"),
150
+ sampleMemory("history")
151
+ ]);
152
+ for (const type of Object.keys(TYPE_FILE)) {
153
+ assert.ok(existsSync(join(dir, TYPE_FILE[type])), `${type} file exists`);
154
+ }
155
+ mirror.sync([]);
156
+ for (const type of Object.keys(TYPE_FILE)) {
157
+ assert.ok(!existsSync(join(dir, TYPE_FILE[type])), `${type} file removed`);
158
+ }
159
+ } finally {
160
+ rmSync(dir, { recursive: true, force: true });
161
+ }
162
+ });
163
+
164
+ test("startup merge keeps human edits across multiple type files (read-all-then-merge)", () => {
165
+ const dir = tempDir();
166
+ try {
167
+ const store = createStore(join(dir, "memory.db"));
168
+ const mirror = createMirror(dir);
169
+ const service = createService({ store, mirror, config: {} });
170
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
171
+ service.saveWithDedupe({ type: "project", title: "项目", content: "机器内容" });
172
+ // human edits BOTH mirror files before the startup merge
173
+ for (const [file, to] of [["preferences.md", "人工偏好"], ["projects.md", "人工项目"]]) {
174
+ const p = join(dir, file);
175
+ writeFileSync(p, readFileSync(p, "utf8").replace("机器内容", to), "utf8");
176
+ }
177
+ // replicate index.js startup: read EVERY type's edits first, then merge
178
+ // (a per-type read-then-merge loop would let the first syncMirror
179
+ // overwrite the unread type's file and lose the edit)
180
+ const byType = new Map();
181
+ for (const type of Object.keys(TYPE_FILE)) byType.set(type, mirror.readHumanEdits(type));
182
+ for (const [type, edits] of byType) if (edits.length) service.mergeHumanEdits(type, edits);
183
+ const prefs = service.list({ type: "preference", includeForgotten: true });
184
+ const projects = service.list({ type: "project", includeForgotten: true });
185
+ assert.ok(prefs.some((m) => m.content.includes("人工偏好")), "preference edit survives");
186
+ assert.ok(projects.some((m) => m.content.includes("人工项目")), "project edit survives");
187
+ store.close();
188
+ } finally {
189
+ rmSync(dir, { recursive: true, force: true });
190
+ }
191
+ });
192
+
193
+ // --- item ④: runtime human edits are reconciled on sync (not only at startup)
194
+
195
+ test("runtime human edit survives the next sync (human wins, no silent overwrite)", () => {
196
+ const dir = tempDir();
197
+ try {
198
+ const store = createStore(join(dir, "memory.db"));
199
+ const mirror = createMirror(dir);
200
+ const service = createService({ store, mirror, config: {} });
201
+ service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
202
+ // human edits the mirror file AFTER the initial sync
203
+ const file = join(dir, "preferences.md");
204
+ writeFileSync(file, readFileSync(file, "utf8").replace("机器内容", "人类编辑内容"), "utf8");
205
+ // the next unrelated store write triggers syncMirror → must merge the edit back
206
+ service.saveWithDedupe({ type: "project", title: "无关", content: "x" });
207
+ const prefs = service.list({ type: "preference", includeArchived: true });
208
+ const m = prefs.find((p) => p.title === "语言");
209
+ assert.equal(m.content, "人类编辑内容", "human edit merged back into the store");
210
+ store.close();
211
+ } finally {
212
+ rmSync(dir, { recursive: true, force: true });
213
+ }
214
+ });
215
+
216
+ test("concurrent human edit + store update produces a three-way conflict marker, no side lost", () => {
217
+ const dir = tempDir();
218
+ try {
219
+ const store = createStore(join(dir, "memory.db"));
220
+ const mirror = createMirror(dir);
221
+ const service = createService({ store, mirror, config: {} });
222
+ const { memory: m } = service.saveWithDedupe({ type: "preference", title: "语言", content: "机器内容" });
223
+ // human edits the file…
224
+ const file = join(dir, "preferences.md");
225
+ writeFileSync(file, readFileSync(file, "utf8").replace("机器内容", "人类编辑内容"), "utf8");
226
+ // …while the store is concurrently updated → next sync sees both sides changed
227
+ service.update(m.id, { content: "并发机器版本" });
228
+ const updated = service.getById(m.id);
229
+ assert.ok(updated.content.includes("人类编辑内容"), "human edit is kept as the head");
230
+ assert.ok(updated.content.includes("并发机器版本"), "store's concurrent version is preserved");
231
+ assert.ok(updated.content.includes("并发冲突"), "conflict marker appended");
232
+ store.close();
233
+ } finally {
234
+ rmSync(dir, { recursive: true, force: true });
235
+ }
236
+ });
237
+
238
+ test("readHumanEdits records the machine-written updated_at as the version token", () => {
239
+ const dir = tempDir();
240
+ try {
241
+ const mirror = createMirror(dir);
242
+ mirror.sync([sampleMemory("preference", { id: "m1", content: "机器内容", updated_at: "2026-03-01T00:00:00.000Z" })]);
243
+ const m1 = mirror.readHumanEdits("preference").find((e) => e.id === "m1");
244
+ assert.ok(m1, "detects m1");
245
+ assert.equal(m1.updated_at, "2026-03-01T00:00:00.000Z", "updated_at captured for three-way merge");
246
+ } finally {
247
+ rmSync(dir, { recursive: true, force: true });
248
+ }
249
+ });