@astratra/memory 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/memory.js ADDED
@@ -0,0 +1,672 @@
1
+ /**
2
+ * Per-person memories of an AI assistant.
3
+ *
4
+ * A memory belongs to one place, `{ ownerId, scope }` — a person, and the
5
+ * partition the consumer chooses (a tenant, a workspace, '' for none). Every
6
+ * read and every write carries that place to the store; nothing here can reach
7
+ * another person's memories, except purgeOwner(), which erases one person
8
+ * everywhere on purpose.
9
+ *
10
+ * Storage, embeddings, the model, the clock, ids, encryption and logs are all
11
+ * injected. Without embeddings recall ranks by words and recency; without a
12
+ * model there is no consolidation. Nothing else degrades.
13
+ *
14
+ * A correction never overwrites: it writes a new memory and marks the old one
15
+ * superseded, so undo() puts the old one back. A forget erases the memory AND
16
+ * the versions it replaced — an "erased" memory whose earlier wording is still
17
+ * in the table is not erased.
18
+ */
19
+ const { randomUUID } = require('crypto');
20
+ const {
21
+ REASONS,
22
+ wordsOf,
23
+ cleanText,
24
+ normalizeKind,
25
+ normalizeImportance,
26
+ checkCandidate
27
+ } = require('./rules');
28
+ const { cosine, keywordScore, fuseByRank, buildPortrait } = require('./ranking');
29
+ const { parseModelJson, defaultConsolidationPrompt, transcriptText } = require('./consolidation');
30
+
31
+ const DEFAULT_KINDS = Object.freeze(['goal', 'preference', 'fact', 'person', 'event', 'feeling']);
32
+ const CHANNELS = Object.freeze({ EXPLICIT: 'explicit', AUTO: 'auto', BACKGROUND: 'background' });
33
+ const REQUIRED_STORE = ['insert', 'get', 'list', 'update', 'remove', 'removeAll', 'purgeOwner', 'getSettings', 'setSettings'];
34
+ const NOOP_LOGGER = { info() {}, warn() {}, error() {} };
35
+
36
+ class MemoryError extends Error {
37
+ constructor(code, message) {
38
+ super(message || code);
39
+ this.name = 'MemoryError';
40
+ this.code = code;
41
+ }
42
+ }
43
+
44
+ function assertStore(store) {
45
+ if (!store || typeof store !== 'object') throw new MemoryError('invalid_store', 'createMemory requires options.store.');
46
+ const missing = REQUIRED_STORE.filter((name) => typeof store[name] !== 'function');
47
+ if (missing.length) throw new MemoryError('invalid_store', `options.store is missing: ${missing.join(', ')}.`);
48
+ }
49
+
50
+ /* A missing owner is a bug in the caller, never "everybody": it throws. */
51
+ function placeOf(where) {
52
+ const ownerId = where && where.ownerId !== undefined && where.ownerId !== null ? String(where.ownerId) : '';
53
+ if (!ownerId) throw new MemoryError('invalid_where', 'A memory operation needs where.ownerId.');
54
+ const scope = where.scope === undefined || where.scope === null ? '' : String(where.scope);
55
+ return { ownerId, scope };
56
+ }
57
+
58
+ function dateOf(value, code) {
59
+ if (value === undefined || value === null || value === '') return null;
60
+ const date = value instanceof Date ? value : new Date(value);
61
+ if (Number.isNaN(date.getTime())) throw new MemoryError(code, `${code}: not a date.`);
62
+ return date;
63
+ }
64
+
65
+ /* One queue per place in this process: two writes for one person never interleave. */
66
+ function createLocalLock() {
67
+ const tails = new Map();
68
+ return async function withLock(where, fn) {
69
+ const key = `${where.ownerId}\u0000${where.scope}`;
70
+ const previous = tails.get(key) || Promise.resolve();
71
+ let release;
72
+ const current = new Promise((resolve) => { release = resolve; });
73
+ const tail = previous.then(() => current);
74
+ tails.set(key, tail);
75
+ await previous;
76
+ try {
77
+ return await fn();
78
+ } finally {
79
+ release();
80
+ if (tails.get(key) === tail) tails.delete(key);
81
+ }
82
+ };
83
+ }
84
+
85
+ /**
86
+ * @param {object} options see index.d.ts (MemoryOptions).
87
+ */
88
+ function createMemory(options = {}) {
89
+ const store = options.store;
90
+ assertStore(store);
91
+
92
+ const kinds = [...(options.kinds || DEFAULT_KINDS)];
93
+ if (!kinds.length) throw new MemoryError('invalid_kinds', 'options.kinds must not be empty.');
94
+ const kindAliases = options.kindAliases || {};
95
+ const defaultKind = options.defaultKind ?? null;
96
+ if (defaultKind !== null && !kinds.includes(defaultKind)) {
97
+ throw new MemoryError('invalid_kinds', 'options.defaultKind must be one of options.kinds.');
98
+ }
99
+ const roleKinds = options.roleKinds || {};
100
+ const rules = [...(options.rules || [])];
101
+ const namesOf = options.namesOf || null;
102
+ const embed = options.embed || null;
103
+ const mask = options.mask || ((text) => text);
104
+ const llm = options.llm || null;
105
+ const cipher = options.cipher || null;
106
+ const now = options.now || (() => new Date());
107
+ const generateId = options.generateId || (() => randomUUID());
108
+ const logger = { ...NOOP_LOGGER, ...(options.logger || {}) };
109
+ const withLock = options.withLock || createLocalLock();
110
+ const maxTextLength = options.maxTextLength ?? 500;
111
+ const maxActive = options.maxActive === undefined ? 300 : options.maxActive;
112
+ const duplicateThreshold = options.duplicateThreshold ?? 0.92;
113
+ const minSimilarity = options.minSimilarity ?? null;
114
+ const consolidationPrompt = options.consolidationPrompt || defaultConsolidationPrompt;
115
+ const isExplicitFact = options.isExplicitFact || null;
116
+ const knownForConsolidation = options.knownForConsolidation ?? 60;
117
+ const knownTextMax = options.knownTextMax ?? 240;
118
+ const transcriptMax = options.transcriptMax ?? 40000;
119
+
120
+ const ruleConfig = { kinds, roleKinds, rules, maxTextLength };
121
+ const kindOf = (value, fallback = defaultKind) => normalizeKind(value, { kinds, aliases: kindAliases, fallback });
122
+
123
+ /* ---- text in and out of the store ----------------------------------- */
124
+
125
+ async function seal(text) {
126
+ if (!cipher) return text;
127
+ const value = await cipher.encrypt(text);
128
+ /* An encrypt that hands the text back has no key: refuse rather than store it in clear. */
129
+ if (typeof value !== 'string' || value === text) throw new MemoryError('encryption_unavailable');
130
+ return value;
131
+ }
132
+
133
+ async function open(record) {
134
+ if (!record) return null;
135
+ if (!cipher) return record;
136
+ return { ...record, text: await cipher.decrypt(record.text) };
137
+ }
138
+
139
+ const openAll = (rows) => Promise.all((rows || []).map(open));
140
+
141
+ /* What leaves the package: never the vector. */
142
+ function publicMemory(record) {
143
+ if (!record) return null;
144
+ const out = {
145
+ id: record.id,
146
+ ownerId: record.ownerId,
147
+ scope: record.scope,
148
+ role: record.role ?? null,
149
+ text: record.text,
150
+ kind: record.kind,
151
+ importance: record.importance,
152
+ source: record.source || {},
153
+ supersededBy: record.supersededBy || null,
154
+ seenAt: record.seenAt || null,
155
+ lastUsedAt: record.lastUsedAt || null,
156
+ createdAt: record.createdAt,
157
+ updatedAt: record.updatedAt,
158
+ hasVector: Array.isArray(record.vector) && record.vector.length > 0
159
+ };
160
+ if (typeof record.score === 'number') out.score = record.score;
161
+ return out;
162
+ }
163
+
164
+ /* ---- embeddings ------------------------------------------------------ */
165
+
166
+ async function vectorFor(text, purpose, where, extra = {}) {
167
+ if (!embed) return null;
168
+ try {
169
+ const out = await embed(await mask(text, where), { purpose, ...extra });
170
+ const vector = Array.isArray(out) ? out : out && out.vector;
171
+ const source = (!Array.isArray(out) && out && out.source) || 'default';
172
+ if (!Array.isArray(vector) || !vector.length || vector.some((value) => !Number.isFinite(value))) {
173
+ throw new Error('The embedding function returned an invalid vector.');
174
+ }
175
+ return { vector, source: String(source) };
176
+ } catch (error) {
177
+ /* A failed embedding never loses the memory: it is kept without a vector, reindex() fills it later. */
178
+ logger.warn(`[memory] embedding failed: ${error && error.message}`);
179
+ return null;
180
+ }
181
+ }
182
+
183
+ /* ---- the checks ------------------------------------------------------ */
184
+
185
+ async function namesFor(where, ctx) {
186
+ if (!namesOf) return [];
187
+ try {
188
+ return (await namesOf(where, ctx)) || [];
189
+ } catch (error) {
190
+ logger.warn(`[memory] namesOf failed: ${error && error.message}`);
191
+ return [];
192
+ }
193
+ }
194
+
195
+ async function refusalFor(where, candidate, ctx) {
196
+ const names = await namesFor(where, ctx);
197
+ return checkCandidate({ ...candidate, names }, ruleConfig);
198
+ }
199
+
200
+ /* ---- chains of versions ---------------------------------------------- */
201
+
202
+ /* Every version the memory replaced, however deep. */
203
+ async function ancestorsOf(where, id) {
204
+ const found = [];
205
+ const queue = [id];
206
+ const seen = new Set([id]);
207
+ while (queue.length) {
208
+ const current = queue.shift();
209
+ const older = await store.list(where, { state: 'superseded', supersededBy: current });
210
+ for (const row of older) {
211
+ if (seen.has(row.id)) continue;
212
+ seen.add(row.id);
213
+ found.push(row.id);
214
+ queue.push(row.id);
215
+ }
216
+ }
217
+ return found;
218
+ }
219
+
220
+ async function removeWithHistory(where, ids) {
221
+ const all = new Set();
222
+ for (const id of ids) {
223
+ all.add(id);
224
+ for (const older of await ancestorsOf(where, id)) all.add(older);
225
+ }
226
+ return store.remove(where, [...all]);
227
+ }
228
+
229
+ /*
230
+ * The cap: least important first, then the longest unused (never used
231
+ * counts from its creation, not from the dawn of time).
232
+ */
233
+ async function enforceCap(where) {
234
+ if (!maxActive) return 0;
235
+ const active = await store.list(where, { state: 'active' });
236
+ if (active.length <= maxActive) return 0;
237
+ const last = (row) => new Date(row.lastUsedAt || row.createdAt || 0).getTime();
238
+ const victims = active
239
+ .sort((a, b) => a.importance - b.importance || last(a) - last(b))
240
+ .slice(0, active.length - maxActive)
241
+ .map((row) => row.id);
242
+ await removeWithHistory(where, victims);
243
+ return victims.length;
244
+ }
245
+
246
+ /* ---- writing --------------------------------------------------------- */
247
+
248
+ /**
249
+ * Keep one memory. Returns { ok: true, memory, supersededId } or
250
+ * { ok: false, reason }. A near duplicate (same meaning, or the same words)
251
+ * is replaced by the new one — undo() brings it back.
252
+ */
253
+ async function remember(whereInput, input = {}) {
254
+ return keep(placeOf(whereInput), input, true);
255
+ }
256
+
257
+ async function keep(where, input, checkPause) {
258
+ if (checkPause && (await isPaused(where))) return { ok: false, reason: REASONS.PAUSED };
259
+ const candidate = {
260
+ text: cleanText(input.text),
261
+ kind: kindOf(input.kind),
262
+ importance: normalizeImportance(input.importance),
263
+ role: input.role ?? null,
264
+ explicit: Boolean(input.explicit),
265
+ personName: input.personName || ''
266
+ };
267
+ const reason = await refusalFor(where, candidate, input.ctx);
268
+ if (reason) return { ok: false, reason };
269
+
270
+ const embedding = await vectorFor(candidate.text, 'passage', where);
271
+ const channel = input.channel || (candidate.explicit ? CHANNELS.EXPLICIT : CHANNELS.AUTO);
272
+
273
+ return withLock(where, async () => {
274
+ const active = await openAll(await store.list(where, { state: 'active' }));
275
+ const words = wordsOf(candidate.text);
276
+ const duplicate = (embedding
277
+ && active.find((row) => Array.isArray(row.vector) && row.vectorSource === embedding.source
278
+ && cosine(embedding.vector, row.vector) >= duplicateThreshold))
279
+ || active.find((row) => wordsOf(row.text) === words)
280
+ || null;
281
+
282
+ const at = now();
283
+ const record = {
284
+ id: String(generateId()),
285
+ ownerId: where.ownerId,
286
+ scope: where.scope,
287
+ role: candidate.role,
288
+ text: await seal(candidate.text),
289
+ kind: candidate.kind,
290
+ importance: candidate.importance,
291
+ source: { ...(input.source || {}), channel },
292
+ vector: embedding ? embedding.vector : null,
293
+ vectorSource: embedding ? embedding.source : null,
294
+ supersededBy: null,
295
+ seenAt: null,
296
+ lastUsedAt: null,
297
+ createdAt: at,
298
+ updatedAt: at
299
+ };
300
+ const inserted = await open(await store.insert(record));
301
+ if (duplicate) {
302
+ await store.update(where, duplicate.id, { supersededBy: record.id, updatedAt: at }, { onlyActive: true });
303
+ }
304
+ await enforceCap(where);
305
+ return { ok: true, memory: publicMemory(inserted), supersededId: duplicate ? duplicate.id : null };
306
+ });
307
+ }
308
+
309
+ /**
310
+ * Change one memory's text, kind or importance. The old version is kept
311
+ * behind the new one, so undo(newId) restores it. A name the memory already
312
+ * carried stays allowed; only a name the edit ADDS is refused.
313
+ */
314
+ async function update(whereInput, id, changes = {}, opts = {}) {
315
+ const where = placeOf(whereInput);
316
+ const old = await open(await store.get(where, String(id)));
317
+ if (!old || old.supersededBy) return { ok: false, reason: REASONS.NOT_FOUND };
318
+
319
+ const text = changes.text !== undefined ? cleanText(changes.text) : old.text;
320
+ const kind = changes.kind !== undefined && changes.kind !== null ? kindOf(changes.kind, old.kind) : old.kind;
321
+ const importance = changes.importance !== undefined && changes.importance !== null
322
+ ? normalizeImportance(changes.importance, old.importance)
323
+ : old.importance;
324
+ const reason = await refusalFor(where, {
325
+ text,
326
+ kind,
327
+ importance,
328
+ role: old.role,
329
+ explicit: Boolean(opts.explicit),
330
+ personName: opts.personName || '',
331
+ alreadyPresent: old.text
332
+ }, opts.ctx);
333
+ if (reason) return { ok: false, reason };
334
+ if (text === old.text && kind === old.kind && importance === old.importance) {
335
+ return { ok: true, memory: publicMemory(old), supersededId: null, unchanged: true };
336
+ }
337
+
338
+ /* New words carry a new meaning: the old vector would lie. */
339
+ const embedding = text === old.text
340
+ ? (Array.isArray(old.vector) ? { vector: old.vector, source: old.vectorSource } : null)
341
+ : await vectorFor(text, 'passage', where);
342
+
343
+ return withLock(where, async () => {
344
+ const at = now();
345
+ const record = {
346
+ id: String(generateId()),
347
+ ownerId: where.ownerId,
348
+ scope: where.scope,
349
+ role: old.role ?? null,
350
+ text: await seal(text),
351
+ kind,
352
+ importance,
353
+ source: { ...(old.source || {}), ...(opts.source || {}) },
354
+ vector: embedding ? embedding.vector : null,
355
+ vectorSource: embedding ? embedding.source : null,
356
+ supersededBy: null,
357
+ seenAt: old.seenAt || null,
358
+ lastUsedAt: old.lastUsedAt || null,
359
+ createdAt: at,
360
+ updatedAt: at
361
+ };
362
+ const inserted = await open(await store.insert(record));
363
+ const replaced = await store.update(where, old.id, { supersededBy: record.id, updatedAt: at }, { onlyActive: true });
364
+ if (!replaced) {
365
+ /* Changed meanwhile by someone else: take ours back, report the conflict. */
366
+ await store.remove(where, [record.id]);
367
+ return { ok: false, reason: REASONS.CONFLICT };
368
+ }
369
+ return { ok: true, memory: publicMemory(inserted), supersededId: old.id };
370
+ });
371
+ }
372
+
373
+ /** Take back a memory just written; what it replaced comes back. */
374
+ async function undo(whereInput, id) {
375
+ const where = placeOf(whereInput);
376
+ return withLock(where, async () => {
377
+ const current = await store.get(where, String(id));
378
+ if (!current || current.supersededBy) return false;
379
+ const older = await store.list(where, { state: 'superseded', supersededBy: current.id });
380
+ const removed = await store.remove(where, [current.id]);
381
+ if (!removed) return false;
382
+ const at = now();
383
+ for (const row of older) await store.update(where, row.id, { supersededBy: null, updatedAt: at });
384
+ return true;
385
+ });
386
+ }
387
+
388
+ /** Erase one memory and every earlier version of it. */
389
+ async function forget(whereInput, id) {
390
+ const where = placeOf(whereInput);
391
+ return withLock(where, async () => {
392
+ const current = await store.get(where, String(id));
393
+ if (!current) return false;
394
+ return (await removeWithHistory(where, [current.id])) > 0;
395
+ });
396
+ }
397
+
398
+ async function eraseAll(whereInput) {
399
+ const where = placeOf(whereInput);
400
+ return withLock(where, () => store.removeAll(where));
401
+ }
402
+
403
+ /** Right to erasure: this owner's memories, settings and consolidation marks, in every scope. */
404
+ async function purgeOwner(ownerId) {
405
+ const id = ownerId === undefined || ownerId === null ? '' : String(ownerId);
406
+ if (!id) throw new MemoryError('invalid_where', 'purgeOwner needs an owner id.');
407
+ return store.purgeOwner(id);
408
+ }
409
+
410
+ /* ---- reading --------------------------------------------------------- */
411
+
412
+ async function get(whereInput, id) {
413
+ const where = placeOf(whereInput);
414
+ const record = await open(await store.get(where, String(id)));
415
+ return record && !record.supersededBy ? publicMemory(record) : null;
416
+ }
417
+
418
+ /** Every current memory, newest first. No hidden cap: a person sees all of it. */
419
+ async function list(whereInput, filter = {}) {
420
+ const where = placeOf(whereInput);
421
+ const kindsFilter = Array.isArray(filter.kinds) ? filter.kinds.map((kind) => kindOf(kind, null)).filter(Boolean) : undefined;
422
+ const rows = await store.list(where, { state: 'active', kinds: kindsFilter, limit: filter.limit });
423
+ return (await openAll(rows)).map(publicMemory);
424
+ }
425
+
426
+ /** Memories learnt in the background and not yet shown to the person. */
427
+ async function listUnseen(whereInput) {
428
+ const where = placeOf(whereInput);
429
+ const rows = await store.list(where, { state: 'active', channel: CHANNELS.BACKGROUND, seen: false });
430
+ return (await openAll(rows)).map(publicMemory);
431
+ }
432
+
433
+ async function markSeen(whereInput, ids = []) {
434
+ const where = placeOf(whereInput);
435
+ const at = now();
436
+ let count = 0;
437
+ for (const id of [...new Set((ids || []).map(String))]) {
438
+ if (await store.update(where, id, { seenAt: at }, { onlyActive: true })) count += 1;
439
+ }
440
+ return count;
441
+ }
442
+
443
+ async function isPaused(whereInput) {
444
+ const where = placeOf(whereInput);
445
+ const settings = await store.getSettings(where);
446
+ return Boolean(settings && settings.paused);
447
+ }
448
+
449
+ async function setPaused(whereInput, paused) {
450
+ const where = placeOf(whereInput);
451
+ const settings = await store.setSettings(where, { paused: Boolean(paused) });
452
+ return Boolean(settings && settings.paused);
453
+ }
454
+
455
+ /**
456
+ * Search by meaning and by words, fused by rank. Without embeddings (or
457
+ * when they fail), by words, then the most recently useful. Found memories
458
+ * are marked used — the portrait and the cap both read that.
459
+ */
460
+ async function recall(whereInput, input = {}) {
461
+ const where = placeOf(whereInput);
462
+ const text = cleanText(typeof input === 'string' ? input : input.query);
463
+ if (!text) return [];
464
+ const limit = Math.max(1, Math.min(Number.isInteger(input.limit) ? input.limit : 8, 20));
465
+ const kindsFilter = Array.isArray(input.kinds) ? [...new Set(input.kinds.map((kind) => kindOf(kind, null)).filter(Boolean))] : undefined;
466
+ if (kindsFilter && !kindsFilter.length) return [];
467
+ const createdAfter = dateOf(input.after, 'invalid_after');
468
+ const createdBefore = dateOf(input.before, 'invalid_before');
469
+ const query = await vectorFor(text, 'query', where);
470
+
471
+ let semantic;
472
+ let lexical;
473
+ /* Encrypted text cannot be matched by the database: the ranking happens here. */
474
+ if (typeof store.search === 'function' && !cipher) {
475
+ const found = await store.search(where, {
476
+ text,
477
+ vector: query ? query.vector : null,
478
+ vectorSource: query ? query.source : null,
479
+ kinds: kindsFilter,
480
+ createdAfter,
481
+ createdBefore,
482
+ limit: limit * 4
483
+ });
484
+ semantic = (found.semantic || []).filter((row) => minSimilarity === null || typeof row.score !== 'number' || row.score >= minSimilarity);
485
+ lexical = found.lexical || [];
486
+ } else {
487
+ const rows = await openAll(await store.list(where, { state: 'active', kinds: kindsFilter, createdAfter, createdBefore }));
488
+ const last = (row) => new Date(row.lastUsedAt || row.createdAt || 0).getTime();
489
+ lexical = rows.map((row) => ({ ...row, score: keywordScore(text, row.text) }))
490
+ .filter((row) => row.score > 0)
491
+ .sort((a, b) => b.score - a.score || last(b) - last(a));
492
+ semantic = query
493
+ ? rows.filter((row) => Array.isArray(row.vector) && row.vectorSource === query.source)
494
+ .map((row) => ({ ...row, score: cosine(query.vector, row.vector) }))
495
+ .filter((row) => minSimilarity === null || row.score >= minSimilarity)
496
+ .sort((a, b) => b.score - a.score)
497
+ : [];
498
+ }
499
+
500
+ const byId = new Map();
501
+ for (const row of [...lexical, ...semantic]) byId.set(row.id, row);
502
+ const ids = fuseByRank([semantic.map((row) => row.id), lexical.map((row) => row.id)]).slice(0, limit);
503
+ const at = now();
504
+ const out = [];
505
+ for (const id of ids) {
506
+ const row = byId.get(id);
507
+ if (!row) continue;
508
+ await store.update(where, id, { lastUsedAt: at }, { onlyActive: true });
509
+ out.push(publicMemory({ ...row, lastUsedAt: at }));
510
+ }
511
+ return out;
512
+ }
513
+
514
+ /** The short text always given to the model. `masked: true` passes it through `mask` first. */
515
+ async function portrait(whereInput, opts = {}) {
516
+ const where = placeOf(whereInput);
517
+ const rows = await openAll(await store.list(where, { state: 'active' }));
518
+ const text = buildPortrait(rows, opts);
519
+ return opts.masked && text ? mask(text, where) : text;
520
+ }
521
+
522
+ /* ---- background ------------------------------------------------------ */
523
+
524
+ /**
525
+ * After a conversation: durable facts added, outdated memories corrected,
526
+ * the episode summary returned. Never throws — it is background work.
527
+ *
528
+ * With `ref` (a conversation id) and a store that implements claimRef, a
529
+ * conversation is consolidated once. Paused: the conversation is marked
530
+ * done and nothing is learnt from it, even after the pause ends.
531
+ */
532
+ async function consolidate(whereInput, input = {}) {
533
+ const empty = { added: 0, corrected: 0, refused: 0, summary: null };
534
+ let where;
535
+ try {
536
+ where = placeOf(whereInput);
537
+ } catch (error) {
538
+ logger.warn(`[memory] consolidate: ${error.message}`);
539
+ return { status: 'failed', ...empty };
540
+ }
541
+ if (!llm) return { status: 'unavailable', ...empty };
542
+ const ref = input.ref === undefined || input.ref === null ? null : String(input.ref);
543
+ const canClaim = ref && typeof store.claimRef === 'function';
544
+ let claimed = false;
545
+ try {
546
+ if (canClaim) {
547
+ claimed = await store.claimRef(where, ref);
548
+ if (!claimed) return { status: 'already', ...empty };
549
+ }
550
+ if (await isPaused(where)) return { status: 'paused', ...empty };
551
+
552
+ const raw = transcriptText(input.transcript).slice(0, transcriptMax);
553
+ if (!raw.trim()) return { status: 'empty', ...empty };
554
+
555
+ const last = (row) => new Date(row.lastUsedAt || 0).getTime();
556
+ const knownRows = (await openAll(await store.list(where, { state: 'active' })))
557
+ .sort((a, b) => b.importance - a.importance || last(b) - last(a)
558
+ || new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
559
+ .slice(0, knownForConsolidation);
560
+ const known = new Map(knownRows.map((row) => [row.id, row]));
561
+ const shown = [];
562
+ for (const row of knownRows) shown.push({ id: row.id, text: String(await mask(row.text, where)).slice(0, knownTextMax) });
563
+
564
+ const request = consolidationPrompt({
565
+ kinds,
566
+ known: shown,
567
+ transcript: await mask(raw, where),
568
+ language: input.language,
569
+ role: input.role
570
+ });
571
+ const answer = await llm({ ...request, purpose: 'memory-consolidation', where });
572
+ const parsed = parseModelJson(typeof answer === 'string' ? answer : JSON.stringify(answer));
573
+
574
+ const result = { added: 0, corrected: 0, refused: 0, summary: null };
575
+ if (typeof parsed.summary === 'string' && parsed.summary.trim()) result.summary = parsed.summary.replace(/\s+/g, ' ').trim();
576
+ const source = { ...(input.source || {}), ...(ref ? { ref } : {}) };
577
+ const explicitFor = async (fact) => (isExplicitFact ? Boolean(await isExplicitFact(fact, input.transcript, where)) : false);
578
+
579
+ /* A correction may only name a memory that was shown. */
580
+ for (const correction of Array.isArray(parsed.corrections) ? parsed.corrections : []) {
581
+ if (!correction || !known.has(String(correction.id))) continue;
582
+ const outcome = await update(where, String(correction.id), {
583
+ text: correction.text,
584
+ kind: correction.kind,
585
+ importance: correction.importance
586
+ }, {
587
+ personName: input.personName,
588
+ explicit: await explicitFor(correction),
589
+ source: { ...source, channel: CHANNELS.BACKGROUND },
590
+ ctx: input.ctx
591
+ });
592
+ if (outcome.ok && !outcome.unchanged) result.corrected += 1;
593
+ else if (!outcome.ok) result.refused += 1;
594
+ }
595
+
596
+ for (const fact of Array.isArray(parsed.facts) ? parsed.facts : []) {
597
+ if (!fact || typeof fact.text !== 'string') continue;
598
+ /* The pause was read once, before the model was asked. */
599
+ const outcome = await keep(where, {
600
+ text: fact.text,
601
+ kind: fact.kind,
602
+ importance: fact.importance,
603
+ role: input.role,
604
+ personName: input.personName,
605
+ explicit: await explicitFor(fact),
606
+ channel: CHANNELS.BACKGROUND,
607
+ source,
608
+ ctx: input.ctx
609
+ }, false);
610
+ if (outcome.ok) result.added += 1;
611
+ else result.refused += 1;
612
+ }
613
+ logger.info(`[memory] consolidated: ${result.added} added, ${result.corrected} corrected, ${result.refused} refused`);
614
+ return { status: 'done', ...result };
615
+ } catch (error) {
616
+ /* A failed run is retried next time: the conversation is not marked done. */
617
+ if (claimed && typeof store.releaseRef === 'function') {
618
+ try { await store.releaseRef(where, ref); } catch (_error) { /* the claim stays; nothing else to do */ }
619
+ }
620
+ logger.warn(`[memory] consolidation failed: ${error && error.message}`);
621
+ return { status: 'failed', ...empty };
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Give a vector to memories that have none — or, with `source`, one from
627
+ * another embedding model, so the store converges on a single space. Stops
628
+ * at the first failure: an embedding service that is down would fail them all.
629
+ */
630
+ async function reindex(opts = {}) {
631
+ if (!embed || typeof store.listNeedingVector !== 'function') return { updated: 0, failed: 0 };
632
+ const rows = await store.listNeedingVector({ limit: opts.limit ?? 50, source: opts.source });
633
+ let updated = 0;
634
+ for (const raw of rows) {
635
+ const row = await open(raw);
636
+ const where = { ownerId: row.ownerId, scope: row.scope };
637
+ const embedding = await vectorFor(row.text, 'passage', where, opts.source ? { source: opts.source } : {});
638
+ if (!embedding || (opts.source && embedding.source !== opts.source)) return { updated, failed: 1 };
639
+ const done = await store.update(where, row.id, { vector: embedding.vector, vectorSource: embedding.source, updatedAt: now() }, { onlyActive: true });
640
+ if (done) updated += 1;
641
+ }
642
+ return { updated, failed: 0 };
643
+ }
644
+
645
+ return {
646
+ remember,
647
+ recall,
648
+ update,
649
+ undo,
650
+ forget,
651
+ eraseAll,
652
+ purgeOwner,
653
+ get,
654
+ list,
655
+ listUnseen,
656
+ markSeen,
657
+ isPaused,
658
+ setPaused,
659
+ portrait,
660
+ consolidate,
661
+ reindex,
662
+ kinds: Object.freeze([...kinds]),
663
+ normalizeKind: (value, fallback) => kindOf(value, fallback === undefined ? defaultKind : fallback)
664
+ };
665
+ }
666
+
667
+ module.exports = {
668
+ createMemory,
669
+ MemoryError,
670
+ DEFAULT_KINDS,
671
+ CHANNELS
672
+ };