@modusensus/dsh-mneme 0.6.0 → 0.6.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.
@@ -0,0 +1,134 @@
1
+ // v0.6.3 目录视图测试。
2
+ // 覆盖:store.getDirectory 按 tag 分组 / 组排序(tag 字典序)/
3
+ // 组内成员排序(importance DESC → updated_at DESC)/
4
+ // 无 tag 记忆进 untagged / disposed·archived·forgotten 过滤 /
5
+ // 多 tag 记忆出现在每个 tag 文件夹 / service.getDirectory 输出 wire DTO。
6
+ import test from "node:test";
7
+ import assert from "node:assert/strict";
8
+ import { createStore } from "../src/store.js";
9
+ import { createService } from "../src/service.js";
10
+
11
+ function setup() {
12
+ const store = createStore(":memory:");
13
+ const service = createService({ store, mirror: null, config: {} });
14
+ return { store, service };
15
+ }
16
+
17
+ function seed(store, title, { importance = 3, type = "preference", tags, session_id } = {}) {
18
+ const mem = store.save({ type, title, content: `content of ${title}`, importance, session_id });
19
+ if (tags && tags.length) store.setMemoryTags(mem.id, tags);
20
+ return mem;
21
+ }
22
+
23
+ // Bump a row's updated_at directly so ordering assertions are deterministic
24
+ // (nowIso() has ~ms resolution and a same-ms save loses the tiebreaker to the
25
+ // random id).
26
+ function setUpdatedAt(store, id, iso) {
27
+ store.db.prepare("UPDATE memories SET updated_at = ? WHERE id = ?").run(iso, id);
28
+ }
29
+
30
+ // ============================================================ grouping
31
+
32
+ test("getDirectory groups live memories by their live tag set", () => {
33
+ const { store } = setup();
34
+ const a = seed(store, "Linux 笔记", { tags: ["linux"] });
35
+ const b = seed(store, "考研计划", { tags: ["考研"] });
36
+ const dir = store.getDirectory();
37
+ assert.equal(dir.groups.length, 2);
38
+ const linux = dir.groups.find((g) => g.tag === "linux");
39
+ const exam = dir.groups.find((g) => g.tag === "考研");
40
+ assert.deepEqual(linux.memories.map((m) => m.id), [a.id]);
41
+ assert.deepEqual(exam.memories.map((m) => m.id), [b.id]);
42
+ assert.deepEqual(dir.untagged, []);
43
+ store.close();
44
+ });
45
+
46
+ test("getDirectory sorts groups by tag (locale-aware)", () => {
47
+ const { store } = setup();
48
+ seed(store, "B", { tags: ["zebra"] });
49
+ seed(store, "A", { tags: ["alpha"] });
50
+ seed(store, "C", { tags: ["æon"] });
51
+ const dir = store.getDirectory();
52
+ const tags = dir.groups.map((g) => g.tag);
53
+ const sorted = [...tags].sort((x, y) => x.localeCompare(y));
54
+ assert.deepEqual(tags, sorted, "groups must come back tag-sorted");
55
+ store.close();
56
+ });
57
+
58
+ test("getDirectory orders group members by importance DESC then updated_at DESC", () => {
59
+ const { store } = setup();
60
+ // same importance → updated_at decides
61
+ const older = seed(store, "older", { tags: ["linux"], importance: 2 });
62
+ const newer = seed(store, "newer", { tags: ["linux"], importance: 2 });
63
+ setUpdatedAt(store, older.id, "2026-01-01T00:00:00.000Z");
64
+ setUpdatedAt(store, newer.id, "2026-08-01T00:00:00.000Z");
65
+ // higher importance wins regardless of age
66
+ const important = seed(store, "important", { tags: ["linux"], importance: 5 });
67
+ setUpdatedAt(store, important.id, "2025-01-01T00:00:00.000Z");
68
+ const dir = store.getDirectory();
69
+ const linux = dir.groups.find((g) => g.tag === "linux");
70
+ assert.deepEqual(
71
+ linux.memories.map((m) => m.id),
72
+ [important.id, newer.id, older.id],
73
+ "importance DESC primary, updated_at DESC secondary"
74
+ );
75
+ store.close();
76
+ });
77
+
78
+ test("getDirectory collects untagged memories and orders them identically", () => {
79
+ const { store } = setup();
80
+ const a = seed(store, "untagged one", { importance: 1 });
81
+ const b = seed(store, "untagged two", { importance: 4 });
82
+ seed(store, "tagged", { tags: ["linux"], importance: 3 });
83
+ const dir = store.getDirectory();
84
+ assert.deepEqual(dir.untagged.map((m) => m.id), [b.id, a.id], "importance DESC inside untagged");
85
+ assert.equal(dir.groups.some((g) => g.tag === "linux"), true);
86
+ store.close();
87
+ });
88
+
89
+ test("getDirectory excludes forgotten, archived and session-disposed memories", () => {
90
+ const { store } = setup();
91
+ const forgotten = seed(store, "forgotten", { tags: ["linux"] });
92
+ const archived = seed(store, "archived", { tags: ["linux"] });
93
+ const disposed = seed(store, "disposed", { tags: ["linux"], type: "summary", session_id: "sess-disposed" });
94
+ const keep = seed(store, "keep", { tags: ["linux"] });
95
+ store.setForget(forgotten.id, true);
96
+ store.setArchived(archived.id, true);
97
+ store.setDisposedBySession(disposed.session_id, true);
98
+ const dir = store.getDirectory();
99
+ const linux = dir.groups.find((g) => g.tag === "linux");
100
+ assert.deepEqual(linux.memories.map((m) => m.id), [keep.id], "only the live row survives");
101
+ assert.deepEqual(dir.untagged, []);
102
+ store.close();
103
+ });
104
+
105
+ test("getDirectory lists a multi-tag memory under every tag folder once each", () => {
106
+ const { store } = setup();
107
+ const multi = seed(store, "multi", { tags: ["linux", "bash"] });
108
+ const single = seed(store, "single", { tags: ["linux"] });
109
+ const dir = store.getDirectory();
110
+ const linux = dir.groups.find((g) => g.tag === "linux");
111
+ const bash = dir.groups.find((g) => g.tag === "bash");
112
+ // `single` is written second → newer updated_at → ranks before `multi`.
113
+ assert.deepEqual(linux.memories.map((m) => m.id), [single.id, multi.id]);
114
+ assert.deepEqual(bash.memories.map((m) => m.id), [multi.id]);
115
+ assert.equal(dir.untagged.length, 0);
116
+ store.close();
117
+ });
118
+
119
+ // ============================================================ service
120
+
121
+ test("service.getDirectory returns the wire DTO shape with tags preserved", () => {
122
+ const { store, service } = setup();
123
+ const mem = seed(store, "笔记", { tags: ["linux"] });
124
+ seed(store, "裸条目", { importance: 2 });
125
+ const dir = service.getDirectory();
126
+ assert.deepEqual(Object.keys(dir).sort(), ["groups", "untagged"]);
127
+ const linux = dir.groups.find((g) => g.tag === "linux");
128
+ assert.equal(linux.memories[0].id, mem.id);
129
+ assert.equal(linux.memories[0].title, "笔记");
130
+ assert.equal(typeof linux.memories[0].updated_at, "string", "DTO carries updated_at for the entry row");
131
+ assert.equal(dir.untagged.length, 1);
132
+ assert.equal(dir.untagged[0].title, "裸条目");
133
+ store.close();
134
+ });
@@ -0,0 +1,125 @@
1
+ // v0.6.4 Tag 加权召回测试。
2
+ // 覆盖:extractQueryTags(#标签/已知 tag/去重/空)/ applyTagBoost(交集乘系数/
3
+ // 无交集不变/双叠加封顶/降序/标记)/ searchMemories 集成(开/关行为)。
4
+ import { test } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ import { extractQueryTags, applyTagBoost } from "../src/search/tag-boost.js";
7
+ import { createStore } from "../src/store.js";
8
+ import { createService } from "../src/service.js";
9
+
10
+ function makeService(config = {}) {
11
+ const store = createStore(":memory:");
12
+ const service = createService({ store, mirror: null, config });
13
+ return { store, service };
14
+ }
15
+
16
+ // ============================================================ extractQueryTags
17
+
18
+ test("extractQueryTags: extracts #hashtags including CJK", () => {
19
+ const tags = extractQueryTags("查看 #规划 和 #meeting_123");
20
+ assert.deepEqual(tags, ["规划", "meeting_123"]);
21
+ });
22
+
23
+ test("extractQueryTags: matches known tags without #", () => {
24
+ const tags = extractQueryTags("规划会议纪要", ["规划", "会议"]);
25
+ assert.deepEqual(tags, ["规划", "会议"]);
26
+ });
27
+
28
+ test("extractQueryTags: dedupes and merges explicit and known tags", () => {
29
+ const tags = extractQueryTags("#规划 规划进度", ["规划", "项目"]);
30
+ assert.deepEqual(tags, ["规划"]);
31
+ });
32
+
33
+ test("extractQueryTags: empty/invalid query returns empty array", () => {
34
+ assert.deepEqual(extractQueryTags(""), []);
35
+ assert.deepEqual(extractQueryTags(null), []);
36
+ });
37
+
38
+ // ============================================================ applyTagBoost
39
+
40
+ test("applyTagBoost: boosts candidates overlapping query tags", () => {
41
+ const out = applyTagBoost([{ id: "a", score: 0.8, tags: ["规划"] }], {
42
+ queryTags: ["规划"],
43
+ factor: 1.15,
44
+ });
45
+ assert.ok(Math.abs(out[0].score - 0.92) < 1e-9, "0.8 × 1.15 ≈ 0.92 (float-safe)");
46
+ assert.equal(out[0].tagBoost, true);
47
+ });
48
+
49
+ test("applyTagBoost: leaves non-overlapping candidates unchanged and stable", () => {
50
+ const out = applyTagBoost(
51
+ [
52
+ { id: "a", score: 0.5, tags: ["x"] },
53
+ { id: "b", score: 0.5, tags: ["y"] },
54
+ ],
55
+ { queryTags: ["z"] }
56
+ );
57
+ assert.deepEqual(out.map((m) => m.score), [0.5, 0.5]);
58
+ assert.deepEqual(out.map((m) => m.id), ["a", "b"]);
59
+ assert.ok(!out.some((m) => m.tagBoost));
60
+ });
61
+
62
+ test("applyTagBoost: applies both boosts and caps at 1", () => {
63
+ const out = applyTagBoost([{ id: "a", score: 0.9, tags: ["规划", "热门"] }], {
64
+ queryTags: ["规划"],
65
+ sessionTags: ["热门"],
66
+ factor: 1.15,
67
+ sessionFactor: 1.08,
68
+ });
69
+ assert.equal(out[0].score, 1);
70
+ assert.equal(out[0].tagBoost, true);
71
+ });
72
+
73
+ test("applyTagBoost: sorts results by boosted score descending", () => {
74
+ const out = applyTagBoost(
75
+ [
76
+ { id: "low", score: 0.9, tags: ["x"] },
77
+ { id: "high", score: 0.8, tags: ["plan"] },
78
+ ],
79
+ { queryTags: ["plan"], factor: 1.25 }
80
+ );
81
+ assert.deepEqual(out.map((m) => m.id), ["high", "low"]);
82
+ assert.equal(out[0].tagBoost, true);
83
+ });
84
+
85
+ // ============================================================ searchMemories 集成
86
+
87
+ test("searchMemories: tagBoostEnabled tags the matching memory", async () => {
88
+ const { store, service } = makeService({ tagBoostEnabled: true });
89
+ const a = service.saveWithDedupe({
90
+ type: "preference", title: "规划笔记", content: "项目规划方案", importance: 3,
91
+ }).memory;
92
+ store.setMemoryTags(a.id, ["规划"]);
93
+ const results = await service.searchMemories("项目 #规划", {
94
+ mode: "hybrid", limit: 10, useRerank: false, trustEpistemicWeighting: false,
95
+ });
96
+ const tagged = results.find((r) => r.id === a.id);
97
+ assert.ok(tagged, "tagged memory should be returned");
98
+ assert.equal(tagged.tagBoost, true, "boosted candidate carries tagBoost marker");
99
+ });
100
+
101
+ test("searchMemories: tagBoostEnabled=false adds no tagBoost markers", async () => {
102
+ const { store, service } = makeService({ tagBoostEnabled: false });
103
+ const a = service.saveWithDedupe({
104
+ type: "preference", title: "规划笔记", content: "项目规划方案", importance: 3,
105
+ }).memory;
106
+ store.setMemoryTags(a.id, ["规划"]);
107
+ const results = await service.searchMemories("项目 #规划", {
108
+ mode: "hybrid", limit: 10, useRerank: false, trustEpistemicWeighting: false,
109
+ });
110
+ assert.ok(!results.some((r) => r.tagBoost), "no tagBoost marker when disabled");
111
+ });
112
+
113
+ test("searchMemories: no tag in query → no boost even when enabled", async () => {
114
+ const { store, service } = makeService({ tagBoostEnabled: true });
115
+ const a = service.saveWithDedupe({
116
+ type: "preference", title: "规划笔记", content: "项目规划方案", importance: 3,
117
+ }).memory;
118
+ store.setMemoryTags(a.id, ["规划"]);
119
+ // query carries no #tag and no known-tag mention → boost is gated off
120
+ const results = await service.searchMemories("项目", {
121
+ mode: "hybrid", limit: 10, useRerank: false, trustEpistemicWeighting: false,
122
+ });
123
+ assert.ok(results.length > 0, "results returned");
124
+ assert.ok(!results.some((r) => r.tagBoost), "no tagBoost marker without a tag-bearing query");
125
+ });
@@ -0,0 +1,294 @@
1
+ // v0.6.2 Tag 系统测试。
2
+ // 覆盖:parser parseTags/sanitizeTags(正常/多标签去重/非法/超长/中文/连字符)/
3
+ // store.setMemoryTags 幂等(同 memory 只存一条、覆盖写、清空即删)/
4
+ // tag: 搜索(基础/多标签 AND/与关键词组合/不存在 tag)/
5
+ // autoDream tag(写 entity_attrs/fail-safe/限频/runDream 集成)/
6
+ // mirror 渲染(有 tag 出 #行、无 tag 不渲染 + service 打标后文件同步)。
7
+ import test from "node:test";
8
+ import assert from "node:assert/strict";
9
+ import { mkdtempSync, readFileSync, 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 { createMirror } from "../src/mirror.js";
15
+ import { parseTags, sanitizeTags, MAX_TAG_LENGTH } from "../src/parser/tag.js";
16
+ import { runAutoTag } from "../src/dream/tag-extractor.js";
17
+ import { createDreamScheduler } from "../src/dream.js";
18
+
19
+ function openStore() {
20
+ return createStore(":memory:");
21
+ }
22
+
23
+ function makeService(config = {}) {
24
+ const store = createStore(":memory:");
25
+ const service = createService({ store, mirror: null, config });
26
+ return { store, service };
27
+ }
28
+
29
+ function makeMirrorService(config = {}) {
30
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-tag-"));
31
+ const store = createStore(":memory:");
32
+ const mirror = createMirror(join(dir, "mirror"));
33
+ const service = createService({ store, mirror, config, logger: { warn: () => {} } });
34
+ return { store, service, dir, file: (t) => join(dir, "mirror", `${t}.md`) };
35
+ }
36
+
37
+ function seed(service, title, content, type = "preference") {
38
+ return service.saveWithDedupe({ type, title, content, importance: 3 }).memory;
39
+ }
40
+
41
+ // ============================================================ parser
42
+
43
+ test("parseTags: plain #tags are extracted in order", () => {
44
+ assert.deepEqual(parseTags("今天用 #linux 学了 #bash 脚本"), ["linux", "bash"]);
45
+ });
46
+
47
+ test("parseTags: multiple tags on one line dedupe (first occurrence wins)", () => {
48
+ assert.deepEqual(parseTags("#a #b #a #c"), ["a", "b", "c"]);
49
+ });
50
+
51
+ test("parseTags: illegal and non-tag markers are ignored", () => {
52
+ assert.deepEqual(parseTags("## 标题 和 #"), [], "markdown heading and a bare # yield nothing");
53
+ assert.deepEqual(parseTags("#foo#bar"), ["foo", "bar"], "back-to-back tags both parse");
54
+ assert.deepEqual(parseTags(""), []);
55
+ assert.deepEqual(parseTags(undefined), []);
56
+ assert.deepEqual(parseTags(null), []);
57
+ });
58
+
59
+ test("parseTags: over-long tags (> 20 chars) are dropped", () => {
60
+ const long = "a".repeat(MAX_TAG_LENGTH + 1);
61
+ const ok = "b".repeat(MAX_TAG_LENGTH);
62
+ assert.deepEqual(parseTags(`#${long} 和 #${ok}`), [ok]);
63
+ });
64
+
65
+ test("parseTags: CJK + edge-hyphen tags work", () => {
66
+ assert.deepEqual(parseTags("#考研 资料与 #深度学习-入门-"), ["考研", "深度学习-入门"]);
67
+ });
68
+
69
+ test("sanitizeTags: LLM-style arrays are validated/deduped and tolerate leading #", () => {
70
+ assert.deepEqual(sanitizeTags(["linux", " 考研 ", "#bash", "linux", "a/b", "x".repeat(30)]), [
71
+ "linux", "考研", "bash"
72
+ ]);
73
+ assert.deepEqual(sanitizeTags("not-an-array"), []);
74
+ });
75
+
76
+ // ============================================================ storage
77
+
78
+ test("setMemoryTags writes exactly one live tags row (idempotent overwrite)", () => {
79
+ const store = openStore();
80
+ const mem = store.save({ type: "preference", title: "Alpha", content: "c", tags: [] });
81
+ store.setMemoryTags(mem.id, ["linux", "考研"]);
82
+ assert.deepEqual(store.getMemoryTags(mem.id), ["linux", "考研"]);
83
+ const live = store.getAttrsByMemory(mem.id).filter((a) => a.attr_key === "tags" && !a.valid_until);
84
+ assert.equal(live.length, 1, "one live tags row per memory");
85
+ // overwrite keeps one live row, value replaced
86
+ store.setMemoryTags(mem.id, ["bash", "linux"]);
87
+ assert.deepEqual(store.getMemoryTags(mem.id), ["bash", "linux"]);
88
+ const live2 = store.getAttrsByMemory(mem.id).filter((a) => a.attr_key === "tags" && !a.valid_until);
89
+ assert.equal(live2.length, 1, "still exactly one live row after overwrite");
90
+ store.close();
91
+ });
92
+
93
+ test("setMemoryTags clears the row when the tag list is empty", () => {
94
+ const store = openStore();
95
+ const mem = store.save({ type: "preference", title: "Alpha", content: "c", tags: [] });
96
+ store.setMemoryTags(mem.id, ["linux"]);
97
+ assert.deepEqual(store.getMemoryTags(mem.id), ["linux"]);
98
+ store.setMemoryTags(mem.id, []);
99
+ assert.deepEqual(store.getMemoryTags(mem.id), []);
100
+ const live = store.getAttrsByMemory(mem.id).filter((a) => a.attr_key === "tags" && !a.valid_until);
101
+ assert.equal(live.length, 0, "no live tags row after clear");
102
+ store.close();
103
+ });
104
+
105
+ // ============================================================ tag: search
106
+
107
+ test("searchMemories: tag:xxx returns only memories carrying that tag", async () => {
108
+ const { store, service } = makeService();
109
+ const a = seed(service, "Linux 笔记", "内核与发行版");
110
+ const b = seed(service, "考研计划", "公共管理学 631");
111
+ store.setMemoryTags(a.id, ["linux"]);
112
+ store.setMemoryTags(b.id, ["考研"]);
113
+ const hits = await service.searchMemories("tag:linux");
114
+ assert.equal(hits.length, 1);
115
+ assert.equal(hits[0].id, a.id);
116
+ assert.equal(hits[0].source, "tag");
117
+ assert.equal((await service.searchMemories("tag:考研"))[0].id, b.id);
118
+ store.close();
119
+ });
120
+
121
+ test("searchMemories: multiple tag: tokens use AND (must carry every tag)", async () => {
122
+ const { store, service } = makeService();
123
+ const both = seed(service, "两者皆有", "正文");
124
+ const one = seed(service, "只有一个", "正文");
125
+ store.setMemoryTags(both.id, ["a", "b"]);
126
+ store.setMemoryTags(one.id, ["a"]);
127
+ const hits = await service.searchMemories("tag:a tag:b");
128
+ assert.equal(hits.length, 1);
129
+ assert.equal(hits[0].id, both.id);
130
+ store.close();
131
+ });
132
+
133
+ test("searchMemories: tag: combines with keyword text (ranked intersection)", async () => {
134
+ const { store, service } = makeService();
135
+ const hit = seed(service, "内核调度", "进程调度器与负载均衡");
136
+ const other = seed(service, "内核编译", "无关关键词");
137
+ store.setMemoryTags(hit.id, ["linux"]);
138
+ store.setMemoryTags(other.id, ["linux"]);
139
+ const hits = await service.searchMemories("tag:linux 调度");
140
+ assert.equal(hits.length, 1, "only the tagged memory whose content mentions 调度");
141
+ assert.equal(hits[0].id, hit.id);
142
+ assert.equal(hits[0].source, "tag");
143
+ store.close();
144
+ });
145
+
146
+ test("searchMemories: non-existent tag returns []", async () => {
147
+ const { store, service } = makeService();
148
+ const a = seed(service, "Alpha", "正文");
149
+ store.setMemoryTags(a.id, ["linux"]);
150
+ assert.deepEqual(await service.searchMemories("tag:不存在的标签"), []);
151
+ store.close();
152
+ });
153
+
154
+ // ============================================================ autoDream tag
155
+
156
+ /** Minimal LLM ctx whose stream yields a queue of texts, one per call. */
157
+ function makeCtx(calls) {
158
+ let n = 0;
159
+ return {
160
+ llm: {
161
+ stream: async function* () {
162
+ n++;
163
+ const text = calls[Math.min(n - 1, calls.length - 1)];
164
+ if (text !== undefined) yield { type: "text-delta", text };
165
+ yield { type: "finish", reason: { kind: "ok" } };
166
+ }
167
+ },
168
+ logger: { warn: () => {}, info: () => {} }
169
+ };
170
+ }
171
+
172
+ test("runAutoTag writes validated tags into entity_attrs", async () => {
173
+ const { store, service } = makeService();
174
+ const a = seed(service, "Linux", "内核");
175
+ const b = seed(service, "考研", "公共管理");
176
+ const text = JSON.stringify([
177
+ { id: a.id, tags: ["linux", "内核"] },
178
+ { id: b.id, tags: ["考研", "公共管理"] }
179
+ ]);
180
+ const ctx = makeCtx([text]);
181
+ const result = await runAutoTag({ ctx, service, config: { dreamProvider: "d", dreamModel: "m" } });
182
+ assert.equal(result.ok, true);
183
+ assert.equal(result.tagged, 2);
184
+ assert.deepEqual(store.getMemoryTags(a.id), ["linux", "内核"]);
185
+ assert.deepEqual(store.getMemoryTags(b.id), ["考研", "公共管理"]);
186
+ store.close();
187
+ });
188
+
189
+ test("runAutoTag fail-safe: garbage / aborted LLM output never throws and writes nothing", async () => {
190
+ const { store, service } = makeService();
191
+ const a = seed(service, "Alpha", "正文");
192
+ // garbage JSON → skipped, no writes
193
+ const r1 = await runAutoTag({
194
+ ctx: makeCtx(["not json at all"]),
195
+ service,
196
+ config: { dreamProvider: "d", dreamModel: "m" }
197
+ });
198
+ assert.equal(r1.ok, false);
199
+ assert.deepEqual(store.getMemoryTags(a.id), []);
200
+ // unknown id / illegal tags are dropped, valid ones still land
201
+ const text = JSON.stringify([
202
+ { id: "不存在", tags: ["x"] },
203
+ { id: a.id, tags: ["ok-tag", "a/b", "y".repeat(30)] }
204
+ ]);
205
+ const r2 = await runAutoTag({ ctx: makeCtx([text]), service, config: { dreamProvider: "d", dreamModel: "m" } });
206
+ assert.equal(r2.ok, true);
207
+ assert.deepEqual(store.getMemoryTags(a.id), ["ok-tag"], "illegal/over-long dropped, valid kept");
208
+ store.close();
209
+ });
210
+
211
+ test("runAutoTag respects autoTagMaxPerRun cap", async () => {
212
+ const { store, service } = makeService();
213
+ const mems = [];
214
+ for (let i = 0; i < 5; i++) mems.push(seed(service, `M${i}`, "正文"));
215
+ const text = JSON.stringify(mems.map((m, i) => ({ id: m.id, tags: [`t${i}`] })));
216
+ const ctx = makeCtx([text]);
217
+ const result = await runAutoTag({ ctx, service, config: { dreamProvider: "d", dreamModel: "m", autoTagMaxPerRun: 2 } });
218
+ assert.equal(result.tagged, 2, "only 2 of 5 memories tagged (cap)");
219
+ const tagged = mems.filter((m) => store.getMemoryTags(m.id).length);
220
+ assert.equal(tagged.length, 2, "exactly 2 memories carry tags");
221
+ const untagged = mems.filter((m) => !store.getMemoryTags(m.id).length);
222
+ assert.equal(untagged.length, 3, "the rest are untouched");
223
+ store.close();
224
+ });
225
+
226
+ test("runDream auto-tags retained memories after consolidation when autoTagEnabled=true", async () => {
227
+ const { store, service } = makeService({ autoTagEnabled: true });
228
+ const a = seed(service, "旧1", "第一段");
229
+ const b = seed(service, "旧2", "第二段");
230
+ const keep = (id) => JSON.stringify([{ action: "keep", ids: [id] }]);
231
+ let calls = 0;
232
+ const ctx = {
233
+ llm: {
234
+ stream: async function* () {
235
+ calls++;
236
+ if (calls === 1) yield { type: "text-delta", text: keep(a.id) }; // consolidation
237
+ else if (calls === 2) yield { type: "text-delta", text: JSON.stringify([{ id: a.id, tags: ["内核"] }]) }; // auto-tag
238
+ else yield { type: "text-delta", text: "总览" }; // summary
239
+ yield { type: "finish", reason: { kind: "ok" } };
240
+ }
241
+ },
242
+ logger: { warn: () => {}, info: () => {} }
243
+ };
244
+ const dream = createDreamScheduler({ thresholdCount: 1, thresholdChars: 0, delayMs: 0 });
245
+ const result = await dream.runDream(ctx, service, {
246
+ dreamProvider: "deepseek", dreamModel: "deepseek-chat", autoTagEnabled: true
247
+ });
248
+ assert.equal(result.ok, true);
249
+ assert.deepEqual(store.getMemoryTags(a.id), ["内核"], "auto-tag landed after consolidation");
250
+ store.close();
251
+ });
252
+
253
+ // ============================================================ mirror rendering
254
+
255
+ test("mirror renderMemory draws a #tag line under the title only when tags exist", () => {
256
+ const dir = mkdtempSync(join(tmpdir(), "dsh-mneme-tag-mirror-"));
257
+ const mirror = createMirror(join(dir, "m"));
258
+ const now = new Date().toISOString();
259
+ mirror.sync([
260
+ { id: "m1", type: "preference", title: "Alpha", content: "正文", importance: 3, updated_at: now, tags: [], entityTags: ["linux", "考研"] },
261
+ { id: "m2", type: "project", title: "Beta", content: "正文2", importance: 3, updated_at: now, tags: [], entityTags: [] }
262
+ ]);
263
+ const pref = readFileSync(join(dir, "m", "preferences.md"), "utf8");
264
+ assert.match(pref, /## Alpha/);
265
+ assert.match(pref, /^#linux #考研$/m, "tag line rendered under the title");
266
+ const proj = readFileSync(join(dir, "m", "projects.md"), "utf8");
267
+ assert.match(proj, /## Beta/);
268
+ assert.doesNotMatch(proj, /^#[^#\s]/m, "no # tag line when the memory has no tags");
269
+ rmSync(dir, { recursive: true, force: true });
270
+ });
271
+
272
+ test("service.setMemoryTags re-renders the mirror with the #tag line", () => {
273
+ const { store, service, file, dir } = makeMirrorService();
274
+ const { memory } = service.saveWithDedupe({ type: "preference", title: "Alpha", content: "正文" });
275
+ const r = service.setMemoryTags(memory.id, ["bash"]);
276
+ assert.equal(r.ok, true);
277
+ assert.deepEqual(r.tags, ["bash"]);
278
+ const pref = readFileSync(file("preferences"), "utf8");
279
+ assert.match(pref, /^#bash$/m, "mirror file updated with the # tag line");
280
+ // no tag line after clearing
281
+ service.setMemoryTags(memory.id, []);
282
+ const cleared = readFileSync(file("preferences"), "utf8");
283
+ assert.doesNotMatch(cleared, /^#[^#\s]/m, "tag line removed after clearing");
284
+ assert.deepEqual(store.getMemoryTags(memory.id), []);
285
+ rmSync(dir, { recursive: true, force: true });
286
+ });
287
+
288
+ test("service.setMemoryTags respects manualTagEnabled=false gate", () => {
289
+ const { service } = makeService({ manualTagEnabled: false });
290
+ const a = seed(service, "Alpha", "正文");
291
+ const r = service.setMemoryTags(a.id, ["linux"]);
292
+ assert.equal(r.ok, false);
293
+ assert.match(r.error, /manualTagEnabled/);
294
+ });