@astratra/memory 0.2.0 → 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/README.md CHANGED
@@ -107,8 +107,23 @@ removed and whitespace collapsed. `C#` and `snake_case` survive.
107
107
  forgotten memory whose previous wording is still in the table is not
108
108
  forgotten. An earlier version is never forgotten on its own (`false`): the
109
109
  memory that replaced it would stay.
110
- - Beyond `maxActive` (300) active memories, the least important go first, then
111
- the longest unused (a never-used memory counts from its creation).
110
+ - Beyond `maxActive` (**1000** by default; `0` or `null` for no cap) active
111
+ memories per person, the least important go first, then the longest unused (a
112
+ never-used memory counts from its creation). `trimAbove` (default: `maxActive`)
113
+ sets when the clean-up starts: with `maxActive: 1000, trimAbove: 1100` nothing
114
+ is removed until the 1101st memory, which brings the person back to 1000 in
115
+ one go instead of removing one memory per write. Under the threshold the cap
116
+ costs no extra query. `markUsed()` and `recall()` both protect a memory
117
+ from it.
118
+ - **Saying it again.** By default a duplicate is replaced by a new memory (new
119
+ id, the old one kept behind it, `undo()` brings it back). With
120
+ `onDuplicate: 'reinforce'` (the option, or `onDuplicate` in one `remember()`
121
+ call) the existing memory stays: **same id**, same text, kind and creation
122
+ date, importance raised to the higher of the two, `updatedAt` refreshed, and a
123
+ vector it lacked is filled in. The result is
124
+ `{ ok: true, memory, supersededId: null, reinforced: true }`; there is nothing
125
+ to undo (the tool says `undo: null` and `reinforced: true`; `undo()` on that id
126
+ would erase the memory itself). Consolidation follows the same option.
112
127
 
113
128
  ## Recall
114
129
 
@@ -121,6 +136,22 @@ Returned memories are marked used, which the portrait and the cap both read.
121
136
  If your store implements `search()` (a vector index, full-text search), recall
122
137
  uses it. With a `cipher`, it cannot: encrypted text is ranked in process.
123
138
 
139
+ ## Used, paused
140
+
141
+ ```js
142
+ await memory.markUsed(where, ids); // → how many were marked
143
+ await memory.pause(where); // → true; nothing new is kept or learnt
144
+ await memory.resume(where); // → false
145
+ await memory.isPaused(where); // setPaused(where, boolean) does both
146
+ ```
147
+
148
+ `markUsed(where, ids)` marks active memories as used without a search — for
149
+ the ones you hand to the model yourself (the portrait, the most important at the
150
+ start of a conversation). Unknown, replaced or other people's ids are skipped.
151
+ `createMemoryHandlers()` has `pause(where)` and `resume(where)` too, among the
152
+ privacy operations that work with the AI off. A paused person can still read,
153
+ take back and erase.
154
+
124
155
  ## Portrait
125
156
 
126
157
  `portrait(where, { maxLength = 1200, minImportance = 4, format, masked, fill })` —
@@ -183,7 +214,7 @@ const { createMemoryHandlers, PRIVACY_OPERATIONS } = require('@astratra/memory')
183
214
 
184
215
  const handlers = createMemoryHandlers({ memory, isAiEnabled: (where) => ai.isOn(where.scope) });
185
216
 
186
- // PRIVACY_OPERATIONS: list, listUnseen, markSeen, setPaused, undo, erase, eraseAll, purgeOwner
217
+ // PRIVACY_OPERATIONS: list, listUnseen, markSeen, setPaused, pause, resume, undo, erase, eraseAll, purgeOwner
187
218
  // They never call isAiEnabled. Only `update` (editing content) does → { ok: false, reason: 'ai_disabled' }.
188
219
  app.get('/me/memories', auth, async (req, res) => res.json(await handlers.list(placeFrom(req.user))));
189
220
  ```
@@ -253,6 +284,71 @@ import { randomUUID } from 'node:crypto';
253
284
  runStoreContract(async () => createMyStore(await freshDatabase()), { describe, test, newId: randomUUID });
254
285
  ```
255
286
 
287
+ A store whose **scope is a foreign key** (an organisation table) cannot be given
288
+ invented scopes: pass `makeScope`, which creates the organisation and returns its
289
+ id. `makeOwner` does the same for owners. Both receive the name the suite uses
290
+ (`'scope-1'`, `'scope-2'`; `'owner-a'`, `'owner-b'`, `'owner-z'`) and the store
291
+ being tested, and must return the same value for the same name within one store.
292
+ A store with a fixed vector size passes `vectorDimensions`; the suite pads its
293
+ test vectors to it.
294
+
295
+ ```js
296
+ runStoreContract(async () => createMyStore(await freshDatabase()), {
297
+ newId: randomUUID,
298
+ makeScope: async (name, store) => (await db.query('INSERT INTO organisations (id) VALUES (gen_random_uuid()) RETURNING id')).rows[0].id,
299
+ makeOwner: (name) => ownerIds[name] ??= randomUUID()
300
+ });
301
+ ```
302
+
303
+ ## PostgreSQL store, ready to use
304
+
305
+ `createPostgresMemoryStore(db, options)` is a reference adapter that passes the
306
+ contract: parameterised queries (nothing a person writes is ever in the SQL
307
+ text), a place carried by every statement, full text search, and pgvector when
308
+ you supply the embeddings. `db` is anything with `query(sql, params)`: a `pg`
309
+ Pool, a client inside a transaction. The package does not depend on `pg`.
310
+
311
+ ```js
312
+ const { createMemory, createPostgresMemoryStore, postgresMemorySchema } = require('@astratra/memory');
313
+
314
+ // once, in a migration of yours (idempotent):
315
+ await pool.query(postgresMemorySchema());
316
+
317
+ const memory = createMemory({ store: createPostgresMemoryStore(pool) });
318
+ ```
319
+
320
+ The schema makes three tables: `memories` (one row per memory, `owner_id` the
321
+ person, `scope` the organisation or workspace), `memories_settings` (the pause)
322
+ and `memories_refs` (conversations already consolidated). Options, the same for
323
+ the schema and the store:
324
+
325
+ | option | default | |
326
+ | --- | --- | --- |
327
+ | `table`, `settingsTable`, `refsTable` | `memories`, `memories_settings`, `memories_refs` | plain identifiers, `ia.memories` accepted |
328
+ | `idType`, `ownerType`, `scopeType` | `text` | `'uuid'` for a uuid column: a place or id that is not a UUID then finds nothing, never throws |
329
+ | `scopeReferences` | none | schema only: `'organisations(id)'` makes the scope a foreign key, `ON DELETE CASCADE` |
330
+ | `vectors` | `'json'` | `'json'`: jsonb, cosine computed in process over the vectors of one source; `'pgvector'`: `vector(N)` column, HNSW cosine index, `ORDER BY <=>` |
331
+ | `vectorDimensions` | | size of your embeddings, required with `'pgvector'` (an embedding of another size is refused by PostgreSQL) |
332
+ | `textSearchConfig` | `'simple'` | `'french'`, `'english'`… |
333
+ | `search` | `true` | `false`: no full text column, no `search()`; the package ranks in process |
334
+
335
+ Recall by words uses a generated `tsvector` column with a GIN index (the words
336
+ of the query joined by "or", ranked by `ts_rank`), then a fragment match when no
337
+ word is found. With a `cipher` the text is not searchable by the database and
338
+ `createMemory` ranks in process, as for any store. `getSettings` keeps `paused`
339
+ only. For several processes, compose `withLock` with a lock of the database
340
+ (`pg_advisory_lock`).
341
+
342
+ Its tests run without a database (queries, schema, refusals). The contract and
343
+ the end-to-end scenarios run against a real PostgreSQL when you give them one:
344
+
345
+ ```bash
346
+ MEMORY_TEST_DATABASE_URL=postgres:///my_test MEMORY_TEST_PGVECTOR=1 npm test -w @astratra/memory
347
+ ```
348
+
349
+ (the name must end in `_test`; `MEMORY_TEST_PGVECTOR=1` also tests pgvector,
350
+ which must be installed).
351
+
256
352
  ## Everything injected
257
353
 
258
354
  | option | default |
@@ -266,7 +362,9 @@ runStoreContract(async () => createMyStore(await freshDatabase()), { describe, t
266
362
  | `cipher { encrypt, decrypt }` | none — an `encrypt` that returns its input is refused |
267
363
  | `now`, `generateId`, `logger` | `new Date()`, `randomUUID()`, silent |
268
364
  | `withLock(where, fn)` | in-process queue per place (`createLocalLock()`, exported to compose with a lock shared across instances) |
269
- | `maxTextLength`, `maxActive`, `duplicateThreshold`, `minSimilarity` | 500, 300, 0.92, none |
365
+ | `maxTextLength`, `maxActive`, `duplicateThreshold`, `minSimilarity` | 500, 1000, 0.92, none |
366
+ | `trimAbove` | `maxActive` |
367
+ | `onDuplicate` | `'replace'` (or `'reinforce'`) |
270
368
  | `transcriptMax`, `transcriptKeep` | 40000, `'start'` |
271
369
 
272
370
  `reindex({ limit, source })` gives a vector to memories without one — or, with
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@astratra/memory",
3
- "version": "0.2.0",
4
- "description": "Per-person memories for an AI assistant: injected store, embeddings and model, hybrid recall, duplicate merging, undoable corrections, background consolidation, portrait, and privacy operations that keep working with the AI switched off.",
3
+ "version": "2.0.0",
4
+ "description": "Per-person memories for an AI assistant: injected store, embeddings and model, hybrid recall, duplicate merging or reinforcing, undoable corrections, background consolidation, portrait, a ready-made PostgreSQL store, and privacy operations that keep working with the AI switched off.",
5
5
  "engines": {
6
6
  "node": ">=20"
7
7
  },
@@ -26,7 +26,8 @@
26
26
  "agent",
27
27
  "embeddings",
28
28
  "recall",
29
- "privacy"
29
+ "privacy",
30
+ "postgres"
30
31
  ],
31
32
  "license": "MIT",
32
33
  "publishConfig": {
@@ -34,6 +35,7 @@
34
35
  },
35
36
  "devDependencies": {
36
37
  "@astratra/ai": "^1.3.0",
37
- "jest": "30.4.2"
38
+ "jest": "30.4.2",
39
+ "pg": "^8.13.1"
38
40
  }
39
41
  }
package/src/handlers.js CHANGED
@@ -11,7 +11,7 @@
11
11
  */
12
12
  const { REASONS } = require('./rules');
13
13
 
14
- const PRIVACY_OPERATIONS = Object.freeze(['list', 'listUnseen', 'markSeen', 'setPaused', 'undo', 'erase', 'eraseAll', 'purgeOwner']);
14
+ const PRIVACY_OPERATIONS = Object.freeze(['list', 'listUnseen', 'markSeen', 'setPaused', 'pause', 'resume', 'undo', 'erase', 'eraseAll', 'purgeOwner']);
15
15
  const AI_OPERATIONS = Object.freeze(['update']);
16
16
 
17
17
  /** True when the operation keeps working with the AI switched off. */
@@ -48,6 +48,14 @@ function createMemoryHandlers(options = {}) {
48
48
  return { ok: true, paused: await memory.setPaused(where, paused === true) };
49
49
  },
50
50
 
51
+ async pause(where) {
52
+ return { ok: true, paused: await memory.pause(where) };
53
+ },
54
+
55
+ async resume(where) {
56
+ return { ok: true, paused: await memory.resume(where) };
57
+ },
58
+
51
59
  async undo(where, { id } = {}) {
52
60
  const undone = await memory.undo(where, String(id ?? ''));
53
61
  return undone ? { ok: true, undone } : { ok: false, reason: REASONS.NOT_FOUND };
package/src/index.d.ts CHANGED
@@ -174,8 +174,12 @@ export interface MemoryOptions {
174
174
  withLock?: <T>(where: MemoryPlace, fn: () => Promise<T>) => Promise<T>;
175
175
  /** Default 500. */
176
176
  maxTextLength?: number;
177
- /** Active memories per place. Default 300; 0 or null for no cap. */
177
+ /** Active memories kept per place; beyond it the least important go first. Default 1000; 0 or null for no cap. */
178
178
  maxActive?: number | null;
179
+ /** The clean-up only starts above this many active memories, then brings the place back to `maxActive`. Default: `maxActive` (clean as soon as it is exceeded). */
180
+ trimAbove?: number | null;
181
+ /** What happens when a memory is said again: 'replace' (default) writes a new memory and keeps the old one behind it; 'reinforce' keeps the same id and the higher importance. */
182
+ onDuplicate?: DuplicateMode;
179
183
  /** Cosine at or above which a new memory replaces an old one. Default 0.92. */
180
184
  duplicateThreshold?: number;
181
185
  /** Cosine below which a meaning match is dropped from recall. Default null (none). */
@@ -195,6 +199,14 @@ export interface MemoryOptions {
195
199
 
196
200
  export type Refusal = { ok: false; reason: string };
197
201
 
202
+ export type DuplicateMode = 'replace' | 'reinforce';
203
+
204
+ export type RememberResult =
205
+ | { ok: true; memory: Memory; supersededId: string | null; reinforced?: undefined }
206
+ /** `onDuplicate: 'reinforce'` met a duplicate: same memory (same id), importance raised. Nothing to undo. */
207
+ | { ok: true; memory: Memory; supersededId: null; reinforced: true }
208
+ | Refusal;
209
+
198
210
  export interface RememberInput {
199
211
  text: string;
200
212
  kind: string;
@@ -205,6 +217,8 @@ export interface RememberInput {
205
217
  channel?: MemoryChannel;
206
218
  source?: Record<string, unknown>;
207
219
  ctx?: unknown;
220
+ /** Overrides `options.onDuplicate` for this call. */
221
+ onDuplicate?: DuplicateMode;
208
222
  }
209
223
 
210
224
  export interface RecallInput {
@@ -243,7 +257,7 @@ export interface ConsolidateResult {
243
257
  }
244
258
 
245
259
  export interface MemoryService {
246
- remember(where: MemoryWhere, input: RememberInput): Promise<{ ok: true; memory: Memory; supersededId: string | null } | Refusal>;
260
+ remember(where: MemoryWhere, input: RememberInput): Promise<RememberResult>;
247
261
  recall(where: MemoryWhere, input: RecallInput | string): Promise<Memory[]>;
248
262
  update(
249
263
  where: MemoryWhere,
@@ -259,8 +273,14 @@ export interface MemoryService {
259
273
  list(where: MemoryWhere, filter?: { kinds?: string[]; limit?: number }): Promise<Memory[]>;
260
274
  listUnseen(where: MemoryWhere): Promise<Memory[]>;
261
275
  markSeen(where: MemoryWhere, ids: string[]): Promise<number>;
276
+ /** Mark memories as used without a search; returns how many (unknown, superseded or foreign ids are skipped). */
277
+ markUsed(where: MemoryWhere, ids: string[]): Promise<number>;
262
278
  isPaused(where: MemoryWhere): Promise<boolean>;
263
279
  setPaused(where: MemoryWhere, paused: boolean): Promise<boolean>;
280
+ /** setPaused(where, true): returns true. */
281
+ pause(where: MemoryWhere): Promise<boolean>;
282
+ /** setPaused(where, false): returns false. */
283
+ resume(where: MemoryWhere): Promise<boolean>;
264
284
  portrait(where: MemoryWhere, options?: PortraitOptions & { masked?: boolean }): Promise<string>;
265
285
  consolidate(where: MemoryWhere, input: ConsolidateInput): Promise<ConsolidateResult>;
266
286
  reindex(options?: { limit?: number; source?: string }): Promise<{ updated: number; failed: number }>;
@@ -279,6 +299,9 @@ export class MemoryError extends Error {
279
299
  }
280
300
 
281
301
  export const DEFAULT_KINDS: readonly string[];
302
+ /** 1000: active memories kept per place unless `maxActive` says otherwise. */
303
+ export const DEFAULT_MAX_ACTIVE: number;
304
+ export const DUPLICATE_MODES: readonly DuplicateMode[];
282
305
  export const CHANNELS: Readonly<{ EXPLICIT: 'explicit'; AUTO: 'auto'; BACKGROUND: 'background' }>;
283
306
  export const REASONS: Readonly<{
284
307
  EMPTY: 'empty';
@@ -398,6 +421,8 @@ export interface MemoryHandlers {
398
421
  listUnseen(where: MemoryWhere): Promise<{ ok: true; memories: Memory[] }>;
399
422
  markSeen(where: MemoryWhere, input: { ids?: unknown[] }): Promise<{ ok: true; seen: number }>;
400
423
  setPaused(where: MemoryWhere, input: { paused?: unknown }): Promise<{ ok: true; paused: boolean }>;
424
+ pause(where: MemoryWhere): Promise<{ ok: true; paused: true }>;
425
+ resume(where: MemoryWhere): Promise<{ ok: true; paused: false }>;
401
426
  undo(where: MemoryWhere, input: { id?: string }): Promise<{ ok: true; undone: true } | Refusal>;
402
427
  erase(where: MemoryWhere, input: { id?: string }): Promise<{ ok: true; erased: true } | Refusal>;
403
428
  eraseAll(where: MemoryWhere): Promise<{ ok: true; erased: number }>;
@@ -422,7 +447,67 @@ export interface ContractRunner {
422
447
  expect?: (value: unknown) => any;
423
448
  /** Makes every id the suite uses (missing ones included), for a store whose ids have a shape, a UUID for instance. */
424
449
  newId?: () => string;
450
+ /**
451
+ * The value to use for a scope the suite names ('scope-1', 'scope-2'), for a store whose scope is a foreign key or has a shape:
452
+ * create the organisation row, return its id. Called with the store being tested; the same name must give the same value for that store.
453
+ */
454
+ makeScope?: (name: string, store: MemoryStore) => Awaitable<string>;
455
+ /** Same for the owners the suite names ('owner-a', 'owner-b', 'owner-z'). */
456
+ makeOwner?: (name: string, store: MemoryStore) => Awaitable<string>;
457
+ /** Size of the vectors the store holds (a pgvector column has a fixed one): the suite pads its test vectors with zeros to it. */
458
+ vectorDimensions?: number;
425
459
  }
426
460
 
427
461
  export function runStoreContract(makeStore: () => Awaitable<MemoryStore>, runner?: ContractRunner): void;
428
462
  export function contractRecord(overrides?: Partial<MemoryRecord>): MemoryRecord;
463
+
464
+ /* ---- PostgreSQL store ---- */
465
+
466
+ /** The query function of a pg Pool, a pg client (inside a transaction too) or any compatible adapter. */
467
+ export interface PostgresExecutor {
468
+ query(sql: string, params?: unknown[]): Promise<{ rows: any[]; rowCount?: number | null }>;
469
+ }
470
+
471
+ export interface PostgresSchemaOptions {
472
+ /** Memories table. Default 'memories'; settings are `${table}_settings`, consolidation marks `${table}_refs`. A schema prefix ('ia.memories') is accepted. */
473
+ table?: string;
474
+ settingsTable?: string;
475
+ refsTable?: string;
476
+ /** Column type of the memory id. Default 'text'. */
477
+ idType?: 'text' | 'uuid';
478
+ /** Column type of the owner (the person). Default 'text'. */
479
+ ownerType?: 'text' | 'uuid';
480
+ /** Column type of the scope (organisation, workspace). Default 'text' (no scope = ''). */
481
+ scopeType?: 'text' | 'uuid';
482
+ /** Makes the scope a foreign key, e.g. 'organisations(id)' (ON DELETE CASCADE). Needs a scopeType matching the referenced column. */
483
+ scopeReferences?: string;
484
+ /** Where vectors live: 'json' (default, jsonb; cosine computed in process over one source) or 'pgvector' (vector column, HNSW cosine index). */
485
+ vectors?: 'json' | 'pgvector';
486
+ /** Size of the embeddings. Required with vectors: 'pgvector'. */
487
+ vectorDimensions?: number;
488
+ /** Text search configuration of the full text index. Default 'simple'; use 'french', 'english'… for stemming. */
489
+ textSearchConfig?: string;
490
+ /** false: no full text column, index or search(): the package ranks in process. Default true. */
491
+ search?: boolean;
492
+ }
493
+
494
+ /** Options of the store: the same as the schema's (`vectorDimensions` and `scopeReferences` only matter to the schema). */
495
+ export type PostgresMemoryStoreOptions = PostgresSchemaOptions;
496
+
497
+ /** The SQL that creates the tables and indexes (idempotent). Run it in a migration of your own. */
498
+ export function postgresMemorySchema(options?: PostgresSchemaOptions): string;
499
+
500
+ /**
501
+ * The reference PostgreSQL store: parameterised queries, full text search, pgvector optional.
502
+ * A place or an id not shaped like its column finds nothing (it never throws).
503
+ */
504
+ export function createPostgresMemoryStore(
505
+ db: PostgresExecutor,
506
+ options?: PostgresMemoryStoreOptions
507
+ ): MemoryStore & {
508
+ claimRef(where: MemoryPlace, ref: string): Promise<boolean>;
509
+ releaseRef(where: MemoryPlace, ref: string): Promise<void>;
510
+ listNeedingVector(options: { limit?: number; source?: string }): Promise<MemoryRecord[]>;
511
+ /** Absent with `search: false`. */
512
+ search?(where: MemoryPlace, input: MemorySearchInput): Promise<{ semantic: MemoryRecord[]; lexical: MemoryRecord[] }>;
513
+ };
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  module.exports = {
2
2
  ...require('./memory'),
3
3
  ...require('./memoryStore'),
4
+ ...require('./postgres'),
4
5
  ...require('./tools'),
5
6
  ...require('./handlers'),
6
7
  ...require('./rules'),
package/src/memory.js CHANGED
@@ -28,6 +28,10 @@ const {
28
28
  const { cosine, keywordScore, fuseByRank, buildPortrait } = require('./ranking');
29
29
  const { readExtraction, defaultConsolidationPrompt, transcriptText } = require('./consolidation');
30
30
 
31
+ /* Active memories kept per place before the least important are dropped. */
32
+ const DEFAULT_MAX_ACTIVE = 1000;
33
+ /* What happens when a memory is said again: 'replace' writes a new one, 'reinforce' keeps the same id. */
34
+ const DUPLICATE_MODES = Object.freeze(['replace', 'reinforce']);
31
35
  const DEFAULT_KINDS = Object.freeze(['goal', 'preference', 'fact', 'person', 'event', 'feeling']);
32
36
  const CHANNELS = Object.freeze({ EXPLICIT: 'explicit', AUTO: 'auto', BACKGROUND: 'background' });
33
37
  const REQUIRED_STORE = ['insert', 'get', 'list', 'update', 'remove', 'removeAll', 'purgeOwner', 'getSettings', 'setSettings'];
@@ -109,7 +113,15 @@ function createMemory(options = {}) {
109
113
  const logger = { ...NOOP_LOGGER, ...(options.logger || {}) };
110
114
  const withLock = options.withLock || createLocalLock();
111
115
  const maxTextLength = options.maxTextLength ?? 500;
112
- const maxActive = options.maxActive === undefined ? 300 : options.maxActive;
116
+ const maxActive = options.maxActive === undefined ? DEFAULT_MAX_ACTIVE : options.maxActive;
117
+ /* The clean-up only starts above this count and brings the person back down to maxActive (default: maxActive itself). */
118
+ const trimAbove = options.trimAbove === undefined || options.trimAbove === null
119
+ ? maxActive
120
+ : Math.max(maxActive || 0, options.trimAbove);
121
+ if (options.onDuplicate !== undefined && !DUPLICATE_MODES.includes(options.onDuplicate)) {
122
+ throw new MemoryError('invalid_option', `options.onDuplicate must be one of: ${DUPLICATE_MODES.join(', ')}.`);
123
+ }
124
+ const onDuplicate = options.onDuplicate || 'replace';
113
125
  const duplicateThreshold = options.duplicateThreshold ?? 0.92;
114
126
  const minSimilarity = options.minSimilarity ?? null;
115
127
  const consolidationPrompt = options.consolidationPrompt || defaultConsolidationPrompt;
@@ -238,10 +250,12 @@ function createMemory(options = {}) {
238
250
  * The cap: least important first, then the longest unused (never used
239
251
  * counts from its creation, not from the dawn of time).
240
252
  */
241
- async function enforceCap(where) {
253
+ async function enforceCap(where, knownCount) {
242
254
  if (!maxActive) return 0;
255
+ /* A count the caller already holds spares the listing while the person is under the threshold. */
256
+ if (typeof knownCount === 'number' && knownCount <= trimAbove) return 0;
243
257
  const active = await store.list(where, { state: 'active', withVector: false });
244
- if (active.length <= maxActive) return 0;
258
+ if (active.length <= trimAbove) return 0;
245
259
  const last = (row) => new Date(row.lastUsedAt || row.createdAt || 0).getTime();
246
260
  const victims = active
247
261
  .sort((a, b) => a.importance - b.importance || last(a) - last(b))
@@ -256,7 +270,11 @@ function createMemory(options = {}) {
256
270
  /**
257
271
  * Keep one memory. Returns { ok: true, memory, supersededId } or
258
272
  * { ok: false, reason }. A near duplicate (same meaning, or the same words)
259
- * is replaced by the new one — undo() brings it back.
273
+ * is replaced by the new one — undo() brings it back. With
274
+ * `onDuplicate: 'reinforce'` (option, or `input.onDuplicate` for one call) the
275
+ * existing memory stays, same id, and takes the higher importance:
276
+ * { ok: true, memory, supersededId: null, reinforced: true }. There is then
277
+ * nothing to undo.
260
278
  */
261
279
  async function remember(whereInput, input = {}) {
262
280
  return keep(placeOf(whereInput), input, true);
@@ -287,6 +305,18 @@ function createMemory(options = {}) {
287
305
  || null;
288
306
 
289
307
  const at = now();
308
+ const mode = DUPLICATE_MODES.includes(input.onDuplicate) ? input.onDuplicate : onDuplicate;
309
+ if (duplicate && mode === 'reinforce') {
310
+ const patch = { importance: Math.max(duplicate.importance, candidate.importance), updatedAt: at };
311
+ /* A vector the memory lacked (or from another model) is worth taking. */
312
+ if (embedding && !comparable(duplicate, embedding)) {
313
+ patch.vector = embedding.vector;
314
+ patch.vectorSource = embedding.source;
315
+ }
316
+ const saved = await store.update(where, duplicate.id, patch, { onlyActive: true });
317
+ if (saved) return { ok: true, memory: publicMemory(await open(saved)), supersededId: null, reinforced: true };
318
+ /* Changed meanwhile: write ours as a new memory instead. */
319
+ }
290
320
  const record = {
291
321
  id: String(generateId()),
292
322
  ownerId: where.ownerId,
@@ -308,7 +338,7 @@ function createMemory(options = {}) {
308
338
  if (duplicate) {
309
339
  await store.update(where, duplicate.id, { supersededBy: record.id, updatedAt: at }, { onlyActive: true });
310
340
  }
311
- await enforceCap(where);
341
+ await enforceCap(where, active.length + 1 - (duplicate ? 1 : 0));
312
342
  return { ok: true, memory: publicMemory(inserted), supersededId: duplicate ? duplicate.id : null };
313
343
  });
314
344
  }
@@ -467,6 +497,21 @@ function createMemory(options = {}) {
467
497
  return count;
468
498
  }
469
499
 
500
+ /**
501
+ * Mark memories as used (they weigh in the portrait and are kept longest by
502
+ * the cap) without going through a search. Unknown, superseded or foreign ids
503
+ * are skipped. Returns how many were marked.
504
+ */
505
+ async function markUsed(whereInput, ids = []) {
506
+ const where = placeOf(whereInput);
507
+ const at = now();
508
+ let count = 0;
509
+ for (const id of [...new Set((ids || []).map(String))]) {
510
+ if (await store.update(where, id, { lastUsedAt: at }, { onlyActive: true })) count += 1;
511
+ }
512
+ return count;
513
+ }
514
+
470
515
  async function isPaused(whereInput) {
471
516
  const where = placeOf(whereInput);
472
517
  const settings = await store.getSettings(where);
@@ -479,6 +524,12 @@ function createMemory(options = {}) {
479
524
  return Boolean(settings && settings.paused);
480
525
  }
481
526
 
527
+ /** Pause the person's memory: nothing new is kept or learnt until resume(). What is kept stays readable. */
528
+ const pause = (whereInput) => setPaused(whereInput, true);
529
+
530
+ /** Resume a paused memory. Returns the new state of the pause (false). */
531
+ const resume = (whereInput) => setPaused(whereInput, false);
532
+
482
533
  /**
483
534
  * Search by meaning and by words, fused by rank. Without embeddings (or
484
535
  * when they fail), by words, then the most recently useful. Found memories
@@ -711,8 +762,11 @@ function createMemory(options = {}) {
711
762
  list,
712
763
  listUnseen,
713
764
  markSeen,
765
+ markUsed,
714
766
  isPaused,
715
767
  setPaused,
768
+ pause,
769
+ resume,
716
770
  portrait,
717
771
  consolidate,
718
772
  reindex,
@@ -726,5 +780,7 @@ module.exports = {
726
780
  createLocalLock,
727
781
  MemoryError,
728
782
  DEFAULT_KINDS,
783
+ DEFAULT_MAX_ACTIVE,
784
+ DUPLICATE_MODES,
729
785
  CHANNELS
730
786
  };
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Reference PostgreSQL store for createMemory(): the SQL schema, parameterised
3
+ * queries, full text search, and pgvector when the embeddings are supplied.
4
+ *
5
+ * const { createMemory, createPostgresMemoryStore, postgresMemorySchema } = require('@astratra/memory');
6
+ * await pool.query(postgresMemorySchema()); // once, in a migration
7
+ * const memory = createMemory({ store: createPostgresMemoryStore(pool) });
8
+ *
9
+ * `db` is anything with `query(sql, params) -> { rows, rowCount }`: a pg Pool,
10
+ * a pg client inside a transaction, a pg-mem adapter. The package does not
11
+ * depend on `pg`.
12
+ *
13
+ * A place is `{ ownerId, scope }`: ownerId is the person, scope the
14
+ * organisation or workspace. Every statement carries both. Names of tables and
15
+ * the text search configuration come from options and are checked as plain
16
+ * identifiers; everything that comes from a person goes through parameters.
17
+ *
18
+ * The scope may be a foreign key (`scopeType: 'uuid'`, `scopeReferences:
19
+ * 'organisations(id)'` in the schema). A place whose id is not of the column's
20
+ * shape (a scope that is not a UUID for a uuid column) finds nothing: reads
21
+ * answer null or empty, writes count zero, nothing throws.
22
+ */
23
+ const { cosine } = require('./ranking');
24
+
25
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)?$/;
26
+ const CONFIG_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
27
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
28
+ const COLUMN_TYPES = ['text', 'uuid'];
29
+
30
+ function pick(value, allowed, fallback, name) {
31
+ if (value === undefined) return fallback;
32
+ if (!allowed.includes(value)) throw new Error(`${name} must be one of: ${allowed.join(', ')}.`);
33
+ return value;
34
+ }
35
+
36
+ function identifier(value, name) {
37
+ if (typeof value !== 'string' || !IDENTIFIER.test(value)) throw new Error(`${name} must be a plain SQL identifier (letters, digits, underscore, optional schema prefix).`);
38
+ return value.split('.').map((part) => `"${part}"`).join('.');
39
+ }
40
+
41
+ /* Index names cannot carry a schema prefix: the bare table name makes them. */
42
+ const bare = (value) => value.split('.').pop();
43
+
44
+ function normalize(options = {}) {
45
+ const table = options.table === undefined ? 'memories' : options.table;
46
+ const settingsTable = options.settingsTable === undefined ? `${table}_settings` : options.settingsTable;
47
+ const refsTable = options.refsTable === undefined ? `${table}_refs` : options.refsTable;
48
+ const textSearchConfig = options.textSearchConfig === undefined ? 'simple' : options.textSearchConfig;
49
+ if (!CONFIG_NAME.test(textSearchConfig)) throw new Error('textSearchConfig must be a text search configuration name.');
50
+ const vectors = pick(options.vectors, ['json', 'pgvector'], 'json', 'vectors');
51
+ const vectorDimensions = options.vectorDimensions === undefined ? null : options.vectorDimensions;
52
+ if (vectorDimensions !== null && !(Number.isInteger(vectorDimensions) && vectorDimensions > 0)) throw new Error('vectorDimensions must be a positive integer.');
53
+ if (options.scopeReferences !== undefined && !/^[A-Za-z_][A-Za-z0-9_.]*\s*\(\s*[A-Za-z_][A-Za-z0-9_]*\s*\)$/.test(options.scopeReferences)) {
54
+ throw new Error('scopeReferences must look like "organisations(id)".');
55
+ }
56
+ return {
57
+ table: identifier(table, 'table'),
58
+ settingsTable: identifier(settingsTable, 'settingsTable'),
59
+ refsTable: identifier(refsTable, 'refsTable'),
60
+ names: { table: bare(table), settingsTable: bare(settingsTable), refsTable: bare(refsTable) },
61
+ idType: pick(options.idType, COLUMN_TYPES, 'text', 'idType'),
62
+ ownerType: pick(options.ownerType, COLUMN_TYPES, 'text', 'ownerType'),
63
+ scopeType: pick(options.scopeType, COLUMN_TYPES, 'text', 'scopeType'),
64
+ scopeReferences: options.scopeReferences || null,
65
+ vectors,
66
+ vectorDimensions,
67
+ textSearchConfig,
68
+ search: options.search !== false
69
+ };
70
+ }
71
+
72
+ /**
73
+ * The SQL that creates the tables and indexes (idempotent: IF NOT EXISTS).
74
+ * Same options as createPostgresMemoryStore for the names and column types,
75
+ * plus `vectorDimensions` (required with `vectors: 'pgvector'`, the size of
76
+ * your embeddings) and `scopeReferences` ('organisations(id)': the scope
77
+ * becomes a foreign key, memories follow the organisation when it is deleted).
78
+ * Run it as a migration of your own.
79
+ */
80
+ function postgresMemorySchema(options = {}) {
81
+ const o = normalize(options);
82
+ const pgvector = o.vectors === 'pgvector';
83
+ if (pgvector && !o.vectorDimensions) throw new Error('vectors: "pgvector" needs vectorDimensions.');
84
+ const scopeDefault = o.scopeType === 'text' ? " DEFAULT ''" : '';
85
+ const reference = o.scopeReferences ? ` REFERENCES ${o.scopeReferences} ON DELETE CASCADE` : '';
86
+ const scopeColumn = `scope ${o.scopeType} NOT NULL${scopeDefault}${reference}`;
87
+ const n = o.names;
88
+ const out = [];
89
+ if (pgvector) out.push('CREATE EXTENSION IF NOT EXISTS vector;');
90
+ out.push(`CREATE TABLE IF NOT EXISTS ${o.table} (
91
+ id ${o.idType} PRIMARY KEY,
92
+ owner_id ${o.ownerType} NOT NULL,
93
+ ${scopeColumn},
94
+ role text,
95
+ text text NOT NULL,
96
+ kind text NOT NULL,
97
+ importance smallint NOT NULL DEFAULT 3,
98
+ source jsonb NOT NULL DEFAULT '{}'::jsonb,
99
+ vector ${pgvector ? `vector(${o.vectorDimensions})` : 'jsonb'},
100
+ vector_source text,
101
+ superseded_by ${o.idType},
102
+ seen_at timestamptz,
103
+ last_used_at timestamptz,
104
+ created_at timestamptz NOT NULL,
105
+ updated_at timestamptz NOT NULL${o.search ? `,
106
+ search_vector tsvector GENERATED ALWAYS AS (to_tsvector('${o.textSearchConfig}', text)) STORED` : ''}
107
+ );`);
108
+ out.push(`CREATE INDEX IF NOT EXISTS ${n.table}_place_idx ON ${o.table} (owner_id, scope, created_at DESC);`);
109
+ out.push(`CREATE INDEX IF NOT EXISTS ${n.table}_superseded_idx ON ${o.table} (owner_id, scope, superseded_by);`);
110
+ if (o.search) out.push(`CREATE INDEX IF NOT EXISTS ${n.table}_search_idx ON ${o.table} USING gin (search_vector);`);
111
+ if (pgvector) out.push(`CREATE INDEX IF NOT EXISTS ${n.table}_vector_idx ON ${o.table} USING hnsw (vector vector_cosine_ops);`);
112
+ out.push(`CREATE TABLE IF NOT EXISTS ${o.settingsTable} (
113
+ owner_id ${o.ownerType} NOT NULL,
114
+ ${scopeColumn},
115
+ paused boolean NOT NULL DEFAULT false,
116
+ PRIMARY KEY (owner_id, scope)
117
+ );`);
118
+ out.push(`CREATE TABLE IF NOT EXISTS ${o.refsTable} (
119
+ owner_id ${o.ownerType} NOT NULL,
120
+ ${scopeColumn},
121
+ ref text NOT NULL,
122
+ claimed_at timestamptz NOT NULL DEFAULT now(),
123
+ PRIMARY KEY (owner_id, scope, ref)
124
+ );`);
125
+ return `${out.join('\n')}\n`;
126
+ }
127
+
128
+ /** Words of a query joined with "or", for to_tsquery: at most 16, letters and digits only (nothing to escape). */
129
+ function tsQueryOf(text) {
130
+ const words = [...new Set(String(text || '').toLowerCase().match(/[\p{L}\p{N}]{2,}/gu) || [])].slice(0, 16);
131
+ return words.length ? words.join(' | ') : null;
132
+ }
133
+
134
+ /* The fields a patch may change, and their columns. id, ownerId and scope never change. */
135
+ const PATCH_COLUMNS = {
136
+ text: 'text',
137
+ kind: 'kind',
138
+ importance: 'importance',
139
+ role: 'role',
140
+ supersededBy: 'superseded_by',
141
+ seenAt: 'seen_at',
142
+ lastUsedAt: 'last_used_at',
143
+ updatedAt: 'updated_at',
144
+ createdAt: 'created_at',
145
+ vectorSource: 'vector_source'
146
+ };
147
+
148
+ /**
149
+ * @param {{ query(sql: string, params?: unknown[]): Promise<{ rows: any[], rowCount?: number | null }> }} db
150
+ * @param {object} [options] see index.d.ts (PostgresMemoryStoreOptions).
151
+ */
152
+ function createPostgresMemoryStore(db, options = {}) {
153
+ if (!db || typeof db.query !== 'function') throw new Error('createPostgresMemoryStore requires a db with query(sql, params).');
154
+ const o = normalize(options);
155
+ const pgvector = o.vectors === 'pgvector';
156
+ const shaped = { id: o.idType, ownerId: o.ownerType, scope: o.scopeType };
157
+
158
+ const okId = (value) => typeof value === 'string' && value !== '' && (o.idType === 'text' || UUID.test(value));
159
+ const okPlace = (where) => Boolean(where) && typeof where.ownerId === 'string' && where.ownerId !== ''
160
+ && typeof where.scope === 'string'
161
+ && (shaped.ownerId === 'text' || UUID.test(where.ownerId))
162
+ && (shaped.scope === 'text' ? true : UUID.test(where.scope));
163
+ const goodIds = (ids) => [...new Set((ids || []).map(String))].filter(okId);
164
+
165
+ const vectorText = (vector) => (Array.isArray(vector) && vector.length ? JSON.stringify(vector) : null);
166
+ const readVector = (value) => {
167
+ if (value === null || value === undefined) return null;
168
+ if (Array.isArray(value)) return value;
169
+ try { return JSON.parse(value); } catch (_error) { return null; }
170
+ };
171
+
172
+ /* The columns read back. The vector is left out when the caller says it will not read it. */
173
+ const columns = (withVector) => {
174
+ const vector = pgvector ? 'vector::text' : 'vector';
175
+ return `id, owner_id, scope, role, text, kind, importance, source, vector_source, superseded_by, seen_at, last_used_at, created_at, updated_at,
176
+ ${withVector ? vector : 'NULL'} AS vector, (vector IS NOT NULL) AS has_vector`;
177
+ };
178
+
179
+ function toRecord(row) {
180
+ const vector = readVector(row.vector);
181
+ const out = {
182
+ id: row.id,
183
+ ownerId: row.owner_id,
184
+ scope: row.scope,
185
+ role: row.role ?? null,
186
+ text: row.text,
187
+ kind: row.kind,
188
+ importance: Number(row.importance),
189
+ source: (typeof row.source === 'string' ? JSON.parse(row.source) : row.source) || {},
190
+ vector,
191
+ vectorSource: row.vector_source ?? null,
192
+ supersededBy: row.superseded_by ?? null,
193
+ seenAt: row.seen_at ?? null,
194
+ lastUsedAt: row.last_used_at ?? null,
195
+ createdAt: row.created_at,
196
+ updatedAt: row.updated_at,
197
+ hasVector: Boolean(row.has_vector)
198
+ };
199
+ if (row.score !== undefined && row.score !== null) out.score = Number(row.score);
200
+ return out;
201
+ }
202
+
203
+ /* The conditions shared by reads. Parameters $1 and $2 are always the place. */
204
+ function conditions(filter = {}, startAt = 3) {
205
+ const sql = [];
206
+ const params = [];
207
+ const add = (value) => { params.push(value); return `$${startAt + params.length - 1}`; };
208
+ const state = filter.state || 'active';
209
+ if (state === 'active') sql.push('superseded_by IS NULL');
210
+ if (state === 'superseded') sql.push('superseded_by IS NOT NULL');
211
+ if (filter.supersededBy !== undefined) sql.push(okId(String(filter.supersededBy)) ? `superseded_by = ${add(String(filter.supersededBy))}` : 'false');
212
+ if (Array.isArray(filter.kinds)) sql.push(`kind = ANY(${add(filter.kinds.map(String))}::text[])`);
213
+ if (filter.channel !== undefined) sql.push(`source->>'channel' = ${add(String(filter.channel))}`);
214
+ if (filter.seen === true) sql.push('seen_at IS NOT NULL');
215
+ else if (filter.seen === false) sql.push('seen_at IS NULL');
216
+ if (filter.createdAfter) sql.push(`created_at >= ${add(new Date(filter.createdAfter))}`);
217
+ if (filter.createdBefore) sql.push(`created_at <= ${add(new Date(filter.createdBefore))}`);
218
+ return { sql: sql.length ? ` AND ${sql.join(' AND ')}` : '', params };
219
+ }
220
+
221
+ const placeSql = 'owner_id = $1 AND scope = $2';
222
+
223
+ async function one(where, id, extra = '') {
224
+ if (!okPlace(where) || !okId(String(id))) return null;
225
+ const result = await db.query(`SELECT ${columns(true)} FROM ${o.table} WHERE id = $1 AND owner_id = $2 AND scope = $3${extra}`, [String(id), where.ownerId, where.scope]);
226
+ return result.rows[0] ? toRecord(result.rows[0]) : null;
227
+ }
228
+
229
+ const store = {
230
+ async insert(record) {
231
+ if (!record || !record.id) throw new Error('insert requires a record with an id.');
232
+ const result = await db.query(
233
+ `INSERT INTO ${o.table} (id, owner_id, scope, role, text, kind, importance, source, vector, vector_source, superseded_by, seen_at, last_used_at, created_at, updated_at)
234
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9${pgvector ? '::vector' : '::jsonb'}, $10, $11, $12, $13, $14, $15)
235
+ RETURNING ${columns(true)}`,
236
+ [record.id, record.ownerId, record.scope, record.role ?? null, record.text, record.kind, record.importance, JSON.stringify(record.source || {}),
237
+ vectorText(record.vector), record.vectorSource ?? null, record.supersededBy ?? null, record.seenAt ?? null, record.lastUsedAt ?? null,
238
+ record.createdAt, record.updatedAt]
239
+ );
240
+ return toRecord(result.rows[0]);
241
+ },
242
+
243
+ get: (where, id) => one(where, id),
244
+
245
+ async list(where, filter = {}) {
246
+ if (!okPlace(where)) return [];
247
+ const c = conditions(filter);
248
+ const limit = filter.limit ? ` LIMIT ${Math.max(1, Math.floor(Number(filter.limit)))}` : '';
249
+ const result = await db.query(
250
+ `SELECT ${columns(filter.withVector !== false)} FROM ${o.table} WHERE ${placeSql}${c.sql} ORDER BY created_at DESC, id${limit}`,
251
+ [where.ownerId, where.scope, ...c.params]
252
+ );
253
+ return result.rows.map(toRecord);
254
+ },
255
+
256
+ async update(where, id, patch = {}, options = {}) {
257
+ const onlyActive = options.onlyActive ? ' AND superseded_by IS NULL' : '';
258
+ const sets = [];
259
+ const params = [];
260
+ const set = (column, value, cast = '') => { params.push(value); sets.push(`${column} = $${params.length + 3}${cast}`); };
261
+ for (const [field, column] of Object.entries(PATCH_COLUMNS)) {
262
+ if (field in patch) set(column, patch[field] === undefined ? null : patch[field]);
263
+ }
264
+ if ('source' in patch) set('source', JSON.stringify(patch.source || {}), '::jsonb');
265
+ if ('vector' in patch) set('vector', vectorText(patch.vector), pgvector ? '::vector' : '::jsonb');
266
+ if (!sets.length) return one(where, id, onlyActive);
267
+ if (!okPlace(where) || !okId(String(id))) return null;
268
+ if ('supersededBy' in patch && patch.supersededBy !== null && patch.supersededBy !== undefined && !okId(String(patch.supersededBy))) return null;
269
+ const result = await db.query(
270
+ `UPDATE ${o.table} SET ${sets.join(', ')} WHERE id = $1 AND owner_id = $2 AND scope = $3${onlyActive} RETURNING ${columns(true)}`,
271
+ [String(id), where.ownerId, where.scope, ...params]
272
+ );
273
+ return result.rows[0] ? toRecord(result.rows[0]) : null;
274
+ },
275
+
276
+ async remove(where, ids) {
277
+ const good = goodIds(ids);
278
+ if (!okPlace(where) || !good.length) return 0;
279
+ const result = await db.query(`DELETE FROM ${o.table} WHERE ${placeSql} AND id = ANY($3::${o.idType}[])`, [where.ownerId, where.scope, good]);
280
+ return result.rowCount ?? 0;
281
+ },
282
+
283
+ async removeAll(where) {
284
+ if (!okPlace(where)) return 0;
285
+ const result = await db.query(`DELETE FROM ${o.table} WHERE ${placeSql}`, [where.ownerId, where.scope]);
286
+ return result.rowCount ?? 0;
287
+ },
288
+
289
+ /* Right to erasure: this owner in every scope — memories, settings and consolidation marks. */
290
+ async purgeOwner(ownerId) {
291
+ const owner = String(ownerId ?? '');
292
+ if (!owner || (shaped.ownerId === 'uuid' && !UUID.test(owner))) return { memories: 0, settings: 0, refs: 0 };
293
+ const count = async (table) => (await db.query(`DELETE FROM ${table} WHERE owner_id = $1`, [owner])).rowCount ?? 0;
294
+ return { memories: await count(o.table), settings: await count(o.settingsTable), refs: await count(o.refsTable) };
295
+ },
296
+
297
+ async getSettings(where) {
298
+ if (!okPlace(where)) return { paused: false };
299
+ const result = await db.query(`SELECT paused FROM ${o.settingsTable} WHERE ${placeSql}`, [where.ownerId, where.scope]);
300
+ return { paused: Boolean(result.rows[0] && result.rows[0].paused) };
301
+ },
302
+
303
+ /* Only `paused` is kept in settings. */
304
+ async setSettings(where, patch = {}) {
305
+ if (!okPlace(where)) return { paused: false };
306
+ const result = await db.query(
307
+ `INSERT INTO ${o.settingsTable} (owner_id, scope, paused) VALUES ($1, $2, $3)
308
+ ON CONFLICT (owner_id, scope) DO UPDATE SET paused = COALESCE($4, ${o.settingsTable}.paused)
309
+ RETURNING paused`,
310
+ [where.ownerId, where.scope, Boolean(patch.paused), patch.paused === undefined ? null : Boolean(patch.paused)]
311
+ );
312
+ return { paused: Boolean(result.rows[0].paused) };
313
+ },
314
+
315
+ async claimRef(where, ref) {
316
+ if (!okPlace(where)) return false;
317
+ const result = await db.query(
318
+ `INSERT INTO ${o.refsTable} (owner_id, scope, ref) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING RETURNING ref`,
319
+ [where.ownerId, where.scope, String(ref)]
320
+ );
321
+ return result.rows.length > 0;
322
+ },
323
+
324
+ async releaseRef(where, ref) {
325
+ if (!okPlace(where)) return;
326
+ await db.query(`DELETE FROM ${o.refsTable} WHERE ${placeSql} AND ref = $3`, [where.ownerId, where.scope, String(ref)]);
327
+ },
328
+
329
+ /* Active memories, every owner, with no vector or one from another source. */
330
+ async listNeedingVector({ limit = 50, source } = {}) {
331
+ const result = await db.query(
332
+ `SELECT ${columns(true)} FROM ${o.table}
333
+ WHERE superseded_by IS NULL AND (vector IS NULL OR ($1::text IS NOT NULL AND vector_source IS DISTINCT FROM $1::text))
334
+ ORDER BY (vector IS NOT NULL), created_at LIMIT $2`,
335
+ [source ?? null, Math.max(1, Math.floor(Number(limit)))]
336
+ );
337
+ return result.rows.map(toRecord);
338
+ }
339
+ };
340
+
341
+ if (o.search) {
342
+ /*
343
+ * Candidates for recall. By words: full text search (OR of the words,
344
+ * ranked), then, when no word matches, by fragment. By meaning: pgvector's
345
+ * cosine distance, or without pgvector the cosine computed here over the
346
+ * vectors of the same source. Active memories only.
347
+ */
348
+ store.search = async function search(where, { text, vector, vectorSource, kinds, createdAfter, createdBefore, limit = 32 } = {}) {
349
+ if (!okPlace(where)) return { semantic: [], lexical: [] };
350
+ const c = conditions({ kinds, createdAfter, createdBefore });
351
+ const bound = Math.max(1, Math.floor(Number(limit)));
352
+ const base = [where.ownerId, where.scope, ...c.params];
353
+ const next = base.length + 1;
354
+
355
+ let lexical = [];
356
+ const query = text ? tsQueryOf(text) : null;
357
+ if (query) {
358
+ const result = await db.query(
359
+ `SELECT ${columns(false)}, ts_rank(search_vector, to_tsquery('${o.textSearchConfig}', $${next})) AS score FROM ${o.table}
360
+ WHERE ${placeSql}${c.sql} AND search_vector @@ to_tsquery('${o.textSearchConfig}', $${next})
361
+ ORDER BY score DESC, importance DESC, updated_at DESC LIMIT ${bound}`,
362
+ [...base, query]
363
+ );
364
+ lexical = result.rows.map(toRecord);
365
+ }
366
+ if (!lexical.length && text && String(text).trim()) {
367
+ const fragment = `%${String(text).trim().replace(/[\\%_]/g, (char) => `\\${char}`)}%`;
368
+ const result = await db.query(
369
+ `SELECT ${columns(false)}, 0.1 AS score FROM ${o.table}
370
+ WHERE ${placeSql}${c.sql} AND text ILIKE $${next}
371
+ ORDER BY importance DESC, updated_at DESC LIMIT ${bound}`,
372
+ [...base, fragment]
373
+ );
374
+ lexical = result.rows.map(toRecord);
375
+ }
376
+
377
+ let semantic = [];
378
+ if (Array.isArray(vector) && vector.length) {
379
+ if (pgvector) {
380
+ const result = await db.query(
381
+ `SELECT ${columns(true)}, 1 - (vector <=> $${next}::vector) AS score FROM ${o.table}
382
+ WHERE ${placeSql}${c.sql} AND vector IS NOT NULL AND vector_source IS NOT DISTINCT FROM $${next + 1}::text AND vector_dims(vector) = $${next + 2}
383
+ ORDER BY vector <=> $${next}::vector LIMIT ${bound}`,
384
+ [...base, JSON.stringify(vector), vectorSource ?? null, vector.length]
385
+ );
386
+ semantic = result.rows.map(toRecord);
387
+ } else {
388
+ const result = await db.query(
389
+ `SELECT ${columns(true)} FROM ${o.table}
390
+ WHERE ${placeSql}${c.sql} AND vector IS NOT NULL AND vector_source IS NOT DISTINCT FROM $${next}::text`,
391
+ [...base, vectorSource ?? null]
392
+ );
393
+ semantic = result.rows.map(toRecord)
394
+ .filter((row) => Array.isArray(row.vector) && row.vector.length === vector.length)
395
+ .map((row) => ({ ...row, score: cosine(vector, row.vector) }))
396
+ .sort((a, b) => b.score - a.score)
397
+ .slice(0, bound);
398
+ }
399
+ }
400
+ return { semantic, lexical };
401
+ };
402
+ }
403
+
404
+ return store;
405
+ }
406
+
407
+ module.exports = { createPostgresMemoryStore, postgresMemorySchema };
@@ -11,6 +11,16 @@
11
11
  * methods (search, claimRef/releaseRef, listNeedingVector) are checked only
12
12
  * when the store has them.
13
13
  *
14
+ * Places: a store whose scope (or owner) is a foreign key, or has a shape, passes
15
+ * `makeScope(name, store)` / `makeOwner(name, store)`. They are called with the
16
+ * names the suite uses ('scope-1', 'scope-2'; 'owner-a', 'owner-b', 'owner-z')
17
+ * and return the value to use in their place — creating the organisation row
18
+ * first when the store needs it. The same name must give the same value within
19
+ * one store.
20
+ *
21
+ * Vectors: a store whose vectors have a fixed size (a pgvector column) passes
22
+ * `vectorDimensions`; the suite pads its test vectors with zeros to that size.
23
+ *
14
24
  * Ids: a store whose ids have a shape (a UUID column) passes `newId`, which
15
25
  * makes every id the suite uses, the missing ones included. A store must answer
16
26
  * "not found" — never throw — for an id of another shape.
@@ -18,15 +28,16 @@
18
28
  const { miniExpect } = require('./miniExpect');
19
29
 
20
30
  let sequence = 0;
21
- let newId = () => `contract-${sequence}-${Math.random().toString(36).slice(2, 8)}`;
31
+ const defaultNewId = () => `contract-${sequence}-${Math.random().toString(36).slice(2, 8)}`;
22
32
 
23
- function record(overrides = {}) {
33
+ /* `places` is the world of one store ({ A1, ... }); without it, the plain names. */
34
+ function record(overrides = {}, places = null, newId = defaultNewId) {
24
35
  sequence += 1;
25
36
  const at = overrides.createdAt || new Date(Date.UTC(2026, 0, 1, 0, 0, sequence));
26
37
  return {
27
38
  id: newId(),
28
- ownerId: 'owner-a',
29
- scope: 'scope-1',
39
+ ownerId: places ? places.A1.ownerId : 'owner-a',
40
+ scope: places ? places.A1.scope : 'scope-1',
30
41
  role: 'member',
31
42
  text: 'likes long walks',
32
43
  kind: 'preference',
@@ -50,22 +61,39 @@ function runStoreContract(makeStore, runner = {}) {
50
61
  if (typeof describe !== 'function' || typeof test !== 'function') {
51
62
  throw new Error('runStoreContract needs describe and test (pass them, or run it inside jest).');
52
63
  }
53
- if (runner.newId) newId = runner.newId;
64
+ const newId = runner.newId || defaultNewId;
65
+ /* A vector of the size the store holds (a pgvector column has a fixed one): the given numbers, then zeros. */
66
+ const vec = (...head) => (runner.vectorDimensions ? [...head, ...new Array(Math.max(0, runner.vectorDimensions - head.length)).fill(0)] : head);
67
+ const makeScope = runner.makeScope || ((name) => name);
68
+ const makeOwner = runner.makeOwner || ((name) => name);
54
69
 
55
- const A1 = { ownerId: 'owner-a', scope: 'scope-1' };
56
- const A2 = { ownerId: 'owner-a', scope: 'scope-2' };
57
- const B1 = { ownerId: 'owner-b', scope: 'scope-1' };
70
+ /* The places of one store: owners and scopes made by the injected factories. */
71
+ async function world(store) {
72
+ const owner = async (name) => String(await makeOwner(name, store));
73
+ const scope = async (name) => String(await makeScope(name, store));
74
+ const [a, b, z, s1, s2] = [await owner('owner-a'), await owner('owner-b'), await owner('owner-z'), await scope('scope-1'), await scope('scope-2')];
75
+ const places = {
76
+ A1: { ownerId: a, scope: s1 },
77
+ A2: { ownerId: a, scope: s2 },
78
+ B1: { ownerId: b, scope: s1 },
79
+ a, b, z, s1, s2
80
+ };
81
+ /* A record of this world, owned by A1 unless the overrides move it. */
82
+ places.rec = (overrides = {}) => record(overrides, places, newId);
83
+ return places;
84
+ }
58
85
  const time = (value) => new Date(value).getTime();
59
86
 
60
87
  describe('memory store contract', () => {
61
88
  test('insert then get returns the same record, and returned objects are copies', async () => {
62
89
  const store = await makeStore();
63
- const row = record({ source: { channel: 'auto', ref: 'c1' }, vector: [0.1, 0.2], vectorSource: 'm1' });
90
+ const { A1, rec: record, a: ownerA, s1: scope1 } = await world(store);
91
+ const row = record({ source: { channel: 'auto', ref: 'c1' }, vector: vec(0.1, 0.2), vectorSource: 'm1' });
64
92
  await store.insert(row);
65
93
  const got = await store.get(A1, row.id);
66
- expect(got).toMatchObject({ id: row.id, ownerId: 'owner-a', scope: 'scope-1', text: row.text, kind: 'preference', importance: 3, supersededBy: null });
94
+ expect(got).toMatchObject({ id: row.id, ownerId: ownerA, scope: scope1, text: row.text, kind: 'preference', importance: 3, supersededBy: null });
67
95
  expect(got.source).toEqual({ channel: 'auto', ref: 'c1' });
68
- expect(got.vector).toEqual([0.1, 0.2]);
96
+ expect(got.vector).toEqual(vec(0.1, 0.2));
69
97
  expect(got.vectorSource).toBe('m1');
70
98
  expect(time(got.createdAt)).toBe(time(row.createdAt));
71
99
  got.text = 'changed outside';
@@ -74,6 +102,7 @@ function runStoreContract(makeStore, runner = {}) {
74
102
 
75
103
  test('a record is invisible from another owner or another scope', async () => {
76
104
  const store = await makeStore();
105
+ const { A1, A2, B1, rec: record } = await world(store);
77
106
  const row = record();
78
107
  await store.insert(row);
79
108
  expect(await store.get(B1, row.id)).toBeNull();
@@ -88,6 +117,7 @@ function runStoreContract(makeStore, runner = {}) {
88
117
 
89
118
  test('list: active by default, newest first, with state, kinds, channel, seen, dates and limit filters', async () => {
90
119
  const store = await makeStore();
120
+ const { A1, rec: record } = await world(store);
91
121
  const old = record({ createdAt: new Date('2026-01-01T00:00:00Z'), kind: 'goal' });
92
122
  const mid = record({ createdAt: new Date('2026-02-01T00:00:00Z'), source: { channel: 'background' } });
93
123
  const recent = record({ createdAt: new Date('2026-03-01T00:00:00Z'), source: { channel: 'background' }, seenAt: new Date('2026-03-02T00:00:00Z') });
@@ -106,7 +136,8 @@ function runStoreContract(makeStore, runner = {}) {
106
136
 
107
137
  test('list with withVector: false leaves the vector out, and hasVector says whether there was one', async () => {
108
138
  const store = await makeStore();
109
- const printed = record({ vector: [0.5, 0.5], vectorSource: 'm1' });
139
+ const { A1, rec: record } = await world(store);
140
+ const printed = record({ vector: vec(0.5, 0.5), vectorSource: 'm1' });
110
141
  const bare = record();
111
142
  await store.insert(printed);
112
143
  await store.insert(bare);
@@ -116,15 +147,16 @@ function runStoreContract(makeStore, runner = {}) {
116
147
  expect(byId[printed.id].vector === null || byId[printed.id].vector === undefined).toBe(true);
117
148
  expect(byId[printed.id].hasVector).toBe(true);
118
149
  expect(byId[bare.id].hasVector === true).toBe(false);
119
- expect((await store.list(A1)).find((row) => row.id === printed.id).vector).toEqual([0.5, 0.5]);
150
+ expect((await store.list(A1)).find((row) => row.id === printed.id).vector).toEqual(vec(0.5, 0.5));
120
151
  });
121
152
 
122
153
  test('update patches in place, never moves a record, and onlyActive refuses a superseded one', async () => {
123
154
  const store = await makeStore();
155
+ const { A1, rec: record, a: ownerA, b: ownerB, s1: scope1, s2: scope2 } = await world(store);
124
156
  const row = record();
125
157
  await store.insert(row);
126
- const updated = await store.update(A1, row.id, { importance: 5, ownerId: 'owner-b', scope: 'scope-2' });
127
- expect(updated).toMatchObject({ id: row.id, importance: 5, ownerId: 'owner-a', scope: 'scope-1' });
158
+ const updated = await store.update(A1, row.id, { importance: 5, ownerId: ownerB, scope: scope2 });
159
+ expect(updated).toMatchObject({ id: row.id, importance: 5, ownerId: ownerA, scope: scope1 });
128
160
  expect(await store.update(A1, row.id, { supersededBy: newId() }, { onlyActive: true })).not.toBeNull();
129
161
  expect(await store.update(A1, row.id, { importance: 1 }, { onlyActive: true })).toBeNull();
130
162
  expect((await store.get(A1, row.id)).importance).toBe(5);
@@ -134,9 +166,10 @@ function runStoreContract(makeStore, runner = {}) {
134
166
 
135
167
  test('remove and removeAll count what they erased, in their place only', async () => {
136
168
  const store = await makeStore();
169
+ const { A1, A2, rec: record, s2: scope2 } = await world(store);
137
170
  const a = record();
138
171
  const b = record();
139
- const other = record({ scope: 'scope-2' });
172
+ const other = record({ scope: scope2 });
140
173
  for (const row of [a, b, other]) await store.insert(row);
141
174
  expect(await store.remove(A1, [a.id, newId()])).toBe(1);
142
175
  expect(await store.removeAll(A1)).toBe(1);
@@ -146,12 +179,13 @@ function runStoreContract(makeStore, runner = {}) {
146
179
 
147
180
  test('purgeOwner erases one owner in every scope, settings included, and nobody else', async () => {
148
181
  const store = await makeStore();
149
- const mine = [record(), record({ scope: 'scope-2' })];
150
- const theirs = record({ ownerId: 'owner-b' });
182
+ const { A1, A2, B1, rec: record, a: ownerA, b: ownerB, s2: scope2 } = await world(store);
183
+ const mine = [record(), record({ scope: scope2 })];
184
+ const theirs = record({ ownerId: ownerB });
151
185
  for (const row of [...mine, theirs]) await store.insert(row);
152
186
  await store.setSettings(A1, { paused: true });
153
187
  await store.setSettings(B1, { paused: true });
154
- const counts = await store.purgeOwner('owner-a');
188
+ const counts = await store.purgeOwner(ownerA);
155
189
  expect(counts.memories).toBe(2);
156
190
  expect(counts.settings).toBeGreaterThanOrEqual(1);
157
191
  expect(await store.list(A1, { state: 'all' })).toEqual([]);
@@ -163,6 +197,7 @@ function runStoreContract(makeStore, runner = {}) {
163
197
 
164
198
  test('settings default to not paused and belong to one place', async () => {
165
199
  const store = await makeStore();
200
+ const { A1, A2, B1 } = await world(store);
166
201
  expect((await store.getSettings(A1)).paused).toBe(false);
167
202
  expect((await store.setSettings(A1, { paused: true })).paused).toBe(true);
168
203
  expect((await store.getSettings(A1)).paused).toBe(true);
@@ -173,6 +208,7 @@ function runStoreContract(makeStore, runner = {}) {
173
208
 
174
209
  test('claimRef (optional) claims once per place; releaseRef frees it', async () => {
175
210
  const store = await makeStore();
211
+ const { A1, B1 } = await world(store);
176
212
  if (typeof store.claimRef !== 'function') return;
177
213
  expect(await store.claimRef(A1, 'conversation-1')).toBe(true);
178
214
  expect(await store.claimRef(A1, 'conversation-1')).toBe(false);
@@ -185,24 +221,26 @@ function runStoreContract(makeStore, runner = {}) {
185
221
 
186
222
  test('search (optional) stays in its place, skips superseded records and compares one vector source only', async () => {
187
223
  const store = await makeStore();
224
+ const { A1, rec: record, b: ownerB } = await world(store);
188
225
  if (typeof store.search !== 'function') return;
189
- const near = record({ text: 'plays the violin every evening', vector: [1, 0], vectorSource: 'm1' });
190
- const otherSource = record({ text: 'unrelated', vector: [1, 0], vectorSource: 'm2' });
191
- const replaced = record({ text: 'plays the violin badly', vector: [1, 0], vectorSource: 'm1', supersededBy: near.id });
192
- const stranger = record({ ownerId: 'owner-b', text: 'plays the violin too', vector: [1, 0], vectorSource: 'm1' });
226
+ const near = record({ text: 'plays the violin every evening', vector: vec(1, 0), vectorSource: 'm1' });
227
+ const otherSource = record({ text: 'unrelated', vector: vec(1, 0), vectorSource: 'm2' });
228
+ const replaced = record({ text: 'plays the violin badly', vector: vec(1, 0), vectorSource: 'm1', supersededBy: near.id });
229
+ const stranger = record({ ownerId: ownerB, text: 'plays the violin too', vector: vec(1, 0), vectorSource: 'm1' });
193
230
  for (const row of [near, otherSource, replaced, stranger]) await store.insert(row);
194
- const found = await store.search(A1, { text: 'violin evening', vector: [1, 0], vectorSource: 'm1', limit: 10 });
231
+ const found = await store.search(A1, { text: 'violin evening', vector: vec(1, 0), vectorSource: 'm1', limit: 10 });
195
232
  expect(found.semantic.map((row) => row.id)).toEqual([near.id]);
196
233
  expect(found.lexical.map((row) => row.id)).toEqual([near.id]);
197
234
  });
198
235
 
199
236
  test('listNeedingVector (optional) returns active records without a vector, or from another source', async () => {
200
237
  const store = await makeStore();
238
+ const { rec: record, z: ownerZ } = await world(store);
201
239
  if (typeof store.listNeedingVector !== 'function') return;
202
- const missing = record({ ownerId: 'owner-z' });
203
- const other = record({ ownerId: 'owner-z', vector: [1], vectorSource: 'old' });
204
- const fine = record({ ownerId: 'owner-z', vector: [1], vectorSource: 'new' });
205
- const replaced = record({ ownerId: 'owner-z', supersededBy: fine.id });
240
+ const missing = record({ ownerId: ownerZ });
241
+ const other = record({ ownerId: ownerZ, vector: vec(1), vectorSource: 'old' });
242
+ const fine = record({ ownerId: ownerZ, vector: vec(1), vectorSource: 'new' });
243
+ const replaced = record({ ownerId: ownerZ, supersededBy: fine.id });
206
244
  for (const row of [missing, other, fine, replaced]) await store.insert(row);
207
245
  const ids = (await store.listNeedingVector({ limit: 50, source: 'new' })).map((row) => row.id);
208
246
  expect(ids).toEqual(expect.arrayContaining([missing.id, other.id]));
package/src/tools.js CHANGED
@@ -87,7 +87,9 @@ function createMemoryTools(options = {}) {
87
87
  ok: true,
88
88
  code: 'memory_saved',
89
89
  memory: { id: result.memory.id, text: result.memory.text, kind: result.memory.kind, importance: result.memory.importance },
90
- undo: { id: result.memory.id }
90
+ /* A memory only reinforced has nothing to take back: undo would erase it. */
91
+ undo: result.reinforced ? null : { id: result.memory.id },
92
+ ...(result.reinforced ? { reinforced: true } : {})
91
93
  }, ctx);
92
94
  })
93
95
  };