@frogmoo/dsh-supermemory 0.0.0-stage → 1.4.1

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,686 @@
1
+ import { h as normalizeTags, i as hubSelection, o as queryWeights, p as deriveTitle, r as enumerateModels, s as rawScore, u as tokenize } from "./model-Z4_-9sAj.js";
2
+ import { t as newId } from "./store-DD2L3GDr.js";
3
+ /**
4
+ * The route a memory decision uses: the acting session's hub model first, then
5
+ * the first enumerated catalog entry. `undefined` means "no model available" —
6
+ * every caller then keeps its heuristic behaviour (and burns no tokens).
7
+ */
8
+ async function resolveLlmRoute(ctx, sessionId) {
9
+ if (!ctx) return void 0;
10
+ if (sessionId) try {
11
+ const agent = ctx.agents?.get?.(sessionId);
12
+ const hub = hubSelection(agent);
13
+ if (hub) return {
14
+ provider: hub.provider,
15
+ model: hub.model,
16
+ ...hub.reasoningEffort ? { reasoningEffort: hub.reasoningEffort } : {}
17
+ };
18
+ } catch {}
19
+ try {
20
+ const { models } = await enumerateModels(ctx);
21
+ const first = models[0];
22
+ if (first) return {
23
+ provider: first.provider,
24
+ model: first.id
25
+ };
26
+ } catch {}
27
+ }
28
+ /** The `llm` service through `ctx.get` (never the property: see model.ts). */
29
+ function llmServiceOf(ctx) {
30
+ try {
31
+ return ctx?.get?.("llm");
32
+ } catch {
33
+ return;
34
+ }
35
+ }
36
+ /** Strip code fences/quotes and parse the first JSON object of an answer. */
37
+ function parseJsonObject(text) {
38
+ const clean = String(text ?? "").replace(/```[a-z]*/gi, "").replace(/```/g, "").trim();
39
+ const start = clean.indexOf("{");
40
+ const end = clean.lastIndexOf("}");
41
+ if (start < 0 || end <= start) return void 0;
42
+ try {
43
+ return JSON.parse(clean.slice(start, end + 1));
44
+ } catch {
45
+ return;
46
+ }
47
+ }
48
+ /**
49
+ * One model call whose answer must be a JSON object. Returns `undefined` when
50
+ * there is no model, the call fails, it times out, or the answer carries no
51
+ * usable JSON — the caller degrades silently in every one of those cases.
52
+ */
53
+ async function askLlmJson(deps, request) {
54
+ const { ctx, logger, sessionId } = deps;
55
+ if (!ctx) return void 0;
56
+ const llm = llmServiceOf(ctx);
57
+ if (!llm || typeof llm.stream !== "function") return void 0;
58
+ const route = await resolveLlmRoute(ctx, sessionId);
59
+ if (!route) return void 0;
60
+ const controller = new AbortController();
61
+ const timer = setTimeout(() => controller.abort(), request.timeoutMs ?? 2e4);
62
+ let text = "";
63
+ try {
64
+ const stream = llm.stream({
65
+ provider: route.provider,
66
+ model: route.model,
67
+ ...route.reasoningEffort ? { reasoningEffort: route.reasoningEffort } : {},
68
+ system: request.system,
69
+ messages: [{
70
+ role: "user",
71
+ content: [{
72
+ type: "text",
73
+ text: request.user
74
+ }]
75
+ }],
76
+ maxTokens: request.maxTokens ?? 600,
77
+ temperature: .2,
78
+ signal: controller.signal
79
+ });
80
+ for await (const chunk of stream) if (chunk?.type === "text-delta" && typeof chunk.text === "string") text += chunk.text;
81
+ } catch (error) {
82
+ logger?.warn(`supermemory: llm-json call failed: ${String(error).slice(0, 160)}`);
83
+ return;
84
+ } finally {
85
+ clearTimeout(timer);
86
+ }
87
+ const parsed = parseJsonObject(text);
88
+ if (parsed === void 0) logger?.warn("supermemory: llm-json answer did not contain a JSON object; degrading to the heuristic");
89
+ return parsed;
90
+ }
91
+ /** Every collection row (empty when the medium predates the table). */
92
+ function collectionRows(store) {
93
+ const table = store.memoryCollections;
94
+ if (!table || typeof table.entries !== "function") return [];
95
+ return [...table.entries()];
96
+ }
97
+ /** Collections of one workspace (archived excluded by default). */
98
+ function listCollections(store, workspaceKey, options = {}) {
99
+ return collectionRows(store).filter(([, row]) => row.workspaceKey === workspaceKey && (options.includeArchived || row.status !== "archived"));
100
+ }
101
+ /** Title/id of the collection one entry belongs to ('' when uncollected). */
102
+ function collectionOfEntry(store, memory) {
103
+ const id = memory.collectionId;
104
+ if (!id) return void 0;
105
+ return collectionRows(store).find(([rowId]) => rowId === id);
106
+ }
107
+ function tokenSet(text) {
108
+ return new Set(tokenize(String(text ?? "")));
109
+ }
110
+ /** Bounded overlap: |A∩B| / min(|A|,|B|) — a subset counts fully. */
111
+ function overlapRatio(left, right) {
112
+ if (left.size === 0 || right.size === 0) return 0;
113
+ let hit = 0;
114
+ for (const token of left) if (right.has(token)) hit += 1;
115
+ return hit / Math.min(left.size, right.size);
116
+ }
117
+ /** Tag overlap: exact (case-insensitive) tag hits, falling back to token overlap. */
118
+ function tagOverlap(left, right) {
119
+ const a = normalizeTags(left).map((tag) => tag.toLowerCase());
120
+ const b = normalizeTags(right).map((tag) => tag.toLowerCase());
121
+ if (a.length === 0 || b.length === 0) return 0;
122
+ let hits = 0;
123
+ for (const tag of a) if (b.includes(tag)) hits += 1;
124
+ const exact = hits / Math.min(a.length, b.length);
125
+ const tokens = overlapRatio(tokenSet(a.join(" ")), tokenSet(b.join(" ")));
126
+ return Math.max(exact, tokens);
127
+ }
128
+ /**
129
+ * 相似度分值(0–8):标题×4 + 标签×3 + 正文×1,各项是**重合率**而不是命中次数,
130
+ * 所以分值与标题/标签长度无关,阈值可解释:>=4 高相似、>=1.75 中等、其余低。
131
+ */
132
+ function shapeScore(entry, collection) {
133
+ const title = overlapRatio(tokenSet(entry.title), tokenSet(collection.title));
134
+ const tags = tagOverlap(entry.keywords ?? [], collection.keywords ?? []);
135
+ const body = overlapRatio(tokenSet(entry.summary), tokenSet(collection.summary));
136
+ return 4 * title + 3 * tags + 1 * body;
137
+ }
138
+ /** 分值 → 三档。 */
139
+ function tierOfScore(score) {
140
+ if (!(score > 0)) return "low";
141
+ if (score >= 4) return "high";
142
+ if (score >= 1.75) return "medium";
143
+ return "low";
144
+ }
145
+ function foldCounts(text) {
146
+ const bag = /* @__PURE__ */ new Map();
147
+ for (const token of tokenize(text)) bag.set(token, (bag.get(token) ?? 0) + 1);
148
+ return bag;
149
+ }
150
+ /**
151
+ * 集合级匹配(读取侧第一级,也是写入侧候选来源):与记忆评分同一套权重
152
+ * (标题×4、标签×3、正文×1),但作用在集合的三个字段上,所以「上次结论所在的
153
+ * 集合」会被同一条查询命中,从而把该集合的条目一起带出来。
154
+ */
155
+ function matchCollections(collections, query, limit = 3, minScore = 0) {
156
+ const weights = queryWeights(query);
157
+ if (weights.size === 0) return [];
158
+ const matches = [];
159
+ for (const [collectionId, row] of collections) {
160
+ if (row.status === "archived") continue;
161
+ const titleBag = foldCounts(row.title ?? "");
162
+ const tagBag = foldCounts((row.keywords ?? []).join(" "));
163
+ const bodyBag = foldCounts(row.summary ?? "");
164
+ let score = 0;
165
+ for (const [token, weight] of weights) {
166
+ score += weight * 4 * Math.min(titleBag.get(token) ?? 0, 2);
167
+ score += weight * 3 * Math.min(tagBag.get(token) ?? 0, 2);
168
+ score += weight * 1 * Math.min(bodyBag.get(token) ?? 0, 2);
169
+ }
170
+ if (score <= minScore) continue;
171
+ matches.push({
172
+ collectionId,
173
+ title: row.title,
174
+ keywords: [...row.keywords ?? []],
175
+ score,
176
+ tier: tierOfScore(score)
177
+ });
178
+ }
179
+ matches.sort((a, b) => b.score - a.score);
180
+ return matches.slice(0, Math.max(1, Math.min(limit, 8)));
181
+ }
182
+ /** Best collection for an incoming entry, with its tier (null when none matches). */
183
+ function bestCollectionFor(entry, collections) {
184
+ let best = null;
185
+ for (const [collectionId, row] of collections) {
186
+ if (row.status === "archived") continue;
187
+ const score = shapeScore(entry, {
188
+ title: row.title,
189
+ keywords: row.keywords,
190
+ summary: row.summary
191
+ });
192
+ if (score <= 0) continue;
193
+ if (!best || score > best.score) best = {
194
+ collectionId,
195
+ title: row.title,
196
+ keywords: [...row.keywords ?? []],
197
+ score,
198
+ tier: tierOfScore(score)
199
+ };
200
+ }
201
+ return best;
202
+ }
203
+ function decay(createdAt, now, halfLifeDays) {
204
+ const ageDays = Math.max(0, (now - createdAt) / 864e5);
205
+ return Math.pow(.5, ageDays / Math.max(1, halfLifeDays));
206
+ }
207
+ /** 集合上下文对条目的加成上限(避免一条弱命中被集合分淹没)。 */
208
+ const COLLECTION_BOOST = .5;
209
+ const COLLECTION_BOOST_CAP = 12;
210
+ /**
211
+ * 两级检索:先按查询给集合打分(一级),再在「命中集合的条目 ∪ 直接命中阈值
212
+ * 的条目」里精选(二级)。
213
+ *
214
+ * 排序分 = 直接分(标题×4/标签×3/正文×1)+ 0.5×集合分(封顶 12),再乘时间衰减:
215
+ * - 直接在正文里命中一次也可能进入结果(与旧行为一致);
216
+ * - 只被集合上下文带出的条目(直接分 0)只有在集合足够强(≥ 高相似阈值)时才算候选,
217
+ * 否则集合命中会把整集条目都倒出来,精确度反而下降。
218
+ */
219
+ function recallEntriesWithCollections(collections, memories, query, options, collectionLimit = 3) {
220
+ const weights = queryWeights(query);
221
+ if (weights.size === 0) return {
222
+ items: [],
223
+ collections: []
224
+ };
225
+ const matched = matchCollections(collections, query, collectionLimit);
226
+ const boost = /* @__PURE__ */ new Map();
227
+ for (const match of matched) boost.set(match.collectionId, match);
228
+ const items = [];
229
+ for (const [memoryId, memory] of memories) {
230
+ if (memory.status !== "active") continue;
231
+ const direct = rawScore(memory, weights);
232
+ const collection = memory.collectionId ? boost.get(memory.collectionId) : void 0;
233
+ const contextual = collection !== void 0 && (direct > 0 || collection.score >= 4);
234
+ if (direct < options.minScore && !contextual) continue;
235
+ const contextScore = collection ? Math.min(collection.score, COLLECTION_BOOST_CAP) : 0;
236
+ const combined = direct + COLLECTION_BOOST * contextScore;
237
+ items.push({
238
+ memoryId,
239
+ title: memory.title ?? "",
240
+ text: memory.text,
241
+ keywords: memory.keywords ?? [],
242
+ createdAt: memory.createdAt,
243
+ score: combined * decay(memory.createdAt, options.now, options.halfLifeDays),
244
+ directScore: direct,
245
+ collectionId: collection?.collectionId ?? "",
246
+ collectionTitle: collection?.title ?? "",
247
+ collectionTags: collection ? [...collection.keywords] : []
248
+ });
249
+ }
250
+ items.sort((a, b) => b.score - a.score || b.createdAt - a.createdAt);
251
+ return {
252
+ items: items.slice(0, options.limit),
253
+ collections: matched
254
+ };
255
+ }
256
+ /**
257
+ * Every active collection of the workspace ranked against one entry (best
258
+ * first, capped at {@link COLLECTION_CANDIDATE_LIMIT}). Zero-similarity rows
259
+ * stay in the list on purpose: the model may still reuse a collection the
260
+ * heuristic cannot see (different wording, same project), and it is the one
261
+ * that decides "new set" — so the candidate list must not pre-decide that.
262
+ */
263
+ function rankCollectionsFor(entry, collections, limit = 12) {
264
+ const ranked = [];
265
+ for (const [collectionId, row] of collections) {
266
+ if (row.status === "archived") continue;
267
+ const score = shapeScore(entry, {
268
+ title: row.title,
269
+ keywords: row.keywords,
270
+ summary: row.summary
271
+ });
272
+ ranked.push({
273
+ collectionId,
274
+ title: row.title,
275
+ keywords: [...row.keywords ?? []],
276
+ summary: clip(row.summary ?? "", 200),
277
+ score,
278
+ tier: tierOfScore(score)
279
+ });
280
+ }
281
+ ranked.sort((a, b) => b.score - a.score);
282
+ return ranked.slice(0, Math.max(1, limit));
283
+ }
284
+ const DECISION_SYSTEM = [
285
+ "你在维护 SuperMemory 的「记忆集合」归属。只输出一个 JSON 对象,不要代码围栏、不要解释。",
286
+ "字段:{\"collectionId\":\"复用的候选集合 id(不新建时必填)\",\"createNew\":false,\"title\":\"新建时的集合标题(≤48字,必填)\",\"tags\":[\"新建时的 3–8 个检索短词\"],\"reason\":\"一句话理由(≤60字)\"}",
287
+ "规则:",
288
+ "- collectionId 必须是候选清单里的 id,不能编造;无法判断时也要按格式二选一回答。",
289
+ "- 候选集合主题相近(同一项目/同一类约定/同一命令族)就复用,哪怕标题字面不同。",
290
+ "- 只有当候选都不相关时才 createNew=true,并给出 title/tags。",
291
+ "- reason 要短,说明为什么归入该集合或为什么另起一个。"
292
+ ].join("\n");
293
+ /** The user half of the decision prompt (exported for smoke assertions). */
294
+ function buildCollectionDecisionPrompt(entry, candidates) {
295
+ const lines = candidates.map((candidate, index) => {
296
+ const tags = candidate.keywords.length ? ` |标签: ${candidate.keywords.join("、")}` : "";
297
+ const summary = candidate.summary ? ` |梗概: ${clip(candidate.summary, 200)}` : "";
298
+ return `${index + 1}. [${candidate.collectionId}] ${candidate.title}${tags}${summary}`;
299
+ });
300
+ return [
301
+ `候选记忆集合(按相关度预排序,共 ${candidates.length} 个):`,
302
+ ...lines,
303
+ "",
304
+ "待写入的记忆:",
305
+ `标题:${clip(entry.title ?? "", 48) || "(无)"}`,
306
+ `标签:${(entry.keywords ?? []).join("、") || "(无)"}`,
307
+ `正文:${clip(entry.summary ?? "", 400) || "(无)"}`,
308
+ "",
309
+ "判断这条记忆应归入哪个候选集合,还是新建集合。只返回 JSON。"
310
+ ].join("\n");
311
+ }
312
+ /**
313
+ * Validate one model answer. An unusable answer (no object, an id outside the
314
+ * candidate list, createNew without a title, neither branch) yields undefined
315
+ * so the caller degrades to the similarity heuristic.
316
+ */
317
+ function normalizeCollectionDecision(raw, candidates) {
318
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
319
+ const record = raw;
320
+ const reason = typeof record.reason === "string" ? record.reason.trim().slice(0, 120) : "";
321
+ const wanted = typeof record.collectionId === "string" ? record.collectionId.trim() : "";
322
+ if (wanted) {
323
+ const hit = candidates.find((candidate) => candidate.collectionId === wanted);
324
+ if (!hit) return void 0;
325
+ return {
326
+ kind: "reuse",
327
+ collectionId: hit.collectionId,
328
+ score: hit.score,
329
+ reason
330
+ };
331
+ }
332
+ if (record.createNew === true) {
333
+ const title = String(record.title ?? "").trim();
334
+ if (!title) return void 0;
335
+ return {
336
+ kind: "create",
337
+ title,
338
+ tags: normalizeTags(record.tags).slice(0, 8),
339
+ reason
340
+ };
341
+ }
342
+ }
343
+ /**
344
+ * One model call deciding where an entry goes. Returns undefined — caller keeps
345
+ * the heuristic — when there is no ctx/llm/route, the call fails or times out,
346
+ * or the answer is not a valid decision.
347
+ */
348
+ async function decideCollectionWithLlm(deps, entry, candidates) {
349
+ if (!deps?.ctx || candidates.length === 0) return void 0;
350
+ const answer = await askLlmJson({
351
+ ctx: deps.ctx,
352
+ logger: deps.logger,
353
+ sessionId: deps.sessionId
354
+ }, {
355
+ system: DECISION_SYSTEM,
356
+ user: buildCollectionDecisionPrompt(entry, candidates),
357
+ maxTokens: 400
358
+ });
359
+ if (answer === void 0) return void 0;
360
+ const decision = normalizeCollectionDecision(answer, candidates);
361
+ if (!decision) {
362
+ deps.logger?.warn("supermemory: collection decision answer was unusable; falling back to similarity");
363
+ return;
364
+ }
365
+ return decision;
366
+ }
367
+ /**
368
+ * 回执里的一句话集合归属说明(tools.ts 的 memory_remember 与 panel.ts 的
369
+ * createMemory 共用,保证两条写入路径同一套词汇)。title 为空(老存储域没有
370
+ * 集合表)时返回 null,调用方按「未归集」渲染。
371
+ */
372
+ function collectionTierNote(assignment) {
373
+ if (!assignment.title) return null;
374
+ if (assignment.created) return `新建记忆集合并写入:「${assignment.title}」${assignment.tier === "llm" ? "(模型判定)" : ""}`;
375
+ if (assignment.tier === "high") return `归入记忆集合「${assignment.title}」(高相似复用)`;
376
+ if (assignment.tier === "medium") return `归入相关记忆集合「${assignment.title}」(中等相似复用)`;
377
+ if (assignment.tier === "llm") return `归入记忆集合「${assignment.title}」(模型判定)`;
378
+ return `已写入指定记忆集合「${assignment.title}」`;
379
+ }
380
+ function clip(text, max) {
381
+ const value = String(text ?? "").trim();
382
+ return value.length <= max ? value : `${value.slice(0, Math.max(0, max - 1))}…`;
383
+ }
384
+ function newCollectionRecord(workspaceKey, title, keywords, summary, now) {
385
+ return {
386
+ workspaceKey,
387
+ title: clip(title, 48) || "记忆集合",
388
+ keywords: normalizeTags(keywords).slice(0, 12),
389
+ summary: clip(summary, 240),
390
+ status: "active",
391
+ createdAt: now,
392
+ updatedAt: now
393
+ };
394
+ }
395
+ async function putCollection(store, record) {
396
+ const id = newId("mc");
397
+ const table = store.memoryCollections;
398
+ if (!table) throw new Error("memory_collections 表不可用(存储域缺少该表)");
399
+ await table.put(id, record);
400
+ return id;
401
+ }
402
+ /**
403
+ * 为一条新条目决定归属集合(需求⑤:有相关集合就先加进去)。
404
+ *
405
+ * 决策顺序:
406
+ * 1. `collectionId` 显式指定:必须已存在,否则报错并列出候选;
407
+ * 2. `collection`(标题)显式指定:同名(忽略大小写/首尾空白)或相似度 ≥ 中等 → 复用,
408
+ * 否则以该标题新建集合;
409
+ * 3. 自动匹配(R27 需求④.3 起优先问模型):
410
+ * a. `options.deps.ctx` 可用且存在候选集合 → 让模型在候选里挑一个复用,或判定新建
411
+ * (一次调用;校验失败/无模型/超时都静默降级到 b);
412
+ * b. 相似度启发式:高/中相似 → 复用(回执里注明相似档位),低相似/无匹配 → 新建集合,
413
+ * 新集合标题 = 条目标题、标签 = 条目标签、正文 = 条目正文(截断),与话题集同形。
414
+ */
415
+ async function resolveCollectionForEntry(store, workspaceKey, entry, options = {}) {
416
+ const now = options.now ?? Date.now();
417
+ const shape = {
418
+ title: entry.title,
419
+ keywords: entry.keywords,
420
+ summary: entry.summary ?? entry.text
421
+ };
422
+ if (!store.memoryCollections) {
423
+ if (options.collectionId || options.collection && options.collection.trim()) return { error: "存储域缺少记忆集合表(memory_collections),无法写入指定集合。" };
424
+ return {
425
+ collectionId: "",
426
+ title: "",
427
+ tier: "low",
428
+ created: false,
429
+ explicit: false,
430
+ score: 0
431
+ };
432
+ }
433
+ const collections = listCollections(store, workspaceKey);
434
+ if (options.collectionId) {
435
+ const found = collections.find(([id]) => id === options.collectionId);
436
+ if (!found) {
437
+ const candidates = bestCollectionFor(shape, collections);
438
+ return {
439
+ error: `指定的记忆集合 ${options.collectionId} 不存在(或不属于当前工作区)。` + (candidates ? `最接近的是「${candidates.title}」。` : ""),
440
+ ...candidates ? { candidates: [candidates] } : {}
441
+ };
442
+ }
443
+ return {
444
+ collectionId: found[0],
445
+ title: found[1].title,
446
+ tier: "explicit",
447
+ created: false,
448
+ explicit: true,
449
+ score: 1
450
+ };
451
+ }
452
+ if (options.collection && options.collection.trim()) {
453
+ const wanted = options.collection.trim().toLowerCase();
454
+ const exact = collections.find(([, row]) => row.title.trim().toLowerCase() === wanted);
455
+ if (exact) return {
456
+ collectionId: exact[0],
457
+ title: exact[1].title,
458
+ tier: "explicit",
459
+ created: false,
460
+ explicit: true,
461
+ score: 1
462
+ };
463
+ const similar = bestCollectionFor({
464
+ ...shape,
465
+ title: options.collection
466
+ }, collections);
467
+ if (similar && similar.tier !== "low") return {
468
+ collectionId: similar.collectionId,
469
+ title: similar.title,
470
+ tier: "medium",
471
+ created: false,
472
+ explicit: true,
473
+ score: similar.score
474
+ };
475
+ const record = newCollectionRecord(workspaceKey, options.collection, shape.keywords ?? [], shape.summary ?? "", now);
476
+ return {
477
+ collectionId: await putCollection(store, record),
478
+ title: record.title,
479
+ tier: "explicit",
480
+ created: true,
481
+ explicit: true,
482
+ score: 1
483
+ };
484
+ }
485
+ const ranked = rankCollectionsFor(shape, collections);
486
+ if (ranked.length > 0) {
487
+ const decision = await decideCollectionWithLlm(options.deps, shape, ranked);
488
+ if (decision?.kind === "reuse") {
489
+ const found = collections.find(([id]) => id === decision.collectionId);
490
+ if (found) {
491
+ options.deps?.logger?.info?.(`supermemory: memory collection decided by model → ${found[1].title}${decision.reason ? ` (${decision.reason})` : ""}`);
492
+ return {
493
+ collectionId: found[0],
494
+ title: found[1].title,
495
+ tier: "llm",
496
+ created: false,
497
+ explicit: false,
498
+ score: decision.score
499
+ };
500
+ }
501
+ }
502
+ if (decision?.kind === "create") {
503
+ const record = newCollectionRecord(workspaceKey, decision.title, decision.tags.length > 0 ? decision.tags : shape.keywords ?? [], shape.summary ?? "", now);
504
+ const id = await putCollection(store, record);
505
+ options.deps?.logger?.info?.(`supermemory: memory collection created by model: ${record.title}${decision.reason ? ` (${decision.reason})` : ""}`);
506
+ return {
507
+ collectionId: id,
508
+ title: record.title,
509
+ tier: "llm",
510
+ created: true,
511
+ explicit: false,
512
+ score: 0
513
+ };
514
+ }
515
+ }
516
+ const match = bestCollectionFor(shape, collections);
517
+ if (match && match.tier !== "low") return {
518
+ collectionId: match.collectionId,
519
+ title: match.title,
520
+ tier: match.tier,
521
+ created: false,
522
+ explicit: false,
523
+ score: match.score
524
+ };
525
+ const record = newCollectionRecord(workspaceKey, shape.title ?? "", shape.keywords ?? [], shape.summary ?? "", now);
526
+ return {
527
+ collectionId: await putCollection(store, record),
528
+ title: record.title,
529
+ tier: match ? match.tier : "low",
530
+ created: true,
531
+ explicit: false,
532
+ score: match?.score ?? 0
533
+ };
534
+ }
535
+ /** Touch a collection's updatedAt (a new entry was appended). */
536
+ async function touchCollection(store, collectionId, now = Date.now()) {
537
+ const table = store.memoryCollections;
538
+ if (!table || typeof table.update !== "function") return;
539
+ if (!table.get(collectionId)) return;
540
+ await table.update(collectionId, (row) => ({
541
+ ...row,
542
+ updatedAt: now
543
+ }));
544
+ }
545
+ /** 迁移后条目的集合归属是否已失效(集合被删/跨工作区)。 */
546
+ function collectionIdValid(store, workspaceKey, memory) {
547
+ if (!memory.collectionId) return false;
548
+ return collectionRows(store).some(([id, row]) => id === memory.collectionId && row.workspaceKey === workspaceKey);
549
+ }
550
+ /** 标签重合(Jaccard)用于聚类:旧记录往往只有标签可用。 */
551
+ function jaccard(left, right) {
552
+ const a = new Set(normalizeTags(left).map((tag) => tag.toLowerCase()));
553
+ const b = new Set(normalizeTags(right).map((tag) => tag.toLowerCase()));
554
+ if (a.size === 0 || b.size === 0) return 0;
555
+ let inter = 0;
556
+ for (const tag of a) if (b.has(tag)) inter += 1;
557
+ return inter / (a.size + b.size - inter);
558
+ }
559
+ /** 聚类:共享标签(Jaccard ≥ 0.34)或标题 token 重合 ≥ 0.5 的旧条目归为一簇。 */
560
+ function clusterFlatMemories(flat) {
561
+ const clusters = [];
562
+ for (const [id, memory] of flat) {
563
+ const tags = normalizeTags(memory.keywords);
564
+ const titleTokens = tokenSet(memory.title);
565
+ let best = null;
566
+ for (const cluster of clusters) {
567
+ const tagScore = jaccard(tags, cluster.tags);
568
+ const titleScore = overlapRatio(titleTokens, cluster.titleTokens);
569
+ const score = Math.max(tagScore, titleScore);
570
+ if (score < .34) continue;
571
+ if (!best || score > best.score) best = {
572
+ cluster,
573
+ score
574
+ };
575
+ }
576
+ if (best) {
577
+ best.cluster.entries.push([id, memory]);
578
+ best.cluster.tags = normalizeTags([...best.cluster.tags, ...tags]);
579
+ for (const token of titleTokens) best.cluster.titleTokens.add(token);
580
+ continue;
581
+ }
582
+ clusters.push({
583
+ entries: [[id, memory]],
584
+ tags: [...tags],
585
+ titleTokens
586
+ });
587
+ }
588
+ return clusters;
589
+ }
590
+ /** 簇的集合标题:主导标签 + 「记忆」,无标签时用条目标题。 */
591
+ function clusterTitle(cluster) {
592
+ const tags = cluster.tags;
593
+ if (tags.length > 0) return `${tags[0]} 记忆`;
594
+ const first = cluster.entries[0]?.[1];
595
+ return deriveTitle(first?.title || first?.text || "", "记忆集合");
596
+ }
597
+ /**
598
+ * 惰性迁移:把当前工作区里「没有集合归属」的旧记忆按标签/标题聚类,补建集合并回写
599
+ * `collectionId`。只做加法(新建集合 + 补一个字段),**不删除、不改写正文/标题/标签**,
600
+ * 已有有效归属的条目直接跳过,所以可以安全地在每次 recall/remember/export 前调用。
601
+ */
602
+ async function migrateFlatMemories(store, workspaceKey, now = Date.now()) {
603
+ const table = store.memoryCollections;
604
+ if (!table) return {
605
+ collections: 0,
606
+ entries: 0
607
+ };
608
+ const flat = [];
609
+ for (const entry of store.memories.entries()) {
610
+ const [id, memory] = entry;
611
+ if (memory.workspaceKey !== workspaceKey) continue;
612
+ if (memory.status !== "active") continue;
613
+ if (collectionIdValid(store, workspaceKey, memory)) continue;
614
+ flat.push([id, memory]);
615
+ }
616
+ if (flat.length === 0) return {
617
+ collections: 0,
618
+ entries: 0
619
+ };
620
+ let created = 0;
621
+ let assigned = 0;
622
+ for (const cluster of clusterFlatMemories(flat)) {
623
+ const title = clusterTitle(cluster);
624
+ const keywords = normalizeTags(cluster.tags).slice(0, 12);
625
+ const summary = String(cluster.entries[0]?.[1].text ?? "").trim();
626
+ const existing = [...table.entries()].find(([, row]) => row.workspaceKey === workspaceKey && row.title === clip(title, 48));
627
+ let collectionId;
628
+ if (existing) collectionId = existing[0];
629
+ else {
630
+ collectionId = await putCollection(store, newCollectionRecord(workspaceKey, title, keywords, summary, now));
631
+ created += 1;
632
+ }
633
+ for (const [id] of cluster.entries) {
634
+ await store.memories.update?.(id, (row) => ({
635
+ ...row,
636
+ collectionId
637
+ }));
638
+ assigned += 1;
639
+ }
640
+ }
641
+ return {
642
+ collections: created,
643
+ entries: assigned
644
+ };
645
+ }
646
+ /**
647
+ * 同 key / 重复写入判定(`memory_remember` 的唯一实现,抽出来便于单测):
648
+ * 1. 同工作区、active、key 相同:
649
+ * - 正文相同 → duplicate(未重复写入);
650
+ * - 正文不同 → conflict(不覆盖,交用户裁决);
651
+ * 2. 无 key 时:同工作区 active 且正文相同 → duplicate。
652
+ * 返回时带上条目所属集合,回执可以说清「已存在于哪个集合」。
653
+ */
654
+ function findMemoryConflict(store, workspaceKey, input) {
655
+ const text = String(input.text ?? "").trim().toLowerCase();
656
+ const withCollection = (memoryId, memory) => {
657
+ const found = collectionOfEntry(store, memory);
658
+ return {
659
+ memoryId,
660
+ title: memory.title ?? "",
661
+ tags: [...memory.keywords ?? []],
662
+ text: memory.text,
663
+ ...found ? {
664
+ collectionId: found[0],
665
+ collectionTitle: found[1].title
666
+ } : {}
667
+ };
668
+ };
669
+ if (input.key) for (const [memoryId, memory] of store.memories.entries()) {
670
+ if (memory.workspaceKey !== workspaceKey || memory.status !== "active" || memory.key !== input.key) continue;
671
+ const same = String(memory.text ?? "").trim().toLowerCase() === text;
672
+ return {
673
+ ...withCollection(memoryId, memory),
674
+ kind: same ? "duplicate" : "conflict"
675
+ };
676
+ }
677
+ for (const [memoryId, memory] of store.memories.entries()) {
678
+ if (memory.workspaceKey !== workspaceKey || memory.status !== "active") continue;
679
+ if (String(memory.text ?? "").trim().toLowerCase() === text) return {
680
+ ...withCollection(memoryId, memory),
681
+ kind: "duplicate"
682
+ };
683
+ }
684
+ return null;
685
+ }
686
+ export { listCollections as a, resolveCollectionForEntry as c, findMemoryConflict as i, touchCollection as l, collectionRows as n, migrateFlatMemories as o, collectionTierNote as r, recallEntriesWithCollections as s, bestCollectionFor as t, askLlmJson as u };