@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,239 @@
1
+ # @astratra/memory
2
+
3
+ What an AI assistant remembers about each person it talks to — kept, found,
4
+ corrected, taken back and erased — with the storage, the embeddings, the model
5
+ and every word shown to a person supplied by you.
6
+
7
+ No runtime dependency. CommonJS, Node 20+.
8
+
9
+ ```bash
10
+ npm install @astratra/memory
11
+ ```
12
+
13
+ ## The idea in one screen
14
+
15
+ ```js
16
+ const { createMemory, createMemoryStore, patternRule } = require('@astratra/memory');
17
+
18
+ const memory = createMemory({
19
+ store: createMemoryStore(), // your adapter in production
20
+ embed: async (text, { purpose }) => ({ vector: await myEmbed(text, purpose), source: 'e5-small' }),
21
+ llm: async ({ system, prompt }) => myModel.complete({ system, prompt }),
22
+ rules: [patternRule({ code: 'secret', patterns: [/password|\bpin\b/i] })],
23
+ namesOf: async (where) => directory.namesInTenant(where.scope) // other people, never stored
24
+ });
25
+
26
+ const where = { ownerId: user.id, scope: tenant.id };
27
+
28
+ await memory.remember(where, { text: 'Prefers short answers', kind: 'preference', importance: 4, role: user.role });
29
+ // → { ok: true, memory, supersededId } or { ok: false, reason: 'secret' }
30
+
31
+ await memory.recall(where, { query: 'how do they like answers?' });
32
+ await memory.portrait(where); // "- Prefers short answers", for the system prompt
33
+ await memory.consolidate(where, { transcript, ref: conversation.id, role: user.role });
34
+ ```
35
+
36
+ ## Places, not users
37
+
38
+ Every memory belongs to a **place**: `{ ownerId, scope }`. `scope` is whatever
39
+ partition you need — a tenant, a workspace, `'global'` for staff, `''` for
40
+ none. Every store call carries the place; a memory is never visible from
41
+ another owner or another scope. A missing `ownerId` throws a `MemoryError`
42
+ (`invalid_where`) instead of meaning "everyone".
43
+
44
+ The one deliberate exception is `purgeOwner(ownerId)`: the right to erasure
45
+ removes a person's memories, settings and consolidation marks in **every**
46
+ scope.
47
+
48
+ ## What is refused, and how you say it
49
+
50
+ Refusals are **codes**, never sentences. Your catalog turns them into words in
51
+ the person's language.
52
+
53
+ | code | when |
54
+ | --- | --- |
55
+ | `empty` | nothing left after cleaning |
56
+ | `too_long` | over `maxTextLength` (500 by default) |
57
+ | `invalid_kind` | not one of `kinds`, nor an alias, and no `defaultKind` |
58
+ | `kind_not_allowed` | `roleKinds[role]` does not list this kind |
59
+ | `other_person` | the text names someone from `namesOf()` |
60
+ | `paused` | the person paused their memory |
61
+ | `not_found`, `conflict`, `ai_disabled` | update/forget/tool outcomes |
62
+ | *yours* | any code returned by one of your `rules` |
63
+
64
+ Content rules are yours — a health product, a school and a bank do not forbid
65
+ the same things. `patternRule()` builds one from regular expressions:
66
+
67
+ ```js
68
+ patternRule({ code: 'sensitive', patterns: [/diagnos/i], exceptRoles: ['minor'], allowWhenExplicit: true });
69
+ patternRule({ code: 'off_topic', patterns: [/relationship/i], roles: ['minor'] });
70
+ ```
71
+
72
+ Patterns are tested on the raw text and on its accent-folded, lower-case form.
73
+ `allowWhenExplicit` lets through what the person explicitly asked to be
74
+ remembered (`explicit: true`).
75
+
76
+ **Names.** `namesOf(where)` returns the names of other people. They are matched
77
+ as whole words, accents and case folded ("Paul" is not found in "Pauline"). The
78
+ person's own name (`personName`) is always allowed. On an **edit**, a name the
79
+ memory already carried stays allowed — it was accepted with it; only a name
80
+ the edit *adds* is refused.
81
+
82
+ **Kinds and importance from real models.** Models send `"GOAL"`, `"Objectif"`,
83
+ `"4"`, `4.6`. Kinds are folded and looked up in `kinds`, then in
84
+ `kindAliases` (`{ objectif: 'goal' }` — yours, in whatever languages you
85
+ serve). Importance is rounded and clamped to 1–5, defaulting to 3.
86
+
87
+ Text is cleaned: model Markdown (`**`, backticks, `__`, a leading heading) is
88
+ removed and whitespace collapsed. `C#` and `snake_case` survive.
89
+
90
+ ## Duplicates, corrections, undo
91
+
92
+ - A new memory whose vector is at least `duplicateThreshold` (0.92) close to an
93
+ active one **of the same embedding source**, or whose words are the same,
94
+ replaces it. Two embedding models never compare vectors.
95
+ - `update(where, id, { text, kind, importance })` never overwrites. It writes a
96
+ new version and marks the old one superseded; kind and importance stay unless
97
+ given; the rules are checked again with the memory's original role.
98
+ - `undo(where, id)` removes a version just written and brings back what it
99
+ replaced. It serves both "don't remember that" after `remember` and "put it
100
+ back" after `update`.
101
+ - `forget(where, id)` erases the memory **and every earlier version of it**. A
102
+ forgotten memory whose previous wording is still in the table is not
103
+ forgotten.
104
+ - Beyond `maxActive` (300) active memories, the least important go first, then
105
+ the longest unused (a never-used memory counts from its creation).
106
+
107
+ ## Recall
108
+
109
+ `recall(where, { query, kinds, after, before, limit })` fuses two rankings by
110
+ reciprocal rank: meaning (cosine, same source only, optional `minSimilarity`)
111
+ and words (share of the query's words found, accents folded). Without `embed` —
112
+ or while it fails — it ranks by words, then by the most recently useful.
113
+ Returned memories are marked used, which the portrait and the cap both read.
114
+
115
+ If your store implements `search()` (a vector index, full-text search), recall
116
+ uses it. With a `cipher`, it cannot: encrypted text is ranked in process.
117
+
118
+ ## Portrait
119
+
120
+ `portrait(where, { maxLength = 1200, minImportance = 4, format, masked })` —
121
+ important memories, most recently useful first, cut on a whole memory. With
122
+ `masked: true` the text goes through your `mask` before it reaches a model.
123
+
124
+ ## Consolidation after a conversation
125
+
126
+ ```js
127
+ const result = await memory.consolidate(where, {
128
+ transcript, // string, or [{ role, text }]
129
+ ref: conversation.id, // consolidated once (store.claimRef)
130
+ role: user.role,
131
+ personName: user.name,
132
+ language: user.language
133
+ });
134
+ // { status: 'done' | 'already' | 'paused' | 'empty' | 'unavailable' | 'failed', added, corrected, refused, summary }
135
+ ```
136
+
137
+ The model is shown the known memories (with ids, masked, 60 at most) and the
138
+ masked transcript, and returns `{ facts, corrections, summary }`. Corrections
139
+ may only name a memory it was shown. Every fact goes through the same rules as
140
+ `remember`. `isExplicitFact(fact, transcript)` decides whether the person asked
141
+ for a fact to be kept (for `allowWhenExplicit` rules).
142
+
143
+ It **never throws**. A failed run releases the `ref` so the next run retries.
144
+ A paused person's conversation is marked done and nothing is learnt from it,
145
+ even after the pause ends. The request is English by default; pass
146
+ `consolidationPrompt` to write your own. Facts land on the `background`
147
+ channel: `listUnseen()` returns them until `markSeen()`.
148
+
149
+ ## Privacy with the AI switched off
150
+
151
+ A person must always be able to see, pause, take back and erase what the
152
+ assistant keeps about them — including when the AI is off for their tenant,
153
+ their plan, or an outage.
154
+
155
+ ```js
156
+ const { createMemoryHandlers, PRIVACY_OPERATIONS } = require('@astratra/memory');
157
+
158
+ const handlers = createMemoryHandlers({ memory, isAiEnabled: (where) => ai.isOn(where.scope) });
159
+
160
+ // PRIVACY_OPERATIONS: list, listUnseen, markSeen, setPaused, undo, erase, eraseAll, purgeOwner
161
+ // They never call isAiEnabled. Only `update` (editing content) does → { ok: false, reason: 'ai_disabled' }.
162
+ app.get('/me/memories', auth, async (req, res) => res.json(await handlers.list(placeFrom(req.user))));
163
+ ```
164
+
165
+ Handlers are plain functions: mount them on any framework. Take the place from
166
+ your authentication, never from the request body.
167
+
168
+ ## Tools for `@astratra/ai`
169
+
170
+ ```js
171
+ const { createToolRegistry } = require('@astratra/ai');
172
+ const { createMemoryTools } = require('@astratra/memory');
173
+
174
+ const registry = createToolRegistry();
175
+ createMemoryTools({
176
+ memory,
177
+ roles: ['member', 'admin'],
178
+ whereOf: (ctx) => ({ ownerId: ctx.userId, scope: ctx.tenantId }), // required
179
+ personNameOf: (ctx) => ctx.userName,
180
+ isExplicit: (params, ctx) => myExplicitRequestDetector(ctx.command),
181
+ isAiEnabled: (ctx) => ai.isOn(ctx.tenantId),
182
+ translate: (code, ctx) => t(ctx.language, `memory.${code}`) // optional
183
+ }).forEach((tool) => registry.register(tool));
184
+ ```
185
+
186
+ `remember`, `recall`, `update_memory`, `forget` (renamable with `names`,
187
+ instructions replaceable with `descriptions`). Results are
188
+ `{ ok, code, ... }` — `memory_saved`, `memories_found`, `memory_corrected`,
189
+ `memory_forgotten`, or `refused` with a `reason` — plus `message` when you pass
190
+ `translate` (keys: the code, or `refused.<reason>`). Writes carry an
191
+ `undo: { id }` token for `memory.undo()`. `forget` erases: gate it with
192
+ `runAgentLoop({ confirmTool })` or `createPendingActions`.
193
+
194
+ ## The store contract
195
+
196
+ `createMemoryStore()` is the in-process reference. For a real database, write
197
+ an adapter with these methods (types in `index.d.ts`):
198
+
199
+ | method | |
200
+ | --- | --- |
201
+ | `insert(record)` | the service supplies `id` |
202
+ | `get(where, id)` | any state; `null` outside the place |
203
+ | `list(where, filter)` | `state` (`active` default, `superseded`, `all`), `supersededBy`, `kinds`, `channel`, `seen`, `createdAfter/Before`, `limit`; newest first |
204
+ | `update(where, id, patch, { onlyActive })` | never moves a record; `onlyActive` is a compare-and-set on "not superseded" |
205
+ | `remove(where, ids)`, `removeAll(where)` | counts |
206
+ | `purgeOwner(ownerId)` | every scope; `{ memories, settings, refs }` |
207
+ | `getSettings(where)`, `setSettings(where, patch)` | `{ paused }` |
208
+ | `claimRef`, `releaseRef` | optional — once-per-conversation consolidation |
209
+ | `search(where, input)` | optional — `{ semantic, lexical }` ranked records |
210
+ | `listNeedingVector({ limit, source })` | optional — for `reindex()` |
211
+
212
+ Prove it with the contract suite, in your adapter's tests:
213
+
214
+ ```js
215
+ const { runStoreContract } = require('@astratra/memory');
216
+ runStoreContract(async () => createMyStore(await freshDatabase()));
217
+ ```
218
+
219
+ ## Everything injected
220
+
221
+ | option | default |
222
+ | --- | --- |
223
+ | `store` | required |
224
+ | `kinds` | `goal, preference, fact, person, event, feeling` |
225
+ | `kindAliases`, `defaultKind`, `roleKinds`, `rules`, `namesOf` | none |
226
+ | `embed(text, { purpose })` → `number[]` or `{ vector, source }` | none: word ranking |
227
+ | `mask(text, where)` | identity — applied before `embed` and the model |
228
+ | `llm({ system, prompt, purpose, where })` → string | none: no consolidation |
229
+ | `cipher { encrypt, decrypt }` | none — an `encrypt` that returns its input is refused |
230
+ | `now`, `generateId`, `logger` | `new Date()`, `randomUUID()`, silent |
231
+ | `withLock(where, fn)` | in-process queue per place; use a distributed lock across instances |
232
+ | `maxTextLength`, `maxActive`, `duplicateThreshold`, `minSimilarity` | 500, 300, 0.92, none |
233
+
234
+ `reindex({ limit, source })` gives a vector to memories without one — or, with
235
+ `source`, re-embeds those from another model — and stops at the first failure.
236
+
237
+ ## License
238
+
239
+ MIT
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@astratra/memory",
3
+ "version": "0.1.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.",
5
+ "engines": {
6
+ "node": ">=20"
7
+ },
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "type": "commonjs",
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "scripts": {
15
+ "test": "jest"
16
+ },
17
+ "jest": {
18
+ "testMatch": [
19
+ "**/__tests__/**/*.test.js"
20
+ ]
21
+ },
22
+ "keywords": [
23
+ "astratra",
24
+ "memory",
25
+ "ai",
26
+ "agent",
27
+ "embeddings",
28
+ "recall",
29
+ "privacy"
30
+ ],
31
+ "license": "MIT",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "devDependencies": {
36
+ "@astratra/ai": "^1.3.0",
37
+ "jest": "30.4.2"
38
+ }
39
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Reading what a model returns after a conversation, and the default request
3
+ * made to it. The request is an instruction to a model, never shown to a
4
+ * person; pass `consolidationPrompt` to write your own.
5
+ */
6
+
7
+ /*
8
+ * Models wrap their JSON in a code fence, or say a word around it: the outer
9
+ * object alone is read. Anything else throws — the caller treats it as a
10
+ * failed run, never as "nothing to remember".
11
+ */
12
+ function parseModelJson(value) {
13
+ const text = String(value ?? '').replace(/^\s*```(?:json)?\s*/i, '').replace(/\s*```\s*$/, '');
14
+ const start = text.indexOf('{');
15
+ const end = text.lastIndexOf('}');
16
+ if (start === -1 || end < start) throw new SyntaxError('The model answer holds no JSON object.');
17
+ const parsed = JSON.parse(text.slice(start, end + 1));
18
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new TypeError('The model answer is not an object.');
19
+ return parsed;
20
+ }
21
+
22
+ /**
23
+ * @param {object} input
24
+ * @param {string[]} input.kinds
25
+ * @param {Array<{id: string, text: string}>} input.known already masked.
26
+ * @param {string} input.transcript already masked.
27
+ * @param {string} [input.language]
28
+ * @param {string} [input.role]
29
+ * @returns {{ system: string, prompt: string }}
30
+ */
31
+ function defaultConsolidationPrompt({ kinds, known, transcript, language, role }) {
32
+ const system = [
33
+ 'Extract durable memories about the person from this conversation, and summarize the episode.',
34
+ 'Return JSON only, shaped exactly as',
35
+ `{"facts":[{"text":"...","kind":"${kinds.join('|')}","importance":3}],"corrections":[{"id":"...","text":"..."}],"summary":"..."}.`,
36
+ 'Keep each fact short and self-contained. Importance is an integer from 1 to 5.',
37
+ 'When the conversation shows that a known memory is no longer right, put it in corrections with its id and the right text, and do not repeat it in facts.',
38
+ 'Do not put in facts what is already known. Never reveal masked data.',
39
+ ...(role ? [`The person's role is: ${role}.`] : []),
40
+ ...(language ? [`Write facts and the summary in the language whose code is "${language}".`] : [])
41
+ ].join('\n');
42
+ const prompt = [
43
+ ...(known.length ? ['--- ALREADY KNOWN ---', ...known.map((row) => `${row.id}: ${row.text}`), '--- END ---'] : []),
44
+ '--- CONVERSATION ---',
45
+ transcript,
46
+ '--- END ---'
47
+ ].join('\n');
48
+ return { system, prompt };
49
+ }
50
+
51
+ /* A transcript is a string, or turns { role, text } joined one per line. */
52
+ function transcriptText(transcript) {
53
+ if (typeof transcript === 'string') return transcript;
54
+ if (!Array.isArray(transcript)) return '';
55
+ return transcript
56
+ .map((turn) => (turn && typeof turn === 'object' ? `${turn.role || 'user'}: ${turn.text ?? turn.content ?? ''}` : String(turn ?? '')))
57
+ .join('\n');
58
+ }
59
+
60
+ module.exports = {
61
+ parseModelJson,
62
+ defaultConsolidationPrompt,
63
+ transcriptText
64
+ };
@@ -0,0 +1,84 @@
1
+ /**
2
+ * What a "my memories" screen calls, as plain functions — mount them on any
3
+ * framework. They take the place from YOUR authentication, never from the
4
+ * request body.
5
+ *
6
+ * A person must always be able to see, pause, take back and erase what the
7
+ * assistant keeps about them — including when the AI is switched off, for a
8
+ * school, a plan, or an outage. Those operations are listed in
9
+ * PRIVACY_OPERATIONS and never consult `isAiEnabled`. Only editing a memory's
10
+ * content does: an edit is a new memory, and the AI is what writes memories.
11
+ */
12
+ const { REASONS } = require('./rules');
13
+
14
+ const PRIVACY_OPERATIONS = Object.freeze(['list', 'listUnseen', 'markSeen', 'setPaused', 'undo', 'erase', 'eraseAll', 'purgeOwner']);
15
+ const AI_OPERATIONS = Object.freeze(['update']);
16
+
17
+ /** True when the operation keeps working with the AI switched off. */
18
+ function worksWithoutAi(operation) {
19
+ return PRIVACY_OPERATIONS.includes(operation);
20
+ }
21
+
22
+ /**
23
+ * @param {object} options
24
+ * @param {object} options.memory from createMemory().
25
+ * @param {Function} [options.isAiEnabled] (where) => boolean. Absent: always on.
26
+ */
27
+ function createMemoryHandlers(options = {}) {
28
+ const memory = options.memory;
29
+ if (!memory || typeof memory.list !== 'function') throw new Error('createMemoryHandlers requires options.memory from createMemory().');
30
+ const isAiEnabled = options.isAiEnabled || (() => true);
31
+
32
+ return {
33
+ async list(where) {
34
+ const [paused, memories] = await Promise.all([memory.isPaused(where), memory.list(where)]);
35
+ return { ok: true, paused, memories };
36
+ },
37
+
38
+ async listUnseen(where) {
39
+ return { ok: true, memories: await memory.listUnseen(where) };
40
+ },
41
+
42
+ async markSeen(where, { ids } = {}) {
43
+ const list = Array.isArray(ids) ? ids.filter((id) => typeof id === 'string') : [];
44
+ return { ok: true, seen: await memory.markSeen(where, list) };
45
+ },
46
+
47
+ async setPaused(where, { paused } = {}) {
48
+ return { ok: true, paused: await memory.setPaused(where, paused === true) };
49
+ },
50
+
51
+ async undo(where, { id } = {}) {
52
+ const undone = await memory.undo(where, String(id ?? ''));
53
+ return undone ? { ok: true, undone } : { ok: false, reason: REASONS.NOT_FOUND };
54
+ },
55
+
56
+ async erase(where, { id } = {}) {
57
+ const erased = await memory.forget(where, String(id ?? ''));
58
+ return erased ? { ok: true, erased } : { ok: false, reason: REASONS.NOT_FOUND };
59
+ },
60
+
61
+ async eraseAll(where) {
62
+ return { ok: true, erased: await memory.eraseAll(where) };
63
+ },
64
+
65
+ /* For an account deletion job, not for a screen: every scope of the owner. */
66
+ async purgeOwner(ownerId) {
67
+ return { ok: true, ...(await memory.purgeOwner(ownerId)) };
68
+ },
69
+
70
+ /* The person edits their own memory: they are asking for it, so it counts as explicit. */
71
+ async update(where, { id, text, kind, importance, personName } = {}) {
72
+ if (!(await isAiEnabled(where))) return { ok: false, reason: REASONS.AI_DISABLED };
73
+ const result = await memory.update(where, String(id ?? ''), { text, kind, importance }, { personName, explicit: true });
74
+ return result.ok ? { ok: true, memory: result.memory, supersededId: result.supersededId } : { ok: false, reason: result.reason };
75
+ }
76
+ };
77
+ }
78
+
79
+ module.exports = {
80
+ createMemoryHandlers,
81
+ PRIVACY_OPERATIONS,
82
+ AI_OPERATIONS,
83
+ worksWithoutAi
84
+ };