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/store.mjs ADDED
@@ -0,0 +1,1334 @@
1
+ // lib/store.mjs — 记忆树的读写核心。
2
+ //
3
+ // 四枝映射(主干 / 情感枝 / 任务枝 / 判断叶):
4
+ // trunk 主干:AGENTS.md 的索引副本(只读派生;正本是文件)
5
+ // emotion 情感枝:相处情感/关系记录
6
+ // task 任务枝:插件/脚本/常驻服务的做法卡(一个 subject 一张卡)
7
+ // leaf 判断叶:会话里临时收集的规则解析、观察,待每日分拣
8
+ //
9
+ // 生命周期:active / candidate / superseded / archived。
10
+ // 遗忘默认是 archived(可恢复),hard 删除必须显式传入,且受 tools 层拦截。
11
+ import { tx, bumpIndexVersion, getMeta, setMeta } from "./db.mjs";
12
+ import { randomUUID } from "node:crypto";
13
+ import { LAYERS, STATUSES } from "./schema.mjs";
14
+ import { checksum, redact as redactText, stableStringify, truncate } from "./text.mjs";
15
+ import { embed, pack, cosine, unpack, VEC_DIM, VEC_KIND } from "./vector.mjs";
16
+ import { localDate, isDateString, dayRange, buildDiaryText } from "./diary.mjs";
17
+
18
+ function boundedTags(v) {
19
+ // 标签只用于检索分面,必须有界:最多 32 个、每个 50 字。
20
+ return Array.from(new Set(parseTags(v))).slice(0, 32).map((t) => truncate(t, 50));
21
+ }
22
+
23
+ function nowMs() {
24
+ return Date.now();
25
+ }
26
+
27
+ function parseTags(v) {
28
+ if (Array.isArray(v)) return v.map((x) => String(x).trim()).filter(Boolean);
29
+ if (v === null || v === undefined || v === "") return [];
30
+ const s = String(v).trim();
31
+ if (!s) return [];
32
+ try {
33
+ const a = JSON.parse(s);
34
+ if (Array.isArray(a)) return a.map((x) => String(x).trim()).filter(Boolean);
35
+ } catch {
36
+ /* 不是 JSON,按分隔符切 */
37
+ }
38
+ return s.split(/[,,、;;\s]+/).map((x) => x.trim()).filter(Boolean);
39
+ }
40
+
41
+ function asInt(v, fallback = null) {
42
+ if (v === null || v === undefined || v === "") return fallback;
43
+ const n = Number(v);
44
+ return Number.isFinite(n) ? Math.trunc(n) : fallback;
45
+ }
46
+
47
+ const TEXT_MAX = 20000;
48
+ const EVIDENCE_MAX = 20000;
49
+
50
+ // 以前是静默 slice,用户以为写进去了、其实后半段丢了。宁可报错让调用方拆分。
51
+ function boundedText(value, max, label) {
52
+ const t = String(value ?? "").trim();
53
+ if (t.length > max) {
54
+ throw new Error(label + " 超过 " + max + " 字上限(当前 " + t.length + " 字),请拆分后再写");
55
+ }
56
+ return t;
57
+ }
58
+
59
+ function escapeLike(s) {
60
+ return String(s).replace(/[\\%_]/g, (c) => "\\" + c);
61
+ }
62
+
63
+ function scopesOf(value) {
64
+ if (value === undefined || value === null) return null;
65
+ return Array.isArray(value) ? value.map(String) : [String(value)];
66
+ }
67
+
68
+ function placementRow(r) {
69
+ return {
70
+ id: String(r.id),
71
+ nodeId: r.node_id === null || r.node_id === undefined ? null : Number(r.node_id),
72
+ text: String(r.text ?? ""),
73
+ title: String(r.title ?? ""),
74
+ scope: String(r.scope ?? "user"),
75
+ kind: String(r.kind ?? "task"),
76
+ status: String(r.status ?? "pending"),
77
+ recommendedSubject: String(r.recommended_subject ?? ""),
78
+ recommendedTitle: String(r.recommended_title ?? ""),
79
+ recommendedGroup: String(r.recommended_group ?? ""),
80
+ reason: String(r.reason ?? ""),
81
+ sessionId: String(r.session_id ?? ""),
82
+ createdAt: Number(r.created_at ?? 0),
83
+ updatedAt: Number(r.updated_at ?? 0),
84
+ };
85
+ }
86
+
87
+ function patchRow(r) {
88
+ return {
89
+ id: String(r.id),
90
+ nodeId: r.node_id === null || r.node_id === undefined ? null : Number(r.node_id),
91
+ uid: String(r.uid ?? ""),
92
+ title: String(r.title ?? ""),
93
+ oldNum: String(r.old_num ?? ""),
94
+ newNum: String(r.new_num ?? ""),
95
+ oldText: String(r.old_text ?? ""),
96
+ newText: String(r.new_text ?? ""),
97
+ kind: String(r.kind ?? "text"),
98
+ baseChecksum: String(r.base_checksum ?? ""),
99
+ status: String(r.status ?? "pending"),
100
+ batchId: r.batch_id === null || r.batch_id === undefined ? null : String(r.batch_id),
101
+ createdAt: Number(r.created_at ?? 0),
102
+ updatedAt: Number(r.updated_at ?? 0),
103
+ };
104
+ }
105
+
106
+ function batchRow(r) {
107
+ return {
108
+ id: String(r.id),
109
+ status: String(r.status ?? "applied"),
110
+ baseChecksum: String(r.base_checksum ?? ""),
111
+ planJson: r.plan_json === null || r.plan_json === undefined ? null : String(r.plan_json),
112
+ backup: r.backup === null || r.backup === undefined ? null : String(r.backup),
113
+ rules: Number(r.rules ?? 0),
114
+ refs: Number(r.refs ?? 0),
115
+ error: r.error === null || r.error === undefined ? null : String(r.error),
116
+ createdAt: Number(r.created_at ?? 0),
117
+ appliedAt: r.applied_at === null || r.applied_at === undefined ? null : Number(r.applied_at),
118
+ };
119
+ }
120
+
121
+ export function rowToNode(r) { if (!r) return null;
122
+ return {
123
+ id: Number(r.id),
124
+ uid: String(r.uid),
125
+ scope: String(r.scope),
126
+ layer: String(r.layer),
127
+ kind: String(r.kind),
128
+ status: String(r.status),
129
+ subject: String(r.subject ?? ""),
130
+ title: String(r.title ?? ""),
131
+ text: String(r.text ?? ""),
132
+ summary: r.summary === null || r.summary === undefined ? null : String(r.summary),
133
+ tags: parseTags(r.tags),
134
+ source: String(r.source ?? ""),
135
+ evidence: r.evidence === null || r.evidence === undefined ? null : String(r.evidence),
136
+ trust: Number(r.trust ?? 70),
137
+ importance: Number(r.importance ?? 0.5),
138
+ halfLifeDays: Number(r.half_life_days ?? 0),
139
+ validUntil: r.valid_until === null || r.valid_until === undefined ? null : Number(r.valid_until),
140
+ supersededBy: r.superseded_by === null || r.superseded_by === undefined ? null : Number(r.superseded_by),
141
+ checksum: String(r.checksum ?? ""),
142
+ len: Number(r.len ?? 0),
143
+ ts: Number(r.ts ?? 0),
144
+ createdAt: Number(r.created_at ?? 0),
145
+ updatedAt: Number(r.updated_at ?? 0),
146
+ };
147
+ }
148
+
149
+ /** 把文本切成词项(存储 tf)。与检索用的是同一个分词器。 */
150
+ function termRows(text) {
151
+ const toks = tokenizeInto(text);
152
+ return Array.from(toks.entries());
153
+ }
154
+
155
+ import { tokenize } from "./text.mjs";
156
+ function tokenizeInto(text) {
157
+ return tokenize(text);
158
+ }
159
+
160
+ export class MemoryStore {
161
+ constructor(db, opts = {}) {
162
+ this.db = db;
163
+ this.clock = typeof opts.clock === "function" ? opts.clock : nowMs;
164
+ this.redactEnabled = opts.redact !== false;
165
+ this.events = [];
166
+ }
167
+
168
+ now() {
169
+ return this.clock();
170
+ }
171
+
172
+ emit(event, payload) {
173
+ if (this.events.length > 200) this.events.shift();
174
+ this.events.push({ at: this.now(), event, payload });
175
+ }
176
+
177
+ // ── 读 ─────────────────────────────────────────────────────────────
178
+ /**
179
+ * 按 id/uid 取一条。opts.scope(字符串或数组)用于限制可见作用域;
180
+ * 不传则是内部全局取(同步主干、看板管理员操作)。
181
+ */
182
+ get(ref, opts = {}) {
183
+ let row;
184
+ if (typeof ref === "number" || /^\d+$/.test(String(ref))) {
185
+ row = this.db.prepare("SELECT * FROM node WHERE id=?").get(asInt(ref));
186
+ } else {
187
+ row = this.db.prepare("SELECT * FROM node WHERE uid=?").get(String(ref));
188
+ }
189
+ const node = rowToNode(row);
190
+ if (!node) return null;
191
+ const allowed = scopesOf(opts.scope);
192
+ if (allowed && !allowed.includes(node.scope)) return null;
193
+ return node;
194
+ }
195
+
196
+ // ── 主干大标题(看板折叠分组;只存覆盖,不改 AGENTS.md)────────────
197
+ trunkBuckets() {
198
+ const out = Object.create(null);
199
+ for (const r of this.db.prepare("SELECT uid,bucket FROM trunk_bucket ORDER BY updated_at, uid").all()) {
200
+ out[String(r.uid)] = String(r.bucket);
201
+ }
202
+ return out;
203
+ }
204
+
205
+ setTrunkBucket(uid, bucket) {
206
+ const u = String(uid || "").trim();
207
+ const b = String(bucket || "").trim();
208
+ if (!u) throw new Error("缺少主干规则编号");
209
+ if (!/^trunk:§1-\d+-\d+$/.test(u)) throw new Error("主干规则编号格式应为 trunk:§1-x-x:" + u);
210
+ if (u.length > 200) throw new Error("主干规则编号超过 200 字上限");
211
+ if (!b) throw new Error("大标题不能为空");
212
+ if (b.length > 60) throw new Error("大标题超过 60 字上限");
213
+ this.db
214
+ .prepare(
215
+ "INSERT INTO trunk_bucket(uid,bucket,updated_at) VALUES(?,?,?) ON CONFLICT(uid) DO UPDATE SET bucket=excluded.bucket, updated_at=excluded.updated_at",
216
+ )
217
+ .run(u, b, this.now());
218
+ this.emit("trunk_bucket", { uid: u, bucket: b });
219
+ return { uid: u, bucket: b };
220
+ }
221
+
222
+ clearTrunkBucket(uid) {
223
+ const u = String(uid || "").trim();
224
+ if (!u) throw new Error("缺少主干规则编号");
225
+ const info = this.db.prepare("DELETE FROM trunk_bucket WHERE uid=?").run(u);
226
+ return { uid: u, removed: Number(info.changes) > 0 };
227
+ }
228
+
229
+ list(filter = {}) {
230
+ const where = [];
231
+ const params = [];
232
+ if (filter.scope !== undefined) {
233
+ const scopes = Array.isArray(filter.scope) ? filter.scope : [filter.scope];
234
+ if (scopes.length === 0) return [];
235
+ where.push("scope IN (" + scopes.map(() => "?").join(",") + ")");
236
+ params.push(...scopes);
237
+ }
238
+ if (filter.layers !== undefined) {
239
+ const layers = Array.isArray(filter.layers) ? filter.layers : [filter.layers];
240
+ if (layers.length === 0) return [];
241
+ where.push("layer IN (" + layers.map(() => "?").join(",") + ")");
242
+ params.push(...layers);
243
+ }
244
+ if (filter.status !== undefined) {
245
+ const sts = Array.isArray(filter.status) ? filter.status : [filter.status];
246
+ if (sts.length === 0) return [];
247
+ where.push("status IN (" + sts.map(() => "?").join(",") + ")");
248
+ params.push(...sts);
249
+ }
250
+ if (filter.subject !== undefined) {
251
+ where.push("subject = ?");
252
+ params.push(String(filter.subject));
253
+ }
254
+ if (filter.kind !== undefined) {
255
+ where.push("kind = ?");
256
+ params.push(String(filter.kind));
257
+ }
258
+ if (filter.tag !== undefined) {
259
+ where.push("tags LIKE ? ESCAPE '\\'");
260
+ params.push('%"' + escapeLike(filter.tag) + '"%');
261
+ }
262
+ if (filter.since !== undefined) {
263
+ where.push("updated_at >= ?");
264
+ params.push(asInt(filter.since, 0));
265
+ }
266
+ const limit = Math.min(Math.max(asInt(filter.limit, 100), 1), 5000);
267
+ const offset = Math.max(asInt(filter.offset, 0), 0);
268
+ const order = filter.order === "created" ? "created_at" : filter.order === "importance" ? "importance DESC, updated_at" : "updated_at";
269
+ const sql =
270
+ "SELECT * FROM node" +
271
+ (where.length ? " WHERE " + where.join(" AND ") : "") +
272
+ " ORDER BY " + order + " DESC LIMIT ? OFFSET ?";
273
+ return this.db.prepare(sql).all(...params, limit, offset).map(rowToNode);
274
+ }
275
+
276
+ count(filter = {}) {
277
+ const where = [];
278
+ const params = [];
279
+ if (filter.scope !== undefined) {
280
+ const scopes = Array.isArray(filter.scope) ? filter.scope : [filter.scope];
281
+ if (scopes.length === 0) return 0;
282
+ where.push("scope IN (" + scopes.map(() => "?").join(",") + ")");
283
+ params.push(...scopes);
284
+ }
285
+ if (filter.layers !== undefined) {
286
+ const layers = Array.isArray(filter.layers) ? filter.layers : [filter.layers];
287
+ if (layers.length === 0) return 0;
288
+ where.push("layer IN (" + layers.map(() => "?").join(",") + ")");
289
+ params.push(...layers);
290
+ }
291
+ if (filter.status !== undefined) {
292
+ const sts = Array.isArray(filter.status) ? filter.status : [filter.status];
293
+ if (sts.length === 0) return 0;
294
+ where.push("status IN (" + sts.map(() => "?").join(",") + ")");
295
+ params.push(...sts);
296
+ }
297
+ if (filter.since !== undefined) {
298
+ where.push("updated_at >= ?");
299
+ params.push(asInt(filter.since, 0));
300
+ }
301
+ const sql = "SELECT COUNT(*) AS c FROM node" + (where.length ? " WHERE " + where.join(" AND ") : "");
302
+ return Number(this.db.prepare(sql).get(...params).c);
303
+ }
304
+
305
+ /** 库里出现过的全部作用域(user + 各 workspace),用于 scope=all 的全库检索。 */
306
+ scopes() {
307
+ return this.db
308
+ .prepare("SELECT DISTINCT scope FROM node WHERE scope IS NOT NULL AND scope <> '' ORDER BY scope")
309
+ .all()
310
+ .map((r) => String(r.scope));
311
+ }
312
+
313
+ /** 任务枝卡:同一 subject 只保留最新的一张 active 卡(旧卡会被 superseded)。 */
314
+ cards(scopes) {
315
+ const rows = this.list({ scope: scopes, layers: ["task"], status: "active", limit: 2000, order: "created" });
316
+ const seen = new Map();
317
+ // list 的 created 是升序;从尾部走,遇到历史遗留的同 subject 重复卡时保留最新那张。
318
+ for (let i = rows.length - 1; i >= 0; i -= 1) {
319
+ const n = rows[i];
320
+ const key = n.subject ? String(n.scope) + "\u0000" + String(n.subject) : "id:" + n.id;
321
+ if (!seen.has(key)) seen.set(key, n);
322
+ }
323
+ return Array.from(seen.values());
324
+ }
325
+
326
+ // ── 待写入位置请求(看板跨页面/刷新用)────────────────────────────
327
+ /**
328
+ * 记一条“这条规则要写入哪条枝/哪张卡”的请求。
329
+ * 页面只记 id;状态、DSH 建议都落在库里,切走/刷新后还能回来。
330
+ */
331
+ placementCreate(input = {}) {
332
+ const text = String(input.text ?? "").trim();
333
+ if (!text) throw new Error("placement.text 不能为空");
334
+ if (text.length > 20000) throw new Error("placement.text 超过 20000 字上限");
335
+ const id = String(input.id || randomUUID());
336
+ const now = this.now();
337
+ this.db
338
+ .prepare(
339
+ `INSERT INTO placement (id,node_id,text,title,scope,kind,status,recommended_subject,
340
+ recommended_title,recommended_group,reason,session_id,created_at,updated_at)
341
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
342
+ )
343
+ .run(
344
+ id,
345
+ input.nodeId === undefined || input.nodeId === null ? null : Number(input.nodeId),
346
+ text,
347
+ String(input.title ?? "").slice(0, 200),
348
+ String(input.scope ?? "user"),
349
+ String(input.kind ?? "task"),
350
+ String(input.status ?? "pending"),
351
+ String(input.recommendedSubject ?? ""),
352
+ String(input.recommendedTitle ?? ""),
353
+ String(input.recommendedGroup ?? ""),
354
+ String(input.reason ?? ""),
355
+ String(input.sessionId ?? ""),
356
+ now,
357
+ now,
358
+ );
359
+ this.revision("placement:create", null, null, { id, kind: String(input.kind ?? "task") });
360
+ return this.placementGet(id);
361
+ }
362
+
363
+ placementGet(id) {
364
+ const row = this.db.prepare("SELECT * FROM placement WHERE id=?").get(String(id));
365
+ return row ? placementRow(row) : null;
366
+ }
367
+
368
+ placementList(opts = {}) {
369
+ const status = opts.status ? String(opts.status) : "";
370
+ const limit = Math.min(200, Math.max(1, Number(opts.limit) || 50));
371
+ const rows = status
372
+ ? this.db.prepare("SELECT * FROM placement WHERE status=? ORDER BY updated_at DESC LIMIT ?").all(status, limit)
373
+ : this.db.prepare("SELECT * FROM placement ORDER BY updated_at DESC LIMIT ?").all(limit);
374
+ return rows.map(placementRow);
375
+ }
376
+
377
+ /** DSH 返回建议,或人工手动指定目标。 */
378
+ placementRecommend(id, patch = {}) {
379
+ const cur = this.placementGet(id);
380
+ if (!cur) throw new Error("找不到这条待写入请求:" + String(id));
381
+ if (cur.status === "confirmed" || cur.status === "cancelled") {
382
+ throw new Error("这条请求已经结束(" + cur.status + "),不能再改目标。");
383
+ }
384
+ const now = this.now();
385
+ this.db
386
+ .prepare(
387
+ `UPDATE placement SET status=?, recommended_subject=?, recommended_title=?,
388
+ recommended_group=?, reason=?, updated_at=? WHERE id=?`,
389
+ )
390
+ .run(
391
+ "recommended",
392
+ String(patch.subject ?? "").trim().slice(0, 200),
393
+ String(patch.title ?? "").trim().slice(0, 200),
394
+ String(patch.group ?? "").trim().slice(0, 200),
395
+ String(patch.reason ?? "").slice(0, 1000),
396
+ now,
397
+ String(id),
398
+ );
399
+ this.revision("placement:recommend", null, null, {
400
+ id: String(id),
401
+ subject: String(patch.subject ?? ""),
402
+ group: String(patch.group ?? ""),
403
+ });
404
+ return this.placementGet(id);
405
+ }
406
+
407
+ placementSetStatus(id, status) {
408
+ const cur = this.placementGet(id);
409
+ if (!cur) throw new Error("找不到这条待写入请求:" + String(id));
410
+ const allowed = ["pending", "recommended", "confirmed", "cancelled", "timeout"];
411
+ if (!allowed.includes(String(status))) throw new Error("未知 placement 状态:" + String(status));
412
+ this.db.prepare("UPDATE placement SET status=?, updated_at=? WHERE id=?").run(String(status), this.now(), String(id));
413
+ this.revision("placement:status", null, null, { id: String(id), from: cur.status, to: String(status) });
414
+ return this.placementGet(id);
415
+ }
416
+
417
+ /** 超过 maxAgeMs 仍未确认的请求标为 timeout;返回超时条数。 */
418
+ placementExpire(maxAgeMs = 10 * 60 * 1000) {
419
+ const cutoff = this.now() - Math.max(60 * 1000, Number(maxAgeMs) || 0);
420
+ const rows = this.db
421
+ .prepare("SELECT id FROM placement WHERE status IN ('pending','recommended') AND updated_at < ?")
422
+ .all(cutoff);
423
+ for (const row of rows) {
424
+ this.db.prepare("UPDATE placement SET status='timeout', updated_at=? WHERE id=?").run(this.now(), row.id);
425
+ }
426
+ return rows.length;
427
+ }
428
+
429
+ // ── 判断叶「待确定写入」补丁 ────────────────────────────────────────
430
+ /** 还没写入 AGENTS.md 的修改;同一规则同一时间只留一条。 */
431
+ pendingPatches() {
432
+ return this.db
433
+ .prepare("SELECT * FROM pending_patch WHERE status='pending' ORDER BY updated_at DESC")
434
+ .all()
435
+ .map(patchRow);
436
+ }
437
+
438
+ pendingPatchGet(id) {
439
+ const row = this.db.prepare("SELECT * FROM pending_patch WHERE id=?").get(String(id));
440
+ return row ? patchRow(row) : null;
441
+ }
442
+
443
+ pendingPatchStage(input = {}) {
444
+ const uid = String(input.uid ?? "").trim();
445
+ if (!uid) throw new Error("pending_patch.uid 不能为空");
446
+ const oldNum = String(input.oldNum ?? "").trim();
447
+ const newNum = String(input.newNum ?? "").trim();
448
+ if (!oldNum || !newNum) throw new Error("pending_patch 的旧号/新号不能为空");
449
+ const newText = String(input.newText ?? "").trim();
450
+ if (!newText) throw new Error("pending_patch.newText 不能为空");
451
+ if (newText.length > 20000) throw new Error("pending_patch.newText 超过 20000 字上限");
452
+ const id = randomUUID();
453
+ const now = this.now();
454
+ return tx(this.db, () => {
455
+ this.db.prepare("DELETE FROM pending_patch WHERE uid=? AND status='pending'").run(uid);
456
+ this.db
457
+ .prepare(
458
+ `INSERT INTO pending_patch (id,node_id,uid,title,old_num,new_num,old_text,new_text,kind,
459
+ base_checksum,status,batch_id,created_at,updated_at)
460
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
461
+ )
462
+ .run(
463
+ id,
464
+ input.nodeId === undefined || input.nodeId === null ? null : Number(input.nodeId),
465
+ uid,
466
+ String(input.title ?? "").slice(0, 200),
467
+ oldNum,
468
+ newNum,
469
+ String(input.oldText ?? ""),
470
+ newText,
471
+ String(input.kind ?? "text"),
472
+ String(input.baseChecksum ?? ""),
473
+ "pending",
474
+ null,
475
+ now,
476
+ now,
477
+ );
478
+ this.revision("patch:stage", input.nodeId ?? null, uid, { id, oldNum, newNum, kind: String(input.kind ?? "text") });
479
+ return patchRow(this.db.prepare("SELECT * FROM pending_patch WHERE id=?").get(id));
480
+ });
481
+ }
482
+
483
+ pendingPatchDelete(id) {
484
+ const info = this.db.prepare("DELETE FROM pending_patch WHERE id=? AND status='pending'").run(String(id));
485
+ const n = Number(info.changes ?? 0);
486
+ if (n > 0) this.revision("patch:delete", null, null, { id: String(id) });
487
+ return n;
488
+ }
489
+
490
+ pendingPatchMarkWritten(ids, batchId) {
491
+ const list = (ids || []).map((x) => String(x)).filter(Boolean);
492
+ if (list.length === 0) return 0;
493
+ const sql = "UPDATE pending_patch SET status='written', batch_id=?, updated_at=? WHERE id IN (" + list.map(() => "?").join(",") + ")";
494
+ const info = this.db.prepare(sql).run(String(batchId), this.now(), ...list);
495
+ this.revision("patch:written", null, null, { batchId: String(batchId), count: list.length });
496
+ return Number(info.changes ?? 0);
497
+ }
498
+
499
+ patchBatchCreate(input = {}) {
500
+ const id = String(input.id || randomUUID());
501
+ const now = this.now();
502
+ this.db
503
+ .prepare(
504
+ `INSERT INTO patch_batch (id,status,base_checksum,plan_json,backup,rules,refs,error,created_at,applied_at)
505
+ VALUES (?,?,?,?,?,?,?,?,?,?)`,
506
+ )
507
+ .run(
508
+ id,
509
+ String(input.status ?? "applied"),
510
+ String(input.baseChecksum ?? ""),
511
+ input.planJson === undefined || input.planJson === null ? null : String(input.planJson).slice(0, 12000),
512
+ input.backup === undefined || input.backup === null ? null : String(input.backup),
513
+ Number(input.rules ?? 0),
514
+ Number(input.refs ?? 0),
515
+ input.error === undefined || input.error === null ? null : String(input.error).slice(0, 1000),
516
+ now,
517
+ input.appliedAt === null ? null : input.appliedAt === undefined ? now : Number(input.appliedAt),
518
+ );
519
+ return this.patchBatchGet(id);
520
+ }
521
+
522
+ patchBatchGet(id) {
523
+ const row = this.db.prepare("SELECT * FROM patch_batch WHERE id=?").get(String(id));
524
+ return row ? batchRow(row) : null;
525
+ }
526
+
527
+ patchBatches(limit = 10) {
528
+ const n = Math.min(Math.max(asInt(limit, 10), 1), 100);
529
+ return this.db.prepare("SELECT * FROM patch_batch ORDER BY created_at DESC LIMIT ?").all(n).map(batchRow);
530
+ }
531
+
532
+ /** 把叶子标记为已被某条新条目取代(不删原文)。 */
533
+ linkSuperseded(id, byId, reason = "已分类") {
534
+ return tx(this.db, () => {
535
+ const cur = this.get(id);
536
+ if (!cur) throw new Error("找不到要归档的条目:" + String(id));
537
+ this.db
538
+ .prepare("UPDATE node SET status='superseded', superseded_by=?, updated_at=? WHERE id=?")
539
+ .run(Number(byId) || null, this.now(), cur.id);
540
+ this.revision("supersede", cur.id, cur.uid, { by: Number(byId) || null, reason });
541
+ bumpIndexVersion(this.db);
542
+ return this.get(cur.id);
543
+ });
544
+ }
545
+
546
+ /** 写入任务卡:同 subject 的 active 卡存在则追加,不存在则新建。 */
547
+ appendToTaskCard(input = {}) {
548
+ const subject = String(input.subject ?? "").trim();
549
+ if (!subject) throw new Error("任务卡 subject 不能为空");
550
+ const text = String(input.text ?? "").trim();
551
+ if (!text) throw new Error("任务卡正文不能为空");
552
+ const scope = String(input.scope ?? "user");
553
+ return tx(this.db, () => {
554
+ const existing = this.list({ scope, layers: ["task"], status: "active", subject, limit: 1, order: "created" })[0];
555
+ if (existing) {
556
+ const merged = String(existing.text || "").trim() + "\n\n" + text;
557
+ const updated = this.update(existing.id, {
558
+ text: merged,
559
+ title: input.title ? String(input.title).slice(0, 120) : existing.title,
560
+ importance: Math.max(Number(existing.importance) || 0, Number(input.importance) || 0),
561
+ source: input.source ? String(input.source) : existing.source,
562
+ });
563
+ return { node: updated, created: false };
564
+ }
565
+ const added = this.add({
566
+ layer: "task",
567
+ scope,
568
+ subject,
569
+ title: String(input.title || subject).slice(0, 120),
570
+ text,
571
+ tags: input.tags || ["任务枝", "看板归枝"],
572
+ source: String(input.source || "board:branch"),
573
+ importance: input.importance === undefined ? 0.75 : input.importance,
574
+ trust: input.trust === undefined ? 85 : input.trust,
575
+ });
576
+ return { node: added.node, created: true };
577
+ });
578
+ }
579
+
580
+ // ── 写 ─────────────────────────────────────────────────────────────
581
+ /**
582
+ * 新增一条记忆。
583
+ * input: {layer, text, subject?, title?, summary?, tags?, scope?, source?, evidence?,
584
+ * trust?, importance?, halfLifeDays?, validUntil?, ts?, uid?, status?, kind?}
585
+ */
586
+ add(input) {
587
+ const layer = String(input.layer ?? "leaf");
588
+ if (!LAYERS.includes(layer)) throw new Error("未知 layer:" + layer + "(可选 " + LAYERS.join("/") + ")");
589
+ let text = boundedText(input.text, TEXT_MAX, "text");
590
+ if (text === "") throw new Error("text 不能为空");
591
+
592
+ const redactions = [];
593
+ if (this.redactEnabled && this.redactEnabled !== "off" && input.skipRedact !== true) {
594
+ const r = redactText(text);
595
+ if (r.redactions.length > 0) {
596
+ text = r.text;
597
+ redactions.push(...r.redactions);
598
+ }
599
+ }
600
+
601
+ const scope = String(input.scope ?? "user").trim();
602
+ if (!scope) throw new Error("scope 不能为空(user 或 workspace:<hash>)");
603
+ if (scope.length > 200) throw new Error("scope 超过 200 字上限");
604
+ const subject = truncate(String(input.subject ?? "").trim(), 120);
605
+ const source = truncate(String(input.source ?? "manual"), 500);
606
+ // 主干正本在 AGENTS.md:只有从 AGENTS.md 同步来的才是 active,其余一律落成「候选」。
607
+ let status = String(input.status ?? "active");
608
+ if (layer === "trunk" && status === "active" && !source.startsWith("AGENTS.md")) status = "candidate";
609
+ if (!STATUSES.includes(status)) throw new Error("未知 status:" + status);
610
+
611
+ const tags = boundedTags(input.tags);
612
+ let evidence =
613
+ input.evidence === undefined || input.evidence === null ? null : boundedText(String(input.evidence), EVIDENCE_MAX, "evidence");
614
+ if (evidence !== null && this.redactEnabled && input.skipRedact !== true) {
615
+ const er = redactText(evidence);
616
+ evidence = er.text;
617
+ redactions.push(...er.redactions);
618
+ }
619
+ if (redactions.length > 0 && !tags.includes("已脱敏")) tags.push("已脱敏");
620
+ if (layer === "trunk" && status === "candidate" && !tags.includes("主干候选")) tags.push("主干候选");
621
+
622
+ const ts = asInt(input.ts, this.now()) ?? this.now();
623
+ const uid =
624
+ (input.uid !== undefined && String(input.uid).trim() !== "" ? String(input.uid).trim() : "") ||
625
+ layer + ":" + checksum(scope + "\u0000" + subject + "\u0000" + text);
626
+ if (uid.length > 200) throw new Error("uid 超过 200 字上限");
627
+ return tx(this.db, () => {
628
+ const existing = this.get(uid);
629
+ if (existing) {
630
+ this.emit("add:duplicate", { uid, id: existing.id });
631
+ return { node: existing, duplicate: true, redactions };
632
+ }
633
+
634
+ const now = this.now();
635
+ const checksumValue = checksum(text);
636
+ const rowTitle = truncate(String(input.title ?? "").trim(), 120);
637
+ const len = sumWeights((rowTitle ? rowTitle + "\n" : "") + text);
638
+ const createdAt = asInt(input.createdAt, now) ?? now;
639
+ const updatedAt = asInt(input.updatedAt, now) ?? now;
640
+ const row = {
641
+ uid,
642
+ scope,
643
+ layer,
644
+ kind: truncate(String(input.kind ?? (layer === "trunk" ? "rule" : layer === "task" ? "card" : "note")), 40),
645
+ status,
646
+ subject,
647
+ title: truncate(String(input.title ?? "").trim(), 120),
648
+ text,
649
+ summary: input.summary === undefined || input.summary === null ? null : truncate(String(input.summary), 500),
650
+ tags: JSON.stringify(tags),
651
+ source,
652
+ evidence,
653
+ trust: clampInt(input.trust, 0, 100, status === "candidate" ? 60 : 70),
654
+ importance: clampNum(input.importance, 0, 1, layer === "trunk" ? 0.85 : layer === "task" ? 0.75 : 0.4),
655
+ half_life_days: Math.max(0, Number(input.halfLifeDays ?? 0) || 0),
656
+ valid_until: normalizeWhen(input.validUntil),
657
+ checksum: checksumValue,
658
+ len,
659
+ ts,
660
+ created_at: createdAt,
661
+ updated_at: updatedAt,
662
+ };
663
+
664
+ const stmt = this.db.prepare(
665
+ `INSERT INTO node (uid,scope,layer,kind,status,subject,title,text,summary,tags,source,evidence,
666
+ trust,importance,half_life_days,valid_until,checksum,len,ts,created_at,updated_at)
667
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
668
+ );
669
+ const info = stmt.run(
670
+ row.uid, row.scope, row.layer, row.kind, row.status, row.subject, row.title, row.text, row.summary,
671
+ row.tags, row.source, row.evidence, row.trust, row.importance, row.half_life_days, row.valid_until,
672
+ row.checksum, row.len, row.ts, row.created_at, row.updated_at,
673
+ );
674
+ const id = Number(info.lastInsertRowid);
675
+ this.reindexNode(id, row.text, row.title);
676
+ // 一张任务卡只留一个 active:新卡落库后,同作用域同 subject 的旧卡转 superseded(不删,可追溯)。
677
+ if (row.layer === "task" && row.status === "active" && row.subject) {
678
+ const olds = this.list({ scope: row.scope, layers: ["task"], status: "active", subject: row.subject, limit: 1000 })
679
+ .filter((n) => n.id !== id);
680
+ for (const old of olds) {
681
+ this.db.prepare("UPDATE node SET status='superseded', superseded_by=?, updated_at=? WHERE id=?").run(id, now, old.id);
682
+ this.revision("supersede", old.id, old.uid, { by: id, auto: true });
683
+ }
684
+ }
685
+ bumpIndexVersion(this.db);
686
+ this.revision("add", id, row.uid, { layer: row.layer, scope: row.scope, redactions });
687
+ return { node: this.get(id), duplicate: false, redactions };
688
+ });
689
+ }
690
+
691
+ /** 修改一条记忆;uid 不变,便于引用。opts.allowActiveTrunk 只给 AGENTS.md 同步用。 */
692
+ update(ref, patch = {}, opts = {}) {
693
+ return tx(this.db, () => {
694
+ const cur = this.get(ref);
695
+ if (!cur) throw new Error("找不到要修改的记忆:" + String(ref));
696
+ // 主干 active 的正文/标题/状态只能由 AGENTS.md 同步改,避免库内文本与正本分叉。
697
+ if (
698
+ cur.layer === "trunk" &&
699
+ cur.status === "active" &&
700
+ opts.allowActiveTrunk !== true &&
701
+ (patch.text !== undefined || patch.title !== undefined || patch.subject !== undefined || patch.status !== undefined)
702
+ ) {
703
+ throw new Error("主干规则只能由 AGENTS.md 同步修改;请改正本后执行 memory_ingest action=sync");
704
+ }
705
+ const next = { ...cur };
706
+ if (patch.text !== undefined) {
707
+ let t = boundedText(patch.text, TEXT_MAX, "text");
708
+ if (t === "") throw new Error("text 不能为空");
709
+ const r = this.redactEnabled && opts.skipRedact !== true ? redactText(t) : { text: t, redactions: [] };
710
+ t = r.text;
711
+ next.text = t;
712
+ next.checksum = checksum(next.text);
713
+ if (r.redactions.length > 0 && !next.tags.includes("已脱敏")) next.tags.push("已脱敏");
714
+ }
715
+ if (patch.title !== undefined) next.title = truncate(String(patch.title).trim(), 120);
716
+ if (patch.text !== undefined || patch.title !== undefined) {
717
+ next.len = sumWeights((next.title ? next.title + "\n" : "") + next.text);
718
+ }
719
+ if (patch.subject !== undefined) next.subject = truncate(String(patch.subject).trim(), 120);
720
+ if (patch.summary !== undefined) next.summary = patch.summary === null ? null : truncate(String(patch.summary), 500);
721
+ if (patch.tags !== undefined) next.tags = boundedTags(patch.tags);
722
+ if (patch.trust !== undefined) next.trust = clampInt(patch.trust, 0, 100, next.trust);
723
+ if (patch.importance !== undefined) next.importance = clampNum(patch.importance, 0, 1, next.importance);
724
+ if (patch.halfLifeDays !== undefined) next.halfLifeDays = Math.max(0, Number(patch.halfLifeDays) || 0);
725
+ if (patch.validUntil !== undefined) next.validUntil = normalizeWhen(patch.validUntil);
726
+ if (patch.status !== undefined) {
727
+ if (!STATUSES.includes(String(patch.status))) throw new Error("未知 status:" + patch.status);
728
+ next.status = String(patch.status);
729
+ // 主干 index 只能由 AGENTS.md 同步激活;看板 set-trust / 导入不能把候选变成 active。
730
+ if (next.layer === "trunk" && next.status === "active" && cur.status !== "active" && opts.allowActiveTrunk !== true) {
731
+ throw new Error("主干规则只能由 AGENTS.md 同步激活,候选不能直接改成 active");
732
+ }
733
+ }
734
+ if (patch.evidence !== undefined) {
735
+ let ev = patch.evidence === null ? null : boundedText(patch.evidence, EVIDENCE_MAX, "evidence");
736
+ if (ev !== null && this.redactEnabled && opts.skipRedact !== true) {
737
+ const er = redactText(ev);
738
+ ev = er.text;
739
+ if (er.redactions.length > 0 && !next.tags.includes("已脱敏")) next.tags.push("已脱敏");
740
+ }
741
+ next.evidence = ev;
742
+ }
743
+ if (patch.source !== undefined) next.source = truncate(String(patch.source), 500);
744
+
745
+ this.db.prepare(
746
+ `UPDATE node SET text=?, title=?, subject=?, summary=?, tags=?, trust=?, importance=?,
747
+ half_life_days=?, valid_until=?, status=?, evidence=?, source=?, checksum=?, len=?, updated_at=?
748
+ WHERE id=?`,
749
+ ).run(
750
+ next.text, next.title, next.subject, next.summary, JSON.stringify(next.tags), next.trust, next.importance,
751
+ next.halfLifeDays, next.validUntil, next.status, next.evidence, next.source, next.checksum, next.len,
752
+ this.now(), next.id,
753
+ );
754
+ this.reindexNode(next.id, next.text, next.title);
755
+ bumpIndexVersion(this.db);
756
+ this.revision("update", next.id, next.uid, { before: cur.checksum, after: next.checksum });
757
+ return this.get(next.id);
758
+ });
759
+ }
760
+
761
+ /**
762
+ * 用一条新记忆取代若干旧条目(合并/改口径的正确做法:旧的不删,标 superseded)。
763
+ * 返回 {node, superseded:[ids]}
764
+ */
765
+ supersede(refs, input, opts = {}) {
766
+ const targetScope = String(input?.scope ?? "user");
767
+ return tx(this.db, () => {
768
+ const all = refs.map((r) => this.get(r));
769
+ const missing = refs.filter((r, i) => !all[i]);
770
+ if (all.filter(Boolean).length === 0) throw new Error("要取代的条目一条都不存在");
771
+ if (missing.length) throw new Error("要取代的条目不存在:" + missing.join("、"));
772
+ const allowed = opts.scopes == null ? null : new Set(Array.isArray(opts.scopes) ? opts.scopes : [opts.scopes]);
773
+ const wrong =
774
+ opts.allowCrossScope === true
775
+ ? []
776
+ : all.filter((n) => n.scope !== targetScope && !(allowed && allowed.has(n.scope)));
777
+ if (wrong.length) {
778
+ throw new Error(
779
+ "不能跨作用域取代:#" + wrong.map((n) => n.id + "(" + n.scope + ")").join("、") + ",新条目作用域是 " + targetScope,
780
+ );
781
+ }
782
+ const activeTrunk = all.filter((n) => n.layer === "trunk" && n.status === "active");
783
+ if (activeTrunk.length && opts.allowActiveTrunk !== true) {
784
+ throw new Error("不能取代 active 主干规则;请改 AGENTS.md 后同步");
785
+ }
786
+ const olds = all;
787
+ let created = this.add(input).node;
788
+ // 同文旧条目可能已被取代/归档;取代动作的本意是让这条内容重新成为当前版本。
789
+ if (created.status !== "active" && created.layer !== "trunk") {
790
+ created = this.update(created.id, { status: "active" });
791
+ }
792
+ for (const o of olds) {
793
+ if (o.id === created.id) continue;
794
+ this.db
795
+ .prepare("UPDATE node SET status='superseded', superseded_by=?, updated_at=? WHERE id=?")
796
+ .run(created.id, this.now(), o.id);
797
+ this.revision("supersede", o.id, o.uid, { by: created.id });
798
+ }
799
+ bumpIndexVersion(this.db);
800
+ return { node: created, superseded: olds.filter((o) => o.id !== created.id).map((o) => o.id) };
801
+ });
802
+ }
803
+
804
+ /** 遗忘:默认归档(可恢复);hard=true 才物理删除。 */
805
+ forget(ref, opts = {}) {
806
+ return tx(this.db, () => {
807
+ const cur = this.get(ref);
808
+ if (!cur) throw new Error("找不到要遗忘的记忆:" + String(ref));
809
+ if (cur.layer === "trunk" && cur.status === "active" && opts.allowActiveTrunk !== true) {
810
+ throw new Error("不能直接遗忘 active 主干规则;请先从 AGENTS.md 删除再同步");
811
+ }
812
+ if (opts.hard === true) {
813
+ this.db.prepare("DELETE FROM term WHERE node_id=?").run(cur.id);
814
+ this.db.prepare("DELETE FROM vec WHERE node_id=?").run(cur.id);
815
+ this.db.prepare("DELETE FROM placement WHERE node_id=?").run(cur.id);
816
+ this.db.prepare("DELETE FROM pending_patch WHERE node_id=? OR uid=?").run(cur.id, cur.uid);
817
+ this.db.prepare("DELETE FROM trunk_bucket WHERE uid=?").run(cur.uid);
818
+ this.db.prepare("UPDATE node SET superseded_by=NULL WHERE superseded_by=?").run(cur.id);
819
+ this.db.prepare("DELETE FROM node WHERE id=?").run(cur.id);
820
+ this.revision("forget:hard", null, cur.uid, { id: cur.id, reason: opts.reason ?? "" });
821
+ } else {
822
+ this.db.prepare("UPDATE node SET status='archived', updated_at=? WHERE id=?").run(this.now(), cur.id);
823
+ if (cur.layer === "trunk") {
824
+ // 归档的主干候选不再出现在看板,对应的大标题覆盖也应一起清掉。
825
+ this.db.prepare("DELETE FROM trunk_bucket WHERE uid=?").run(cur.uid);
826
+ }
827
+ this.revision("forget:archive", cur.id, cur.uid, { reason: opts.reason ?? "" });
828
+ }
829
+ bumpIndexVersion(this.db);
830
+ return { id: cur.id, uid: cur.uid, hard: opts.hard === true };
831
+ });
832
+ }
833
+
834
+ /** 把任务枝同 subject 的旧 active 卡降级,保证一张卡只有一个 active 版本。 */
835
+ replaceCard(subject, input) {
836
+ return tx(this.db, () => {
837
+ const scope = String(input.scope ?? "user");
838
+ const rows = this.list({ scope, layers: ["task"], status: "active", subject, limit: 1000, order: "created" });
839
+ // subject 由方法参数决定:调用方即使忘了在 input 里带 subject,也不能建出无主题的卡。
840
+ const added = this.add({ ...input, scope, subject });
841
+ let created = added.node;
842
+ if (added.duplicate) {
843
+ // 正文没变但标题/标签/重要度可能变了:任务卡仍应刷新这些元数据。
844
+ // 若命中的是历史遗留的 superseded/archived 同文卡,恢复为 active,否则新卡“写入成功”却不可见。
845
+ const revive = created.status !== "active";
846
+ created = this.update(created.id, {
847
+ title: input.title,
848
+ tags: input.tags,
849
+ importance: input.importance,
850
+ trust: input.trust,
851
+ status: revive ? "active" : undefined,
852
+ });
853
+ for (const r of rows) {
854
+ if (r.id === created.id) continue;
855
+ this.db.prepare("UPDATE node SET status='superseded', superseded_by=?, updated_at=? WHERE id=?").run(created.id, this.now(), r.id);
856
+ this.revision("replace-card", r.id, r.uid, { by: created.id });
857
+ }
858
+ if (rows.length > 0) bumpIndexVersion(this.db);
859
+ return { node: created, superseded: rows.filter((r) => r.id !== created.id).map((r) => r.id) };
860
+ }
861
+ for (const r of rows) {
862
+ if (r.id === created.id) continue;
863
+ this.db.prepare("UPDATE node SET status='superseded', superseded_by=?, updated_at=? WHERE id=?").run(created.id, this.now(), r.id);
864
+ this.revision("replace-card", r.id, r.uid, { by: created.id });
865
+ }
866
+ if (rows.length > 0) bumpIndexVersion(this.db);
867
+ return { node: created, superseded: rows.map((r) => r.id) };
868
+ });
869
+ }
870
+
871
+ // ── 索引维护 ────────────────────────────────────────────────────────
872
+ reindexNode(id, text, title = "") {
873
+ this.db.prepare("DELETE FROM term WHERE node_id=?").run(id);
874
+ this.db.prepare("DELETE FROM vec WHERE node_id=?").run(id);
875
+ const ins = this.db.prepare("INSERT INTO term(node_id,term,tf) VALUES(?,?,?)");
876
+ const corpus = title ? String(title) + "\n" + String(text ?? "") : String(text ?? "");
877
+ for (const [term, tf] of termRows(corpus)) ins.run(id, term, tf);
878
+ const v = embed(corpus);
879
+ this.db.prepare("INSERT INTO vec(node_id,dim,kind,data) VALUES(?,?,?,?)").run(id, VEC_DIM, VEC_KIND, pack(v));
880
+ }
881
+
882
+ /** 全量重建派生索引(doctor / 迁移后用)。 */
883
+ reindexAll() {
884
+ const rows = this.db.prepare("SELECT id,text,title FROM node").all();
885
+ tx(this.db, () => {
886
+ this.db.exec("DELETE FROM term");
887
+ this.db.exec("DELETE FROM vec");
888
+ for (const r of rows) this.reindexNode(Number(r.id), String(r.text), String(r.title ?? ""));
889
+ });
890
+ bumpIndexVersion(this.db);
891
+ return rows.length;
892
+ }
893
+
894
+ revision(action, nodeId, uid, detail) {
895
+ try {
896
+ this.db
897
+ .prepare("INSERT INTO revision(ts,action,node_id,uid,detail) VALUES(?,?,?,?,?)")
898
+ .run(this.now(), action, nodeId ?? null, uid ?? null, stableStringify(detail ?? {}));
899
+ this.db
900
+ .prepare("DELETE FROM revision WHERE id <= (SELECT id FROM revision ORDER BY id DESC LIMIT 1 OFFSET 5000)")
901
+ .run();
902
+ } catch {
903
+ /* 版本记录失败不能影响主操作 */
904
+ }
905
+ }
906
+
907
+ audit(kind, data = {}) {
908
+ try {
909
+ this.db
910
+ .prepare("INSERT INTO audit(ts,kind,scope,query,hits,detail) VALUES(?,?,?,?,?,?)")
911
+ .run(this.now(), String(kind), data.scope ? String(data.scope) : null, data.query ? String(data.query).slice(0, 300) : null,
912
+ data.hits === undefined ? null : Number(data.hits), data.detail === undefined ? null : stableStringify(data.detail).slice(0, 4000));
913
+ this.db
914
+ .prepare("DELETE FROM audit WHERE id <= (SELECT id FROM audit ORDER BY id DESC LIMIT 1 OFFSET 5000)")
915
+ .run();
916
+ } catch {
917
+ /* 审计失败不能挡住检索 */
918
+ }
919
+ }
920
+
921
+ recentAudit(limit = 20) {
922
+ return this.db.prepare("SELECT * FROM audit ORDER BY id DESC LIMIT ?").all(Math.min(Math.max(asInt(limit, 20), 1), 200))
923
+ .map((r) => ({
924
+ id: Number(r.id), ts: Number(r.ts), kind: String(r.kind), scope: r.scope, query: r.query,
925
+ hits: r.hits === null ? null : Number(r.hits),
926
+ detail: safeJson(r.detail),
927
+ }));
928
+ }
929
+
930
+ recentRevisions(limit = 20) {
931
+ return this.db.prepare("SELECT * FROM revision ORDER BY id DESC LIMIT ?").all(Math.min(Math.max(asInt(limit, 20), 1), 200))
932
+ .map((r) => ({ id: Number(r.id), ts: Number(r.ts), action: String(r.action), nodeId: r.node_id, uid: r.uid, detail: safeJson(r.detail) }));
933
+ }
934
+
935
+ /** 作用域别名:把 workspace:<hash> 与真实 cwd 关联,报告和卡片里能看懂。 */
936
+ rememberScope(scope, cwd) {
937
+ if (!scope || !cwd) return;
938
+ try {
939
+ this.db
940
+ .prepare("INSERT INTO scope_alias(scope,cwd,label,last_seen) VALUES(?,?,?,?) ON CONFLICT(scope) DO UPDATE SET cwd=excluded.cwd,label=excluded.label,last_seen=excluded.last_seen")
941
+ .run(String(scope), String(cwd), String(cwd).replace(/\\/g, "/").split("/").filter(Boolean).slice(-1)[0] || "", this.now());
942
+ } catch {
943
+ /* 别名只是展示用 */
944
+ }
945
+ }
946
+
947
+ scopeAliases() {
948
+ const out = Object.create(null);
949
+ for (const r of this.db.prepare("SELECT scope,cwd FROM scope_alias").all()) out[String(r.scope)] = String(r.cwd);
950
+ return out;
951
+ }
952
+
953
+ /** 看板要展示全部作用域:user + 所有写过条目的 workspace。 */
954
+ allScopes() {
955
+ const set = new Set(["user"]);
956
+ for (const r of this.db.prepare("SELECT DISTINCT scope FROM node").all()) set.add(String(r.scope));
957
+ for (const scope of Object.keys(this.scopeAliases())) set.add(scope);
958
+ return [...set];
959
+ }
960
+
961
+ // ── 日记索引(属于情感枝的索引,不是第六枝)──────────────────────────
962
+ diaryAdd(date, text, mood = "manual") {
963
+ const d = String(date ?? "").trim();
964
+ if (!isDateString(d)) throw new Error("日记日期格式应为 YYYY-MM-DD:" + d);
965
+ const body = String(text ?? "").trim();
966
+ if (!body) throw new Error("日记正文不能为空");
967
+ if (body.length > 20000) throw new Error("日记正文超过 20000 字上限,请拆分后再写");
968
+ const safe = redactText(body);
969
+ const stored = safe.text;
970
+ const ts = this.now();
971
+ this.db
972
+ .prepare(
973
+ "INSERT INTO diary(date,text,mood,created_at,updated_at) VALUES(?,?,?,?,?) " +
974
+ "ON CONFLICT(date) DO UPDATE SET text=excluded.text,mood=excluded.mood,updated_at=excluded.updated_at",
975
+ )
976
+ .run(d, stored, truncate(String(mood ?? ""), 40), ts, ts);
977
+ this.revision("diary", null, "diary:" + d, { mood: String(mood ?? ""), chars: stored.length, redactions: safe.redactions.length });
978
+ return this.diaryGet(d);
979
+ }
980
+
981
+ diaryGet(date) {
982
+ const r = this.db.prepare("SELECT date,text,mood,created_at,updated_at FROM diary WHERE date=?").get(String(date));
983
+ if (!r) return null;
984
+ return {
985
+ date: String(r.date),
986
+ text: String(r.text),
987
+ mood: String(r.mood ?? ""),
988
+ createdAt: Number(r.created_at),
989
+ updatedAt: Number(r.updated_at),
990
+ };
991
+ }
992
+
993
+ diaryList(limit = 60) {
994
+ const n = Math.min(Math.max(asInt(limit, 60), 1), 366);
995
+ return this.db
996
+ .prepare("SELECT date,text,mood,created_at,updated_at FROM diary ORDER BY date DESC LIMIT ?")
997
+ .all(n)
998
+ .map((r) => ({
999
+ date: String(r.date),
1000
+ text: String(r.text),
1001
+ mood: String(r.mood ?? ""),
1002
+ createdAt: Number(r.created_at),
1003
+ updatedAt: Number(r.updated_at),
1004
+ }));
1005
+ }
1006
+
1007
+ /**
1008
+ * 自动拼装某天的日记索引(只读库内事实)。
1009
+ * 默认不覆盖手写日记(mood=manual);force=true 才覆盖。
1010
+ */
1011
+ diaryAuto(date = localDate(this.now()), opts = {}) {
1012
+ const d = String(date ?? "").trim();
1013
+ if (!isDateString(d)) throw new Error("日记日期格式应为 YYYY-MM-DD:" + d);
1014
+ const existing = this.diaryGet(d);
1015
+ if (existing && existing.mood === "manual" && opts.force !== true) {
1016
+ return { skipped: true, reason: "当天已有手写日记,未覆盖;要覆盖请传 force=true", record: existing };
1017
+ }
1018
+ const { start, end } = dayRange(d);
1019
+ const scopeList = opts.scopes === undefined ? null : Array.isArray(opts.scopes) ? opts.scopes : [opts.scopes];
1020
+ let revisions = [];
1021
+ if (!scopeList || scopeList.length > 0) {
1022
+ const scopeSql = scopeList ? " AND n.scope IN (" + scopeList.map(() => "?").join(",") + ")" : "";
1023
+ revisions = this.db
1024
+ .prepare(
1025
+ "SELECT r.action, r.ts, r.node_id, r.uid, n.title, n.subject, n.layer " +
1026
+ "FROM revision r LEFT JOIN node n ON n.id=r.node_id WHERE r.ts>=? AND r.ts<?" + scopeSql + " ORDER BY r.id",
1027
+ )
1028
+ .all(start, end, ...(scopeList ?? []));
1029
+ }
1030
+ const searchRows = this.db
1031
+ .prepare("SELECT query,hits,scope FROM audit WHERE kind='search' AND ts>=? AND ts<? AND query IS NOT NULL ORDER BY id DESC LIMIT 50")
1032
+ .all(start, end);
1033
+ const allowedScopes = scopeList ? new Set(scopeList) : null;
1034
+ const searches = searchRows
1035
+ .filter((r) => {
1036
+ if (!allowedScopes) return true;
1037
+ if (!r.scope) return true;
1038
+ return String(r.scope).split(",").some((s) => allowedScopes.has(s));
1039
+ })
1040
+ .slice(0, 8);
1041
+ const text = buildDiaryText({ date: d, revisions, searches, dbFile: opts.dbFile ?? "", agentsPath: opts.agentsPath ?? "" }).slice(0, 20000);
1042
+ const record = this.diaryAdd(d, text, "auto");
1043
+ return { skipped: false, record, revisions: revisions.length, searches: searches.length };
1044
+ }
1045
+
1046
+ // ── 统计 / 树视图 ──────────────────────────────────────────────────
1047
+ stats(scopes) {
1048
+ const scopeList = scopes === undefined ? null : Array.isArray(scopes) ? scopes : [scopes];
1049
+ const emptyScope = Boolean(scopeList && scopeList.length === 0);
1050
+ const scopeWhere = scopeList ? (emptyScope ? " WHERE 0" : " WHERE scope IN (" + scopeList.map(() => "?").join(",") + ")") : "";
1051
+ const scopeAnd = scopeList ? (emptyScope ? " AND 0" : " AND scope IN (" + scopeList.map(() => "?").join(",") + ")") : "";
1052
+ const byLayer = Object.create(null);
1053
+ const byStatus = Object.create(null);
1054
+ const byScope = Object.create(null);
1055
+ for (const r of this.db.prepare("SELECT layer,status,scope,COUNT(*) c FROM node" + scopeWhere + " GROUP BY layer,status,scope").all(...(scopeList ?? []))) {
1056
+ const c = Number(r.c);
1057
+ byLayer[r.layer] = (byLayer[r.layer] ?? 0) + c;
1058
+ byStatus[r.status] = (byStatus[r.status] ?? 0) + c;
1059
+ byScope[r.scope] = (byScope[r.scope] ?? 0) + c;
1060
+ }
1061
+ const now = this.now();
1062
+ const expired = Number(
1063
+ this.db
1064
+ .prepare("SELECT COUNT(*) c FROM node WHERE status='active' AND valid_until IS NOT NULL AND valid_until < ?" + scopeAnd)
1065
+ .get(now, ...(scopeList ?? [])).c,
1066
+ );
1067
+ const pageSize = Number(this.db.prepare("PRAGMA page_size").get().page_size);
1068
+ const pageCount = Number(this.db.prepare("PRAGMA page_count").get().page_count);
1069
+ return {
1070
+ total: scopeList ? this.count({ scope: scopeList }) : this.count({}),
1071
+ byLayer,
1072
+ byStatus,
1073
+ byScope,
1074
+ expired,
1075
+ pendingLeaves: this.count({ layers: ["leaf"], status: "active", ...(scopeList ? { scope: scopeList } : {}) }),
1076
+ candidates: this.count({ layers: ["trunk"], status: "candidate", ...(scopeList ? { scope: scopeList } : {}) }),
1077
+ taskCards: this.count({ layers: ["task"], status: "active", ...(scopeList ? { scope: scopeList } : {}) }),
1078
+ diaryTotal: Number(this.db.prepare("SELECT COUNT(*) c FROM diary").get().c),
1079
+ diaryLastDate: this.db.prepare("SELECT MAX(date) d FROM diary").get()?.d ?? null,
1080
+ indexVersion: Number(getMeta(this.db, "index_version", "0")),
1081
+ dbBytes: pageSize * pageCount,
1082
+ schemaVersion: Number(getMeta(this.db, "schema_version", "0")),
1083
+ lastSyncAt: Number(getMeta(this.db, "agents_sync_at", "0")) || null,
1084
+ lastAgentsChecksum: getMeta(this.db, "agents_checksum", null),
1085
+ };
1086
+ }
1087
+
1088
+ /** 树视图:各枝条目、任务卡清单、候选、过期提醒。给 memory_tree 工具用。 */
1089
+ tree(opts = {}) {
1090
+ const scopes = opts.scopes;
1091
+ const aliases = this.scopeAliases();
1092
+ const layers = [];
1093
+ for (const layer of LAYERS) {
1094
+ const rows = this.list({ scope: scopes, layers: [layer], status: "active", limit: 500, order: "importance" });
1095
+ const activeTotal = this.count({ scope: scopes, layers: [layer], status: "active" });
1096
+ const statusCounts = {};
1097
+ for (const s of STATUSES) statusCounts[s] = this.count({ scope: scopes, layers: [layer], status: s });
1098
+ layers.push({
1099
+ layer,
1100
+ active: rows.length,
1101
+ activeTotal,
1102
+ truncated: activeTotal > rows.length,
1103
+ statusCounts,
1104
+ items: rows.map((n) => ({
1105
+ id: n.id,
1106
+ uid: n.uid,
1107
+ subject: n.subject,
1108
+ title: n.title,
1109
+ scope: n.scope,
1110
+ importance: n.importance,
1111
+ trust: n.trust,
1112
+ updatedAt: n.updatedAt,
1113
+ preview: truncate(n.text.replace(/\s+/g, " "), 90),
1114
+ tags: n.tags,
1115
+ expired: n.validUntil !== null && n.validUntil < this.now(),
1116
+ })),
1117
+ });
1118
+ }
1119
+ const candidates = this.list({ scope: scopes, layers: ["trunk"], status: "candidate", limit: 100, order: "created" })
1120
+ .map((n) => ({ id: n.id, uid: n.uid, title: n.title, text: truncate(n.text, 180), source: n.source }));
1121
+ return {
1122
+ stats: this.stats(scopes),
1123
+ scopes,
1124
+ aliases,
1125
+ layers,
1126
+ candidates,
1127
+ taskSubjects: this.list({ scope: scopes, layers: ["task"], status: "active", limit: 200, order: "created" }).map((n) => n.subject),
1128
+ };
1129
+ }
1130
+
1131
+ // ── 迁移 / 导入导出 ────────────────────────────────────────────────
1132
+ exportJsonl() {
1133
+ const rows = this.db.prepare("SELECT * FROM node ORDER BY id").all().map(rowToNode);
1134
+ // 备份里同时记下「取代者 uid」:恢复后 id 会重排,只有 uid 能稳定重建 supersededBy 链。
1135
+ const uidById = new Map(rows.map((n) => [n.id, n.uid]));
1136
+ const lines = rows.map((n) => JSON.stringify({
1137
+ ...n,
1138
+ supersededByUid: n.supersededBy ? uidById.get(n.supersededBy) ?? null : null,
1139
+ }));
1140
+ for (const d of this.db.prepare("SELECT date,text,mood FROM diary ORDER BY date").all()) {
1141
+ lines.push(JSON.stringify({ _kind: "diary", date: d.date, text: d.text, mood: d.mood }));
1142
+ }
1143
+ for (const b of this.db.prepare("SELECT uid,bucket FROM trunk_bucket ORDER BY uid").all()) {
1144
+ lines.push(JSON.stringify({ _kind: "trunk_bucket", uid: b.uid, bucket: b.bucket }));
1145
+ }
1146
+ return lines.join("\n") + (lines.length ? "\n" : "");
1147
+ }
1148
+
1149
+ /** 导入 JSONL;byUid 已存在则跳过(merge)或更新(update)。整批原子,失败全部回滚。 */
1150
+ importJsonl(text, opts = {}) {
1151
+ const lines = String(text ?? "").split(/\r?\n/).filter((x) => x.trim() !== "");
1152
+ return tx(this.db, () => {
1153
+ let added = 0;
1154
+ let updated = 0;
1155
+ let skipped = 0;
1156
+ let diary = 0;
1157
+ let buckets = 0;
1158
+ const supersededLinks = [];
1159
+ for (const line of lines) {
1160
+ let obj;
1161
+ try {
1162
+ obj = JSON.parse(line);
1163
+ } catch {
1164
+ skipped += 1;
1165
+ continue;
1166
+ }
1167
+ if (obj && obj._kind === "diary") {
1168
+ const date = String(obj.date ?? "");
1169
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || typeof obj.text !== "string" || obj.text.length > TEXT_MAX) { skipped += 1; continue; }
1170
+ if (this.diaryGet(date) && opts.mode !== "update") { skipped += 1; continue; }
1171
+ this.diaryAdd(date, obj.text, String(obj.mood ?? "auto"));
1172
+ diary += 1;
1173
+ continue;
1174
+ }
1175
+ if (obj && obj._kind === "trunk_bucket") {
1176
+ if (!obj.uid || typeof obj.bucket !== "string" || obj.bucket.trim() === "" || obj.bucket.length > 60 || !/^trunk:§1-\d+-\d+$/.test(String(obj.uid))) { skipped += 1; continue; }
1177
+ this.setTrunkBucket(String(obj.uid), String(obj.bucket));
1178
+ buckets += 1;
1179
+ continue;
1180
+ }
1181
+ if (obj && obj._kind && obj._kind !== "diary" && obj._kind !== "trunk_bucket") {
1182
+ // 未来版本新增的备份行类型:当前版本不认识就跳过,不当成记忆条目写坏库。
1183
+ skipped += 1;
1184
+ continue;
1185
+ }
1186
+ if (!obj || typeof obj !== "object" || typeof obj.text !== "string" || obj.text.trim() === "") {
1187
+ skipped += 1;
1188
+ continue;
1189
+ }
1190
+ if (obj.text.length > TEXT_MAX) {
1191
+ skipped += 1;
1192
+ continue;
1193
+ }
1194
+ const uid = obj.uid ? String(obj.uid) : undefined;
1195
+ if (uid && uid.length > 200) {
1196
+ skipped += 1;
1197
+ continue;
1198
+ }
1199
+ if (obj.scope !== undefined && (typeof obj.scope !== "string" || obj.scope.trim() === "" || obj.scope.length > 200)) {
1200
+ skipped += 1;
1201
+ continue;
1202
+ }
1203
+ if (!LAYERS.includes(obj.layer)) {
1204
+ skipped += 1;
1205
+ continue;
1206
+ }
1207
+ const layer = obj.layer;
1208
+ // uid 必须与 layer 前缀一致;旧库迁移留下的 legacy:<id> 也允许,保证备份能往返。
1209
+ if (uid && !uid.startsWith(layer + ":") && !uid.startsWith("legacy:")) {
1210
+ skipped += 1;
1211
+ continue;
1212
+ }
1213
+ const existing = uid ? this.get(uid) : null;
1214
+ if (existing) {
1215
+ if (existing.layer !== layer) {
1216
+ skipped += 1;
1217
+ continue;
1218
+ }
1219
+ if (existing.layer === "trunk" && existing.status === "active") {
1220
+ // 正本优先:导入永远不覆盖已激活的主干规则,等 AGENTS.md 同步。
1221
+ skipped += 1;
1222
+ continue;
1223
+ }
1224
+ if (existing.layer === "trunk" && String(obj.status) === "active") {
1225
+ // 候选也不能借备份导入直接转正;必须走 AGENTS.md 同步。
1226
+ skipped += 1;
1227
+ continue;
1228
+ }
1229
+ if (opts.mode === "update") {
1230
+ const nextStatus = obj.status === undefined ? undefined : String(obj.status);
1231
+ if (nextStatus !== undefined && !STATUSES.includes(nextStatus)) { skipped += 1; continue; }
1232
+ this.update(existing.id, {
1233
+ text: obj.text, title: obj.title, subject: obj.subject, tags: obj.tags,
1234
+ trust: obj.trust, importance: obj.importance, validUntil: obj.validUntil,
1235
+ status: nextStatus, halfLifeDays: obj.halfLifeDays,
1236
+ summary: obj.summary, evidence: obj.evidence, source: obj.source,
1237
+ });
1238
+ if (obj.supersededByUid) supersededLinks.push({ uid, byUid: String(obj.supersededByUid) });
1239
+ updated += 1;
1240
+ } else skipped += 1;
1241
+ continue;
1242
+ }
1243
+ const rawStatus = obj.status === undefined ? "active" : String(obj.status);
1244
+ if (!STATUSES.includes(rawStatus)) {
1245
+ skipped += 1;
1246
+ continue;
1247
+ }
1248
+ const status = layer === "trunk" && rawStatus === "active" ? "candidate" : rawStatus;
1249
+ const res = this.add({
1250
+ uid,
1251
+ scope: obj.scope ?? "user",
1252
+ layer,
1253
+ kind: obj.kind,
1254
+ status,
1255
+ subject: obj.subject,
1256
+ title: obj.title,
1257
+ text: obj.text,
1258
+ summary: obj.summary,
1259
+ tags: obj.tags,
1260
+ source: obj.source,
1261
+ evidence: obj.evidence,
1262
+ trust: obj.trust,
1263
+ importance: obj.importance,
1264
+ halfLifeDays: obj.halfLifeDays,
1265
+ validUntil: obj.validUntil,
1266
+ ts: obj.ts,
1267
+ createdAt: obj.createdAt,
1268
+ updatedAt: obj.updatedAt,
1269
+ });
1270
+ if (res.duplicate) skipped += 1;
1271
+ else added += 1;
1272
+ if (obj.supersededByUid) supersededLinks.push({ uid, byUid: String(obj.supersededByUid) });
1273
+ }
1274
+ // 恢复 supersededBy 链:id 会重排,必须等所有 uid 都落库后再按 uid 回填。
1275
+ for (const link of supersededLinks) {
1276
+ const target = this.get(link.uid);
1277
+ const by = this.get(link.byUid);
1278
+ if (!target || !by || target.id === by.id || target.status !== "superseded") continue;
1279
+ this.db.prepare("UPDATE node SET superseded_by=? WHERE id=?").run(by.id, target.id);
1280
+ }
1281
+ return { added, updated, skipped, diary, buckets, total: added + updated + skipped + diary + buckets };
1282
+ });
1283
+ }
1284
+
1285
+ close() {
1286
+ try {
1287
+ this.db.close();
1288
+ } catch {
1289
+ /* 已经关了 */
1290
+ }
1291
+ }
1292
+ }
1293
+
1294
+ export function normalizeWhen(v) {
1295
+ if (v === null || v === undefined || v === "") return null;
1296
+ if (typeof v === "number" && Number.isFinite(v)) return v < 1e12 ? Math.trunc(v * 1000) : Math.trunc(v);
1297
+ if (v instanceof Date) return v.getTime();
1298
+ const s = String(v).trim();
1299
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) {
1300
+ const t = Date.parse(s + "T23:59:59");
1301
+ return Number.isNaN(t) ? null : t;
1302
+ }
1303
+ const t = Date.parse(s);
1304
+ return Number.isNaN(t) ? null : t;
1305
+ }
1306
+
1307
+ function sumWeights(text) {
1308
+ let n = 0;
1309
+ for (const [, w] of tokenizeInto(text)) n += w;
1310
+ return n;
1311
+ }
1312
+
1313
+ function clampInt(v, min, max, fallback) {
1314
+ const n = Number(v);
1315
+ if (!Number.isFinite(n)) return fallback;
1316
+ return Math.min(max, Math.max(min, Math.round(n)));
1317
+ }
1318
+
1319
+ function clampNum(v, min, max, fallback) {
1320
+ const n = Number(v);
1321
+ if (!Number.isFinite(n)) return fallback;
1322
+ return Math.min(max, Math.max(min, n));
1323
+ }
1324
+
1325
+ function safeJson(s) {
1326
+ if (s === null || s === undefined) return null;
1327
+ try {
1328
+ return JSON.parse(String(s));
1329
+ } catch {
1330
+ return String(s);
1331
+ }
1332
+ }
1333
+
1334
+ export { cosine, unpack, VEC_DIM };