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.
package/lib/cards.mjs ADDED
@@ -0,0 +1,56 @@
1
+ // lib/cards.mjs — 把任务枝卡导出成插件可读的快照。
2
+ //
3
+ // 为什么要有这个文件:外部插件不在记忆树进程里,不能直接调 memory_* 工具。
4
+ // 记忆树把「当前 active 的任务卡」写成一份 JSON,插件启动/组装提示词时读它,
5
+ // 这样用户在记忆树里改卡后,插件下一次唤醒就能拿到新规则,不需要改插件配置。
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+
9
+ export const CARDS_FILE_NAME = "cards.json";
10
+
11
+ /**
12
+ * 写 <dataDir>/cards.json。
13
+ * 结构:{ version, exportedAt, cards: { [subject]: { id, uid, scope, title, text, updatedAt } } }
14
+ * 同 subject 多张 active 卡时,store.cards() 已按 created_at DESC 取最新一张。
15
+ */
16
+ export function exportTaskCards(store, dataDir) {
17
+ const nodes = store.cards();
18
+ const cards = Object.create(null);
19
+ const scoped = Object.create(null);
20
+ for (const n of nodes) {
21
+ const subject = String(n.subject ?? "").trim();
22
+ if (!subject) continue;
23
+ const entry = {
24
+ id: n.id,
25
+ uid: n.uid,
26
+ scope: n.scope,
27
+ title: n.title,
28
+ text: n.text,
29
+ updatedAt: n.updatedAt,
30
+ };
31
+ if (!scoped[n.scope]) scoped[n.scope] = Object.create(null);
32
+ scoped[n.scope][subject] = entry;
33
+ // 顶层 cards 保持「一个 subject 一张」的旧契约:user 优先,其余取较新的一张。
34
+ // 同 subject 的其它工作区版本仍可从 scoped[scope][subject] 取到,不再静默覆盖。
35
+ const prev = cards[subject];
36
+ if (!prev || n.scope === "user" || (prev.scope !== "user" && String(n.updatedAt) > String(prev.updatedAt))) {
37
+ cards[subject] = entry;
38
+ }
39
+ }
40
+ const payload = { version: 1, exportedAt: new Date().toISOString(), cards, scoped };
41
+ const file = path.join(dataDir, CARDS_FILE_NAME);
42
+ fs.mkdirSync(dataDir, { recursive: true });
43
+ const tmp = file + ".tmp-" + process.pid + "-" + Date.now();
44
+ fs.writeFileSync(tmp, JSON.stringify(payload, null, 2), "utf8");
45
+ fs.renameSync(tmp, file);
46
+ return { ok: true, file, count: Object.keys(cards).length, exportedAt: payload.exportedAt };
47
+ }
48
+
49
+ /** 读回快照(给 CLI/诊断用,不供插件热路径调用)。 */
50
+ export function readTaskCards(dataDir) {
51
+ try {
52
+ return JSON.parse(fs.readFileSync(path.join(dataDir, CARDS_FILE_NAME), "utf8"));
53
+ } catch {
54
+ return null;
55
+ }
56
+ }
package/lib/daily.mjs ADDED
@@ -0,0 +1,140 @@
1
+ // lib/daily.mjs — 每日分拣的报告与「一次性提交决定」。
2
+ //
3
+ // 分工(有意为之):插件不调 LLM、不存任何 key;报告只做事实汇总与聚类建议,
4
+ // 真正的「分到哪里」由宿主模型读报告后决定,再调 memory_daily action=apply 或 memory_write/forget。
5
+ import { truncate } from "./text.mjs";
6
+
7
+ const STALE_DAYS = 30;
8
+
9
+ export function buildDailyReport(store, opts = {}) {
10
+ const now = store.now();
11
+ const hours = Math.max(1, Number(opts.hours ?? 24));
12
+ const since = now - hours * 3600 * 1000;
13
+ const scopes = opts.scopes ?? ["user"];
14
+ const limit = Math.max(1, Number(opts.limit ?? 30));
15
+
16
+ const leafTotal = store.count({ scope: scopes, layers: ["leaf"], status: "active" });
17
+ const recentTotal = store.count({ scope: scopes, layers: ["leaf"], status: "active", since });
18
+ const allLeaves = store.list({ scope: scopes, layers: ["leaf"], status: "active", since, limit: 2000, order: "created" });
19
+ const pending = allLeaves;
20
+ const items = pending.slice(0, limit).map((n) => ({
21
+ id: n.id,
22
+ uid: n.uid,
23
+ text: truncate(n.text.replace(/\s+/g, " "), 400),
24
+ tags: n.tags,
25
+ subject: n.subject,
26
+ scope: n.scope,
27
+ updatedAt: n.updatedAt,
28
+ ageHours: Math.round((now - n.updatedAt) / 3600000),
29
+ source: n.source,
30
+ }));
31
+
32
+ // 聚类:同 subject 的直接一组;没 subject 的按「共享 tag」分组;都没有就单独。
33
+ const groups = new Map();
34
+ for (const n of pending) {
35
+ const keys = [];
36
+ if (n.subject) keys.push("subject:" + n.subject);
37
+ for (const t of n.tags) if (t !== "已脱敏") keys.push("tag:" + t);
38
+ if (keys.length === 0) keys.push("solo:" + n.id);
39
+ for (const k of keys) {
40
+ if (!groups.has(k)) groups.set(k, new Set());
41
+ groups.get(k).add(n.id);
42
+ }
43
+ }
44
+ const clusters = [...groups.entries()]
45
+ .filter(([, ids]) => ids.size >= 2)
46
+ .map(([key, ids]) => ({ key, ids: [...ids].sort((a, b) => a - b) }))
47
+ .sort((a, b) => b.ids.length - a.ids.length)
48
+ .slice(0, 8);
49
+
50
+ const staleBefore = now - STALE_DAYS * 86400 * 1000;
51
+ const staleCards = store
52
+ .list({ scope: scopes, layers: ["task"], status: "active", limit: 5000, order: "updated" })
53
+ .filter((n) => n.updatedAt < staleBefore)
54
+ .slice(0, 10)
55
+ .map((n) => ({ id: n.id, subject: n.subject, title: n.title, updatedAt: n.updatedAt, days: Math.round((now - n.updatedAt) / 86400000) }));
56
+
57
+ const expired = store
58
+ .list({ scope: scopes, status: "active", limit: 5000, order: "updated" })
59
+ .filter((n) => n.validUntil !== null && n.validUntil < now)
60
+ .slice(0, 10)
61
+ .map((n) => ({ id: n.id, layer: n.layer, title: n.title || truncate(n.text, 60), validUntil: n.validUntil }));
62
+
63
+ const candidates = store.list({ scope: scopes, layers: ["trunk"], status: "candidate", limit: 20, order: "created" })
64
+ .map((n) => ({ id: n.id, title: n.title || truncate(n.text, 60), createdAt: n.createdAt, source: n.source }));
65
+
66
+ return {
67
+ generatedAt: now,
68
+ scope: scopes,
69
+ scopes,
70
+ hours,
71
+ pendingCount: recentTotal,
72
+ pendingTruncated: Math.max(0, recentTotal - pending.length),
73
+ pendingOlderThanWindow: Math.max(0, leafTotal - recentTotal),
74
+ items,
75
+ clusters,
76
+ staleCards,
77
+ staleDays: STALE_DAYS,
78
+ expired,
79
+ candidates,
80
+ stats: store.stats(scopes),
81
+ };
82
+ }
83
+
84
+ /**
85
+ * decisions: [{id, to:'trunk'|'emotion'|'task'|'leaf'|'forget', subject?, title?, text?, importance?, halfLifeDays?, tags?}]
86
+ */
87
+ export function applyDailyDecisions(store, decisions, opts = {}) {
88
+ const scopes = opts.scopes ?? ["user"];
89
+ const results = [];
90
+ let candidates = 0;
91
+ for (const d of decisions) {
92
+ const id = d && d.id !== undefined ? Number(d.id) : NaN;
93
+ if (!Number.isFinite(id)) {
94
+ results.push({ id: d?.id ?? null, ok: false, error: "缺少有效 id" });
95
+ continue;
96
+ }
97
+ const node = store.get(id, { scope: scopes });
98
+ if (!node) {
99
+ results.push({ id, ok: false, error: "找不到这条记忆,或它不在当前作用域" });
100
+ continue;
101
+ }
102
+ const to = String(d.to ?? "");
103
+ try {
104
+ if (to === "forget" || to === "archive") {
105
+ store.forget(id, { reason: d.reason ?? "daily triage" });
106
+ results.push({ id, ok: true, to: "forget" });
107
+ continue;
108
+ }
109
+ if (!["trunk", "emotion", "task", "leaf"].includes(to)) {
110
+ results.push({ id, ok: false, error: "to 只能是 trunk/emotion/task/leaf/forget" });
111
+ continue;
112
+ }
113
+ if (to === "leaf") {
114
+ results.push({ id, ok: true, to: "leaf", note: "保留在判断叶,未做转移" });
115
+ continue;
116
+ }
117
+ const tags = Array.from(new Set([...(node.tags ?? []), ...(Array.isArray(d.tags) ? d.tags : []), "已分拣"]));
118
+ const input = {
119
+ layer: to,
120
+ scope: to === "emotion" || to === "trunk" ? "user" : node.scope,
121
+ text: d.text ? String(d.text) : node.text,
122
+ subject: d.subject !== undefined ? String(d.subject) : node.subject,
123
+ title: d.title !== undefined ? String(d.title) : node.title,
124
+ tags,
125
+ source: "triage",
126
+ evidence: node.evidence,
127
+ importance: d.importance !== undefined ? d.importance : undefined,
128
+ halfLifeDays: d.halfLifeDays !== undefined ? d.halfLifeDays : node.halfLifeDays,
129
+ };
130
+ // 分拣允许把工作区判断叶提升到 user 主干候选,跨作用域是这里的正常动作。
131
+ const res = store.supersede([id], { ...input, status: "active" }, { allowCrossScope: true });
132
+ if (res.node.status === "candidate") candidates += 1;
133
+ results.push({ id, ok: true, to, newId: res.node.id, newStatus: res.node.status });
134
+ } catch (err) {
135
+ results.push({ id, ok: false, error: err && err.message ? err.message : String(err) });
136
+ }
137
+ }
138
+ store.audit("daily:apply", { hits: results.filter((r) => r.ok).length, detail: { total: decisions.length, candidates } });
139
+ return { results, candidates, applied: results.filter((r) => r.ok).length };
140
+ }
package/lib/db.mjs ADDED
@@ -0,0 +1,84 @@
1
+ // lib/db.mjs — 打开库、事务、并发与崩溃恢复相关的 pragma。
2
+ //
3
+ // 并发:宿主里可能同时有主会话、子代理、面板在读同一个库。
4
+ // - WAL:读写不互相阻塞;busy_timeout 让并发写在锁上等待而不是立刻报 SQLITE_BUSY。
5
+ // - synchronous=NORMAL:WAL 下仍能扛进程崩溃(不会丢已提交事务,最多丢最近一次 checkpoint)。
6
+ // - 所有多步写都在 BEGIN IMMEDIATE 里,避免两个进程各写一半。
7
+ import { mkdirSync } from "node:fs";
8
+ import { dirname } from "node:path";
9
+ import { DatabaseSync } from "node:sqlite";
10
+ import { migrate } from "./schema.mjs";
11
+
12
+ export function openMemoryDb(file, opts = {}) {
13
+ if (opts.readOnly !== true) mkdirSync(dirname(file), { recursive: true });
14
+ const db = new DatabaseSync(file, opts.readOnly === true ? { readOnly: true } : {});
15
+ db.exec("PRAGMA busy_timeout = 8000");
16
+ if (opts.readOnly !== true) {
17
+ db.exec("PRAGMA journal_mode = WAL");
18
+ db.exec("PRAGMA synchronous = NORMAL");
19
+ db.exec("PRAGMA foreign_keys = ON");
20
+ db.exec("PRAGMA wal_autocheckpoint = 512");
21
+ migrate(db);
22
+ }
23
+ return db;
24
+ }
25
+
26
+ // 每个连接一份嵌套深度;store 的写方法可以互相调用(supersede→add),
27
+ // 内层用 SAVEPOINT,外层用 BEGIN IMMEDIATE,避免「cannot start a transaction within a transaction」。
28
+ const TX_DEPTH = new WeakMap();
29
+ let txSeq = 0;
30
+
31
+ /** 事务包装:fn 里抛错则整体回滚。支持嵌套(内层 SAVEPOINT)。fn 必须是同步函数。 */
32
+ export function tx(db, fn) {
33
+ const depth = TX_DEPTH.get(db) || 0;
34
+ const nested = depth > 0;
35
+ const savepoint = "mt_sp_" + (++txSeq);
36
+ db.exec(nested ? "SAVEPOINT " + savepoint : "BEGIN IMMEDIATE");
37
+ TX_DEPTH.set(db, depth + 1);
38
+ try {
39
+ const out = fn();
40
+ if (nested) db.exec("RELEASE " + savepoint);
41
+ else db.exec("COMMIT");
42
+ TX_DEPTH.set(db, depth);
43
+ return out;
44
+ } catch (e) {
45
+ try {
46
+ if (nested) {
47
+ db.exec("ROLLBACK TO " + savepoint);
48
+ db.exec("RELEASE " + savepoint);
49
+ } else {
50
+ db.exec("ROLLBACK");
51
+ }
52
+ } catch {
53
+ /* 回滚失败也要把原始错误抛出去 */
54
+ }
55
+ TX_DEPTH.set(db, depth);
56
+ throw e;
57
+ }
58
+ }
59
+
60
+ export function getMeta(db, key, fallback = null) {
61
+ try {
62
+ const row = db.prepare("SELECT value FROM meta WHERE key=?").get(key);
63
+ return row ? row.value : fallback;
64
+ } catch {
65
+ return fallback;
66
+ }
67
+ }
68
+
69
+ export function setMeta(db, key, value) {
70
+ db.prepare("INSERT INTO meta(key,value) VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(
71
+ String(key),
72
+ String(value),
73
+ );
74
+ }
75
+
76
+ export function bumpIndexVersion(db) {
77
+ const cur = Number(getMeta(db, "index_version", "0")) || 0;
78
+ setMeta(db, "index_version", String(cur + 1));
79
+ return cur + 1;
80
+ }
81
+
82
+ export function indexVersion(db) {
83
+ return Number(getMeta(db, "index_version", "0")) || 0;
84
+ }
package/lib/demo.mjs ADDED
@@ -0,0 +1,161 @@
1
+ // lib/demo.mjs — `mt demo`:在临时目录里生成一套四枝示例,不碰真实记忆库。
2
+ //
3
+ // 目的:刚装插件的 DSH 打开看板时不是空的,而是能看到「主干/情感枝/任务枝/判断叶」
4
+ // 各自长什么样、状态如何流转。所有条目都带「示例」标签;临时目录可随时删除。
5
+ import fs from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { fileURLToPath } from "node:url";
9
+ import { MemoryRuntime } from "./runtime.mjs";
10
+ import { buildReportHtml } from "./report.mjs";
11
+ import { localDate } from "./diary.mjs";
12
+
13
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
14
+ const DEMO_AGENTS = path.join(HERE, "..", "examples", "AGENTS.demo.md");
15
+
16
+ function seed(store) {
17
+ const add = (input) => store.add({ source: "demo", tags: ["示例"], ...input });
18
+
19
+ // 情感枝:一段叙事 + 一条工作感受。都标「示例」,不是真实经历。
20
+ add({
21
+ layer: "emotion",
22
+ scope: "user",
23
+ subject: "相处",
24
+ title: "示例:用户更在意能不能接上",
25
+ text:
26
+ "示例,不是真实记忆:用户在一次长任务收尾时说「今天先到这,剩下的明天接上」。当时没有催进度,只把未完成项和路径写进任务清单;" +
27
+ "第二天新会话按清单接回,用户说「这样就对了」。这条记的是「用户更在意能不能接上,而不是一次做完」,不是任务日志。测试完可删。",
28
+ evidence: "「今天先到这,剩下的明天接上」——示例原话,非真实记录",
29
+ tags: ["示例", "情感枝", "相处"],
30
+ importance: 0.8,
31
+ trust: 80,
32
+ halfLifeDays: 0,
33
+ });
34
+ add({
35
+ layer: "emotion",
36
+ scope: "user",
37
+ subject: "工作感受",
38
+ title: "示例:先给结论更省沟通",
39
+ text: "示例,不是真实记忆:用户对「先给结论、再给验证方式」的汇报最认可;只报「已完成」会被追问细节。测试完可删。",
40
+ tags: ["示例", "情感枝", "工作感受"],
41
+ importance: 0.6,
42
+ trust: 75,
43
+ halfLifeDays: 180,
44
+ });
45
+
46
+ // 任务枝:同一 subject 先放一张旧卡,再放新卡,演示旧卡自动转 superseded。
47
+ add({
48
+ layer: "task",
49
+ scope: "user",
50
+ subject: "memorytree",
51
+ title: "记忆树插件(旧示例卡)",
52
+ text: "示例旧卡:只写了「装完先跑 doctor」。这张卡会被下面的新卡自动取代,但不会删除,方便追溯。",
53
+ tags: ["示例", "任务枝", "memorytree"],
54
+ importance: 0.5,
55
+ trust: 60,
56
+ halfLifeDays: 0,
57
+ });
58
+ add({
59
+ layer: "task",
60
+ scope: "user",
61
+ subject: "memorytree",
62
+ title: "记忆树插件:安装与排障",
63
+ text:
64
+ "示例任务卡:① 装完先跑 `node bin/mt.mjs doctor`,看数据目录、库、AGENTS.md、旧库四项;" +
65
+ "② 改完插件代码要重装/重启 DSH,别只改源码就以为生效;" +
66
+ "③ 不要把 `trunk` 手写成 active,手动写入只会落 candidate,主干 active 只由 AGENTS.md 同步产生;" +
67
+ "④ 不要直接改 `memory.db`,用 `memory_*` 工具或 CLI;" +
68
+ "⑤ 物理删除前先导出或确认有备份。测试完可删。",
69
+ evidence: "本机实测:空 DSH_HOME 下 doctor 正常退出;`mt demo` 可用临时库复现四枝。",
70
+ tags: ["示例", "任务枝", "memorytree", "排障"],
71
+ importance: 0.8,
72
+ trust: 85,
73
+ halfLifeDays: 0,
74
+ });
75
+
76
+ // 判断叶:两条待分拣、一条零散观察。
77
+ add({
78
+ layer: "leaf",
79
+ scope: "user",
80
+ title: "示例:先别改 = 暂停,不是撤销",
81
+ text: "示例,待确认:用户说「先别改」时,通常指暂停当前改动,不是撤销已经改好的内容。未验证,先放判断叶。",
82
+ tags: ["示例", "判断叶", "待确认"],
83
+ importance: 0.4,
84
+ trust: 55,
85
+ halfLifeDays: 30,
86
+ });
87
+ add({
88
+ layer: "leaf",
89
+ scope: "user",
90
+ title: "示例:报错先贴原文",
91
+ text: "示例候选规则:报错时先贴原始错误,再给解释和修法。还没验证,先放判断叶,等日结决定去留。",
92
+ tags: ["示例", "判断叶", "候选规则"],
93
+ importance: 0.35,
94
+ trust: 50,
95
+ halfLifeDays: 30,
96
+ });
97
+ add({
98
+ layer: "leaf",
99
+ scope: "user",
100
+ title: "示例:周五更适合整理",
101
+ text: "示例零散观察:周五下午用户更愿意做整理类任务。样本太少,不上升为规则。",
102
+ tags: ["示例", "判断叶", "观察"],
103
+ importance: 0.25,
104
+ trust: 45,
105
+ halfLifeDays: 14,
106
+ });
107
+
108
+ // 主干候选:展示「手动写入 trunk 只会是 candidate」。
109
+ add({
110
+ layer: "trunk",
111
+ scope: "user",
112
+ title: "示例候选:收尾写清未完成项",
113
+ text: "示例主干候选:收尾时把未完成项、下一步和关键路径写进任务清单,新会话按清单接回。这条不是 active 规则,等用户点头后才并入主干。",
114
+ tags: ["示例", "主干候选"],
115
+ importance: 0.6,
116
+ trust: 55,
117
+ halfLifeDays: 0,
118
+ });
119
+
120
+ store.diaryAdd(
121
+ localDate(),
122
+ "示例日记(不是真实记录):今天跑了 `mt demo`,看了四枝示例和看板;这一步只写「做了什么、路径」,情感本体不写在这里。",
123
+ "示例",
124
+ );
125
+
126
+ return store.stats();
127
+ }
128
+
129
+ /**
130
+ * 生成隔离演示库。
131
+ * @param {{out?: string}} opts
132
+ * @returns {{ok: boolean, dir: string, agentsPath: string, dbFile: string, reportPath: string, stats: object, sync: object}}
133
+ */
134
+ export function runDemo(opts = {}) {
135
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "memorytree-demo-"));
136
+ const agentsPath = path.join(dir, "AGENTS.md");
137
+ fs.copyFileSync(DEMO_AGENTS, agentsPath);
138
+
139
+ const rt = new MemoryRuntime({ dataDir: dir, agentsPath, autoSync: false });
140
+ try {
141
+ const store = rt.open();
142
+ const sync = rt.ensureTrunk(null, { force: true });
143
+ if (!sync.ok) throw new Error("演示主干同步失败:" + (sync.reason || "未知原因"));
144
+ const stats = seed(store);
145
+ const html = buildReportHtml(rt, store, null, { board: { base: "", token: "", sessionId: null } });
146
+ const reportPath = opts.out ? path.resolve(String(opts.out)) : path.join(dir, "report.html");
147
+ fs.mkdirSync(path.dirname(reportPath), { recursive: true });
148
+ fs.writeFileSync(reportPath, html, "utf8");
149
+ return {
150
+ ok: true,
151
+ dir,
152
+ agentsPath,
153
+ dbFile: rt.paths.dbFile,
154
+ reportPath,
155
+ stats,
156
+ sync,
157
+ };
158
+ } finally {
159
+ rt.close();
160
+ }
161
+ }
package/lib/diary.mjs ADDED
@@ -0,0 +1,92 @@
1
+ // lib/diary.mjs — 日记索引:每天一条,记「今天做了什么、路径」。
2
+ //
3
+ // 边界(对齐 AGENTS §2-4):
4
+ // - 日记只是索引,不是情感本体;相处情感仍写在 emotion 枝。
5
+ // - 自动模式只从库内既有事实(revision / audit)拼装,不调 LLM、不抓会话正文、不联网。
6
+ // - 同一天重复 auto 会整体重算覆盖;手写(mood=manual)默认不被自动覆盖。
7
+
8
+ const ACTION_LABELS = {
9
+ add: "新增",
10
+ update: "更新",
11
+ supersede: "取代",
12
+ "replace-card": "取代",
13
+ "forget:archive": "归档",
14
+ "forget:hard": "删除",
15
+ diary: "日记",
16
+ };
17
+
18
+ const LAYER_LABELS = {
19
+ trunk: "§1 主干",
20
+ emotion: "§2 情感枝",
21
+ task: "§3 任务枝",
22
+ leaf: "§4 判断叶",
23
+ };
24
+
25
+ export function localDate(ms = Date.now()) {
26
+ const d = new Date(Number(ms) || Date.now());
27
+ const y = d.getFullYear();
28
+ const m = String(d.getMonth() + 1).padStart(2, "0");
29
+ const day = String(d.getDate()).padStart(2, "0");
30
+ return `${y}-${m}-${day}`;
31
+ }
32
+
33
+ export function isDateString(s) {
34
+ return /^\d{4}-\d{2}-\d{2}$/.test(String(s ?? ""));
35
+ }
36
+
37
+ /** 本地时区的一天 [start, end),毫秒。 */
38
+ export function dayRange(date) {
39
+ if (!isDateString(date)) throw new Error("日期格式应为 YYYY-MM-DD:" + String(date));
40
+ const [y, m, d] = String(date).split("-").map((x) => Number(x));
41
+ const start = new Date(y, m - 1, d, 0, 0, 0, 0).getTime();
42
+ const end = new Date(y, m - 1, d + 1, 0, 0, 0, 0).getTime();
43
+ return { start, end };
44
+ }
45
+
46
+ function itemLabel(row) {
47
+ const name = row.title || row.subject || row.uid || (row.node_id ? "#" + row.node_id : "未命名");
48
+ const layer = LAYER_LABELS[row.layer] ? "(" + LAYER_LABELS[row.layer] + ")" : "";
49
+ return String(name).replace(/\s+/g, " ").slice(0, 90) + layer;
50
+ }
51
+
52
+ /**
53
+ * 拼装一天的日记索引正文。
54
+ * revisions: [{action, ts, node_id, uid, title, subject, layer}]
55
+ * searches: [{query, hits}]
56
+ */
57
+ export function buildDiaryText({ date, revisions = [], searches = [], dbFile = "", agentsPath = "" }) {
58
+ const groups = new Map();
59
+ for (const r of revisions) {
60
+ const action = String(r.action ?? "");
61
+ if (action === "diary") continue; // 日记自己的版本记录不进正文
62
+ const label = ACTION_LABELS[action] ?? action;
63
+ if (!groups.has(label)) groups.set(label, []);
64
+ groups.get(label).push(r);
65
+ }
66
+
67
+ const lines = [`${date} 记忆树日记(索引)`];
68
+ if (groups.size === 0) {
69
+ lines.push("记忆树今天没有增删改。");
70
+ } else {
71
+ for (const [label, rows] of groups) {
72
+ const names = rows.slice(0, 6).map(itemLabel).join(";");
73
+ const more = rows.length > 6 ? `;等 ${rows.length} 条` : "";
74
+ lines.push(`${label} ${rows.length} 条:${names}${more}`);
75
+ }
76
+ const subjects = [...new Set(revisions.filter((r) => r.layer === "task" && (r.subject || r.title)).map((r) => r.subject || r.title))];
77
+ if (subjects.length) lines.push(`涉及任务卡:${subjects.slice(0, 10).join("、")}${subjects.length > 10 ? " 等" : ""}`);
78
+ }
79
+
80
+ const queries = (searches ?? []).filter((s) => s && s.query);
81
+ if (queries.length) {
82
+ const qs = queries.slice(0, 6).map((s) => `「${String(s.query).slice(0, 40)}」${s.hits === null || s.hits === undefined ? "" : "→" + s.hits + " 条"}`);
83
+ lines.push(`今天查过:${qs.join(";")}`);
84
+ }
85
+
86
+ const paths = [];
87
+ if (dbFile) paths.push(`库 ${dbFile}`);
88
+ if (agentsPath) paths.push(`主干 ${agentsPath}`);
89
+ if (paths.length) lines.push(paths.join(";"));
90
+ lines.push("(自动索引:只记库内事实,不含会话正文与情感叙事)");
91
+ return lines.join("\n");
92
+ }