@amemhq/core 1.0.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2353 @@
1
+ // src/auth.ts
2
+ var SYSTEM_ACTOR = "__amem_system__";
3
+ function canWrite(note, callerAgentId) {
4
+ return note.owner === callerAgentId || note.writers.includes(callerAgentId) || note.writers.includes("*");
5
+ }
6
+ function canRead(note, callerAgentId) {
7
+ return note.owner === callerAgentId || note.readers.includes(callerAgentId) || note.readers.includes("*");
8
+ }
9
+
10
+ // src/embedding.ts
11
+ var pipeline = null;
12
+ var extractor = null;
13
+ var loadedKey = null;
14
+ var cachedDim = null;
15
+ var DEFAULT_EMBEDDING_MODEL = "Xenova/bge-m3";
16
+ var LEGACY_DEFAULT_EMBEDDING_MODEL = "Xenova/paraphrase-multilingual-MiniLM-L12-v2";
17
+ var LEGACY_DEFAULT_DIM = 384;
18
+ var DEFAULT_MODEL_DTYPE = "fp16";
19
+ var pinnedModel = null;
20
+ function pinEmbeddingModel(model) {
21
+ if (pinnedModel === model) return;
22
+ pinnedModel = model;
23
+ extractor = null;
24
+ loadedKey = null;
25
+ cachedDim = null;
26
+ }
27
+ function getPinnedEmbeddingModel() {
28
+ return pinnedModel;
29
+ }
30
+ function getEmbeddingModel() {
31
+ return process.env.AMEM_EMBED_MODEL?.trim() || pinnedModel || DEFAULT_EMBEDDING_MODEL;
32
+ }
33
+ var CLS_POOLED_MODELS = /* @__PURE__ */ new Set([
34
+ "bge-m3",
35
+ "bge-base-zh-v1.5",
36
+ "bge-small-zh-v1.5",
37
+ "bge-base-en-v1.5",
38
+ "bge-small-en-v1.5",
39
+ "bge-large-en-v1.5",
40
+ "gte-multilingual-base",
41
+ "gte-modernbert-base",
42
+ "gte-large-en-v1.5",
43
+ "snowflake-arctic-embed-m",
44
+ "snowflake-arctic-embed-l"
45
+ ]);
46
+ function getEmbeddingPooling() {
47
+ const explicit = process.env.AMEM_EMBED_POOLING?.trim().toLowerCase();
48
+ if (explicit === "mean" || explicit === "cls") return explicit;
49
+ const basename = getEmbeddingModel().split("/").pop()?.toLowerCase() ?? "";
50
+ return CLS_POOLED_MODELS.has(basename) ? "cls" : "mean";
51
+ }
52
+ function getEmbeddingDevice() {
53
+ return process.env.AMEM_EMBED_DEVICE?.trim() || void 0;
54
+ }
55
+ function getEmbeddingDtype() {
56
+ const explicit = process.env.AMEM_EMBED_DTYPE?.trim();
57
+ if (explicit) return explicit;
58
+ return getEmbeddingModel() === DEFAULT_EMBEDDING_MODEL ? DEFAULT_MODEL_DTYPE : void 0;
59
+ }
60
+ function extractorKey() {
61
+ return `${getEmbeddingModel()}|${getEmbeddingDevice() ?? ""}|${getEmbeddingDtype() ?? ""}`;
62
+ }
63
+ async function getExtractor() {
64
+ const wanted = extractorKey();
65
+ if (extractor && loadedKey === wanted) return extractor;
66
+ if (!pipeline) {
67
+ const mod = await import("@huggingface/transformers");
68
+ pipeline = mod.pipeline;
69
+ }
70
+ const device = getEmbeddingDevice();
71
+ const dtype = getEmbeddingDtype();
72
+ extractor = await pipeline("feature-extraction", getEmbeddingModel(), {
73
+ revision: "main",
74
+ // Omitted entirely when unset, so an unconfigured install gets exactly the
75
+ // library defaults it got before these existed.
76
+ ...device ? { device } : {},
77
+ ...dtype ? { dtype } : {}
78
+ });
79
+ loadedKey = wanted;
80
+ cachedDim = null;
81
+ return extractor;
82
+ }
83
+ async function getEmbeddingDim() {
84
+ if (cachedDim !== null && loadedKey === extractorKey()) return cachedDim;
85
+ const probe = await encode("dimension probe");
86
+ cachedDim = probe.length;
87
+ return cachedDim;
88
+ }
89
+ function poolNormalize(output, attentionMask, mode) {
90
+ const seqLen = output.length;
91
+ const dim = output[0].length;
92
+ const pooled = new Array(dim).fill(0);
93
+ if (mode === "cls") {
94
+ for (let j = 0; j < dim; j++) pooled[j] = output[0][j];
95
+ } else {
96
+ let maskSum = 0;
97
+ for (let i = 0; i < seqLen; i++) {
98
+ const m = attentionMask[i];
99
+ maskSum += m;
100
+ for (let j = 0; j < dim; j++) {
101
+ pooled[j] += output[i][j] * m;
102
+ }
103
+ }
104
+ for (let j = 0; j < dim; j++) {
105
+ pooled[j] /= Math.max(maskSum, 1e-9);
106
+ }
107
+ }
108
+ let norm = 0;
109
+ for (const v of pooled) norm += v * v;
110
+ norm = Math.sqrt(norm);
111
+ return pooled.map((v) => v / Math.max(norm, 1e-9));
112
+ }
113
+ async function encode(text) {
114
+ const ext = await getExtractor();
115
+ const pooling = getEmbeddingPooling();
116
+ const result = await ext(text, { pooling, normalize: true });
117
+ if (result && result.data) {
118
+ return Array.from(result.data);
119
+ }
120
+ const tensor = result;
121
+ if (tensor.dims && tensor.dims.length === 3) {
122
+ const seqLen = tensor.dims[1];
123
+ const dim = tensor.dims[2];
124
+ const raw = [];
125
+ for (let i = 0; i < seqLen; i++) {
126
+ const row = [];
127
+ for (let j = 0; j < dim; j++) {
128
+ row.push(tensor.data[i * dim + j]);
129
+ }
130
+ raw.push(row);
131
+ }
132
+ return poolNormalize(raw, new Array(seqLen).fill(1), pooling);
133
+ }
134
+ throw new Error("Unexpected embedding output shape");
135
+ }
136
+ async function loadModel() {
137
+ await getExtractor();
138
+ }
139
+ function isModelLoaded() {
140
+ return extractor !== null;
141
+ }
142
+ function cosineSimilarity(a, b) {
143
+ let dot = 0;
144
+ for (let i = 0; i < a.length; i++) dot += a[i] * b[i];
145
+ return dot;
146
+ }
147
+
148
+ // src/storage.ts
149
+ var QDRANT_URL = "http://localhost:6333";
150
+ var getCollection = () => process.env.AMEM_COLLECTION || "amem_notes";
151
+ var EmbeddingDimensionMismatchError = class extends Error {
152
+ constructor(collection, collectionDim, modelDim, model) {
153
+ super(
154
+ `Collection "${collection}" stores ${collectionDim}-dimension vectors, but the embedding model "${model}" produces ${modelDim}. Qdrant fixes a collection's vector size at creation and cannot change it, so writes and searches would both fail.
155
+ Either set AMEM_EMBED_MODEL back to the model this collection was built with, or ${migrationHint(collection, model)}`
156
+ );
157
+ this.collection = collection;
158
+ this.collectionDim = collectionDim;
159
+ this.modelDim = modelDim;
160
+ this.model = model;
161
+ this.name = "EmbeddingDimensionMismatchError";
162
+ }
163
+ collection;
164
+ collectionDim;
165
+ modelDim;
166
+ model;
167
+ };
168
+ function migrationHint(collection, targetModel) {
169
+ return `migrate onto it:
170
+
171
+ AMEM_EMBED_MODEL=${targetModel} \\
172
+ npx --package=@amemhq/core amem-migrate --from-collection ${collection}
173
+
174
+ That only reports; it takes --apply to write anything, and "${collection}" is read either way. The new store ends up behind the name you already use, so there is nothing to change in your config afterwards. See https://amem.owo.lc/reference/embedding-models.`;
175
+ }
176
+ var EmbeddingModelMismatchError = class extends Error {
177
+ constructor(collection, collectionModel, configuredModel) {
178
+ super(
179
+ `Collection "${collection}" was built with the embedding model "${collectionModel}", but this process is configured for "${configuredModel}". Both produce vectors of the same width, so nothing would fail \u2014 searches would just quietly compare vectors from two different models.
180
+ Either set AMEM_EMBED_MODEL back to "${collectionModel}", or ` + migrationHint(collection, configuredModel)
181
+ );
182
+ this.collection = collection;
183
+ this.collectionModel = collectionModel;
184
+ this.configuredModel = configuredModel;
185
+ this.name = "EmbeddingModelMismatchError";
186
+ }
187
+ collection;
188
+ collectionModel;
189
+ configuredModel;
190
+ };
191
+ var MixedEmbeddingModelsError = class extends Error {
192
+ constructor(collection, wanted, inUse) {
193
+ super(
194
+ `Collection "${collection}" was built with "${wanted}", but this process is already embedding with "${inUse}" for another collection. One process can only use one model.
195
+ Migrate the remaining collections so they all agree:
196
+
197
+ npx --package=@amemhq/core amem-migrate --from-collection ${collection}
198
+
199
+ Or set AMEM_EMBED_MODEL to pin every collection to one model, which is only correct if they really were all built with it.`
200
+ );
201
+ this.collection = collection;
202
+ this.wanted = wanted;
203
+ this.inUse = inUse;
204
+ this.name = "MixedEmbeddingModelsError";
205
+ }
206
+ collection;
207
+ wanted;
208
+ inUse;
209
+ };
210
+ async function recordCollectionModel(collection, model) {
211
+ try {
212
+ await qdrant("PATCH", `/collections/${collection}`, { metadata: { embedding_model: model } });
213
+ } catch {
214
+ }
215
+ }
216
+ async function qdrant(method, path4, body) {
217
+ const res = await fetch(`${QDRANT_URL}${path4}`, {
218
+ method,
219
+ headers: { "Content-Type": "application/json" },
220
+ body: body ? JSON.stringify(body) : void 0
221
+ });
222
+ const data = await res.json();
223
+ if (!res.ok || data.status && data.status !== "ok" && data.status !== "acknowledged") {
224
+ throw new Error(`Qdrant ${method} ${path4} failed: ${data.error || JSON.stringify(data)}`);
225
+ }
226
+ return data.result;
227
+ }
228
+ async function pingQdrant() {
229
+ const res = await fetch(`${QDRANT_URL}/readyz`);
230
+ if (!res.ok) throw new Error(`Qdrant GET /readyz failed: ${res.status}`);
231
+ }
232
+ var _collectionReady = false;
233
+ var _collectionReadyMap = /* @__PURE__ */ new Map();
234
+ async function ensureCollection(collectionName) {
235
+ const col = collectionName || getCollection();
236
+ if (collectionName) {
237
+ if (_collectionReadyMap.get(col)) return;
238
+ } else {
239
+ if (_collectionReady) return;
240
+ }
241
+ const markReady = () => {
242
+ if (collectionName) _collectionReadyMap.set(col, true);
243
+ else _collectionReady = true;
244
+ };
245
+ let existing = null;
246
+ try {
247
+ existing = await qdrant("GET", `/collections/${col}`);
248
+ } catch {
249
+ }
250
+ if (existing) {
251
+ const collectionDim = existing.config?.params?.vectors?.size;
252
+ const recorded = existing.config?.metadata?.embedding_model;
253
+ const explicit = process.env.AMEM_EMBED_MODEL?.trim();
254
+ const inferLegacy = !explicit && recorded === void 0 && collectionDim === LEGACY_DEFAULT_DIM;
255
+ if (!explicit) {
256
+ const wanted = (
257
+ // The collection says what built it, which outranks whatever the shipped
258
+ // default happens to be today. This is what keeps changing the default
259
+ // from breaking every install that already has data.
260
+ typeof recorded === "string" ? recorded : inferLegacy ? LEGACY_DEFAULT_EMBEDDING_MODEL : DEFAULT_EMBEDDING_MODEL
261
+ );
262
+ const inUse = getPinnedEmbeddingModel();
263
+ if (inUse !== null && inUse !== wanted) throw new MixedEmbeddingModelsError(col, wanted, inUse);
264
+ pinEmbeddingModel(wanted);
265
+ if (wanted === LEGACY_DEFAULT_EMBEDDING_MODEL) {
266
+ console.warn(
267
+ `[amem] "${col}" is on ${LEGACY_DEFAULT_EMBEDDING_MODEL} (${LEGACY_DEFAULT_DIM}-dim).
268
+ [amem] ${DEFAULT_EMBEDDING_MODEL} reads 8192 tokens where that one stops at 128, so anything longer is being truncated before it reaches the vector.
269
+ [amem] To move: npx --package=@amemhq/core amem-migrate --from-collection ${col}`
270
+ );
271
+ }
272
+ }
273
+ if (typeof collectionDim === "number") {
274
+ const modelDim = await getEmbeddingDim();
275
+ if (collectionDim !== modelDim) {
276
+ throw new EmbeddingDimensionMismatchError(col, collectionDim, modelDim, getEmbeddingModel());
277
+ }
278
+ }
279
+ const current = getEmbeddingModel();
280
+ if (typeof recorded === "string" && recorded !== current) {
281
+ throw new EmbeddingModelMismatchError(col, recorded, current);
282
+ }
283
+ if (recorded === void 0 && !inferLegacy) {
284
+ await recordCollectionModel(col, current);
285
+ }
286
+ markReady();
287
+ return;
288
+ }
289
+ try {
290
+ const size = await getEmbeddingDim();
291
+ await qdrant("PUT", `/collections/${col}`, {
292
+ vectors: { size, distance: "Cosine" }
293
+ });
294
+ } catch (err) {
295
+ if (!(err instanceof Error) || !err.message.includes("already exists")) throw err;
296
+ }
297
+ const created = getEmbeddingModel();
298
+ await recordCollectionModel(col, created);
299
+ if (!process.env.AMEM_EMBED_MODEL?.trim()) pinEmbeddingModel(created);
300
+ await qdrant("PUT", `/collections/${col}/index`, {
301
+ field_name: "agent_id",
302
+ field_schema: "keyword"
303
+ });
304
+ await qdrant("PUT", `/collections/${col}/index`, {
305
+ field_name: "hash",
306
+ field_schema: "keyword"
307
+ });
308
+ await qdrant("PUT", `/collections/${col}/index`, {
309
+ field_name: "topics",
310
+ field_schema: "keyword"
311
+ });
312
+ await qdrant("PUT", `/collections/${col}/index`, {
313
+ field_name: "subjects",
314
+ field_schema: "keyword"
315
+ });
316
+ markReady();
317
+ }
318
+ async function scrollAllRaw(collection, limit = 1e4) {
319
+ const out = [];
320
+ let offset = void 0;
321
+ for (; ; ) {
322
+ const body = { with_payload: true, with_vector: true, limit };
323
+ if (offset !== void 0 && offset !== null) body.offset = offset;
324
+ const res = await qdrant("POST", `/collections/${collection}/points/scroll`, body);
325
+ out.push(...res.points);
326
+ offset = res.next_page_offset;
327
+ if (offset === void 0 || offset === null || res.points.length === 0) break;
328
+ }
329
+ return out;
330
+ }
331
+ async function countPointsRaw(collection) {
332
+ const res = await qdrant("POST", `/collections/${collection}/points/count`, { exact: true });
333
+ return res.count;
334
+ }
335
+ async function collectionDimRaw(collection) {
336
+ try {
337
+ const info = await qdrant("GET", `/collections/${collection}`);
338
+ return info.config?.params?.vectors?.size ?? null;
339
+ } catch {
340
+ return null;
341
+ }
342
+ }
343
+ async function createCollectionRaw(collection, size) {
344
+ await qdrant("PUT", `/collections/${collection}`, { vectors: { size, distance: "Cosine" } });
345
+ await recordCollectionModel(collection, getEmbeddingModel());
346
+ for (const field_name of ["agent_id", "hash", "topics", "subjects"]) {
347
+ await qdrant("PUT", `/collections/${collection}/index`, { field_name, field_schema: "keyword" });
348
+ }
349
+ }
350
+ async function upsertPointsRaw(collection, points) {
351
+ await qdrant("PUT", `/collections/${collection}/points?wait=true`, { points });
352
+ }
353
+ async function scrollIdsRaw(collection, limit = 1e4) {
354
+ const ids = /* @__PURE__ */ new Set();
355
+ let offset = void 0;
356
+ for (; ; ) {
357
+ const body = { with_payload: false, with_vector: false, limit };
358
+ if (offset !== void 0 && offset !== null) body.offset = offset;
359
+ const res = await qdrant("POST", `/collections/${collection}/points/scroll`, body);
360
+ for (const p of res.points) ids.add(String(p.id));
361
+ offset = res.next_page_offset;
362
+ if (offset === void 0 || offset === null || res.points.length === 0) break;
363
+ }
364
+ return ids;
365
+ }
366
+ async function deleteCollectionRaw(collection) {
367
+ await qdrant("DELETE", `/collections/${collection}`);
368
+ }
369
+ async function resolveAliasRaw(alias) {
370
+ try {
371
+ const res = await qdrant("GET", `/aliases`);
372
+ return res.aliases.find((a) => a.alias_name === alias)?.collection_name ?? null;
373
+ } catch {
374
+ return null;
375
+ }
376
+ }
377
+ async function createAliasRaw(alias, collection) {
378
+ await qdrant("POST", `/collections/aliases`, {
379
+ actions: [{ create_alias: { collection_name: collection, alias_name: alias } }]
380
+ });
381
+ }
382
+ async function setAliasRaw(alias, collection) {
383
+ await qdrant("POST", `/collections/aliases`, {
384
+ actions: [
385
+ { delete_alias: { alias_name: alias } },
386
+ { create_alias: { collection_name: collection, alias_name: alias } }
387
+ ]
388
+ });
389
+ }
390
+ function noteToPoint(note) {
391
+ return {
392
+ id: note.id,
393
+ vector: note.embedding,
394
+ payload: {
395
+ content: note.content,
396
+ keywords: note.keywords,
397
+ tags: note.tags,
398
+ context: note.context,
399
+ links: note.links,
400
+ timestamp: note.timestamp,
401
+ agent_id: note.agent_id,
402
+ hash: note.hash,
403
+ // 13-A
404
+ retrieval_count: note.retrieval_count ?? 0,
405
+ last_accessed: note.last_accessed || note.timestamp,
406
+ // 13-B: stored as JSON string (Qdrant payload can't handle nested array-of-objects)
407
+ evolution_history: JSON.stringify(note.evolution_history ?? []),
408
+ // 13-E
409
+ category: note.category || "General",
410
+ is_active: note.is_active !== false,
411
+ // 26B
412
+ topics: note.topics ?? [],
413
+ // 26A
414
+ note_type: note.note_type || "memory",
415
+ // 29
416
+ pending_merge: note.pending_merge ?? false,
417
+ // 30
418
+ evolution_type: note.evolution_type || "",
419
+ conflict: note.conflict ?? false,
420
+ conflicts_with: note.conflicts_with ?? [],
421
+ conflict_reason: note.conflict_reason ?? "",
422
+ conflict_scanned_at: note.conflict_scanned_at ?? "",
423
+ subjects: note.subjects ?? [],
424
+ // 31
425
+ ephemeral: note.ephemeral ?? false,
426
+ low_quality: note.low_quality ?? false,
427
+ // 32
428
+ owner: note.owner || note.agent_id,
429
+ readers: note.readers ?? [note.agent_id],
430
+ writers: note.writers ?? [note.agent_id]
431
+ }
432
+ };
433
+ }
434
+ function pointToNote(point) {
435
+ const p = point.payload;
436
+ const timestamp = p.timestamp || "";
437
+ let evolutionHistory = [];
438
+ try {
439
+ const raw = p.evolution_history;
440
+ if (typeof raw === "string" && raw.length > 0) {
441
+ evolutionHistory = JSON.parse(raw);
442
+ } else if (Array.isArray(raw)) {
443
+ evolutionHistory = raw;
444
+ }
445
+ } catch {
446
+ evolutionHistory = [];
447
+ }
448
+ return {
449
+ id: String(point.id),
450
+ content: p.content || "",
451
+ keywords: p.keywords || [],
452
+ tags: p.tags || [],
453
+ context: p.context || "",
454
+ links: p.links || [],
455
+ timestamp,
456
+ agent_id: p.agent_id || "main",
457
+ embedding: point.vector || [],
458
+ hash: p.hash || "",
459
+ // 13-A
460
+ retrieval_count: typeof p.retrieval_count === "number" ? p.retrieval_count : 0,
461
+ last_accessed: p.last_accessed || timestamp,
462
+ // 13-B
463
+ evolution_history: evolutionHistory,
464
+ // 13-E
465
+ category: p.category || "General",
466
+ is_active: p.is_active !== false,
467
+ // 26A
468
+ note_type: p.note_type === "knowledge" ? "knowledge" : "memory",
469
+ // 26B
470
+ topics: Array.isArray(p.topics) ? p.topics : [],
471
+ // 29
472
+ pending_merge: p.pending_merge === true,
473
+ // 30
474
+ evolution_type: typeof p.evolution_type === "string" && ["EVOLVE", "CONFLICT", "EXPAND", "NEW"].includes(p.evolution_type) ? p.evolution_type : void 0,
475
+ conflict: p.conflict === true,
476
+ conflicts_with: Array.isArray(p.conflicts_with) ? p.conflicts_with.filter((v) => typeof v === "string") : [],
477
+ conflict_reason: typeof p.conflict_reason === "string" ? p.conflict_reason : "",
478
+ conflict_scanned_at: typeof p.conflict_scanned_at === "string" ? p.conflict_scanned_at : "",
479
+ subjects: Array.isArray(p.subjects) ? p.subjects.filter((v) => typeof v === "string") : [],
480
+ // 31
481
+ ephemeral: p.ephemeral === true,
482
+ low_quality: p.low_quality === true,
483
+ // 32
484
+ owner: p.owner || p.agent_id || "main",
485
+ readers: Array.isArray(p.readers) ? p.readers : [p.agent_id || "main"],
486
+ writers: Array.isArray(p.writers) ? p.writers : [p.agent_id || "main"]
487
+ };
488
+ }
489
+ function agentFilter(agentId, subject) {
490
+ const must = [
491
+ {
492
+ should: [
493
+ { key: "agent_id", match: { value: agentId } },
494
+ { key: "agent_id", match: { value: "shared" } }
495
+ ]
496
+ }
497
+ ];
498
+ if (subject !== void 0) {
499
+ must.push({
500
+ should: [{ key: "subjects", match: { value: subject } }, { is_empty: { key: "subjects" } }]
501
+ });
502
+ }
503
+ return {
504
+ must,
505
+ must_not: [{ key: "is_active", match: { value: false } }]
506
+ };
507
+ }
508
+ function makeCrud(collectionName, modeBIsolated = false) {
509
+ const col = collectionName;
510
+ function scopedAgentFilter(agentId, subject) {
511
+ if (modeBIsolated) {
512
+ const must = [];
513
+ if (subject !== void 0) {
514
+ must.push({
515
+ should: [{ key: "subjects", match: { value: subject } }, { is_empty: { key: "subjects" } }]
516
+ });
517
+ }
518
+ return {
519
+ ...must.length > 0 && { must },
520
+ must_not: [{ key: "is_active", match: { value: false } }]
521
+ };
522
+ }
523
+ return agentFilter(agentId, subject);
524
+ }
525
+ return {
526
+ async addNote(note) {
527
+ await ensureCollection(col);
528
+ await qdrant("PUT", `/collections/${col}/points?wait=true`, {
529
+ points: [noteToPoint(note)]
530
+ });
531
+ },
532
+ /**
533
+ * Story 36: this is the one read that bypasses the agent filter — it fetches
534
+ * straight by UUID. An unreadable note comes back as `null`, indistinguishable
535
+ * from missing, so nothing leaks and callers already handle it.
536
+ *
537
+ * `reader` is required. It used to be optional, and omitting it skipped the
538
+ * check — which meant the safe behaviour was the one you had to remember to
539
+ * ask for. Pass `SYSTEM_ACTOR` to read as the engine itself; that reads as a
540
+ * deliberate act at the call site, where an absent argument did not.
541
+ */
542
+ async getNote(id, reader) {
543
+ await ensureCollection(col);
544
+ try {
545
+ const result = await qdrant("POST", `/collections/${col}/points`, {
546
+ ids: [id],
547
+ with_payload: true,
548
+ with_vector: true
549
+ });
550
+ if (!result.length) return null;
551
+ const note = pointToNote(result[0]);
552
+ if (reader !== SYSTEM_ACTOR && !canRead(note, reader)) return null;
553
+ return note;
554
+ } catch {
555
+ return null;
556
+ }
557
+ },
558
+ async updateNote(note) {
559
+ await ensureCollection(col);
560
+ await qdrant("PUT", `/collections/${col}/points?wait=true`, {
561
+ points: [noteToPoint(note)]
562
+ });
563
+ },
564
+ async findByHash(hash, agentId) {
565
+ await ensureCollection(col);
566
+ const body = {
567
+ filter: {
568
+ must: [
569
+ { key: "hash", match: { value: hash } },
570
+ { key: "is_active", match: { value: true } },
571
+ ...modeBIsolated ? [] : [
572
+ {
573
+ should: [
574
+ { key: "agent_id", match: { value: agentId } },
575
+ { key: "agent_id", match: { value: "shared" } }
576
+ ]
577
+ }
578
+ ]
579
+ ]
580
+ },
581
+ with_payload: true,
582
+ with_vector: true,
583
+ limit: 1
584
+ };
585
+ const result = await qdrant("POST", `/collections/${col}/points/scroll`, body);
586
+ if (!result.points.length) return null;
587
+ return pointToNote(result.points[0]);
588
+ },
589
+ /**
590
+ * Story 33: enforces the writers policy. Returns false — without writing —
591
+ * when the caller may not write. This fetch-then-check path exists for callers
592
+ * that only have an id (the plugin's CRUD hook); callers already holding the
593
+ * note can check `canWrite` themselves and skip a round trip.
594
+ *
595
+ * `caller` is required. Pass `SYSTEM_ACTOR` for the engine's own maintenance
596
+ * writes. The self-read below is a genuine `SYSTEM_ACTOR` case: it fetches the
597
+ * note in order to decide whether the caller may write it, and gating that
598
+ * fetch on the same policy it exists to evaluate would be circular.
599
+ */
600
+ async updateNoteContent(id, content, embedding, hash, caller) {
601
+ await ensureCollection(col);
602
+ let existing = null;
603
+ if (caller !== SYSTEM_ACTOR) {
604
+ existing = await this.getNote(id, SYSTEM_ACTOR);
605
+ if (existing && !canWrite(existing, caller)) return false;
606
+ }
607
+ await qdrant("PUT", `/collections/${col}/points/vectors?wait=true`, {
608
+ points: [{ id, vector: embedding }]
609
+ });
610
+ const payload = { content, hash };
611
+ if (existing) {
612
+ const history = [
613
+ ...existing.evolution_history ?? [],
614
+ {
615
+ triggeredBy: "",
616
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
617
+ oldContext: existing.context,
618
+ newContext: existing.context,
619
+ oldTags: existing.tags,
620
+ newTags: existing.tags,
621
+ action: "crud_update",
622
+ oldContent: existing.content
623
+ }
624
+ ];
625
+ payload.evolution_history = JSON.stringify(history);
626
+ }
627
+ await qdrant("POST", `/collections/${col}/points/payload?wait=true`, {
628
+ payload,
629
+ points: [id]
630
+ });
631
+ return true;
632
+ },
633
+ async queryByEmbedding(embedding, topK, agentId, scoreThreshold = 0, subject) {
634
+ await ensureCollection(col);
635
+ const result = await qdrant("POST", `/collections/${col}/points/search`, {
636
+ vector: embedding,
637
+ limit: topK,
638
+ with_payload: true,
639
+ with_vector: true,
640
+ score_threshold: scoreThreshold,
641
+ filter: scopedAgentFilter(agentId, subject)
642
+ });
643
+ const queryResults = result.map((r) => ({
644
+ note: pointToNote(r),
645
+ score: r.score
646
+ }));
647
+ if (queryResults.length > 0) {
648
+ const now = (/* @__PURE__ */ new Date()).toISOString();
649
+ const ids = queryResults.map((r) => r.note.id);
650
+ const patches = queryResults.map((r) => ({
651
+ id: r.note.id,
652
+ retrieval_count: (r.note.retrieval_count || 0) + 1
653
+ }));
654
+ Promise.all([
655
+ qdrant("POST", `/collections/${col}/points/payload?wait=false`, {
656
+ payload: { last_accessed: now },
657
+ points: ids
658
+ }),
659
+ ...patches.map(
660
+ (p) => qdrant("POST", `/collections/${col}/points/payload?wait=false`, {
661
+ payload: { retrieval_count: p.retrieval_count },
662
+ points: [p.id]
663
+ })
664
+ )
665
+ ]).catch((err) => {
666
+ console.error(`[amem] retrieval tracking patch failed: ${err.message}`);
667
+ });
668
+ for (const r of queryResults) {
669
+ r.note.retrieval_count = (r.note.retrieval_count || 0) + 1;
670
+ r.note.last_accessed = now;
671
+ }
672
+ }
673
+ return queryResults;
674
+ },
675
+ async listNotes(agentId, subject) {
676
+ await ensureCollection(col);
677
+ const body = {
678
+ with_payload: true,
679
+ with_vector: true,
680
+ limit: 1e4
681
+ };
682
+ if (agentId) body.filter = scopedAgentFilter(agentId, subject);
683
+ const result = await qdrant("POST", `/collections/${col}/points/scroll`, body);
684
+ return result.points.map(pointToNote);
685
+ },
686
+ async deleteNote(id) {
687
+ await ensureCollection(col);
688
+ await qdrant("POST", `/collections/${col}/points/delete`, {
689
+ points: [id]
690
+ });
691
+ },
692
+ /** Story 33: see `updateNoteContent` — returns false, unwritten, when denied. */
693
+ async invalidateNote(id, caller) {
694
+ await ensureCollection(col);
695
+ if (caller !== SYSTEM_ACTOR) {
696
+ const existing = await this.getNote(id, SYSTEM_ACTOR);
697
+ if (existing && !canWrite(existing, caller)) return false;
698
+ }
699
+ await qdrant("POST", `/collections/${col}/points/payload?wait=true`, {
700
+ payload: { is_active: false },
701
+ points: [id]
702
+ });
703
+ return true;
704
+ },
705
+ async getNotesByDatePrefix(datePrefix, agentId) {
706
+ await ensureCollection(col);
707
+ const filterClauses = [{ key: "is_active", match: { value: true } }];
708
+ if (!modeBIsolated) {
709
+ filterClauses.push({
710
+ should: [
711
+ { key: "agent_id", match: { value: agentId } },
712
+ { key: "agent_id", match: { value: "shared" } }
713
+ ]
714
+ });
715
+ }
716
+ const body = {
717
+ filter: { must: filterClauses },
718
+ with_payload: true,
719
+ with_vector: true,
720
+ limit: 1e4
721
+ };
722
+ const result = await qdrant("POST", `/collections/${col}/points/scroll`, body);
723
+ return result.points.map(pointToNote).filter((n) => n.timestamp.startsWith(datePrefix));
724
+ },
725
+ async countNotes(agentId) {
726
+ await ensureCollection(col);
727
+ const body = { exact: true };
728
+ if (agentId) body.filter = scopedAgentFilter(agentId);
729
+ const result = await qdrant("POST", `/collections/${col}/points/count`, body);
730
+ return result.count;
731
+ },
732
+ async updateNoteLinks(id, links) {
733
+ await ensureCollection(col);
734
+ await qdrant("POST", `/collections/${col}/points/payload?wait=true`, {
735
+ payload: { links },
736
+ points: [id]
737
+ });
738
+ },
739
+ async patchNotePayload(id, fields) {
740
+ await ensureCollection(col);
741
+ await qdrant("POST", `/collections/${col}/points/payload?wait=true`, {
742
+ payload: fields,
743
+ points: [id]
744
+ });
745
+ },
746
+ async replaceLinkReferences(oldId, newId, agentId) {
747
+ const notes = await this.listNotes(agentId);
748
+ for (const note of notes) {
749
+ if (!canWrite(note, agentId)) continue;
750
+ if (note.links.includes(oldId)) {
751
+ const newLinks = note.links.map((linkId) => linkId === oldId ? newId : linkId);
752
+ const filteredLinks = newLinks.filter((linkId) => linkId !== note.id);
753
+ const uniqueLinks = Array.from(new Set(filteredLinks));
754
+ await this.updateNoteLinks(note.id, uniqueLinks);
755
+ }
756
+ }
757
+ }
758
+ };
759
+ }
760
+ function createStorageContext(collectionName, modeBIsolated = false) {
761
+ return makeCrud(collectionName || getCollection(), modeBIsolated);
762
+ }
763
+ async function getNote(id, reader) {
764
+ return makeCrud(getCollection()).getNote(id, reader);
765
+ }
766
+ async function updateNote(note) {
767
+ return makeCrud(getCollection()).updateNote(note);
768
+ }
769
+ async function listNotes(agentId, subject) {
770
+ return makeCrud(getCollection()).listNotes(agentId, subject);
771
+ }
772
+ async function deleteNote(id) {
773
+ return makeCrud(getCollection()).deleteNote(id);
774
+ }
775
+ async function invalidateNote(id, caller) {
776
+ return makeCrud(getCollection()).invalidateNote(id, caller);
777
+ }
778
+ async function patchNotePayload(id, fields) {
779
+ return makeCrud(getCollection()).patchNotePayload(id, fields);
780
+ }
781
+
782
+ // src/llm.ts
783
+ import Anthropic from "@anthropic-ai/sdk";
784
+ import OpenAI from "openai";
785
+
786
+ // src/prompts.ts
787
+ var LOCALE = process.env.AMEM_PROMPT_LOCALE === "zh" ? "zh" : "en";
788
+ var en = {
789
+ crudDecision: (userText, assistantText, memoryList) => `You are a memory management agent. Analyze the conversation and decide what memory operations are needed.
790
+
791
+ ## Conversation
792
+
793
+ User: ${userText}
794
+ Assistant: ${assistantText}
795
+
796
+ ## Existing relevant memories (identified by integer idx)
797
+
798
+ ${memoryList}
799
+
800
+ ## Task
801
+
802
+ Extract only genuinely important long-term facts (decisions, preferences, account info, project status, key insights). Skip small talk, confirmations, and information already captured in existing memories.
803
+
804
+ ## Operation types
805
+ - NEW: Extract a brand new fact not present in existing memories
806
+ - UPDATE: New information refines or supersedes an existing memory; specify existingIdx
807
+ - DELETE: An existing memory is outdated, contradicted, or wrong; specify existingIdx, fact = original content
808
+ - NONE: Nothing worth recording, or information already fully captured
809
+
810
+ ## Output format
811
+
812
+ Return a JSON array. Each item:
813
+ {"action": "NEW"|"UPDATE"|"DELETE"|"NONE", "fact": "fact content", "existingIdx": integer or omit, "reason": "optional"}
814
+
815
+ Return at most 3 operations. If nothing is worth recording, return [].
816
+ Return only the JSON array, no other text.
817
+
818
+ Examples:
819
+
820
+ 1. New preference:
821
+ [{"action": "NEW", "fact": "User prefers TypeScript over JavaScript", "reason": "Explicitly stated tech preference"}]
822
+
823
+ 2. Updating an existing memory (idx 0 was "User is evaluating React and Vue"):
824
+ [{"action": "UPDATE", "fact": "User decided to use React (dropped Vue)", "existingIdx": 0, "reason": "Decision finalized, update evaluation status"}]
825
+
826
+ 3. Conversation is just "Sure, thanks" / "Got it" with no new info:
827
+ []`,
828
+ shouldMerge: (contentA, contentB) => `You are a memory deduplication assistant. Determine whether two memories express essentially the same information.
829
+
830
+ Memory A: ${contentA}
831
+ Memory B: ${contentB}
832
+
833
+ Rules:
834
+ - If both memories express the same core fact (possibly different wording or granularity), return:
835
+ {"shouldMerge": true, "merged": "Concise merged statement preserving key details from both, more complete than either alone"}
836
+ - If the memories are complementary, on different topics, or contain different specific facts, return:
837
+ {"shouldMerge": false}
838
+
839
+ Return only JSON, no other text.
840
+
841
+ Examples:
842
+
843
+ 1. Should merge (different granularity):
844
+ A: "Project uses PostgreSQL"
845
+ B: "Project's primary database is PostgreSQL 16, deployed on AWS RDS"
846
+ -> {"shouldMerge": true, "merged": "Project uses PostgreSQL 16 as primary database, deployed on AWS RDS"}
847
+
848
+ 2. Should NOT merge (complementary but distinct):
849
+ A: "User prefers VS Code"
850
+ B: "User's VS Code uses One Dark Pro theme"
851
+ -> {"shouldMerge": false}`,
852
+ evolutionJudge: (oldContent, newContent) => `You are a memory evolution judge. Analyze the relationship between an old and new memory and return JSON.
853
+
854
+ Old memory: ${oldContent}
855
+ New memory: ${newContent}
856
+
857
+ Classification rules:
858
+
859
+ - EVOLVE: New content deepens or updates the old memory (e.g. "Considering Next.js" -> "Decided on Next.js 14 App Router")
860
+ Return: {"type": "EVOLVE", "mergedContent": "Merged content preserving the evolution trajectory"}
861
+
862
+ - CONFLICT: Old and new information directly contradict each other on the same attribute (e.g. "Uses MySQL as primary DB" vs "Migrated to PostgreSQL")
863
+ Return: {"type": "CONFLICT"}
864
+
865
+ - EXPAND: New information supplements the old memory on the same topic (e.g. "Handles backend dev" + "Backend uses Go and gRPC")
866
+ Return: {"type": "EXPAND", "mergedContent": "Merged content integrating both pieces of information"}
867
+
868
+ - NEW: Completely unrelated information, no substantive connection to the old memory
869
+ Return: {"type": "NEW"}
870
+
871
+ Return only JSON, no other text.`,
872
+ conflictScan: (numberedNotes) => `You are auditing a person's memory store for CONTRADICTIONS.
873
+
874
+ Below are numbered memories. Find pairs that CANNOT both be true of the same person at the same time.
875
+
876
+ ${numberedNotes}
877
+
878
+ What counts as a contradiction:
879
+ - The same attribute holding two incompatible values ("lives in Paris" vs "moved to Berlin")
880
+ - A stated preference or constraint that a later memory violates ("is vegetarian" vs "loved the steak")
881
+ - A fact that a later memory supersedes ("uses MySQL" vs "migrated to PostgreSQL")
882
+
883
+ What does NOT count \u2014 be strict, these are the common false positives:
884
+ - Additive facts. Two things can both be true ("has a dog named Buddy" + "adopted a second dog, Scout" is NOT a contradiction)
885
+ - Change over time that both memories already acknowledge
886
+ - Merely similar or related topics
887
+ - Different contexts (likes coffee at work, tea at home)
888
+
889
+ For each contradicting pair, also say which one is SUPERSEDED \u2014 the one that is
890
+ no longer true. Judge this from the WORDING, not from any assumed order: phrases
891
+ like "used to", "back in 2019", "moved last month", "switched to" tell you which
892
+ statement describes the past. The memories are NOT listed in chronological order,
893
+ and the number does not imply age.
894
+
895
+ If you cannot tell which one is superseded, set it to null. That is a normal and
896
+ useful answer \u2014 say null rather than guessing, because a wrong guess retires a
897
+ memory that is still true.
898
+
899
+ Return ONLY a JSON array. Empty array if nothing genuinely contradicts:
900
+ [{"a": 0, "b": 3, "superseded": 0, "reason": "one short sentence naming the incompatible attribute"}]
901
+
902
+ "superseded" must be either the value of "a", the value of "b", or null.
903
+ Use the numbers shown. Report a pair once. Prefer returning nothing over guessing.`
904
+ };
905
+ var zh = {
906
+ crudDecision: (userText, assistantText, memoryList) => `\u4F60\u662F\u4E00\u4E2A\u8BB0\u5FC6\u7BA1\u7406 agent\uFF0C\u8D1F\u8D23\u5206\u6790\u5BF9\u8BDD\u5185\u5BB9\u5E76\u51B3\u5B9A\u5982\u4F55\u64CD\u4F5C\u8BB0\u5FC6\u5E93\u3002
907
+
908
+ ## \u5BF9\u8BDD\u5185\u5BB9
909
+
910
+ \u7528\u6237\uFF1A${userText}
911
+ \u52A9\u624B\uFF1A${assistantText}
912
+
913
+ ## \u5DF2\u6709\u76F8\u5173\u8BB0\u5FC6\uFF08\u7528\u6574\u6570 idx \u6807\u8BC6\uFF09
914
+
915
+ ${memoryList}
916
+
917
+ ## \u4EFB\u52A1
918
+
919
+ \u5206\u6790\u4E0A\u8FF0\u5BF9\u8BDD\uFF0C\u51B3\u5B9A\u9700\u8981\u54EA\u4E9B\u8BB0\u5FC6\u64CD\u4F5C\u3002\u53EA\u63D0\u53D6\u771F\u6B63\u91CD\u8981\u7684\u957F\u671F\u4E8B\u5B9E\uFF08\u51B3\u7B56\u3001\u504F\u597D\u3001\u8D26\u53F7\u4FE1\u606F\u3001\u9879\u76EE\u72B6\u6001\u3001\u5173\u952E\u6D1E\u5BDF\uFF09\u3002\u8DF3\u8FC7\u95F2\u804A\u3001\u786E\u8BA4\u8BED\u3001\u91CD\u590D\u4FE1\u606F\u3002
920
+
921
+ ## \u64CD\u4F5C\u7C7B\u578B
922
+ - NEW\uFF1A\u63D0\u53D6\u5168\u65B0\u4E8B\u5B9E\uFF08\u5DF2\u6709\u8BB0\u5FC6\u4E2D\u6CA1\u6709\u7684\u4FE1\u606F\uFF09
923
+ - UPDATE\uFF1A\u65B0\u4FE1\u606F\u66F4\u65B0\u4E86\u67D0\u6761\u5DF2\u6709\u8BB0\u5FC6\uFF0C\u7528 existingIdx \u6307\u5B9A\u8981\u66F4\u65B0\u7684\u6761\u76EE
924
+ - DELETE\uFF1A\u67D0\u6761\u5DF2\u6709\u8BB0\u5FC6\u5DF2\u7ECF\u8FC7\u65F6\u3001\u53D1\u751F\u51B2\u7A81\u6216\u9519\u8BEF\uFF0C\u7528 existingIdx \u6307\u5B9A\uFF0Cfact \u586B\u539F\u5185\u5BB9
925
+ - NONE\uFF1A\u4E0D\u503C\u5F97\u8BB0\u5F55\u6216\u5DF2\u6709\u5B8C\u5168\u76F8\u540C\u7684\u4FE1\u606F
926
+
927
+ ## \u8F93\u51FA\u683C\u5F0F
928
+
929
+ \u8FD4\u56DE JSON \u6570\u7EC4\uFF0C\u6BCF\u6761\u683C\u5F0F\uFF1A
930
+ {"action": "NEW"|"UPDATE"|"DELETE"|"NONE", "fact": "\u4E8B\u5B9E\u5185\u5BB9", "existingIdx": \u6574\u6570\u6216\u7701\u7565, "reason": "\u539F\u56E0\uFF08\u53EF\u9009\uFF09"}
931
+
932
+ \u6BCF\u6B21\u6700\u591A\u8FD4\u56DE 3 \u6761\u64CD\u4F5C\u3002\u5982\u679C\u6CA1\u6709\u503C\u5F97\u64CD\u4F5C\u7684\u5185\u5BB9\uFF0C\u8FD4\u56DE []\u3002
933
+ \u53EA\u8FD4\u56DE JSON \u6570\u7EC4\uFF0C\u4E0D\u8981\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002
934
+
935
+ \u793A\u4F8B\uFF1A
936
+
937
+ 1. \u63D0\u53D6\u65B0\u504F\u597D\uFF1A
938
+ [{"action": "NEW", "fact": "\u7528\u6237\u504F\u597D TypeScript \u800C\u975E JavaScript", "reason": "\u660E\u786E\u8868\u8FBE\u7684\u6280\u672F\u504F\u597D"}]
939
+
940
+ 2. \u66F4\u65B0\u5DF2\u6709\u8BB0\u5FC6\uFF08idx 0 \u539F\u4E3A"\u7528\u6237\u6B63\u5728\u8BC4\u4F30 React \u548C Vue"\uFF09\uFF1A
941
+ [{"action": "UPDATE", "fact": "\u7528\u6237\u51B3\u5B9A\u4F7F\u7528 React\uFF08\u653E\u5F03\u4E86 Vue\uFF09", "existingIdx": 0, "reason": "\u51B3\u7B56\u5DF2\u660E\u786E\uFF0C\u66F4\u65B0\u8BC4\u4F30\u72B6\u6001"}]
942
+
943
+ 3. \u5BF9\u8BDD\u4EC5\u4E3A"\u597D\u7684\uFF0C\u8C22\u8C22"/"\u6CA1\u95EE\u9898"\u7B49\u786E\u8BA4\u8BED\uFF0C\u65E0\u65B0\u4FE1\u606F\uFF1A
944
+ []`,
945
+ shouldMerge: (contentA, contentB) => `\u4F60\u662F\u4E00\u4E2A\u8BB0\u5FC6\u53BB\u91CD\u52A9\u624B\uFF0C\u8D1F\u8D23\u5224\u65AD\u4E24\u6761\u8BB0\u5FC6\u662F\u5426\u8868\u8FBE\u4E86\u672C\u8D28\u76F8\u540C\u7684\u4FE1\u606F\u3002
946
+
947
+ \u8BB0\u5FC6A\uFF1A${contentA}
948
+ \u8BB0\u5FC6B\uFF1A${contentB}
949
+
950
+ \u5224\u65AD\u89C4\u5219\uFF1A
951
+ - \u5982\u679C\u4E24\u6761\u8BB0\u5FC6\u8868\u8FBE\u7684\u662F\u672C\u8D28\u76F8\u540C\u7684\u4FE1\u606F\uFF08\u53EF\u80FD\u63AA\u8F9E\u4E0D\u540C\u3001\u7C92\u5EA6\u4E0D\u540C\uFF0C\u4F46\u6838\u5FC3\u4E8B\u5B9E\u4E00\u81F4\uFF09\uFF0C\u8FD4\u56DE JSON\uFF1A
952
+ {"shouldMerge": true, "merged": "\u5408\u5E76\u540E\u7684\u7B80\u6D01\u8868\u8FF0\uFF0C\u4FDD\u7559\u4E24\u6761\u8BB0\u5FC6\u7684\u5173\u952E\u4FE1\u606F\uFF0C\u6BD4\u4EFB\u4F55\u4E00\u6761\u90FD\u66F4\u5B8C\u6574"}
953
+ - \u5982\u679C\u4E24\u6761\u8BB0\u5FC6\u662F\u4E92\u8865\u4FE1\u606F\u3001\u4E0D\u540C\u4E3B\u9898\u3001\u6216\u5305\u542B\u4E0D\u540C\u7684\u5177\u4F53\u4E8B\u5B9E\uFF0C\u8FD4\u56DE JSON\uFF1A
954
+ {"shouldMerge": false}
955
+
956
+ \u53EA\u8FD4\u56DE JSON\uFF0C\u4E0D\u8981\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002
957
+
958
+ \u793A\u4F8B\uFF1A
959
+
960
+ 1. \u5E94\u5408\u5E76\uFF08\u7C92\u5EA6\u4E0D\u540C\uFF09\uFF1A
961
+ A: "\u9879\u76EE\u4F7F\u7528 PostgreSQL \u6570\u636E\u5E93"
962
+ B: "\u9879\u76EE\u7684\u4E3B\u6570\u636E\u5E93\u662F PostgreSQL 16\uFF0C\u90E8\u7F72\u5728 AWS RDS \u4E0A"
963
+ \u2192 {"shouldMerge": true, "merged": "\u9879\u76EE\u4F7F\u7528 PostgreSQL 16 \u4F5C\u4E3A\u4E3B\u6570\u636E\u5E93\uFF0C\u90E8\u7F72\u5728 AWS RDS \u4E0A"}
964
+
965
+ 2. \u4E0D\u5E94\u5408\u5E76\uFF08\u4E92\u8865\u4F46\u4E0D\u540C\uFF09\uFF1A
966
+ A: "\u7528\u6237\u559C\u6B22\u7528 VS Code"
967
+ B: "\u7528\u6237\u7684 VS Code \u4F7F\u7528 One Dark Pro \u4E3B\u9898"
968
+ \u2192 {"shouldMerge": false}`,
969
+ evolutionJudge: (oldContent, newContent) => `\u4F60\u662F\u4E00\u4E2A\u8BB0\u5FC6\u6F14\u5316\u5224\u65AD\u52A9\u624B\u3002\u5206\u6790\u4EE5\u4E0B\u4E24\u6761\u8BB0\u5FC6\u7684\u5173\u7CFB\u5E76\u8FD4\u56DE JSON\u3002
970
+
971
+ \u65E7\u8BB0\u5FC6\uFF1A${oldContent}
972
+ \u65B0\u8BB0\u5FC6\uFF1A${newContent}
973
+
974
+ \u5224\u65AD\u89C4\u5219\uFF1A
975
+
976
+ - EVOLVE\uFF1A\u65B0\u5185\u5BB9\u662F\u5BF9\u65E7\u8BB0\u5FC6\u7684\u6DF1\u5316/\u66F4\u65B0\uFF08\u5982\u300C\u6B63\u5728\u8003\u8651\u7528 Next.js\u300D\u2192\u300C\u51B3\u5B9A\u7528 Next.js 14 App Router\u300D\uFF09
977
+ \u8FD4\u56DE\uFF1A{"type": "EVOLVE", "mergedContent": "\u878D\u5408\u540E\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u4FDD\u7559\u6F14\u5316\u8F68\u8FF9"}
978
+
979
+ - CONFLICT\uFF1A\u65B0\u65E7\u4FE1\u606F\u5728\u540C\u4E00\u5C5E\u6027\u4E0A\u76F4\u63A5\u77DB\u76FE\uFF08\u5982\u300C\u4F7F\u7528 MySQL \u4F5C\u4E3A\u4E3B\u6570\u636E\u5E93\u300Dvs\u300C\u5DF2\u8FC1\u79FB\u5230 PostgreSQL\u300D\uFF09
980
+ \u8FD4\u56DE\uFF1A{"type": "CONFLICT"}
981
+
982
+ - EXPAND\uFF1A\u65B0\u4FE1\u606F\u662F\u5BF9\u65E7\u8BB0\u5FC6\u540C\u4E00\u4E3B\u9898\u7684\u8865\u5145\u6269\u5C55\uFF08\u5982\u300C\u8D1F\u8D23\u540E\u7AEF\u5F00\u53D1\u300D+\u300C\u540E\u7AEF\u4F7F\u7528 Go \u548C gRPC\u300D\uFF09
983
+ \u8FD4\u56DE\uFF1A{"type": "EXPAND", "mergedContent": "\u5408\u5E76\u540E\u7684\u5B8C\u6574\u5185\u5BB9\uFF0C\u6574\u5408\u53CC\u65B9\u4FE1\u606F"}
984
+
985
+ - NEW\uFF1A\u5168\u65B0\u4FE1\u606F\uFF0C\u4E0E\u65E7\u8BB0\u5FC6\u65E0\u5B9E\u8D28\u5173\u8054\uFF08\u5982\u300C\u559C\u6B22 dark mode\u300Dvs\u300C\u4E0B\u5468\u8981\u53BB\u51FA\u5DEE\u300D\uFF09
986
+ \u8FD4\u56DE\uFF1A{"type": "NEW"}
987
+
988
+ \u53EA\u8FD4\u56DE JSON\uFF0C\u4E0D\u8981\u4EFB\u4F55\u5176\u4ED6\u6587\u5B57\u3002`,
989
+ conflictScan: (numberedNotes) => `\u4F60\u5728\u5BA1\u8BA1\u4E00\u4E2A\u4EBA\u7684\u8BB0\u5FC6\u5E93\uFF0C\u627E\u51FA\u5176\u4E2D**\u4E92\u76F8\u77DB\u76FE**\u7684\u6761\u76EE\u3002
990
+
991
+ \u4E0B\u9762\u662F\u7F16\u53F7\u7684\u8BB0\u5FC6\u3002\u627E\u51FA\u90A3\u4E9B**\u4E0D\u53EF\u80FD\u540C\u65F6\u4E3A\u771F**\u7684\u914D\u5BF9\u3002
992
+
993
+ ${numberedNotes}
994
+
995
+ \u7B97\u77DB\u76FE\u7684\u60C5\u51B5\uFF1A
996
+ - \u540C\u4E00\u5C5E\u6027\u4E0A\u51FA\u73B0\u4E92\u65A5\u7684\u503C\uFF08\u300C\u4F4F\u5728\u5DF4\u9ECE\u300Dvs\u300C\u642C\u5230\u4E86\u67CF\u6797\u300D\uFF09
997
+ - \u540E\u6765\u7684\u8BB0\u5FC6\u8FDD\u53CD\u4E86\u5148\u524D\u9648\u8FF0\u7684\u504F\u597D\u6216\u7EA6\u675F\uFF08\u300C\u5403\u7D20\u300Dvs\u300C\u90A3\u5757\u725B\u6392\u5F88\u597D\u5403\u300D\uFF09
998
+ - \u540E\u6765\u7684\u4E8B\u5B9E\u53D6\u4EE3\u4E86\u5148\u524D\u7684\uFF08\u300C\u7528 MySQL\u300Dvs\u300C\u5DF2\u8FC1\u79FB\u5230 PostgreSQL\u300D\uFF09
999
+
1000
+ **\u4E0D\u7B97**\u77DB\u76FE \u2014\u2014 \u8BF7\u4E25\u683C\uFF0C\u4EE5\u4E0B\u662F\u6700\u5E38\u89C1\u7684\u8BEF\u5224\uFF1A
1001
+ - \u7D2F\u52A0\u7684\u4E8B\u5B9E\u3002\u4E24\u8005\u53EF\u4EE5\u540C\u65F6\u6210\u7ACB\uFF08\u300C\u517B\u4E86\u4E00\u53EA\u72D7\u53EB Buddy\u300D+\u300C\u53C8\u9886\u517B\u4E86\u7B2C\u4E8C\u53EA\u53EB Scout\u300D**\u4E0D\u662F**\u77DB\u76FE\uFF09
1002
+ - \u4E24\u6761\u8BB0\u5FC6\u672C\u8EAB\u5DF2\u7ECF\u4F53\u73B0\u4E86\u968F\u65F6\u95F4\u7684\u53D8\u5316
1003
+ - \u53EA\u662F\u4E3B\u9898\u76F8\u4F3C\u6216\u76F8\u5173
1004
+ - \u573A\u666F\u4E0D\u540C\uFF08\u5728\u516C\u53F8\u559D\u5496\u5561\uFF0C\u5728\u5BB6\u559D\u8336\uFF09
1005
+
1006
+ \u5BF9\u6BCF\u4E00\u5BF9\u77DB\u76FE\uFF0C\u8FD8\u8981\u6307\u51FA\u54EA\u4E00\u6761\u662F**\u5DF2\u5931\u6548\u7684**\uFF08\u4E0D\u518D\u4E3A\u771F\u7684\u90A3\u6761\uFF09\u3002\u8BF7\u4ECE**\u63AA\u8F9E**\u5224\u65AD\uFF0C\u4E0D\u8981\u5047\u8BBE\u987A\u5E8F\uFF1A
1007
+ \u300C\u4EE5\u524D\u300D\u300C2019 \u5E74\u90A3\u4F1A\u513F\u300D\u300C\u4E0A\u4E2A\u6708\u642C\u4E86\u300D\u300C\u6539\u7528\u4E86\u300D\u8FD9\u7C7B\u8BF4\u6CD5\u80FD\u544A\u8BC9\u4F60\u54EA\u6761\u63CF\u8FF0\u7684\u662F\u8FC7\u53BB\u3002
1008
+ \u8FD9\u4E9B\u8BB0\u5FC6**\u4E0D\u662F\u6309\u65F6\u95F4\u987A\u5E8F\u6392\u5217\u7684**\uFF0C\u7F16\u53F7\u4E5F\u4E0D\u4EE3\u8868\u65B0\u65E7\u3002
1009
+
1010
+ \u5982\u679C\u65E0\u6CD5\u5224\u65AD\u54EA\u6761\u5DF2\u5931\u6548\uFF0C\u5C31\u586B null\u3002\u8FD9\u662F\u4E00\u4E2A**\u6B63\u5E38\u4E14\u6709\u7528**\u7684\u56DE\u7B54 \u2014\u2014 \u5B81\u53EF\u586B null \u4E5F\u4E0D\u8981\u731C\uFF0C
1011
+ \u56E0\u4E3A\u731C\u9519\u4F1A\u8BA9\u4E00\u6761**\u4ECD\u7136\u4E3A\u771F**\u7684\u8BB0\u5FC6\u88AB\u505C\u7528\u3002
1012
+
1013
+ \u53EA\u8FD4\u56DE JSON \u6570\u7EC4\u3002\u6CA1\u6709\u771F\u6B63\u77DB\u76FE\u5C31\u8FD4\u56DE\u7A7A\u6570\u7EC4\uFF1A
1014
+ [{"a": 0, "b": 3, "superseded": 0, "reason": "\u4E00\u53E5\u8BDD\u8BF4\u660E\u662F\u54EA\u4E2A\u5C5E\u6027\u4E92\u65A5"}]
1015
+
1016
+ "superseded" \u53EA\u80FD\u662F "a" \u7684\u503C\u3001"b" \u7684\u503C\uFF0C\u6216 null\u3002
1017
+ \u4F7F\u7528\u4E0A\u9762\u663E\u793A\u7684\u7F16\u53F7\u3002\u540C\u4E00\u5BF9\u53EA\u62A5\u4E00\u6B21\u3002**\u5B81\u53EF\u4E0D\u62A5\uFF0C\u4E5F\u4E0D\u8981\u731C\u3002**`
1018
+ };
1019
+ var templates = { en, zh };
1020
+ var t = templates[LOCALE];
1021
+
1022
+ // src/llm.ts
1023
+ var _override = {};
1024
+ function configureLlm(cfg) {
1025
+ _override = { ...cfg };
1026
+ _anthropicClients.clear();
1027
+ _openaiClients.clear();
1028
+ }
1029
+ var _warned = /* @__PURE__ */ new Set();
1030
+ function warnOnce(key, message) {
1031
+ if (_warned.has(key)) return;
1032
+ _warned.add(key);
1033
+ console.error(message);
1034
+ }
1035
+ function resolveProvider(role = "fast") {
1036
+ const raw = role === "strong" ? process.env.AMEM_LLM_STRONG_PROVIDER || _override.strong?.provider || void 0 : void 0;
1037
+ const p = (raw || process.env.AMEM_LLM_PROVIDER || _override.provider || "anthropic").trim().toLowerCase();
1038
+ if (p !== "anthropic" && p !== "openai") {
1039
+ warnOnce(`provider:${p}`, `[amem] unknown LLM provider "${p}"; falling back to anthropic`);
1040
+ }
1041
+ return p;
1042
+ }
1043
+ function resolveModel(role = "fast") {
1044
+ const strong = role === "strong" ? process.env.AMEM_LLM_STRONG_MODEL || _override.strong?.model || void 0 : void 0;
1045
+ return strong || process.env.AMEM_LLM_MODEL || _override.model || (resolveProvider(role) === "openai" ? "gpt-4o-mini" : "claude-sonnet-4-6");
1046
+ }
1047
+ function resolveBaseURL(role = "fast") {
1048
+ const strong = role === "strong" ? process.env.AMEM_LLM_STRONG_BASE_URL || _override.strong?.baseURL || void 0 : void 0;
1049
+ return strong || process.env.AMEM_LLM_BASE_URL || _override.baseURL || void 0;
1050
+ }
1051
+ function resolveCrudRole() {
1052
+ const raw = (process.env.AMEM_LLM_CRUD_ROLE || _override.crudRole || "fast").trim().toLowerCase();
1053
+ if (raw === "strong") return "strong";
1054
+ if (raw !== "fast") {
1055
+ warnOnce(`crudRole:${raw}`, `[amem] unknown AMEM_LLM_CRUD_ROLE "${raw}"; using fast`);
1056
+ }
1057
+ return "fast";
1058
+ }
1059
+ var DEFAULT_TIMEOUT_MS = 3e4;
1060
+ function resolveTimeoutMs() {
1061
+ const envVal = Number(process.env.AMEM_LLM_TIMEOUT);
1062
+ if (Number.isFinite(envVal) && envVal > 0) return envVal;
1063
+ if (_override.timeoutMs && _override.timeoutMs > 0) return _override.timeoutMs;
1064
+ return DEFAULT_TIMEOUT_MS;
1065
+ }
1066
+ var _anthropicClients = /* @__PURE__ */ new Map();
1067
+ function anthropic(baseURL) {
1068
+ const key = baseURL ?? "";
1069
+ let client = _anthropicClients.get(key);
1070
+ if (!client) {
1071
+ client = new Anthropic({
1072
+ ...process.env.AMEM_LLM_API_KEY && { apiKey: process.env.AMEM_LLM_API_KEY },
1073
+ ...baseURL && { baseURL },
1074
+ timeout: resolveTimeoutMs()
1075
+ });
1076
+ _anthropicClients.set(key, client);
1077
+ }
1078
+ return client;
1079
+ }
1080
+ var _openaiClients = /* @__PURE__ */ new Map();
1081
+ function openai(baseURL) {
1082
+ const key = baseURL ?? "";
1083
+ let client = _openaiClients.get(key);
1084
+ if (!client) {
1085
+ client = new OpenAI({
1086
+ // AMEM_LLM_API_KEY first (engine convention), then the SDK's own
1087
+ // OPENAI_API_KEY (the standard) — passing an explicit key blocks the SDK's
1088
+ // env fallback, so read it here. Placeholder last, so keyless local servers
1089
+ // (Ollama, vLLM) still work.
1090
+ apiKey: process.env.AMEM_LLM_API_KEY || process.env.OPENAI_API_KEY || "sk-no-key-required",
1091
+ ...baseURL && { baseURL },
1092
+ timeout: resolveTimeoutMs()
1093
+ });
1094
+ _openaiClients.set(key, client);
1095
+ }
1096
+ return client;
1097
+ }
1098
+ async function llmCall(prompt, maxTokens = 500, role = "fast") {
1099
+ const provider = resolveProvider(role);
1100
+ const model = resolveModel(role);
1101
+ const baseURL = resolveBaseURL(role);
1102
+ const isThinking = model.includes("gemini") || model.includes("pro-agent");
1103
+ const effectiveMaxTokens = isThinking ? Math.max(maxTokens * 8, 4e3) : maxTokens;
1104
+ try {
1105
+ return provider === "openai" ? await openaiCall(prompt, model, effectiveMaxTokens, baseURL) : await anthropicCall(prompt, model, effectiveMaxTokens, baseURL);
1106
+ } catch (e) {
1107
+ console.error(`[amem] LLM call failed: ${e.message}`);
1108
+ return null;
1109
+ }
1110
+ }
1111
+ async function anthropicCall(prompt, model, maxTokens, baseURL) {
1112
+ const resp = await anthropic(baseURL).messages.create({
1113
+ model,
1114
+ max_tokens: maxTokens,
1115
+ messages: [{ role: "user", content: prompt }]
1116
+ });
1117
+ for (const block of resp.content) {
1118
+ if (block.type === "text") return block.text.trim();
1119
+ }
1120
+ return null;
1121
+ }
1122
+ async function openaiCall(prompt, model, maxTokens, baseURL) {
1123
+ const isReasoning = /^o\d/.test(model) || model.startsWith("gpt-5");
1124
+ const resp = await openai(baseURL).chat.completions.create({
1125
+ model,
1126
+ ...isReasoning ? { max_completion_tokens: maxTokens } : { max_tokens: maxTokens },
1127
+ messages: [{ role: "user", content: prompt }]
1128
+ });
1129
+ return resp.choices[0]?.message?.content?.trim() ?? null;
1130
+ }
1131
+ function stripReasoning(raw) {
1132
+ return raw.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/<\|(?:eot_id|im_start|im_end|begin_of_text|end_of_text|endoftext)\|>/g, "").trim();
1133
+ }
1134
+ function stripFences(raw) {
1135
+ raw = stripReasoning(raw);
1136
+ if (raw.startsWith("```")) {
1137
+ const lines = raw.split("\n");
1138
+ lines.shift();
1139
+ if (lines[lines.length - 1] === "```") lines.pop();
1140
+ raw = lines.join("\n").trim();
1141
+ }
1142
+ if (raw.startsWith('"') && raw.endsWith('"') || raw.startsWith("'") && raw.endsWith("'")) {
1143
+ try {
1144
+ raw = JSON.parse(raw);
1145
+ } catch {
1146
+ }
1147
+ }
1148
+ return raw;
1149
+ }
1150
+ function parseJsonLoose(raw) {
1151
+ const cleaned = stripFences(raw);
1152
+ try {
1153
+ return JSON.parse(cleaned);
1154
+ } catch (e) {
1155
+ const m = cleaned.match(/\{[\s\S]*\}/);
1156
+ if (m) return JSON.parse(m[0]);
1157
+ throw e;
1158
+ }
1159
+ }
1160
+ var VALID_CONFIDENCE = /* @__PURE__ */ new Set(["high", "medium", "low"]);
1161
+ var VALID_CATEGORIES = /* @__PURE__ */ new Set([
1162
+ "Technical",
1163
+ "Business",
1164
+ "Personal",
1165
+ "Project",
1166
+ "Research",
1167
+ "System",
1168
+ "General"
1169
+ ]);
1170
+ async function llmConstructNote(content) {
1171
+ const prompt = `Analyze the following text and respond with valid JSON only (no markdown fences, no explanation, no comments). All string values must use standard double quotes and be properly escaped:
1172
+ {
1173
+ "keywords": ["keyword1", "keyword2"],
1174
+ "tags": ["tag1", "tag2"],
1175
+ "context": "one sentence summary in the same language as the input",
1176
+ "category": "Technical|Business|Personal|Project|Research|System|General",
1177
+ "note_type": "memory|knowledge",
1178
+ "topics": ["Topic1", "Topic2"],
1179
+ "confidence": "high|medium|low"
1180
+ }
1181
+
1182
+ Category guide:
1183
+ - Technical: code, tools, configuration, APIs, debugging
1184
+ - Business: company, finance, compliance, contracts, invoices
1185
+ - Personal: personal state, habits, preferences, emotions
1186
+ - Project: project progress, decisions, milestones
1187
+ - Research: research, literature, evaluation, comparison
1188
+ - System: system services, monitoring, operations
1189
+ - General: anything that does not fit the above
1190
+
1191
+ note_type guide:
1192
+ - knowledge: books, methodologies, tools, domain knowledge, reference material \u2014 durable, no strong time component
1193
+ - memory: events, decisions, preferences, states, observations \u2014 episodic, time-sensitive
1194
+
1195
+ topics guide (Story 26B):
1196
+ - Only populate for knowledge notes (note_type=knowledge). For memory notes, return [].
1197
+ - List 1-5 concise subject tags representing the main topics of this knowledge, e.g. ["TypeScript", "Qdrant", "Vector DB"].
1198
+
1199
+ confidence guide (Story 27):
1200
+ - high: note_type is unambiguous \u2014 clearly episodic (event/decision/state) or clearly durable knowledge (tool doc/methodology)
1201
+ - medium: some ambiguity \u2014 e.g. "learned X method" could be either memory or knowledge
1202
+ - low: LLM is uncertain \u2014 vague, fragmentary, or mixed content
1203
+
1204
+ Text: ${content}`;
1205
+ const raw = await llmCall(prompt, 400);
1206
+ if (!raw)
1207
+ return {
1208
+ keywords: [],
1209
+ tags: [],
1210
+ context: "",
1211
+ category: "General",
1212
+ note_type: "memory",
1213
+ topics: [],
1214
+ confidence: "medium"
1215
+ };
1216
+ try {
1217
+ const data = parseJsonLoose(raw);
1218
+ const rawCategory = typeof data.category === "string" ? data.category : "General";
1219
+ const category = VALID_CATEGORIES.has(rawCategory) ? rawCategory : "General";
1220
+ const note_type = data.note_type === "knowledge" ? "knowledge" : "memory";
1221
+ const topics = note_type === "knowledge" && Array.isArray(data.topics) ? data.topics.filter((v) => typeof v === "string") : [];
1222
+ const rawConfidence = typeof data.confidence === "string" ? data.confidence : "medium";
1223
+ const confidence = VALID_CONFIDENCE.has(rawConfidence) ? rawConfidence : "medium";
1224
+ return {
1225
+ keywords: Array.isArray(data.keywords) ? data.keywords : [],
1226
+ tags: Array.isArray(data.tags) ? data.tags : [],
1227
+ context: typeof data.context === "string" ? data.context : "",
1228
+ category,
1229
+ note_type,
1230
+ topics,
1231
+ confidence
1232
+ };
1233
+ } catch (e) {
1234
+ console.error(`[amem] Note construction parse failed: ${e.message}`);
1235
+ return {
1236
+ keywords: [],
1237
+ tags: [],
1238
+ context: "",
1239
+ category: "General",
1240
+ note_type: "memory",
1241
+ topics: [],
1242
+ confidence: "medium"
1243
+ };
1244
+ }
1245
+ }
1246
+ async function llmShouldLink(noteContent, candidateContent) {
1247
+ const prompt = `Do these two memory notes have a meaningful relationship that would be useful to link?
1248
+ Reply with only "yes" or "no".
1249
+
1250
+ Note A: ${noteContent}
1251
+ Note B: ${candidateContent}`;
1252
+ const raw = await llmCall(prompt, 10);
1253
+ if (!raw) return false;
1254
+ return raw.toLowerCase().startsWith("yes");
1255
+ }
1256
+ async function llmCrudDecision(userText, assistantText, existingMemories) {
1257
+ const memoryList = existingMemories.length > 0 ? existingMemories.map((m) => `[${m.idx}] ${m.content}`).join("\n") : "(none)";
1258
+ const prompt = t.crudDecision(userText.slice(0, 500), assistantText.slice(0, 500), memoryList);
1259
+ try {
1260
+ const raw = await llmCall(prompt, 400, resolveCrudRole());
1261
+ if (!raw) return [];
1262
+ const match = stripReasoning(raw).match(/\[.*\]/s);
1263
+ if (!match) return [];
1264
+ const parsed = JSON.parse(match[0]);
1265
+ if (!Array.isArray(parsed)) return [];
1266
+ const ops = [];
1267
+ for (const item of parsed) {
1268
+ if (!item || typeof item !== "object") continue;
1269
+ const action = item.action;
1270
+ if (!["NEW", "UPDATE", "DELETE", "NONE"].includes(action)) continue;
1271
+ if (action === "NONE") continue;
1272
+ const op = {
1273
+ action,
1274
+ fact: typeof item.fact === "string" ? item.fact : "",
1275
+ reason: typeof item.reason === "string" ? item.reason : void 0
1276
+ };
1277
+ if (typeof item.existingIdx === "number") {
1278
+ op.existingIdx = item.existingIdx;
1279
+ }
1280
+ ops.push(op);
1281
+ }
1282
+ return ops.slice(0, 3);
1283
+ } catch (e) {
1284
+ console.error(`[amem] llmCrudDecision failed: ${e.message}`);
1285
+ return [];
1286
+ }
1287
+ }
1288
+ async function llmShouldMerge(contentA, contentB) {
1289
+ const prompt = t.shouldMerge(contentA, contentB);
1290
+ const raw = await llmCall(prompt, 300, "strong");
1291
+ if (!raw) return { shouldMerge: false };
1292
+ try {
1293
+ const data = parseJsonLoose(raw);
1294
+ if (typeof data.shouldMerge !== "boolean") return { shouldMerge: false };
1295
+ if (data.shouldMerge && typeof data.merged === "string") {
1296
+ return { shouldMerge: true, merged: data.merged };
1297
+ }
1298
+ return { shouldMerge: false };
1299
+ } catch (e) {
1300
+ console.error(`[amem] llmShouldMerge parse failed: ${e.message}`);
1301
+ return { shouldMerge: false };
1302
+ }
1303
+ }
1304
+ var VALID_EVOLUTION_TYPES = /* @__PURE__ */ new Set(["EVOLVE", "CONFLICT", "EXPAND", "NEW"]);
1305
+ async function llmEvolutionJudge(oldContent, newContent) {
1306
+ const prompt = t.evolutionJudge(oldContent, newContent);
1307
+ const raw = await llmCall(prompt, 300, "strong");
1308
+ if (!raw) return { type: "NEW" };
1309
+ try {
1310
+ const data = parseJsonLoose(raw);
1311
+ const type = VALID_EVOLUTION_TYPES.has(data.type) ? data.type : "NEW";
1312
+ return {
1313
+ type,
1314
+ mergedContent: typeof data.mergedContent === "string" ? data.mergedContent : void 0
1315
+ };
1316
+ } catch (e) {
1317
+ console.error(`[amem] llmEvolutionJudge parse failed: ${e.message}`);
1318
+ return { type: "NEW" };
1319
+ }
1320
+ }
1321
+ async function llmEvolveNote(content, linkedNotes) {
1322
+ const linkedStr = linkedNotes.map((n) => `- ID: ${n.id}
1323
+ Content: ${n.content}`).join("\n");
1324
+ const prompt = `A memory note has gained new connections. Update its context, tags, and decide whether to strengthen connections with specific neighbors.
1325
+ Reply with JSON only (no markdown):
1326
+ {
1327
+ "tags": ["tag1", "tag2", ...],
1328
+ "context": "updated one sentence summary",
1329
+ "should_strengthen": true|false,
1330
+ "suggested_connections": ["neighbor_id_1", "neighbor_id_2", ...],
1331
+ "tags_to_update": ["tag_1", ..., "tag_n"]
1332
+ }
1333
+
1334
+ Guidelines:
1335
+ - "tags" and "context" are for updating the original note based on new connections.
1336
+ - "should_strengthen" is a decision whether this note should strengthen its connections to any of the newly linked notes (neighbors).
1337
+ - "suggested_connections" must contain only IDs from the newly linked notes (neighbors) listed below.
1338
+ - "tags_to_update" are updated tags for the original note itself if we strengthen connections.
1339
+
1340
+ Original note content: ${content}
1341
+
1342
+ Newly linked notes (neighbors):
1343
+ ${linkedStr}`;
1344
+ const raw = await llmCall(prompt, 500);
1345
+ if (!raw) return { tags: null, context: null, shouldStrengthen: false, suggestedConnections: [], tagsToUpdate: [] };
1346
+ try {
1347
+ const data = parseJsonLoose(raw);
1348
+ return {
1349
+ tags: Array.isArray(data.tags) ? data.tags : null,
1350
+ context: typeof data.context === "string" ? data.context : null,
1351
+ shouldStrengthen: typeof data.should_strengthen === "boolean" ? data.should_strengthen : false,
1352
+ suggestedConnections: Array.isArray(data.suggested_connections) ? data.suggested_connections.map(String) : [],
1353
+ tagsToUpdate: Array.isArray(data.tags_to_update) ? data.tags_to_update.map(String) : []
1354
+ };
1355
+ } catch (e) {
1356
+ console.error(`[amem] Evolution parse failed: ${e.message}`);
1357
+ return { tags: null, context: null, shouldStrengthen: false, suggestedConnections: [], tagsToUpdate: [] };
1358
+ }
1359
+ }
1360
+ async function llmConflictScan(contents) {
1361
+ if (contents.length < 2) return [];
1362
+ const numbered = contents.map((c, i) => `[${i}] ${c}`).join("\n");
1363
+ try {
1364
+ const raw = await llmCall(t.conflictScan(numbered), 600, "strong");
1365
+ if (!raw) return [];
1366
+ const cleaned = stripReasoning(raw);
1367
+ const match = cleaned.match(/\[[\s\S]*\]/);
1368
+ if (!match) return [];
1369
+ const parsed = JSON.parse(match[0]);
1370
+ if (!Array.isArray(parsed)) return [];
1371
+ const pairs = [];
1372
+ const seen = /* @__PURE__ */ new Set();
1373
+ for (const item of parsed) {
1374
+ if (!item || typeof item !== "object") continue;
1375
+ const { a, b } = item;
1376
+ if (typeof a !== "number" || typeof b !== "number") continue;
1377
+ if (!Number.isInteger(a) || !Number.isInteger(b)) continue;
1378
+ if (a < 0 || b < 0 || a >= contents.length || b >= contents.length) continue;
1379
+ if (a === b) continue;
1380
+ const key = a < b ? `${a}:${b}` : `${b}:${a}`;
1381
+ if (seen.has(key)) continue;
1382
+ seen.add(key);
1383
+ const rawSup = item.superseded;
1384
+ const supersededIndex = rawSup === a || rawSup === b ? rawSup : null;
1385
+ pairs.push({
1386
+ a,
1387
+ b,
1388
+ reason: typeof item.reason === "string" ? item.reason : "",
1389
+ supersededIndex
1390
+ });
1391
+ }
1392
+ return pairs;
1393
+ } catch (e) {
1394
+ console.error(`[amem] llmConflictScan failed: ${e.message}`);
1395
+ return [];
1396
+ }
1397
+ }
1398
+
1399
+ // src/config.ts
1400
+ import * as os from "os";
1401
+ import * as path from "path";
1402
+ var _dataDir = process.env.AMEM_DATA_DIR || path.join(os.homedir(), ".amem");
1403
+ function configure(opts) {
1404
+ if (opts.dataDir) _dataDir = opts.dataDir;
1405
+ }
1406
+ function getDataDir() {
1407
+ return _dataDir;
1408
+ }
1409
+
1410
+ // src/memory.ts
1411
+ import { v4 as uuidv4 } from "uuid";
1412
+ import { createHash } from "crypto";
1413
+ import * as fs2 from "fs";
1414
+ import * as path3 from "path";
1415
+
1416
+ // src/evo-counter.ts
1417
+ import * as fs from "fs";
1418
+ import * as path2 from "path";
1419
+ function counterFile() {
1420
+ return process.env.AMEM_EVO_COUNTER_PATH || path2.join(getDataDir(), "amem_evo_cnt.json");
1421
+ }
1422
+ var EVO_THRESHOLD = 20;
1423
+ function getEvoCount() {
1424
+ try {
1425
+ const data = JSON.parse(fs.readFileSync(counterFile(), "utf-8"));
1426
+ return data.count || 0;
1427
+ } catch {
1428
+ return 0;
1429
+ }
1430
+ }
1431
+ function incrementEvoCount() {
1432
+ const count = getEvoCount() + 1;
1433
+ fs.writeFileSync(counterFile(), JSON.stringify({ count, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }));
1434
+ return count;
1435
+ }
1436
+ function shouldRunEvolution() {
1437
+ const count = incrementEvoCount();
1438
+ return count % EVO_THRESHOLD === 0;
1439
+ }
1440
+
1441
+ // src/memory.ts
1442
+ import { Jieba } from "@node-rs/jieba";
1443
+ var logSafe = (id) => id.replace(/[\r\n]/g, "");
1444
+ var _jieba = null;
1445
+ function getJieba() {
1446
+ if (!_jieba) _jieba = new Jieba();
1447
+ return _jieba;
1448
+ }
1449
+ function simpleTokenize(text) {
1450
+ const hasChinese = /[\u4e00-\u9fff]/.test(text);
1451
+ if (hasChinese) {
1452
+ return getJieba().cut(text, true).map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 0 && /[\w\u4e00-\u9fff]/.test(t2));
1453
+ }
1454
+ return Array.from(text.toLowerCase().matchAll(/[\w]+/g)).map((m) => m[0]);
1455
+ }
1456
+ function buildBM25(notes) {
1457
+ const ids = notes.map((n) => n.id);
1458
+ const corpus = notes.map((n) => {
1459
+ const text = [n.content, ...n.keywords, ...n.tags].join(" ");
1460
+ return simpleTokenize(text);
1461
+ });
1462
+ const df = /* @__PURE__ */ new Map();
1463
+ for (const tokens of corpus) {
1464
+ for (const t2 of new Set(tokens)) df.set(t2, (df.get(t2) ?? 0) + 1);
1465
+ }
1466
+ const N = corpus.length;
1467
+ const idf = /* @__PURE__ */ new Map();
1468
+ df.forEach((freq, term) => {
1469
+ idf.set(term, Math.log((N - freq + 0.5) / (freq + 0.5) + 1));
1470
+ });
1471
+ const avgdl = corpus.reduce((s, t2) => s + t2.length, 0) / Math.max(N, 1);
1472
+ return { ids, corpus, idf, avgdl };
1473
+ }
1474
+ function bm25Score(state, queryTokens, k1 = 1.5, b = 0.75) {
1475
+ const scores = state.ids.map((id, i) => {
1476
+ const doc = state.corpus[i];
1477
+ const dl = doc.length;
1478
+ const tf = /* @__PURE__ */ new Map();
1479
+ for (const t2 of doc) tf.set(t2, (tf.get(t2) ?? 0) + 1);
1480
+ let score = 0;
1481
+ for (const t2 of queryTokens) {
1482
+ const f = tf.get(t2) ?? 0;
1483
+ if (f === 0) continue;
1484
+ const idfVal = state.idf.get(t2) ?? 0;
1485
+ score += idfVal * (f * (k1 + 1) / (f + k1 * (1 - b + b * (dl / state.avgdl))));
1486
+ }
1487
+ return [id, score];
1488
+ });
1489
+ return scores.sort((a, b2) => b2[1] - a[1]);
1490
+ }
1491
+ function rrfMerge(embIds, bm25Ids, k = 60) {
1492
+ const scores = /* @__PURE__ */ new Map();
1493
+ embIds.forEach((id, rank) => scores.set(id, (scores.get(id) ?? 0) + 1 / (k + rank + 1)));
1494
+ bm25Ids.forEach((id, rank) => scores.set(id, (scores.get(id) ?? 0) + 1 / (k + rank + 1)));
1495
+ return Array.from(scores.entries()).sort((a, b) => b[1] - a[1]);
1496
+ }
1497
+ function buildEmbedText(note) {
1498
+ let text = note.content;
1499
+ if (note.keywords.length) text += " " + note.keywords.join(" ");
1500
+ if (note.tags.length) text += " " + note.tags.join(" ");
1501
+ if (note.context) text += " " + note.context;
1502
+ return text;
1503
+ }
1504
+ var EPHEMERAL_SIGNALS = ["\u5F85\u8DD1", "\u7B49\u786E\u8BA4", "\u6628\u65E5", "\u660E\u5929\u5B8C\u6210"];
1505
+ function checkQuality(content) {
1506
+ const trimmed = content.trim();
1507
+ if (trimmed.length < 10) {
1508
+ return { ok: false, ephemeral: false, reason: `\u5185\u5BB9\u8FC7\u77ED\uFF08${trimmed.length} \u5B57\uFF0C\u6700\u5C11 10 \u5B57\uFF09` };
1509
+ }
1510
+ const ephemeral = EPHEMERAL_SIGNALS.some((w) => trimmed.includes(w));
1511
+ return { ok: true, ephemeral };
1512
+ }
1513
+ function defaultCtx() {
1514
+ return createStorageContext();
1515
+ }
1516
+ async function addMemory(content, agentId = "main", opts) {
1517
+ const scope = opts?.scope ?? "private";
1518
+ const subjects = opts?.subjects ?? [];
1519
+ const ctx = opts?.storageCtx ?? defaultCtx();
1520
+ const quality = checkQuality(content);
1521
+ if (!quality.ok) {
1522
+ throw new Error(`[quality] \u5199\u5165\u62D2\u7EDD: ${quality.reason}`);
1523
+ }
1524
+ const effectiveNoteAgentId = scope === "shared" ? "shared" : agentId;
1525
+ const hash = createHash("md5").update(content).digest("hex");
1526
+ const existingByHash = await ctx.findByHash(hash, agentId);
1527
+ if (existingByHash) {
1528
+ console.log(`[add] dedup: exact hash match, skipping (id=${existingByHash.id.slice(0, 8)})`);
1529
+ return existingByHash.id;
1530
+ }
1531
+ console.log("[add] Constructing note...");
1532
+ const { keywords, tags, context, category, note_type, topics } = await llmConstructNote(content);
1533
+ console.log(` keywords: ${keywords.join(", ")}`);
1534
+ console.log(` tags: ${tags.join(", ")}`);
1535
+ console.log(` context: ${context}`);
1536
+ console.log(` category: ${category}`);
1537
+ console.log(` note_type: ${note_type}`);
1538
+ console.log(` topics: ${topics.join(", ")}`);
1539
+ const fieldsText = buildEmbedText({ content, keywords, tags, context });
1540
+ const embedding = await encode(fieldsText);
1541
+ const topMatch = await ctx.queryByEmbedding(embedding, 1, agentId, 0);
1542
+ if (topMatch.length > 0 && topMatch[0].score >= 0.85) {
1543
+ if (canWrite(topMatch[0].note, agentId)) {
1544
+ console.log(`[add] dedup: high-sim match (sim=${topMatch[0].score.toFixed(3)}), updating existing`);
1545
+ await ctx.updateNoteContent(topMatch[0].note.id, content, embedding, hash, agentId);
1546
+ return topMatch[0].note.id;
1547
+ }
1548
+ console.log(
1549
+ `[add] dedup: high-sim match ${topMatch[0].note.id.slice(0, 8)} is not writable by ${logSafe(agentId)} \u2014 inserting a new note instead`
1550
+ );
1551
+ }
1552
+ const pendingMerge = topMatch.length > 0 && topMatch[0].score >= 0.72 && topMatch[0].score < 0.85;
1553
+ if (pendingMerge) {
1554
+ console.log(`[add] dedup: borderline sim (sim=${topMatch[0].score.toFixed(3)}), marking pending_merge=true`);
1555
+ }
1556
+ const readers = scope === "shared" ? ["*"] : [agentId];
1557
+ const writers = [agentId];
1558
+ const note = {
1559
+ id: uuidv4(),
1560
+ subjects,
1561
+ content,
1562
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1563
+ keywords,
1564
+ tags,
1565
+ context,
1566
+ embedding,
1567
+ links: [],
1568
+ agent_id: effectiveNoteAgentId,
1569
+ hash,
1570
+ // 13-A
1571
+ retrieval_count: 0,
1572
+ last_accessed: (/* @__PURE__ */ new Date()).toISOString(),
1573
+ // 13-B
1574
+ evolution_history: [],
1575
+ // 13-E
1576
+ category,
1577
+ is_active: true,
1578
+ // 26A
1579
+ note_type,
1580
+ // 26B
1581
+ topics,
1582
+ // 29
1583
+ pending_merge: pendingMerge,
1584
+ // 30
1585
+ conflict: false,
1586
+ // 31
1587
+ ephemeral: quality.ephemeral,
1588
+ low_quality: false,
1589
+ // 32
1590
+ owner: agentId,
1591
+ readers,
1592
+ writers
1593
+ };
1594
+ await ctx.addNote(note);
1595
+ console.log(` saved note ${note.id}`);
1596
+ try {
1597
+ const total = await ctx.countNotes(agentId);
1598
+ if (total > 1) {
1599
+ const candidates = await ctx.queryByEmbedding(embedding, 6, agentId, 0);
1600
+ const linkedIds = [];
1601
+ const linkedContents = [];
1602
+ for (const { note: cand, score } of candidates) {
1603
+ if (cand.id === note.id) continue;
1604
+ if (score < 0.3) continue;
1605
+ console.log(` candidate ${cand.id.slice(0, 8)}... sim=${score.toFixed(3)}, asking LLM...`);
1606
+ const shouldLink = await llmShouldLink(content, cand.content);
1607
+ if (shouldLink) {
1608
+ linkedIds.push(cand.id);
1609
+ linkedContents.push(cand.content);
1610
+ console.log(` \u2192 linked!`);
1611
+ }
1612
+ }
1613
+ if (linkedIds.length > 0) {
1614
+ note.links = linkedIds;
1615
+ await ctx.updateNote(note);
1616
+ for (const lid of linkedIds) {
1617
+ const linked = await ctx.getNote(lid, agentId);
1618
+ if (linked && !linked.links.includes(note.id)) {
1619
+ if (!canWrite(linked, agentId)) {
1620
+ console.log(`[link] back-link into ${lid.slice(0, 8)} skipped \u2014 not writable by ${logSafe(agentId)}`);
1621
+ continue;
1622
+ }
1623
+ linked.links.push(note.id);
1624
+ await ctx.updateNote(linked);
1625
+ }
1626
+ }
1627
+ if (shouldRunEvolution()) {
1628
+ console.log(` [evo] threshold reached, running evolution for ${Math.min(linkedIds.length, 3)} linked notes`);
1629
+ for (const lid of linkedIds.slice(0, 3)) {
1630
+ const linked = await ctx.getNote(lid, agentId);
1631
+ if (!linked) continue;
1632
+ if (!canWrite(linked, agentId)) {
1633
+ console.log(` [evo] skipping ${lid.slice(0, 8)} \u2014 not writable by ${logSafe(agentId)}`);
1634
+ continue;
1635
+ }
1636
+ const linkedNotes = [];
1637
+ for (const llid of linked.links.slice(0, 5)) {
1638
+ if (llid === note.id) continue;
1639
+ const ln = await ctx.getNote(llid, agentId);
1640
+ if (ln) linkedNotes.push({ id: ln.id, content: ln.content });
1641
+ }
1642
+ linkedNotes.push({ id: note.id, content });
1643
+ const oldTags = [...linked.tags];
1644
+ const oldContext = linked.context;
1645
+ const {
1646
+ tags: newTags,
1647
+ context: newContext,
1648
+ shouldStrengthen,
1649
+ suggestedConnections,
1650
+ tagsToUpdate
1651
+ } = await llmEvolveNote(linked.content, linkedNotes);
1652
+ let evolved = false;
1653
+ if (newTags !== null || newContext !== null) {
1654
+ if (newTags !== null) linked.tags = newTags;
1655
+ if (newContext !== null) linked.context = newContext;
1656
+ linked.evolution_history = linked.evolution_history || [];
1657
+ linked.evolution_history.push({
1658
+ triggeredBy: note.id,
1659
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
1660
+ oldContext,
1661
+ newContext: newContext ?? oldContext,
1662
+ oldTags,
1663
+ newTags: newTags ?? oldTags,
1664
+ action: "update_neighbor"
1665
+ });
1666
+ evolved = true;
1667
+ }
1668
+ let noteChanged = false;
1669
+ let noteTagsChanged = false;
1670
+ if (shouldStrengthen && suggestedConnections.length > 0) {
1671
+ for (const targetId of suggestedConnections) {
1672
+ if (!note.links.includes(targetId)) {
1673
+ note.links.push(targetId);
1674
+ noteChanged = true;
1675
+ }
1676
+ const target = await ctx.getNote(targetId, agentId);
1677
+ if (target && !target.links.includes(note.id)) {
1678
+ if (canWrite(target, agentId)) {
1679
+ target.links.push(note.id);
1680
+ await ctx.updateNote(target);
1681
+ } else {
1682
+ console.log(` [evo] strengthen back-link into ${targetId.slice(0, 8)} skipped \u2014 not writable`);
1683
+ }
1684
+ }
1685
+ }
1686
+ if (tagsToUpdate.length > 0) {
1687
+ note.tags = tagsToUpdate;
1688
+ noteChanged = true;
1689
+ noteTagsChanged = true;
1690
+ }
1691
+ linked.evolution_history = linked.evolution_history || [];
1692
+ linked.evolution_history.push({
1693
+ triggeredBy: note.id,
1694
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
1695
+ oldContext: linked.context,
1696
+ newContext: linked.context,
1697
+ oldTags: [...linked.tags],
1698
+ newTags: [...linked.tags],
1699
+ action: "strengthen",
1700
+ suggestedConnections,
1701
+ tagsUpdated: tagsToUpdate
1702
+ });
1703
+ evolved = true;
1704
+ }
1705
+ if (noteChanged) {
1706
+ if (noteTagsChanged) {
1707
+ note.embedding = await encode(buildEmbedText(note));
1708
+ }
1709
+ await ctx.updateNote(note);
1710
+ }
1711
+ if (evolved) {
1712
+ if (newTags !== null || newContext !== null) {
1713
+ linked.embedding = await encode(buildEmbedText(linked));
1714
+ }
1715
+ await ctx.updateNote(linked);
1716
+ console.log(` evolved/strengthened note ${lid.slice(0, 8)}...`);
1717
+ }
1718
+ }
1719
+ } else {
1720
+ console.log(` [evo] threshold not reached, skipping evolution this round`);
1721
+ }
1722
+ }
1723
+ }
1724
+ } catch (e) {
1725
+ console.error(`[warn] Link/Evolution phase failed: ${e.message}`);
1726
+ }
1727
+ console.log(`[done] Note added: ${note.id}`);
1728
+ return note.id;
1729
+ }
1730
+ async function addEpisodic(content, agentId = "main", opts) {
1731
+ const scope = opts?.scope ?? "private";
1732
+ const subjects = opts?.subjects ?? [];
1733
+ const ctx = opts?.storageCtx ?? defaultCtx();
1734
+ const quality = checkQuality(content);
1735
+ if (!quality.ok) {
1736
+ throw new Error(`[quality] \u5199\u5165\u62D2\u7EDD: ${quality.reason}`);
1737
+ }
1738
+ const embedding = await encode(content);
1739
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1740
+ const note = {
1741
+ id: uuidv4(),
1742
+ subjects,
1743
+ content,
1744
+ timestamp: now,
1745
+ keywords: [],
1746
+ tags: [],
1747
+ context: "",
1748
+ embedding,
1749
+ links: [],
1750
+ agent_id: scope === "shared" ? "shared" : agentId,
1751
+ hash: createHash("md5").update(content).digest("hex"),
1752
+ retrieval_count: 0,
1753
+ last_accessed: now,
1754
+ evolution_history: [],
1755
+ category: "General",
1756
+ is_active: true,
1757
+ note_type: "memory",
1758
+ topics: [],
1759
+ pending_merge: false,
1760
+ conflict: false,
1761
+ ephemeral: quality.ephemeral,
1762
+ low_quality: false,
1763
+ owner: agentId,
1764
+ readers: scope === "shared" ? ["*"] : [agentId],
1765
+ writers: [agentId]
1766
+ };
1767
+ await ctx.addNote(note);
1768
+ return note.id;
1769
+ }
1770
+ async function searchMemory(query, topK = 5, agentId = "main", opts) {
1771
+ const useBfs = opts?.useBfs !== false;
1772
+ const subject = opts?.subject;
1773
+ const bfsSimThreshold = opts?.bfsSimThreshold ?? 0.25;
1774
+ const ctx = opts?.storageCtx ?? defaultCtx();
1775
+ const total = await ctx.countNotes(agentId);
1776
+ if (total === 0) return [];
1777
+ const queryEmbedding = await encode(query);
1778
+ const n = Math.min(Math.max(topK * 4, 20), total);
1779
+ const embResults = await ctx.queryByEmbedding(queryEmbedding, n, agentId, 0, subject);
1780
+ const allNotes = await ctx.listNotes(agentId, subject);
1781
+ const bm25State = buildBM25(allNotes);
1782
+ const queryTokens = simpleTokenize(query);
1783
+ const bm25Ranked = bm25Score(bm25State, queryTokens).filter(([, score]) => score > 0).slice(0, n);
1784
+ const merged = rrfMerge(
1785
+ embResults.map((r) => r.note.id),
1786
+ bm25Ranked.map((r) => r[0])
1787
+ );
1788
+ const now = Date.now();
1789
+ const noteMap = new Map(allNotes.map((n2) => [n2.id, n2]));
1790
+ const boostedMerged = merged.map(([id, rrfScore]) => {
1791
+ const note = noteMap.get(id);
1792
+ if (!note) return [id, rrfScore];
1793
+ if (note.note_type === "knowledge") return [id, rrfScore];
1794
+ const lastAccessed = new Date(note.last_accessed || note.timestamp).getTime();
1795
+ const ageDays = (now - lastAccessed) / 864e5;
1796
+ const recencyBoost = 1 + 0.05 * Math.log(1 + (note.retrieval_count || 0)) / (ageDays + 1);
1797
+ return [id, rrfScore * recencyBoost];
1798
+ });
1799
+ boostedMerged.sort((a, b) => b[1] - a[1]);
1800
+ const topIds = boostedMerged.slice(0, topK).map(([id]) => id);
1801
+ const BFS_MAX_HOPS = 2;
1802
+ const BFS_MAX_EXPAND = 8;
1803
+ const visitedIds = new Set(topIds);
1804
+ const bfsQueue = useBfs ? topIds.map((id) => ({ id, hop: 0 })) : [];
1805
+ const bfsExtra = [];
1806
+ const bfsSimMap = /* @__PURE__ */ new Map();
1807
+ while (bfsQueue.length > 0 && bfsExtra.length < BFS_MAX_EXPAND) {
1808
+ const item = bfsQueue.shift();
1809
+ if (item.hop >= BFS_MAX_HOPS) continue;
1810
+ const note = noteMap.get(item.id);
1811
+ if (!note) continue;
1812
+ for (const linkedId of note.links) {
1813
+ if (visitedIds.has(linkedId)) continue;
1814
+ visitedIds.add(linkedId);
1815
+ const linked = noteMap.get(linkedId);
1816
+ if (!linked || linked.is_active === false) continue;
1817
+ const sim = cosineSimilarity(queryEmbedding, linked.embedding);
1818
+ if (bfsSimThreshold > 0 && sim < bfsSimThreshold) continue;
1819
+ bfsSimMap.set(linkedId, sim);
1820
+ bfsExtra.push(linkedId);
1821
+ bfsQueue.push({ id: linkedId, hop: item.hop + 1 });
1822
+ if (bfsExtra.length >= BFS_MAX_EXPAND) break;
1823
+ }
1824
+ }
1825
+ const topicsFilter = opts?.topicsFilter;
1826
+ const filteredTopIds = topicsFilter && topicsFilter.length > 0 ? topIds.filter((id) => {
1827
+ const note = noteMap.get(id);
1828
+ if (!note) return false;
1829
+ if (note.note_type !== "knowledge") return true;
1830
+ return topicsFilter.every((t2) => note.topics.map((s) => s.toLowerCase()).includes(t2.toLowerCase()));
1831
+ }) : topIds;
1832
+ const embSimMap = new Map(embResults.map((r) => [r.note.id, r.score]));
1833
+ const rrfMap = new Map(boostedMerged.map(([id, score]) => [id, score]));
1834
+ const results = [];
1835
+ const ordered = [
1836
+ ...filteredTopIds.map((id) => [id, "match"]),
1837
+ ...bfsExtra.map((id) => [id, "link"])
1838
+ ];
1839
+ for (const [id, via] of ordered) {
1840
+ const note = noteMap.get(id);
1841
+ if (!note) continue;
1842
+ results.push({
1843
+ id: note.id,
1844
+ content: note.content,
1845
+ context: note.context,
1846
+ tags: note.tags,
1847
+ keywords: note.keywords,
1848
+ links: note.links,
1849
+ timestamp: note.timestamp,
1850
+ similarity: embSimMap.get(id) ?? bfsSimMap.get(id) ?? 0,
1851
+ rrf: rrfMap.get(id) ?? 0,
1852
+ via,
1853
+ topics: note.topics ?? [],
1854
+ note_type: note.note_type ?? "memory"
1855
+ });
1856
+ }
1857
+ return results;
1858
+ }
1859
+ async function listMemories(agentId = "main", storageCtx) {
1860
+ const ctx = storageCtx ?? defaultCtx();
1861
+ const count = await ctx.countNotes(agentId);
1862
+ return { count };
1863
+ }
1864
+ function sleep(ms) {
1865
+ return new Promise((resolve) => setTimeout(resolve, ms));
1866
+ }
1867
+ async function mergeSimilarNotes(agentId, storageCtx) {
1868
+ const ctx = storageCtx ?? defaultCtx();
1869
+ const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1870
+ const allNotes = await ctx.getNotesByDatePrefix(today, agentId);
1871
+ const notes = allNotes.filter((n) => n.agent_id !== "shared");
1872
+ const pendingNotes = notes.filter((n) => n.pending_merge === true);
1873
+ let evolvedCount = 0;
1874
+ for (const pendingNote of pendingNotes) {
1875
+ let bestSim = -1;
1876
+ let bestNeighbor = null;
1877
+ for (const other of notes) {
1878
+ if (other.id === pendingNote.id) continue;
1879
+ if (other.pending_merge) continue;
1880
+ if (!other.embedding.length || !pendingNote.embedding.length) continue;
1881
+ const sim = cosineSimilarity(pendingNote.embedding, other.embedding);
1882
+ if (sim > bestSim) {
1883
+ bestSim = sim;
1884
+ bestNeighbor = other;
1885
+ }
1886
+ }
1887
+ if (!bestNeighbor) {
1888
+ await ctx.patchNotePayload(pendingNote.id, { pending_merge: false });
1889
+ continue;
1890
+ }
1891
+ const judgment = await llmEvolutionJudge(bestNeighbor.content, pendingNote.content);
1892
+ console.log(
1893
+ `[merge] evolution judgment: ${pendingNote.id.slice(0, 8)} \u2192 ${bestNeighbor.id.slice(0, 8)}: ${judgment.type}`
1894
+ );
1895
+ if (judgment.type === "EVOLVE") {
1896
+ const oldHistory = bestNeighbor.evolution_history || [];
1897
+ oldHistory.push({
1898
+ triggeredBy: pendingNote.id,
1899
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
1900
+ oldContext: bestNeighbor.context,
1901
+ newContext: bestNeighbor.context,
1902
+ oldTags: [...bestNeighbor.tags],
1903
+ newTags: [...bestNeighbor.tags],
1904
+ action: "consolidate"
1905
+ });
1906
+ const mergedContent = judgment.mergedContent || pendingNote.content;
1907
+ const newEmbedding = await encode(buildEmbedText({ ...bestNeighbor, content: mergedContent }));
1908
+ const newHash = createHash("md5").update(mergedContent).digest("hex");
1909
+ await ctx.updateNoteContent(bestNeighbor.id, mergedContent, newEmbedding, newHash, agentId);
1910
+ await ctx.patchNotePayload(bestNeighbor.id, {
1911
+ evolution_history: JSON.stringify(oldHistory),
1912
+ evolution_type: "EVOLVE"
1913
+ });
1914
+ await ctx.deleteNote(pendingNote.id);
1915
+ evolvedCount++;
1916
+ } else if (judgment.type === "CONFLICT") {
1917
+ await ctx.patchNotePayload(pendingNote.id, { pending_merge: false, conflict: true, evolution_type: "CONFLICT" });
1918
+ await ctx.patchNotePayload(bestNeighbor.id, { conflict: true, evolution_type: "CONFLICT" });
1919
+ } else if (judgment.type === "EXPAND") {
1920
+ const oldHistory = bestNeighbor.evolution_history || [];
1921
+ oldHistory.push({
1922
+ triggeredBy: pendingNote.id,
1923
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
1924
+ oldContext: bestNeighbor.context,
1925
+ newContext: bestNeighbor.context,
1926
+ oldTags: [...bestNeighbor.tags],
1927
+ newTags: [...bestNeighbor.tags],
1928
+ action: "consolidate"
1929
+ });
1930
+ const mergedContent = judgment.mergedContent || `${bestNeighbor.content}\uFF1B${pendingNote.content}`;
1931
+ const newEmbedding = await encode(buildEmbedText({ ...bestNeighbor, content: mergedContent }));
1932
+ const newHash = createHash("md5").update(mergedContent).digest("hex");
1933
+ await ctx.updateNoteContent(bestNeighbor.id, mergedContent, newEmbedding, newHash, agentId);
1934
+ await ctx.patchNotePayload(bestNeighbor.id, {
1935
+ evolution_history: JSON.stringify(oldHistory),
1936
+ evolution_type: "EXPAND"
1937
+ });
1938
+ await ctx.deleteNote(pendingNote.id);
1939
+ evolvedCount++;
1940
+ } else {
1941
+ await ctx.patchNotePayload(pendingNote.id, { pending_merge: false, evolution_type: "NEW" });
1942
+ }
1943
+ await sleep(200);
1944
+ }
1945
+ if (notes.length < 5) return evolvedCount;
1946
+ const pendingIds = new Set(pendingNotes.map((n) => n.id));
1947
+ const pairs = [];
1948
+ for (let i = 0; i < notes.length; i++) {
1949
+ if (pendingIds.has(notes[i].id)) continue;
1950
+ for (let j = i + 1; j < notes.length; j++) {
1951
+ if (pendingIds.has(notes[j].id)) continue;
1952
+ if (!notes[i].embedding.length || !notes[j].embedding.length) continue;
1953
+ const sim = cosineSimilarity(notes[i].embedding, notes[j].embedding);
1954
+ if (sim >= 0.8) {
1955
+ pairs.push({ i, j, sim });
1956
+ }
1957
+ }
1958
+ }
1959
+ if (pairs.length === 0) return evolvedCount;
1960
+ pairs.sort((a, b) => b.sim - a.sim);
1961
+ const topPairs = pairs.slice(0, 10);
1962
+ const deletedIds = /* @__PURE__ */ new Set();
1963
+ let mergedCount = 0;
1964
+ for (const { i, j } of topPairs) {
1965
+ const noteA = notes[i];
1966
+ const noteB = notes[j];
1967
+ if (deletedIds.has(noteA.id) || deletedIds.has(noteB.id)) continue;
1968
+ const result = await llmShouldMerge(noteA.content, noteB.content);
1969
+ if (result.shouldMerge && result.merged) {
1970
+ const [keepNote, dropNote] = noteA.content.length >= noteB.content.length ? [noteA, noteB] : [noteB, noteA];
1971
+ const newEmbedding = await encode(result.merged);
1972
+ const newHash = createHash("md5").update(result.merged).digest("hex");
1973
+ await ctx.updateNoteContent(keepNote.id, result.merged, newEmbedding, newHash, agentId);
1974
+ await ctx.deleteNote(dropNote.id);
1975
+ deletedIds.add(dropNote.id);
1976
+ mergedCount++;
1977
+ }
1978
+ await sleep(200);
1979
+ }
1980
+ return evolvedCount + mergedCount;
1981
+ }
1982
+ async function consolidateMemories(agentId, logger, storageCtx) {
1983
+ const ctx = storageCtx ?? defaultCtx();
1984
+ const log = {
1985
+ info: (msg) => logger ? logger.info(msg) : console.log(msg),
1986
+ warn: (msg) => logger ? logger.warn(msg) : console.warn(msg),
1987
+ error: (msg) => logger ? logger.error(msg) : console.error(msg)
1988
+ };
1989
+ log.info(`[Consolidation] Starting consolidation for agentId: ${agentId}`);
1990
+ const rawNotes = await ctx.listNotes(agentId);
1991
+ const allNotes = rawNotes.filter((n) => n.agent_id !== "shared");
1992
+ log.info(
1993
+ `[Consolidation] Loaded ${allNotes.length} active private notes (${rawNotes.length - allNotes.length} shared skipped).`
1994
+ );
1995
+ const groups = /* @__PURE__ */ new Map();
1996
+ for (const note of allNotes) {
1997
+ if (note.note_type === "knowledge") continue;
1998
+ const category = note.category || "General";
1999
+ if (!groups.has(category)) {
2000
+ groups.set(category, []);
2001
+ }
2002
+ groups.get(category).push(note);
2003
+ }
2004
+ const candidates = [];
2005
+ for (const [category, groupNotes] of groups.entries()) {
2006
+ log.info(`[Consolidation] Category "${category}" has ${groupNotes.length} notes.`);
2007
+ for (let i = 0; i < groupNotes.length; i++) {
2008
+ for (let j = i + 1; j < groupNotes.length; j++) {
2009
+ const noteA = groupNotes[i];
2010
+ const noteB = groupNotes[j];
2011
+ if (!noteA.embedding.length || !noteB.embedding.length) continue;
2012
+ const sim = cosineSimilarity(noteA.embedding, noteB.embedding);
2013
+ if (sim >= 0.75) {
2014
+ candidates.push({ noteA, noteB, similarity: sim });
2015
+ }
2016
+ }
2017
+ }
2018
+ }
2019
+ candidates.sort((a, b) => b.similarity - a.similarity);
2020
+ const topPairs = candidates.slice(0, 15);
2021
+ log.info(
2022
+ `[Consolidation] Found ${candidates.length} candidate pairs with similarity >= 0.75. Processing top ${topPairs.length}.`
2023
+ );
2024
+ const processedIds = /* @__PURE__ */ new Set();
2025
+ let mergedCount = 0;
2026
+ function logMergeToFile(keepId, dropId, mergedContent) {
2027
+ const logDir = path3.join(getDataDir(), "logs");
2028
+ const logFile = path3.join(logDir, "amem-consolidate.log");
2029
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
2030
+ const logMsg = `[${timestamp}] Consolidated: KeepNote ${keepId} and DropNote ${dropId}. Merged length: ${mergedContent.length} chars.
2031
+ `;
2032
+ try {
2033
+ fs2.mkdirSync(logDir, { recursive: true });
2034
+ fs2.appendFileSync(logFile, logMsg, "utf8");
2035
+ } catch (err) {
2036
+ log.error(`[Consolidation] Failed to write log: ${err.message}`);
2037
+ }
2038
+ }
2039
+ for (const { noteA, noteB, similarity } of topPairs) {
2040
+ if (processedIds.has(noteA.id) || processedIds.has(noteB.id)) {
2041
+ log.info(
2042
+ `[Consolidation] Skipping pair (${noteA.id.slice(0, 8)}, ${noteB.id.slice(0, 8)}) as one or both already merged.`
2043
+ );
2044
+ continue;
2045
+ }
2046
+ log.info(
2047
+ `[Consolidation] Evaluating pair (${noteA.id.slice(0, 8)}, ${noteB.id.slice(0, 8)}) with sim ${similarity.toFixed(4)}...`
2048
+ );
2049
+ const mergeDecision = await llmShouldMerge(noteA.content, noteB.content);
2050
+ if (mergeDecision.shouldMerge && mergeDecision.merged) {
2051
+ log.info(` -> LLM decision: MERGE!`);
2052
+ const [keepNote, dropNote] = noteA.content.length >= noteB.content.length ? [noteA, noteB] : [noteB, noteA];
2053
+ log.info(
2054
+ ` -> KeepNote: ${keepNote.id.slice(0, 8)} (len: ${keepNote.content.length}), DropNote: ${dropNote.id.slice(0, 8)} (len: ${dropNote.content.length})`
2055
+ );
2056
+ const oldContext = keepNote.context;
2057
+ const oldTags = [...keepNote.tags];
2058
+ keepNote.content = mergeDecision.merged;
2059
+ keepNote.tags = Array.from(/* @__PURE__ */ new Set([...keepNote.tags, ...dropNote.tags]));
2060
+ keepNote.keywords = Array.from(/* @__PURE__ */ new Set([...keepNote.keywords, ...dropNote.keywords]));
2061
+ keepNote.links = Array.from(/* @__PURE__ */ new Set([...keepNote.links, ...dropNote.links])).filter(
2062
+ (id) => id !== keepNote.id && id !== dropNote.id
2063
+ );
2064
+ keepNote.retrieval_count = (keepNote.retrieval_count || 0) + (dropNote.retrieval_count || 0);
2065
+ const keepAccessTime = new Date(keepNote.last_accessed || keepNote.timestamp).getTime();
2066
+ const dropAccessTime = new Date(dropNote.last_accessed || dropNote.timestamp).getTime();
2067
+ keepNote.last_accessed = keepAccessTime >= dropAccessTime ? keepNote.last_accessed || keepNote.timestamp : dropNote.last_accessed || dropNote.timestamp;
2068
+ const embedText = buildEmbedText(keepNote);
2069
+ keepNote.embedding = await encode(embedText);
2070
+ keepNote.hash = createHash("md5").update(keepNote.content).digest("hex");
2071
+ keepNote.evolution_history = keepNote.evolution_history || [];
2072
+ keepNote.evolution_history.push({
2073
+ triggeredBy: dropNote.id,
2074
+ triggeredAt: (/* @__PURE__ */ new Date()).toISOString(),
2075
+ oldContext,
2076
+ newContext: keepNote.context,
2077
+ oldTags,
2078
+ newTags: keepNote.tags,
2079
+ action: "consolidate"
2080
+ });
2081
+ await ctx.updateNote(keepNote);
2082
+ await ctx.invalidateNote(dropNote.id, agentId);
2083
+ await ctx.replaceLinkReferences(dropNote.id, keepNote.id, agentId);
2084
+ logMergeToFile(keepNote.id, dropNote.id, keepNote.content);
2085
+ processedIds.add(keepNote.id);
2086
+ processedIds.add(dropNote.id);
2087
+ mergedCount++;
2088
+ } else {
2089
+ log.info(` -> LLM decision: DO NOT MERGE.`);
2090
+ }
2091
+ await sleep(200);
2092
+ }
2093
+ log.info(`[Consolidation] Completed consolidation run. Merged ${mergedCount} pairs.`);
2094
+ return mergedCount;
2095
+ }
2096
+ function resolveConflictMode(override) {
2097
+ const raw = (process.env.AMEM_CONFLICT_MODE || override || "review").trim().toLowerCase();
2098
+ return raw === "auto" ? "auto" : "review";
2099
+ }
2100
+ var CONFLICT_BATCH_SIZE = 25;
2101
+ async function conflictSweep(agentId, opts) {
2102
+ const ctx = opts?.storageCtx ?? defaultCtx();
2103
+ const force = opts?.force === true;
2104
+ const mode = resolveConflictMode(opts?.mode);
2105
+ const log = opts?.logger?.info ?? ((m) => console.log(m));
2106
+ const raw = await ctx.listNotes(agentId);
2107
+ const notes = raw.filter((n) => n.agent_id !== "shared" && n.note_type !== "knowledge" && n.is_active !== false);
2108
+ const groups = /* @__PURE__ */ new Map();
2109
+ for (const n of notes) {
2110
+ const c = n.category || "General";
2111
+ if (!groups.has(c)) groups.set(c, []);
2112
+ groups.get(c).push(n);
2113
+ }
2114
+ let pairsFound = 0;
2115
+ let retired = 0;
2116
+ let batchesScanned = 0;
2117
+ let batchesSkipped = 0;
2118
+ for (const [category, groupNotes] of groups.entries()) {
2119
+ groupNotes.sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
2120
+ for (let start = 0; start < groupNotes.length; start += CONFLICT_BATCH_SIZE) {
2121
+ const batch = groupNotes.slice(start, start + CONFLICT_BATCH_SIZE);
2122
+ if (batch.length < 2) continue;
2123
+ if (!force && batch.every((n) => n.conflict_scanned_at)) {
2124
+ batchesSkipped++;
2125
+ continue;
2126
+ }
2127
+ batchesScanned++;
2128
+ const pairs = await llmConflictScan(batch.map((n) => n.content));
2129
+ for (const { a, b, reason, supersededIndex } of pairs) {
2130
+ const noteA = batch[a];
2131
+ const noteB = batch[b];
2132
+ if (!noteA || !noteB) continue;
2133
+ pairsFound++;
2134
+ await ctx.patchNotePayload(noteA.id, {
2135
+ conflict: true,
2136
+ evolution_type: "CONFLICT",
2137
+ conflicts_with: Array.from(/* @__PURE__ */ new Set([...noteA.conflicts_with ?? [], noteB.id])),
2138
+ conflict_reason: reason
2139
+ });
2140
+ await ctx.patchNotePayload(noteB.id, {
2141
+ conflict: true,
2142
+ evolution_type: "CONFLICT",
2143
+ conflicts_with: Array.from(/* @__PURE__ */ new Set([...noteB.conflicts_with ?? [], noteA.id])),
2144
+ conflict_reason: reason
2145
+ });
2146
+ log(`[conflict] ${category}: ${noteA.id.slice(0, 8)} \u2194 ${noteB.id.slice(0, 8)} \u2014 ${reason}`);
2147
+ if (mode === "auto") {
2148
+ const superseded = supersededIndex === a ? noteA : supersededIndex === b ? noteB : null;
2149
+ if (!superseded) {
2150
+ log(`[conflict] auto: no superseded side identified \u2014 marked only, nothing retired`);
2151
+ } else {
2152
+ const ok = await ctx.invalidateNote(superseded.id, agentId);
2153
+ if (ok) {
2154
+ retired++;
2155
+ log(`[conflict] auto-retired the superseded note ${superseded.id.slice(0, 8)}`);
2156
+ }
2157
+ }
2158
+ }
2159
+ }
2160
+ const scannedAt = (/* @__PURE__ */ new Date()).toISOString();
2161
+ for (const n of batch) {
2162
+ await ctx.patchNotePayload(n.id, { conflict_scanned_at: scannedAt });
2163
+ }
2164
+ }
2165
+ }
2166
+ log(
2167
+ `[conflict] ${batchesScanned} batch(es) scanned, ${batchesSkipped} already up to date; ${pairsFound} pair(s) found, ${retired} retired`
2168
+ );
2169
+ return { scanned: notes.length, pairsFound, retired, batchesScanned, batchesSkipped };
2170
+ }
2171
+
2172
+ // src/migrate.ts
2173
+ function missingDerivedFields(n) {
2174
+ return n.keywords.length === 0 || n.tags.length === 0;
2175
+ }
2176
+ async function migrateCollection(opts) {
2177
+ const { from, to } = opts;
2178
+ const refreshFields = opts.refreshFields !== false;
2179
+ const dryRun = opts.dryRun !== false;
2180
+ const log = opts.logger?.info ?? ((m) => console.log(m));
2181
+ const warn = opts.logger?.warn ?? ((m) => console.warn(m));
2182
+ if (from === to) throw new Error(`migrate: source and target are the same collection ("${from}")`);
2183
+ const model = getEmbeddingModel();
2184
+ const targetDim = await getEmbeddingDim();
2185
+ const sourceDim = await collectionDimRaw(from);
2186
+ if (sourceDim === null) throw new Error(`migrate: source collection "${from}" does not exist`);
2187
+ const points = await scrollAllRaw(from);
2188
+ const notes = points.map(pointToNote);
2189
+ const missingDerived = notes.filter(missingDerivedFields).length;
2190
+ log(
2191
+ `[migrate] ${from} (${sourceDim}d, ${notes.length} notes) \u2192 ${to} (${targetDim}d, ${model}); ${missingDerived} note(s) missing keywords/tags`
2192
+ );
2193
+ if (dryRun) {
2194
+ log("[migrate] dry run \u2014 nothing written. Pass dryRun: false to apply.");
2195
+ return {
2196
+ total: notes.length,
2197
+ missingDerived,
2198
+ refreshed: 0,
2199
+ migrated: 0,
2200
+ skipped: 0,
2201
+ sourceDim,
2202
+ targetDim,
2203
+ model,
2204
+ dryRun: true
2205
+ };
2206
+ }
2207
+ let alreadyDone = /* @__PURE__ */ new Set();
2208
+ const existingTargetDim = await collectionDimRaw(to);
2209
+ if (existingTargetDim === null) {
2210
+ await createCollectionRaw(to, targetDim);
2211
+ log(`[migrate] created ${to} at ${targetDim}d`);
2212
+ } else {
2213
+ if (existingTargetDim !== targetDim) {
2214
+ throw new Error(`migrate: target "${to}" exists at ${existingTargetDim}d but the model produces ${targetDim}d`);
2215
+ }
2216
+ const present = await scrollIdsRaw(to);
2217
+ if (present.size > 0) {
2218
+ const sourceIds = new Set(notes.map((n) => n.id));
2219
+ const foreign = [...present].filter((id) => !sourceIds.has(id));
2220
+ if (foreign.length > 0) {
2221
+ throw new Error(
2222
+ `migrate: target "${to}" holds ${foreign.length} point(s) that are not in "${from}" (e.g. ${foreign[0]}). That is not an interrupted migration \u2014 use a different target.`
2223
+ );
2224
+ }
2225
+ alreadyDone = present;
2226
+ log(`[migrate] resuming: ${present.size} of ${notes.length} already in ${to}`);
2227
+ }
2228
+ }
2229
+ let refreshed = 0;
2230
+ let migrated = 0;
2231
+ const BATCH = 64;
2232
+ let buffer = [];
2233
+ const flush = async () => {
2234
+ if (!buffer.length) return;
2235
+ await upsertPointsRaw(to, buffer);
2236
+ migrated += buffer.length;
2237
+ buffer = [];
2238
+ };
2239
+ for (const note of notes) {
2240
+ if (alreadyDone.has(note.id)) continue;
2241
+ if (refreshFields && missingDerivedFields(note)) {
2242
+ try {
2243
+ const built = await llmConstructNote(note.content);
2244
+ if (note.keywords.length === 0) note.keywords = built.keywords;
2245
+ if (note.tags.length === 0) note.tags = built.tags;
2246
+ if (!note.context) note.context = built.context;
2247
+ refreshed++;
2248
+ } catch (e) {
2249
+ warn(`[migrate] re-extract failed for ${note.id.slice(0, 8)} \u2014 keeping as-is: ${e.message}`);
2250
+ }
2251
+ }
2252
+ const point = noteToPoint({ ...note, embedding: await encode(buildEmbedText(note)) });
2253
+ buffer.push(point);
2254
+ if (buffer.length >= BATCH) {
2255
+ await flush();
2256
+ log(`[migrate] ${alreadyDone.size + migrated}/${notes.length}`);
2257
+ }
2258
+ }
2259
+ await flush();
2260
+ const finalCount = await countPointsRaw(to);
2261
+ if (finalCount !== notes.length) {
2262
+ warn(`[migrate] target holds ${finalCount} point(s) but the source had ${notes.length} \u2014 check before switching`);
2263
+ }
2264
+ log(`[migrate] done: ${migrated} written, ${alreadyDone.size} already present, ${refreshed} re-extracted.`);
2265
+ return {
2266
+ total: notes.length,
2267
+ missingDerived,
2268
+ refreshed,
2269
+ migrated,
2270
+ skipped: alreadyDone.size,
2271
+ sourceDim,
2272
+ targetDim,
2273
+ model,
2274
+ dryRun: false
2275
+ };
2276
+ }
2277
+ async function switchToMigrated(opts) {
2278
+ const { name, to } = opts;
2279
+ const log = opts.logger?.info ?? ((m) => console.log(m));
2280
+ if (name === to) throw new Error(`switch: "${name}" and "${to}" are the same collection`);
2281
+ const already = await resolveAliasRaw(name);
2282
+ if (already === to) {
2283
+ log(`[switch] "${name}" already points at "${to}" \u2014 nothing to do`);
2284
+ return { name, to, moved: await countPointsRaw(to) };
2285
+ }
2286
+ const targetCount = await countPointsRaw(to);
2287
+ if (targetCount === 0) throw new Error(`switch: "${to}" is empty \u2014 migrate into it first`);
2288
+ if (already === null) {
2289
+ const sourceCount = await countPointsRaw(name);
2290
+ if (targetCount < sourceCount) {
2291
+ throw new Error(
2292
+ `switch: "${to}" holds ${targetCount} point(s) but "${name}" still holds ${sourceCount}. The migration is not finished \u2014 run it again before switching.`
2293
+ );
2294
+ }
2295
+ log(`[switch] verified ${targetCount} in "${to}" against ${sourceCount} in "${name}"`);
2296
+ await deleteCollectionRaw(name);
2297
+ log(`[switch] dropped "${name}"`);
2298
+ await createAliasRaw(name, to);
2299
+ } else {
2300
+ await setAliasRaw(name, to);
2301
+ }
2302
+ log(`[switch] "${name}" now resolves to "${to}"`);
2303
+ return { name, to, moved: targetCount };
2304
+ }
2305
+
2306
+ export {
2307
+ SYSTEM_ACTOR,
2308
+ canWrite,
2309
+ canRead,
2310
+ DEFAULT_EMBEDDING_MODEL,
2311
+ LEGACY_DEFAULT_EMBEDDING_MODEL,
2312
+ LEGACY_DEFAULT_DIM,
2313
+ getEmbeddingModel,
2314
+ getEmbeddingPooling,
2315
+ getEmbeddingDevice,
2316
+ getEmbeddingDtype,
2317
+ getEmbeddingDim,
2318
+ encode,
2319
+ loadModel,
2320
+ isModelLoaded,
2321
+ cosineSimilarity,
2322
+ getCollection,
2323
+ EmbeddingDimensionMismatchError,
2324
+ EmbeddingModelMismatchError,
2325
+ MixedEmbeddingModelsError,
2326
+ pingQdrant,
2327
+ ensureCollection,
2328
+ countPointsRaw,
2329
+ collectionDimRaw,
2330
+ scrollIdsRaw,
2331
+ resolveAliasRaw,
2332
+ createStorageContext,
2333
+ getNote,
2334
+ updateNote,
2335
+ listNotes,
2336
+ deleteNote,
2337
+ invalidateNote,
2338
+ patchNotePayload,
2339
+ configureLlm,
2340
+ llmCrudDecision,
2341
+ configure,
2342
+ checkQuality,
2343
+ addMemory,
2344
+ addEpisodic,
2345
+ searchMemory,
2346
+ listMemories,
2347
+ mergeSimilarNotes,
2348
+ consolidateMemories,
2349
+ conflictSweep,
2350
+ migrateCollection,
2351
+ switchToMigrated
2352
+ };
2353
+ //# sourceMappingURL=chunk-K6WZTDM7.js.map