mnemocyte 0.3.0 → 0.5.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 +266 -22
- package/dist/embedders/openai.d.mts +1 -1
- package/dist/embedders/openai.d.mts.map +1 -1
- package/dist/embedders/openai.mjs +24 -9
- package/dist/embedders/openai.mjs.map +1 -1
- package/dist/{errors-B_7ZdjEO.mjs → errors-DIPysVWl.mjs} +1 -1
- package/dist/errors-DIPysVWl.mjs.map +1 -0
- package/dist/index.d.mts +16 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +155 -1699
- package/dist/index.mjs.map +1 -1
- package/dist/postgres-BHQ1pj16.mjs +913 -0
- package/dist/postgres-BHQ1pj16.mjs.map +1 -0
- package/dist/postgres-runtime-DxJxns07.mjs +9 -0
- package/dist/postgres-runtime-DxJxns07.mjs.map +1 -0
- package/dist/store-config-BFFTm1sj.mjs +1255 -0
- package/dist/store-config-BFFTm1sj.mjs.map +1 -0
- package/dist/stores/drizzle.d.mts +18 -0
- package/dist/stores/drizzle.d.mts.map +1 -0
- package/dist/stores/drizzle.mjs +20 -0
- package/dist/stores/drizzle.mjs.map +1 -0
- package/dist/{types-gOPLre4V.d.mts → types-XUWYDoXM.d.mts} +136 -34
- package/dist/types-XUWYDoXM.d.mts.map +1 -0
- package/migrations/0000_initial.sql.template +2 -1
- package/migrations/0002_add_embedding_model.sql +15 -0
- package/migrations/meta/0002_snapshot.json +315 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +7 -3
- package/dist/errors-B_7ZdjEO.mjs.map +0 -1
- package/dist/types-gOPLre4V.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store-config-BFFTm1sj.mjs","names":[],"sources":["../src/database-url.ts","../src/context/formatter.ts","../src/context/tokens.ts","../src/context/builder.ts","../src/observability.ts","../src/resilience.ts","../src/memory/json.ts","../src/memory/records.ts","../src/retrieval/scorer.ts","../src/memory/defaults.ts","../src/memory/embeddings.ts","../src/memory/store.ts","../src/memory/validation.ts","../src/memory/client-core.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 type { ContextFormat, MemoryWithScore } from \"../types.js\";\n\nfunction escapeXml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&\")\n\t\t.replaceAll(\"<\", \"<\")\n\t\t.replaceAll(\">\", \">\")\n\t\t.replaceAll('\"', \""\")\n\t\t.replaceAll(\"'\", \"'\");\n}\n\nfunction formatMetadata(memory: MemoryWithScore): string {\n\tconst parts = [\n\t\t`type=${memory.type}`,\n\t\t`importance=${memory.importance}`,\n\t\t`score=${memory.score.toFixed(3)}`,\n\t];\n\tif (memory.source) {\n\t\tparts.push(`source=${memory.source}`);\n\t}\n\tif (memory.tags.length > 0) {\n\t\tparts.push(`tags=${memory.tags.join(\",\")}`);\n\t}\n\treturn parts.join(\"; \");\n}\n\nfunction markdownFence(value: string): string {\n\tconst longestBacktickRun = Math.max(\n\t\t0,\n\t\t...Array.from(value.matchAll(/`+/g), (match) => match[0].length),\n\t);\n\treturn \"`\".repeat(Math.max(3, longestBacktickRun + 1));\n}\n\nfunction plainFence(values: readonly string[]): string {\n\tconst longestEqualsRun = Math.max(\n\t\t0,\n\t\t...values.flatMap((value) =>\n\t\t\tArray.from(value.matchAll(/=+/g), (match) => match[0].length),\n\t\t),\n\t);\n\treturn \"=\".repeat(Math.max(8, longestEqualsRun + 1));\n}\n\nfunction formatMarkdown(\n\tmemories: readonly MemoryWithScore[],\n\tquery: string,\n\tomittedCount: number,\n): string {\n\tconst lines = [\n\t\t\"# Memory Context\",\n\t\t\"\",\n\t\t`Query: ${query}`,\n\t\t\"\",\n\t\t\"## Relevant Memories\",\n\t];\n\tfor (const memory of memories) {\n\t\tconst fence = markdownFence(memory.content);\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t`- ${formatMetadata(memory)}`,\n\t\t\t` ${fence}text`,\n\t\t\t...memory.content.split(\"\\n\").map((line) => ` ${line}`),\n\t\t\t` ${fence}`,\n\t\t);\n\t}\n\tif (omittedCount > 0) {\n\t\tlines.push(\"\", `[${omittedCount} memories omitted to fit token budget]`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatPlain(\n\tmemories: readonly MemoryWithScore[],\n\tquery: string,\n\tomittedCount: number,\n): string {\n\tconst formattedMemories = memories.map((memory) => ({\n\t\tmemory,\n\t\tmetadata: formatMetadata(memory),\n\t}));\n\tconst fence = plainFence([\n\t\tquery,\n\t\t...formattedMemories.flatMap(({ memory, metadata }) => [\n\t\t\tmetadata,\n\t\t\tmemory.content,\n\t\t]),\n\t]);\n\tconst lines = [\n\t\t\"MEMORY CONTEXT\",\n\t\t\"\",\n\t\t`QUERY: ${query}`,\n\t\t\"\",\n\t\t\"RELEVANT MEMORIES\",\n\t];\n\tfor (const [index, { memory, metadata }] of formattedMemories.entries()) {\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t`${fence} MEMORY ${index + 1} START ${fence}`,\n\t\t\tmetadata,\n\t\t\tmemory.content,\n\t\t\t`${fence} MEMORY ${index + 1} END ${fence}`,\n\t\t);\n\t}\n\tif (omittedCount > 0) {\n\t\tlines.push(\"\", `[${omittedCount} memories omitted to fit token budget]`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction formatXml(\n\tmemories: readonly MemoryWithScore[],\n\tquery: string,\n\tomittedCount: number,\n): string {\n\tconst lines = [`<memory_context query=\"${escapeXml(query)}\">`];\n\tfor (const memory of memories) {\n\t\tlines.push(\n\t\t\t` <memory id=\"${escapeXml(memory.id)}\" type=\"${escapeXml(memory.type)}\" importance=\"${escapeXml(memory.importance)}\" score=\"${memory.score.toFixed(3)}\">`,\n\t\t\t` <content>${escapeXml(memory.content)}</content>`,\n\t\t\t` <metadata>${escapeXml(formatMetadata(memory))}</metadata>`,\n\t\t\t\" </memory>\",\n\t\t);\n\t}\n\tif (omittedCount > 0) {\n\t\tlines.push(` <omitted count=\"${omittedCount}\" reason=\"token_budget\" />`);\n\t}\n\tlines.push(\"</memory_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nexport function formatContext(\n\tmemories: readonly MemoryWithScore[],\n\tquery: string,\n\tformat: ContextFormat,\n\tomittedCount = 0,\n): string {\n\tswitch (format) {\n\t\tcase \"markdown\":\n\t\t\treturn formatMarkdown(memories, query, omittedCount);\n\t\tcase \"plain\":\n\t\t\treturn formatPlain(memories, query, omittedCount);\n\t\tcase \"xml\":\n\t\t\treturn formatXml(memories, query, omittedCount);\n\t}\n}\n","import type { TokenCounter } from \"../types.js\";\n\nconst TRUNCATION_MARKER = \"[truncated to fit token budget]\";\n\nexport const heuristicTokenCounter: TokenCounter = {\n\tcount(text) {\n\t\treturn Math.ceil(text.length / 4);\n\t},\n};\n\nexport function trimToTokenBudget(\n\ttext: string,\n\tmaxTokens: number,\n\ttokenCounter: TokenCounter,\n): string {\n\tif (maxTokens < 1 || tokenCounter.count(text) <= maxTokens) {\n\t\treturn text;\n\t}\n\tlet low = 0;\n\tlet high = text.length;\n\tlet best = \"\";\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tconst candidate = text.slice(0, mid).trimEnd();\n\t\tconst output = `${candidate}\\n${TRUNCATION_MARKER}`;\n\t\tif (tokenCounter.count(output) <= maxTokens) {\n\t\t\tbest = output;\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid - 1;\n\t\t}\n\t}\n\tif (best) {\n\t\treturn best;\n\t}\n\tfor (let length = TRUNCATION_MARKER.length; length > 0; length -= 1) {\n\t\tconst markerFragment = TRUNCATION_MARKER.slice(0, length);\n\t\tif (tokenCounter.count(markerFragment) <= maxTokens) {\n\t\t\treturn markerFragment;\n\t\t}\n\t}\n\treturn \"\";\n}\n","import type { BuildContextInput, MemoryWithScore } from \"../types.js\";\nimport { formatContext } from \"./formatter.js\";\nimport { heuristicTokenCounter, trimToTokenBudget } from \"./tokens.js\";\n\nexport interface BuildContextOptions {\n\tinput: BuildContextInput;\n\trecall(input: BuildContextInput): Promise<MemoryWithScore[]>;\n}\n\nexport async function buildContext(\n\toptions: BuildContextOptions,\n): Promise<string> {\n\tconst format = options.input.format ?? \"markdown\";\n\tconst maxTokens = options.input.maxTokens ?? 1200;\n\tconst tokenCounter = options.input.tokenCounter ?? heuristicTokenCounter;\n\tconst memories = await options.recall(options.input);\n\tlet low = 0;\n\tlet high = memories.length;\n\tlet bestContext = \"\";\n\twhile (low <= high) {\n\t\tconst mid = Math.floor((low + high) / 2);\n\t\tconst omittedCount = memories.length - mid;\n\t\tconst context = formatContext(\n\t\t\tmemories.slice(0, mid),\n\t\t\toptions.input.query,\n\t\t\tformat,\n\t\t\tomittedCount,\n\t\t);\n\t\tif (tokenCounter.count(context) <= maxTokens) {\n\t\t\tbestContext = context;\n\t\t\tlow = mid + 1;\n\t\t} else {\n\t\t\thigh = mid - 1;\n\t\t}\n\t}\n\tif (bestContext || memories.length === 0) {\n\t\treturn bestContext;\n\t}\n\treturn trimToTokenBudget(\n\t\tformatContext([], options.input.query, format, memories.length),\n\t\tmaxTokens,\n\t\ttokenCounter,\n\t);\n}\n","import type {\n\tMnemocyteBackend,\n\tMnemocyteConfig,\n\tMnemocyteObservation,\n\tMnemocyteOperation,\n} from \"./types.js\";\n\ninterface ObservationMetadata {\n\tentityId?: string;\n\tmemoryId?: string;\n\tcount?: number;\n}\n\nfunction withMetadata(\n\tevent: MnemocyteObservation,\n\tmetadata: ObservationMetadata,\n): MnemocyteObservation {\n\treturn {\n\t\t...event,\n\t\t...(metadata.entityId === undefined ? {} : { entityId: metadata.entityId }),\n\t\t...(metadata.memoryId === undefined ? {} : { memoryId: metadata.memoryId }),\n\t\t...(metadata.count === undefined ? {} : { count: metadata.count }),\n\t};\n}\n\nasync function emitObservation(\n\tconfig: MnemocyteConfig,\n\tevent: MnemocyteObservation,\n): Promise<void> {\n\ttry {\n\t\tawait config.observability?.onEvent?.(event);\n\t} catch {\n\t\treturn;\n\t}\n}\n\nasync function observeFromStartedAt<T>(\n\tconfig: MnemocyteConfig,\n\tbackend: MnemocyteBackend,\n\toperation: MnemocyteOperation,\n\tmetadata: ObservationMetadata,\n\tstartedAt: number,\n\taction: () => Promise<T>,\n\tsuccessMetadata?: (result: T) => ObservationMetadata,\n): Promise<T> {\n\tawait emitObservation(\n\t\tconfig,\n\t\twithMetadata(\n\t\t\t{\n\t\t\t\toperation,\n\t\t\t\tphase: \"start\",\n\t\t\t\tbackend,\n\t\t\t\ttimestamp: new Date(startedAt),\n\t\t\t},\n\t\t\tmetadata,\n\t\t),\n\t);\n\ttry {\n\t\tconst result = await action();\n\t\tawait emitObservation(\n\t\t\tconfig,\n\t\t\twithMetadata(\n\t\t\t\t{\n\t\t\t\t\toperation,\n\t\t\t\t\tphase: \"success\",\n\t\t\t\t\tbackend,\n\t\t\t\t\ttimestamp: new Date(),\n\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t},\n\t\t\t\t{ ...metadata, ...successMetadata?.(result) },\n\t\t\t),\n\t\t);\n\t\treturn result;\n\t} catch (error) {\n\t\tawait emitObservation(\n\t\t\tconfig,\n\t\t\twithMetadata(\n\t\t\t\t{\n\t\t\t\t\toperation,\n\t\t\t\t\tphase: \"error\",\n\t\t\t\t\tbackend,\n\t\t\t\t\ttimestamp: new Date(),\n\t\t\t\t\tdurationMs: Date.now() - startedAt,\n\t\t\t\t\terror,\n\t\t\t\t},\n\t\t\t\tmetadata,\n\t\t\t),\n\t\t);\n\t\tthrow error;\n\t}\n}\n\nexport function observe<T>(\n\tconfig: MnemocyteConfig,\n\tbackend: MnemocyteBackend,\n\toperation: MnemocyteOperation,\n\tmetadata: ObservationMetadata,\n\taction: () => Promise<T>,\n\tsuccessMetadata?: (result: T) => ObservationMetadata,\n): Promise<T> {\n\treturn observeFromStartedAt(\n\t\tconfig,\n\t\tbackend,\n\t\toperation,\n\t\tmetadata,\n\t\tDate.now(),\n\t\taction,\n\t\tsuccessMetadata,\n\t);\n}\n\nexport function observePrepared<Prepared, Result>(\n\tconfig: MnemocyteConfig,\n\tbackend: MnemocyteBackend,\n\toperation: MnemocyteOperation,\n\tmetadata: ObservationMetadata,\n\tprepare: () => Prepared,\n\taction: (prepared: Prepared) => Promise<Result>,\n\tsuccessMetadata?: (result: Result) => ObservationMetadata,\n): Promise<Result> {\n\tconst startedAt = Date.now();\n\ttry {\n\t\tconst prepared = prepare();\n\t\treturn observeFromStartedAt(\n\t\t\tconfig,\n\t\t\tbackend,\n\t\t\toperation,\n\t\t\tmetadata,\n\t\t\tstartedAt,\n\t\t\t() => action(prepared),\n\t\t\tsuccessMetadata,\n\t\t);\n\t} catch (error) {\n\t\treturn observeFromStartedAt(\n\t\t\tconfig,\n\t\t\tbackend,\n\t\t\toperation,\n\t\t\tmetadata,\n\t\t\tstartedAt,\n\t\t\tasync () => {\n\t\t\t\tthrow error;\n\t\t\t},\n\t\t);\n\t}\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 { cloneMemory } from \"../memory/records.js\";\nimport type {\n\tImportanceLevel,\n\tMemory,\n\tMemoryWithScore,\n\tRecallInput,\n\tRetrievalConfig,\n\tRetrievalScoreWeights,\n} from \"../types.js\";\n\nconst IMPORTANCE_SCORES: Record<ImportanceLevel, number> = {\n\tlow: 0,\n\tnormal: 0.5,\n\thigh: 0.8,\n\tcritical: 1,\n};\n\nexport const DEFAULT_RETRIEVAL_WEIGHTS: Readonly<\n\tRequired<RetrievalScoreWeights>\n> = {\n\tvector: 0.55,\n\tlexical: 0.2,\n\trecency: 0.1,\n\tconfidence: 0.05,\n\taccess: 0.05,\n\timportance: 0.05,\n};\n\nconst DEFAULT_RECENCY_HALF_LIFE_DAYS = 90;\nconst DEFAULT_ACCESS_SATURATION = 10;\nexport const DEFAULT_CANDIDATE_MULTIPLIER = 3;\n\nexport interface ScoringConfig {\n\tweights: Required<RetrievalScoreWeights>;\n\trecencyHalfLifeDays: number;\n\taccessSaturation: number;\n}\n\nexport function cosineSimilarity(\n\ta: readonly number[],\n\tb: readonly number[],\n): number {\n\tlet dot = 0;\n\tlet aMagnitude = 0;\n\tlet bMagnitude = 0;\n\tfor (let i = 0; i < a.length; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\taMagnitude += av * av;\n\t\tbMagnitude += bv * bv;\n\t}\n\tif (aMagnitude === 0 || bMagnitude === 0) {\n\t\treturn 0;\n\t}\n\treturn dot / (Math.sqrt(aMagnitude) * Math.sqrt(bMagnitude));\n}\n\nexport function tokenizeQuery(query: string): readonly string[] {\n\treturn query.toLowerCase().split(/\\s+/).filter(Boolean);\n}\n\nexport function lexicalScoreWithTerms(\n\tcontent: string,\n\tterms: readonly string[],\n): number {\n\tif (terms.length === 0) {\n\t\treturn 0;\n\t}\n\tconst lowerContent = content.toLowerCase();\n\tconst matches = terms.filter((term) => lowerContent.includes(term)).length;\n\treturn matches / terms.length;\n}\n\nexport function createLexicalScorer(\n\tquery: string,\n): (content: string) => number {\n\tconst terms = tokenizeQuery(query);\n\treturn (content) => lexicalScoreWithTerms(content, terms);\n}\n\nfunction clampScore(value: number): number {\n\tif (!Number.isFinite(value)) {\n\t\treturn 0;\n\t}\n\treturn Math.max(0, Math.min(1, value));\n}\n\nexport function toVectorScore(cosineSimilarity: number): number {\n\treturn clampScore(cosineSimilarity);\n}\n\nfunction normalizeWeights(\n\tweights: RetrievalScoreWeights | undefined,\n): Required<RetrievalScoreWeights> {\n\tconst merged = { ...DEFAULT_RETRIEVAL_WEIGHTS, ...weights };\n\tconst total =\n\t\tmerged.vector +\n\t\tmerged.lexical +\n\t\tmerged.recency +\n\t\tmerged.confidence +\n\t\tmerged.access +\n\t\tmerged.importance;\n\tif (total <= 0) {\n\t\treturn { ...DEFAULT_RETRIEVAL_WEIGHTS };\n\t}\n\treturn {\n\t\tvector: merged.vector / total,\n\t\tlexical: merged.lexical / total,\n\t\trecency: merged.recency / total,\n\t\tconfidence: merged.confidence / total,\n\t\taccess: merged.access / total,\n\t\timportance: merged.importance / total,\n\t};\n}\n\nexport function createScoringConfig(config?: RetrievalConfig): ScoringConfig {\n\treturn {\n\t\tweights: normalizeWeights(config?.weights),\n\t\trecencyHalfLifeDays:\n\t\t\tconfig?.recencyHalfLifeDays ?? DEFAULT_RECENCY_HALF_LIFE_DAYS,\n\t\taccessSaturation: config?.accessSaturation ?? DEFAULT_ACCESS_SATURATION,\n\t};\n}\n\nfunction recencyScore(createdAt: Date, halfLifeDays: number): number {\n\tconst ageMs = Date.now() - createdAt.getTime();\n\tconst ageDays = Math.max(0, ageMs / 86_400_000);\n\treturn Math.exp((-Math.LN2 * ageDays) / halfLifeDays);\n}\n\nfunction accessScore(accessCount: number, saturation: number): number {\n\tif (accessCount <= 0) {\n\t\treturn 0;\n\t}\n\treturn Math.min(1, Math.log1p(accessCount) / Math.log1p(saturation));\n}\n\nexport function toScoredMemoryWithConfig(\n\tmemory: Memory,\n\tvector: number,\n\tlexical: number,\n\tinput: RecallInput,\n\tconfig: ScoringConfig,\n): MemoryWithScore {\n\tconst { weights } = config;\n\tconst recency = recencyScore(memory.createdAt, config.recencyHalfLifeDays);\n\tconst confidence = clampScore(memory.confidence);\n\tconst access = accessScore(memory.accessCount, config.accessSaturation);\n\tconst importance = IMPORTANCE_SCORES[memory.importance];\n\tconst score = Math.max(\n\t\t0,\n\t\tMath.min(\n\t\t\t1,\n\t\t\tclampScore(vector) * weights.vector +\n\t\t\t\tclampScore(lexical) * weights.lexical +\n\t\t\t\trecency * weights.recency +\n\t\t\t\tconfidence * weights.confidence +\n\t\t\t\taccess * weights.access +\n\t\t\t\timportance * weights.importance,\n\t\t),\n\t);\n\treturn {\n\t\t...cloneMemory(memory),\n\t\tscore,\n\t\tscores: {\n\t\t\tvector: clampScore(vector),\n\t\t\tlexical: clampScore(lexical),\n\t\t\trecency,\n\t\t\tconfidence,\n\t\t\taccess,\n\t\t\timportance,\n\t\t},\n\t\texplanation: input.explain\n\t\t\t? {\n\t\t\t\t\tvectorScore: clampScore(vector),\n\t\t\t\t\tlexicalScore: clampScore(lexical),\n\t\t\t\t\trecencyScore: recency,\n\t\t\t\t\tconfidenceScore: confidence,\n\t\t\t\t\taccessScore: access,\n\t\t\t\t\timportanceScore: importance,\n\t\t\t\t\timportanceBoost: importance * weights.importance,\n\t\t\t\t\tweights,\n\t\t\t\t\tfinalScore: score,\n\t\t\t\t}\n\t\t\t: null,\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 { withResilience } from \"../resilience.js\";\nimport type { Embedder, ProviderResilienceConfig } from \"../types.js\";\n\nfunction validateEmbedding(\n\tembedding: readonly number[],\n\tdimensions: number,\n): void {\n\tif (embedding.length !== dimensions) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Embedder returned an embedding with unexpected dimensions.\",\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n\tif (embedding.some((component) => !Number.isFinite(component))) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Embedder returned an embedding with non-finite values.\",\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n\tif (embedding.every((component) => component === 0)) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Embedder returned an embedding with zero norm.\",\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n}\n\nexport async function embedOne(\n\tembedder: Embedder,\n\ttext: string,\n\toptions: {\n\t\tsignal?: AbortSignal;\n\t\tresilience?: ProviderResilienceConfig;\n\t} = {},\n): Promise<number[]> {\n\tlet embeddings: number[][];\n\ttry {\n\t\tembeddings = await withResilience(\n\t\t\t(signal) =>\n\t\t\t\tsignal === undefined\n\t\t\t\t\t? embedder.embed([text])\n\t\t\t\t\t: embedder.embed([text], { signal }),\n\t\t\t{\n\t\t\t\t...(options.signal === undefined ? {} : { signal: options.signal }),\n\t\t\t\t...(options.resilience === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { resilience: options.resilience }),\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof MnemocyteError &&\n\t\t\t(error.code === \"TIMEOUT\" || error.code === \"ABORTED\")\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new MnemocyteError(\"Failed to embed text.\", \"EMBEDDING\", error);\n\t}\n\tconst embedding = embeddings[0];\n\tif (!embedding) {\n\t\tthrow new MnemocyteError(\"Embedder returned no embedding.\", \"EMBEDDING\");\n\t}\n\tvalidateEmbedding(embedding, embedder.dimensions);\n\treturn embedding;\n}\n\nexport async function embedMany(\n\tembedder: Embedder,\n\ttexts: readonly string[],\n\toptions: {\n\t\tsignal?: AbortSignal;\n\t\tresilience?: ProviderResilienceConfig;\n\t} = {},\n): Promise<number[][]> {\n\tif (texts.length === 0) {\n\t\treturn [];\n\t}\n\tlet embeddings: number[][];\n\ttry {\n\t\tembeddings = await withResilience(\n\t\t\t(signal) =>\n\t\t\t\tsignal === undefined\n\t\t\t\t\t? embedder.embed(texts)\n\t\t\t\t\t: embedder.embed(texts, { signal }),\n\t\t\t{\n\t\t\t\t...(options.signal === undefined ? {} : { signal: options.signal }),\n\t\t\t\t...(options.resilience === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { resilience: options.resilience }),\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof MnemocyteError &&\n\t\t\t(error.code === \"TIMEOUT\" || error.code === \"ABORTED\")\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new MnemocyteError(\"Failed to embed texts.\", \"EMBEDDING\", error);\n\t}\n\tif (embeddings.length !== texts.length) {\n\t\tthrow new MnemocyteError(\n\t\t\t`Embedder returned ${embeddings.length} embeddings for ${texts.length} texts.`,\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n\tfor (const embedding of embeddings) {\n\t\tvalidateEmbedding(embedding, embedder.dimensions);\n\t}\n\treturn embeddings;\n}\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\";\nimport { DEFAULT_RETRIEVAL_WEIGHTS } from \"../retrieval/scorer.js\";\nimport type {\n\tAuditLogCursor,\n\tBuildContextInput,\n\tConsolidateInput,\n\tEmbedder,\n\tFindDuplicatesInput,\n\tImportanceLevel,\n\tListAuditLogInput,\n\tMemoryType,\n\tProviderResilienceConfig,\n\tPruneInput,\n\tRecallInput,\n\tRememberInput,\n\tRetrievalConfig,\n\tRetrievalScoreWeights,\n} from \"../types.js\";\nimport type { OwnedJsonObject } from \"./json.js\";\nimport {\n\tassertPruneFilterHasSelector,\n\ttype ValidatedPruneFilter,\n} from \"./store.js\";\n\nconst MEMORY_TYPES = [\n\t\"fact\",\n\t\"preference\",\n\t\"instruction\",\n\t\"backstory\",\n\t\"episode\",\n\t\"session\",\n] as const satisfies readonly MemoryType[];\n\nconst IMPORTANCE_LEVELS = [\n\t\"low\",\n\t\"normal\",\n\t\"high\",\n\t\"critical\",\n] as const satisfies readonly ImportanceLevel[];\n\nexport interface PreparedRememberInput extends Omit<RememberInput, \"metadata\"> {\n\tmetadata: OwnedJsonObject;\n}\n\nfunction isMemoryType(value: unknown): value is MemoryType {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\t(MEMORY_TYPES as readonly string[]).includes(value)\n\t);\n}\n\nfunction isImportanceLevel(value: unknown): value is ImportanceLevel {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\t(IMPORTANCE_LEVELS as readonly string[]).includes(value)\n\t);\n}\n\nfunction assertMemoryType(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is MemoryType {\n\tif (!isMemoryType(value)) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be a known memory type.`,\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nfunction assertImportanceLevel(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is ImportanceLevel {\n\tif (!isImportanceLevel(value)) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be a known importance level.`,\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nfunction assertMemoryTypeArray(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is readonly MemoryType[] {\n\tif (!Array.isArray(value)) {\n\t\tthrow new MnemocyteError(`${field} must be an array.`, \"VALIDATION\");\n\t}\n\tfor (const item of value) {\n\t\tif (!isMemoryType(item)) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`${field} must contain only known memory types.`,\n\t\t\t\t\"VALIDATION\",\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction assertValidDate(value: unknown, field: string): asserts value is Date {\n\tif (!(value instanceof Date) || !Number.isFinite(value.getTime())) {\n\t\tthrow new MnemocyteError(`${field} must be a valid Date.`, \"VALIDATION\");\n\t}\n}\n\nexport function assertNonEmptyString(\n\tvalue: unknown,\n\tfield: string,\n\tcode: \"CONFIG\" | \"VALIDATION\" = \"VALIDATION\",\n): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new MnemocyteError(`${field} must be a non-empty string.`, code);\n\t}\n}\n\nexport function assertLimit(value: number): void {\n\tif (!Number.isInteger(value) || value < 1) {\n\t\tthrow new MnemocyteError(\"limit must be a positive integer.\", \"VALIDATION\");\n\t}\n}\n\nexport function assertMinScore(value: number): void {\n\tif (!Number.isFinite(value) || value < 0 || value > 1) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"minScore must be a number between 0 and 1.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nexport function assertEmbedder(embedder: Embedder): void {\n\tif (!embedder || typeof embedder.embed !== \"function\") {\n\t\tthrow new MnemocyteError(\n\t\t\t\"embedder with an embed function is required.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tassertNonEmptyString(embedder.model, \"embedder.model\", \"CONFIG\");\n\tif (!Number.isInteger(embedder.dimensions) || embedder.dimensions < 1) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"embedder.dimensions must be a positive integer.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nconst RETRIEVAL_WEIGHT_KEYS = [\n\t\"vector\",\n\t\"lexical\",\n\t\"recency\",\n\t\"confidence\",\n\t\"access\",\n\t\"importance\",\n] as const satisfies readonly (keyof RetrievalScoreWeights)[];\n\nfunction assertPositiveFiniteConfigValue(value: number, field: string): void {\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be a positive finite number.`,\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nexport function validateRetrievalConfig(\n\tconfig: RetrievalConfig | undefined,\n): void {\n\tif (config === undefined) {\n\t\treturn;\n\t}\n\n\tlet weightTotal = 0;\n\tfor (const key of RETRIEVAL_WEIGHT_KEYS) {\n\t\tconst weight = config.weights?.[key] ?? DEFAULT_RETRIEVAL_WEIGHTS[key];\n\t\tif (!Number.isFinite(weight) || weight < 0) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`retrieval.weights.${key} must be a non-negative finite number.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t\tweightTotal += weight;\n\t}\n\tif (weightTotal === 0) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"retrieval.weights must have an effective total greater than zero.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\n\tif (config.recencyHalfLifeDays !== undefined) {\n\t\tassertPositiveFiniteConfigValue(\n\t\t\tconfig.recencyHalfLifeDays,\n\t\t\t\"retrieval.recencyHalfLifeDays\",\n\t\t);\n\t}\n\tif (config.accessSaturation !== undefined) {\n\t\tassertPositiveFiniteConfigValue(\n\t\t\tconfig.accessSaturation,\n\t\t\t\"retrieval.accessSaturation\",\n\t\t);\n\t}\n\tif (\n\t\tconfig.candidateMultiplier !== undefined &&\n\t\t(!Number.isInteger(config.candidateMultiplier) ||\n\t\t\tconfig.candidateMultiplier < 1)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"retrieval.candidateMultiplier must be an integer greater than or equal to 1.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nexport function validateProviderResilienceConfig(\n\tconfig: ProviderResilienceConfig | undefined,\n): void {\n\tif (config === undefined) {\n\t\treturn;\n\t}\n\tif (typeof config !== \"object\" || config === null || Array.isArray(config)) {\n\t\tthrow new MnemocyteError(\"provider must be an object.\", \"CONFIG\");\n\t}\n\n\tfor (const [field, value] of [\n\t\t[\"provider.timeoutMs\", config.timeoutMs],\n\t\t[\"provider.baseDelayMs\", config.baseDelayMs],\n\t\t[\"provider.maxDelayMs\", config.maxDelayMs],\n\t] as const) {\n\t\tif (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`${field} must be a non-negative finite number.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t}\n\tif (\n\t\tconfig.retries !== undefined &&\n\t\t(!Number.isInteger(config.retries) || config.retries < 0)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"provider.retries must be a non-negative integer.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tif (\n\t\tconfig.shouldRetry !== undefined &&\n\t\ttypeof config.shouldRetry !== \"function\"\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"provider.shouldRetry must be a function.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nexport function validateBuildContextInput(input: BuildContextInput): void {\n\tif (\n\t\tinput.maxTokens !== undefined &&\n\t\t(!Number.isInteger(input.maxTokens) || input.maxTokens < 1)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"maxTokens must be a positive integer when supplied.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nexport function validateRememberInput(input: PreparedRememberInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tassertNonEmptyString(input.content, \"content\");\n\tif (input.type !== undefined) {\n\t\tassertMemoryType(input.type, \"type\");\n\t}\n\tif (input.importance !== undefined) {\n\t\tassertImportanceLevel(input.importance, \"importance\");\n\t}\n\tif (input.tags !== undefined) {\n\t\tif (!Array.isArray(input.tags)) {\n\t\t\tthrow new MnemocyteError(\"tags must be an array.\", \"VALIDATION\");\n\t\t}\n\t\tfor (const tag of input.tags as readonly unknown[]) {\n\t\t\tif (typeof tag !== \"string\") {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"tags must contain only strings.\",\n\t\t\t\t\t\"VALIDATION\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tif (input.source !== undefined && typeof input.source !== \"string\") {\n\t\tthrow new MnemocyteError(\"source must be a string.\", \"VALIDATION\");\n\t}\n\tif (\n\t\tinput.confidence !== undefined &&\n\t\t(!Number.isFinite(input.confidence) ||\n\t\t\tinput.confidence < 0 ||\n\t\t\tinput.confidence > 1)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"confidence must be a number between 0 and 1.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n\tif (input.expiresAt !== undefined) {\n\t\tassertValidDate(input.expiresAt, \"expiresAt\");\n\t}\n}\n\nexport function validateRecallInput(input: RecallInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tassertNonEmptyString(input.query, \"query\");\n\tif (input.limit !== undefined) {\n\t\tassertLimit(input.limit);\n\t}\n\tif (input.minScore !== undefined) {\n\t\tassertMinScore(input.minScore);\n\t}\n\tif (input.types !== undefined) {\n\t\tassertMemoryTypeArray(input.types, \"types\");\n\t}\n}\n\nexport function contextInputToRecallInput(\n\tinput: BuildContextInput,\n): RecallInput {\n\treturn {\n\t\tentityId: input.entityId,\n\t\tquery: input.query,\n\t\t...(input.limit === undefined ? {} : { limit: input.limit }),\n\t\t...(input.minScore === undefined ? {} : { minScore: input.minScore }),\n\t\t...(input.types === undefined ? {} : { types: input.types }),\n\t\t...(input.tags === undefined ? {} : { tags: input.tags }),\n\t\t...(input.includeSuperseded === undefined\n\t\t\t? {}\n\t\t\t: { includeSuperseded: input.includeSuperseded }),\n\t\t...(input.includeExpired === undefined\n\t\t\t? {}\n\t\t\t: { includeExpired: input.includeExpired }),\n\t};\n}\n\n/**\n * Validate and normalize a {@link PruneInput}. Throws a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed fields or when normalization leaves no\n * effective selector, preventing surprise full-table deletes.\n */\nexport function validatePruneInput(input: PruneInput): ValidatedPruneFilter {\n\tif (input.entityId !== undefined) {\n\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t}\n\tfor (const [field, value] of [\n\t\t[\"expired\", input.expired],\n\t\t[\"superseded\", input.superseded],\n\t\t[\"dryRun\", input.dryRun],\n\t] as const) {\n\t\tif (value !== undefined && typeof value !== \"boolean\") {\n\t\t\tthrow new MnemocyteError(`${field} must be a boolean.`, \"VALIDATION\");\n\t\t}\n\t}\n\tfor (const [field, value] of [\n\t\t[\"createdBefore\", input.createdBefore],\n\t\t[\"notAccessedSince\", input.notAccessedSince],\n\t] as const) {\n\t\tif (value !== undefined) {\n\t\t\tassertValidDate(value, field);\n\t\t}\n\t}\n\tlet types: readonly MemoryType[] | undefined;\n\tif (input.types !== undefined) {\n\t\tassertMemoryTypeArray(input.types, \"types\");\n\t\tconst normalized = new Set<MemoryType>(input.types);\n\t\tif (normalized.size > 0) {\n\t\t\ttypes = [...normalized];\n\t\t}\n\t}\n\tlet tags: readonly string[] | undefined;\n\tif (input.tags !== undefined) {\n\t\tif (!Array.isArray(input.tags)) {\n\t\t\tthrow new MnemocyteError(\"tags must be an array.\", \"VALIDATION\");\n\t\t}\n\t\tconst normalized = new Set<string>();\n\t\tfor (const value of input.tags as readonly unknown[]) {\n\t\t\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"tags must contain only non-empty strings.\",\n\t\t\t\t\t\"VALIDATION\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tnormalized.add(value.trim());\n\t\t}\n\t\tif (normalized.size > 0) {\n\t\t\ttags = [...normalized];\n\t\t}\n\t}\n\tif (input.maxImportance !== undefined) {\n\t\tassertImportanceLevel(input.maxImportance, \"maxImportance\");\n\t}\n\tif (\n\t\tinput.signal !== undefined &&\n\t\t(typeof input.signal !== \"object\" ||\n\t\t\tinput.signal === null ||\n\t\t\ttypeof input.signal.aborted !== \"boolean\" ||\n\t\t\ttypeof input.signal.addEventListener !== \"function\" ||\n\t\t\ttypeof input.signal.removeEventListener !== \"function\")\n\t) {\n\t\tthrow new MnemocyteError(\"signal must be an AbortSignal.\", \"VALIDATION\");\n\t}\n\tconst filter: ValidatedPruneFilter = {\n\t\t...(input.entityId === undefined ? {} : { entityId: input.entityId }),\n\t\t...(input.expired === true ? { expired: true as const } : {}),\n\t\t...(input.superseded === true ? { superseded: true as const } : {}),\n\t\t...(input.createdBefore === undefined\n\t\t\t? {}\n\t\t\t: { createdBefore: new Date(input.createdBefore) }),\n\t\t...(input.notAccessedSince === undefined\n\t\t\t? {}\n\t\t\t: { notAccessedSince: new Date(input.notAccessedSince) }),\n\t\t...(types === undefined ? {} : { types }),\n\t\t...(tags === undefined ? {} : { tags }),\n\t\t...(input.maxImportance === undefined\n\t\t\t? {}\n\t\t\t: { maxImportance: input.maxImportance }),\n\t\tdryRun: input.dryRun === true,\n\t};\n\tassertPruneFilterHasSelector(filter);\n\treturn filter;\n}\n\n/**\n * Validate a {@link FindDuplicatesInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed `threshold` / `limit` values.\n */\nexport function validateFindDuplicatesInput(input: FindDuplicatesInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tif (input.threshold !== undefined) {\n\t\tif (\n\t\t\t!Number.isFinite(input.threshold) ||\n\t\t\tinput.threshold < 0 ||\n\t\t\tinput.threshold > 1\n\t\t) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t\"threshold must be a number between 0 and 1.\",\n\t\t\t\t\"VALIDATION\",\n\t\t\t);\n\t\t}\n\t}\n\tif (input.limit !== undefined) {\n\t\tassertLimit(input.limit);\n\t}\n\tif (input.types !== undefined) {\n\t\tassertMemoryTypeArray(input.types, \"types\");\n\t}\n}\n\n/**\n * Validate a {@link ConsolidateInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed inputs (empty `supersededIds`\n * a `survivorId` appearing in `supersededIds`, or duplicate loser IDs).\n */\nexport function validateConsolidateInput(input: ConsolidateInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tassertNonEmptyString(input.survivorId, \"survivorId\");\n\tif (input.supersededIds.length === 0) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"supersededIds must contain at least one memory id.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n\tif (input.supersededIds.includes(input.survivorId)) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"survivorId must not appear in supersededIds.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n\tconst seenIds = new Set<string>();\n\tfor (const id of input.supersededIds) {\n\t\tassertNonEmptyString(id, \"supersededIds[*]\");\n\t\tif (seenIds.has(id)) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t\"supersededIds must not contain duplicate memory ids.\",\n\t\t\t\t\"VALIDATION\",\n\t\t\t);\n\t\t}\n\t\tseenIds.add(id);\n\t}\n}\n\n/**\n * Validate a {@link ListAuditLogInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} when malformed.\n */\nexport function validateListAuditLogInput(input: ListAuditLogInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tif (input.limit !== undefined) {\n\t\tassertLimit(input.limit);\n\t}\n\tfor (const [field, cursor] of [\n\t\t[\"beforeCursor\", input.beforeCursor],\n\t\t[\"afterCursor\", input.afterCursor],\n\t] as const) {\n\t\tif (cursor === undefined) {\n\t\t\tcontinue;\n\t\t}\n\t\tassertAuditLogCursor(cursor, field);\n\t}\n}\n\nfunction assertAuditLogCursor(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is AuditLogCursor {\n\tif (typeof value !== \"object\" || value === null) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be an audit-log cursor.`,\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n\tconst cursor = value as { id?: unknown; timestamp?: unknown };\n\tassertValidDate(cursor.timestamp, `${field}.timestamp`);\n\tassertNonEmptyString(cursor.id, `${field}.id`);\n}\n","import { buildContext } from \"../context/builder.js\";\nimport { MnemocyteError } from \"../errors.js\";\nimport { observe, observePrepared } from \"../observability.js\";\nimport { throwIfAborted } from \"../resilience.js\";\nimport {\n\tcosineSimilarity,\n\tcreateLexicalScorer,\n\tcreateScoringConfig,\n\tDEFAULT_CANDIDATE_MULTIPLIER,\n\ttoScoredMemoryWithConfig,\n\ttoVectorScore,\n} from \"../retrieval/scorer.js\";\nimport type {\n\tAuditEvent,\n\tConsolidateInput,\n\tConsolidateResult,\n\tDuplicatePair,\n\tJsonObject,\n\tMemory,\n\tMemoryWithScore,\n\tMnemocyteClient,\n\tMnemocyteConfig,\n\tMnemocyteOperation,\n\tRecallInput,\n\tRememberInput,\n\tRememberManyInput,\n} from \"../types.js\";\nimport {\n\tDEFAULT_IMPORTANCE,\n\tDEFAULT_LIMIT,\n\tDEFAULT_MIN_SCORE,\n\tDEFAULT_TYPE,\n} from \"./defaults.js\";\nimport { embedMany, embedOne } from \"./embeddings.js\";\nimport { cloneJsonObject } from \"./json.js\";\nimport {\n\tcloneMemory,\n\tcreateEventId,\n\tcreateId,\n\tnormalizeTags,\n} from \"./records.js\";\nimport type {\n\tMemoryStore,\n\tStorePruneEntityDeletion,\n\tStorePruneResult,\n} from \"./store.js\";\nimport {\n\tassertLimit,\n\tassertMinScore,\n\tassertNonEmptyString,\n\tcontextInputToRecallInput,\n\ttype PreparedRememberInput,\n\tvalidateBuildContextInput,\n\tvalidateConsolidateInput,\n\tvalidateFindDuplicatesInput,\n\tvalidateListAuditLogInput,\n\tvalidatePruneInput,\n\tvalidateRecallInput,\n\tvalidateRememberInput,\n} from \"./validation.js\";\n\ninterface ScoredCandidate {\n\tmemory: Memory;\n\tvectorScore: number;\n\tlexicalScore: number;\n}\n\ninterface OperationMetadata {\n\tentityId?: string;\n\tmemoryId?: string;\n\tcount?: number;\n}\n\nfunction isPositionalRememberManyInput(\n\tinput: RememberManyInput | readonly RememberInput[],\n): input is readonly RememberInput[] {\n\treturn Array.isArray(input);\n}\n\nfunction providerOptions(\n\tconfig: MnemocyteConfig,\n\tsignal: AbortSignal | undefined,\n) {\n\treturn {\n\t\t...(signal === undefined ? {} : { signal }),\n\t\t...(config.provider === undefined ? {} : { resilience: config.provider }),\n\t};\n}\n\nfunction storeOptions(signal: AbortSignal | undefined) {\n\treturn signal === undefined ? undefined : { signal };\n}\n\nfunction snapshotRememberInput(input: RememberInput): PreparedRememberInput {\n\treturn {\n\t\t...input,\n\t\t...(input.tags === undefined\n\t\t\t? {}\n\t\t\t: { tags: Array.isArray(input.tags) ? [...input.tags] : input.tags }),\n\t\tmetadata: cloneJsonObject(input.metadata ?? {}),\n\t\t...(input.expiresAt === undefined\n\t\t\t? {}\n\t\t\t: {\n\t\t\t\t\texpiresAt:\n\t\t\t\t\t\tinput.expiresAt instanceof Date\n\t\t\t\t\t\t\t? new Date(input.expiresAt)\n\t\t\t\t\t\t\t: input.expiresAt,\n\t\t\t\t}),\n\t};\n}\n\nfunction createStoredMemory(\n\tconfig: MnemocyteConfig,\n\tinput: PreparedRememberInput,\n\tembedding: number[],\n\tnow: Date,\n) {\n\treturn {\n\t\tid: createId(),\n\t\tentityId: input.entityId,\n\t\tcontent: input.content,\n\t\ttype: input.type ?? DEFAULT_TYPE,\n\t\timportance: input.importance ?? DEFAULT_IMPORTANCE,\n\t\ttags: normalizeTags(input.tags),\n\t\tsource: input.source ?? null,\n\t\tmetadata: input.metadata,\n\t\tconfidence: input.confidence ?? 1,\n\t\tembeddingModel: config.embedder.model,\n\t\tembeddingDimensions: config.embedder.dimensions,\n\t\tsupersededBy: null,\n\t\tsupersededAt: null,\n\t\texpiresAt: input.expiresAt ?? null,\n\t\tlastAccessedAt: null,\n\t\taccessCount: 0,\n\t\tcreatedAt: now,\n\t\tupdatedAt: now,\n\t\tembedding,\n\t};\n}\n\nfunction auditEvent(\n\tentityId: string,\n\tdescription: string,\n\tmetadata: JsonObject,\n\ttimestamp = new Date(),\n): AuditEvent {\n\treturn {\n\t\tid: createEventId(),\n\t\tentityId,\n\t\tdescription,\n\t\tmetadata,\n\t\ttimestamp,\n\t};\n}\n\nfunction normalizeStoreRows<T extends { id: string }>(\n\texpected: readonly { id: string }[],\n\treturned: readonly T[],\n\toperation: string,\n): T[] {\n\tconst expectedIds = new Set(expected.map((memory) => memory.id));\n\tconst returnedById = new Map<string, T>();\n\n\tfor (const row of returned) {\n\t\tif (!expectedIds.has(row.id)) {\n\t\t\tthrow new MnemocyteError(`${operation} returned an unknown ID.`, \"DB\");\n\t\t}\n\t\tif (returnedById.has(row.id)) {\n\t\t\tthrow new MnemocyteError(`${operation} returned a duplicate ID.`, \"DB\");\n\t\t}\n\t\treturnedById.set(row.id, row);\n\t}\n\n\treturn expected.map((row) => {\n\t\tconst returnedRow = returnedById.get(row.id);\n\t\tif (!returnedRow) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`${operation} did not return every requested ID.`,\n\t\t\t\t\"DB\",\n\t\t\t);\n\t\t}\n\t\treturn returnedRow;\n\t});\n}\n\nfunction normalizePruneEntityDeletions(\n\tresult: StorePruneResult,\n\texpectedEntityId: string | undefined,\n): StorePruneEntityDeletion[] {\n\tconst seenEntityIds = new Set<string>();\n\tlet detailedDeletedCount = 0;\n\n\tfor (const detail of result.deletedByEntity) {\n\t\tif (\n\t\t\tdetail.entityId.length === 0 ||\n\t\t\t!Number.isInteger(detail.deletedCount) ||\n\t\t\tdetail.deletedCount <= 0 ||\n\t\t\tseenEntityIds.has(detail.entityId) ||\n\t\t\t(expectedEntityId !== undefined && detail.entityId !== expectedEntityId)\n\t\t) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t\"Memory prune returned invalid per-entity deletion details.\",\n\t\t\t\t\"DB\",\n\t\t\t);\n\t\t}\n\t\tseenEntityIds.add(detail.entityId);\n\t\tdetailedDeletedCount += detail.deletedCount;\n\t}\n\n\tif (\n\t\tdetailedDeletedCount !== result.deletedCount ||\n\t\t(result.dryRun && result.deletedByEntity.length > 0)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Memory prune deletion details did not match the deleted count.\",\n\t\t\t\"DB\",\n\t\t);\n\t}\n\n\treturn [...result.deletedByEntity].sort((a, b) =>\n\t\ta.entityId.localeCompare(b.entityId),\n\t);\n}\n\nfunction toDuplicatePair(pair: {\n\ta: Memory;\n\tb: Memory;\n\tsimilarity: number;\n}): DuplicatePair {\n\treturn {\n\t\ta: cloneMemory(pair.a),\n\t\tb: cloneMemory(pair.b),\n\t\tsimilarity: Math.max(0, Math.min(1, pair.similarity)),\n\t};\n}\n\nexport function createMemoryClient(\n\tconfig: MnemocyteConfig,\n\tstore: MemoryStore,\n): MnemocyteClient {\n\ttype ClientState = \"open\" | \"closing\" | \"closed\";\n\n\tlet state: ClientState = \"open\";\n\tlet activeOperations = 0;\n\tlet operationsDrainedPromise: Promise<void> | undefined;\n\tlet resolveOperationsDrained: (() => void) | undefined;\n\tlet closePromise: Promise<void> | undefined;\n\n\tfunction assertOpen(): void {\n\t\tif (state === \"closed\") {\n\t\t\tthrow new MnemocyteError(\"Mnemocyte client is closed.\", \"DB\");\n\t\t}\n\t}\n\n\tfunction beginOperation(): () => void {\n\t\tif (state !== \"open\") {\n\t\t\tthrow new MnemocyteError(\"Mnemocyte client is closed.\", \"DB\");\n\t\t}\n\t\tactiveOperations += 1;\n\t\tlet completed = false;\n\t\treturn () => {\n\t\t\tif (completed) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcompleted = true;\n\t\t\tactiveOperations -= 1;\n\t\t\tif (activeOperations === 0 && resolveOperationsDrained) {\n\t\t\t\tconst resolve = resolveOperationsDrained;\n\t\t\t\tresolveOperationsDrained = undefined;\n\t\t\t\toperationsDrainedPromise = undefined;\n\t\t\t\tresolve();\n\t\t\t}\n\t\t};\n\t}\n\n\tfunction runOperation<T>(\n\t\toperationName: MnemocyteOperation,\n\t\tmetadata: OperationMetadata,\n\t\toperation: () => Promise<T>,\n\t): Promise<T> {\n\t\tlet complete: () => void;\n\t\ttry {\n\t\t\tcomplete = beginOperation();\n\t\t} catch (error) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\toperationName,\n\t\t\t\tmetadata,\n\t\t\t\tasync () => {\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\ttry {\n\t\t\treturn operation().then(\n\t\t\t\t(result) => {\n\t\t\t\t\tcomplete();\n\t\t\t\t\treturn result;\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tcomplete();\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tcomplete();\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t}\n\n\tfunction waitForActiveOperations(): Promise<void> {\n\t\tif (activeOperations === 0) {\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (!operationsDrainedPromise) {\n\t\t\toperationsDrainedPromise = new Promise<void>((resolve) => {\n\t\t\t\tresolveOperationsDrained = resolve;\n\t\t\t});\n\t\t}\n\t\treturn operationsDrainedPromise;\n\t}\n\n\tasync function ensureSchema(): Promise<void> {\n\t\tawait store.ensureSchema();\n\t}\n\n\tasync function ensureEmbeddingCompatibility(): Promise<void> {\n\t\tawait store.ensureEmbeddingCompatibility(config.embedder);\n\t}\n\n\tasync function recordAudit(events: readonly AuditEvent[]): Promise<void> {\n\t\tif (events.length === 0 || config.audit?.enabled !== true) {\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tawait store.addAuditEvents(events);\n\t\t} catch {\n\t\t\t// Audit writes must not break the primary operation.\n\t\t}\n\t}\n\n\tfunction remember(input: RememberInput): Promise<Memory> {\n\t\treturn runOperation(\"remember\", { entityId: input.entityId }, () =>\n\t\t\tobservePrepared(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"remember\",\n\t\t\t\t{ entityId: input.entityId },\n\t\t\t\t() => snapshotRememberInput(input),\n\t\t\t\tasync (preparedInput) => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tvalidateRememberInput(preparedInput);\n\t\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\t\tconst embedding = await embedOne(\n\t\t\t\t\t\tconfig.embedder,\n\t\t\t\t\t\tpreparedInput.content,\n\t\t\t\t\t\tproviderOptions(config, preparedInput.signal),\n\t\t\t\t\t);\n\t\t\t\t\tconst stored = [\n\t\t\t\t\t\tcreateStoredMemory(config, preparedInput, embedding, new Date()),\n\t\t\t\t\t];\n\t\t\t\t\tconst [memory] = normalizeStoreRows(\n\t\t\t\t\t\tstored,\n\t\t\t\t\t\tawait store.insertMemories(stored),\n\t\t\t\t\t\t\"Memory insert\",\n\t\t\t\t\t);\n\t\t\t\t\tif (!memory) {\n\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\"Memory insert did not return the inserted ID.\",\n\t\t\t\t\t\t\t\"DB\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tawait recordAudit([\n\t\t\t\t\t\tauditEvent(memory.entityId, \"memory.created\", {\n\t\t\t\t\t\t\tmemoryId: memory.id,\n\t\t\t\t\t\t\ttype: memory.type,\n\t\t\t\t\t\t\timportance: memory.importance,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]);\n\t\t\t\t\treturn memory;\n\t\t\t\t},\n\t\t\t\t(memory) => ({ memoryId: memory.id, count: 1 }),\n\t\t\t),\n\t\t);\n\t}\n\n\tfunction rememberMany(\n\t\tinput: RememberManyInput | readonly RememberInput[],\n\t): Promise<Memory[]> {\n\t\tconst count = isPositionalRememberManyInput(input)\n\t\t\t? input.length\n\t\t\t: input.inputs.length;\n\t\treturn runOperation(\"rememberMany\", { count }, () =>\n\t\t\tobservePrepared(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"rememberMany\",\n\t\t\t\t{ count },\n\t\t\t\t() => {\n\t\t\t\t\tconst positional = isPositionalRememberManyInput(input);\n\t\t\t\t\tconst inputs = positional ? input : input.inputs;\n\t\t\t\t\treturn {\n\t\t\t\t\t\tpreparedInputs: inputs.map(snapshotRememberInput),\n\t\t\t\t\t\tsignal: positional ? input[0]?.signal : input.signal,\n\t\t\t\t\t};\n\t\t\t\t},\n\t\t\t\tasync ({ preparedInputs, signal }) => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tif (preparedInputs.length === 0) {\n\t\t\t\t\t\treturn [];\n\t\t\t\t\t}\n\t\t\t\t\tfor (const item of preparedInputs) {\n\t\t\t\t\t\tvalidateRememberInput(item);\n\t\t\t\t\t}\n\t\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\t\tconst embeddings = await embedMany(\n\t\t\t\t\t\tconfig.embedder,\n\t\t\t\t\t\tpreparedInputs.map((item) => item.content),\n\t\t\t\t\t\tproviderOptions(config, signal),\n\t\t\t\t\t);\n\t\t\t\t\tconst now = new Date();\n\t\t\t\t\tconst stored = preparedInputs.map((item, idx) =>\n\t\t\t\t\t\tcreateStoredMemory(config, item, embeddings[idx] as number[], now),\n\t\t\t\t\t);\n\t\t\t\t\tconst memories = normalizeStoreRows(\n\t\t\t\t\t\tstored,\n\t\t\t\t\t\tawait store.insertMemories(stored),\n\t\t\t\t\t\t\"Memory insert\",\n\t\t\t\t\t);\n\t\t\t\t\tawait recordAudit(\n\t\t\t\t\t\tmemories.map((memory) =>\n\t\t\t\t\t\t\tauditEvent(memory.entityId, \"memory.created\", {\n\t\t\t\t\t\t\t\tmemoryId: memory.id,\n\t\t\t\t\t\t\t\ttype: memory.type,\n\t\t\t\t\t\t\t\timportance: memory.importance,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t),\n\t\t\t\t\t);\n\t\t\t\t\treturn memories;\n\t\t\t\t},\n\t\t\t\t(result) => ({ count: result.length }),\n\t\t\t),\n\t\t);\n\t}\n\n\tfunction recall(input: RecallInput): Promise<MemoryWithScore[]> {\n\t\treturn observe(\n\t\t\tconfig,\n\t\t\tstore.backend,\n\t\t\t\"recall\",\n\t\t\t{ entityId: input.entityId },\n\t\t\tasync () => {\n\t\t\t\tassertOpen();\n\t\t\t\tvalidateRecallInput(input);\n\t\t\t\tconst limit = input.limit ?? config.defaults?.limit ?? DEFAULT_LIMIT;\n\t\t\t\tconst minScore =\n\t\t\t\t\tinput.minScore ?? config.defaults?.minScore ?? DEFAULT_MIN_SCORE;\n\t\t\t\tassertLimit(limit);\n\t\t\t\tassertMinScore(minScore);\n\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\tconst queryEmbedding = await embedOne(\n\t\t\t\t\tconfig.embedder,\n\t\t\t\t\tinput.query,\n\t\t\t\t\tproviderOptions(config, input.signal),\n\t\t\t\t);\n\t\t\t\tconst candidateMultiplier =\n\t\t\t\t\tconfig.retrieval?.candidateMultiplier ?? DEFAULT_CANDIDATE_MULTIPLIER;\n\t\t\t\tconst candidateLimit = Math.max(limit, limit * candidateMultiplier);\n\t\t\t\tconst scoreLexical = createLexicalScorer(input.query);\n\t\t\t\tconst scoringConfig = createScoringConfig(config.retrieval);\n\t\t\t\tconst [vectorCandidates, lexicalCandidates] = await Promise.all([\n\t\t\t\t\tstore.vectorSearch({\n\t\t\t\t\t\t...input,\n\t\t\t\t\t\tembedding: queryEmbedding,\n\t\t\t\t\t\tlimit: candidateLimit,\n\t\t\t\t\t\tminVectorScore: 0,\n\t\t\t\t\t}),\n\t\t\t\t\tstore.lexicalSearch({ ...input, limit: candidateLimit }),\n\t\t\t\t]);\n\t\t\t\tconst merged = new Map<string, ScoredCandidate>();\n\t\t\t\tfor (const candidate of vectorCandidates) {\n\t\t\t\t\tmerged.set(candidate.memory.id, {\n\t\t\t\t\t\tmemory: candidate.memory,\n\t\t\t\t\t\tvectorScore: candidate.vectorScore,\n\t\t\t\t\t\tlexicalScore: scoreLexical(candidate.memory.content),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst lexicalOnly = lexicalCandidates.filter(\n\t\t\t\t\t(candidate) => !merged.has(candidate.memory.id),\n\t\t\t\t);\n\t\t\t\tconst lexicalOnlyEmbeddings = await store.getMemoryEmbeddings(\n\t\t\t\t\tlexicalOnly.map((candidate) => candidate.memory.id),\n\t\t\t\t);\n\t\t\t\tfor (const candidate of lexicalCandidates) {\n\t\t\t\t\tconst existing = merged.get(candidate.memory.id);\n\t\t\t\t\tif (existing) {\n\t\t\t\t\t\texisting.lexicalScore = candidate.lexicalScore;\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst embedding = lexicalOnlyEmbeddings.get(candidate.memory.id);\n\t\t\t\t\tconst similarity = embedding\n\t\t\t\t\t\t? cosineSimilarity(embedding, queryEmbedding)\n\t\t\t\t\t\t: 0;\n\t\t\t\t\tmerged.set(candidate.memory.id, {\n\t\t\t\t\t\tmemory: candidate.memory,\n\t\t\t\t\t\tvectorScore: toVectorScore(similarity),\n\t\t\t\t\t\tlexicalScore: candidate.lexicalScore,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst scored: MemoryWithScore[] = Array.from(merged.values())\n\t\t\t\t\t.map((entry) =>\n\t\t\t\t\t\ttoScoredMemoryWithConfig(\n\t\t\t\t\t\t\tentry.memory,\n\t\t\t\t\t\t\tMath.max(0, entry.vectorScore),\n\t\t\t\t\t\t\tMath.max(0, entry.lexicalScore),\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tscoringConfig,\n\t\t\t\t\t\t),\n\t\t\t\t\t)\n\t\t\t\t\t.filter((memory) => memory.score >= minScore)\n\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t.slice(0, limit);\n\t\t\t\tconst accessUpdates = normalizeStoreRows(\n\t\t\t\t\tscored,\n\t\t\t\t\tawait store.markMemoriesAccessed(scored.map((memory) => memory.id)),\n\t\t\t\t\t\"Memory access update\",\n\t\t\t\t);\n\t\t\t\treturn scored.map((memory, index) => {\n\t\t\t\t\tconst update = accessUpdates[index];\n\t\t\t\t\tif (!update) {\n\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\"Memory access update did not return every requested ID.\",\n\t\t\t\t\t\t\t\"DB\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\treturn {\n\t\t\t\t\t\t...memory,\n\t\t\t\t\t\tlastAccessedAt: new Date(update.lastAccessedAt),\n\t\t\t\t\t\taccessCount: update.accessCount,\n\t\t\t\t\t\tupdatedAt: new Date(update.updatedAt),\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t},\n\t\t\t(result) => ({ count: result.length }),\n\t\t);\n\t}\n\n\tconst client: MnemocyteClient = {\n\t\tremember,\n\t\trememberMany,\n\t\trecall(input) {\n\t\t\treturn runOperation(\"recall\", { entityId: input.entityId }, () =>\n\t\t\t\trecall(input),\n\t\t\t);\n\t\t},\n\t\tbuildContext(input) {\n\t\t\treturn runOperation(\"buildContext\", { entityId: input.entityId }, () =>\n\t\t\t\tobserve(\n\t\t\t\t\tconfig,\n\t\t\t\t\tstore.backend,\n\t\t\t\t\t\"buildContext\",\n\t\t\t\t\t{ entityId: input.entityId },\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\tvalidateBuildContextInput(input);\n\t\t\t\t\t\treturn buildContext({\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\trecall: (contextInput) => {\n\t\t\t\t\t\t\t\tconst recallInput = contextInputToRecallInput(contextInput);\n\t\t\t\t\t\t\t\treturn recall(\n\t\t\t\t\t\t\t\t\tinput.signal === undefined\n\t\t\t\t\t\t\t\t\t\t? recallInput\n\t\t\t\t\t\t\t\t\t\t: { ...recallInput, signal: input.signal },\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tforget(input) {\n\t\t\treturn runOperation(\n\t\t\t\t\"forget\",\n\t\t\t\t{ entityId: input.entityId, memoryId: input.memoryId },\n\t\t\t\t() =>\n\t\t\t\t\tobserve(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tstore.backend,\n\t\t\t\t\t\t\"forget\",\n\t\t\t\t\t\t{ entityId: input.entityId, memoryId: input.memoryId },\n\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t\t\t\t\t\t\tassertNonEmptyString(input.memoryId, \"memoryId\");\n\t\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\t\tconst deleted = await store.deleteMemory(\n\t\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t\t\tinput.memoryId,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (!deleted) {\n\t\t\t\t\t\t\t\tthrow new MnemocyteError(\"Memory was not found.\", \"NOT_FOUND\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tawait recordAudit([\n\t\t\t\t\t\t\t\tauditEvent(input.entityId, \"memory.deleted\", {\n\t\t\t\t\t\t\t\t\tmemoryId: input.memoryId,\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t]);\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tforgetAll(input) {\n\t\t\treturn runOperation(\"forgetAll\", { entityId: input.entityId }, () =>\n\t\t\t\tobserve(\n\t\t\t\t\tconfig,\n\t\t\t\t\tstore.backend,\n\t\t\t\t\t\"forgetAll\",\n\t\t\t\t\t{ entityId: input.entityId },\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\tconst deletedCount = await store.deleteMemoriesForEntity(\n\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tawait recordAudit([\n\t\t\t\t\t\t\tauditEvent(input.entityId, \"entity.cleared\", {\n\t\t\t\t\t\t\t\tcount: deletedCount,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t]);\n\t\t\t\t\t\treturn deletedCount;\n\t\t\t\t\t},\n\t\t\t\t\t(count) => ({ count }),\n\t\t\t\t).then(() => undefined),\n\t\t\t);\n\t\t},\n\t\tprune(input) {\n\t\t\treturn runOperation(\n\t\t\t\t\"prune\",\n\t\t\t\tinput.entityId === undefined ? {} : { entityId: input.entityId },\n\t\t\t\t() =>\n\t\t\t\t\tobserve(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tstore.backend,\n\t\t\t\t\t\t\"prune\",\n\t\t\t\t\t\tinput.entityId === undefined ? {} : { entityId: input.entityId },\n\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\t\tthrowIfAborted(input.signal);\n\t\t\t\t\t\t\tconst filter = validatePruneInput(input);\n\t\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\t\tconst result = await store.prune(\n\t\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tconst deletedByEntity = normalizePruneEntityDeletions(\n\t\t\t\t\t\t\t\tresult,\n\t\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\tif (result.deletedCount > 0 && result.dryRun === false) {\n\t\t\t\t\t\t\t\tawait recordAudit(\n\t\t\t\t\t\t\t\t\tdeletedByEntity.map((detail) =>\n\t\t\t\t\t\t\t\t\t\tauditEvent(detail.entityId, \"memory.pruned\", {\n\t\t\t\t\t\t\t\t\t\t\tcount: detail.deletedCount,\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tmatchedCount: result.matchedCount,\n\t\t\t\t\t\t\t\tdeletedCount: result.deletedCount,\n\t\t\t\t\t\t\t\tdryRun: result.dryRun,\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t},\n\t\t\t\t\t\t(result) => ({ count: result.deletedCount }),\n\t\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tfindDuplicates(input) {\n\t\t\treturn runOperation(\"findDuplicates\", { entityId: input.entityId }, () =>\n\t\t\t\tobserve(\n\t\t\t\t\tconfig,\n\t\t\t\t\tstore.backend,\n\t\t\t\t\t\"findDuplicates\",\n\t\t\t\t\t{ entityId: input.entityId },\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\tthrowIfAborted(input.signal);\n\t\t\t\t\t\tvalidateFindDuplicatesInput(input);\n\t\t\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\t\t\tconst pairs = await store.findDuplicatePairs(\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn pairs.map(toDuplicatePair);\n\t\t\t\t\t},\n\t\t\t\t\t(result) => ({ count: result.length }),\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tlistAuditLog(input) {\n\t\t\treturn runOperation(\"listAuditLog\", { entityId: input.entityId }, () =>\n\t\t\t\tobserve(\n\t\t\t\t\tconfig,\n\t\t\t\t\tstore.backend,\n\t\t\t\t\t\"listAuditLog\",\n\t\t\t\t\t{ entityId: input.entityId },\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\tthrowIfAborted(input.signal);\n\t\t\t\t\t\tvalidateListAuditLogInput(input);\n\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\tconst events = await store.listAuditLog(\n\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn events;\n\t\t\t\t\t},\n\t\t\t\t\t(result) => ({ count: result.length }),\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tstats(input) {\n\t\t\treturn runOperation(\n\t\t\t\t\"stats\",\n\t\t\t\tinput?.entityId ? { entityId: input.entityId } : {},\n\t\t\t\t() =>\n\t\t\t\t\tobserve(\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tstore.backend,\n\t\t\t\t\t\t\"stats\",\n\t\t\t\t\t\tinput?.entityId ? { entityId: input.entityId } : {},\n\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\t\treturn store.stats(input, new Date());\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\texperimental: {\n\t\t\tconsolidate(input: ConsolidateInput): Promise<ConsolidateResult> {\n\t\t\t\treturn runOperation(\n\t\t\t\t\t\"consolidate\",\n\t\t\t\t\t{ entityId: input.entityId, memoryId: input.survivorId },\n\t\t\t\t\t() =>\n\t\t\t\t\t\tobserve(\n\t\t\t\t\t\t\tconfig,\n\t\t\t\t\t\t\tstore.backend,\n\t\t\t\t\t\t\t\"consolidate\",\n\t\t\t\t\t\t\t{ entityId: input.entityId, memoryId: input.survivorId },\n\t\t\t\t\t\t\tasync () => {\n\t\t\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\t\t\tthrowIfAborted(input.signal);\n\t\t\t\t\t\t\t\tvalidateConsolidateInput(input);\n\t\t\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\t\t\tconst survivor = await store.getMemory(\n\t\t\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t\t\t\tinput.survivorId,\n\t\t\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tthrowIfAborted(input.signal);\n\t\t\t\t\t\t\t\tif (!survivor) {\n\t\t\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\t\t\"Survivor memory was not found.\",\n\t\t\t\t\t\t\t\t\t\t\"NOT_FOUND\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (survivor.supersededBy !== null) {\n\t\t\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\t\t\"Survivor memory is itself superseded.\",\n\t\t\t\t\t\t\t\t\t\t\"VALIDATION\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst targets = await store.loadConsolidationTargets(\n\t\t\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t\t\t\tinput.supersededIds,\n\t\t\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tthrowIfAborted(input.signal);\n\t\t\t\t\t\t\t\tconst foundIds = new Set(targets.map((target) => target.id));\n\t\t\t\t\t\t\t\tfor (const id of input.supersededIds) {\n\t\t\t\t\t\t\t\t\tif (!foundIds.has(id)) {\n\t\t\t\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\t\t\t\"Superseded memory was not found.\",\n\t\t\t\t\t\t\t\t\t\t\t\"NOT_FOUND\",\n\t\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (\n\t\t\t\t\t\t\t\t\ttargets.some(\n\t\t\t\t\t\t\t\t\t\t(target) =>\n\t\t\t\t\t\t\t\t\t\t\ttarget.supersededBy !== null &&\n\t\t\t\t\t\t\t\t\t\t\ttarget.supersededBy !== survivor.id,\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t) {\n\t\t\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\t\t\"Superseded memory already belongs to a different survivor.\",\n\t\t\t\t\t\t\t\t\t\t\"CONFLICT\",\n\t\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst losers = targets.filter(\n\t\t\t\t\t\t\t\t\t(target) => target.supersededBy === null,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tif (losers.length === 0) {\n\t\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\t\t\t\tsupersededCount: 0,\n\t\t\t\t\t\t\t\t\t\tsupersededIds: [],\n\t\t\t\t\t\t\t\t\t} satisfies ConsolidateResult;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst result = await store.consolidate(\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\t\t\t\tsupersededIds: input.supersededIds,\n\t\t\t\t\t\t\t\t\t\tmergeTags: input.mergeTags !== false,\n\t\t\t\t\t\t\t\t\t\tnow: new Date(),\n\t\t\t\t\t\t\t\t\t\tauditEnabled: config.audit?.enabled === true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\t\t\tsupersededCount: result.supersededIds.length,\n\t\t\t\t\t\t\t\t\tsupersededIds: result.supersededIds,\n\t\t\t\t\t\t\t\t} satisfies ConsolidateResult;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t(result) => ({ count: result.supersededCount }),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tclose() {\n\t\t\tif (closePromise) {\n\t\t\t\treturn closePromise;\n\t\t\t}\n\t\t\tstate = \"closing\";\n\t\t\tclosePromise = observe(config, store.backend, \"close\", {}, async () => {\n\t\t\t\tawait waitForActiveOperations();\n\t\t\t\ttry {\n\t\t\t\t\tawait store.close();\n\t\t\t\t\tstate = \"closed\";\n\t\t\t\t} catch (error) {\n\t\t\t\t\tstate = \"open\";\n\t\t\t\t\tclosePromise = undefined;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn closePromise;\n\t\t},\n\t};\n\n\treturn client;\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);\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YAAqB;CAC3B,IACC,OAAO,cAAc,YACrB,cAAc,QACd,EAAE,uBAAuB,YAEzB,MAAM,IAAI,eACT,iEACA,QACD;CAGD,OAAQ,UAAwC;AACjD"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { D as MnemocyteStoreConfig } from "../types-XUWYDoXM.mjs";
|
|
2
|
+
import { PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
|
3
|
+
|
|
4
|
+
//#region src/stores/drizzle.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* Wrap a caller-owned postgres.js Drizzle instance for
|
|
7
|
+
* {@link MnemocyteConfig.store}.
|
|
8
|
+
*
|
|
9
|
+
* The Mnemocyte tables must already exist in the public schema through the
|
|
10
|
+
* bundled migrations. Closing the Mnemocyte client does not close the supplied
|
|
11
|
+
* Drizzle instance or its underlying postgres.js client.
|
|
12
|
+
*
|
|
13
|
+
* @param db - A Drizzle instance created with `drizzle-orm/postgres-js`.
|
|
14
|
+
*/
|
|
15
|
+
declare function drizzleStore<TSchema extends Record<string, unknown>>(db: PostgresJsDatabase<TSchema>): MnemocyteStoreConfig;
|
|
16
|
+
//#endregion
|
|
17
|
+
export { drizzleStore };
|
|
18
|
+
//# sourceMappingURL=drizzle.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drizzle.d.mts","names":[],"sources":["../../src/stores/drizzle.ts"],"mappings":";;;;;;AAgBA;;;;;;;;iBAAgB,YAAA,iBAA6B,MAAA,kBAAA,CAC5C,EAAA,EAAI,kBAAA,CAAmB,OAAA,IACrB,oBAAA"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { n as createCallerOwnedDatabaseHandle, t as createPostgresStore } from "../postgres-BHQ1pj16.mjs";
|
|
2
|
+
import { t as createMnemocyteStoreConfig } from "../store-config-BFFTm1sj.mjs";
|
|
3
|
+
//#region src/stores/drizzle.ts
|
|
4
|
+
/**
|
|
5
|
+
* Wrap a caller-owned postgres.js Drizzle instance for
|
|
6
|
+
* {@link MnemocyteConfig.store}.
|
|
7
|
+
*
|
|
8
|
+
* The Mnemocyte tables must already exist in the public schema through the
|
|
9
|
+
* bundled migrations. Closing the Mnemocyte client does not close the supplied
|
|
10
|
+
* Drizzle instance or its underlying postgres.js client.
|
|
11
|
+
*
|
|
12
|
+
* @param db - A Drizzle instance created with `drizzle-orm/postgres-js`.
|
|
13
|
+
*/
|
|
14
|
+
function drizzleStore(db) {
|
|
15
|
+
return createMnemocyteStoreConfig(createPostgresStore(createCallerOwnedDatabaseHandle(db)));
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
export { drizzleStore };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=drizzle.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"drizzle.mjs","names":[],"sources":["../../src/stores/drizzle.ts"],"sourcesContent":["import type { PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport { createCallerOwnedDatabaseHandle } from \"../db/index.js\";\nimport { createPostgresStore } from \"../memory/postgres.js\";\nimport { createMnemocyteStoreConfig } from \"../memory/store-config.js\";\nimport type { MnemocyteStoreConfig } from \"../types.js\";\n\n/**\n * Wrap a caller-owned postgres.js Drizzle instance for\n * {@link MnemocyteConfig.store}.\n *\n * The Mnemocyte tables must already exist in the public schema through the\n * bundled migrations. Closing the Mnemocyte client does not close the supplied\n * Drizzle instance or its underlying postgres.js client.\n *\n * @param db - A Drizzle instance created with `drizzle-orm/postgres-js`.\n */\nexport function drizzleStore<TSchema extends Record<string, unknown>>(\n\tdb: PostgresJsDatabase<TSchema>,\n): MnemocyteStoreConfig {\n\treturn createMnemocyteStoreConfig(\n\t\tcreatePostgresStore(createCallerOwnedDatabaseHandle(db)),\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAgB,aACf,IACuB;CACvB,OAAO,2BACN,oBAAoB,gCAAgC,EAAE,CAAC,CACxD;AACD"}
|