dsh-memorytree-rule 0.0.0-stage → 1.1.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.
@@ -0,0 +1,620 @@
1
+ // tests/memory-tree.test.mjs — 纯 Node 单测:不依赖宿主,直接测库、检索、同步、迁移、分拣。
2
+ import test from "node:test";
3
+ import assert from "node:assert/strict";
4
+ import fs from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { DatabaseSync } from "node:sqlite";
8
+ import { openMemoryDb } from "../lib/db.mjs";
9
+ import { MemoryStore } from "../lib/store.mjs";
10
+ import { searchMemory } from "../lib/search.mjs";
11
+ import { parseAgents, syncTrunk } from "../lib/ingest.mjs";
12
+ import { importLegacy } from "../lib/import-legacy.mjs";
13
+ import { buildDailyReport, applyDailyDecisions } from "../lib/daily.mjs";
14
+ import { contentBlocks, tokenize, redact } from "../lib/text.mjs";
15
+ import { localDate } from "../lib/diary.mjs";
16
+ import { MemoryRuntime } from "../lib/runtime.mjs";
17
+ import { buildReportHtml } from "../lib/report.mjs";
18
+ import { buildThinkPrompt, ensureBoardToken, runBoardAction, appendRuleToAgents, trunkGroups } from "../lib/board.mjs";
19
+
20
+ function makeStore() {
21
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-test-"));
22
+ const db = openMemoryDb(path.join(dir, "memory.db"));
23
+ const store = new MemoryStore(db, { clock: () => Date.now() });
24
+ return {
25
+ dir,
26
+ db,
27
+ store,
28
+ cleanup() {
29
+ try {
30
+ db.close();
31
+ } catch {
32
+ /* 忽略 */
33
+ }
34
+ fs.rmSync(dir, { recursive: true, force: true });
35
+ },
36
+ };
37
+ }
38
+
39
+ test("分词:中文能切出二字组,英文按词切", () => {
40
+ const t = tokenize("记忆树插件 memory_tree");
41
+ assert.ok(t.has("b:记忆"));
42
+ assert.ok(t.has("b:插件"));
43
+ assert.ok(t.has("w:memory"));
44
+ assert.ok(t.has("w:tree"));
45
+ });
46
+
47
+ test("脱敏:密钥/邮箱/长数字在写入前被替换", () => {
48
+ const r = redact("token sk-abcdefghijklmnop123456 联系 a@b.com 电话 13800138000");
49
+ assert.match(r.text, /sk-\*\*\*/);
50
+ assert.match(r.text, /\*\*\*@\*\*\*/);
51
+ assert.doesNotMatch(r.text, /13800138000/);
52
+ assert.ok(r.redactions.length >= 2);
53
+ });
54
+
55
+ test("工具渲染:字符串包成宿主可接受的内容块数组", () => {
56
+ const one = contentBlocks("命中 1 条");
57
+ assert.deepEqual(one, [{ type: "text", text: "命中 1 条" }]);
58
+ const passthrough = [{ type: "text", text: "已经是数组" }];
59
+ assert.equal(contentBlocks(passthrough), passthrough);
60
+ assert.deepEqual(contentBlocks(null), [{ type: "text", text: "" }]);
61
+ });
62
+
63
+ test("看板:自包含 HTML 带星图、四主题、详情抽屉与打印入口", () => {
64
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-report-"));
65
+ const rt = new MemoryRuntime({ dataDir: dir, agentsPath: path.join(dir, "AGENTS.md") });
66
+ try {
67
+ const store = rt.open();
68
+ store.add({ layer: "task", subject: "visual", title: "看板测试卡", text: "星图与主题包的自包含页面。" });
69
+ store.add({ layer: "emotion", title: "情感测试", text: "情感枝完整正文-EMOTION" });
70
+ store.add({ layer: "leaf", title: "判断测试", text: "判断叶完整正文-LEAF" });
71
+ fs.writeFileSync(rt.paths.agentsPath, [
72
+ "## §2 情感枝",
73
+ "",
74
+ "- **§2-1 相处情感**:测试 §2 正文。",
75
+ "",
76
+ "## §3 任务枝",
77
+ "",
78
+ "- **§3-1 任务枝规则**:测试 §3 正文。",
79
+ "",
80
+ "## §4 判断叶",
81
+ "",
82
+ "- **§4-1 判断叶是什么**:测试 §4 正文。",
83
+ "",
84
+ ].join("\n"));
85
+ const longText = "这是一条很长的规则正文,用来确认详情抽屉不会只显示摘要。".repeat(8) + "尾部标记:完整正文已显示。";
86
+ store.add({ layer: "task", subject: "visual-long", title: "长规则测试", text: longText });
87
+ const html = buildReportHtml(rt, store, null);
88
+ assert.match(html, /data-theme-set="paper"/);
89
+ assert.match(html, /class="star"/);
90
+ assert.match(html, /id="drawer"/);
91
+ assert.match(html, /打印 \/ PDF/);
92
+ assert.match(html, /四枝构成/);
93
+ assert.match(html, /data-act="edit"/);
94
+ assert.match(html, /data-act="think"/);
95
+ assert.match(html, /data-act="delete"/);
96
+ assert.match(html, /id="edit-modal"/);
97
+ assert.match(html, /id="think-modal"/);
98
+ assert.match(html, /发送至“当前会话”/);
99
+ assert.match(html, /发送至“新会话”/);
100
+ assert.match(html, /id="branch-modal"/);
101
+ assert.match(html, /请选择写入哪条枝/);
102
+ assert.match(html, /id="task-modal"/);
103
+ assert.match(html, /id="trunk-modal"/);
104
+ assert.match(html, /先核对核心规则资格/);
105
+ assert.doesNotMatch(html, /id="trust-value"/);
106
+ assert.doesNotMatch(html, /重要程度/);
107
+ assert.doesNotMatch(html, /id="importance-value"/);
108
+ assert.doesNotMatch(html, /id="level-data"/);
109
+ assert.doesNotMatch(html, /importance/);
110
+ assert.match(html, /id="board-data"/);
111
+ assert.match(html, /id="map-zoom"/);
112
+ assert.match(html, /map-full/);
113
+ assert.match(html, /点击星图空白处放大\/还原/);
114
+ assert.doesNotMatch(html, /08 \/ 根系/);
115
+ assert.doesNotMatch(html, /09 \/ 健康检查/);
116
+ assert.doesNotMatch(html, /根系是什么/);
117
+ assert.doesNotMatch(html, /根系/);
118
+ assert.match(html, /08 \/ 规则/);
119
+ assert.match(html, /09 \/ 审计/);
120
+ assert.match(html, /§2-1/);
121
+ assert.match(html, /class="rule-item searchable"/);
122
+ assert.match(html, /data-node="agent:§2-1"/);
123
+ assert.match(html, /情感枝、任务枝、判断叶规则/);
124
+ assert.match(html, /情感枝、任务枝、判断叶本体规则正文。/);
125
+ assert.match(html, /write-section-rule/);
126
+ assert.match(html, /delete-section-rule/);
127
+ assert.match(html, /<p>星图与主题包的自包含页面。<\/p>/);
128
+ assert.match(html, /情感枝完整正文-EMOTION/);
129
+ assert.match(html, /判断叶完整正文-LEAF/);
130
+ assert.ok(html.includes("尾部标记:完整正文已显示。"), "详情抽屉应带完整正文,而不是截断的 preview");
131
+ assert.doesNotMatch(html, /https?:\/\//);
132
+ } finally {
133
+ try { rt.close(); } catch { /* 忽略 */ }
134
+ fs.rmSync(dir, { recursive: true, force: true });
135
+ }
136
+ });
137
+
138
+ test("看板按钮:主干修改生成候选,删除归档,通过提升,令牌可复用", () => {
139
+ const { dir, store, cleanup } = makeStore();
140
+ try {
141
+ const tr = store.add({
142
+ layer: "trunk",
143
+ scope: "user",
144
+ subject: "测试规则",
145
+ title: "测试规则",
146
+ text: "原始规则正文。",
147
+ source: "AGENTS.md#L1-L2",
148
+ }).node;
149
+ assert.equal(tr.status, "active");
150
+
151
+ const changed = runBoardAction(store, { op: "update", id: tr.id, text: "修改后的规则正文。" });
152
+ assert.equal(changed.ok, true);
153
+ assert.equal(changed.mode, "candidate");
154
+ assert.equal(changed.node.layer, "trunk");
155
+ assert.equal(changed.node.status, "candidate");
156
+ assert.match(changed.node.text, /修改后的规则正文/);
157
+ assert.equal(store.get(tr.id).text, "原始规则正文。", "AGENTS 正本对应条目不能被看板直接改掉");
158
+
159
+ const denied = runBoardAction(store, { op: "delete", id: tr.id });
160
+ assert.equal(denied.ok, false);
161
+ assert.match(denied.error, /AGENTS\.md/);
162
+
163
+ const candDenied = runBoardAction(store, { op: "delete-trunk", id: changed.node.id, confirm: true });
164
+ assert.equal(candDenied.ok, false);
165
+ assert.match(candDenied.error, /候选/);
166
+ const candDeleted = runBoardAction(store, { op: "delete", id: changed.node.id });
167
+ assert.equal(candDeleted.ok, true);
168
+ assert.equal(store.get(changed.node.id).status, "archived");
169
+
170
+ const leaf = store.add({ layer: "leaf", scope: "user", text: "一条临时判断。" }).node;
171
+ const archived = runBoardAction(store, { op: "delete", id: leaf.id });
172
+ assert.equal(archived.ok, true);
173
+ assert.equal(store.get(leaf.id).status, "archived");
174
+
175
+ const cand = store.update(leaf.id, { status: "candidate", trust: 40 });
176
+ assert.equal(cand.status, "candidate");
177
+ const approved = runBoardAction(store, { op: "approve", id: leaf.id });
178
+ assert.equal(approved.ok, true);
179
+ assert.equal(store.get(leaf.id).status, "active");
180
+ assert.equal(store.get(leaf.id).trust, 100);
181
+
182
+ const prompt = buildThinkPrompt(store.get(tr.id));
183
+ assert.match(prompt, /【规则信息】/);
184
+ assert.match(prompt, /AGENTS\.md/);
185
+ assert.match(prompt, /不写文件、不调用工具/);
186
+
187
+ const t1 = ensureBoardToken(dir);
188
+ const t2 = ensureBoardToken(dir);
189
+ assert.match(t1, /^[a-f0-9]{48}$/);
190
+ assert.equal(t1, t2);
191
+ assert.equal(fs.readFileSync(path.join(dir, "board-token"), "utf8").trim(), t1);
192
+ } finally {
193
+ cleanup();
194
+ }
195
+ });
196
+
197
+ test("客户端入口:注册侧栏「记忆树」与主区域 iframe", () => {
198
+ const code = fs.readFileSync(new URL("../client.js", import.meta.url), "utf8");
199
+ assert.match(code, /sidebar\.panellist/);
200
+ assert.match(code, /name:\s*["']main["']/);
201
+ assert.match(code, /key:\s*PANEL_ID/);
202
+ assert.match(code, /\/memory-tree\/board\?panel=1/);
203
+ assert.match(code, /\/memory-tree\/health/);
204
+ assert.match(code, /记忆树看板暂不可用/);
205
+ });
206
+
207
+ test("写入检索:2 个汉字也能召回", () => {
208
+ const { store, cleanup } = makeStore();
209
+ try {
210
+ const { node } = store.add({
211
+ layer: "task",
212
+ subject: "backup",
213
+ title: "备份脚本",
214
+ text: "备份脚本把 memories.db 复制到 D:\\backup\\memory-backup,保留最近 20 份。",
215
+ });
216
+ assert.equal(node.layer, "task");
217
+ const res = searchMemory(store, { query: "备份", scopes: ["user"], limit: 5 });
218
+ assert.equal(res.empty, undefined);
219
+ assert.equal(res.hits[0].id, node.id);
220
+ } finally {
221
+ cleanup();
222
+ }
223
+ });
224
+
225
+ test("检索:没命中时如实返回空结果,不编造", () => {
226
+ const { store, cleanup } = makeStore();
227
+ try {
228
+ store.add({ layer: "task", subject: "x", text: "语音链路走 GPT-SoVITS 9881 端口。" });
229
+ const res = searchMemory(store, { query: "kubernetes 集群升级", scopes: ["user"] });
230
+ assert.equal(res.empty, true);
231
+ assert.equal(res.hits.length, 0);
232
+ assert.ok(res.reason.includes("没有命中"));
233
+ } finally {
234
+ cleanup();
235
+ }
236
+ });
237
+
238
+ test("作用域:workspace 条目不会串到别的工作区", () => {
239
+ const { store, cleanup } = makeStore();
240
+ try {
241
+ const n = store.add({ layer: "leaf", scope: "workspace:aaa", text: "项目甲的私有配置在 config 目录。" }).node;
242
+ assert.equal(searchMemory(store, { query: "私有配置", scopes: ["user", "workspace:bbb"] }).hits.length, 0);
243
+ const hit = searchMemory(store, { query: "私有配置", scopes: ["workspace:aaa"] });
244
+ assert.equal(hit.hits[0].id, n.id);
245
+ } finally {
246
+ cleanup();
247
+ }
248
+ });
249
+
250
+ test("默认作用域:四枝默认 user,all 检索覆盖全库", () => {
251
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-scope-"));
252
+ const agents = path.join(dir, "AGENTS.md");
253
+ fs.writeFileSync(agents, "## §1 主干\n\n- **§1-1 核心规则**:测试规则。\n");
254
+ const rt = new MemoryRuntime({ dataDir: dir, agentsPath: agents });
255
+ try {
256
+ for (const layer of ["trunk", "emotion", "task", "leaf"]) {
257
+ assert.equal(rt.defaultScope(layer, { cwd: dir }), "user");
258
+ }
259
+ const store = rt.open();
260
+ store.add({ layer: "task", scope: "user", subject: "global", text: "全局任务卡" });
261
+ store.add({ layer: "leaf", scope: "workspace:other", text: "别的项目判断叶" });
262
+ const all = rt.scopesFor({ cwd: dir }, "all");
263
+ assert.ok(all.scopes.includes("user"));
264
+ assert.ok(all.scopes.includes("workspace:other"));
265
+ const hit = searchMemory(store, { query: "别的项目", scopes: all.scopes });
266
+ assert.equal(hit.hits.length, 1);
267
+ const current = rt.scopesFor({ cwd: dir }, "workspace");
268
+ assert.deepEqual(current.scopes, [rt.workspaceOf({ cwd: dir }).scope]);
269
+ const raw = store.add({ layer: "leaf", text: "邮箱 raw@example.com", skipRedact: true }).node;
270
+ assert.match(raw.text, /raw@example\.com/);
271
+ } finally {
272
+ rt.close();
273
+ fs.rmSync(dir, { recursive: true, force: true });
274
+ }
275
+ });
276
+
277
+ test("主干:手工写入只产生候选;AGENTS.md 同步的才是 active", () => {
278
+ const { store, cleanup } = makeStore();
279
+ try {
280
+ const manual = store.add({ layer: "trunk", title: "新规则", text: "每天先看任务清单。" }).node;
281
+ assert.equal(manual.status, "candidate");
282
+ assert.ok(manual.tags.includes("主干候选"));
283
+ const synced = store.add({ layer: "trunk", source: "AGENTS.md#L1-L2", text: "主干的正式规则。" }).node;
284
+ assert.equal(synced.status, "active");
285
+ } finally {
286
+ cleanup();
287
+ }
288
+ });
289
+
290
+ test("取代:旧条目不删除,标 superseded,默认检索不到", () => {
291
+ const { store, cleanup } = makeStore();
292
+ try {
293
+ const old = store.add({ layer: "task", subject: "eac", text: "渲染走旧脚本 render.ps1。" }).node;
294
+ const { node: next, superseded } = store.supersede([old.id], { layer: "task", subject: "eac", text: "渲染改走 eac 插件,旧脚本已停用。" });
295
+ assert.deepEqual(superseded, [old.id]);
296
+ assert.equal(store.get(old.id).status, "superseded");
297
+ const fresh = searchMemory(store, { query: "渲染", scopes: ["user"] });
298
+ assert.equal(fresh.hits.some((h) => h.id === old.id), false);
299
+ const withOld = searchMemory(store, { query: "渲染", scopes: ["user"], status: ["active", "candidate", "superseded", "archived"] });
300
+ assert.ok(withOld.hits.some((h) => h.id === next.id));
301
+ } finally {
302
+ cleanup();
303
+ }
304
+ });
305
+
306
+ test("遗忘:默认归档可恢复,hard 才物理删除", () => {
307
+ const { store, cleanup } = makeStore();
308
+ try {
309
+ const a = store.add({ layer: "leaf", text: "这条要归档。" }).node;
310
+ store.forget(a.id, { reason: "测试" });
311
+ assert.equal(store.get(a.id).status, "archived");
312
+ const b = store.add({ layer: "leaf", text: "这条要删除。" }).node;
313
+ store.forget(b.id, { hard: true, reason: "测试" });
314
+ assert.equal(store.get(b.id), null);
315
+ } finally {
316
+ cleanup();
317
+ }
318
+ });
319
+
320
+ test("任务卡:同 subject 新卡替换旧卡,只留一张 active", () => {
321
+ const { store, cleanup } = makeStore();
322
+ try {
323
+ store.replaceCard("pet-bridge", { layer: "task", subject: "pet-bridge", text: "旧的声音链路说明。" });
324
+ store.replaceCard("pet-bridge", { layer: "task", subject: "pet-bridge", text: "新的声音链路说明:9881 端口。" });
325
+ const actives = store.list({ layers: ["task"], status: "active", subject: "pet-bridge" });
326
+ assert.equal(actives.length, 1);
327
+ assert.match(actives[0].text, /9881/);
328
+ assert.equal(store.count({ layers: ["task"], status: "superseded", subject: "pet-bridge" }), 1);
329
+ } finally {
330
+ cleanup();
331
+ }
332
+ });
333
+
334
+ test("解析 AGENTS.md:只收 §1 规则,多行规则合并且给出行号", () => {
335
+ const md = [
336
+ "# 记忆树",
337
+ "## §1 主干(大脑)",
338
+ "### 核心判据",
339
+ "#### §1-1 基本判据",
340
+ "",
341
+ "- **§1-1-1 我是谁**:我叫「续」。",
342
+ " 第二行是同一条规则的补充。",
343
+ " - 子条目也属于这条规则。",
344
+ "- **§1-1-2 永久规则**:优先级最高。",
345
+ "",
346
+ "## §2 情感枝",
347
+ "- **§2-1 相处情感**:不在主干里。",
348
+ "",
349
+ "## §3 任务枝",
350
+ "- **§3-1 任务枝规则**:也不在主干里。",
351
+ ].join("\n");
352
+ const p = parseAgents(md);
353
+ assert.equal(p.rules.length, 2);
354
+ assert.equal(p.rules[0].num, "§1-1-1");
355
+ assert.equal(p.rules[0].group, "基本判据");
356
+ assert.ok(p.rules[0].text.includes("补充"));
357
+ assert.ok(p.rules[0].text.includes("子条目"));
358
+ assert.equal(p.rules[0].startLine, 6);
359
+
360
+ const { store, cleanup, dir } = makeStore();
361
+ try {
362
+ const agents = path.join(dir, "AGENTS.md");
363
+ fs.writeFileSync(agents, md, "utf8");
364
+ const r1 = syncTrunk(store, agents);
365
+ assert.equal(r1.ok, true);
366
+ assert.equal(r1.added, 2);
367
+ assert.equal(store.count({ layers: ["trunk"], status: "active" }), 2);
368
+ const r2 = syncTrunk(store, agents);
369
+ assert.equal(r2.added + r2.updated, 0);
370
+ assert.equal(r2.unchanged, 2);
371
+
372
+ fs.writeFileSync(agents, md.replace("优先级最高。", "优先级最高,任何行为都不能绕过。"), "utf8");
373
+ const r3 = syncTrunk(store, agents);
374
+ assert.equal(r3.updated, 1);
375
+
376
+ fs.writeFileSync(agents, md.split("\n").filter((l) => !l.includes("§1-1-2")).join("\n"), "utf8");
377
+ const r4 = syncTrunk(store, agents);
378
+ assert.equal(r4.archived, 1);
379
+ assert.equal(store.count({ layers: ["trunk"], status: "active" }), 1);
380
+ } finally {
381
+ cleanup();
382
+ }
383
+ });
384
+
385
+ test("迁移旧库:task/misc 按标签分流,重跑幂等", () => {
386
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-legacy-"));
387
+ const legacy = path.join(dir, "memories.db");
388
+ const db = new DatabaseSync(legacy);
389
+ db.exec(`CREATE TABLE memory (id INTEGER PRIMARY KEY, layer TEXT, subject TEXT, text TEXT, summary TEXT,
390
+ tags TEXT, ts INTEGER, half_life_days REAL, tier TEXT)`);
391
+ const ins = db.prepare("INSERT INTO memory (id,layer,subject,text,summary,tags,ts,half_life_days,tier) VALUES (?,?,?,?,?,?,?,?,?)");
392
+ ins.run(1, "task", "restart-dsh", "重启只走 restart_dsh.ps1。", null, '["任务枝"]', 1700000000, 0, "L2");
393
+ ins.run(2, "misc", "", "主人说以后先备份再改。", null, '["情感枝","relationship"]', 1700000100, 30, "L2");
394
+ ins.run(3, "misc", "", "备份脚本要带时间戳。", null, '["主干候选"]', 1700000200, 0, "L2");
395
+ ins.run(4, "misc", "", "一个还没分类的观察。", null, "[]", 1700000300, 0, "L2");
396
+ db.close();
397
+
398
+ const { store, cleanup } = makeStore();
399
+ try {
400
+ const r = importLegacy(store, legacy);
401
+ assert.equal(r.ok, true);
402
+ assert.equal(r.added, 4);
403
+ assert.equal(r.byLayer.emotion, 1);
404
+ assert.equal(r.byLayer.task, 1);
405
+ assert.equal(r.byLayer.trunk, 1);
406
+ assert.equal(r.byLayer.leaf, 1);
407
+ assert.equal(store.count({ layers: ["trunk"], status: "candidate" }), 1);
408
+ const again = importLegacy(store, legacy);
409
+ assert.equal(again.added, 0);
410
+ assert.equal(again.duplicate, 4);
411
+ } finally {
412
+ cleanup();
413
+ fs.rmSync(dir, { recursive: true, force: true });
414
+ }
415
+ });
416
+
417
+ test("每日分拣:报告列待分拣,apply 能把叶转成卡或遗忘", () => {
418
+ const { store, cleanup } = makeStore();
419
+ try {
420
+ const a = store.add({ layer: "leaf", text: "pet-bridge 的 TTS 端口固定 9881。", tags: "语音" }).node;
421
+ store.add({ layer: "leaf", text: "今天先不聊这个。", tags: "语音,闲聊" }).node;
422
+ const rep = buildDailyReport(store, { scopes: ["user"], hours: 24, limit: 10 });
423
+ assert.equal(rep.pendingCount, 2);
424
+ assert.ok(rep.items.some((i) => i.id === a.id));
425
+ assert.ok(rep.clusters.some((c) => c.key === "tag:语音"));
426
+
427
+ const res = applyDailyDecisions(
428
+ store,
429
+ [
430
+ { id: a.id, to: "task", subject: "pet-bridge" },
431
+ { id: store.list({ layers: ["leaf"], status: "active" }).find((n) => n.id !== a.id).id, to: "forget" },
432
+ ],
433
+ { scopes: ["user"] },
434
+ );
435
+ assert.equal(res.applied, 2);
436
+ assert.equal(store.get(a.id).status, "superseded");
437
+ const card = store.list({ layers: ["task"], status: "active", subject: "pet-bridge" });
438
+ assert.equal(card.length, 1);
439
+ assert.match(card[0].text, /9881/);
440
+ } finally {
441
+ cleanup();
442
+ }
443
+ });
444
+
445
+ test("同 subject 直接 add 任务卡也会取代旧卡", () => {
446
+ const { store, cleanup } = makeStore();
447
+ try {
448
+ const a = store.add({ layer: "task", subject: "add-card", text: "旧卡:走 8080。" }).node;
449
+ const b = store.add({ layer: "task", subject: "add-card", text: "新卡:走插件。" }).node;
450
+ assert.equal(store.get(a.id).status, "superseded");
451
+ assert.equal(store.get(a.id).supersededBy, b.id);
452
+ assert.equal(store.count({ layers: ["task"], status: "active", subject: "add-card" }), 1);
453
+ } finally {
454
+ cleanup();
455
+ }
456
+ });
457
+
458
+ test("过期条目降权,active 优先", () => {
459
+ const { store, cleanup } = makeStore();
460
+ try {
461
+ const now = Date.now();
462
+ const expired = store.add({ layer: "task", subject: "old", text: "旧路线:走 8080 端口。", validUntil: now - 86400000 }).node;
463
+ const fresh = store.add({ layer: "task", subject: "new", text: "新路线:走 8787 端口。", validUntil: now + 86400000 }).node;
464
+ const res = searchMemory(store, { query: "端口", scopes: ["user"], limit: 5, now });
465
+ assert.equal(res.hits[0].id, fresh.id);
466
+ assert.ok(res.hits.some((h) => h.id === expired.id && h.expired));
467
+ } finally {
468
+ cleanup();
469
+ }
470
+ });
471
+
472
+ test("日记:自动索引只写库内事实,手写不被自动覆盖", () => {
473
+ const { store, cleanup } = makeStore();
474
+ try {
475
+ const today = localDate(Date.now());
476
+ store.add({ layer: "task", subject: "diary-demo", title: "日记测试卡", text: "写一条日记索引,路径 D:\\example\\workspace。" });
477
+ const auto = store.diaryAuto(today, { dbFile: "X:\\memory.db" });
478
+ assert.equal(auto.skipped, false);
479
+ assert.match(auto.record.text, /新增 1 条/);
480
+ assert.match(auto.record.text, /日记测试卡/);
481
+ assert.match(auto.record.text, /X:\\memory\.db/);
482
+ assert.equal(auto.record.mood, "auto");
483
+
484
+ store.diaryAdd(today, "手写:今天把日记补回来了。", "manual");
485
+ const again = store.diaryAuto(today);
486
+ assert.equal(again.skipped, true);
487
+ assert.match(again.record.text, /手写/);
488
+
489
+ const forced = store.diaryAuto(today, { force: true });
490
+ assert.equal(forced.skipped, false);
491
+ assert.equal(store.diaryList(10).length, 1);
492
+ assert.equal(store.stats().diaryTotal, 1);
493
+ } finally {
494
+ cleanup();
495
+ }
496
+ });
497
+
498
+ test("导入导出:JSONL 往返不丢关键字段", () => {
499
+ const { store, cleanup } = makeStore();
500
+ try {
501
+ store.add({ layer: "emotion", text: "主人说先做插件,再谈别的。", tags: "相处", importance: 0.8, validUntil: Date.now() + 3600000 });
502
+ const jsonl = store.exportJsonl();
503
+ const { store: store2, cleanup: cleanup2 } = makeStore();
504
+ try {
505
+ const r = store2.importJsonl(jsonl);
506
+ assert.equal(r.added, 1);
507
+ const n = store2.list({ limit: 5 })[0];
508
+ assert.equal(n.layer, "emotion");
509
+ assert.ok(n.tags.includes("相处"));
510
+ assert.ok(n.validUntil > Date.now());
511
+ } finally {
512
+ cleanup2();
513
+ }
514
+ } finally {
515
+ cleanup();
516
+ }
517
+ });
518
+ test("归类:任务推荐落卡、情感归枝、主干五项检查写正本", () => {
519
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-place-"));
520
+ const agents = path.join(dir, "AGENTS.md");
521
+ fs.writeFileSync(
522
+ agents,
523
+ "# AGENTS.md\n\n## §1 主干(大脑)\n\n### §1-1 基本判据\n\n- **§1-1-1 测试规则**:原始规则正文。\n\n## §2 情感枝\n\n内容。\n",
524
+ "utf8",
525
+ );
526
+ const db = openMemoryDb(path.join(dir, "memory.db"));
527
+ const store = new MemoryStore(db, { clock: () => Date.now() });
528
+ const options = { agentsPath: agents, backupDir: path.join(dir, "backups") };
529
+ try {
530
+ syncTrunk(store, agents, { scope: "user" });
531
+ const groups = trunkGroups(fs.readFileSync(agents, "utf8"));
532
+ assert.equal(groups[0].key, "§1-1");
533
+ assert.equal(groups[0].title, "基本判据");
534
+
535
+ const leaf = store.add({ layer: "leaf", scope: "user", subject: "self", title: "群规则", text: "群管理档只能查询,不能执行操作。", importance: 0.85 }).node;
536
+ const created = runBoardAction(store, { op: "placement-create", id: leaf.id, text: leaf.text }, options);
537
+ assert.equal(created.ok, true);
538
+ assert.equal(created.placement.status, "pending");
539
+ assert.match(created.prompt, /action=placement, op=recommend/);
540
+
541
+ store.placementRecommend(created.placement.id, { subject: "bot", reason: "这是插件操作规则" });
542
+ const task = runBoardAction(store, { op: "branch-task", id: leaf.id, requestId: created.placement.id, subject: "bot" }, options);
543
+ assert.equal(task.ok, true);
544
+ assert.equal(store.get(leaf.id).status, "superseded");
545
+ assert.match(store.cards(["user"]).find((c) => c.subject === "bot").text, /群管理档/);
546
+
547
+ const emo = store.add({ layer: "leaf", scope: "user", subject: "self", title: "偏好", text: "用户喜欢安静的环境。" }).node;
548
+ const emoDone = runBoardAction(store, { op: "branch-emotion", id: emo.id, text: emo.text }, options);
549
+ assert.equal(emoDone.ok, true);
550
+ assert.equal(emoDone.node.layer, "emotion");
551
+ assert.equal(store.get(emo.id).status, "superseded");
552
+
553
+ const trunkLeaf = store.add({ layer: "leaf", scope: "user", subject: "self", title: "新约定", text: "每次答复先给结论,再给理由。" }).node;
554
+ const denied = runBoardAction(store, { op: "write-trunk-new", id: trunkLeaf.id, text: trunkLeaf.text }, options);
555
+ assert.equal(denied.ok, false);
556
+ const ok = runBoardAction(store, {
557
+ op: "write-trunk-new",
558
+ id: trunkLeaf.id,
559
+ text: trunkLeaf.text,
560
+ confirm: true,
561
+ checks: [true, true, true, true, true],
562
+ group: "§1-1",
563
+ }, options);
564
+ assert.equal(ok.ok, true, ok.error || JSON.stringify(ok));
565
+ assert.match(fs.readFileSync(agents, "utf8"), /每次答复先给结论/);
566
+ assert.ok(ok.backup && fs.existsSync(ok.backup));
567
+ assert.equal(store.get(trunkLeaf.id).status, "superseded");
568
+ } finally {
569
+ try { db.close(); } catch { /* 忽略 */ }
570
+ fs.rmSync(dir, { recursive: true, force: true });
571
+ }
572
+ });
573
+
574
+ test("看板写正本:确认后备份并改 AGENTS.md;信任升档;添加规则", () => {
575
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mt-write-"));
576
+ const agents = path.join(dir, "AGENTS.md");
577
+ fs.writeFileSync(agents, "# AGENTS.md\n\n## §1 主干(大脑)\n\n- **§1-1-1 测试规则**:原始规则正文。\n\n## §2 情感枝\n\n内容。\n", "utf8");
578
+ const db = openMemoryDb(path.join(dir, "memory.db"));
579
+ const store = new MemoryStore(db, { clock: () => Date.now() });
580
+ const options = { agentsPath: agents, backupDir: path.join(dir, "backups") };
581
+ try {
582
+ syncTrunk(store, agents, { scope: "user" });
583
+ const tr = store.list({ layers: ["trunk"], status: "active" })[0];
584
+ assert.ok(tr, "应先同步出一条主干");
585
+ const denied = runBoardAction(store, { op: "write-trunk", id: tr.id, text: "改写后的规则正文。" }, options);
586
+ assert.equal(denied.ok, false);
587
+
588
+ const written = runBoardAction(store, { op: "write-trunk", id: tr.id, text: "改写后的规则正文。", confirm: true }, options);
589
+ assert.equal(written.ok, true);
590
+ assert.match(fs.readFileSync(agents, "utf8"), /改写后的规则正文/);
591
+ assert.ok(written.backup && fs.existsSync(written.backup), "写文件前应留备份");
592
+ assert.match(store.get(tr.id).text, /改写后的规则正文/);
593
+
594
+ const add = runBoardAction(store, { op: "add-rule", text: "新规则:回复先给结论。" }, options);
595
+ assert.equal(add.ok, true);
596
+ assert.equal(add.node.layer, "leaf");
597
+
598
+ const leaf = store.add({ layer: "leaf", scope: "user", text: "待评估的候选。" }).node;
599
+ store.update(leaf.id, { status: "candidate" });
600
+ const promoted = runBoardAction(store, { op: "set-trust", id: leaf.id, level: "mid" }, options);
601
+ assert.equal(promoted.ok, true);
602
+ assert.equal(store.get(leaf.id).status, "active");
603
+ assert.equal(store.get(leaf.id).trust, 80);
604
+
605
+ const beforeImportance = store.get(leaf.id).importance;
606
+ const imp = runBoardAction(store, { op: "set-importance", id: leaf.id, level: "high" }, options);
607
+ assert.equal(imp.ok, false, "重要程度功能已移除,旧操作应被拒绝");
608
+ assert.match(imp.error, /未知操作/);
609
+ assert.equal(store.get(leaf.id).importance, beforeImportance);
610
+
611
+ const del = runBoardAction(store, { op: "delete-trunk", id: tr.id, confirm: true }, options);
612
+ assert.equal(del.ok, true);
613
+ assert.doesNotMatch(fs.readFileSync(agents, "utf8"), /测试规则/);
614
+ assert.equal(store.get(tr.id).status, "archived");
615
+ } finally {
616
+ try { db.close(); } catch { /* 忽略 */ }
617
+ fs.rmSync(dir, { recursive: true, force: true });
618
+ }
619
+ });
620
+