mnemocyte 0.5.0 → 0.5.1
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 +68 -177
- package/dist/embedders/index.mjs +1 -2
- package/dist/embedders/openai.d.mts +3 -8
- package/dist/embedders/openai.mjs +3 -4
- package/dist/embedders/openai.mjs.map +1 -1
- package/dist/{errors-DIPysVWl.mjs → errors-Dgt2nAs1.mjs} +2 -3
- package/dist/{errors-DIPysVWl.mjs.map → errors-Dgt2nAs1.mjs.map} +1 -1
- package/dist/index.d.mts +5 -11
- package/dist/index.mjs +947 -12
- package/dist/index.mjs.map +1 -1
- package/dist/{postgres-BHQ1pj16.mjs → postgres-BDti0rrm.mjs} +14 -23
- package/dist/{postgres-BHQ1pj16.mjs.map → postgres-BDti0rrm.mjs.map} +1 -1
- package/dist/{postgres-runtime-DxJxns07.mjs → postgres-runtime-51fQVwqa.mjs} +3 -4
- package/dist/{postgres-runtime-DxJxns07.mjs.map → postgres-runtime-51fQVwqa.mjs.map} +1 -1
- package/dist/store-config-BZ4J1hrM.mjs +304 -0
- package/dist/store-config-BZ4J1hrM.mjs.map +1 -0
- package/dist/stores/drizzle.d.mts +2 -7
- package/dist/stores/drizzle.mjs +3 -4
- package/dist/{types-XUWYDoXM.d.mts → types-DXYtLiOT.d.mts} +3 -4
- package/migrations/fresh-install.sql +43 -0
- package/package.json +23 -20
- package/dist/embedders/openai.d.mts.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/store-config-BFFTm1sj.mjs +0 -1255
- package/dist/store-config-BFFTm1sj.mjs.map +0 -1
- package/dist/stores/drizzle.d.mts.map +0 -1
- package/dist/types-XUWYDoXM.d.mts.map +0 -1
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
import { t as MnemocyteError } from "./errors-Dgt2nAs1.mjs";
|
|
2
|
+
// src/database-url.ts
|
|
3
|
+
function parsePostgresDatabaseUrl(databaseUrl) {
|
|
4
|
+
let url;
|
|
5
|
+
try {
|
|
6
|
+
url = new URL(databaseUrl);
|
|
7
|
+
} catch (error) {
|
|
8
|
+
throw new MnemocyteError("databaseUrl must be a valid Postgres connection URL.", "CONFIG", error);
|
|
9
|
+
}
|
|
10
|
+
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") throw new MnemocyteError("databaseUrl must use the postgres: or postgresql: protocol.", "CONFIG");
|
|
11
|
+
return url;
|
|
12
|
+
}
|
|
13
|
+
// src/resilience.ts
|
|
14
|
+
/**
|
|
15
|
+
* Default per-provider-call timeout. Disabled by default so that callers
|
|
16
|
+
* who do not configure {@link ProviderResilienceConfig.timeoutMs} are
|
|
17
|
+
* unaffected.
|
|
18
|
+
*/
|
|
19
|
+
const DEFAULT_TIMEOUT_MS = 0;
|
|
20
|
+
/** Default number of retry attempts on transient provider failures. */
|
|
21
|
+
const DEFAULT_RETRIES = 0;
|
|
22
|
+
/** Default base backoff delay used between retry attempts. */
|
|
23
|
+
const DEFAULT_BASE_DELAY_MS = 100;
|
|
24
|
+
/** Default ceiling for retry backoff delay. */
|
|
25
|
+
const DEFAULT_MAX_DELAY_MS = 2e3;
|
|
26
|
+
/**
|
|
27
|
+
* Throw a {@link MnemocyteError} with code `"ABORTED"` if `signal` is
|
|
28
|
+
* already aborted. Safe to call with `undefined`.
|
|
29
|
+
*/
|
|
30
|
+
function throwIfAborted(signal) {
|
|
31
|
+
if (signal?.aborted) throw new MnemocyteError("Operation was aborted.", "ABORTED", signal.reason);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Heuristic default for whether an error should be retried.
|
|
35
|
+
*
|
|
36
|
+
* Conservative by design: only retries on common transient failure
|
|
37
|
+
* indicators (network errors, 5xx-ish messages, `ECONN*` etc.). Never
|
|
38
|
+
* retries on validation, configuration, or {@link MnemocyteError} of
|
|
39
|
+
* code `"VALIDATION"` / `"CONFIG"` / `"CONFLICT"` / `"ABORTED"`.
|
|
40
|
+
*/
|
|
41
|
+
function defaultShouldRetry(error) {
|
|
42
|
+
if (error instanceof MnemocyteError) {
|
|
43
|
+
if (error.code === "VALIDATION" || error.code === "CONFIG" || error.code === "CONFLICT" || error.code === "ABORTED") return false;
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
46
|
+
if (typeof error === "object" && error !== null && "status" in error && typeof error.status === "number" && [
|
|
47
|
+
429,
|
|
48
|
+
500,
|
|
49
|
+
502,
|
|
50
|
+
503,
|
|
51
|
+
504
|
|
52
|
+
].includes(error.status)) return true;
|
|
53
|
+
if (error instanceof Error) {
|
|
54
|
+
const message = error.message.toLowerCase();
|
|
55
|
+
if (message.includes("econn") || message.includes("etimedout") || message.includes("network") || message.includes("timeout") || message.includes("temporarily") || message.includes("rate limit") || message.includes("503") || message.includes("502") || message.includes("504") || message.includes("500")) return true;
|
|
56
|
+
}
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Compute the backoff delay for the given retry attempt, using exponential
|
|
61
|
+
* growth capped at {@link ProviderResilienceConfig.maxDelayMs}.
|
|
62
|
+
*
|
|
63
|
+
* `attempt` is 1-indexed: the delay before the first retry uses
|
|
64
|
+
* `attempt = 1`, before the second retry `attempt = 2`, etc.
|
|
65
|
+
*/
|
|
66
|
+
function computeDelayMs(attempt, baseDelayMs, maxDelayMs) {
|
|
67
|
+
const exponential = baseDelayMs * 2 ** (attempt - 1);
|
|
68
|
+
return Math.max(0, Math.min(maxDelayMs, exponential));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Promise-based `setTimeout` that rejects with an `"ABORTED"`
|
|
72
|
+
* {@link MnemocyteError} if `signal` aborts while waiting.
|
|
73
|
+
*/
|
|
74
|
+
function delay(ms, signal) {
|
|
75
|
+
if (ms <= 0) {
|
|
76
|
+
throwIfAborted(signal);
|
|
77
|
+
return Promise.resolve();
|
|
78
|
+
}
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
const timer = setTimeout(() => {
|
|
81
|
+
signal?.removeEventListener("abort", onAbort);
|
|
82
|
+
resolve();
|
|
83
|
+
}, ms);
|
|
84
|
+
const onAbort = () => {
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal?.reason));
|
|
87
|
+
};
|
|
88
|
+
if (signal) {
|
|
89
|
+
if (signal.aborted) {
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal.reason));
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
function timeoutError(timeoutMs) {
|
|
99
|
+
return new MnemocyteError(`Provider call timed out after ${timeoutMs}ms.`, "TIMEOUT");
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Run one provider attempt with a signal linked to the caller's signal and
|
|
103
|
+
* Mnemocyte's configured timeout. Timeout aborts are actively propagated to
|
|
104
|
+
* providers that honor `AbortSignal`.
|
|
105
|
+
*/
|
|
106
|
+
function runAttempt(action, timeoutMs, signal) {
|
|
107
|
+
if (timeoutMs <= 0 && !signal) return action(void 0);
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
let settled = false;
|
|
110
|
+
const controller = new AbortController();
|
|
111
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
112
|
+
if (settled) return;
|
|
113
|
+
settled = true;
|
|
114
|
+
signal?.removeEventListener("abort", onAbort);
|
|
115
|
+
controller.abort(timeoutError(timeoutMs));
|
|
116
|
+
reject(timeoutError(timeoutMs));
|
|
117
|
+
}, timeoutMs) : void 0;
|
|
118
|
+
const onAbort = () => {
|
|
119
|
+
if (settled) return;
|
|
120
|
+
settled = true;
|
|
121
|
+
if (timer) clearTimeout(timer);
|
|
122
|
+
controller.abort(signal?.reason);
|
|
123
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal?.reason));
|
|
124
|
+
};
|
|
125
|
+
if (signal) {
|
|
126
|
+
if (signal.aborted) {
|
|
127
|
+
if (timer) clearTimeout(timer);
|
|
128
|
+
settled = true;
|
|
129
|
+
controller.abort(signal.reason);
|
|
130
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal.reason));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
134
|
+
}
|
|
135
|
+
action(controller.signal).then((value) => {
|
|
136
|
+
if (settled) return;
|
|
137
|
+
settled = true;
|
|
138
|
+
if (timer) clearTimeout(timer);
|
|
139
|
+
signal?.removeEventListener("abort", onAbort);
|
|
140
|
+
resolve(value);
|
|
141
|
+
}, (error) => {
|
|
142
|
+
if (settled) return;
|
|
143
|
+
settled = true;
|
|
144
|
+
if (timer) clearTimeout(timer);
|
|
145
|
+
signal?.removeEventListener("abort", onAbort);
|
|
146
|
+
reject(error);
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Run `action` with timeout, retry, and abort handling derived from
|
|
152
|
+
* `options.resilience` and `options.signal`. Each retry attempt receives
|
|
153
|
+
* a fresh `AbortSignal` linked to the caller's signal — so callers may
|
|
154
|
+
* abort mid-retry and the in-flight attempt will cancel promptly if the
|
|
155
|
+
* underlying provider honours signals.
|
|
156
|
+
*
|
|
157
|
+
* Errors from {@link MnemocyteError} with code `"VALIDATION"` /
|
|
158
|
+
* `"CONFIG"` / `"CONFLICT"` / `"ABORTED"` are never retried.
|
|
159
|
+
*/
|
|
160
|
+
async function withResilience(action, options = {}) {
|
|
161
|
+
const config = options.resilience ?? {};
|
|
162
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
163
|
+
const retries = Math.max(0, config.retries ?? DEFAULT_RETRIES);
|
|
164
|
+
const baseDelayMs = Math.max(0, config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);
|
|
165
|
+
const maxDelayMs = Math.max(baseDelayMs, config.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);
|
|
166
|
+
const shouldRetry = config.shouldRetry ?? defaultShouldRetry;
|
|
167
|
+
const externalSignal = options.signal;
|
|
168
|
+
throwIfAborted(externalSignal);
|
|
169
|
+
const maxAttempts = retries + 1;
|
|
170
|
+
let lastError;
|
|
171
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
172
|
+
throwIfAborted(externalSignal);
|
|
173
|
+
try {
|
|
174
|
+
return await runAttempt(action, timeoutMs, externalSignal);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
lastError = error;
|
|
177
|
+
if (error instanceof MnemocyteError && error.code === "ABORTED") throw error;
|
|
178
|
+
if (attempt >= maxAttempts) throw error;
|
|
179
|
+
if (!shouldRetry(error, attempt)) throw error;
|
|
180
|
+
await delay(computeDelayMs(attempt, baseDelayMs, maxDelayMs), externalSignal);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
throw lastError;
|
|
184
|
+
}
|
|
185
|
+
// src/memory/json.ts
|
|
186
|
+
function invalidJsonValue(path, cause) {
|
|
187
|
+
return new MnemocyteError(`${path} must contain only JSON-compatible value data.`, "VALIDATION", cause);
|
|
188
|
+
}
|
|
189
|
+
function cloneJsonValue(value, path, ancestors) {
|
|
190
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
191
|
+
if (typeof value === "number") {
|
|
192
|
+
if (!Number.isFinite(value)) throw invalidJsonValue(path);
|
|
193
|
+
return Object.is(value, -0) ? 0 : value;
|
|
194
|
+
}
|
|
195
|
+
if (typeof value !== "object") throw invalidJsonValue(path);
|
|
196
|
+
if (ancestors.has(value)) throw invalidJsonValue(path);
|
|
197
|
+
ancestors.add(value);
|
|
198
|
+
try {
|
|
199
|
+
if (Array.isArray(value)) {
|
|
200
|
+
if (Object.getOwnPropertySymbols(value).length > 0 || Object.keys(value).some((key) => !/^(0|[1-9]\d*)$/.test(key))) throw invalidJsonValue(path);
|
|
201
|
+
return Array.from({ length: value.length }, (_, index) => {
|
|
202
|
+
if (!Object.hasOwn(value, index)) throw invalidJsonValue(`${path}[${index}]`);
|
|
203
|
+
return cloneJsonValue(value[index], `${path}[${index}]`, ancestors);
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const prototype = Object.getPrototypeOf(value);
|
|
207
|
+
if (prototype !== Object.prototype && prototype !== null) throw invalidJsonValue(path);
|
|
208
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
209
|
+
const entries = [];
|
|
210
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
211
|
+
if (typeof key !== "string") throw invalidJsonValue(path);
|
|
212
|
+
const descriptor = descriptors[key];
|
|
213
|
+
if (descriptor === void 0 || descriptor.enumerable !== true || !("value" in descriptor)) throw invalidJsonValue(`${path}.${key}`);
|
|
214
|
+
entries.push([key, cloneJsonValue(descriptor.value, `${path}.${key}`, ancestors)]);
|
|
215
|
+
}
|
|
216
|
+
return Object.fromEntries(entries);
|
|
217
|
+
} finally {
|
|
218
|
+
ancestors.delete(value);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
/** Validate and deep-clone a JSON-compatible object. */
|
|
222
|
+
function cloneJsonObject(value, path = "metadata") {
|
|
223
|
+
try {
|
|
224
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw invalidJsonValue(path);
|
|
225
|
+
return cloneJsonValue(value, path, /* @__PURE__ */ new Set());
|
|
226
|
+
} catch (error) {
|
|
227
|
+
if (error instanceof MnemocyteError) throw error;
|
|
228
|
+
throw invalidJsonValue(path, error);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// src/memory/records.ts
|
|
232
|
+
function normalizeTags(tags) {
|
|
233
|
+
if (!tags) return [];
|
|
234
|
+
return [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];
|
|
235
|
+
}
|
|
236
|
+
function createId() {
|
|
237
|
+
return `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
238
|
+
}
|
|
239
|
+
/** Generate a unique audit-event id (`evt_*`). */
|
|
240
|
+
function createEventId() {
|
|
241
|
+
return `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
242
|
+
}
|
|
243
|
+
function cloneMemory(memory) {
|
|
244
|
+
return {
|
|
245
|
+
id: memory.id,
|
|
246
|
+
entityId: memory.entityId,
|
|
247
|
+
content: memory.content,
|
|
248
|
+
type: memory.type,
|
|
249
|
+
importance: memory.importance,
|
|
250
|
+
tags: [...memory.tags],
|
|
251
|
+
source: memory.source,
|
|
252
|
+
metadata: cloneJsonObject(memory.metadata),
|
|
253
|
+
confidence: memory.confidence,
|
|
254
|
+
embeddingModel: memory.embeddingModel,
|
|
255
|
+
embeddingDimensions: memory.embeddingDimensions,
|
|
256
|
+
supersededBy: memory.supersededBy,
|
|
257
|
+
supersededAt: memory.supersededAt ? new Date(memory.supersededAt) : null,
|
|
258
|
+
expiresAt: memory.expiresAt ? new Date(memory.expiresAt) : null,
|
|
259
|
+
lastAccessedAt: memory.lastAccessedAt ? new Date(memory.lastAccessedAt) : null,
|
|
260
|
+
accessCount: memory.accessCount,
|
|
261
|
+
createdAt: new Date(memory.createdAt),
|
|
262
|
+
updatedAt: new Date(memory.updatedAt)
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
// src/memory/defaults.ts
|
|
266
|
+
const DEFAULT_TYPE = "fact";
|
|
267
|
+
const DEFAULT_IMPORTANCE = "normal";
|
|
268
|
+
/**
|
|
269
|
+
* Ordering of {@link ImportanceLevel} from least to most important. Used
|
|
270
|
+
* by `prune({ maxImportance })` to compare a memory's importance against
|
|
271
|
+
* the caller-supplied ceiling.
|
|
272
|
+
*/
|
|
273
|
+
const IMPORTANCE_RANK = {
|
|
274
|
+
low: 0,
|
|
275
|
+
normal: 1,
|
|
276
|
+
high: 2,
|
|
277
|
+
critical: 3
|
|
278
|
+
};
|
|
279
|
+
/** Default cosine-similarity threshold for {@link FindDuplicatesInput}. */
|
|
280
|
+
const DEFAULT_DUPLICATE_THRESHOLD = .95;
|
|
281
|
+
// src/memory/store.ts
|
|
282
|
+
function hasPruneSelector(filter) {
|
|
283
|
+
return filter.entityId !== void 0 || filter.expired === true || filter.superseded === true || filter.createdBefore !== void 0 || filter.notAccessedSince !== void 0 || filter.types !== void 0 && filter.types.length > 0 || filter.tags !== void 0 && filter.tags.length > 0 || filter.maxImportance !== void 0;
|
|
284
|
+
}
|
|
285
|
+
function assertPruneFilterHasSelector(filter) {
|
|
286
|
+
if (!hasPruneSelector(filter)) throw new MnemocyteError("prune requires at least one selector (entityId, expired, superseded, createdBefore, notAccessedSince, types, tags, or maxImportance).", "VALIDATION");
|
|
287
|
+
}
|
|
288
|
+
// src/memory/deletion.ts
|
|
289
|
+
function memoryHasDependentsError(cause) {
|
|
290
|
+
return new MnemocyteError("Memory cannot be deleted while other memories reference it as their consolidation survivor.", "CONFLICT", cause);
|
|
291
|
+
}
|
|
292
|
+
// src/memory/store-config.ts
|
|
293
|
+
const MEMORY_STORE_CONFIG = Symbol.for("mnemocyte.memory-store-config");
|
|
294
|
+
function createMnemocyteStoreConfig(store) {
|
|
295
|
+
return Object.freeze({ [MEMORY_STORE_CONFIG]: store });
|
|
296
|
+
}
|
|
297
|
+
function unwrapMnemocyteStoreConfig(config) {
|
|
298
|
+
const candidate = config;
|
|
299
|
+
if (typeof candidate !== "object" || candidate === null || !(MEMORY_STORE_CONFIG in candidate)) throw new MnemocyteError("store must be created by a supported Mnemocyte store adapter.", "CONFIG");
|
|
300
|
+
return candidate[MEMORY_STORE_CONFIG];
|
|
301
|
+
}
|
|
302
|
+
export { DEFAULT_DUPLICATE_THRESHOLD as a, IMPORTANCE_RANK as c, createId as d, normalizeTags as f, parsePostgresDatabaseUrl as g, withResilience as h, assertPruneFilterHasSelector as i, cloneMemory as l, throwIfAborted as m, unwrapMnemocyteStoreConfig as n, DEFAULT_IMPORTANCE as o, cloneJsonObject as p, memoryHasDependentsError as r, DEFAULT_TYPE as s, createMnemocyteStoreConfig as t, createEventId as u };
|
|
303
|
+
|
|
304
|
+
//# sourceMappingURL=store-config-BZ4J1hrM.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-config-BZ4J1hrM.mjs","names":[],"sources":["../src/database-url.ts","../src/resilience.ts","../src/memory/json.ts","../src/memory/records.ts","../src/memory/defaults.ts","../src/memory/store.ts","../src/memory/deletion.ts","../src/memory/store-config.ts"],"sourcesContent":["import { MnemocyteError } from \"./errors.js\";\n\nexport function parsePostgresDatabaseUrl(databaseUrl: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(databaseUrl);\n\t} catch (error) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl must be a valid Postgres connection URL.\",\n\t\t\t\"CONFIG\",\n\t\t\terror,\n\t\t);\n\t}\n\tif (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl must use the postgres: or postgresql: protocol.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\treturn url;\n}\n","import { MnemocyteError } from \"./errors.js\";\nimport type { ProviderResilienceConfig } from \"./types.js\";\n\n/**\n * Default per-provider-call timeout. Disabled by default so that callers\n * who do not configure {@link ProviderResilienceConfig.timeoutMs} are\n * unaffected.\n */\nconst DEFAULT_TIMEOUT_MS = 0;\n/** Default number of retry attempts on transient provider failures. */\nconst DEFAULT_RETRIES = 0;\n/** Default base backoff delay used between retry attempts. */\nconst DEFAULT_BASE_DELAY_MS = 100;\n/** Default ceiling for retry backoff delay. */\nconst DEFAULT_MAX_DELAY_MS = 2000;\n\n/**\n * Throw a {@link MnemocyteError} with code `\"ABORTED\"` if `signal` is\n * already aborted. Safe to call with `undefined`.\n */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Operation was aborted.\",\n\t\t\t\"ABORTED\",\n\t\t\tsignal.reason,\n\t\t);\n\t}\n}\n\n/**\n * Heuristic default for whether an error should be retried.\n *\n * Conservative by design: only retries on common transient failure\n * indicators (network errors, 5xx-ish messages, `ECONN*` etc.). Never\n * retries on validation, configuration, or {@link MnemocyteError} of\n * code `\"VALIDATION\"` / `\"CONFIG\"` / `\"CONFLICT\"` / `\"ABORTED\"`.\n */\nexport function defaultShouldRetry(error: unknown): boolean {\n\tif (error instanceof MnemocyteError) {\n\t\tif (\n\t\t\terror.code === \"VALIDATION\" ||\n\t\t\terror.code === \"CONFIG\" ||\n\t\t\terror.code === \"CONFLICT\" ||\n\t\t\terror.code === \"ABORTED\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"status\" in error &&\n\t\ttypeof (error as { status?: unknown }).status === \"number\" &&\n\t\t[429, 500, 502, 503, 504].includes((error as { status: number }).status)\n\t) {\n\t\treturn true;\n\t}\n\tif (error instanceof Error) {\n\t\tconst message = error.message.toLowerCase();\n\t\tif (\n\t\t\tmessage.includes(\"econn\") ||\n\t\t\tmessage.includes(\"etimedout\") ||\n\t\t\tmessage.includes(\"network\") ||\n\t\t\tmessage.includes(\"timeout\") ||\n\t\t\tmessage.includes(\"temporarily\") ||\n\t\t\tmessage.includes(\"rate limit\") ||\n\t\t\tmessage.includes(\"503\") ||\n\t\t\tmessage.includes(\"502\") ||\n\t\t\tmessage.includes(\"504\") ||\n\t\t\tmessage.includes(\"500\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Compute the backoff delay for the given retry attempt, using exponential\n * growth capped at {@link ProviderResilienceConfig.maxDelayMs}.\n *\n * `attempt` is 1-indexed: the delay before the first retry uses\n * `attempt = 1`, before the second retry `attempt = 2`, etc.\n */\nfunction computeDelayMs(\n\tattempt: number,\n\tbaseDelayMs: number,\n\tmaxDelayMs: number,\n): number {\n\tconst exponential = baseDelayMs * 2 ** (attempt - 1);\n\treturn Math.max(0, Math.min(maxDelayMs, exponential));\n}\n\n/**\n * Promise-based `setTimeout` that rejects with an `\"ABORTED\"`\n * {@link MnemocyteError} if `signal` aborts while waiting.\n */\nfunction delay(ms: number, signal: AbortSignal | undefined): Promise<void> {\n\tif (ms <= 0) {\n\t\tthrowIfAborted(signal);\n\t\treturn Promise.resolve();\n\t}\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(\n\t\t\t\tnew MnemocyteError(\"Operation was aborted.\", \"ABORTED\", signal?.reason),\n\t\t\t);\n\t\t};\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(\n\t\t\t\t\tnew MnemocyteError(\n\t\t\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t\tsignal.reason,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t});\n}\n\nfunction timeoutError(timeoutMs: number): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t`Provider call timed out after ${timeoutMs}ms.`,\n\t\t\"TIMEOUT\",\n\t);\n}\n\n/**\n * Run one provider attempt with a signal linked to the caller's signal and\n * Mnemocyte's configured timeout. Timeout aborts are actively propagated to\n * providers that honor `AbortSignal`.\n */\nfunction runAttempt<T>(\n\taction: (signal: AbortSignal | undefined) => Promise<T>,\n\ttimeoutMs: number,\n\tsignal: AbortSignal | undefined,\n): Promise<T> {\n\tif (timeoutMs <= 0 && !signal) {\n\t\treturn action(undefined);\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst controller = new AbortController();\n\t\tconst timer =\n\t\t\ttimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\tif (settled) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tcontroller.abort(timeoutError(timeoutMs));\n\t\t\t\t\t\treject(timeoutError(timeoutMs));\n\t\t\t\t\t}, timeoutMs)\n\t\t\t\t: undefined;\n\t\tconst onAbort = (): void => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\tcontroller.abort(signal?.reason);\n\t\t\treject(\n\t\t\t\tnew MnemocyteError(\"Operation was aborted.\", \"ABORTED\", signal?.reason),\n\t\t\t);\n\t\t};\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcontroller.abort(signal.reason);\n\t\t\t\treject(\n\t\t\t\t\tnew MnemocyteError(\n\t\t\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t\tsignal.reason,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t\taction(controller.signal).then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Options accepted by {@link withResilience}.\n */\nexport interface ResilienceCallOptions {\n\t/** External cancellation signal forwarded to each attempt. */\n\tsignal?: AbortSignal;\n\t/** Provider-level retry/timeout configuration. */\n\tresilience?: ProviderResilienceConfig;\n}\n\n/**\n * Run `action` with timeout, retry, and abort handling derived from\n * `options.resilience` and `options.signal`. Each retry attempt receives\n * a fresh `AbortSignal` linked to the caller's signal — so callers may\n * abort mid-retry and the in-flight attempt will cancel promptly if the\n * underlying provider honours signals.\n *\n * Errors from {@link MnemocyteError} with code `\"VALIDATION\"` /\n * `\"CONFIG\"` / `\"CONFLICT\"` / `\"ABORTED\"` are never retried.\n */\nexport async function withResilience<T>(\n\taction: (signal: AbortSignal | undefined) => Promise<T>,\n\toptions: ResilienceCallOptions = {},\n): Promise<T> {\n\tconst config = options.resilience ?? {};\n\tconst timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\tconst retries = Math.max(0, config.retries ?? DEFAULT_RETRIES);\n\tconst baseDelayMs = Math.max(0, config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n\tconst maxDelayMs = Math.max(\n\t\tbaseDelayMs,\n\t\tconfig.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,\n\t);\n\tconst shouldRetry = config.shouldRetry ?? defaultShouldRetry;\n\tconst externalSignal = options.signal;\n\n\tthrowIfAborted(externalSignal);\n\n\tconst maxAttempts = retries + 1;\n\tlet lastError: unknown;\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n\t\tthrowIfAborted(externalSignal);\n\t\ttry {\n\t\t\treturn await runAttempt(action, timeoutMs, externalSignal);\n\t\t} catch (error) {\n\t\t\tlastError = error;\n\t\t\tif (error instanceof MnemocyteError && error.code === \"ABORTED\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (attempt >= maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (!shouldRetry(error, attempt)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst waitMs = computeDelayMs(attempt, baseDelayMs, maxDelayMs);\n\t\t\tawait delay(waitMs, externalSignal);\n\t\t}\n\t}\n\tthrow lastError;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport type { JsonObject, JsonValue } from \"../types.js\";\n\ndeclare const ownedJsonObject: unique symbol;\n\n/** Internal marker for a JSON object that Mnemocyte has validated and cloned. */\nexport type OwnedJsonObject = JsonObject & {\n\treadonly [ownedJsonObject]: true;\n};\n\nfunction invalidJsonValue(path: string, cause?: unknown): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t`${path} must contain only JSON-compatible value data.`,\n\t\t\"VALIDATION\",\n\t\tcause,\n\t);\n}\n\nfunction cloneJsonValue(\n\tvalue: unknown,\n\tpath: string,\n\tancestors: Set<object>,\n): JsonValue {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\"\n\t) {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\treturn Object.is(value, -0) ? 0 : value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow invalidJsonValue(path);\n\t}\n\tif (ancestors.has(value)) {\n\t\tthrow invalidJsonValue(path);\n\t}\n\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (\n\t\t\t\tObject.getOwnPropertySymbols(value).length > 0 ||\n\t\t\t\tObject.keys(value).some((key) => !/^(0|[1-9]\\d*)$/.test(key))\n\t\t\t) {\n\t\t\t\tthrow invalidJsonValue(path);\n\t\t\t}\n\t\t\treturn Array.from({ length: value.length }, (_, index) => {\n\t\t\t\tif (!Object.hasOwn(value, index)) {\n\t\t\t\t\tthrow invalidJsonValue(`${path}[${index}]`);\n\t\t\t\t}\n\t\t\t\treturn cloneJsonValue(value[index], `${path}[${index}]`, ancestors);\n\t\t\t});\n\t\t}\n\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(value);\n\t\tconst entries: Array<[string, JsonValue]> = [];\n\t\tfor (const key of Reflect.ownKeys(descriptors)) {\n\t\t\tif (typeof key !== \"string\") {\n\t\t\t\tthrow invalidJsonValue(path);\n\t\t\t}\n\t\t\tconst descriptor = descriptors[key];\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t!(\"value\" in descriptor)\n\t\t\t) {\n\t\t\t\tthrow invalidJsonValue(`${path}.${key}`);\n\t\t\t}\n\t\t\tentries.push([\n\t\t\t\tkey,\n\t\t\t\tcloneJsonValue(descriptor.value, `${path}.${key}`, ancestors),\n\t\t\t]);\n\t\t}\n\t\treturn Object.fromEntries(entries);\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\n/** Validate and deep-clone a JSON-compatible object. */\nexport function cloneJsonObject(\n\tvalue: unknown,\n\tpath = \"metadata\",\n): OwnedJsonObject {\n\ttry {\n\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\treturn cloneJsonValue(value, path, new Set()) as OwnedJsonObject;\n\t} catch (error) {\n\t\tif (error instanceof MnemocyteError) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow invalidJsonValue(path, error);\n\t}\n}\n","import type { Memory } from \"../types.js\";\nimport { cloneJsonObject } from \"./json.js\";\n\nexport interface StoredMemory extends Memory {\n\tembedding: number[];\n}\n\nexport function normalizeTags(tags: readonly string[] | undefined): string[] {\n\tif (!tags) {\n\t\treturn [];\n\t}\n\treturn [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];\n}\n\nexport function createId(): string {\n\treturn `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Generate a unique audit-event id (`evt_*`). */\nexport function createEventId(): string {\n\treturn `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport function cloneMemory(memory: Memory): Memory {\n\treturn {\n\t\tid: memory.id,\n\t\tentityId: memory.entityId,\n\t\tcontent: memory.content,\n\t\ttype: memory.type,\n\t\timportance: memory.importance,\n\t\ttags: [...memory.tags],\n\t\tsource: memory.source,\n\t\tmetadata: cloneJsonObject(memory.metadata),\n\t\tconfidence: memory.confidence,\n\t\tembeddingModel: memory.embeddingModel,\n\t\tembeddingDimensions: memory.embeddingDimensions,\n\t\tsupersededBy: memory.supersededBy,\n\t\tsupersededAt: memory.supersededAt ? new Date(memory.supersededAt) : null,\n\t\texpiresAt: memory.expiresAt ? new Date(memory.expiresAt) : null,\n\t\tlastAccessedAt: memory.lastAccessedAt\n\t\t\t? new Date(memory.lastAccessedAt)\n\t\t\t: null,\n\t\taccessCount: memory.accessCount,\n\t\tcreatedAt: new Date(memory.createdAt),\n\t\tupdatedAt: new Date(memory.updatedAt),\n\t};\n}\n","import type {\n\tFindDuplicatesInput,\n\tImportanceLevel,\n\tMemoryType,\n} from \"../types.js\";\n\nexport const DEFAULT_LIMIT = 10;\nexport const DEFAULT_MIN_SCORE = 0;\nexport const DEFAULT_TYPE: MemoryType = \"fact\";\nexport const DEFAULT_IMPORTANCE: ImportanceLevel = \"normal\";\n\n/**\n * Ordering of {@link ImportanceLevel} from least to most important. Used\n * by `prune({ maxImportance })` to compare a memory's importance against\n * the caller-supplied ceiling.\n */\nexport const IMPORTANCE_RANK: Record<ImportanceLevel, number> = {\n\tlow: 0,\n\tnormal: 1,\n\thigh: 2,\n\tcritical: 3,\n};\n\n/** Default cosine-similarity threshold for {@link FindDuplicatesInput}. */\nexport const DEFAULT_DUPLICATE_THRESHOLD = 0.95;\n/** Default cap on the number of duplicate pairs returned. */\nexport const DEFAULT_DUPLICATE_LIMIT = 100;\n/** Default cap on audit-log entries returned per `listAuditLog`. */\nexport const DEFAULT_AUDIT_LOG_LIMIT = 50;\n","import { MnemocyteError } from \"../errors.js\";\nimport type {\n\tAuditEvent,\n\tEmbedder,\n\tEntityStats,\n\tFindDuplicatesInput,\n\tGlobalStats,\n\tImportanceLevel,\n\tListAuditLogInput,\n\tMemory,\n\tMemoryType,\n\tMnemocyteBackend,\n\tPruneResult,\n\tRecallInput,\n} from \"../types.js\";\nimport type { StoredMemory } from \"./records.js\";\n\nexport interface StoreVectorSearchInput extends Omit<RecallInput, \"minScore\"> {\n\tembedding: readonly number[];\n\tlimit: number;\n\tminVectorScore?: number;\n}\n\nexport interface StoreLexicalSearchInput extends RecallInput {\n\tlimit: number;\n}\n\nexport interface StoreVectorCandidate {\n\tmemory: Memory;\n\t/** Finite cosine component clamped to the inclusive range `[0, 1]`. */\n\tvectorScore: number;\n}\n\nexport interface StoreLexicalCandidate {\n\tmemory: Memory;\n\tlexicalScore: number;\n}\n\nexport interface StoreDuplicatePair {\n\ta: Memory;\n\tb: Memory;\n\tsimilarity: number;\n}\n\nexport interface StoreAccessUpdate {\n\tid: string;\n\tlastAccessedAt: Date;\n\taccessCount: number;\n\tupdatedAt: Date;\n}\n\nexport interface StorePruneEntityDeletion {\n\tentityId: string;\n\tdeletedCount: number;\n}\n\nexport interface StorePruneResult extends PruneResult {\n\tdeletedByEntity: readonly StorePruneEntityDeletion[];\n}\n\nexport interface StoreConsolidationTarget {\n\tid: string;\n\ttags: readonly string[];\n\tsupersededBy: string | null;\n}\n\nexport interface StoreConsolidateInput {\n\tentityId: string;\n\tsurvivorId: string;\n\tsupersededIds: readonly string[];\n\tmergeTags: boolean;\n\tnow: Date;\n\tauditEnabled: boolean;\n}\n\nexport interface StoreConsolidateResult {\n\tsupersededIds: readonly string[];\n}\n\nexport interface StoreOperationOptions {\n\tsignal?: AbortSignal;\n}\n\nexport interface ValidatedPruneFilter {\n\treadonly entityId?: string;\n\treadonly expired?: true;\n\treadonly superseded?: true;\n\treadonly createdBefore?: Date;\n\treadonly notAccessedSince?: Date;\n\treadonly types?: readonly MemoryType[];\n\treadonly tags?: readonly string[];\n\treadonly maxImportance?: ImportanceLevel;\n\treadonly dryRun: boolean;\n}\n\nexport function hasPruneSelector(filter: ValidatedPruneFilter): boolean {\n\treturn (\n\t\tfilter.entityId !== undefined ||\n\t\tfilter.expired === true ||\n\t\tfilter.superseded === true ||\n\t\tfilter.createdBefore !== undefined ||\n\t\tfilter.notAccessedSince !== undefined ||\n\t\t(filter.types !== undefined && filter.types.length > 0) ||\n\t\t(filter.tags !== undefined && filter.tags.length > 0) ||\n\t\tfilter.maxImportance !== undefined\n\t);\n}\n\nexport function assertPruneFilterHasSelector(\n\tfilter: ValidatedPruneFilter,\n): void {\n\tif (!hasPruneSelector(filter)) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"prune requires at least one selector (entityId, expired, superseded, createdBefore, notAccessedSince, types, tags, or maxImportance).\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\n/**\n * Internal storage adapter boundary used by the shared client orchestration.\n *\n * This is intentionally not exported from the public package root in 0.3.x.\n * The public adapter surface is reserved for the later `drizzleStore(db)` line.\n *\n * Every method is unconditional. There is intentionally no capability-flag\n * surface, and adapters do not declare capabilities before shared orchestration\n * calls a method.\n *\n * Deleting a referenced consolidation survivor through `deleteMemory`,\n * `deleteMemoriesForEntity`, or a non-dry-run `prune` must reject with\n * `\"CONFLICT\"` before deleting anything. The dependency check and mutation must\n * be one atomic, non-interleavable operation; a check followed by a later write\n * with an interleaving gap does not satisfy the contract.\n *\n * Unless a method documents a stronger boundary, cancellation support and its\n * mechanism are implementation-defined. Adapters may use cooperative checks,\n * active statement cancellation, or no mid-operation cancellation while still\n * honoring the method's documented postconditions.\n */\nexport interface MemoryStore {\n\treadonly backend: MnemocyteBackend;\n\n\t/**\n\t * Completes the adapter's base-schema readiness hook.\n\t *\n\t * The built-in stores currently resolve without work and rely on explicit\n\t * schema management. An implementation may verify externally managed schema\n\t * state here, but this hook does not authorize hidden schema creation or\n\t * migration.\n\t */\n\tensureSchema(): Promise<void>;\n\t/**\n\t * Enforces the embedding compatibility check meaningful to this store's\n\t * persistence model before embedding-dependent work proceeds.\n\t *\n\t * The hook is unconditional and needs no capability flag. A store with no\n\t * persistent installation state may legitimately resolve without work. The\n\t * built-in Postgres store validates installation model and dimensions and may\n\t * reject with `\"MIGRATION\"` or `\"CONFIG\"`; the in-memory store is a no-op.\n\t */\n\tensureEmbeddingCompatibility(embedder: Embedder): Promise<void>;\n\n\t/**\n\t * Takes ownership of freshly prepared rows and returns exactly one detached\n\t * public record for every prepared input ID. Callers must not mutate or reuse\n\t * rows after passing them here.\n\t *\n\t * The store has no return-order obligation. Shared orchestration treats order\n\t * as untrusted, rejects missing or duplicate results and any returned ID\n\t * outside the prepared set, then restores prepared-input order.\n\t */\n\tinsertMemories(memories: readonly StoredMemory[]): Promise<Memory[]>;\n\t/**\n\t * Returns up to `input.limit` detached candidates that satisfy the shared\n\t * recall filters and `minVectorScore`, ordered by decreasing vector\n\t * similarity. Every `vectorScore` is finite and clamped to `[0, 1]`.\n\t *\n\t * An implementation may scan or use an index. When an approximate index is\n\t * available, candidate inclusion, ranking, and performance are index- and\n\t * planner-dependent and are not guaranteed to match an exhaustive scan.\n\t */\n\tvectorSearch(input: StoreVectorSearchInput): Promise<StoreVectorCandidate[]>;\n\t/**\n\t * Returns up to `input.limit` detached candidates that satisfy the shared\n\t * recall filters and have a positive implementation-defined lexical score,\n\t * ordered by decreasing score.\n\t *\n\t * Lexical parsing and relevance scoring are backend-defined. Implementations\n\t * may therefore differ in mechanism, returned candidates, and ranking, not\n\t * only in latency.\n\t */\n\tlexicalSearch(\n\t\tinput: StoreLexicalSearchInput,\n\t): Promise<StoreLexicalCandidate[]>;\n\t/**\n\t * Returns available embeddings for the requested IDs, keyed by memory ID.\n\t * Missing memories and memories without an embedding are omitted. Returned\n\t * vectors are detached from stored state, and input or map iteration order is\n\t * not part of the contract.\n\t */\n\tgetMemoryEmbeddings(\n\t\tmemoryIds: readonly string[],\n\t): Promise<Map<string, number[]>>;\n\t/**\n\t * Increments access state exactly once for each requested stored memory and\n\t * returns one record per ID containing its post-update `accessCount`,\n\t * `lastAccessedAt`, and `updatedAt`. Return order is untrusted and normalized\n\t * by shared orchestration.\n\t *\n\t * The input IDs must be distinct. Duplicate-ID behavior is backend-specific,\n\t * and callers must not rely on any particular deduplication or increment\n\t * behavior when this precondition is violated.\n\t */\n\tmarkMemoriesAccessed(\n\t\tmemoryIds: readonly string[],\n\t): Promise<StoreAccessUpdate[]>;\n\n\t/**\n\t * Deletes the memory only when both entity and memory ID match, returning\n\t * `false` when they do not and `true` after deletion.\n\t *\n\t * If any memory references the target through `supersededBy`, rejects with\n\t * `\"CONFLICT\"` without deleting it. Dependency detection and deletion must be\n\t * atomic and non-interleavable.\n\t */\n\tdeleteMemory(entityId: string, memoryId: string): Promise<boolean>;\n\t/**\n\t * Deletes every memory for the entity and returns the number deleted.\n\t *\n\t * If any memory references a selected target through `supersededBy`, rejects\n\t * the entire operation with `\"CONFLICT\"` before deleting anything, including\n\t * when the dependent is itself selected. Dependency detection and the batch\n\t * deletion must be atomic and non-interleavable.\n\t */\n\tdeleteMemoriesForEntity(entityId: string): Promise<number>;\n\tprune(\n\t\tinput: ValidatedPruneFilter,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StorePruneResult>;\n\t/**\n\t * Compares qualifying memories pairwise and returns up to the requested limit\n\t * of unordered pairs meeting the similarity threshold, ordered by decreasing\n\t * similarity. Similarities are clamped to `[0, 1]`; pair orientation and\n\t * equal-score order are not guaranteed.\n\t *\n\t * This contract neither implies nor requires indexed nearest-neighbor pair\n\t * generation. A database planner may still use ordinary indexes while\n\t * filtering or executing a pairwise join.\n\t */\n\tfindDuplicatePairs(\n\t\tinput: FindDuplicatesInput,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StoreDuplicatePair[]>;\n\n\t/**\n\t * Persists independent copies of audit events supplied by shared core.\n\t *\n\t * Ordinary audit writes are best-effort at the shared caller. Rejection does\n\t * not promise batch atomicity: failure behavior is implementation-defined,\n\t * and some stores may retain a partial batch after the promise rejects.\n\t */\n\taddAuditEvents(events: readonly AuditEvent[]): Promise<void>;\n\t/**\n\t * Returns detached events for the requested entity in strict descending\n\t * `(timestamp, id)` order, subject to the requested limit.\n\t *\n\t * Event IDs must be stable and timestamps comparable. Plain `before` and\n\t * `after` values are strict timestamp filters. Composite cursors use strict\n\t * tuple filtering on the same `(timestamp, id)` tuple used for ordering, so\n\t * equal-timestamp events can be paged without requiring a transaction.\n\t * Cancellation may be cooperative or active and is implementation-defined.\n\t */\n\tlistAuditLog(\n\t\tinput: ListAuditLogInput,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<AuditEvent[]>;\n\n\t/**\n\t * Returns a detached memory only when both entity and memory ID match;\n\t * otherwise returns `null`.\n\t */\n\tgetMemory(\n\t\tentityId: string,\n\t\tmemoryId: string,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<Memory | null>;\n\t/** Shared validation supplies distinct IDs before this preflight lookup. */\n\tloadConsolidationTargets(\n\t\tentityId: string,\n\t\tids: readonly string[],\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StoreConsolidationTarget[]>;\n\t/**\n\t * Applies one atomic consolidation after re-reading and protecting the\n\t * survivor and requested losers. Throws `\"CONFLICT\"` before mutation when\n\t * the survivor is missing or superseded, or when any requested loser points\n\t * to a different survivor. Tag merging starts from the protected survivor's\n\t * mutation-time tags.\n\t */\n\tconsolidate(\n\t\tinput: StoreConsolidateInput,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StoreConsolidateResult>;\n\n\t/**\n\t * Returns entity-scoped or global counts evaluated against the supplied\n\t * `now`. `memoryCount` includes every selected memory; active memories are\n\t * neither expired nor superseded. Expired and superseded counts are\n\t * independent and may overlap. Global `entityCount` counts distinct entities\n\t * across all stored memories, and an empty scope returns zero counts.\n\t */\n\tstats(\n\t\tinput: { entityId?: string } | undefined,\n\t\tnow: Date,\n\t): Promise<EntityStats | GlobalStats>;\n\t/**\n\t * Releases only resources and transient state owned by this store instance.\n\t *\n\t * The in-memory store destroys its owned memory and audit state. The built-in\n\t * Postgres store closes the connection handle it created while leaving\n\t * persisted rows intact. An adapter wrapping a caller-supplied connection must\n\t * not close that connection or any other resource it does not own.\n\t */\n\tclose(): Promise<void>;\n}\n","import { MnemocyteError } from \"../errors.js\";\n\nexport function memoryHasDependentsError(cause?: unknown): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t\"Memory cannot be deleted while other memories reference it as their consolidation survivor.\",\n\t\t\"CONFLICT\",\n\t\tcause,\n\t);\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport type { MnemocyteStoreConfig } from \"../types.js\";\nimport type { MemoryStore } from \"./store.js\";\n\nconst MEMORY_STORE_CONFIG = Symbol.for(\"mnemocyte.memory-store-config\");\n\ninterface MemoryStoreConfigEnvelope {\n\treadonly [MEMORY_STORE_CONFIG]: MemoryStore;\n}\n\nexport function createMnemocyteStoreConfig(\n\tstore: MemoryStore,\n): MnemocyteStoreConfig {\n\treturn Object.freeze({\n\t\t[MEMORY_STORE_CONFIG]: store,\n\t}) as unknown as MnemocyteStoreConfig;\n}\n\nexport function unwrapMnemocyteStoreConfig(\n\tconfig: MnemocyteStoreConfig,\n): MemoryStore {\n\tconst candidate: unknown = config;\n\tif (\n\t\ttypeof candidate !== \"object\" ||\n\t\tcandidate === null ||\n\t\t!(MEMORY_STORE_CONFIG in candidate)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"store must be created by a supported Mnemocyte store adapter.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\n\treturn (candidate as MemoryStoreConfigEnvelope)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,YACrB,cAAc,QACd,EAAE,uBAAuB,YAEzB,MAAM,IAAI,eACT,iEACA,QACD;CAGD,OAAQ,UAAwC;AACjD"}
|
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import { D as MnemocyteStoreConfig } from "../types-
|
|
1
|
+
import { D as MnemocyteStoreConfig } from "../types-DXYtLiOT.mjs";
|
|
2
2
|
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
3
|
-
|
|
4
|
-
//#region src/stores/drizzle.d.ts
|
|
5
3
|
/**
|
|
6
4
|
* Wrap a caller-owned postgres.js Drizzle instance for
|
|
7
5
|
* {@link MnemocyteConfig.store}.
|
|
@@ -12,7 +10,4 @@ import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
|
12
10
|
*
|
|
13
11
|
* @param db - A Drizzle instance created with `drizzle-orm/postgres-js`.
|
|
14
12
|
*/
|
|
15
|
-
declare function drizzleStore<TSchema extends Record<string, unknown>>(db: PostgresJsDatabase<TSchema>): MnemocyteStoreConfig;
|
|
16
|
-
//#endregion
|
|
17
|
-
export { drizzleStore };
|
|
18
|
-
//# sourceMappingURL=drizzle.d.mts.map
|
|
13
|
+
export declare function drizzleStore<TSchema extends Record<string, unknown>>(db: PostgresJsDatabase<TSchema>): MnemocyteStoreConfig;
|
package/dist/stores/drizzle.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as createCallerOwnedDatabaseHandle, t as createPostgresStore } from "../postgres-
|
|
2
|
-
import { t as createMnemocyteStoreConfig } from "../store-config-
|
|
3
|
-
|
|
1
|
+
import { n as createCallerOwnedDatabaseHandle, t as createPostgresStore } from "../postgres-BDti0rrm.mjs";
|
|
2
|
+
import { t as createMnemocyteStoreConfig } from "../store-config-BZ4J1hrM.mjs";
|
|
3
|
+
// src/stores/drizzle.ts
|
|
4
4
|
/**
|
|
5
5
|
* Wrap a caller-owned postgres.js Drizzle instance for
|
|
6
6
|
* {@link MnemocyteConfig.store}.
|
|
@@ -14,7 +14,6 @@ import { t as createMnemocyteStoreConfig } from "../store-config-BFFTm1sj.mjs";
|
|
|
14
14
|
function drizzleStore(db) {
|
|
15
15
|
return createMnemocyteStoreConfig(createPostgresStore(createCallerOwnedDatabaseHandle(db)));
|
|
16
16
|
}
|
|
17
|
-
//#endregion
|
|
18
17
|
export { drizzleStore };
|
|
19
18
|
|
|
20
19
|
//# sourceMappingURL=drizzle.mjs.map
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
//#region src/types.d.ts
|
|
2
1
|
/**
|
|
3
2
|
* Discriminator describing what kind of memory a {@link Memory} represents.
|
|
4
3
|
*
|
|
@@ -177,7 +176,9 @@ interface MnemocyteConfig {
|
|
|
177
176
|
embedder: Embedder;
|
|
178
177
|
/** Default values applied to {@link RecallInput} when properties are omitted. */
|
|
179
178
|
defaults?: {
|
|
180
|
-
/** Default `limit` for {@link MnemocyteClient.recall}. */
|
|
179
|
+
/** Default `limit` for {@link MnemocyteClient.recall}. */
|
|
180
|
+
limit?: number;
|
|
181
|
+
/** Default `minScore` cutoff for {@link MnemocyteClient.recall}. */
|
|
181
182
|
minScore?: number;
|
|
182
183
|
};
|
|
183
184
|
/** Retrieval-ranking tuning. See {@link RetrievalConfig}. */
|
|
@@ -977,6 +978,4 @@ interface ExperimentalMnemocyteClient {
|
|
|
977
978
|
*/
|
|
978
979
|
consolidate(input: ConsolidateInput): Promise<ConsolidateResult>;
|
|
979
980
|
}
|
|
980
|
-
//#endregion
|
|
981
981
|
export { PruneInput as A, MnemocyteConfig as C, MnemocyteStoreConfig as D, MnemocyteOperation as E, RetrievalConfig as F, RetrievalExplanation as I, RetrievalScoreWeights as L, RecallInput as M, RememberInput as N, ObservabilityConfig as O, RememberManyInput as P, RetrievalScores as R, MnemocyteClient as S, MnemocyteObservationPhase as T, ListAuditLogInput as _, ConsolidateInput as a, MemoryWithScore as b, DuplicatePair as c, ExperimentalMnemocyteClient as d, FindDuplicatesInput as f, JsonValue as g, JsonObject as h, BuildContextInput as i, PruneResult as j, ProviderResilienceConfig as k, Embedder as l, ImportanceLevel as m, AuditEvent as n, ConsolidateResult as o, GlobalStats as p, AuditLogCursor as r, ContextFormat as s, AuditConfig as t, EntityStats as u, Memory as v, MnemocyteObservation as w, MnemocyteBackend as x, MemoryType as y, TokenCounter as z };
|
|
982
|
-
//# sourceMappingURL=types-XUWYDoXM.d.mts.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
CREATE TABLE "mnemocyte_events" (
|
|
2
|
+
"id" text PRIMARY KEY NOT NULL,
|
|
3
|
+
"entity_id" text NOT NULL,
|
|
4
|
+
"description" text NOT NULL,
|
|
5
|
+
"metadata" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
|
6
|
+
"timestamp" timestamp with time zone DEFAULT now() NOT NULL
|
|
7
|
+
);
|
|
8
|
+
--> statement-breakpoint
|
|
9
|
+
CREATE TABLE "mnemocyte_meta" (
|
|
10
|
+
"key" text PRIMARY KEY NOT NULL,
|
|
11
|
+
"embedding_dimensions" integer NOT NULL,
|
|
12
|
+
"embedding_model" text
|
|
13
|
+
);
|
|
14
|
+
--> statement-breakpoint
|
|
15
|
+
INSERT INTO "mnemocyte_meta" ("key", "embedding_dimensions") VALUES ('installation', 1536);
|
|
16
|
+
--> statement-breakpoint
|
|
17
|
+
CREATE TABLE "mnemocyte_memories" (
|
|
18
|
+
"id" text PRIMARY KEY NOT NULL,
|
|
19
|
+
"entity_id" text NOT NULL,
|
|
20
|
+
"content" text NOT NULL,
|
|
21
|
+
"type" text DEFAULT 'fact' NOT NULL,
|
|
22
|
+
"importance" text DEFAULT 'normal' NOT NULL,
|
|
23
|
+
"tags" text[] DEFAULT '{}'::text[] NOT NULL,
|
|
24
|
+
"source" text,
|
|
25
|
+
"metadata" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
|
26
|
+
"confidence" real DEFAULT 1 NOT NULL,
|
|
27
|
+
"embedding" vector(1536),
|
|
28
|
+
"embedding_model" text NOT NULL,
|
|
29
|
+
"embedding_dimensions" integer NOT NULL,
|
|
30
|
+
"superseded_by" text,
|
|
31
|
+
"superseded_at" timestamp with time zone,
|
|
32
|
+
"expires_at" timestamp with time zone,
|
|
33
|
+
"last_accessed_at" timestamp with time zone,
|
|
34
|
+
"access_count" integer DEFAULT 0 NOT NULL,
|
|
35
|
+
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
|
36
|
+
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
|
37
|
+
);
|
|
38
|
+
--> statement-breakpoint
|
|
39
|
+
ALTER TABLE "mnemocyte_memories" ADD CONSTRAINT "mnemocyte_memories_superseded_by_mnemocyte_memories_id_fk" FOREIGN KEY ("superseded_by") REFERENCES "public"."mnemocyte_memories"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
|
40
|
+
CREATE INDEX "mnemocyte_events_entity_time_idx" ON "mnemocyte_events" USING btree ("entity_id","timestamp");--> statement-breakpoint
|
|
41
|
+
CREATE INDEX "mnemocyte_memories_entity_idx" ON "mnemocyte_memories" USING btree ("entity_id");--> statement-breakpoint
|
|
42
|
+
CREATE INDEX "mnemocyte_memories_entity_type_idx" ON "mnemocyte_memories" USING btree ("entity_id","type");--> statement-breakpoint
|
|
43
|
+
CREATE INDEX "mnemocyte_memories_embedding_hnsw_idx" ON "mnemocyte_memories" USING hnsw ("embedding" vector_cosine_ops);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mnemocyte",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "Persistent memory for TypeScript AI apps.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -11,26 +11,25 @@
|
|
|
11
11
|
"exports": {
|
|
12
12
|
".": {
|
|
13
13
|
"types": "./dist/index.d.mts",
|
|
14
|
-
"
|
|
14
|
+
"default": "./dist/index.mjs"
|
|
15
15
|
},
|
|
16
16
|
"./embedders": {
|
|
17
17
|
"types": "./dist/embedders/index.d.mts",
|
|
18
|
-
"
|
|
18
|
+
"default": "./dist/embedders/index.mjs"
|
|
19
19
|
},
|
|
20
|
-
"./embedders/
|
|
21
|
-
|
|
22
|
-
"
|
|
23
|
-
"import": "./dist/embedders/*.mjs"
|
|
20
|
+
"./embedders/openai": {
|
|
21
|
+
"types": "./dist/embedders/openai.d.mts",
|
|
22
|
+
"default": "./dist/embedders/openai.mjs"
|
|
24
23
|
},
|
|
25
|
-
"./stores
|
|
26
|
-
"types": "./dist/stores
|
|
27
|
-
"
|
|
24
|
+
"./stores/drizzle": {
|
|
25
|
+
"types": "./dist/stores/drizzle.d.mts",
|
|
26
|
+
"default": "./dist/stores/drizzle.mjs"
|
|
28
27
|
}
|
|
29
28
|
},
|
|
30
29
|
"types": "./dist/index.d.mts",
|
|
31
30
|
"repository": {
|
|
32
31
|
"type": "git",
|
|
33
|
-
"url": "https://github.com/Meenic/mnemocyte.git"
|
|
32
|
+
"url": "git+https://github.com/Meenic/mnemocyte.git"
|
|
34
33
|
},
|
|
35
34
|
"keywords": [
|
|
36
35
|
"ai",
|
|
@@ -56,20 +55,23 @@
|
|
|
56
55
|
"node": ">=22.18"
|
|
57
56
|
},
|
|
58
57
|
"dependencies": {
|
|
59
|
-
"drizzle-orm": "^0.45.
|
|
58
|
+
"drizzle-orm": "^0.45.4",
|
|
60
59
|
"postgres": "^3.4.9"
|
|
61
60
|
},
|
|
62
61
|
"devDependencies": {
|
|
63
|
-
"@
|
|
64
|
-
"@
|
|
65
|
-
"
|
|
66
|
-
"
|
|
62
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
63
|
+
"@biomejs/biome": "2.6.3",
|
|
64
|
+
"@types/node": "^22.20.5",
|
|
65
|
+
"drizzle-kit": "^0.31.11",
|
|
66
|
+
"publint": "0.3.25",
|
|
67
|
+
"tsdown": "0.23.1",
|
|
67
68
|
"typescript": "^6.0.3",
|
|
68
|
-
"
|
|
69
|
+
"vite": "^8.3.5",
|
|
70
|
+
"vitest": "5.0.5"
|
|
69
71
|
},
|
|
70
72
|
"scripts": {
|
|
71
|
-
"build": "tsdown
|
|
72
|
-
"dev": "tsdown
|
|
73
|
+
"build": "tsdown",
|
|
74
|
+
"dev": "tsdown --watch",
|
|
73
75
|
"checktypes": "tsc --noEmit && tsc --noEmit --project tsconfig.test.json",
|
|
74
76
|
"test": "pnpm run test:ci",
|
|
75
77
|
"test:ci": "pnpm build && vitest run --typecheck --project unit --project package",
|
|
@@ -85,9 +87,10 @@
|
|
|
85
87
|
"test:retrieval": "vitest run --project unit test/retrieval/quality.test.ts",
|
|
86
88
|
"test:context": "vitest run --project unit test/context/builder.test.ts",
|
|
87
89
|
"test:integration": "vitest run --project integration",
|
|
88
|
-
"bench:retrieval": "vitest bench --project
|
|
90
|
+
"bench:retrieval": "pnpm build && vitest bench --project \"package (bench)\" test/benchmarks/retrieval.bench.ts",
|
|
89
91
|
"lint": "biome check --error-on-warnings .",
|
|
90
92
|
"lint:fix": "biome check --write .",
|
|
93
|
+
"lint:package": "pnpm build && node scripts/check-package.mjs",
|
|
91
94
|
"format": "biome format --write",
|
|
92
95
|
"migration:render": "node migrations/render-initial.mjs",
|
|
93
96
|
"db:generate": "drizzle-kit generate",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"openai.d.mts","names":[],"sources":["../../src/embedders/openai.ts"],"mappings":";;;UAciB,qBAAA;;AAAjB;;WAIU,MAAA;EAJ4B;;;EAAA,SAQ5B,KAAA;EAUA;;AAAO;AAoIjB;EApIU,SALA,UAAA;;;;;WAKA,OAAA;AAAA;AAoI8D;;;;AAAA,iBAAxD,cAAA,CAAe,OAAA,EAAS,qBAAA,GAAwB,QAAQ"}
|
package/dist/index.d.mts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/client.ts","../src/errors.ts"],"mappings":";;;;;AA2CA;;;;;;;;AAAyE;;;;AC9BzE;;;;AAA8B;AA8B9B;;;;;;;;;;iBDAgB,eAAA,CAAgB,MAAA,EAAQ,eAAA,GAAkB,eAAe;;;;;;AAAzE;;;;;;;;AAAyE;;KC9B7D,kBAAA;;AAAZ;;;;AAA8B;AA8B9B;;;;;;;;;;;;;cAAa,cAAA,SAAuB,KAAA;EAWA;EAAA,SAT1B,IAAA,EAAM,kBAAA;EASwC;EAAA,SAPrC,KAAA;EAOoD;AAkBvE;;;;cAlBa,OAAA,UAAiB,IAAA,EAAM,kBAAA,EAAoB,KAAA;AAAA;;;AAkBiB;;;;;;;;iBAAzD,gBAAA,CAAiB,KAAA,YAAiB,KAAA,IAAS,cAAc"}
|