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