mnemocyte 0.5.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -177
- package/dist/embedders/index.mjs +1 -2
- package/dist/embedders/openai.d.mts +3 -8
- package/dist/embedders/openai.mjs +3 -4
- package/dist/embedders/openai.mjs.map +1 -1
- package/dist/{errors-DIPysVWl.mjs → errors-Dgt2nAs1.mjs} +2 -3
- package/dist/{errors-DIPysVWl.mjs.map → errors-Dgt2nAs1.mjs.map} +1 -1
- package/dist/index.d.mts +5 -11
- package/dist/index.mjs +947 -12
- package/dist/index.mjs.map +1 -1
- package/dist/{postgres-BHQ1pj16.mjs → postgres-BDti0rrm.mjs} +14 -23
- package/dist/{postgres-BHQ1pj16.mjs.map → postgres-BDti0rrm.mjs.map} +1 -1
- package/dist/{postgres-runtime-DxJxns07.mjs → postgres-runtime-51fQVwqa.mjs} +3 -4
- package/dist/{postgres-runtime-DxJxns07.mjs.map → postgres-runtime-51fQVwqa.mjs.map} +1 -1
- package/dist/store-config-BZ4J1hrM.mjs +304 -0
- package/dist/store-config-BZ4J1hrM.mjs.map +1 -0
- package/dist/stores/drizzle.d.mts +2 -7
- package/dist/stores/drizzle.mjs +3 -4
- package/dist/{types-XUWYDoXM.d.mts → types-DXYtLiOT.d.mts} +3 -4
- package/migrations/fresh-install.sql +43 -0
- package/package.json +23 -20
- package/dist/embedders/openai.d.mts.map +0 -1
- package/dist/index.d.mts.map +0 -1
- package/dist/store-config-BFFTm1sj.mjs +0 -1255
- package/dist/store-config-BFFTm1sj.mjs.map +0 -1
- package/dist/stores/drizzle.d.mts.map +0 -1
- package/dist/types-XUWYDoXM.d.mts.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/memory/filters.ts","../src/memory/in-memory.ts","../src/memory/lazy-postgres.ts","../src/client.ts"],"sourcesContent":["import type { FindDuplicatesInput, Memory, RecallInput } from \"../types.js\";\nimport { IMPORTANCE_RANK } from \"./defaults.js\";\nimport type { ValidatedPruneFilter } from \"./store.js\";\n\nexport function isExpired(memory: Memory, now: Date): boolean {\n\treturn (\n\t\tmemory.expiresAt !== null && memory.expiresAt.getTime() <= now.getTime()\n\t);\n}\n\n/**\n * Test whether `memory` matches a validated prune filter. All specified\n * selectors are AND-combined; unspecified selectors do not restrict.\n *\n * `now` is supplied by the caller so callers can share a consistent\n * timestamp across a batch.\n */\nexport function matchesPruneFilter(\n\tmemory: Memory,\n\tinput: ValidatedPruneFilter,\n\tnow: Date,\n): boolean {\n\tif (input.entityId !== undefined && memory.entityId !== input.entityId) {\n\t\treturn false;\n\t}\n\tif (input.expired === true && !isExpired(memory, now)) {\n\t\treturn false;\n\t}\n\tif (input.superseded === true && memory.supersededBy === null) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.createdBefore !== undefined &&\n\t\tmemory.createdAt.getTime() >= input.createdBefore.getTime()\n\t) {\n\t\treturn false;\n\t}\n\tif (input.notAccessedSince !== undefined) {\n\t\tconst last = memory.lastAccessedAt;\n\t\tif (last !== null && last.getTime() >= input.notAccessedSince.getTime()) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (input.types !== undefined && !input.types.includes(memory.type)) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.tags !== undefined &&\n\t\tinput.tags.length > 0 &&\n\t\t!input.tags.every((tag) => memory.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.maxImportance !== undefined &&\n\t\tIMPORTANCE_RANK[memory.importance] > IMPORTANCE_RANK[input.maxImportance]\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/**\n * Return `true` when a memory should participate in a duplicate scan,\n * given the filters on `input` and a shared `now` timestamp.\n */\nexport function matchesDuplicateFilter(\n\tmemory: Memory,\n\tinput: FindDuplicatesInput,\n\tnow: Date,\n): boolean {\n\tif (memory.entityId !== input.entityId) {\n\t\treturn false;\n\t}\n\tif (input.includeSuperseded !== true && memory.supersededBy !== null) {\n\t\treturn false;\n\t}\n\tif (input.includeExpired !== true && isExpired(memory, now)) {\n\t\treturn false;\n\t}\n\tif (input.types !== undefined && !input.types.includes(memory.type)) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.tags !== undefined &&\n\t\tinput.tags.length > 0 &&\n\t\t!input.tags.every((tag) => memory.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function matchesRecallFilter(\n\tmemory: Memory,\n\tinput: RecallInput,\n\tnow: Date,\n): boolean {\n\tif (memory.entityId !== input.entityId) {\n\t\treturn false;\n\t}\n\tif (!input.includeSuperseded && memory.supersededBy !== null) {\n\t\treturn false;\n\t}\n\tif (!input.includeExpired && isExpired(memory, now)) {\n\t\treturn false;\n\t}\n\tif (input.types && !input.types.includes(memory.type)) {\n\t\treturn false;\n\t}\n\tif (input.tags && !input.tags.every((tag) => memory.tags.includes(tag))) {\n\t\treturn false;\n\t}\n\tif (input.before && memory.createdAt >= input.before) {\n\t\treturn false;\n\t}\n\tif (input.after && memory.createdAt <= input.after) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport { throwIfAborted } from \"../resilience.js\";\nimport {\n\tcosineSimilarity,\n\tcreateLexicalScorer,\n\ttoVectorScore,\n} from \"../retrieval/scorer.js\";\nimport type {\n\tAuditEvent,\n\tEntityStats,\n\tGlobalStats,\n\tMemory,\n\tMnemocyteClient,\n\tMnemocyteConfig,\n} from \"../types.js\";\nimport { createMemoryClient } from \"./client-core.js\";\nimport {\n\tDEFAULT_AUDIT_LOG_LIMIT,\n\tDEFAULT_DUPLICATE_LIMIT,\n\tDEFAULT_DUPLICATE_THRESHOLD,\n} from \"./defaults.js\";\nimport { memoryHasDependentsError } from \"./deletion.js\";\nimport {\n\tisExpired,\n\tmatchesDuplicateFilter,\n\tmatchesPruneFilter,\n\tmatchesRecallFilter,\n} from \"./filters.js\";\nimport { cloneJsonObject } from \"./json.js\";\nimport { cloneMemory, createEventId, type StoredMemory } from \"./records.js\";\nimport {\n\tassertPruneFilterHasSelector,\n\ttype MemoryStore,\n\ttype StoreAccessUpdate,\n\ttype StoreConsolidateInput,\n\ttype StoreConsolidateResult,\n\ttype StoreDuplicatePair,\n\ttype StoreLexicalCandidate,\n\ttype StoreLexicalSearchInput,\n\ttype StorePruneEntityDeletion,\n\ttype StoreVectorCandidate,\n\ttype StoreVectorSearchInput,\n} from \"./store.js\";\n\nfunction cloneAuditEvent(event: AuditEvent): AuditEvent {\n\treturn {\n\t\tid: event.id,\n\t\tentityId: event.entityId,\n\t\tdescription: event.description,\n\t\tmetadata: cloneJsonObject(event.metadata),\n\t\ttimestamp: new Date(event.timestamp),\n\t};\n}\n\nfunction compareAuditPositions(\n\ta: { id: string; timestamp: Date },\n\tb: { id: string; timestamp: Date },\n): number {\n\tconst timestampDifference = a.timestamp.getTime() - b.timestamp.getTime();\n\tif (timestampDifference !== 0) {\n\t\treturn timestampDifference;\n\t}\n\tif (a.id === b.id) {\n\t\treturn 0;\n\t}\n\treturn a.id < b.id ? -1 : 1;\n}\n\nfunction assertNoDependentMemories(\n\tmemories: ReadonlyMap<string, StoredMemory>,\n\ttargetIds: ReadonlySet<string>,\n): void {\n\tfor (const memory of memories.values()) {\n\t\tif (memory.supersededBy !== null && targetIds.has(memory.supersededBy)) {\n\t\t\tthrow memoryHasDependentsError();\n\t\t}\n\t}\n}\n\nexport function createInMemoryStore(): MemoryStore {\n\tconst memories = new Map<string, StoredMemory>();\n\tconst auditLog: AuditEvent[] = [];\n\n\treturn {\n\t\tbackend: \"in-memory\",\n\t\tasync ensureSchema() {},\n\t\tasync ensureEmbeddingCompatibility() {},\n\t\tasync insertMemories(rows) {\n\t\t\tconst inserted: Memory[] = [];\n\t\t\tfor (const row of rows) {\n\t\t\t\tmemories.set(row.id, row);\n\t\t\t\tinserted.push(cloneMemory(row));\n\t\t\t}\n\t\t\treturn inserted;\n\t\t},\n\t\tasync vectorSearch(input: StoreVectorSearchInput) {\n\t\t\tconst now = new Date();\n\t\t\tconst minVectorScore = input.minVectorScore ?? 0;\n\t\t\treturn Array.from(memories.values())\n\t\t\t\t.filter((memory) => matchesRecallFilter(memory, input, now))\n\t\t\t\t.map((memory) => ({\n\t\t\t\t\tmemory: cloneMemory(memory),\n\t\t\t\t\tvectorScore: toVectorScore(\n\t\t\t\t\t\tcosineSimilarity(memory.embedding, input.embedding),\n\t\t\t\t\t),\n\t\t\t\t}))\n\t\t\t\t.filter((candidate) => candidate.vectorScore >= minVectorScore)\n\t\t\t\t.sort((a, b) => b.vectorScore - a.vectorScore)\n\t\t\t\t.slice(0, input.limit) satisfies StoreVectorCandidate[];\n\t\t},\n\t\tasync lexicalSearch(input: StoreLexicalSearchInput) {\n\t\t\tconst now = new Date();\n\t\t\tconst scoreLexical = createLexicalScorer(input.query);\n\t\t\treturn Array.from(memories.values())\n\t\t\t\t.filter((memory) => matchesRecallFilter(memory, input, now))\n\t\t\t\t.map((memory) => ({\n\t\t\t\t\tmemory: cloneMemory(memory),\n\t\t\t\t\tlexicalScore: scoreLexical(memory.content),\n\t\t\t\t}))\n\t\t\t\t.filter((candidate) => candidate.lexicalScore > 0)\n\t\t\t\t.sort((a, b) => b.lexicalScore - a.lexicalScore)\n\t\t\t\t.slice(0, input.limit) satisfies StoreLexicalCandidate[];\n\t\t},\n\t\tasync getMemoryEmbeddings(memoryIds) {\n\t\t\tconst result = new Map<string, number[]>();\n\t\t\tfor (const id of memoryIds) {\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (memory) {\n\t\t\t\t\tresult.set(id, [...memory.embedding]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\tasync markMemoriesAccessed(memoryIds) {\n\t\t\tconst now = new Date();\n\t\t\tconst updates: StoreAccessUpdate[] = [];\n\t\t\tfor (const id of memoryIds) {\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (memory) {\n\t\t\t\t\tmemory.lastAccessedAt = now;\n\t\t\t\t\tmemory.accessCount += 1;\n\t\t\t\t\tmemory.updatedAt = now;\n\t\t\t\t\tupdates.push({\n\t\t\t\t\t\tid: memory.id,\n\t\t\t\t\t\tlastAccessedAt: now,\n\t\t\t\t\t\taccessCount: memory.accessCount,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn updates;\n\t\t},\n\t\tasync deleteMemory(entityId, memoryId) {\n\t\t\tconst memory = memories.get(memoryId);\n\t\t\tif (!memory || memory.entityId !== entityId) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tassertNoDependentMemories(memories, new Set([memoryId]));\n\t\t\treturn memories.delete(memoryId);\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\tconst targetIds = new Set(\n\t\t\t\tArray.from(memories.values())\n\t\t\t\t\t.filter((memory) => memory.entityId === entityId)\n\t\t\t\t\t.map((memory) => memory.id),\n\t\t\t);\n\t\t\tassertNoDependentMemories(memories, targetIds);\n\t\t\tfor (const id of targetIds) {\n\t\t\t\tmemories.delete(id);\n\t\t\t}\n\t\t\treturn targetIds.size;\n\t\t},\n\t\tasync prune(input, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tassertPruneFilterHasSelector(input);\n\t\t\tconst now = new Date();\n\t\t\tconst matched: StoredMemory[] = [];\n\t\t\tfor (const memory of memories.values()) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tif (matchesPruneFilter(memory, input, now)) {\n\t\t\t\t\tmatched.push(memory);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst dryRun = input.dryRun === true;\n\t\t\tlet deletedByEntity: StorePruneEntityDeletion[] = [];\n\t\t\tif (!dryRun) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tassertNoDependentMemories(\n\t\t\t\t\tmemories,\n\t\t\t\t\tnew Set(matched.map((memory) => memory.id)),\n\t\t\t\t);\n\t\t\t\tconst deletedCounts = new Map<string, number>();\n\t\t\t\tfor (const memory of matched) {\n\t\t\t\t\tmemories.delete(memory.id);\n\t\t\t\t\tdeletedCounts.set(\n\t\t\t\t\t\tmemory.entityId,\n\t\t\t\t\t\t(deletedCounts.get(memory.entityId) ?? 0) + 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tdeletedByEntity = Array.from(\n\t\t\t\t\tdeletedCounts,\n\t\t\t\t\t([entityId, deletedCount]) => ({ entityId, deletedCount }),\n\t\t\t\t).sort((a, b) => a.entityId.localeCompare(b.entityId));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmatchedCount: matched.length,\n\t\t\t\tdeletedCount: dryRun ? 0 : matched.length,\n\t\t\t\tdryRun,\n\t\t\t\tdeletedByEntity,\n\t\t\t};\n\t\t},\n\t\tasync findDuplicatePairs(input, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst threshold = input.threshold ?? DEFAULT_DUPLICATE_THRESHOLD;\n\t\t\tconst limit = input.limit ?? DEFAULT_DUPLICATE_LIMIT;\n\t\t\tconst now = new Date();\n\t\t\tconst candidates = Array.from(memories.values()).filter((memory) => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\treturn matchesDuplicateFilter(memory, input, now);\n\t\t\t});\n\t\t\tconst pairs: StoreDuplicatePair[] = [];\n\t\t\tfor (let i = 0; i < candidates.length; i += 1) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst a = candidates[i];\n\t\t\t\tif (a === undefined) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (let j = i + 1; j < candidates.length; j += 1) {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tconst b = candidates[j];\n\t\t\t\t\tif (b === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst similarity = Math.max(\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tMath.min(1, cosineSimilarity(a.embedding, b.embedding)),\n\t\t\t\t\t);\n\t\t\t\t\tif (similarity >= threshold) {\n\t\t\t\t\t\tpairs.push({\n\t\t\t\t\t\t\ta: cloneMemory(a),\n\t\t\t\t\t\t\tb: cloneMemory(b),\n\t\t\t\t\t\t\tsimilarity,\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\tpairs.sort((x, y) => y.similarity - x.similarity);\n\t\t\treturn pairs.slice(0, limit);\n\t\t},\n\t\tasync addAuditEvents(events) {\n\t\t\tauditLog.push(...events.map(cloneAuditEvent));\n\t\t},\n\t\tasync listAuditLog(input, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst limit = input.limit ?? DEFAULT_AUDIT_LOG_LIMIT;\n\t\t\treturn auditLog\n\t\t\t\t.filter((event) => {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tif (event.entityId !== input.entityId) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.before !== undefined &&\n\t\t\t\t\t\tevent.timestamp.getTime() >= input.before.getTime()\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.after !== undefined &&\n\t\t\t\t\t\tevent.timestamp.getTime() <= input.after.getTime()\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.beforeCursor !== undefined &&\n\t\t\t\t\t\tcompareAuditPositions(event, input.beforeCursor) >= 0\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.afterCursor !== undefined &&\n\t\t\t\t\t\tcompareAuditPositions(event, input.afterCursor) <= 0\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.sort((a, b) => {\n\t\t\t\t\treturn compareAuditPositions(b, a);\n\t\t\t\t})\n\t\t\t\t.slice(0, limit)\n\t\t\t\t.map(cloneAuditEvent);\n\t\t},\n\t\tasync getMemory(entityId, memoryId, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst memory = memories.get(memoryId);\n\t\t\treturn memory && memory.entityId === entityId\n\t\t\t\t? cloneMemory(memory)\n\t\t\t\t: null;\n\t\t},\n\t\tasync loadConsolidationTargets(entityId, ids, options) {\n\t\t\treturn ids.flatMap((id) => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (!memory || memory.entityId !== entityId) {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: memory.id,\n\t\t\t\t\t\ttags: [...memory.tags],\n\t\t\t\t\t\tsupersededBy: memory.supersededBy,\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t});\n\t\t},\n\t\tasync consolidate(\n\t\t\tinput: StoreConsolidateInput,\n\t\t\toptions,\n\t\t): Promise<StoreConsolidateResult> {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst survivor = memories.get(input.survivorId);\n\t\t\tif (\n\t\t\t\t!survivor ||\n\t\t\t\tsurvivor.entityId !== input.entityId ||\n\t\t\t\tsurvivor.supersededBy !== null\n\t\t\t) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"Consolidation survivor changed before mutation.\",\n\t\t\t\t\t\"CONFLICT\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst newlySuperseded: StoredMemory[] = [];\n\t\t\tconst targets: StoredMemory[] = [];\n\t\t\tfor (const id of input.supersededIds) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (!memory || memory.entityId !== input.entityId) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttargets.push(memory);\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttargets.some(\n\t\t\t\t\t(memory) =>\n\t\t\t\t\t\tmemory.supersededBy !== null &&\n\t\t\t\t\t\tmemory.supersededBy !== input.survivorId,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"Superseded memory already belongs to a different survivor.\",\n\t\t\t\t\t\"CONFLICT\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const memory of targets) {\n\t\t\t\tif (memory.supersededBy === null) {\n\t\t\t\t\tnewlySuperseded.push(memory);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet mergedSurvivorTags: string[] | undefined;\n\t\t\tif (input.mergeTags && newlySuperseded.length > 0) {\n\t\t\t\tconst mergedTags = new Set(survivor.tags);\n\t\t\t\tfor (const memory of newlySuperseded) {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tfor (const tag of memory.tags) {\n\t\t\t\t\t\tmergedTags.add(tag);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (mergedTags.size !== survivor.tags.length) {\n\t\t\t\t\tmergedSurvivorTags = [...mergedTags];\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst auditEvents = input.auditEnabled\n\t\t\t\t? newlySuperseded.map((memory) => ({\n\t\t\t\t\t\tid: createEventId(),\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\tdescription: \"memory.superseded\",\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tmemoryId: memory.id,\n\t\t\t\t\t\t\tsupersededBy: input.survivorId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: input.now,\n\t\t\t\t\t}))\n\t\t\t\t: [];\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tfor (const memory of newlySuperseded) {\n\t\t\t\tmemory.supersededBy = input.survivorId;\n\t\t\t\tmemory.supersededAt = input.now;\n\t\t\t\tmemory.updatedAt = input.now;\n\t\t\t}\n\t\t\tif (mergedSurvivorTags) {\n\t\t\t\tsurvivor.tags = mergedSurvivorTags;\n\t\t\t\tsurvivor.updatedAt = input.now;\n\t\t\t}\n\t\t\tif (input.auditEnabled) {\n\t\t\t\tauditLog.push(...auditEvents);\n\t\t\t}\n\t\t\treturn { supersededIds: newlySuperseded.map((memory) => memory.id) };\n\t\t},\n\t\tasync stats(input, now) {\n\t\t\tconst allMemories = Array.from(memories.values());\n\t\t\tconst selected = input?.entityId\n\t\t\t\t? allMemories.filter((memory) => memory.entityId === input.entityId)\n\t\t\t\t: allMemories;\n\t\t\tconst activeMemoryCount = selected.filter(\n\t\t\t\t(memory) => !isExpired(memory, now) && memory.supersededBy === null,\n\t\t\t).length;\n\t\t\tconst expiredMemoryCount = selected.filter((memory) =>\n\t\t\t\tisExpired(memory, now),\n\t\t\t).length;\n\t\t\tconst supersededMemoryCount = selected.filter(\n\t\t\t\t(memory) => memory.supersededBy !== null,\n\t\t\t).length;\n\t\t\tif (input?.entityId) {\n\t\t\t\treturn {\n\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\tmemoryCount: selected.length,\n\t\t\t\t\tactiveMemoryCount,\n\t\t\t\t\texpiredMemoryCount,\n\t\t\t\t\tsupersededMemoryCount,\n\t\t\t\t} satisfies EntityStats;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tentityCount: new Set(allMemories.map((memory) => memory.entityId)).size,\n\t\t\t\tmemoryCount: selected.length,\n\t\t\t\tactiveMemoryCount,\n\t\t\t\texpiredMemoryCount,\n\t\t\t\tsupersededMemoryCount,\n\t\t\t} satisfies GlobalStats;\n\t\t},\n\t\tasync close() {\n\t\t\tmemories.clear();\n\t\t\tauditLog.length = 0;\n\t\t},\n\t};\n}\n\nexport function createInMemoryClient(config: MnemocyteConfig): MnemocyteClient {\n\treturn createMemoryClient(config, createInMemoryStore());\n}\n","import type { MemoryStore } from \"./store.js\";\n\nexport function createLazyPostgresStore(databaseUrl: string): MemoryStore {\n\tlet storePromise: Promise<MemoryStore> | undefined;\n\n\tfunction loadStore(): Promise<MemoryStore> {\n\t\tstorePromise ??= import(\"./postgres-runtime.js\").then(\n\t\t\t({ createPostgresStoreFromUrl }) =>\n\t\t\t\tcreatePostgresStoreFromUrl(databaseUrl),\n\t\t);\n\t\treturn storePromise;\n\t}\n\n\treturn {\n\t\tbackend: \"postgres\",\n\t\tasync ensureSchema() {\n\t\t\treturn (await loadStore()).ensureSchema();\n\t\t},\n\t\tasync ensureEmbeddingCompatibility(embedder) {\n\t\t\treturn (await loadStore()).ensureEmbeddingCompatibility(embedder);\n\t\t},\n\t\tasync insertMemories(memories) {\n\t\t\treturn (await loadStore()).insertMemories(memories);\n\t\t},\n\t\tasync vectorSearch(input) {\n\t\t\treturn (await loadStore()).vectorSearch(input);\n\t\t},\n\t\tasync lexicalSearch(input) {\n\t\t\treturn (await loadStore()).lexicalSearch(input);\n\t\t},\n\t\tasync getMemoryEmbeddings(memoryIds) {\n\t\t\treturn (await loadStore()).getMemoryEmbeddings(memoryIds);\n\t\t},\n\t\tasync markMemoriesAccessed(memoryIds) {\n\t\t\treturn (await loadStore()).markMemoriesAccessed(memoryIds);\n\t\t},\n\t\tasync deleteMemory(entityId, memoryId) {\n\t\t\treturn (await loadStore()).deleteMemory(entityId, memoryId);\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\treturn (await loadStore()).deleteMemoriesForEntity(entityId);\n\t\t},\n\t\tasync prune(input, options) {\n\t\t\treturn (await loadStore()).prune(input, options);\n\t\t},\n\t\tasync findDuplicatePairs(input, options) {\n\t\t\treturn (await loadStore()).findDuplicatePairs(input, options);\n\t\t},\n\t\tasync addAuditEvents(events) {\n\t\t\treturn (await loadStore()).addAuditEvents(events);\n\t\t},\n\t\tasync listAuditLog(input, options) {\n\t\t\treturn (await loadStore()).listAuditLog(input, options);\n\t\t},\n\t\tasync getMemory(entityId, memoryId, options) {\n\t\t\treturn (await loadStore()).getMemory(entityId, memoryId, options);\n\t\t},\n\t\tasync loadConsolidationTargets(entityId, ids, options) {\n\t\t\treturn (await loadStore()).loadConsolidationTargets(\n\t\t\t\tentityId,\n\t\t\t\tids,\n\t\t\t\toptions,\n\t\t\t);\n\t\t},\n\t\tasync consolidate(input, options) {\n\t\t\treturn (await loadStore()).consolidate(input, options);\n\t\t},\n\t\tasync stats(input, now) {\n\t\t\treturn (await loadStore()).stats(input, now);\n\t\t},\n\t\tasync close() {\n\t\t\treturn (await loadStore()).close();\n\t\t},\n\t};\n}\n","import { parsePostgresDatabaseUrl } from \"./database-url.js\";\nimport { MnemocyteError } from \"./errors.js\";\nimport { createMemoryClient } from \"./memory/client-core.js\";\nimport { createInMemoryClient } from \"./memory/in-memory.js\";\nimport { createLazyPostgresStore } from \"./memory/lazy-postgres.js\";\nimport { unwrapMnemocyteStoreConfig } from \"./memory/store-config.js\";\nimport {\n\tassertEmbedder,\n\tassertNonEmptyString,\n\tvalidateProviderResilienceConfig,\n\tvalidateRetrievalConfig,\n} from \"./memory/validation.js\";\nimport type { MnemocyteClient, MnemocyteConfig } from \"./types.js\";\n\n/**\n * Create a Mnemocyte client.\n *\n * When {@link MnemocyteConfig.store} is provided, that adapter is used. When\n * {@link MnemocyteConfig.databaseUrl} is provided, a URL-owned Postgres client\n * is used (requires the `pgvector` extension and the bundled migrations).\n * When neither is supplied, an in-memory client is returned for tests, demos,\n * and short-lived processes.\n *\n * Call {@link MnemocyteClient.close} when finished. URL-created database\n * resources are owned and closed by Mnemocyte; resources behind a supplied\n * store retain the ownership policy documented by that adapter.\n *\n * @param config - Client configuration. {@link MnemocyteConfig.embedder} is required.\n * @returns A {@link MnemocyteClient} instance.\n * @throws {MnemocyteError} With code `\"CONFIG\"` if `embedder`, retrieval\n * tuning, provider resilience, or the database URL is malformed or does not\n * use the `postgres:` / `postgresql:` protocol, or if `databaseUrl` and\n * `store` are both provided; or `\"VALIDATION\"` if `databaseUrl` is explicitly\n * empty.\n *\n * @example Postgres-backed client\n * ```ts\n * const client = createMnemocyte({\n * databaseUrl: process.env.DATABASE_URL,\n * embedder, // embedder.dimensions must match mnemocyte_meta\n * });\n * ```\n */\nexport function createMnemocyte(config: MnemocyteConfig): MnemocyteClient {\n\tassertEmbedder(config.embedder);\n\tvalidateRetrievalConfig(config.retrieval);\n\tvalidateProviderResilienceConfig(config.provider);\n\tif (config.databaseUrl !== undefined && config.store !== undefined) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl and store cannot be provided together.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tif (config.databaseUrl !== undefined) {\n\t\tassertNonEmptyString(config.databaseUrl, \"databaseUrl\");\n\t\tparsePostgresDatabaseUrl(config.databaseUrl);\n\t\treturn createMemoryClient(\n\t\t\tconfig,\n\t\t\tcreateLazyPostgresStore(config.databaseUrl),\n\t\t);\n\t}\n\tif (config.store !== undefined) {\n\t\treturn createMemoryClient(config, unwrapMnemocyteStoreConfig(config.store));\n\t}\n\treturn createInMemoryClient(config);\n}\n"],"mappings":";;;AAIA,SAAgB,UAAU,QAAgB,KAAoB;CAC7D,OACC,OAAO,cAAc,QAAQ,OAAO,UAAU,QAAQ,KAAK,IAAI,QAAQ;AAEzE;;;;;;;;AASA,SAAgB,mBACf,QACA,OACA,KACU;CACV,IAAI,MAAM,aAAa,KAAA,KAAa,OAAO,aAAa,MAAM,UAC7D,OAAO;CAER,IAAI,MAAM,YAAY,QAAQ,CAAC,UAAU,QAAQ,GAAG,GACnD,OAAO;CAER,IAAI,MAAM,eAAe,QAAQ,OAAO,iBAAiB,MACxD,OAAO;CAER,IACC,MAAM,kBAAkB,KAAA,KACxB,OAAO,UAAU,QAAQ,KAAK,MAAM,cAAc,QAAQ,GAE1D,OAAO;CAER,IAAI,MAAM,qBAAqB,KAAA,GAAW;EACzC,MAAM,OAAO,OAAO;EACpB,IAAI,SAAS,QAAQ,KAAK,QAAQ,KAAK,MA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,CAC3C;CACD;CACA,IAAI,OAAO,UAAU,KAAA,GACpB,OAAO,mBAAmB,QAAQ,2BAA2B,OAAO,KAAK,CAAC;CAE3E,OAAO,qBAAqB,MAAM;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/context/formatter.ts","../src/context/tokens.ts","../src/context/builder.ts","../src/observability.ts","../src/retrieval/scorer.ts","../src/memory/embeddings.ts","../src/memory/validation.ts","../src/memory/client-core.ts","../src/memory/filters.ts","../src/memory/in-memory.ts","../src/memory/lazy-postgres.ts","../src/client.ts"],"sourcesContent":["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 { 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 { 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 { 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 type { FindDuplicatesInput, Memory, RecallInput } from \"../types.js\";\nimport { IMPORTANCE_RANK } from \"./defaults.js\";\nimport type { ValidatedPruneFilter } from \"./store.js\";\n\nexport function isExpired(memory: Memory, now: Date): boolean {\n\treturn (\n\t\tmemory.expiresAt !== null && memory.expiresAt.getTime() <= now.getTime()\n\t);\n}\n\n/**\n * Test whether `memory` matches a validated prune filter. All specified\n * selectors are AND-combined; unspecified selectors do not restrict.\n *\n * `now` is supplied by the caller so callers can share a consistent\n * timestamp across a batch.\n */\nexport function matchesPruneFilter(\n\tmemory: Memory,\n\tinput: ValidatedPruneFilter,\n\tnow: Date,\n): boolean {\n\tif (input.entityId !== undefined && memory.entityId !== input.entityId) {\n\t\treturn false;\n\t}\n\tif (input.expired === true && !isExpired(memory, now)) {\n\t\treturn false;\n\t}\n\tif (input.superseded === true && memory.supersededBy === null) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.createdBefore !== undefined &&\n\t\tmemory.createdAt.getTime() >= input.createdBefore.getTime()\n\t) {\n\t\treturn false;\n\t}\n\tif (input.notAccessedSince !== undefined) {\n\t\tconst last = memory.lastAccessedAt;\n\t\tif (last !== null && last.getTime() >= input.notAccessedSince.getTime()) {\n\t\t\treturn false;\n\t\t}\n\t}\n\tif (input.types !== undefined && !input.types.includes(memory.type)) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.tags !== undefined &&\n\t\tinput.tags.length > 0 &&\n\t\t!input.tags.every((tag) => memory.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.maxImportance !== undefined &&\n\t\tIMPORTANCE_RANK[memory.importance] > IMPORTANCE_RANK[input.maxImportance]\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n/**\n * Return `true` when a memory should participate in a duplicate scan,\n * given the filters on `input` and a shared `now` timestamp.\n */\nexport function matchesDuplicateFilter(\n\tmemory: Memory,\n\tinput: FindDuplicatesInput,\n\tnow: Date,\n): boolean {\n\tif (memory.entityId !== input.entityId) {\n\t\treturn false;\n\t}\n\tif (input.includeSuperseded !== true && memory.supersededBy !== null) {\n\t\treturn false;\n\t}\n\tif (input.includeExpired !== true && isExpired(memory, now)) {\n\t\treturn false;\n\t}\n\tif (input.types !== undefined && !input.types.includes(memory.type)) {\n\t\treturn false;\n\t}\n\tif (\n\t\tinput.tags !== undefined &&\n\t\tinput.tags.length > 0 &&\n\t\t!input.tags.every((tag) => memory.tags.includes(tag))\n\t) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport function matchesRecallFilter(\n\tmemory: Memory,\n\tinput: RecallInput,\n\tnow: Date,\n): boolean {\n\tif (memory.entityId !== input.entityId) {\n\t\treturn false;\n\t}\n\tif (!input.includeSuperseded && memory.supersededBy !== null) {\n\t\treturn false;\n\t}\n\tif (!input.includeExpired && isExpired(memory, now)) {\n\t\treturn false;\n\t}\n\tif (input.types && !input.types.includes(memory.type)) {\n\t\treturn false;\n\t}\n\tif (input.tags && !input.tags.every((tag) => memory.tags.includes(tag))) {\n\t\treturn false;\n\t}\n\tif (input.before && memory.createdAt >= input.before) {\n\t\treturn false;\n\t}\n\tif (input.after && memory.createdAt <= input.after) {\n\t\treturn false;\n\t}\n\treturn true;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport { throwIfAborted } from \"../resilience.js\";\nimport {\n\tcosineSimilarity,\n\tcreateLexicalScorer,\n\ttoVectorScore,\n} from \"../retrieval/scorer.js\";\nimport type {\n\tAuditEvent,\n\tEntityStats,\n\tGlobalStats,\n\tMemory,\n\tMnemocyteClient,\n\tMnemocyteConfig,\n} from \"../types.js\";\nimport { createMemoryClient } from \"./client-core.js\";\nimport {\n\tDEFAULT_AUDIT_LOG_LIMIT,\n\tDEFAULT_DUPLICATE_LIMIT,\n\tDEFAULT_DUPLICATE_THRESHOLD,\n} from \"./defaults.js\";\nimport { memoryHasDependentsError } from \"./deletion.js\";\nimport {\n\tisExpired,\n\tmatchesDuplicateFilter,\n\tmatchesPruneFilter,\n\tmatchesRecallFilter,\n} from \"./filters.js\";\nimport { cloneJsonObject } from \"./json.js\";\nimport { cloneMemory, createEventId, type StoredMemory } from \"./records.js\";\nimport {\n\tassertPruneFilterHasSelector,\n\ttype MemoryStore,\n\ttype StoreAccessUpdate,\n\ttype StoreConsolidateInput,\n\ttype StoreConsolidateResult,\n\ttype StoreDuplicatePair,\n\ttype StoreLexicalCandidate,\n\ttype StoreLexicalSearchInput,\n\ttype StorePruneEntityDeletion,\n\ttype StoreVectorCandidate,\n\ttype StoreVectorSearchInput,\n} from \"./store.js\";\n\nfunction cloneAuditEvent(event: AuditEvent): AuditEvent {\n\treturn {\n\t\tid: event.id,\n\t\tentityId: event.entityId,\n\t\tdescription: event.description,\n\t\tmetadata: cloneJsonObject(event.metadata),\n\t\ttimestamp: new Date(event.timestamp),\n\t};\n}\n\nfunction compareAuditPositions(\n\ta: { id: string; timestamp: Date },\n\tb: { id: string; timestamp: Date },\n): number {\n\tconst timestampDifference = a.timestamp.getTime() - b.timestamp.getTime();\n\tif (timestampDifference !== 0) {\n\t\treturn timestampDifference;\n\t}\n\tif (a.id === b.id) {\n\t\treturn 0;\n\t}\n\treturn a.id < b.id ? -1 : 1;\n}\n\nfunction assertNoDependentMemories(\n\tmemories: ReadonlyMap<string, StoredMemory>,\n\ttargetIds: ReadonlySet<string>,\n): void {\n\tfor (const memory of memories.values()) {\n\t\tif (memory.supersededBy !== null && targetIds.has(memory.supersededBy)) {\n\t\t\tthrow memoryHasDependentsError();\n\t\t}\n\t}\n}\n\nexport function createInMemoryStore(): MemoryStore {\n\tconst memories = new Map<string, StoredMemory>();\n\tconst auditLog: AuditEvent[] = [];\n\n\treturn {\n\t\tbackend: \"in-memory\",\n\t\tasync ensureSchema() {},\n\t\tasync ensureEmbeddingCompatibility() {},\n\t\tasync insertMemories(rows) {\n\t\t\tconst inserted: Memory[] = [];\n\t\t\tfor (const row of rows) {\n\t\t\t\tmemories.set(row.id, row);\n\t\t\t\tinserted.push(cloneMemory(row));\n\t\t\t}\n\t\t\treturn inserted;\n\t\t},\n\t\tasync vectorSearch(input: StoreVectorSearchInput) {\n\t\t\tconst now = new Date();\n\t\t\tconst minVectorScore = input.minVectorScore ?? 0;\n\t\t\treturn Array.from(memories.values())\n\t\t\t\t.filter((memory) => matchesRecallFilter(memory, input, now))\n\t\t\t\t.map((memory) => ({\n\t\t\t\t\tmemory: cloneMemory(memory),\n\t\t\t\t\tvectorScore: toVectorScore(\n\t\t\t\t\t\tcosineSimilarity(memory.embedding, input.embedding),\n\t\t\t\t\t),\n\t\t\t\t}))\n\t\t\t\t.filter((candidate) => candidate.vectorScore >= minVectorScore)\n\t\t\t\t.sort((a, b) => b.vectorScore - a.vectorScore)\n\t\t\t\t.slice(0, input.limit) satisfies StoreVectorCandidate[];\n\t\t},\n\t\tasync lexicalSearch(input: StoreLexicalSearchInput) {\n\t\t\tconst now = new Date();\n\t\t\tconst scoreLexical = createLexicalScorer(input.query);\n\t\t\treturn Array.from(memories.values())\n\t\t\t\t.filter((memory) => matchesRecallFilter(memory, input, now))\n\t\t\t\t.map((memory) => ({\n\t\t\t\t\tmemory: cloneMemory(memory),\n\t\t\t\t\tlexicalScore: scoreLexical(memory.content),\n\t\t\t\t}))\n\t\t\t\t.filter((candidate) => candidate.lexicalScore > 0)\n\t\t\t\t.sort((a, b) => b.lexicalScore - a.lexicalScore)\n\t\t\t\t.slice(0, input.limit) satisfies StoreLexicalCandidate[];\n\t\t},\n\t\tasync getMemoryEmbeddings(memoryIds) {\n\t\t\tconst result = new Map<string, number[]>();\n\t\t\tfor (const id of memoryIds) {\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (memory) {\n\t\t\t\t\tresult.set(id, [...memory.embedding]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\tasync markMemoriesAccessed(memoryIds) {\n\t\t\tconst now = new Date();\n\t\t\tconst updates: StoreAccessUpdate[] = [];\n\t\t\tfor (const id of memoryIds) {\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (memory) {\n\t\t\t\t\tmemory.lastAccessedAt = now;\n\t\t\t\t\tmemory.accessCount += 1;\n\t\t\t\t\tmemory.updatedAt = now;\n\t\t\t\t\tupdates.push({\n\t\t\t\t\t\tid: memory.id,\n\t\t\t\t\t\tlastAccessedAt: now,\n\t\t\t\t\t\taccessCount: memory.accessCount,\n\t\t\t\t\t\tupdatedAt: now,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn updates;\n\t\t},\n\t\tasync deleteMemory(entityId, memoryId) {\n\t\t\tconst memory = memories.get(memoryId);\n\t\t\tif (!memory || memory.entityId !== entityId) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tassertNoDependentMemories(memories, new Set([memoryId]));\n\t\t\treturn memories.delete(memoryId);\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\tconst targetIds = new Set(\n\t\t\t\tArray.from(memories.values())\n\t\t\t\t\t.filter((memory) => memory.entityId === entityId)\n\t\t\t\t\t.map((memory) => memory.id),\n\t\t\t);\n\t\t\tassertNoDependentMemories(memories, targetIds);\n\t\t\tfor (const id of targetIds) {\n\t\t\t\tmemories.delete(id);\n\t\t\t}\n\t\t\treturn targetIds.size;\n\t\t},\n\t\tasync prune(input, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tassertPruneFilterHasSelector(input);\n\t\t\tconst now = new Date();\n\t\t\tconst matched: StoredMemory[] = [];\n\t\t\tfor (const memory of memories.values()) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tif (matchesPruneFilter(memory, input, now)) {\n\t\t\t\t\tmatched.push(memory);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst dryRun = input.dryRun === true;\n\t\t\tlet deletedByEntity: StorePruneEntityDeletion[] = [];\n\t\t\tif (!dryRun) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tassertNoDependentMemories(\n\t\t\t\t\tmemories,\n\t\t\t\t\tnew Set(matched.map((memory) => memory.id)),\n\t\t\t\t);\n\t\t\t\tconst deletedCounts = new Map<string, number>();\n\t\t\t\tfor (const memory of matched) {\n\t\t\t\t\tmemories.delete(memory.id);\n\t\t\t\t\tdeletedCounts.set(\n\t\t\t\t\t\tmemory.entityId,\n\t\t\t\t\t\t(deletedCounts.get(memory.entityId) ?? 0) + 1,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tdeletedByEntity = Array.from(\n\t\t\t\t\tdeletedCounts,\n\t\t\t\t\t([entityId, deletedCount]) => ({ entityId, deletedCount }),\n\t\t\t\t).sort((a, b) => a.entityId.localeCompare(b.entityId));\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tmatchedCount: matched.length,\n\t\t\t\tdeletedCount: dryRun ? 0 : matched.length,\n\t\t\t\tdryRun,\n\t\t\t\tdeletedByEntity,\n\t\t\t};\n\t\t},\n\t\tasync findDuplicatePairs(input, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst threshold = input.threshold ?? DEFAULT_DUPLICATE_THRESHOLD;\n\t\t\tconst limit = input.limit ?? DEFAULT_DUPLICATE_LIMIT;\n\t\t\tconst now = new Date();\n\t\t\tconst candidates = Array.from(memories.values()).filter((memory) => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\treturn matchesDuplicateFilter(memory, input, now);\n\t\t\t});\n\t\t\tconst pairs: StoreDuplicatePair[] = [];\n\t\t\tfor (let i = 0; i < candidates.length; i += 1) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst a = candidates[i];\n\t\t\t\tif (a === undefined) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (let j = i + 1; j < candidates.length; j += 1) {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tconst b = candidates[j];\n\t\t\t\t\tif (b === undefined) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst similarity = Math.max(\n\t\t\t\t\t\t0,\n\t\t\t\t\t\tMath.min(1, cosineSimilarity(a.embedding, b.embedding)),\n\t\t\t\t\t);\n\t\t\t\t\tif (similarity >= threshold) {\n\t\t\t\t\t\tpairs.push({\n\t\t\t\t\t\t\ta: cloneMemory(a),\n\t\t\t\t\t\t\tb: cloneMemory(b),\n\t\t\t\t\t\t\tsimilarity,\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\tpairs.sort((x, y) => y.similarity - x.similarity);\n\t\t\treturn pairs.slice(0, limit);\n\t\t},\n\t\tasync addAuditEvents(events) {\n\t\t\tauditLog.push(...events.map(cloneAuditEvent));\n\t\t},\n\t\tasync listAuditLog(input, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst limit = input.limit ?? DEFAULT_AUDIT_LOG_LIMIT;\n\t\t\treturn auditLog\n\t\t\t\t.filter((event) => {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tif (event.entityId !== input.entityId) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.before !== undefined &&\n\t\t\t\t\t\tevent.timestamp.getTime() >= input.before.getTime()\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.after !== undefined &&\n\t\t\t\t\t\tevent.timestamp.getTime() <= input.after.getTime()\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.beforeCursor !== undefined &&\n\t\t\t\t\t\tcompareAuditPositions(event, input.beforeCursor) >= 0\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\tif (\n\t\t\t\t\t\tinput.afterCursor !== undefined &&\n\t\t\t\t\t\tcompareAuditPositions(event, input.afterCursor) <= 0\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t})\n\t\t\t\t.sort((a, b) => {\n\t\t\t\t\treturn compareAuditPositions(b, a);\n\t\t\t\t})\n\t\t\t\t.slice(0, limit)\n\t\t\t\t.map(cloneAuditEvent);\n\t\t},\n\t\tasync getMemory(entityId, memoryId, options) {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst memory = memories.get(memoryId);\n\t\t\treturn memory && memory.entityId === entityId\n\t\t\t\t? cloneMemory(memory)\n\t\t\t\t: null;\n\t\t},\n\t\tasync loadConsolidationTargets(entityId, ids, options) {\n\t\t\treturn ids.flatMap((id) => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (!memory || memory.entityId !== entityId) {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\treturn [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: memory.id,\n\t\t\t\t\t\ttags: [...memory.tags],\n\t\t\t\t\t\tsupersededBy: memory.supersededBy,\n\t\t\t\t\t},\n\t\t\t\t];\n\t\t\t});\n\t\t},\n\t\tasync consolidate(\n\t\t\tinput: StoreConsolidateInput,\n\t\t\toptions,\n\t\t): Promise<StoreConsolidateResult> {\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tconst survivor = memories.get(input.survivorId);\n\t\t\tif (\n\t\t\t\t!survivor ||\n\t\t\t\tsurvivor.entityId !== input.entityId ||\n\t\t\t\tsurvivor.supersededBy !== null\n\t\t\t) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"Consolidation survivor changed before mutation.\",\n\t\t\t\t\t\"CONFLICT\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst newlySuperseded: StoredMemory[] = [];\n\t\t\tconst targets: StoredMemory[] = [];\n\t\t\tfor (const id of input.supersededIds) {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst memory = memories.get(id);\n\t\t\t\tif (!memory || memory.entityId !== input.entityId) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttargets.push(memory);\n\t\t\t}\n\t\t\tif (\n\t\t\t\ttargets.some(\n\t\t\t\t\t(memory) =>\n\t\t\t\t\t\tmemory.supersededBy !== null &&\n\t\t\t\t\t\tmemory.supersededBy !== input.survivorId,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"Superseded memory already belongs to a different survivor.\",\n\t\t\t\t\t\"CONFLICT\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tfor (const memory of targets) {\n\t\t\t\tif (memory.supersededBy === null) {\n\t\t\t\t\tnewlySuperseded.push(memory);\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet mergedSurvivorTags: string[] | undefined;\n\t\t\tif (input.mergeTags && newlySuperseded.length > 0) {\n\t\t\t\tconst mergedTags = new Set(survivor.tags);\n\t\t\t\tfor (const memory of newlySuperseded) {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tfor (const tag of memory.tags) {\n\t\t\t\t\t\tmergedTags.add(tag);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (mergedTags.size !== survivor.tags.length) {\n\t\t\t\t\tmergedSurvivorTags = [...mergedTags];\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst auditEvents = input.auditEnabled\n\t\t\t\t? newlySuperseded.map((memory) => ({\n\t\t\t\t\t\tid: createEventId(),\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\tdescription: \"memory.superseded\",\n\t\t\t\t\t\tmetadata: {\n\t\t\t\t\t\t\tmemoryId: memory.id,\n\t\t\t\t\t\t\tsupersededBy: input.survivorId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\ttimestamp: input.now,\n\t\t\t\t\t}))\n\t\t\t\t: [];\n\t\t\tthrowIfAborted(options?.signal);\n\t\t\tfor (const memory of newlySuperseded) {\n\t\t\t\tmemory.supersededBy = input.survivorId;\n\t\t\t\tmemory.supersededAt = input.now;\n\t\t\t\tmemory.updatedAt = input.now;\n\t\t\t}\n\t\t\tif (mergedSurvivorTags) {\n\t\t\t\tsurvivor.tags = mergedSurvivorTags;\n\t\t\t\tsurvivor.updatedAt = input.now;\n\t\t\t}\n\t\t\tif (input.auditEnabled) {\n\t\t\t\tauditLog.push(...auditEvents);\n\t\t\t}\n\t\t\treturn { supersededIds: newlySuperseded.map((memory) => memory.id) };\n\t\t},\n\t\tasync stats(input, now) {\n\t\t\tconst allMemories = Array.from(memories.values());\n\t\t\tconst selected = input?.entityId\n\t\t\t\t? allMemories.filter((memory) => memory.entityId === input.entityId)\n\t\t\t\t: allMemories;\n\t\t\tconst activeMemoryCount = selected.filter(\n\t\t\t\t(memory) => !isExpired(memory, now) && memory.supersededBy === null,\n\t\t\t).length;\n\t\t\tconst expiredMemoryCount = selected.filter((memory) =>\n\t\t\t\tisExpired(memory, now),\n\t\t\t).length;\n\t\t\tconst supersededMemoryCount = selected.filter(\n\t\t\t\t(memory) => memory.supersededBy !== null,\n\t\t\t).length;\n\t\t\tif (input?.entityId) {\n\t\t\t\treturn {\n\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\tmemoryCount: selected.length,\n\t\t\t\t\tactiveMemoryCount,\n\t\t\t\t\texpiredMemoryCount,\n\t\t\t\t\tsupersededMemoryCount,\n\t\t\t\t} satisfies EntityStats;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tentityCount: new Set(allMemories.map((memory) => memory.entityId)).size,\n\t\t\t\tmemoryCount: selected.length,\n\t\t\t\tactiveMemoryCount,\n\t\t\t\texpiredMemoryCount,\n\t\t\t\tsupersededMemoryCount,\n\t\t\t} satisfies GlobalStats;\n\t\t},\n\t\tasync close() {\n\t\t\tmemories.clear();\n\t\t\tauditLog.length = 0;\n\t\t},\n\t};\n}\n\nexport function createInMemoryClient(config: MnemocyteConfig): MnemocyteClient {\n\treturn createMemoryClient(config, createInMemoryStore());\n}\n","import type { MemoryStore } from \"./store.js\";\n\nexport function createLazyPostgresStore(databaseUrl: string): MemoryStore {\n\tlet storePromise: Promise<MemoryStore> | undefined;\n\n\tfunction loadStore(): Promise<MemoryStore> {\n\t\tstorePromise ??= import(\"./postgres-runtime.js\").then(\n\t\t\t({ createPostgresStoreFromUrl }) =>\n\t\t\t\tcreatePostgresStoreFromUrl(databaseUrl),\n\t\t);\n\t\treturn storePromise;\n\t}\n\n\treturn {\n\t\tbackend: \"postgres\",\n\t\tasync ensureSchema() {\n\t\t\treturn (await loadStore()).ensureSchema();\n\t\t},\n\t\tasync ensureEmbeddingCompatibility(embedder) {\n\t\t\treturn (await loadStore()).ensureEmbeddingCompatibility(embedder);\n\t\t},\n\t\tasync insertMemories(memories) {\n\t\t\treturn (await loadStore()).insertMemories(memories);\n\t\t},\n\t\tasync vectorSearch(input) {\n\t\t\treturn (await loadStore()).vectorSearch(input);\n\t\t},\n\t\tasync lexicalSearch(input) {\n\t\t\treturn (await loadStore()).lexicalSearch(input);\n\t\t},\n\t\tasync getMemoryEmbeddings(memoryIds) {\n\t\t\treturn (await loadStore()).getMemoryEmbeddings(memoryIds);\n\t\t},\n\t\tasync markMemoriesAccessed(memoryIds) {\n\t\t\treturn (await loadStore()).markMemoriesAccessed(memoryIds);\n\t\t},\n\t\tasync deleteMemory(entityId, memoryId) {\n\t\t\treturn (await loadStore()).deleteMemory(entityId, memoryId);\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\treturn (await loadStore()).deleteMemoriesForEntity(entityId);\n\t\t},\n\t\tasync prune(input, options) {\n\t\t\treturn (await loadStore()).prune(input, options);\n\t\t},\n\t\tasync findDuplicatePairs(input, options) {\n\t\t\treturn (await loadStore()).findDuplicatePairs(input, options);\n\t\t},\n\t\tasync addAuditEvents(events) {\n\t\t\treturn (await loadStore()).addAuditEvents(events);\n\t\t},\n\t\tasync listAuditLog(input, options) {\n\t\t\treturn (await loadStore()).listAuditLog(input, options);\n\t\t},\n\t\tasync getMemory(entityId, memoryId, options) {\n\t\t\treturn (await loadStore()).getMemory(entityId, memoryId, options);\n\t\t},\n\t\tasync loadConsolidationTargets(entityId, ids, options) {\n\t\t\treturn (await loadStore()).loadConsolidationTargets(\n\t\t\t\tentityId,\n\t\t\t\tids,\n\t\t\t\toptions,\n\t\t\t);\n\t\t},\n\t\tasync consolidate(input, options) {\n\t\t\treturn (await loadStore()).consolidate(input, options);\n\t\t},\n\t\tasync stats(input, now) {\n\t\t\treturn (await loadStore()).stats(input, now);\n\t\t},\n\t\tasync close() {\n\t\t\treturn (await loadStore()).close();\n\t\t},\n\t};\n}\n","import { parsePostgresDatabaseUrl } from \"./database-url.js\";\nimport { MnemocyteError } from \"./errors.js\";\nimport { createMemoryClient } from \"./memory/client-core.js\";\nimport { createInMemoryClient } from \"./memory/in-memory.js\";\nimport { createLazyPostgresStore } from \"./memory/lazy-postgres.js\";\nimport { unwrapMnemocyteStoreConfig } from \"./memory/store-config.js\";\nimport {\n\tassertEmbedder,\n\tassertNonEmptyString,\n\tvalidateProviderResilienceConfig,\n\tvalidateRetrievalConfig,\n} from \"./memory/validation.js\";\nimport type { MnemocyteClient, MnemocyteConfig } from \"./types.js\";\n\n/**\n * Create a Mnemocyte client.\n *\n * When {@link MnemocyteConfig.store} is provided, that adapter is used. When\n * {@link MnemocyteConfig.databaseUrl} is provided, a URL-owned Postgres client\n * is used (requires the `pgvector` extension and the bundled migrations).\n * When neither is supplied, an in-memory client is returned for tests, demos,\n * and short-lived processes.\n *\n * Call {@link MnemocyteClient.close} when finished. URL-created database\n * resources are owned and closed by Mnemocyte; resources behind a supplied\n * store retain the ownership policy documented by that adapter.\n *\n * @param config - Client configuration. {@link MnemocyteConfig.embedder} is required.\n * @returns A {@link MnemocyteClient} instance.\n * @throws {MnemocyteError} With code `\"CONFIG\"` if `embedder`, retrieval\n * tuning, provider resilience, or the database URL is malformed or does not\n * use the `postgres:` / `postgresql:` protocol, or if `databaseUrl` and\n * `store` are both provided; or `\"VALIDATION\"` if `databaseUrl` is explicitly\n * empty.\n *\n * @example Postgres-backed client\n * ```ts\n * const client = createMnemocyte({\n * databaseUrl: process.env.DATABASE_URL,\n * embedder, // embedder.dimensions must match mnemocyte_meta\n * });\n * ```\n */\nexport function createMnemocyte(config: MnemocyteConfig): MnemocyteClient {\n\tassertEmbedder(config.embedder);\n\tvalidateRetrievalConfig(config.retrieval);\n\tvalidateProviderResilienceConfig(config.provider);\n\tif (config.databaseUrl !== undefined && config.store !== undefined) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl and store cannot be provided together.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tif (config.databaseUrl !== undefined) {\n\t\tassertNonEmptyString(config.databaseUrl, \"databaseUrl\");\n\t\tparsePostgresDatabaseUrl(config.databaseUrl);\n\t\treturn createMemoryClient(\n\t\t\tconfig,\n\t\t\tcreateLazyPostgresStore(config.databaseUrl),\n\t\t);\n\t}\n\tif (config.store !== undefined) {\n\t\treturn createMemoryClient(config, unwrapM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@
|
|
|
1
|
-
import { t as MnemocyteError } from "./errors-
|
|
2
|
-
import {
|
|
1
|
+
import { t as MnemocyteError } from "./errors-Dgt2nAs1.mjs";
|
|
2
|
+
import { c as IMPORTANCE_RANK, g as parsePostgresDatabaseUrl, i as assertPruneFilterHasSelector, m as throwIfAborted, p as cloneJsonObject, r as memoryHasDependentsError, u as createEventId } from "./store-config-BZ4J1hrM.mjs";
|
|
3
3
|
import { drizzle } from "drizzle-orm/postgres-js";
|
|
4
4
|
import postgres from "postgres";
|
|
5
5
|
import { and, count, countDistinct, eq, inArray, isNotNull, isNull, lt, or, sql } from "drizzle-orm";
|
|
6
6
|
import { PgDialect, customType, index, integer, jsonb, pgTable, real, text, timestamp } from "drizzle-orm/pg-core";
|
|
7
|
-
|
|
7
|
+
// \0rolldown/runtime.js
|
|
8
8
|
var __defProp = Object.defineProperty;
|
|
9
9
|
var __exportAll = (all, no_symbols) => {
|
|
10
10
|
let target = {};
|
|
@@ -15,14 +15,12 @@ var __exportAll = (all, no_symbols) => {
|
|
|
15
15
|
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
16
16
|
return target;
|
|
17
17
|
};
|
|
18
|
-
|
|
19
|
-
//#region src/db/vector.ts
|
|
18
|
+
// src/db/vector.ts
|
|
20
19
|
function formatVectorComponent(value) {
|
|
21
20
|
if (!Number.isFinite(value)) throw new Error("Vector values must be finite numbers.");
|
|
22
21
|
return Object.is(value, -0) ? "0" : value.toString();
|
|
23
22
|
}
|
|
24
|
-
|
|
25
|
-
//#region src/db/schema.ts
|
|
23
|
+
// src/db/schema.ts
|
|
26
24
|
var schema_exports = /* @__PURE__ */ __exportAll({
|
|
27
25
|
eventsTable: () => eventsTable,
|
|
28
26
|
memoriesTable: () => memoriesTable,
|
|
@@ -76,8 +74,7 @@ const metaTable = pgTable("mnemocyte_meta", {
|
|
|
76
74
|
embeddingDimensions: integer("embedding_dimensions").notNull(),
|
|
77
75
|
embeddingModel: text("embedding_model")
|
|
78
76
|
});
|
|
79
|
-
|
|
80
|
-
//#region src/db/index.ts
|
|
77
|
+
// src/db/index.ts
|
|
81
78
|
function createCallerOwnedDatabaseHandle(db) {
|
|
82
79
|
return {
|
|
83
80
|
db,
|
|
@@ -108,8 +105,7 @@ function createDatabase(databaseUrl) {
|
|
|
108
105
|
}
|
|
109
106
|
};
|
|
110
107
|
}
|
|
111
|
-
|
|
112
|
-
//#region src/db/cancellation.ts
|
|
108
|
+
// src/db/cancellation.ts
|
|
113
109
|
const postgresDialect = new PgDialect();
|
|
114
110
|
async function awaitCancelableQuery(query, signal) {
|
|
115
111
|
throwIfAborted(signal);
|
|
@@ -133,8 +129,7 @@ async function executeCancelableSql(db, statement, signal) {
|
|
|
133
129
|
if (!client) throw new MnemocyteError("Cancelable Postgres query requires the postgres.js client.", "DB");
|
|
134
130
|
return await awaitCancelableQuery(client.unsafe(query.sql, query.params), signal);
|
|
135
131
|
}
|
|
136
|
-
|
|
137
|
-
//#region src/db/queries/events.ts
|
|
132
|
+
// src/db/queries/events.ts
|
|
138
133
|
function timestampParam$1(value) {
|
|
139
134
|
return sql`${value.toISOString()}::timestamptz`;
|
|
140
135
|
}
|
|
@@ -161,8 +156,7 @@ async function listEvents(db, filter, signal) {
|
|
|
161
156
|
LIMIT ${filter.limit ?? 50}
|
|
162
157
|
`, signal);
|
|
163
158
|
}
|
|
164
|
-
|
|
165
|
-
//#region src/db/queries/memories.ts
|
|
159
|
+
// src/db/queries/memories.ts
|
|
166
160
|
function vectorLiteral(embedding) {
|
|
167
161
|
return `[${embedding.map(formatVectorComponent).join(",")}]`;
|
|
168
162
|
}
|
|
@@ -428,7 +422,7 @@ async function loadConsolidationTargets(db, entityId, ids) {
|
|
|
428
422
|
}).from(memoriesTable).where(and(eq(memoriesTable.entityId, entityId), inArray(memoriesTable.id, [...ids])));
|
|
429
423
|
}
|
|
430
424
|
async function lockConsolidationMemories(db, entityId, survivorId, supersededIds) {
|
|
431
|
-
const ids = [
|
|
425
|
+
const ids = [.../* @__PURE__ */ new Set([survivorId, ...supersededIds])].sort();
|
|
432
426
|
return db.select({
|
|
433
427
|
id: memoriesTable.id,
|
|
434
428
|
tags: memoriesTable.tags,
|
|
@@ -559,8 +553,7 @@ async function getStoredEmbeddingModels(db) {
|
|
|
559
553
|
async function recordInstallationEmbeddingModel(db, embeddingModel) {
|
|
560
554
|
return (await db.update(metaTable).set({ embeddingModel }).where(and(eq(metaTable.key, "installation"), isNull(metaTable.embeddingModel))).returning())[0] ?? null;
|
|
561
555
|
}
|
|
562
|
-
|
|
563
|
-
//#region src/memory/postgres-records.ts
|
|
556
|
+
// src/memory/postgres-records.ts
|
|
564
557
|
function toDate(value) {
|
|
565
558
|
return value instanceof Date ? value : new Date(value);
|
|
566
559
|
}
|
|
@@ -589,15 +582,14 @@ function rowToMemory(row) {
|
|
|
589
582
|
updatedAt: toDate(row.updatedAt)
|
|
590
583
|
};
|
|
591
584
|
}
|
|
592
|
-
|
|
593
|
-
//#region src/memory/postgres.ts
|
|
585
|
+
// src/memory/postgres.ts
|
|
594
586
|
const IMPORTANCE_LEVELS = [
|
|
595
587
|
"low",
|
|
596
588
|
"normal",
|
|
597
589
|
"high",
|
|
598
590
|
"critical"
|
|
599
591
|
];
|
|
600
|
-
const MIGRATION_ERROR_CODES = new Set([
|
|
592
|
+
const MIGRATION_ERROR_CODES = /* @__PURE__ */ new Set([
|
|
601
593
|
"42P01",
|
|
602
594
|
"42703",
|
|
603
595
|
"42704",
|
|
@@ -907,7 +899,6 @@ function createPostgresStore(handle) {
|
|
|
907
899
|
}
|
|
908
900
|
};
|
|
909
901
|
}
|
|
910
|
-
//#endregion
|
|
911
902
|
export { createCallerOwnedDatabaseHandle as n, createDatabase as r, createPostgresStore as t };
|
|
912
903
|
|
|
913
|
-
//# sourceMappingURL=postgres-
|
|
904
|
+
//# sourceMappingURL=postgres-BDti0rrm.mjs.map
|