@astratra/memory 0.1.0 → 0.2.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 +51 -13
- package/package.json +1 -1
- package/src/consolidation.js +134 -2
- package/src/index.d.ts +31 -1
- package/src/memory.js +117 -59
- package/src/memoryStore.js +10 -2
- package/src/ranking.js +8 -3
- package/src/rules.js +3 -2
- package/src/testing/miniExpect.js +63 -0
- package/src/testing/storeContract.js +35 -11
package/README.md
CHANGED
|
@@ -90,17 +90,23 @@ removed and whitespace collapsed. `C#` and `snake_case` survive.
|
|
|
90
90
|
## Duplicates, corrections, undo
|
|
91
91
|
|
|
92
92
|
- A new memory whose vector is at least `duplicateThreshold` (0.92) close to an
|
|
93
|
-
active one **of the same embedding source
|
|
94
|
-
replaces it. Two embedding models never compare vectors
|
|
93
|
+
active one **of the same embedding source and the same length**, or whose
|
|
94
|
+
words are the same, replaces it. Two embedding models never compare vectors,
|
|
95
|
+
and neither do two vectors of different lengths under one label.
|
|
95
96
|
- `update(where, id, { text, kind, importance })` never overwrites. It writes a
|
|
96
97
|
new version and marks the old one superseded; kind and importance stay unless
|
|
97
98
|
given; the rules are checked again with the memory's original role.
|
|
99
|
+
- `update(where, id, changes, { inPlace: true })` edits the memory where it
|
|
100
|
+
stands — same id, same creation date, no earlier version, nothing to undo.
|
|
101
|
+
It is for a person correcting their own memory on a screen that lists it by
|
|
102
|
+
id: a new id after each edit would leave the screen showing the old one.
|
|
98
103
|
- `undo(where, id)` removes a version just written and brings back what it
|
|
99
104
|
replaced. It serves both "don't remember that" after `remember` and "put it
|
|
100
105
|
back" after `update`.
|
|
101
106
|
- `forget(where, id)` erases the memory **and every earlier version of it**. A
|
|
102
107
|
forgotten memory whose previous wording is still in the table is not
|
|
103
|
-
forgotten.
|
|
108
|
+
forgotten. An earlier version is never forgotten on its own (`false`): the
|
|
109
|
+
memory that replaced it would stay.
|
|
104
110
|
- Beyond `maxActive` (300) active memories, the least important go first, then
|
|
105
111
|
the longest unused (a never-used memory counts from its creation).
|
|
106
112
|
|
|
@@ -117,9 +123,11 @@ uses it. With a `cipher`, it cannot: encrypted text is ranked in process.
|
|
|
117
123
|
|
|
118
124
|
## Portrait
|
|
119
125
|
|
|
120
|
-
`portrait(where, { maxLength = 1200, minImportance = 4, format, masked })` —
|
|
121
|
-
important memories, most recently useful first, cut on a whole memory.
|
|
122
|
-
|
|
126
|
+
`portrait(where, { maxLength = 1200, minImportance = 4, format, masked, fill })` —
|
|
127
|
+
important memories, most recently useful first, cut on a whole memory. It stops
|
|
128
|
+
at the first memory that no longer fits; with `fill: true` that one is left out
|
|
129
|
+
and the shorter ones after it still get their place. With `masked: true` the
|
|
130
|
+
text goes through your `mask` before it reaches a model.
|
|
123
131
|
|
|
124
132
|
## Consolidation after a conversation
|
|
125
133
|
|
|
@@ -138,13 +146,31 @@ The model is shown the known memories (with ids, masked, 60 at most) and the
|
|
|
138
146
|
masked transcript, and returns `{ facts, corrections, summary }`. Corrections
|
|
139
147
|
may only name a memory it was shown. Every fact goes through the same rules as
|
|
140
148
|
`remember`. `isExplicitFact(fact, transcript)` decides whether the person asked
|
|
141
|
-
for a fact to be kept (for `allowWhenExplicit` rules
|
|
149
|
+
for a fact to be kept (for `allowWhenExplicit` rules, or your own rule reading
|
|
150
|
+
`candidate.explicit`).
|
|
151
|
+
|
|
152
|
+
The answer is read as models really give it (`readExtraction`, also exported):
|
|
153
|
+
a code fence or a sentence around the JSON, raw line breaks in strings, a
|
|
154
|
+
trailing comma, a bare list of facts, facts as plain strings, `memories` or
|
|
155
|
+
`new_facts` for `facts`, `updates` for `corrections`, `fact`/`memory`/`content`
|
|
156
|
+
for `text`, `type`/`category` for `kind`, `priority` for `importance`, and an
|
|
157
|
+
answer stopped half way (each whole fact before the cut is kept).
|
|
158
|
+
|
|
159
|
+
It **never throws**, and each write stands on its own: a fact that is refused
|
|
160
|
+
or whose write fails never loses the others. A failed run releases the `ref`
|
|
161
|
+
so the next run retries (what was kept merges as a duplicate). It says why, for
|
|
162
|
+
your logs: `{ status: 'failed', reason, error, added, corrected, refused,
|
|
163
|
+
failed, proposed }` with `reason` one of `model` (the function threw),
|
|
164
|
+
`unreadable` (nothing to read in the answer), `store` (`failed` writes threw),
|
|
165
|
+
`invalid_where`, `error`. `error` is the cause itself — classify it yourself,
|
|
166
|
+
never log the person's words.
|
|
142
167
|
|
|
143
|
-
It **never throws**. A failed run releases the `ref` so the next run retries.
|
|
144
168
|
A paused person's conversation is marked done and nothing is learnt from it,
|
|
145
169
|
even after the pause ends. The request is English by default; pass
|
|
146
|
-
`consolidationPrompt` to write your own.
|
|
147
|
-
|
|
170
|
+
`consolidationPrompt` to write your own. A transcript over `transcriptMax`
|
|
171
|
+
keeps its start, or its end with `transcriptKeep: 'end'` (what is new, when you
|
|
172
|
+
consolidate after each answer). Facts land on the `background` channel:
|
|
173
|
+
`listUnseen()` returns them until `markSeen()`.
|
|
148
174
|
|
|
149
175
|
## Privacy with the AI switched off
|
|
150
176
|
|
|
@@ -200,12 +226,12 @@ an adapter with these methods (types in `index.d.ts`):
|
|
|
200
226
|
| --- | --- |
|
|
201
227
|
| `insert(record)` | the service supplies `id` |
|
|
202
228
|
| `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
|
|
229
|
+
| `list(where, filter)` | `state` (`active` default, `superseded`, `all`), `supersededBy`, `kinds`, `channel`, `seen`, `createdAfter/Before`, `limit`, `withVector` (`false`: leave the vectors out, set `hasVector`); newest first |
|
|
204
230
|
| `update(where, id, patch, { onlyActive })` | never moves a record; `onlyActive` is a compare-and-set on "not superseded" |
|
|
205
231
|
| `remove(where, ids)`, `removeAll(where)` | counts |
|
|
206
232
|
| `purgeOwner(ownerId)` | every scope; `{ memories, settings, refs }` |
|
|
207
233
|
| `getSettings(where)`, `setSettings(where, patch)` | `{ paused }` |
|
|
208
|
-
| `claimRef`, `releaseRef` | optional — once-per-conversation consolidation |
|
|
234
|
+
| `claimRef`, `releaseRef` | optional — once-per-conversation consolidation (a host that follows its own watermark, "read up to this message", does without) |
|
|
209
235
|
| `search(where, input)` | optional — `{ semantic, lexical }` ranked records |
|
|
210
236
|
| `listNeedingVector({ limit, source })` | optional — for `reindex()` |
|
|
211
237
|
|
|
@@ -216,6 +242,17 @@ const { runStoreContract } = require('@astratra/memory');
|
|
|
216
242
|
runStoreContract(async () => createMyStore(await freshDatabase()));
|
|
217
243
|
```
|
|
218
244
|
|
|
245
|
+
The suite runs under Jest or Vitest as it is. Under `node:test`, hand it the
|
|
246
|
+
runner (its own small `expect` is used when there is none). A store whose ids
|
|
247
|
+
have a shape (a UUID column) gives it a generator, and must answer "not found",
|
|
248
|
+
never throw, for an id of another shape:
|
|
249
|
+
|
|
250
|
+
```js
|
|
251
|
+
import { describe, test } from 'node:test';
|
|
252
|
+
import { randomUUID } from 'node:crypto';
|
|
253
|
+
runStoreContract(async () => createMyStore(await freshDatabase()), { describe, test, newId: randomUUID });
|
|
254
|
+
```
|
|
255
|
+
|
|
219
256
|
## Everything injected
|
|
220
257
|
|
|
221
258
|
| option | default |
|
|
@@ -228,8 +265,9 @@ runStoreContract(async () => createMyStore(await freshDatabase()));
|
|
|
228
265
|
| `llm({ system, prompt, purpose, where })` → string | none: no consolidation |
|
|
229
266
|
| `cipher { encrypt, decrypt }` | none — an `encrypt` that returns its input is refused |
|
|
230
267
|
| `now`, `generateId`, `logger` | `new Date()`, `randomUUID()`, silent |
|
|
231
|
-
| `withLock(where, fn)` | in-process queue per place
|
|
268
|
+
| `withLock(where, fn)` | in-process queue per place (`createLocalLock()`, exported to compose with a lock shared across instances) |
|
|
232
269
|
| `maxTextLength`, `maxActive`, `duplicateThreshold`, `minSimilarity` | 500, 300, 0.92, none |
|
|
270
|
+
| `transcriptMax`, `transcriptKeep` | 40000, `'start'` |
|
|
233
271
|
|
|
234
272
|
`reindex({ limit, source })` gives a vector to memories without one — or, with
|
|
235
273
|
`source`, re-embeds those from another model — and stops at the first failure.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/memory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
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
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
package/src/consolidation.js
CHANGED
|
@@ -4,6 +4,48 @@
|
|
|
4
4
|
* person; pass `consolidationPrompt` to write your own.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
+
/*
|
|
8
|
+
* A model's answer is read as leniently as it can be without inventing
|
|
9
|
+
* anything. Syntax first: a code fence or a sentence around the JSON, raw line
|
|
10
|
+
* breaks inside its strings, a comma before a closing bracket.
|
|
11
|
+
*/
|
|
12
|
+
function repairJson(text) {
|
|
13
|
+
let out = '';
|
|
14
|
+
let inString = false;
|
|
15
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
16
|
+
const char = text[index];
|
|
17
|
+
if (inString) {
|
|
18
|
+
if (char === '\\') {
|
|
19
|
+
out += char + (text[index + 1] ?? '');
|
|
20
|
+
index += 1;
|
|
21
|
+
continue;
|
|
22
|
+
}
|
|
23
|
+
if (char === '"') inString = false;
|
|
24
|
+
else if (char === '\n') { out += '\\n'; continue; }
|
|
25
|
+
else if (char === '\r') continue;
|
|
26
|
+
else if (char === '\t') { out += '\\t'; continue; }
|
|
27
|
+
out += char;
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
if (char === '"') inString = true;
|
|
31
|
+
out += char;
|
|
32
|
+
}
|
|
33
|
+
return out.replace(/,\s*([}\]])/g, '$1');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function parseLoosely(text) {
|
|
37
|
+
for (const candidate of [text, repairJson(text)]) {
|
|
38
|
+
try {
|
|
39
|
+
return JSON.parse(candidate);
|
|
40
|
+
} catch (_error) {
|
|
41
|
+
/* The next reading. */
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
48
|
+
|
|
7
49
|
/*
|
|
8
50
|
* Models wrap their JSON in a code fence, or say a word around it: the outer
|
|
9
51
|
* object alone is read. Anything else throws — the caller treats it as a
|
|
@@ -14,11 +56,100 @@ function parseModelJson(value) {
|
|
|
14
56
|
const start = text.indexOf('{');
|
|
15
57
|
const end = text.lastIndexOf('}');
|
|
16
58
|
if (start === -1 || end < start) throw new SyntaxError('The model answer holds no JSON object.');
|
|
17
|
-
const parsed =
|
|
18
|
-
if (
|
|
59
|
+
const parsed = parseLoosely(text.slice(start, end + 1));
|
|
60
|
+
if (parsed === undefined) throw new SyntaxError('The model answer holds no readable JSON.');
|
|
61
|
+
if (!isObject(parsed)) throw new TypeError('The model answer is not an object.');
|
|
19
62
|
return parsed;
|
|
20
63
|
}
|
|
21
64
|
|
|
65
|
+
/* Every whole {...} in the text, even when what holds them was cut short. */
|
|
66
|
+
function wholeObjects(text) {
|
|
67
|
+
const found = [];
|
|
68
|
+
for (let start = text.indexOf('{'); start !== -1; start = text.indexOf('{', start + 1)) {
|
|
69
|
+
let depth = 0;
|
|
70
|
+
let inString = false;
|
|
71
|
+
for (let index = start; index < text.length; index += 1) {
|
|
72
|
+
const char = text[index];
|
|
73
|
+
if (inString) {
|
|
74
|
+
if (char === '\\') index += 1;
|
|
75
|
+
else if (char === '"') inString = false;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (char === '"') inString = true;
|
|
79
|
+
else if (char === '{') depth += 1;
|
|
80
|
+
else if (char === '}' && --depth === 0) {
|
|
81
|
+
const parsed = parseLoosely(text.slice(start, index + 1));
|
|
82
|
+
if (isObject(parsed)) found.push(parsed);
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return found;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/* The answer as an object with facts, corrections and summary, or null when nothing can be read in it. */
|
|
91
|
+
function answerOf(value) {
|
|
92
|
+
const text = String(value ?? '');
|
|
93
|
+
const open = text.indexOf('{');
|
|
94
|
+
const bracket = text.indexOf('[');
|
|
95
|
+
/* A list that comes before the first object is the list of facts itself. */
|
|
96
|
+
const list = bracket === -1 || (open !== -1 && open < bracket) ? undefined : parseLoosely(text.slice(bracket, text.lastIndexOf(']') + 1));
|
|
97
|
+
if (Array.isArray(list)) return { facts: list };
|
|
98
|
+
const whole = open === -1 ? undefined : parseLoosely(text.slice(open, text.lastIndexOf('}') + 1));
|
|
99
|
+
if (isObject(whole)) return whole;
|
|
100
|
+
if (open === -1) return null;
|
|
101
|
+
/* Cut short: the objects that are whole, a summary if it was written before the cut. */
|
|
102
|
+
const objects = wholeObjects(text.slice(open));
|
|
103
|
+
const summary = /"summary"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(text)?.[1];
|
|
104
|
+
if (!objects.length && summary === undefined) return null;
|
|
105
|
+
return {
|
|
106
|
+
facts: objects.filter((item) => !('id' in item)),
|
|
107
|
+
corrections: objects.filter((item) => 'id' in item),
|
|
108
|
+
...(summary === undefined ? {} : { summary: parseLoosely(`"${summary}"`) ?? summary })
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const listOf = (value) => (Array.isArray(value) ? value : []);
|
|
113
|
+
const oneLine = (value) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim() : '');
|
|
114
|
+
|
|
115
|
+
/* A fact as a string, or as an object whose text, kind and importance go by the names models give them. */
|
|
116
|
+
function factOf(item) {
|
|
117
|
+
const raw = typeof item === 'string' ? { text: item } : item;
|
|
118
|
+
if (!isObject(raw)) return null;
|
|
119
|
+
const text = oneLine(raw.text ?? raw.fact ?? raw.memory ?? raw.content);
|
|
120
|
+
if (!text) return null;
|
|
121
|
+
return { text, kind: raw.kind ?? raw.type ?? raw.category, importance: raw.importance ?? raw.priority };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* The facts, the corrections and the summary of a model's answer. Throws when
|
|
126
|
+
* nothing can be read in it. Read as models really answer: a code fence or a
|
|
127
|
+
* sentence around the JSON, raw line breaks in strings, a trailing comma, a
|
|
128
|
+
* bare list of facts, facts as plain strings, `memories` or `new_facts` for
|
|
129
|
+
* `facts`, `updates` for `corrections`, `fact`/`memory`/`content` for `text`,
|
|
130
|
+
* `type`/`category` for `kind`, `priority` for `importance`, and an answer
|
|
131
|
+
* stopped half way (each whole fact before the cut is kept).
|
|
132
|
+
*
|
|
133
|
+
* Kind and importance are returned as the model wrote them: `remember()` and
|
|
134
|
+
* `update()` normalize them. The summary may be missing (null): the facts are
|
|
135
|
+
* kept all the same.
|
|
136
|
+
*
|
|
137
|
+
* @returns {{ facts: Array<{text: string, kind: unknown, importance: unknown}>,
|
|
138
|
+
* corrections: Array<{id: string, text: string, kind: unknown, importance: unknown}>,
|
|
139
|
+
* summary: string | null }}
|
|
140
|
+
*/
|
|
141
|
+
function readExtraction(value) {
|
|
142
|
+
const parsed = answerOf(value);
|
|
143
|
+
if (!parsed) throw new SyntaxError('The model answer holds nothing readable.');
|
|
144
|
+
const facts = listOf(parsed.facts ?? parsed.memories ?? parsed.new_facts).map(factOf).filter(Boolean);
|
|
145
|
+
const corrections = listOf(parsed.corrections ?? parsed.updates).flatMap((item) => {
|
|
146
|
+
const id = typeof item?.id === 'string' ? item.id.trim() : '';
|
|
147
|
+
const fact = id ? factOf(item) : null;
|
|
148
|
+
return fact ? [{ id, ...fact }] : [];
|
|
149
|
+
});
|
|
150
|
+
return { facts, corrections, summary: oneLine(parsed.summary) || null };
|
|
151
|
+
}
|
|
152
|
+
|
|
22
153
|
/**
|
|
23
154
|
* @param {object} input
|
|
24
155
|
* @param {string[]} input.kinds
|
|
@@ -59,6 +190,7 @@ function transcriptText(transcript) {
|
|
|
59
190
|
|
|
60
191
|
module.exports = {
|
|
61
192
|
parseModelJson,
|
|
193
|
+
readExtraction,
|
|
62
194
|
defaultConsolidationPrompt,
|
|
63
195
|
transcriptText
|
|
64
196
|
};
|
package/src/index.d.ts
CHANGED
|
@@ -39,6 +39,8 @@ export interface MemoryRecord {
|
|
|
39
39
|
updatedAt: Date;
|
|
40
40
|
/** Set by search() only. */
|
|
41
41
|
score?: number;
|
|
42
|
+
/** Set by a store that left the vector out (list with `withVector: false`): whether there is one. */
|
|
43
|
+
hasVector?: boolean;
|
|
42
44
|
}
|
|
43
45
|
|
|
44
46
|
/** What leaves the package: clear text, never the vector. */
|
|
@@ -70,6 +72,8 @@ export interface MemoryListFilter {
|
|
|
70
72
|
createdAfter?: Date | null;
|
|
71
73
|
createdBefore?: Date | null;
|
|
72
74
|
limit?: number;
|
|
75
|
+
/** Default true. false: the caller does not read vectors, so the store may leave them out (`vector: null`, `hasVector` set): a database saves shipping every 768 numbers of every memory. */
|
|
76
|
+
withVector?: boolean;
|
|
73
77
|
}
|
|
74
78
|
|
|
75
79
|
export interface MemorySearchInput {
|
|
@@ -185,6 +189,8 @@ export interface MemoryOptions {
|
|
|
185
189
|
knownTextMax?: number;
|
|
186
190
|
/** Characters of transcript sent. Default 40000. */
|
|
187
191
|
transcriptMax?: number;
|
|
192
|
+
/** Which part of a transcript over transcriptMax is kept: its 'start' (default) or its 'end' (what is new). */
|
|
193
|
+
transcriptKeep?: 'start' | 'end';
|
|
188
194
|
}
|
|
189
195
|
|
|
190
196
|
export type Refusal = { ok: false; reason: string };
|
|
@@ -223,8 +229,17 @@ export interface ConsolidateResult {
|
|
|
223
229
|
status: 'done' | 'already' | 'paused' | 'empty' | 'unavailable' | 'failed';
|
|
224
230
|
added: number;
|
|
225
231
|
corrected: number;
|
|
232
|
+
/** Facts and corrections a rule (or the checks) refused. */
|
|
226
233
|
refused: number;
|
|
234
|
+
/** Writes that threw: the others were kept all the same. */
|
|
235
|
+
failed: number;
|
|
236
|
+
/** Facts and corrections read in the model's answer. */
|
|
237
|
+
proposed: number;
|
|
227
238
|
summary: string | null;
|
|
239
|
+
/** With status 'failed': why. */
|
|
240
|
+
reason?: 'invalid_where' | 'model' | 'unreadable' | 'store' | 'error';
|
|
241
|
+
/** With status 'failed': the error behind it (the model's, the store's), for the host to log a cause without the person's words. */
|
|
242
|
+
error?: unknown;
|
|
228
243
|
}
|
|
229
244
|
|
|
230
245
|
export interface MemoryService {
|
|
@@ -234,7 +249,7 @@ export interface MemoryService {
|
|
|
234
249
|
where: MemoryWhere,
|
|
235
250
|
id: string,
|
|
236
251
|
changes: { text?: string; kind?: string; importance?: number | string },
|
|
237
|
-
options?: { personName?: string; explicit?: boolean; source?: Record<string, unknown>; ctx?: unknown }
|
|
252
|
+
options?: { personName?: string; explicit?: boolean; source?: Record<string, unknown>; ctx?: unknown; inPlace?: boolean }
|
|
238
253
|
): Promise<{ ok: true; memory: Memory; supersededId: string | null; unchanged?: boolean } | Refusal>;
|
|
239
254
|
undo(where: MemoryWhere, id: string): Promise<boolean>;
|
|
240
255
|
forget(where: MemoryWhere, id: string): Promise<boolean>;
|
|
@@ -255,6 +270,9 @@ export interface MemoryService {
|
|
|
255
270
|
|
|
256
271
|
export function createMemory(options: MemoryOptions): MemoryService;
|
|
257
272
|
|
|
273
|
+
/** One queue per place in this process; compose it with a lock shared between processes for `withLock`. */
|
|
274
|
+
export function createLocalLock(): <T>(where: MemoryPlace, fn: () => Promise<T>) => Promise<T>;
|
|
275
|
+
|
|
258
276
|
export class MemoryError extends Error {
|
|
259
277
|
constructor(code: string, message?: string);
|
|
260
278
|
code: string;
|
|
@@ -308,6 +326,8 @@ export interface PortraitOptions {
|
|
|
308
326
|
/** Default 4. */
|
|
309
327
|
minImportance?: number;
|
|
310
328
|
format?: (memory: { text: string; importance: number }) => string;
|
|
329
|
+
/** false (default): stop at the first memory that no longer fits. true: leave it out, and let the shorter ones after it in. */
|
|
330
|
+
fill?: boolean;
|
|
311
331
|
}
|
|
312
332
|
|
|
313
333
|
export function cosine(a: number[], b: number[]): number;
|
|
@@ -319,6 +339,13 @@ export function buildPortrait(
|
|
|
319
339
|
): string;
|
|
320
340
|
|
|
321
341
|
export function parseModelJson(value: unknown): Record<string, unknown>;
|
|
342
|
+
export interface Extraction {
|
|
343
|
+
facts: Array<{ text: string; kind: unknown; importance: unknown }>;
|
|
344
|
+
corrections: Array<{ id: string; text: string; kind: unknown; importance: unknown }>;
|
|
345
|
+
summary: string | null;
|
|
346
|
+
}
|
|
347
|
+
/** What a model's answer holds, read as leniently as models need; throws when nothing can be read. */
|
|
348
|
+
export function readExtraction(value: unknown): Extraction;
|
|
322
349
|
export function defaultConsolidationPrompt(input: {
|
|
323
350
|
kinds: string[];
|
|
324
351
|
known: Array<{ id: string; text: string }>;
|
|
@@ -391,7 +418,10 @@ export function worksWithoutAi(operation: string): boolean;
|
|
|
391
418
|
export interface ContractRunner {
|
|
392
419
|
describe?: (name: string, fn: () => void) => void;
|
|
393
420
|
test?: (name: string, fn: () => Promise<void> | void) => void;
|
|
421
|
+
/** Default: the global one (jest, vitest), else a small built-in that covers what the suite uses. */
|
|
394
422
|
expect?: (value: unknown) => any;
|
|
423
|
+
/** Makes every id the suite uses (missing ones included), for a store whose ids have a shape, a UUID for instance. */
|
|
424
|
+
newId?: () => string;
|
|
395
425
|
}
|
|
396
426
|
|
|
397
427
|
export function runStoreContract(makeStore: () => Awaitable<MemoryStore>, runner?: ContractRunner): void;
|
package/src/memory.js
CHANGED
|
@@ -26,7 +26,7 @@ const {
|
|
|
26
26
|
checkCandidate
|
|
27
27
|
} = require('./rules');
|
|
28
28
|
const { cosine, keywordScore, fuseByRank, buildPortrait } = require('./ranking');
|
|
29
|
-
const {
|
|
29
|
+
const { readExtraction, defaultConsolidationPrompt, transcriptText } = require('./consolidation');
|
|
30
30
|
|
|
31
31
|
const DEFAULT_KINDS = Object.freeze(['goal', 'preference', 'fact', 'person', 'event', 'feeling']);
|
|
32
32
|
const CHANNELS = Object.freeze({ EXPLICIT: 'explicit', AUTO: 'auto', BACKGROUND: 'background' });
|
|
@@ -62,7 +62,8 @@ function dateOf(value, code) {
|
|
|
62
62
|
return date;
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
/* One queue per place in this process: two writes for one person never interleave.
|
|
65
|
+
/* One queue per place in this process: two writes for one person never interleave.
|
|
66
|
+
Exported so a host can compose it with a lock shared between processes. */
|
|
66
67
|
function createLocalLock() {
|
|
67
68
|
const tails = new Map();
|
|
68
69
|
return async function withLock(where, fn) {
|
|
@@ -116,6 +117,8 @@ function createMemory(options = {}) {
|
|
|
116
117
|
const knownForConsolidation = options.knownForConsolidation ?? 60;
|
|
117
118
|
const knownTextMax = options.knownTextMax ?? 240;
|
|
118
119
|
const transcriptMax = options.transcriptMax ?? 40000;
|
|
120
|
+
/* A transcript over transcriptMax keeps its start ('start') or its end ('end': what is new). */
|
|
121
|
+
const transcriptKeep = options.transcriptKeep === 'end' ? 'end' : 'start';
|
|
119
122
|
|
|
120
123
|
const ruleConfig = { kinds, roleKinds, rules, maxTextLength };
|
|
121
124
|
const kindOf = (value, fallback = defaultKind) => normalizeKind(value, { kinds, aliases: kindAliases, fallback });
|
|
@@ -138,6 +141,11 @@ function createMemory(options = {}) {
|
|
|
138
141
|
|
|
139
142
|
const openAll = (rows) => Promise.all((rows || []).map(open));
|
|
140
143
|
|
|
144
|
+
/* Only vectors of the same embedding source AND the same length are compared: a source label alone cannot vouch for it. */
|
|
145
|
+
const comparable = (row, embedding) => Array.isArray(row.vector)
|
|
146
|
+
&& row.vectorSource === embedding.source
|
|
147
|
+
&& row.vector.length === embedding.vector.length;
|
|
148
|
+
|
|
141
149
|
/* What leaves the package: never the vector. */
|
|
142
150
|
function publicMemory(record) {
|
|
143
151
|
if (!record) return null;
|
|
@@ -155,7 +163,7 @@ function createMemory(options = {}) {
|
|
|
155
163
|
lastUsedAt: record.lastUsedAt || null,
|
|
156
164
|
createdAt: record.createdAt,
|
|
157
165
|
updatedAt: record.updatedAt,
|
|
158
|
-
hasVector: Array.isArray(record.vector) && record.vector.length > 0
|
|
166
|
+
hasVector: typeof record.hasVector === 'boolean' ? record.hasVector : Array.isArray(record.vector) && record.vector.length > 0
|
|
159
167
|
};
|
|
160
168
|
if (typeof record.score === 'number') out.score = record.score;
|
|
161
169
|
return out;
|
|
@@ -232,7 +240,7 @@ function createMemory(options = {}) {
|
|
|
232
240
|
*/
|
|
233
241
|
async function enforceCap(where) {
|
|
234
242
|
if (!maxActive) return 0;
|
|
235
|
-
const active = await store.list(where, { state: 'active' });
|
|
243
|
+
const active = await store.list(where, { state: 'active', withVector: false });
|
|
236
244
|
if (active.length <= maxActive) return 0;
|
|
237
245
|
const last = (row) => new Date(row.lastUsedAt || row.createdAt || 0).getTime();
|
|
238
246
|
const victims = active
|
|
@@ -274,8 +282,7 @@ function createMemory(options = {}) {
|
|
|
274
282
|
const active = await openAll(await store.list(where, { state: 'active' }));
|
|
275
283
|
const words = wordsOf(candidate.text);
|
|
276
284
|
const duplicate = (embedding
|
|
277
|
-
&& active.find((row) =>
|
|
278
|
-
&& cosine(embedding.vector, row.vector) >= duplicateThreshold))
|
|
285
|
+
&& active.find((row) => comparable(row, embedding) && cosine(embedding.vector, row.vector) >= duplicateThreshold))
|
|
279
286
|
|| active.find((row) => wordsOf(row.text) === words)
|
|
280
287
|
|| null;
|
|
281
288
|
|
|
@@ -310,6 +317,10 @@ function createMemory(options = {}) {
|
|
|
310
317
|
* Change one memory's text, kind or importance. The old version is kept
|
|
311
318
|
* behind the new one, so undo(newId) restores it. A name the memory already
|
|
312
319
|
* carried stays allowed; only a name the edit ADDS is refused.
|
|
320
|
+
*
|
|
321
|
+
* With `opts.inPlace` the memory is edited where it stands: same id, same
|
|
322
|
+
* creation date, no earlier version kept, so nothing to undo. It is for a
|
|
323
|
+
* person correcting their own memory on a screen that shows it by id.
|
|
313
324
|
*/
|
|
314
325
|
async function update(whereInput, id, changes = {}, opts = {}) {
|
|
315
326
|
const where = placeOf(whereInput);
|
|
@@ -340,6 +351,18 @@ function createMemory(options = {}) {
|
|
|
340
351
|
? (Array.isArray(old.vector) ? { vector: old.vector, source: old.vectorSource } : null)
|
|
341
352
|
: await vectorFor(text, 'passage', where);
|
|
342
353
|
|
|
354
|
+
if (opts.inPlace) {
|
|
355
|
+
return withLock(where, async () => {
|
|
356
|
+
const patch = { text: await seal(text), kind, importance, updatedAt: now() };
|
|
357
|
+
if (text !== old.text) {
|
|
358
|
+
patch.vector = embedding ? embedding.vector : null;
|
|
359
|
+
patch.vectorSource = embedding ? embedding.source : null;
|
|
360
|
+
}
|
|
361
|
+
const saved = await store.update(where, old.id, patch, { onlyActive: true });
|
|
362
|
+
return saved ? { ok: true, memory: publicMemory(await open(saved)), supersededId: null } : { ok: false, reason: REASONS.CONFLICT };
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
|
|
343
366
|
return withLock(where, async () => {
|
|
344
367
|
const at = now();
|
|
345
368
|
const record = {
|
|
@@ -385,12 +408,16 @@ function createMemory(options = {}) {
|
|
|
385
408
|
});
|
|
386
409
|
}
|
|
387
410
|
|
|
388
|
-
/**
|
|
411
|
+
/**
|
|
412
|
+
* Erase one memory and every earlier version of it. An earlier version is
|
|
413
|
+
* never erased on its own: the memory that replaced it would stay, and the
|
|
414
|
+
* person would believe the fact forgotten.
|
|
415
|
+
*/
|
|
389
416
|
async function forget(whereInput, id) {
|
|
390
417
|
const where = placeOf(whereInput);
|
|
391
418
|
return withLock(where, async () => {
|
|
392
419
|
const current = await store.get(where, String(id));
|
|
393
|
-
if (!current) return false;
|
|
420
|
+
if (!current || current.supersededBy) return false;
|
|
394
421
|
return (await removeWithHistory(where, [current.id])) > 0;
|
|
395
422
|
});
|
|
396
423
|
}
|
|
@@ -419,14 +446,14 @@ function createMemory(options = {}) {
|
|
|
419
446
|
async function list(whereInput, filter = {}) {
|
|
420
447
|
const where = placeOf(whereInput);
|
|
421
448
|
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 });
|
|
449
|
+
const rows = await store.list(where, { state: 'active', kinds: kindsFilter, limit: filter.limit, withVector: false });
|
|
423
450
|
return (await openAll(rows)).map(publicMemory);
|
|
424
451
|
}
|
|
425
452
|
|
|
426
453
|
/** Memories learnt in the background and not yet shown to the person. */
|
|
427
454
|
async function listUnseen(whereInput) {
|
|
428
455
|
const where = placeOf(whereInput);
|
|
429
|
-
const rows = await store.list(where, { state: 'active', channel: CHANNELS.BACKGROUND, seen: false });
|
|
456
|
+
const rows = await store.list(where, { state: 'active', channel: CHANNELS.BACKGROUND, seen: false, withVector: false });
|
|
430
457
|
return (await openAll(rows)).map(publicMemory);
|
|
431
458
|
}
|
|
432
459
|
|
|
@@ -490,7 +517,7 @@ function createMemory(options = {}) {
|
|
|
490
517
|
.filter((row) => row.score > 0)
|
|
491
518
|
.sort((a, b) => b.score - a.score || last(b) - last(a));
|
|
492
519
|
semantic = query
|
|
493
|
-
? rows.filter((row) =>
|
|
520
|
+
? rows.filter((row) => comparable(row, query))
|
|
494
521
|
.map((row) => ({ ...row, score: cosine(query.vector, row.vector) }))
|
|
495
522
|
.filter((row) => minSimilarity === null || row.score >= minSimilarity)
|
|
496
523
|
.sort((a, b) => b.score - a.score)
|
|
@@ -514,7 +541,7 @@ function createMemory(options = {}) {
|
|
|
514
541
|
/** The short text always given to the model. `masked: true` passes it through `mask` first. */
|
|
515
542
|
async function portrait(whereInput, opts = {}) {
|
|
516
543
|
const where = placeOf(whereInput);
|
|
517
|
-
const rows = await openAll(await store.list(where, { state: 'active' }));
|
|
544
|
+
const rows = await openAll(await store.list(where, { state: 'active', withVector: false }));
|
|
518
545
|
const text = buildPortrait(rows, opts);
|
|
519
546
|
return opts.masked && text ? mask(text, where) : text;
|
|
520
547
|
}
|
|
@@ -528,32 +555,50 @@ function createMemory(options = {}) {
|
|
|
528
555
|
* With `ref` (a conversation id) and a store that implements claimRef, a
|
|
529
556
|
* conversation is consolidated once. Paused: the conversation is marked
|
|
530
557
|
* done and nothing is learnt from it, even after the pause ends.
|
|
558
|
+
*
|
|
559
|
+
* Each write stands on its own: one that is refused or fails never loses
|
|
560
|
+
* the others. When something failed, the status is 'failed' with a `reason`
|
|
561
|
+
* ('invalid_where', 'model', 'unreadable', 'store', 'error') and the `error`
|
|
562
|
+
* behind it, so the host can log why; what was kept stays kept, and the
|
|
563
|
+
* next run merges it as a duplicate.
|
|
531
564
|
*/
|
|
532
565
|
async function consolidate(whereInput, input = {}) {
|
|
533
|
-
const
|
|
566
|
+
const none = { added: 0, corrected: 0, refused: 0, failed: 0, proposed: 0, summary: null };
|
|
534
567
|
let where;
|
|
535
568
|
try {
|
|
536
569
|
where = placeOf(whereInput);
|
|
537
570
|
} catch (error) {
|
|
538
571
|
logger.warn(`[memory] consolidate: ${error.message}`);
|
|
539
|
-
return { status: 'failed', ...
|
|
572
|
+
return { status: 'failed', reason: 'invalid_where', error, ...none };
|
|
540
573
|
}
|
|
541
|
-
if (!llm) return { status: 'unavailable', ...
|
|
574
|
+
if (!llm) return { status: 'unavailable', ...none };
|
|
542
575
|
const ref = input.ref === undefined || input.ref === null ? null : String(input.ref);
|
|
543
576
|
const canClaim = ref && typeof store.claimRef === 'function';
|
|
544
577
|
let claimed = false;
|
|
578
|
+
let stage = 'error';
|
|
579
|
+
|
|
580
|
+
/* A failed run is retried next time: the conversation is not marked done. */
|
|
581
|
+
async function failed(reason, error, result = none) {
|
|
582
|
+
if (claimed && typeof store.releaseRef === 'function') {
|
|
583
|
+
try { await store.releaseRef(where, ref); } catch (_error) { /* the claim stays; nothing else to do */ }
|
|
584
|
+
}
|
|
585
|
+
logger.warn(`[memory] consolidation failed (${reason}): ${error && error.message}`);
|
|
586
|
+
return { status: 'failed', reason, error, ...result };
|
|
587
|
+
}
|
|
588
|
+
|
|
545
589
|
try {
|
|
546
590
|
if (canClaim) {
|
|
547
591
|
claimed = await store.claimRef(where, ref);
|
|
548
|
-
if (!claimed) return { status: 'already', ...
|
|
592
|
+
if (!claimed) return { status: 'already', ...none };
|
|
549
593
|
}
|
|
550
|
-
if (await isPaused(where)) return { status: 'paused', ...
|
|
594
|
+
if (await isPaused(where)) return { status: 'paused', ...none };
|
|
551
595
|
|
|
552
|
-
const
|
|
553
|
-
if (!
|
|
596
|
+
const whole = transcriptText(input.transcript);
|
|
597
|
+
if (!whole.trim()) return { status: 'empty', ...none };
|
|
598
|
+
const raw = whole.length <= transcriptMax ? whole : transcriptKeep === 'end' ? whole.slice(-transcriptMax) : whole.slice(0, transcriptMax);
|
|
554
599
|
|
|
555
600
|
const last = (row) => new Date(row.lastUsedAt || 0).getTime();
|
|
556
|
-
const knownRows = (await openAll(await store.list(where, { state: 'active' })))
|
|
601
|
+
const knownRows = (await openAll(await store.list(where, { state: 'active', withVector: false })))
|
|
557
602
|
.sort((a, b) => b.importance - a.importance || last(b) - last(a)
|
|
558
603
|
|| new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
|
|
559
604
|
.slice(0, knownForConsolidation);
|
|
@@ -568,57 +613,69 @@ function createMemory(options = {}) {
|
|
|
568
613
|
language: input.language,
|
|
569
614
|
role: input.role
|
|
570
615
|
});
|
|
616
|
+
stage = 'model';
|
|
571
617
|
const answer = await llm({ ...request, purpose: 'memory-consolidation', where });
|
|
572
|
-
|
|
618
|
+
stage = 'error';
|
|
619
|
+
let extraction;
|
|
620
|
+
try {
|
|
621
|
+
extraction = readExtraction(typeof answer === 'string' ? answer : JSON.stringify(answer));
|
|
622
|
+
} catch (error) {
|
|
623
|
+
return await failed('unreadable', error);
|
|
624
|
+
}
|
|
573
625
|
|
|
574
|
-
const result = {
|
|
575
|
-
|
|
626
|
+
const result = { ...none, summary: extraction.summary, proposed: extraction.facts.length + extraction.corrections.length };
|
|
627
|
+
let firstError = null;
|
|
576
628
|
const source = { ...(input.source || {}), ...(ref ? { ref } : {}) };
|
|
577
629
|
const explicitFor = async (fact) => (isExplicitFact ? Boolean(await isExplicitFact(fact, input.transcript, where)) : false);
|
|
578
630
|
|
|
579
631
|
/* A correction may only name a memory that was shown. */
|
|
580
|
-
for (const correction of
|
|
581
|
-
if (!
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
632
|
+
for (const correction of extraction.corrections) {
|
|
633
|
+
if (!known.has(correction.id)) continue;
|
|
634
|
+
try {
|
|
635
|
+
const outcome = await update(where, correction.id, {
|
|
636
|
+
text: correction.text,
|
|
637
|
+
kind: correction.kind,
|
|
638
|
+
importance: correction.importance
|
|
639
|
+
}, {
|
|
640
|
+
personName: input.personName,
|
|
641
|
+
explicit: await explicitFor(correction),
|
|
642
|
+
source: { ...source, channel: CHANNELS.BACKGROUND },
|
|
643
|
+
ctx: input.ctx
|
|
644
|
+
});
|
|
645
|
+
if (outcome.ok && !outcome.unchanged) result.corrected += 1;
|
|
646
|
+
else if (!outcome.ok) result.refused += 1;
|
|
647
|
+
} catch (error) {
|
|
648
|
+
result.failed += 1;
|
|
649
|
+
firstError ??= error;
|
|
650
|
+
}
|
|
594
651
|
}
|
|
595
652
|
|
|
596
|
-
for (const fact of
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
653
|
+
for (const fact of extraction.facts) {
|
|
654
|
+
try {
|
|
655
|
+
/* The pause was read once, before the model was asked. */
|
|
656
|
+
const outcome = await keep(where, {
|
|
657
|
+
text: fact.text,
|
|
658
|
+
kind: fact.kind,
|
|
659
|
+
importance: fact.importance,
|
|
660
|
+
role: input.role,
|
|
661
|
+
personName: input.personName,
|
|
662
|
+
explicit: await explicitFor(fact),
|
|
663
|
+
channel: CHANNELS.BACKGROUND,
|
|
664
|
+
source,
|
|
665
|
+
ctx: input.ctx
|
|
666
|
+
}, false);
|
|
667
|
+
if (outcome.ok) result.added += 1;
|
|
668
|
+
else result.refused += 1;
|
|
669
|
+
} catch (error) {
|
|
670
|
+
result.failed += 1;
|
|
671
|
+
firstError ??= error;
|
|
672
|
+
}
|
|
612
673
|
}
|
|
674
|
+
if (result.failed) return await failed('store', firstError, result);
|
|
613
675
|
logger.info(`[memory] consolidated: ${result.added} added, ${result.corrected} corrected, ${result.refused} refused`);
|
|
614
676
|
return { status: 'done', ...result };
|
|
615
677
|
} catch (error) {
|
|
616
|
-
|
|
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 };
|
|
678
|
+
return failed(stage === 'model' ? 'model' : 'error', error);
|
|
622
679
|
}
|
|
623
680
|
}
|
|
624
681
|
|
|
@@ -666,6 +723,7 @@ function createMemory(options = {}) {
|
|
|
666
723
|
|
|
667
724
|
module.exports = {
|
|
668
725
|
createMemory,
|
|
726
|
+
createLocalLock,
|
|
669
727
|
MemoryError,
|
|
670
728
|
DEFAULT_KINDS,
|
|
671
729
|
CHANNELS
|
package/src/memoryStore.js
CHANGED
|
@@ -64,7 +64,15 @@ function createMemoryStore() {
|
|
|
64
64
|
const rows = [...records.values()]
|
|
65
65
|
.filter((record) => inPlace(where, record) && matches(record, filter))
|
|
66
66
|
.sort(newestFirst);
|
|
67
|
-
|
|
67
|
+
const out = (filter.limit ? rows.slice(0, filter.limit) : rows).map(clone);
|
|
68
|
+
/* The vector left out when the caller does not need it: hasVector says whether there is one. */
|
|
69
|
+
if (filter.withVector === false) {
|
|
70
|
+
for (const record of out) {
|
|
71
|
+
record.hasVector = Array.isArray(record.vector) && record.vector.length > 0;
|
|
72
|
+
record.vector = null;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
68
76
|
},
|
|
69
77
|
|
|
70
78
|
async update(where, id, patch, options = {}) {
|
|
@@ -147,7 +155,7 @@ function createMemoryStore() {
|
|
|
147
155
|
const rows = [...records.values()].filter((record) => inPlace(where, record)
|
|
148
156
|
&& matches(record, { kinds, createdAfter, createdBefore }));
|
|
149
157
|
const semantic = Array.isArray(vector)
|
|
150
|
-
? rows.filter((record) => Array.isArray(record.vector) && record.vectorSource === vectorSource)
|
|
158
|
+
? rows.filter((record) => Array.isArray(record.vector) && record.vectorSource === vectorSource && record.vector.length === vector.length)
|
|
151
159
|
.map((record) => ({ record, score: cosine(vector, record.vector) }))
|
|
152
160
|
.sort((a, b) => b.score - a.score)
|
|
153
161
|
.slice(0, limit)
|
package/src/ranking.js
CHANGED
|
@@ -49,9 +49,11 @@ const time = (value) => (value ? new Date(value).getTime() : 0);
|
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
51
|
* The short text always handed to the model: important memories first by the
|
|
52
|
-
* most recently useful, cut on a whole memory, never mid-sentence.
|
|
52
|
+
* most recently useful, cut on a whole memory, never mid-sentence. By default
|
|
53
|
+
* the portrait stops at the first memory that no longer fits; with `fill`, that
|
|
54
|
+
* one is left out and the shorter ones after it still get their place.
|
|
53
55
|
*/
|
|
54
|
-
function buildPortrait(memories, { maxLength = 1200, minImportance = 4, format = (memory) => `- ${memory.text}
|
|
56
|
+
function buildPortrait(memories, { maxLength = 1200, minImportance = 4, format = (memory) => `- ${memory.text}`, fill = false } = {}) {
|
|
55
57
|
const rows = (memories || [])
|
|
56
58
|
.filter((memory) => Number(memory.importance) >= minImportance)
|
|
57
59
|
.sort((a, b) => time(b.lastUsedAt) - time(a.lastUsedAt)
|
|
@@ -60,7 +62,10 @@ function buildPortrait(memories, { maxLength = 1200, minImportance = 4, format =
|
|
|
60
62
|
let out = '';
|
|
61
63
|
for (const memory of rows) {
|
|
62
64
|
const line = format(memory);
|
|
63
|
-
if (out.length + (out ? 1 : 0) + line.length > maxLength)
|
|
65
|
+
if (out.length + (out ? 1 : 0) + line.length > maxLength) {
|
|
66
|
+
if (fill) continue;
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
64
69
|
out += (out ? '\n' : '') + line;
|
|
65
70
|
}
|
|
66
71
|
return out;
|
package/src/rules.js
CHANGED
|
@@ -60,9 +60,10 @@ function normalizeKind(value, { kinds, aliases = {}, fallback = null } = {}) {
|
|
|
60
60
|
return fallback;
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
-
/* "4", 4.4 and 4 all mean 4; out of range is clamped; nonsense is the fallback. */
|
|
63
|
+
/* "4", 4.4 and 4 all mean 4; out of range is clamped; nonsense (and a blank string) is the fallback. */
|
|
64
64
|
function normalizeImportance(value, fallback = 3) {
|
|
65
|
-
if (value === null || value === undefined
|
|
65
|
+
if (value === null || value === undefined) return fallback;
|
|
66
|
+
if (typeof value === 'string' && !value.trim()) return fallback;
|
|
66
67
|
const number = Number(value);
|
|
67
68
|
return Number.isFinite(number) ? Math.min(5, Math.max(1, Math.round(number))) : fallback;
|
|
68
69
|
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The few matchers the store contract uses, for a test runner that has no
|
|
3
|
+
* `expect` of its own (node:test): toBe, toEqual, toBeNull, toMatchObject,
|
|
4
|
+
* toBeGreaterThanOrEqual, toContain, `.not`, and expect.arrayContaining.
|
|
5
|
+
* Jest and Vitest bring their own and are used first.
|
|
6
|
+
*/
|
|
7
|
+
const { inspect } = require('util');
|
|
8
|
+
|
|
9
|
+
const ASYMMETRIC = Symbol('asymmetric matcher');
|
|
10
|
+
|
|
11
|
+
function arrayContaining(items) {
|
|
12
|
+
return { [ASYMMETRIC]: true, match: (actual) => Array.isArray(actual) && items.every((item) => actual.some((value) => equals(value, item))) };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const isPlain = (value) => value !== null && typeof value === 'object' && !(value instanceof Date) && !Array.isArray(value);
|
|
16
|
+
const definedKeys = (value) => Object.keys(value).filter((key) => value[key] !== undefined);
|
|
17
|
+
|
|
18
|
+
/* Deep equality; a property that is undefined counts as missing, as in Jest's toEqual. */
|
|
19
|
+
function equals(actual, expected) {
|
|
20
|
+
if (expected && expected[ASYMMETRIC]) return expected.match(actual);
|
|
21
|
+
if (actual instanceof Date || expected instanceof Date) {
|
|
22
|
+
return actual instanceof Date && expected instanceof Date && actual.getTime() === expected.getTime();
|
|
23
|
+
}
|
|
24
|
+
if (Array.isArray(actual) || Array.isArray(expected)) {
|
|
25
|
+
return Array.isArray(actual) && Array.isArray(expected) && actual.length === expected.length
|
|
26
|
+
&& actual.every((value, index) => equals(value, expected[index]));
|
|
27
|
+
}
|
|
28
|
+
if (isPlain(actual) && isPlain(expected)) {
|
|
29
|
+
const keys = definedKeys(expected);
|
|
30
|
+
return definedKeys(actual).length === keys.length && keys.every((key) => equals(actual[key], expected[key]));
|
|
31
|
+
}
|
|
32
|
+
return Object.is(actual, expected);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/* Every property of `expected` is found, recursively, in `actual`. */
|
|
36
|
+
function contains(actual, expected) {
|
|
37
|
+
if (expected && expected[ASYMMETRIC]) return expected.match(actual);
|
|
38
|
+
if (isPlain(expected)) return isPlain(actual) && Object.keys(expected).every((key) => contains(actual[key], expected[key]));
|
|
39
|
+
return equals(actual, expected);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function matchers(actual, negate) {
|
|
43
|
+
const check = (pass, what, expected) => {
|
|
44
|
+
if (pass === negate) {
|
|
45
|
+
throw new Error(`expected ${inspect(actual, { depth: 4 })} ${negate ? 'not ' : ''}${what}${expected === undefined ? '' : ` ${inspect(expected, { depth: 4 })}`}`);
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
return {
|
|
49
|
+
toBe: (expected) => check(Object.is(actual, expected), 'to be', expected),
|
|
50
|
+
toEqual: (expected) => check(equals(actual, expected), 'to equal', expected),
|
|
51
|
+
toBeNull: () => check(actual === null, 'to be null'),
|
|
52
|
+
toMatchObject: (expected) => check(contains(actual, expected), 'to match', expected),
|
|
53
|
+
toBeGreaterThanOrEqual: (expected) => check(actual >= expected, 'to be at least', expected),
|
|
54
|
+
toContain: (expected) => check(Array.isArray(actual) || typeof actual === 'string' ? actual.includes(expected) : false, 'to contain', expected)
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function miniExpect(actual) {
|
|
59
|
+
return { ...matchers(actual, false), not: matchers(actual, true) };
|
|
60
|
+
}
|
|
61
|
+
miniExpect.arrayContaining = arrayContaining;
|
|
62
|
+
|
|
63
|
+
module.exports = { miniExpect };
|
|
@@ -5,19 +5,26 @@
|
|
|
5
5
|
* const { runStoreContract } = require('@astratra/memory');
|
|
6
6
|
* runStoreContract(async () => createPostgresMemoryStore(await freshPool()));
|
|
7
7
|
*
|
|
8
|
-
* It uses the test runner's describe/test
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
*
|
|
8
|
+
* It uses the test runner's describe/test (jest's globals, or pass them:
|
|
9
|
+
* `import { describe, test } from 'node:test'`) and expect (jest's global, or
|
|
10
|
+
* the small one of ./miniExpect, which covers what the suite uses). Optional
|
|
11
|
+
* methods (search, claimRef/releaseRef, listNeedingVector) are checked only
|
|
12
|
+
* when the store has them.
|
|
13
|
+
*
|
|
14
|
+
* Ids: a store whose ids have a shape (a UUID column) passes `newId`, which
|
|
15
|
+
* makes every id the suite uses, the missing ones included. A store must answer
|
|
16
|
+
* "not found" — never throw — for an id of another shape.
|
|
12
17
|
*/
|
|
18
|
+
const { miniExpect } = require('./miniExpect');
|
|
13
19
|
|
|
14
20
|
let sequence = 0;
|
|
21
|
+
let newId = () => `contract-${sequence}-${Math.random().toString(36).slice(2, 8)}`;
|
|
15
22
|
|
|
16
23
|
function record(overrides = {}) {
|
|
17
24
|
sequence += 1;
|
|
18
25
|
const at = overrides.createdAt || new Date(Date.UTC(2026, 0, 1, 0, 0, sequence));
|
|
19
26
|
return {
|
|
20
|
-
id:
|
|
27
|
+
id: newId(),
|
|
21
28
|
ownerId: 'owner-a',
|
|
22
29
|
scope: 'scope-1',
|
|
23
30
|
role: 'member',
|
|
@@ -39,10 +46,11 @@ function record(overrides = {}) {
|
|
|
39
46
|
function runStoreContract(makeStore, runner = {}) {
|
|
40
47
|
const describe = runner.describe || globalThis.describe;
|
|
41
48
|
const test = runner.test || globalThis.test;
|
|
42
|
-
const expect = runner.expect || globalThis.expect;
|
|
43
|
-
if (typeof describe !== 'function' || typeof test !== 'function'
|
|
44
|
-
throw new Error('runStoreContract needs describe
|
|
49
|
+
const expect = runner.expect || globalThis.expect || miniExpect;
|
|
50
|
+
if (typeof describe !== 'function' || typeof test !== 'function') {
|
|
51
|
+
throw new Error('runStoreContract needs describe and test (pass them, or run it inside jest).');
|
|
45
52
|
}
|
|
53
|
+
if (runner.newId) newId = runner.newId;
|
|
46
54
|
|
|
47
55
|
const A1 = { ownerId: 'owner-a', scope: 'scope-1' };
|
|
48
56
|
const A2 = { ownerId: 'owner-a', scope: 'scope-2' };
|
|
@@ -96,16 +104,32 @@ function runStoreContract(makeStore, runner = {}) {
|
|
|
96
104
|
expect((await store.list(A1, { limit: 2 })).map((row) => row.id)).toEqual([recent.id, mid.id]);
|
|
97
105
|
});
|
|
98
106
|
|
|
107
|
+
test('list with withVector: false leaves the vector out, and hasVector says whether there was one', async () => {
|
|
108
|
+
const store = await makeStore();
|
|
109
|
+
const printed = record({ vector: [0.5, 0.5], vectorSource: 'm1' });
|
|
110
|
+
const bare = record();
|
|
111
|
+
await store.insert(printed);
|
|
112
|
+
await store.insert(bare);
|
|
113
|
+
const light = await store.list(A1, { withVector: false });
|
|
114
|
+
expect(light.length).toBe(2);
|
|
115
|
+
const byId = Object.fromEntries(light.map((row) => [row.id, row]));
|
|
116
|
+
expect(byId[printed.id].vector === null || byId[printed.id].vector === undefined).toBe(true);
|
|
117
|
+
expect(byId[printed.id].hasVector).toBe(true);
|
|
118
|
+
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]);
|
|
120
|
+
});
|
|
121
|
+
|
|
99
122
|
test('update patches in place, never moves a record, and onlyActive refuses a superseded one', async () => {
|
|
100
123
|
const store = await makeStore();
|
|
101
124
|
const row = record();
|
|
102
125
|
await store.insert(row);
|
|
103
126
|
const updated = await store.update(A1, row.id, { importance: 5, ownerId: 'owner-b', scope: 'scope-2' });
|
|
104
127
|
expect(updated).toMatchObject({ id: row.id, importance: 5, ownerId: 'owner-a', scope: 'scope-1' });
|
|
105
|
-
expect(await store.update(A1, row.id, { supersededBy:
|
|
128
|
+
expect(await store.update(A1, row.id, { supersededBy: newId() }, { onlyActive: true })).not.toBeNull();
|
|
106
129
|
expect(await store.update(A1, row.id, { importance: 1 }, { onlyActive: true })).toBeNull();
|
|
107
130
|
expect((await store.get(A1, row.id)).importance).toBe(5);
|
|
108
|
-
expect(await store.update(A1,
|
|
131
|
+
expect(await store.update(A1, newId(), { importance: 1 })).toBeNull();
|
|
132
|
+
expect(await store.get(A1, 'not-an-id-at-all')).toBeNull();
|
|
109
133
|
});
|
|
110
134
|
|
|
111
135
|
test('remove and removeAll count what they erased, in their place only', async () => {
|
|
@@ -114,7 +138,7 @@ function runStoreContract(makeStore, runner = {}) {
|
|
|
114
138
|
const b = record();
|
|
115
139
|
const other = record({ scope: 'scope-2' });
|
|
116
140
|
for (const row of [a, b, other]) await store.insert(row);
|
|
117
|
-
expect(await store.remove(A1, [a.id,
|
|
141
|
+
expect(await store.remove(A1, [a.id, newId()])).toBe(1);
|
|
118
142
|
expect(await store.removeAll(A1)).toBe(1);
|
|
119
143
|
expect(await store.list(A1, { state: 'all' })).toEqual([]);
|
|
120
144
|
expect((await store.list(A2)).map((row) => row.id)).toEqual([other.id]);
|