dsh-memorytree-rule 0.0.0-stage → 1.0.2

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,474 @@
1
+ // lib/emotion.mjs — 情感枝自动收录(可选):本地采集、打分、候选表与日结数据。
2
+ //
3
+ // 边界(说明见 docs/EMOTION.md):
4
+ // - 默认关闭(emotionCapture:false);用户显式开启后,采集只在本机 SQLite 里做,不调模型、不联网。
5
+ // - 候选只留节选(默认 30 天清掉),不是记忆;真正写进 node 的仍走 memory_write,日结时按第一人称感受门槛筛。
6
+ // - 采集失败绝不影响会话:captureEmotionEvent 只返回结果,不向调用方抛错。
7
+ import { createHash } from "node:crypto";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { tx } from "./db.mjs";
11
+ import { localDate } from "./diary.mjs";
12
+ import { redact, truncate } from "./text.mjs";
13
+
14
+ export const CAPTURE_TEXT_MAX = 800;
15
+ export const CONTEXT_MAX = 240;
16
+ export const CAPTURE_MIN_SCORE = 35;
17
+ export const DAILY_CANDIDATE_LIMIT = 12;
18
+ export const SESSION_CANDIDATE_LIMIT = 6;
19
+ export const CANDIDATE_RETENTION_DAYS = 30;
20
+ export const CATEGORY_LIMITS = { relationship: 6, plugin: 4, work: 6 };
21
+
22
+ const EMOTION_WORDS = [
23
+ "想你", "难过", "开心", "高兴", "害怕", "生气", "对不起", "谢谢", "陪我", "离开",
24
+ "永远", "喜欢", "讨厌", "孤独", "累", "心疼", "委屈", "感动", "想哭", "眼泪",
25
+ "温暖", "舍不得", "担心", "焦虑", "失望", "骄傲", "安心", "舍不得", "崩了",
26
+ ];
27
+ const MEMORY_WORDS = ["记得", "第一次", "以前", "那时候", "小时候", "当年", "后来", "曾经", "回忆", "忘不了"];
28
+ const PROMISE_WORDS = ["以后", "答应", "别忘了", "说好", "约定", "下次", "一直", "陪着你"];
29
+ const WORK_FAIL_WORDS = ["崩了", "报错", "失败", "卡住", "踩坑", "不兼容", "挂了", "修不好", "白忙", "没跑通"];
30
+ const WORK_DONE_WORDS = ["搞定", "修好", "通过", "跑通", "成功", "完成", "上线", "恢复", "能用了"];
31
+ const WORK_CORRECTION_WORDS = ["被骂", "被说", "被纠正", "不对", "返工", "打回"];
32
+ const WORK_PRAISE_WORDS = ["被夸", "很好", "不错", "满意", "可以了"];
33
+ const PLUGIN_REFLECTION_WORDS = [
34
+ "我觉得", "有点", "其实", "这条不回", "不回", "已发", "看到", "访客", "挑衅",
35
+ "低俗", "可怜", "可笑", "没必要", "算了", "挑事", "不想接",
36
+ ];
37
+
38
+ const NOISE_PREFIX = /^(Current runtime context\.|Time sampled while preparing|<system-reminder>|\[SCHEDULE REMINDER\]|<available_skills>)/i;
39
+
40
+ function hits(text, words) {
41
+ return words.filter((w) => text.includes(w));
42
+ }
43
+
44
+ function sha1(s) {
45
+ return createHash("sha1").update(String(s)).digest("hex");
46
+ }
47
+
48
+ function round4(n) {
49
+ return Math.round((Number(n) || 0) * 10000) / 10000;
50
+ }
51
+
52
+ function tsOf(event, fallback = Date.now()) {
53
+ const raw = event?.ts ?? event?.time;
54
+ if (typeof raw === "number" && Number.isFinite(raw)) return raw;
55
+ if (typeof raw === "string") {
56
+ const n = Date.parse(raw);
57
+ if (Number.isFinite(n)) return n;
58
+ }
59
+ return fallback;
60
+ }
61
+
62
+ function textBlocks(content) {
63
+ if (typeof content === "string") return [content];
64
+ if (!Array.isArray(content)) return [];
65
+ return content
66
+ .filter((b) => b && b.type === "text" && typeof b.text === "string")
67
+ .map((b) => b.text);
68
+ }
69
+
70
+ /** 从 session/event 事件里判断角色;拿不到返回空串。 */
71
+ export function eventRole(event) {
72
+ const type = String(event?.type ?? "");
73
+ if (type === "user/message" || type.endsWith("/user/message")) return "user";
74
+ if (type === "assistant/message" || type.endsWith("/assistant/message")) return "assistant";
75
+ const d = event?.data;
76
+ if (d?.message?.role === "assistant" || d?.role === "assistant") return "assistant";
77
+ if (d?.role === "user" || d?.source) return "user";
78
+ return "";
79
+ }
80
+
81
+ /** 只取 text 块;去掉运行时上下文、身份提示、代码围栏、纯 JSON/工具输出。 */
82
+ export function extractText(event) {
83
+ const role = eventRole(event);
84
+ if (!role) return "";
85
+ const data = event?.data;
86
+ const content = role === "assistant" ? data?.message?.content : data?.content;
87
+ let text = textBlocks(content).join("\n").trim();
88
+ if (!text) return "";
89
+ if (NOISE_PREFIX.test(text)) return "";
90
+ // 代码围栏整段是工具/代码时丢掉;夹在叙述里的围栏只去掉围栏本身。
91
+ if (/^```[\s\S]*```$/.test(text)) return "";
92
+ text = text.replace(/```[\s\S]*?```/g, " ").replace(/[ \t]+\n/g, "\n").trim();
93
+ if (/^\s*[{[]/.test(text)) {
94
+ try {
95
+ JSON.parse(text);
96
+ return "";
97
+ } catch {
98
+ /* 不是纯 JSON,继续 */
99
+ }
100
+ }
101
+ return text.replace(/\n{3,}/g, "\n\n").trim();
102
+ }
103
+
104
+ export function sessionCwd(session) {
105
+ const cwd = session?.header?.cwd ?? session?.cwd ?? "";
106
+ return String(cwd ?? "").trim();
107
+ }
108
+
109
+ /**
110
+ * 外部插件会话的 cwd 子串;默认空数组(不把任何 cwd 当访客)。
111
+ * 用户可在配置里加 emotionPluginCwdPatterns: ["plugins", "chat"] 之类。
112
+ */
113
+ export function isPluginCwd(cwd, patterns = []) {
114
+ const p = String(cwd ?? "");
115
+ return (Array.isArray(patterns) ? patterns : []).some((x) => String(x).trim() !== "" && p.includes(String(x)));
116
+ }
117
+
118
+ /**
119
+ * 分类:plugin(配置命中的外部插件会话)、work(干活受挫/完成/被纠正)、relationship(与用户相处)。
120
+ * 外部插件会话优先按 cwd 判定;主会话里 user 消息看 source.kind,助手消息看工作词。
121
+ */
122
+ export function classifyEvent(session, event, text = extractText(event), options = {}) {
123
+ const role = eventRole(event);
124
+ if (!role) return null;
125
+ const cwd = sessionCwd(session);
126
+ const patterns = options.pluginCwdPatterns ?? [];
127
+ if (isPluginCwd(cwd, patterns)) return { role, category: "plugin", cwd };
128
+ if (role === "user") {
129
+ const kind = String(event?.data?.source?.kind ?? "");
130
+ // 只有用户亲手发的消息才算相处;调度、看板、工具注入的消息是工作消息,不能冒充访客。
131
+ return { role, category: kind === "user" ? "relationship" : "work", cwd };
132
+ }
133
+ if (hits(text, WORK_FAIL_WORDS).length || hits(text, WORK_DONE_WORDS).length || hits(text, WORK_CORRECTION_WORDS).length) {
134
+ return { role, category: "work", cwd };
135
+ }
136
+ return { role, category: "relationship", cwd };
137
+ }
138
+
139
+ /**
140
+ * 0–100 分。分数只用于「值不值得进候选」,不判断艺术质量;35 分以上才入表。
141
+ * reasons 写清楚加分项,方便日结时回看为什么选中它。
142
+ */
143
+ export function scoreCandidate(text, role, category) {
144
+ const t = String(text ?? "");
145
+ let score = 0;
146
+ const reasons = [];
147
+ const add = (n, why) => {
148
+ if (!n) return;
149
+ score += n;
150
+ reasons.push(why + (n > 0 ? "+" : "") + n);
151
+ };
152
+
153
+ if (t.length < 8) return { score: 0, reasons: ["太短"] };
154
+ const body = t.length > 4000 ? t.slice(0, 4000) : t;
155
+
156
+ if (category === "relationship" || category === "plugin") {
157
+ const emo = hits(body, EMOTION_WORDS);
158
+ if (emo.length) add(Math.min(36, emo.length * 15), "情绪词:" + emo.slice(0, 3).join("/"));
159
+ const mem = hits(body, MEMORY_WORDS);
160
+ if (mem.length) add(Math.min(24, mem.length * 12), "回忆词:" + mem.slice(0, 3).join("/"));
161
+ const prom = hits(body, PROMISE_WORDS);
162
+ if (prom.length) add(Math.min(20, prom.length * 10), "约定词:" + prom.slice(0, 3).join("/"));
163
+ }
164
+
165
+ if (category === "work") {
166
+ const fail = hits(body, WORK_FAIL_WORDS);
167
+ const done = hits(body, WORK_DONE_WORDS);
168
+ const corr = hits(body, WORK_CORRECTION_WORDS);
169
+ const praise = hits(body, WORK_PRAISE_WORDS);
170
+ if (fail.length) add(Math.min(36, fail.length * 15), "受挫:" + fail.slice(0, 3).join("/"));
171
+ if (done.length) add(Math.min(24, done.length * 12), "完成:" + done.slice(0, 3).join("/"));
172
+ if (corr.length) add(Math.min(24, corr.length * 12), "被纠正:" + corr.slice(0, 3).join("/"));
173
+ if (praise.length) add(Math.min(18, praise.length * 9), "被夸:" + praise.slice(0, 3).join("/"));
174
+ add(6, "工作消息");
175
+ }
176
+
177
+ if (category === "plugin") {
178
+ const refl = hits(body, PLUGIN_REFLECTION_WORDS);
179
+ if (refl.length) add(Math.min(30, refl.length * 10), "插件反思:" + refl.slice(0, 3).join("/"));
180
+ if (role === "assistant") add(10, "助手反应");
181
+ else add(4, "访客消息");
182
+ }
183
+
184
+ if (/[我咱]|我们/.test(body)) add(8, "第一人称");
185
+ if (/[??]|吗|呢/.test(body)) add(5, "问句");
186
+ if (body.length >= 40 && body.length <= 800) add(6, "长度适中");
187
+ if (body.length > 1200) add(-12, "过长");
188
+ if (NOISE_PREFIX.test(body)) add(-60, "系统提示");
189
+ if (/^\s*[{[]/.test(body)) {
190
+ try {
191
+ JSON.parse(body);
192
+ add(-60, "纯JSON");
193
+ } catch {
194
+ /* 不是纯 JSON */
195
+ }
196
+ }
197
+ if (/^https?:\/\/\S+$/.test(body.trim())) add(-30, "纯链接");
198
+
199
+ return { score: Math.max(0, Math.min(100, score)), reasons: reasons.length ? reasons : ["无加分项"] };
200
+ }
201
+
202
+ /** 候选脱敏:访客消息的 [昵称 (OpenID)] 变 [访客],长 hex、邮箱、密钥交给 text.mjs。 */
203
+ export function redactForCandidate(text) {
204
+ let t = String(text ?? "");
205
+ t = t.replace(/\[([^\]\n]{0,40})\s*\((?:OpenID|openid)?[::]?\s*[0-9A-Fa-f]{16,}\)\]/g, "[访客]");
206
+ t = t.replace(/\b[0-9A-Fa-f]{32,}\b/g, "[id]");
207
+ t = t.replace(/(?:OpenID|open_id|openid)\s*[::=]\s*[0-9A-Za-z_-]{8,}/gi, "OpenID ***");
208
+ t = t.replace(/@[A-Za-z0-9_-]{2,}/g, "@某人");
209
+ return redact(t).text;
210
+ }
211
+
212
+ function contextMap(runtime) {
213
+ if (!(runtime._emotionContext instanceof Map)) runtime._emotionContext = new Map();
214
+ return runtime._emotionContext;
215
+ }
216
+
217
+ function noteContext(runtime, sessionId, role, text) {
218
+ if (!sessionId || !text) return;
219
+ const map = contextMap(runtime);
220
+ const cur = map.get(sessionId) ?? { user: "", assistant: "" };
221
+ cur[role] = truncate(text, 500);
222
+ map.delete(sessionId);
223
+ map.set(sessionId, cur);
224
+ if (map.size > 200) {
225
+ const first = map.keys().next().value;
226
+ if (first !== undefined) map.delete(first);
227
+ }
228
+ }
229
+
230
+ function contextOf(runtime, sessionId, role) {
231
+ const cur = contextMap(runtime).get(sessionId);
232
+ if (!cur) return "";
233
+ return role === "user" ? cur.assistant : cur.user;
234
+ }
235
+
236
+ /**
237
+ * 采集一条消息。runtime 需要 open()(MemoryRuntime)与 config。
238
+ * 返回 {ok:true,id,...} 或 {ok:false,skipped/error};调用方不该因为它失败而中断会话。
239
+ */
240
+ export function captureEmotionEvent(runtime, session, event, opts = {}) {
241
+ const cfg = { ...(runtime?.config ?? {}), ...(opts ?? {}) };
242
+ // 公开版默认关闭;只有显式 emotionCapture:true 才采集。
243
+ if (cfg.emotionCapture !== true) return { ok: false, skipped: "disabled" };
244
+
245
+ const role = eventRole(event);
246
+ if (!role) return { ok: false, skipped: "not-message" };
247
+ const text = extractText(event);
248
+ const sessionId = String(session?.header?.id ?? session?.id ?? "");
249
+ if (!text || text.length < 8) {
250
+ noteContext(runtime, sessionId, role, text);
251
+ return { ok: false, skipped: "empty" };
252
+ }
253
+
254
+ const cls = classifyEvent(session, event, text, { pluginCwdPatterns: cfg.emotionPluginCwdPatterns });
255
+ if (!cls) return { ok: false, skipped: "no-category" };
256
+ const { score, reasons } = scoreCandidate(text, role, cls.category);
257
+ const minScore = Number(cfg.emotionMinScore ?? CAPTURE_MIN_SCORE);
258
+
259
+ // 无论是否入选都记上下文,下一条消息才能带上前一句。
260
+ const prev = contextOf(runtime, sessionId, role);
261
+ noteContext(runtime, sessionId, role, text);
262
+
263
+ if (score < minScore) return { ok: false, skipped: "low-score", score, category: cls.category };
264
+
265
+ const now = Date.now();
266
+ const ts = tsOf(event, now);
267
+ const day = localDate(ts);
268
+ // 用「天 + 会话 + 角色 + 正文」去重:同一条消息被 event 重复投递时只留一次,
269
+ // 同一天同一句话再发一次也视为重复;隔天再发仍可入候选。
270
+ const dedupe = sha1(sessionId + "|" + role + "|" + day + "|" + text).slice(0, 32);
271
+ const candidateText = truncate(redactForCandidate(text), CAPTURE_TEXT_MAX);
272
+ const contextText = truncate(redactForCandidate(prev), CONTEXT_MAX);
273
+
274
+ let store;
275
+ try {
276
+ store = runtime.open();
277
+ } catch (err) {
278
+ return { ok: false, error: err?.message ? String(err.message) : String(err) };
279
+ }
280
+
281
+ const sessionLimit = Number(cfg.emotionSessionLimit ?? SESSION_CANDIDATE_LIMIT);
282
+ const dayLimit = Number(cfg.emotionDailyLimit ?? DAILY_CANDIDATE_LIMIT);
283
+ const categoryLimit = Number(cfg.emotionCategoryLimits?.[cls.category] ?? CATEGORY_LIMITS[cls.category] ?? dayLimit);
284
+
285
+ try {
286
+ return tx(store.db, () => {
287
+ const countSession = store.db
288
+ .prepare("SELECT COUNT(*) AS n FROM emotion_candidate WHERE day=? AND session_id=?")
289
+ .get(day, sessionId).n;
290
+ if (countSession >= sessionLimit) return { ok: false, skipped: "session-cap", score, category: cls.category };
291
+ const countDay = store.db.prepare("SELECT COUNT(*) AS n FROM emotion_candidate WHERE day=?").get(day).n;
292
+ if (countDay >= dayLimit) return { ok: false, skipped: "day-cap", score, category: cls.category };
293
+ const countCategory = store.db
294
+ .prepare("SELECT COUNT(*) AS n FROM emotion_candidate WHERE day=? AND category=?")
295
+ .get(day, cls.category).n;
296
+ if (countCategory >= categoryLimit) return { ok: false, skipped: "category-cap", score, category: cls.category };
297
+
298
+ const info = store.db
299
+ .prepare(
300
+ `INSERT OR IGNORE INTO emotion_candidate
301
+ (day, ts, session_id, cwd, role, category, score, reasons, text, context, dedupe, status, created_at, updated_at)
302
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,'pending',?,?)`,
303
+ )
304
+ .run(
305
+ day, ts, sessionId, cls.cwd, role, cls.category, score, JSON.stringify(reasons),
306
+ candidateText, contextText, dedupe, now, now,
307
+ );
308
+ if (info.changes === 0) return { ok: false, skipped: "duplicate", score, category: cls.category };
309
+
310
+ // 顺手清掉过期候选;表很小,按 created_at 删不会影响索引。
311
+ store.db
312
+ .prepare("DELETE FROM emotion_candidate WHERE created_at < ?")
313
+ .run(now - (Number(cfg.emotionRetentionDays) || CANDIDATE_RETENTION_DAYS) * 24 * 60 * 60 * 1000);
314
+
315
+ return { ok: true, id: Number(info.lastInsertRowid), score, category: cls.category, day };
316
+ });
317
+ } catch (err) {
318
+ return { ok: false, error: err?.message ? String(err.message) : String(err) };
319
+ }
320
+ }
321
+
322
+ function candidateRow(r) {
323
+ let reasons = [];
324
+ try {
325
+ reasons = JSON.parse(String(r.reasons ?? "[]"));
326
+ } catch {
327
+ reasons = [];
328
+ }
329
+ return {
330
+ id: Number(r.id),
331
+ day: String(r.day ?? ""),
332
+ ts: Number(r.ts ?? 0),
333
+ sessionId: String(r.session_id ?? ""),
334
+ cwd: String(r.cwd ?? ""),
335
+ role: String(r.role ?? ""),
336
+ category: String(r.category ?? ""),
337
+ score: Number(r.score ?? 0),
338
+ reasons,
339
+ text: String(r.text ?? ""),
340
+ context: String(r.context ?? ""),
341
+ status: String(r.status ?? "pending"),
342
+ nodeId: r.node_id === null || r.node_id === undefined ? null : Number(r.node_id),
343
+ };
344
+ }
345
+
346
+ export function listCandidates(db, { day, status = "pending", limit = 20 } = {}) {
347
+ const d = String(day || localDate());
348
+ const s = String(status || "pending");
349
+ const lim = Math.max(1, Math.min(50, Number(limit) || 20));
350
+ const rows = db
351
+ .prepare(
352
+ `SELECT * FROM emotion_candidate
353
+ WHERE day=? AND (?='all' OR status=?)
354
+ ORDER BY score DESC, id ASC LIMIT ?`,
355
+ )
356
+ .all(d, s, s, lim);
357
+ return rows.map(candidateRow);
358
+ }
359
+
360
+ export function markCandidates(db, ids, status, nodeIds = []) {
361
+ const want = String(status);
362
+ if (want !== "accepted" && want !== "dismissed") {
363
+ throw new Error("status 只能是 accepted / dismissed");
364
+ }
365
+ const list = (Array.isArray(ids) ? ids : []).map((x) => Number(x)).filter((x) => Number.isFinite(x));
366
+ if (list.length === 0) return { updated: 0, missing: [], status: want };
367
+ const nodeList = (Array.isArray(nodeIds) ? nodeIds : []).map((x) => Number(x));
368
+ return tx(db, () => {
369
+ let updated = 0;
370
+ const missing = [];
371
+ const stmt = db.prepare("UPDATE emotion_candidate SET status=?, node_id=?, updated_at=? WHERE id=?");
372
+ list.forEach((id, i) => {
373
+ const nodeId = want === "accepted" && Number.isFinite(nodeList[i]) ? nodeList[i] : null;
374
+ const info = stmt.run(want, nodeId, Date.now(), id);
375
+ if (info.changes) updated += 1;
376
+ else missing.push(id);
377
+ });
378
+ return { updated, missing, status: want };
379
+ });
380
+ }
381
+
382
+ export function candidateStats(db, day = localDate()) {
383
+ const d = String(day || localDate());
384
+ const rows = db
385
+ .prepare("SELECT category, status, COUNT(*) AS n FROM emotion_candidate WHERE day=? GROUP BY category, status")
386
+ .all(d);
387
+ const byCategory = {};
388
+ const byStatus = {};
389
+ let total = 0;
390
+ for (const r of rows) {
391
+ const n = Number(r.n) || 0;
392
+ total += n;
393
+ byCategory[r.category] = (byCategory[r.category] || 0) + n;
394
+ byStatus[r.status] = (byStatus[r.status] || 0) + n;
395
+ }
396
+ const weekStart = localDate(Date.now() - 6 * 24 * 60 * 60 * 1000);
397
+ const week = db
398
+ .prepare("SELECT COUNT(*) AS n FROM emotion_candidate WHERE day>=?")
399
+ .get(weekStart).n;
400
+ return { day: d, total, byCategory, byStatus, weekStart, week: Number(week) || 0 };
401
+ }
402
+
403
+ export function sessionIdOf(exec) {
404
+ try {
405
+ return String(exec?.agent?.session?.id ?? exec?.agent?.id ?? "");
406
+ } catch {
407
+ return "";
408
+ }
409
+ }
410
+
411
+ /** 读 cost-meter 账本:今日总花费、本会话花费、今日日结累计、上限、是否超。 */
412
+ export function budgetFor(runtime, exec = {}) {
413
+ const day = localDate();
414
+ const cap = Number(runtime?.config?.emotionReviewCostCapCny ?? 0.3);
415
+ const file = path.join(String(runtime?.paths?.home ?? ""), "storages", "cost-meter", "ledger.json");
416
+ let ledger = null;
417
+ try {
418
+ ledger = JSON.parse(fs.readFileSync(file, "utf8"));
419
+ } catch {
420
+ ledger = null;
421
+ }
422
+ const sid = sessionIdOf(exec);
423
+ let todayTotal = 0;
424
+ let sessionCost = 0;
425
+ const dayRow = ledger?.days?.[day];
426
+ if (dayRow) {
427
+ todayTotal = Number(dayRow.costCny) || 0;
428
+ for (const s of Array.isArray(dayRow.sessions) ? dayRow.sessions : []) {
429
+ if (sid && String(s?.id ?? "") === sid) sessionCost += Number(s?.costCny) || 0;
430
+ }
431
+ }
432
+ let reviewSpent = 0;
433
+ try {
434
+ reviewSpent = Number(
435
+ runtime.open().db.prepare("SELECT COALESCE(SUM(cost_cny),0) AS n FROM emotion_review WHERE day=?").get(day).n,
436
+ ) || 0;
437
+ } catch {
438
+ reviewSpent = 0;
439
+ }
440
+ return {
441
+ ok: true,
442
+ day,
443
+ capCny: cap,
444
+ todayTotalCny: round4(todayTotal),
445
+ sessionCostCny: round4(sessionCost),
446
+ reviewSpentCny: round4(reviewSpent),
447
+ over: sessionCost + reviewSpent > cap + 1e-9,
448
+ ledger: Boolean(ledger),
449
+ };
450
+ }
451
+
452
+ export function recordReview(db, input = {}) {
453
+ const day = String(input.day || localDate());
454
+ const now = Date.now();
455
+ const info = db
456
+ .prepare(
457
+ `INSERT INTO emotion_review
458
+ (day, session_id, candidates, written, dismissed, cost_cny, tokens, status, note, created_at)
459
+ VALUES (?,?,?,?,?,?,?,?,?,?)`,
460
+ )
461
+ .run(
462
+ day,
463
+ String(input.sessionId ?? ""),
464
+ Number(input.candidates) || 0,
465
+ Number(input.written) || 0,
466
+ Number(input.dismissed) || 0,
467
+ Number(input.costCny) || 0,
468
+ Number(input.tokens) || 0,
469
+ String(input.status ?? "done"),
470
+ String(input.note ?? ""),
471
+ now,
472
+ );
473
+ return { id: Number(info.lastInsertRowid), day };
474
+ }
@@ -0,0 +1,167 @@
1
+ // lib/import-legacy.mjs — 把旧 Python 版 memories.db 的记忆条目迁进新库(幂等、可重跑)。
2
+ //
3
+ // 旧库里除了四枝还混着旧插件遗留的人设/梗/词条等表;这里只搬「记忆条目」这一件事:
4
+ // memory.layer='task' → task 卡(subject 保留)
5
+ // memory.layer='misc' 且 tags 含 情感枝/relationship → emotion
6
+ // memory.layer='misc' 且 tags 含 任务枝 → task
7
+ // memory.layer='misc' 且 tags 含 主干候选/judge-trunk → trunk 候选(status=candidate,等主人点头)
8
+ // 其余 misc → leaf(待分拣)
9
+ // 每条都带 source=legacy:memories.db#<id> 与逐字 evidence,便于回查。
10
+ import fs from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { DatabaseSync } from "node:sqlite";
14
+ import { checksum } from "./text.mjs";
15
+ import { tx } from "./db.mjs";
16
+
17
+ function toMs(v) {
18
+ const n = Number(v);
19
+ if (!Number.isFinite(n) || n <= 0) return 0;
20
+ return n < 1e12 ? Math.trunc(n * 1000) : Math.trunc(n);
21
+ }
22
+
23
+ function parseTags(v) {
24
+ if (Array.isArray(v)) return v.map(String);
25
+ try {
26
+ const a = JSON.parse(v ?? "[]");
27
+ return Array.isArray(a) ? a.map(String) : [];
28
+ } catch {
29
+ return [];
30
+ }
31
+ }
32
+
33
+ function classify(row) {
34
+ const tags = parseTags(row.tags);
35
+ const layer = String(row.layer ?? "misc");
36
+ if (layer === "task") return { layer: "task", status: "active", tags, importance: 0.8, trust: 90 };
37
+ const has = (s) => tags.some((t) => t.includes(s));
38
+ if (has("情感枝") || has("relationship")) return { layer: "emotion", status: "active", tags, importance: 0.7, trust: 85 };
39
+ if (has("任务枝")) return { layer: "task", status: "active", tags, importance: 0.75, trust: 85 };
40
+ if (has("主干候选") || has("judge-trunk") || has("judge_trunk")) {
41
+ return { layer: "trunk", status: "candidate", tags: Array.from(new Set([...tags, "主干候选"])), importance: 0.85, trust: 80 };
42
+ }
43
+ return { layer: "leaf", status: "active", tags, importance: 0.4, trust: 60 };
44
+ }
45
+
46
+ function openLegacy(file) {
47
+ try {
48
+ return { db: new DatabaseSync(file, { readOnly: true }), temp: null };
49
+ } catch (err) {
50
+ // 旧服务可能正占着文件:复制一份再读(只读迁移,不动原库)。
51
+ const temp = path.join(os.tmpdir(), "mt-legacy-" + checksum(file + ":" + Date.now()) + ".db");
52
+ fs.copyFileSync(file, temp);
53
+ return { db: new DatabaseSync(temp, { readOnly: true }), temp };
54
+ }
55
+ }
56
+
57
+ export function importLegacy(store, legacyFile, opts = {}) {
58
+ if (!legacyFile || !fs.existsSync(legacyFile)) {
59
+ return { ok: false, reason: "找不到旧库文件:" + String(legacyFile), added: 0 };
60
+ }
61
+ const scope = opts.scope ?? "user";
62
+ const dryRun = opts.dryRun === true;
63
+ let opened;
64
+ try {
65
+ opened = openLegacy(legacyFile);
66
+ } catch (err) {
67
+ return { ok: false, reason: "打不开旧库:" + (err && err.message ? err.message : String(err)), added: 0 };
68
+ }
69
+ const db = opened.db;
70
+ try {
71
+ const tables = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map((r) => String(r.name)));
72
+ if (!tables.has("memory")) return { ok: false, reason: "旧库里没有 memory 表,可能不是记忆树库", added: 0, tables: [...tables] };
73
+
74
+ const cols = new Set(db.prepare("PRAGMA table_info(memory)").all().map((r) => String(r.name)));
75
+ const rows = db.prepare("SELECT * FROM memory ORDER BY id").all();
76
+ const byLayer = {};
77
+ const skipped = [];
78
+ let added = 0;
79
+ let duplicate = 0;
80
+
81
+ const processRows = () => {
82
+ for (const row of rows) {
83
+ const text = String(row.text ?? "").trim();
84
+ if (text === "") {
85
+ skipped.push({ id: Number(row.id), reason: "空文本" });
86
+ continue;
87
+ }
88
+ const c = classify(row);
89
+ const legacyTags = c.tags;
90
+ const uid = "legacy:" + Number(row.id);
91
+ if (store.get(uid)) {
92
+ duplicate += 1;
93
+ continue;
94
+ }
95
+ const subject = String(row.subject ?? "").trim();
96
+ if (dryRun) {
97
+ added += 1;
98
+ byLayer[c.layer] = (byLayer[c.layer] ?? 0) + 1;
99
+ continue;
100
+ }
101
+ const res = store.add({
102
+ uid,
103
+ scope,
104
+ layer: c.layer,
105
+ kind: c.layer === "task" ? "card" : c.layer === "trunk" ? "rule" : "note",
106
+ status: c.status,
107
+ subject,
108
+ title: subject || String(row.summary ?? "").slice(0, 40) || text.slice(0, 40),
109
+ text,
110
+ summary: row.summary ? String(row.summary) : null,
111
+ tags: legacyTags,
112
+ source: "legacy:memories.db#" + Number(row.id),
113
+ evidence: text,
114
+ trust: c.trust,
115
+ importance: c.importance,
116
+ halfLifeDays: cols.has("half_life_days") ? Number(row.half_life_days ?? 0) || 0 : Number(opts.defaultHalfLifeDays ?? 0),
117
+ ts: toMs(row.ts) || undefined,
118
+ });
119
+ if (res.duplicate) duplicate += 1;
120
+ else added += 1;
121
+ byLayer[c.layer] = (byLayer[c.layer] ?? 0) + 1;
122
+ }
123
+ };
124
+ // 非 dryRun 的整批迁移放进一个事务:中途失败不留半批数据。
125
+ if (dryRun) processRows();
126
+ else tx(store.db, processRows);
127
+
128
+ // 旧库里的 diary/emotion_log 是日记与旧情绪日志:日记按 §2-4 只是索引,默认不搬。
129
+ const hasDiary = tables.has("diary");
130
+ const otherTables = [...tables].filter((t) => !["memory", "meta"].includes(t));
131
+ if (!dryRun) {
132
+ store.audit("migrate", {
133
+ scope,
134
+ query: legacyFile,
135
+ hits: added,
136
+ detail: { total: rows.length, added, duplicate, skipped: skipped.length, byLayer, dryRun },
137
+ });
138
+ }
139
+ return {
140
+ ok: true,
141
+ dryRun,
142
+ source: legacyFile,
143
+ total: rows.length,
144
+ added,
145
+ duplicate,
146
+ skipped,
147
+ byLayer,
148
+ ignoredTables: otherTables,
149
+ note: hasDiary ? "旧库的 diary 表按「日记只是索引」的规则未搬入;需要时用 memory_admin action=import 手工导入导出文件。" : undefined,
150
+ };
151
+ } catch (err) {
152
+ return { ok: false, reason: "迁移失败:" + (err && err.message ? err.message : String(err)), added: 0 };
153
+ } finally {
154
+ try {
155
+ db.close();
156
+ } catch {
157
+ /* 忽略 */
158
+ }
159
+ if (opened.temp) {
160
+ try {
161
+ fs.rmSync(opened.temp, { force: true });
162
+ } catch {
163
+ /* 忽略 */
164
+ }
165
+ }
166
+ }
167
+ }