@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 +21 -0
- package/README.md +239 -0
- package/package.json +39 -0
- package/src/consolidation.js +64 -0
- package/src/handlers.js +84 -0
- package/src/index.d.ts +398 -0
- package/src/index.js +10 -0
- package/src/memory.js +672 -0
- package/src/memoryStore.js +181 -0
- package/src/ranking.js +74 -0
- package/src/rules.js +153 -0
- package/src/testing/storeContract.js +194 -0
- package/src/tools.js +172 -0
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The reference store: in process, not persistent. Tests use it, and it is the
|
|
3
|
+
* executable description of the store contract — an adapter for a real
|
|
4
|
+
* database proves itself with runStoreContract() from ./testing.
|
|
5
|
+
*
|
|
6
|
+
* A place is `{ ownerId, scope }`. Nothing ever crosses from one place to
|
|
7
|
+
* another, except purgeOwner(), which is meant to: it erases an owner
|
|
8
|
+
* everywhere.
|
|
9
|
+
*/
|
|
10
|
+
const { cosine, keywordScore } = require('./ranking');
|
|
11
|
+
|
|
12
|
+
/* Deep copy that keeps Dates as Dates: what the caller holds never aliases the store. */
|
|
13
|
+
function copy(value) {
|
|
14
|
+
if (value instanceof Date) return new Date(value.getTime());
|
|
15
|
+
if (Array.isArray(value)) return value.map(copy);
|
|
16
|
+
if (value && typeof value === 'object') {
|
|
17
|
+
const out = {};
|
|
18
|
+
for (const [key, item] of Object.entries(value)) out[key] = copy(item);
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const keyOf = (where) => `${where.ownerId}\u0000${where.scope}`;
|
|
25
|
+
const time = (value) => (value ? new Date(value).getTime() : 0);
|
|
26
|
+
|
|
27
|
+
function matches(record, filter = {}) {
|
|
28
|
+
const state = filter.state || 'active';
|
|
29
|
+
if (state === 'active' && record.supersededBy) return false;
|
|
30
|
+
if (state === 'superseded' && !record.supersededBy) return false;
|
|
31
|
+
if (filter.supersededBy !== undefined && record.supersededBy !== filter.supersededBy) return false;
|
|
32
|
+
if (Array.isArray(filter.kinds) && !filter.kinds.includes(record.kind)) return false;
|
|
33
|
+
if (filter.channel !== undefined && (record.source || {}).channel !== filter.channel) return false;
|
|
34
|
+
if (filter.seen === false && record.seenAt) return false;
|
|
35
|
+
if (filter.seen === true && !record.seenAt) return false;
|
|
36
|
+
if (filter.createdAfter && time(record.createdAt) < time(filter.createdAfter)) return false;
|
|
37
|
+
if (filter.createdBefore && time(record.createdAt) > time(filter.createdBefore)) return false;
|
|
38
|
+
return true;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function createMemoryStore() {
|
|
42
|
+
const records = new Map();
|
|
43
|
+
const settings = new Map();
|
|
44
|
+
const refs = new Map();
|
|
45
|
+
|
|
46
|
+
const clone = (value) => (value === null || value === undefined ? null : copy(value));
|
|
47
|
+
const inPlace = (where, record) => record && record.ownerId === where.ownerId && record.scope === where.scope;
|
|
48
|
+
const newestFirst = (a, b) => time(b.createdAt) - time(a.createdAt);
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
async insert(record) {
|
|
52
|
+
if (!record || !record.id) throw new Error('insert requires a record with an id.');
|
|
53
|
+
if (records.has(record.id)) throw new Error(`A memory with id ${record.id} already exists.`);
|
|
54
|
+
records.set(record.id, clone(record));
|
|
55
|
+
return clone(record);
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
async get(where, id) {
|
|
59
|
+
const record = records.get(String(id));
|
|
60
|
+
return inPlace(where, record) ? clone(record) : null;
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
async list(where, filter = {}) {
|
|
64
|
+
const rows = [...records.values()]
|
|
65
|
+
.filter((record) => inPlace(where, record) && matches(record, filter))
|
|
66
|
+
.sort(newestFirst);
|
|
67
|
+
return (filter.limit ? rows.slice(0, filter.limit) : rows).map(clone);
|
|
68
|
+
},
|
|
69
|
+
|
|
70
|
+
async update(where, id, patch, options = {}) {
|
|
71
|
+
const record = records.get(String(id));
|
|
72
|
+
if (!inPlace(where, record)) return null;
|
|
73
|
+
if (options.onlyActive && record.supersededBy) return null;
|
|
74
|
+
const allowed = clone(patch || {});
|
|
75
|
+
/* A record never changes identity or place through an update. */
|
|
76
|
+
delete allowed.id;
|
|
77
|
+
delete allowed.ownerId;
|
|
78
|
+
delete allowed.scope;
|
|
79
|
+
Object.assign(record, allowed);
|
|
80
|
+
return clone(record);
|
|
81
|
+
},
|
|
82
|
+
|
|
83
|
+
async remove(where, ids) {
|
|
84
|
+
let removed = 0;
|
|
85
|
+
for (const id of ids || []) {
|
|
86
|
+
if (inPlace(where, records.get(String(id)))) {
|
|
87
|
+
records.delete(String(id));
|
|
88
|
+
removed += 1;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return removed;
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
async removeAll(where) {
|
|
95
|
+
let removed = 0;
|
|
96
|
+
for (const [id, record] of records) {
|
|
97
|
+
if (inPlace(where, record)) {
|
|
98
|
+
records.delete(id);
|
|
99
|
+
removed += 1;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return removed;
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
async purgeOwner(ownerId) {
|
|
106
|
+
const counts = { memories: 0, settings: 0, refs: 0 };
|
|
107
|
+
for (const [id, record] of records) {
|
|
108
|
+
if (record.ownerId === ownerId) { records.delete(id); counts.memories += 1; }
|
|
109
|
+
}
|
|
110
|
+
const prefix = `${ownerId}\u0000`;
|
|
111
|
+
for (const key of [...settings.keys()]) {
|
|
112
|
+
if (key.startsWith(prefix)) { settings.delete(key); counts.settings += 1; }
|
|
113
|
+
}
|
|
114
|
+
for (const key of [...refs.keys()]) {
|
|
115
|
+
if (key.startsWith(prefix)) { refs.delete(key); counts.refs += 1; }
|
|
116
|
+
}
|
|
117
|
+
return counts;
|
|
118
|
+
},
|
|
119
|
+
|
|
120
|
+
async getSettings(where) {
|
|
121
|
+
return { paused: false, ...(clone(settings.get(keyOf(where))) || {}) };
|
|
122
|
+
},
|
|
123
|
+
|
|
124
|
+
async setSettings(where, patch) {
|
|
125
|
+
const next = { paused: false, ...(settings.get(keyOf(where)) || {}), ...clone(patch) };
|
|
126
|
+
settings.set(keyOf(where), next);
|
|
127
|
+
return clone(next);
|
|
128
|
+
},
|
|
129
|
+
|
|
130
|
+
async claimRef(where, ref) {
|
|
131
|
+
const key = `${keyOf(where)}\u0000${ref}`;
|
|
132
|
+
if (refs.has(key)) return false;
|
|
133
|
+
refs.set(key, true);
|
|
134
|
+
return true;
|
|
135
|
+
},
|
|
136
|
+
|
|
137
|
+
async releaseRef(where, ref) {
|
|
138
|
+
refs.delete(`${keyOf(where)}\u0000${ref}`);
|
|
139
|
+
},
|
|
140
|
+
|
|
141
|
+
/*
|
|
142
|
+
* Optional in the contract: a database with a vector index answers this
|
|
143
|
+
* itself. Only vectors of the query's source are compared — two embedding
|
|
144
|
+
* models never share a space.
|
|
145
|
+
*/
|
|
146
|
+
async search(where, { text, vector, vectorSource, kinds, createdAfter, createdBefore, limit = 32 } = {}) {
|
|
147
|
+
const rows = [...records.values()].filter((record) => inPlace(where, record)
|
|
148
|
+
&& matches(record, { kinds, createdAfter, createdBefore }));
|
|
149
|
+
const semantic = Array.isArray(vector)
|
|
150
|
+
? rows.filter((record) => Array.isArray(record.vector) && record.vectorSource === vectorSource)
|
|
151
|
+
.map((record) => ({ record, score: cosine(vector, record.vector) }))
|
|
152
|
+
.sort((a, b) => b.score - a.score)
|
|
153
|
+
.slice(0, limit)
|
|
154
|
+
.map(({ record, score }) => ({ ...clone(record), score }))
|
|
155
|
+
: [];
|
|
156
|
+
const lexical = text
|
|
157
|
+
? rows.map((record) => ({ record, score: keywordScore(text, record.text) }))
|
|
158
|
+
.filter((row) => row.score > 0)
|
|
159
|
+
.sort((a, b) => b.score - a.score
|
|
160
|
+
|| time(b.record.lastUsedAt || b.record.createdAt) - time(a.record.lastUsedAt || a.record.createdAt))
|
|
161
|
+
.slice(0, limit)
|
|
162
|
+
.map(({ record, score }) => ({ ...clone(record), score }))
|
|
163
|
+
: [];
|
|
164
|
+
return { semantic, lexical };
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
/* Optional: active memories, every owner, with no vector or one from another source. */
|
|
168
|
+
async listNeedingVector({ limit = 50, source } = {}) {
|
|
169
|
+
return [...records.values()]
|
|
170
|
+
.filter((record) => !record.supersededBy
|
|
171
|
+
&& (!Array.isArray(record.vector) || !record.vector.length || (source !== undefined && record.vectorSource !== source)))
|
|
172
|
+
.sort((a, b) => (Array.isArray(a.vector) ? 1 : 0) - (Array.isArray(b.vector) ? 1 : 0) || time(a.createdAt) - time(b.createdAt))
|
|
173
|
+
.slice(0, limit)
|
|
174
|
+
.map(clone);
|
|
175
|
+
},
|
|
176
|
+
|
|
177
|
+
size: () => records.size
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
module.exports = { createMemoryStore };
|
package/src/ranking.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure ranking helpers: no store, no clock, no network.
|
|
3
|
+
*/
|
|
4
|
+
const { wordsOf } = require('./rules');
|
|
5
|
+
|
|
6
|
+
/* Vectors of different lengths are compared on their common part; a zero vector scores 0. */
|
|
7
|
+
function cosine(a, b) {
|
|
8
|
+
if (!Array.isArray(a) || !Array.isArray(b)) return 0;
|
|
9
|
+
let dot = 0;
|
|
10
|
+
let left = 0;
|
|
11
|
+
let right = 0;
|
|
12
|
+
const size = Math.min(a.length, b.length);
|
|
13
|
+
for (let i = 0; i < size; i += 1) {
|
|
14
|
+
dot += a[i] * b[i];
|
|
15
|
+
left += a[i] * a[i];
|
|
16
|
+
right += b[i] * b[i];
|
|
17
|
+
}
|
|
18
|
+
return left && right ? dot / Math.sqrt(left * right) : 0;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/* Share of the query's words (3 letters or more, accents folded) found in the text. */
|
|
22
|
+
function keywordScore(query, text) {
|
|
23
|
+
const extract = (value) => new Set(wordsOf(value).split(' ').filter((word) => word.length >= 3));
|
|
24
|
+
const asked = extract(query);
|
|
25
|
+
if (!asked.size) return 0;
|
|
26
|
+
const found = extract(text);
|
|
27
|
+
let shared = 0;
|
|
28
|
+
asked.forEach((word) => { if (found.has(word)) shared += 1; });
|
|
29
|
+
return shared / asked.size;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Reciprocal rank fusion: each list votes 1 / (k + rank). An id near the top
|
|
34
|
+
* of both lists beats one at the top of a single list.
|
|
35
|
+
*
|
|
36
|
+
* @param {string[][]} lists ranked ids, best first.
|
|
37
|
+
* @param {number} [k=60]
|
|
38
|
+
* @returns {string[]}
|
|
39
|
+
*/
|
|
40
|
+
function fuseByRank(lists, k = 60) {
|
|
41
|
+
const scores = new Map();
|
|
42
|
+
for (const list of Array.isArray(lists) ? lists : []) {
|
|
43
|
+
(list || []).forEach((id, index) => scores.set(id, (scores.get(id) || 0) + 1 / (k + index + 1)));
|
|
44
|
+
}
|
|
45
|
+
return [...scores].sort((a, b) => b[1] - a[1]).map(([id]) => id);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const time = (value) => (value ? new Date(value).getTime() : 0);
|
|
49
|
+
|
|
50
|
+
/**
|
|
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.
|
|
53
|
+
*/
|
|
54
|
+
function buildPortrait(memories, { maxLength = 1200, minImportance = 4, format = (memory) => `- ${memory.text}` } = {}) {
|
|
55
|
+
const rows = (memories || [])
|
|
56
|
+
.filter((memory) => Number(memory.importance) >= minImportance)
|
|
57
|
+
.sort((a, b) => time(b.lastUsedAt) - time(a.lastUsedAt)
|
|
58
|
+
|| b.importance - a.importance
|
|
59
|
+
|| time(b.createdAt) - time(a.createdAt));
|
|
60
|
+
let out = '';
|
|
61
|
+
for (const memory of rows) {
|
|
62
|
+
const line = format(memory);
|
|
63
|
+
if (out.length + (out ? 1 : 0) + line.length > maxLength) break;
|
|
64
|
+
out += (out ? '\n' : '') + line;
|
|
65
|
+
}
|
|
66
|
+
return out;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
cosine,
|
|
71
|
+
keywordScore,
|
|
72
|
+
fuseByRank,
|
|
73
|
+
buildPortrait
|
|
74
|
+
};
|
package/src/rules.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What may become a memory, and how loose model output is read.
|
|
3
|
+
*
|
|
4
|
+
* Every refusal is a code, never a sentence: the words shown to a person come
|
|
5
|
+
* from the consumer's own catalog. Content rules (health, secrets, whatever a
|
|
6
|
+
* product must never keep) are injected — this file only knows the structural
|
|
7
|
+
* ones: empty, too long, unknown kind, kind not allowed for a role, and the
|
|
8
|
+
* name of somebody else.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const REASONS = Object.freeze({
|
|
12
|
+
EMPTY: 'empty',
|
|
13
|
+
TOO_LONG: 'too_long',
|
|
14
|
+
INVALID_KIND: 'invalid_kind',
|
|
15
|
+
KIND_NOT_ALLOWED: 'kind_not_allowed',
|
|
16
|
+
OTHER_PERSON: 'other_person',
|
|
17
|
+
PAUSED: 'paused',
|
|
18
|
+
NOT_FOUND: 'not_found',
|
|
19
|
+
CONFLICT: 'conflict',
|
|
20
|
+
AI_DISABLED: 'ai_disabled'
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
/** Accents off, lower case: "José" and "JOSE" are the same name. */
|
|
24
|
+
function fold(value) {
|
|
25
|
+
return String(value ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLocaleLowerCase();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Letters and digits only, one space between words. */
|
|
29
|
+
function wordsOf(value) {
|
|
30
|
+
return fold(value).replace(/[^\p{L}\p{N}]+/gu, ' ').trim();
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/*
|
|
34
|
+
* A memory is plain words. Models write it with their Markdown (**bold**,
|
|
35
|
+
* `code`, a heading) — that is removed. A single underscore or hash is left
|
|
36
|
+
* alone: "C#" and "snake_case" are words too.
|
|
37
|
+
*/
|
|
38
|
+
function cleanText(value) {
|
|
39
|
+
if (typeof value !== 'string') return '';
|
|
40
|
+
return value
|
|
41
|
+
.replace(/\*+|`+|_{2,}/g, '')
|
|
42
|
+
.replace(/^\s*#+\s+/, '')
|
|
43
|
+
.replace(/\s+/g, ' ')
|
|
44
|
+
.trim();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/*
|
|
48
|
+
* Models answer with the kind in capitals, in another language, with an
|
|
49
|
+
* accent. The kind is folded and looked up in the kinds, then in the
|
|
50
|
+
* consumer's aliases. Unknown → `fallback` (null by default: refused).
|
|
51
|
+
*/
|
|
52
|
+
function normalizeKind(value, { kinds, aliases = {}, fallback = null } = {}) {
|
|
53
|
+
const key = fold(String(value ?? '').trim());
|
|
54
|
+
if (!key) return fallback;
|
|
55
|
+
const direct = (kinds || []).find((kind) => fold(kind) === key);
|
|
56
|
+
if (direct) return direct;
|
|
57
|
+
for (const [alias, kind] of Object.entries(aliases)) {
|
|
58
|
+
if (fold(alias) === key && (kinds || []).includes(kind)) return kind;
|
|
59
|
+
}
|
|
60
|
+
return fallback;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/* "4", 4.4 and 4 all mean 4; out of range is clamped; nonsense is the fallback. */
|
|
64
|
+
function normalizeImportance(value, fallback = 3) {
|
|
65
|
+
if (value === null || value === undefined || value === '') return fallback;
|
|
66
|
+
const number = Number(value);
|
|
67
|
+
return Number.isFinite(number) ? Math.min(5, Math.max(1, Math.round(number))) : fallback;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/*
|
|
71
|
+
* Whole words only: a registered "Paul" is not found inside "Pauline", and a
|
|
72
|
+
* name shorter than three letters never matches (too many false alarms).
|
|
73
|
+
*/
|
|
74
|
+
function mentionsName(text, name) {
|
|
75
|
+
const target = wordsOf(name);
|
|
76
|
+
if (target.length < 3) return false;
|
|
77
|
+
return ` ${wordsOf(text)} `.includes(` ${target} `);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* A content rule built from patterns. Each pattern is tested on the raw text
|
|
82
|
+
* AND on its folded form, so a pattern written without accents still matches
|
|
83
|
+
* "santé", and one written with them still matches.
|
|
84
|
+
*
|
|
85
|
+
* @param {object} options
|
|
86
|
+
* @param {string} options.code the refusal code returned.
|
|
87
|
+
* @param {RegExp[]} options.patterns
|
|
88
|
+
* @param {string[]} [options.roles] apply to these roles only.
|
|
89
|
+
* @param {string[]} [options.exceptRoles] never apply to these roles.
|
|
90
|
+
* @param {boolean} [options.allowWhenExplicit] the person asked for this
|
|
91
|
+
* exact thing to be remembered: let it through.
|
|
92
|
+
*/
|
|
93
|
+
function patternRule({ code, patterns, roles, exceptRoles, allowWhenExplicit = false } = {}) {
|
|
94
|
+
if (!code) throw new Error('patternRule requires a code.');
|
|
95
|
+
if (!Array.isArray(patterns) || !patterns.length) throw new Error('patternRule requires patterns.');
|
|
96
|
+
return function rule(candidate) {
|
|
97
|
+
if (roles && !roles.includes(candidate.role)) return null;
|
|
98
|
+
if (exceptRoles && exceptRoles.includes(candidate.role)) return null;
|
|
99
|
+
if (allowWhenExplicit && candidate.explicit) return null;
|
|
100
|
+
const raw = candidate.text;
|
|
101
|
+
const folded = fold(raw);
|
|
102
|
+
for (const pattern of patterns) {
|
|
103
|
+
pattern.lastIndex = 0;
|
|
104
|
+
if (pattern.test(raw)) return code;
|
|
105
|
+
pattern.lastIndex = 0;
|
|
106
|
+
if (pattern.test(folded)) return code;
|
|
107
|
+
}
|
|
108
|
+
return null;
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The full check, in order: structure, kind, the consumer's rules, then names.
|
|
114
|
+
* Returns a refusal code, or null when the memory may be kept.
|
|
115
|
+
*
|
|
116
|
+
* `alreadyPresent` is the text a memory carried before an edit: a name it
|
|
117
|
+
* already held was accepted with it and is not refused again. Only a name
|
|
118
|
+
* ADDED by the edit is.
|
|
119
|
+
*/
|
|
120
|
+
async function checkCandidate(candidate, config) {
|
|
121
|
+
const { text, kind, role } = candidate;
|
|
122
|
+
if (!text) return REASONS.EMPTY;
|
|
123
|
+
if (text.length > config.maxTextLength) return REASONS.TOO_LONG;
|
|
124
|
+
if (!kind || !config.kinds.includes(kind)) return REASONS.INVALID_KIND;
|
|
125
|
+
const allowed = role !== undefined && role !== null ? config.roleKinds[role] : undefined;
|
|
126
|
+
if (Array.isArray(allowed) && !allowed.includes(kind)) return REASONS.KIND_NOT_ALLOWED;
|
|
127
|
+
|
|
128
|
+
for (const rule of config.rules) {
|
|
129
|
+
const code = await rule(candidate);
|
|
130
|
+
if (code) return String(code);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const own = wordsOf(candidate.personName || '');
|
|
134
|
+
const before = candidate.alreadyPresent || '';
|
|
135
|
+
for (const name of candidate.names || []) {
|
|
136
|
+
if (own && wordsOf(name) === own) continue;
|
|
137
|
+
if (before && mentionsName(before, name)) continue;
|
|
138
|
+
if (mentionsName(text, name)) return REASONS.OTHER_PERSON;
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
module.exports = {
|
|
144
|
+
REASONS,
|
|
145
|
+
fold,
|
|
146
|
+
wordsOf,
|
|
147
|
+
cleanText,
|
|
148
|
+
normalizeKind,
|
|
149
|
+
normalizeImportance,
|
|
150
|
+
mentionsName,
|
|
151
|
+
patternRule,
|
|
152
|
+
checkCandidate
|
|
153
|
+
};
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The store contract, as a test suite. An adapter for a real database proves
|
|
3
|
+
* it behaves like the reference store:
|
|
4
|
+
*
|
|
5
|
+
* const { runStoreContract } = require('@astratra/memory');
|
|
6
|
+
* runStoreContract(async () => createPostgresMemoryStore(await freshPool()));
|
|
7
|
+
*
|
|
8
|
+
* It uses the test runner's describe/test/expect (jest or a compatible one);
|
|
9
|
+
* pass them explicitly when they are not globals. Optional methods (search,
|
|
10
|
+
* claimRef/releaseRef, listNeedingVector) are checked only when the store has
|
|
11
|
+
* them.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
let sequence = 0;
|
|
15
|
+
|
|
16
|
+
function record(overrides = {}) {
|
|
17
|
+
sequence += 1;
|
|
18
|
+
const at = overrides.createdAt || new Date(Date.UTC(2026, 0, 1, 0, 0, sequence));
|
|
19
|
+
return {
|
|
20
|
+
id: `contract-${sequence}-${Math.random().toString(36).slice(2, 8)}`,
|
|
21
|
+
ownerId: 'owner-a',
|
|
22
|
+
scope: 'scope-1',
|
|
23
|
+
role: 'member',
|
|
24
|
+
text: 'likes long walks',
|
|
25
|
+
kind: 'preference',
|
|
26
|
+
importance: 3,
|
|
27
|
+
source: { channel: 'auto' },
|
|
28
|
+
vector: null,
|
|
29
|
+
vectorSource: null,
|
|
30
|
+
supersededBy: null,
|
|
31
|
+
seenAt: null,
|
|
32
|
+
lastUsedAt: null,
|
|
33
|
+
createdAt: at,
|
|
34
|
+
updatedAt: at,
|
|
35
|
+
...overrides
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function runStoreContract(makeStore, runner = {}) {
|
|
40
|
+
const describe = runner.describe || globalThis.describe;
|
|
41
|
+
const test = runner.test || globalThis.test;
|
|
42
|
+
const expect = runner.expect || globalThis.expect;
|
|
43
|
+
if (typeof describe !== 'function' || typeof test !== 'function' || typeof expect !== 'function') {
|
|
44
|
+
throw new Error('runStoreContract needs describe, test and expect (pass them, or run it inside jest).');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const A1 = { ownerId: 'owner-a', scope: 'scope-1' };
|
|
48
|
+
const A2 = { ownerId: 'owner-a', scope: 'scope-2' };
|
|
49
|
+
const B1 = { ownerId: 'owner-b', scope: 'scope-1' };
|
|
50
|
+
const time = (value) => new Date(value).getTime();
|
|
51
|
+
|
|
52
|
+
describe('memory store contract', () => {
|
|
53
|
+
test('insert then get returns the same record, and returned objects are copies', async () => {
|
|
54
|
+
const store = await makeStore();
|
|
55
|
+
const row = record({ source: { channel: 'auto', ref: 'c1' }, vector: [0.1, 0.2], vectorSource: 'm1' });
|
|
56
|
+
await store.insert(row);
|
|
57
|
+
const got = await store.get(A1, row.id);
|
|
58
|
+
expect(got).toMatchObject({ id: row.id, ownerId: 'owner-a', scope: 'scope-1', text: row.text, kind: 'preference', importance: 3, supersededBy: null });
|
|
59
|
+
expect(got.source).toEqual({ channel: 'auto', ref: 'c1' });
|
|
60
|
+
expect(got.vector).toEqual([0.1, 0.2]);
|
|
61
|
+
expect(got.vectorSource).toBe('m1');
|
|
62
|
+
expect(time(got.createdAt)).toBe(time(row.createdAt));
|
|
63
|
+
got.text = 'changed outside';
|
|
64
|
+
expect((await store.get(A1, row.id)).text).toBe(row.text);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test('a record is invisible from another owner or another scope', async () => {
|
|
68
|
+
const store = await makeStore();
|
|
69
|
+
const row = record();
|
|
70
|
+
await store.insert(row);
|
|
71
|
+
expect(await store.get(B1, row.id)).toBeNull();
|
|
72
|
+
expect(await store.get(A2, row.id)).toBeNull();
|
|
73
|
+
expect(await store.list(B1)).toEqual([]);
|
|
74
|
+
expect(await store.list(A2)).toEqual([]);
|
|
75
|
+
expect(await store.update(B1, row.id, { text: 'stolen' })).toBeNull();
|
|
76
|
+
expect(await store.remove(B1, [row.id])).toBe(0);
|
|
77
|
+
expect(await store.removeAll(A2)).toBe(0);
|
|
78
|
+
expect((await store.get(A1, row.id)).text).toBe(row.text);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
test('list: active by default, newest first, with state, kinds, channel, seen, dates and limit filters', async () => {
|
|
82
|
+
const store = await makeStore();
|
|
83
|
+
const old = record({ createdAt: new Date('2026-01-01T00:00:00Z'), kind: 'goal' });
|
|
84
|
+
const mid = record({ createdAt: new Date('2026-02-01T00:00:00Z'), source: { channel: 'background' } });
|
|
85
|
+
const recent = record({ createdAt: new Date('2026-03-01T00:00:00Z'), source: { channel: 'background' }, seenAt: new Date('2026-03-02T00:00:00Z') });
|
|
86
|
+
const replaced = record({ createdAt: new Date('2026-04-01T00:00:00Z'), supersededBy: recent.id });
|
|
87
|
+
for (const row of [old, mid, recent, replaced]) await store.insert(row);
|
|
88
|
+
|
|
89
|
+
expect((await store.list(A1)).map((row) => row.id)).toEqual([recent.id, mid.id, old.id]);
|
|
90
|
+
expect((await store.list(A1, { state: 'superseded' })).map((row) => row.id)).toEqual([replaced.id]);
|
|
91
|
+
expect((await store.list(A1, { state: 'all' })).map((row) => row.id)).toEqual([replaced.id, recent.id, mid.id, old.id]);
|
|
92
|
+
expect((await store.list(A1, { state: 'superseded', supersededBy: recent.id })).map((row) => row.id)).toEqual([replaced.id]);
|
|
93
|
+
expect((await store.list(A1, { kinds: ['goal'] })).map((row) => row.id)).toEqual([old.id]);
|
|
94
|
+
expect((await store.list(A1, { channel: 'background', seen: false })).map((row) => row.id)).toEqual([mid.id]);
|
|
95
|
+
expect((await store.list(A1, { createdAfter: new Date('2026-01-15T00:00:00Z'), createdBefore: new Date('2026-02-15T00:00:00Z') })).map((row) => row.id)).toEqual([mid.id]);
|
|
96
|
+
expect((await store.list(A1, { limit: 2 })).map((row) => row.id)).toEqual([recent.id, mid.id]);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
test('update patches in place, never moves a record, and onlyActive refuses a superseded one', async () => {
|
|
100
|
+
const store = await makeStore();
|
|
101
|
+
const row = record();
|
|
102
|
+
await store.insert(row);
|
|
103
|
+
const updated = await store.update(A1, row.id, { importance: 5, ownerId: 'owner-b', scope: 'scope-2' });
|
|
104
|
+
expect(updated).toMatchObject({ id: row.id, importance: 5, ownerId: 'owner-a', scope: 'scope-1' });
|
|
105
|
+
expect(await store.update(A1, row.id, { supersededBy: 'next' }, { onlyActive: true })).not.toBeNull();
|
|
106
|
+
expect(await store.update(A1, row.id, { importance: 1 }, { onlyActive: true })).toBeNull();
|
|
107
|
+
expect((await store.get(A1, row.id)).importance).toBe(5);
|
|
108
|
+
expect(await store.update(A1, 'missing-id', { importance: 1 })).toBeNull();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('remove and removeAll count what they erased, in their place only', async () => {
|
|
112
|
+
const store = await makeStore();
|
|
113
|
+
const a = record();
|
|
114
|
+
const b = record();
|
|
115
|
+
const other = record({ scope: 'scope-2' });
|
|
116
|
+
for (const row of [a, b, other]) await store.insert(row);
|
|
117
|
+
expect(await store.remove(A1, [a.id, 'missing-id'])).toBe(1);
|
|
118
|
+
expect(await store.removeAll(A1)).toBe(1);
|
|
119
|
+
expect(await store.list(A1, { state: 'all' })).toEqual([]);
|
|
120
|
+
expect((await store.list(A2)).map((row) => row.id)).toEqual([other.id]);
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
test('purgeOwner erases one owner in every scope, settings included, and nobody else', async () => {
|
|
124
|
+
const store = await makeStore();
|
|
125
|
+
const mine = [record(), record({ scope: 'scope-2' })];
|
|
126
|
+
const theirs = record({ ownerId: 'owner-b' });
|
|
127
|
+
for (const row of [...mine, theirs]) await store.insert(row);
|
|
128
|
+
await store.setSettings(A1, { paused: true });
|
|
129
|
+
await store.setSettings(B1, { paused: true });
|
|
130
|
+
const counts = await store.purgeOwner('owner-a');
|
|
131
|
+
expect(counts.memories).toBe(2);
|
|
132
|
+
expect(counts.settings).toBeGreaterThanOrEqual(1);
|
|
133
|
+
expect(await store.list(A1, { state: 'all' })).toEqual([]);
|
|
134
|
+
expect(await store.list(A2, { state: 'all' })).toEqual([]);
|
|
135
|
+
expect((await store.getSettings(A1)).paused).toBe(false);
|
|
136
|
+
expect((await store.list(B1)).map((row) => row.id)).toEqual([theirs.id]);
|
|
137
|
+
expect((await store.getSettings(B1)).paused).toBe(true);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test('settings default to not paused and belong to one place', async () => {
|
|
141
|
+
const store = await makeStore();
|
|
142
|
+
expect((await store.getSettings(A1)).paused).toBe(false);
|
|
143
|
+
expect((await store.setSettings(A1, { paused: true })).paused).toBe(true);
|
|
144
|
+
expect((await store.getSettings(A1)).paused).toBe(true);
|
|
145
|
+
expect((await store.getSettings(A2)).paused).toBe(false);
|
|
146
|
+
expect((await store.getSettings(B1)).paused).toBe(false);
|
|
147
|
+
expect((await store.setSettings(A1, { paused: false })).paused).toBe(false);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('claimRef (optional) claims once per place; releaseRef frees it', async () => {
|
|
151
|
+
const store = await makeStore();
|
|
152
|
+
if (typeof store.claimRef !== 'function') return;
|
|
153
|
+
expect(await store.claimRef(A1, 'conversation-1')).toBe(true);
|
|
154
|
+
expect(await store.claimRef(A1, 'conversation-1')).toBe(false);
|
|
155
|
+
expect(await store.claimRef(B1, 'conversation-1')).toBe(true);
|
|
156
|
+
if (typeof store.releaseRef === 'function') {
|
|
157
|
+
await store.releaseRef(A1, 'conversation-1');
|
|
158
|
+
expect(await store.claimRef(A1, 'conversation-1')).toBe(true);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
test('search (optional) stays in its place, skips superseded records and compares one vector source only', async () => {
|
|
163
|
+
const store = await makeStore();
|
|
164
|
+
if (typeof store.search !== 'function') return;
|
|
165
|
+
const near = record({ text: 'plays the violin every evening', vector: [1, 0], vectorSource: 'm1' });
|
|
166
|
+
const otherSource = record({ text: 'unrelated', vector: [1, 0], vectorSource: 'm2' });
|
|
167
|
+
const replaced = record({ text: 'plays the violin badly', vector: [1, 0], vectorSource: 'm1', supersededBy: near.id });
|
|
168
|
+
const stranger = record({ ownerId: 'owner-b', text: 'plays the violin too', vector: [1, 0], vectorSource: 'm1' });
|
|
169
|
+
for (const row of [near, otherSource, replaced, stranger]) await store.insert(row);
|
|
170
|
+
const found = await store.search(A1, { text: 'violin evening', vector: [1, 0], vectorSource: 'm1', limit: 10 });
|
|
171
|
+
expect(found.semantic.map((row) => row.id)).toEqual([near.id]);
|
|
172
|
+
expect(found.lexical.map((row) => row.id)).toEqual([near.id]);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
test('listNeedingVector (optional) returns active records without a vector, or from another source', async () => {
|
|
176
|
+
const store = await makeStore();
|
|
177
|
+
if (typeof store.listNeedingVector !== 'function') return;
|
|
178
|
+
const missing = record({ ownerId: 'owner-z' });
|
|
179
|
+
const other = record({ ownerId: 'owner-z', vector: [1], vectorSource: 'old' });
|
|
180
|
+
const fine = record({ ownerId: 'owner-z', vector: [1], vectorSource: 'new' });
|
|
181
|
+
const replaced = record({ ownerId: 'owner-z', supersededBy: fine.id });
|
|
182
|
+
for (const row of [missing, other, fine, replaced]) await store.insert(row);
|
|
183
|
+
const ids = (await store.listNeedingVector({ limit: 50, source: 'new' })).map((row) => row.id);
|
|
184
|
+
expect(ids).toEqual(expect.arrayContaining([missing.id, other.id]));
|
|
185
|
+
expect(ids).not.toContain(fine.id);
|
|
186
|
+
expect(ids).not.toContain(replaced.id);
|
|
187
|
+
const withoutSource = (await store.listNeedingVector({ limit: 50 })).map((row) => row.id);
|
|
188
|
+
expect(withoutSource).toContain(missing.id);
|
|
189
|
+
expect(withoutSource).not.toContain(other.id);
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
module.exports = { runStoreContract, contractRecord: record };
|