mnemocyte 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +171 -17
- package/dist/embedders/openai.d.mts +1 -1
- package/dist/embedders/openai.d.mts.map +1 -1
- package/dist/embedders/openai.mjs +23 -8
- package/dist/embedders/openai.mjs.map +1 -1
- package/dist/errors-B_7ZdjEO.mjs.map +1 -1
- package/dist/index.d.mts +6 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1036 -523
- package/dist/index.mjs.map +1 -1
- package/dist/{types-gOPLre4V.d.mts → types-DH0inEay.d.mts} +107 -27
- package/dist/types-DH0inEay.d.mts.map +1 -0
- package/migrations/0000_initial.sql.template +2 -1
- package/migrations/0002_add_embedding_model.sql +15 -0
- package/migrations/meta/0002_snapshot.json +315 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +1 -1
- package/dist/types-gOPLre4V.d.mts.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["insertMemoryRows","vectorSearchQuery","lexicalSearchQuery","getMemoryEmbeddingsQuery","deleteMemoryQuery","deleteMemoriesForEntityQuery","findDuplicatePairsQuery"],"sources":["../src/db/vector.ts","../src/db/schema.ts","../src/db/index.ts","../src/memory/json.ts","../src/memory/records.ts","../src/retrieval/scorer.ts","../src/context/formatter.ts","../src/context/tokens.ts","../src/context/builder.ts","../src/observability.ts","../src/memory/defaults.ts","../src/resilience.ts","../src/memory/embeddings.ts","../src/memory/validation.ts","../src/memory/client-core.ts","../src/memory/filters.ts","../src/memory/in-memory.ts","../src/db/queries/events.ts","../src/db/queries/memories.ts","../src/db/queries/meta.ts","../src/memory/postgres-records.ts","../src/memory/postgres.ts","../src/client.ts"],"sourcesContent":["export function formatVectorComponent(value: number): string {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new Error(\"Vector values must be finite numbers.\");\n\t}\n\treturn Object.is(value, -0) ? \"0\" : value.toFixed(17);\n}\n","import { sql } from \"drizzle-orm\";\nimport {\n\ttype AnyPgColumn,\n\tcustomType,\n\tindex,\n\tinteger,\n\tjsonb,\n\tpgTable,\n\treal,\n\ttext,\n\ttimestamp,\n} from \"drizzle-orm/pg-core\";\nimport type { JsonObject } from \"../types.js\";\nimport { formatVectorComponent } from \"./vector.js\";\n\nconst vector = customType<{\n\tdata: number[];\n\tdriverData: string;\n\tconfig: { dimensions?: number };\n}>({\n\tdataType(config) {\n\t\tconst dimensions = config?.dimensions ?? 1536;\n\t\treturn `vector(${dimensions})`;\n\t},\n\ttoDriver(value) {\n\t\treturn `[${value.map(formatVectorComponent).join(\",\")}]`;\n\t},\n\tfromDriver(value) {\n\t\treturn value.slice(1, -1).split(\",\").filter(Boolean).map(Number);\n\t},\n});\n\nexport const memoriesTable = pgTable(\n\t\"mnemocyte_memories\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tentityId: text(\"entity_id\").notNull(),\n\t\tcontent: text(\"content\").notNull(),\n\t\ttype: text(\"type\").notNull().default(\"fact\"),\n\t\timportance: text(\"importance\").notNull().default(\"normal\"),\n\t\ttags: text(\"tags\").array().notNull().default(sql`'{}'::text[]`),\n\t\tsource: text(\"source\"),\n\t\tmetadata: jsonb(\"metadata\").$type<JsonObject>().notNull().default({}),\n\t\tconfidence: real(\"confidence\").notNull().default(1),\n\t\tembedding: vector(\"embedding\", { dimensions: 1536 }),\n\t\tembeddingModel: text(\"embedding_model\").notNull(),\n\t\tembeddingDimensions: integer(\"embedding_dimensions\").notNull(),\n\t\tsupersededBy: text(\"superseded_by\").references(\n\t\t\t(): AnyPgColumn => memoriesTable.id,\n\t\t),\n\t\tsupersededAt: timestamp(\"superseded_at\", { withTimezone: true }),\n\t\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }),\n\t\tlastAccessedAt: timestamp(\"last_accessed_at\", { withTimezone: true }),\n\t\taccessCount: integer(\"access_count\").notNull().default(0),\n\t\tcreatedAt: timestamp(\"created_at\", { withTimezone: true })\n\t\t\t.notNull()\n\t\t\t.defaultNow(),\n\t\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true })\n\t\t\t.notNull()\n\t\t\t.defaultNow(),\n\t},\n\t(table) => [\n\t\tindex(\"mnemocyte_memories_entity_idx\").on(table.entityId),\n\t\tindex(\"mnemocyte_memories_entity_type_idx\").on(table.entityId, table.type),\n\t\tindex(\"mnemocyte_memories_embedding_hnsw_idx\").using(\n\t\t\t\"hnsw\",\n\t\t\ttable.embedding.op(\"vector_cosine_ops\"),\n\t\t),\n\t],\n);\n\nexport const eventsTable = pgTable(\n\t\"mnemocyte_events\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tentityId: text(\"entity_id\").notNull(),\n\t\tdescription: text(\"description\").notNull(),\n\t\tmetadata: jsonb(\"metadata\").$type<JsonObject>().notNull().default({}),\n\t\ttimestamp: timestamp(\"timestamp\", { withTimezone: true })\n\t\t\t.notNull()\n\t\t\t.defaultNow(),\n\t},\n\t(table) => [\n\t\tindex(\"mnemocyte_events_entity_time_idx\").on(\n\t\t\ttable.entityId,\n\t\t\ttable.timestamp,\n\t\t),\n\t],\n);\n\nexport const metaTable = pgTable(\"mnemocyte_meta\", {\n\tkey: text(\"key\").primaryKey(),\n\tembeddingDimensions: integer(\"embedding_dimensions\").notNull(),\n});\n\nexport type MemoryRow = typeof memoriesTable.$inferSelect;\nexport type NewMemoryRow = typeof memoriesTable.$inferInsert;\nexport type EventRow = typeof eventsTable.$inferSelect;\nexport type NewEventRow = typeof eventsTable.$inferInsert;\nexport type MetaRow = typeof metaTable.$inferSelect;\n","import { drizzle, type PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { MnemocyteError } from \"../errors.js\";\nimport * as schema from \"./schema.js\";\n\nexport type MnemocyteDatabase = PostgresJsDatabase<typeof schema>;\n\nexport interface DatabaseHandle {\n\tdb: MnemocyteDatabase;\n\tclose(): Promise<void>;\n}\n\ntype PostgresSslMode =\n\t| \"require\"\n\t| \"prefer\"\n\t| \"allow\"\n\t| \"verify-full\"\n\t| \"disable\";\n\ntype ValidPostgresSsl =\n\t| \"require\"\n\t| \"prefer\"\n\t| \"allow\"\n\t| \"verify-full\"\n\t| boolean\n\t| { rejectUnauthorized: false };\n\nfunction parseSslFromUrl(url: URL): ValidPostgresSsl | undefined {\n\tconst mode = url.searchParams.get(\"sslmode\") as PostgresSslMode | null;\n\tif (!mode || mode === \"disable\") return undefined;\n\n\tif (mode === \"require\" || mode === \"prefer\" || mode === \"allow\") {\n\t\treturn { rejectUnauthorized: false };\n\t}\n\n\tif (mode === \"verify-full\") return \"verify-full\";\n\n\treturn undefined;\n}\n\nexport function createDatabase(databaseUrl: string): DatabaseHandle {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(databaseUrl);\n\t} catch (error) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl must be a valid Postgres connection URL.\",\n\t\t\t\"CONFIG\",\n\t\t\terror,\n\t\t);\n\t}\n\tconst ssl = parseSslFromUrl(url);\n\n\tconst isPooler =\n\t\turl.port === \"6543\" || url.searchParams.get(\"pgbouncer\") === \"true\";\n\n\tconst client = postgres(databaseUrl, {\n\t\tmax: 10,\n\t\tidle_timeout: 20,\n\t\tconnect_timeout: 10,\n\t\t...(ssl ? { ssl } : {}),\n\t\t...(isPooler ? { prepare: false } : {}),\n\t});\n\n\treturn {\n\t\tdb: drizzle(client, { schema }),\n\t\tasync close() {\n\t\t\tawait client.end();\n\t\t},\n\t};\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport type { JsonObject, JsonValue } from \"../types.js\";\n\nfunction invalidJsonValue(path: string, cause?: unknown): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t`${path} must contain only JSON-compatible value data.`,\n\t\t\"VALIDATION\",\n\t\tcause,\n\t);\n}\n\nfunction cloneJsonValue(\n\tvalue: unknown,\n\tpath: string,\n\tancestors: Set<object>,\n): JsonValue {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\"\n\t) {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\treturn Object.is(value, -0) ? 0 : value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow invalidJsonValue(path);\n\t}\n\tif (ancestors.has(value)) {\n\t\tthrow invalidJsonValue(path);\n\t}\n\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (\n\t\t\t\tObject.getOwnPropertySymbols(value).length > 0 ||\n\t\t\t\tObject.keys(value).some((key) => !/^(0|[1-9]\\d*)$/.test(key))\n\t\t\t) {\n\t\t\t\tthrow invalidJsonValue(path);\n\t\t\t}\n\t\t\treturn Array.from({ length: value.length }, (_, index) => {\n\t\t\t\tif (!Object.hasOwn(value, index)) {\n\t\t\t\t\tthrow invalidJsonValue(`${path}[${index}]`);\n\t\t\t\t}\n\t\t\t\treturn cloneJsonValue(value[index], `${path}[${index}]`, ancestors);\n\t\t\t});\n\t\t}\n\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(value);\n\t\tconst entries: Array<[string, JsonValue]> = [];\n\t\tfor (const key of Reflect.ownKeys(descriptors)) {\n\t\t\tif (typeof key !== \"string\") {\n\t\t\t\tthrow invalidJsonValue(path);\n\t\t\t}\n\t\t\tconst descriptor = descriptors[key];\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t!(\"value\" in descriptor)\n\t\t\t) {\n\t\t\t\tthrow invalidJsonValue(`${path}.${key}`);\n\t\t\t}\n\t\t\tentries.push([\n\t\t\t\tkey,\n\t\t\t\tcloneJsonValue(descriptor.value, `${path}.${key}`, ancestors),\n\t\t\t]);\n\t\t}\n\t\treturn Object.fromEntries(entries);\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\n/** Validate and deep-clone a JSON-compatible object. */\nexport function cloneJsonObject(value: unknown, path = \"metadata\"): JsonObject {\n\ttry {\n\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\treturn cloneJsonValue(value, path, new Set()) as JsonObject;\n\t} catch (error) {\n\t\tif (error instanceof MnemocyteError) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow invalidJsonValue(path, error);\n\t}\n}\n\n/** Assert that a runtime value is a JSON-compatible object. */\nexport function validateJsonObject(\n\tvalue: unknown,\n\tpath = \"metadata\",\n): asserts value is JsonObject {\n\tcloneJsonObject(value, path);\n}\n","import type { Memory } from \"../types.js\";\nimport { cloneJsonObject } from \"./json.js\";\n\nexport interface StoredMemory extends Memory {\n\tembedding: number[];\n}\n\nexport function normalizeTags(tags: readonly string[] | undefined): string[] {\n\tif (!tags) {\n\t\treturn [];\n\t}\n\treturn [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];\n}\n\nexport function createId(): string {\n\treturn `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Generate a unique audit-event id (`evt_*`). */\nexport function createEventId(): string {\n\treturn `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport function cloneMemory(memory: Memory): Memory {\n\treturn {\n\t\tid: memory.id,\n\t\tentityId: memory.entityId,\n\t\tcontent: memory.content,\n\t\ttype: memory.type,\n\t\timportance: memory.importance,\n\t\ttags: [...memory.tags],\n\t\tsource: memory.source,\n\t\tmetadata: cloneJsonObject(memory.metadata),\n\t\tconfidence: memory.confidence,\n\t\tembeddingModel: memory.embeddingModel,\n\t\tembeddingDimensions: memory.embeddingDimensions,\n\t\tsupersededBy: memory.supersededBy,\n\t\tsupersededAt: memory.supersededAt ? new Date(memory.supersededAt) : null,\n\t\texpiresAt: memory.expiresAt ? new Date(memory.expiresAt) : null,\n\t\tlastAccessedAt: memory.lastAccessedAt\n\t\t\t? new Date(memory.lastAccessedAt)\n\t\t\t: null,\n\t\taccessCount: memory.accessCount,\n\t\tcreatedAt: new Date(memory.createdAt),\n\t\tupdatedAt: new Date(memory.updatedAt),\n\t};\n}\n","import { cloneMemory } from \"../memory/records.js\";\nimport type {\n\tImportanceLevel,\n\tMemory,\n\tMemoryWithScore,\n\tRecallInput,\n\tRetrievalConfig,\n\tRetrievalScoreWeights,\n} from \"../types.js\";\n\nconst IMPORTANCE_SCORES: Record<ImportanceLevel, number> = {\n\tlow: 0,\n\tnormal: 0.5,\n\thigh: 0.8,\n\tcritical: 1,\n};\n\nexport const DEFAULT_RETRIEVAL_WEIGHTS: Readonly<\n\tRequired<RetrievalScoreWeights>\n> = {\n\tvector: 0.55,\n\tlexical: 0.2,\n\trecency: 0.1,\n\tconfidence: 0.05,\n\taccess: 0.05,\n\timportance: 0.05,\n};\n\nconst DEFAULT_RECENCY_HALF_LIFE_DAYS = 90;\nconst DEFAULT_ACCESS_SATURATION = 10;\nexport const DEFAULT_CANDIDATE_MULTIPLIER = 3;\n\nexport interface ScoringConfig {\n\tweights: Required<RetrievalScoreWeights>;\n\trecencyHalfLifeDays: number;\n\taccessSaturation: number;\n}\n\nexport function cosineSimilarity(\n\ta: readonly number[],\n\tb: readonly number[],\n): number {\n\tlet dot = 0;\n\tlet aMagnitude = 0;\n\tlet bMagnitude = 0;\n\tfor (let i = 0; i < a.length; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\taMagnitude += av * av;\n\t\tbMagnitude += bv * bv;\n\t}\n\tif (aMagnitude === 0 || bMagnitude === 0) {\n\t\treturn 0;\n\t}\n\treturn dot / (Math.sqrt(aMagnitude) * Math.sqrt(bMagnitude));\n}\n\nexport function tokenizeQuery(query: string): readonly string[] {\n\treturn query.toLowerCase().split(/\\s+/).filter(Boolean);\n}\n\nexport function lexicalScoreWithTerms(\n\tcontent: string,\n\tterms: readonly string[],\n): number {\n\tif (terms.length === 0) {\n\t\treturn 0;\n\t}\n\tconst lowerContent = content.toLowerCase();\n\tconst matches = terms.filter((term) => lowerContent.includes(term)).length;\n\treturn matches / terms.length;\n}\n\nexport function createLexicalScorer(\n\tquery: string,\n): (content: string) => number {\n\tconst terms = tokenizeQuery(query);\n\treturn (content) => lexicalScoreWithTerms(content, terms);\n}\n\nfunction clampScore(value: number): number {\n\tif (!Number.isFinite(value)) {\n\t\treturn 0;\n\t}\n\treturn Math.max(0, Math.min(1, value));\n}\n\nfunction normalizeWeights(\n\tweights: RetrievalScoreWeights | undefined,\n): Required<RetrievalScoreWeights> {\n\tconst merged = { ...DEFAULT_RETRIEVAL_WEIGHTS, ...weights };\n\tconst total =\n\t\tmerged.vector +\n\t\tmerged.lexical +\n\t\tmerged.recency +\n\t\tmerged.confidence +\n\t\tmerged.access +\n\t\tmerged.importance;\n\tif (total <= 0) {\n\t\treturn { ...DEFAULT_RETRIEVAL_WEIGHTS };\n\t}\n\treturn {\n\t\tvector: merged.vector / total,\n\t\tlexical: merged.lexical / total,\n\t\trecency: merged.recency / total,\n\t\tconfidence: merged.confidence / total,\n\t\taccess: merged.access / total,\n\t\timportance: merged.importance / total,\n\t};\n}\n\nexport function createScoringConfig(config?: RetrievalConfig): ScoringConfig {\n\treturn {\n\t\tweights: normalizeWeights(config?.weights),\n\t\trecencyHalfLifeDays:\n\t\t\tconfig?.recencyHalfLifeDays ?? DEFAULT_RECENCY_HALF_LIFE_DAYS,\n\t\taccessSaturation: config?.accessSaturation ?? DEFAULT_ACCESS_SATURATION,\n\t};\n}\n\nfunction recencyScore(createdAt: Date, halfLifeDays: number): number {\n\tconst ageMs = Date.now() - createdAt.getTime();\n\tconst ageDays = Math.max(0, ageMs / 86_400_000);\n\treturn Math.exp((-Math.LN2 * ageDays) / halfLifeDays);\n}\n\nfunction accessScore(accessCount: number, saturation: number): number {\n\tif (accessCount <= 0) {\n\t\treturn 0;\n\t}\n\treturn Math.min(1, Math.log1p(accessCount) / Math.log1p(saturation));\n}\n\nexport function toScoredMemoryWithConfig(\n\tmemory: Memory,\n\tvector: number,\n\tlexical: number,\n\tinput: RecallInput,\n\tconfig: ScoringConfig,\n): MemoryWithScore {\n\tconst { weights } = config;\n\tconst recency = recencyScore(memory.createdAt, config.recencyHalfLifeDays);\n\tconst confidence = clampScore(memory.confidence);\n\tconst access = accessScore(memory.accessCount, config.accessSaturation);\n\tconst importance = IMPORTANCE_SCORES[memory.importance];\n\tconst score = Math.max(\n\t\t0,\n\t\tMath.min(\n\t\t\t1,\n\t\t\tclampScore(vector) * weights.vector +\n\t\t\t\tclampScore(lexical) * weights.lexical +\n\t\t\t\trecency * weights.recency +\n\t\t\t\tconfidence * weights.confidence +\n\t\t\t\taccess * weights.access +\n\t\t\t\timportance * weights.importance,\n\t\t),\n\t);\n\treturn {\n\t\t...cloneMemory(memory),\n\t\tscore,\n\t\tscores: {\n\t\t\tvector: clampScore(vector),\n\t\t\tlexical: clampScore(lexical),\n\t\t\trecency,\n\t\t\tconfidence,\n\t\t\taccess,\n\t\t\timportance,\n\t\t},\n\t\texplanation: input.explain\n\t\t\t? {\n\t\t\t\t\tvectorScore: clampScore(vector),\n\t\t\t\t\tlexicalScore: clampScore(lexical),\n\t\t\t\t\trecencyScore: recency,\n\t\t\t\t\tconfidenceScore: confidence,\n\t\t\t\t\taccessScore: access,\n\t\t\t\t\timportanceScore: importance,\n\t\t\t\t\timportanceBoost: importance * weights.importance,\n\t\t\t\t\tweights,\n\t\t\t\t\tfinalScore: score,\n\t\t\t\t}\n\t\t\t: null,\n\t};\n}\n","import type { 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 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 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] of memories.entries()) {\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t`--- MEMORY ${index + 1} START ---`,\n\t\t\tformatMetadata(memory),\n\t\t\tmemory.content,\n\t\t\t`--- MEMORY ${index + 1} END ---`,\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\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[truncated to fit token budget]`;\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\treturn best || \"[truncated to fit token budget]\";\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\nexport async 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\tconst startedAt = Date.now();\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","import type {\n\tFindDuplicatesInput,\n\tImportanceLevel,\n\tMemoryType,\n} from \"../types.js\";\n\nexport const DEFAULT_LIMIT = 10;\nexport const DEFAULT_MIN_SCORE = 0;\nexport const DEFAULT_TYPE: MemoryType = \"fact\";\nexport const DEFAULT_IMPORTANCE: ImportanceLevel = \"normal\";\n\n/**\n * Ordering of {@link ImportanceLevel} from least to most important. Used\n * by `prune({ maxImportance })` to compare a memory's importance against\n * the caller-supplied ceiling.\n */\nexport const IMPORTANCE_RANK: Record<ImportanceLevel, number> = {\n\tlow: 0,\n\tnormal: 1,\n\thigh: 2,\n\tcritical: 3,\n};\n\n/** Default cosine-similarity threshold for {@link FindDuplicatesInput}. */\nexport const DEFAULT_DUPLICATE_THRESHOLD = 0.95;\n/** Default cap on the number of duplicate pairs returned. */\nexport const DEFAULT_DUPLICATE_LIMIT = 100;\n/** Default cap on audit-log entries returned per `listAuditLog`. */\nexport const DEFAULT_AUDIT_LOG_LIMIT = 50;\n","import { MnemocyteError } from \"./errors.js\";\nimport type { ProviderResilienceConfig } from \"./types.js\";\n\n/**\n * Default per-provider-call timeout. Disabled by default so that callers\n * who do not configure {@link ProviderResilienceConfig.timeoutMs} are\n * unaffected.\n */\nconst DEFAULT_TIMEOUT_MS = 0;\n/** Default number of retry attempts on transient provider failures. */\nconst DEFAULT_RETRIES = 0;\n/** Default base backoff delay used between retry attempts. */\nconst DEFAULT_BASE_DELAY_MS = 100;\n/** Default ceiling for retry backoff delay. */\nconst DEFAULT_MAX_DELAY_MS = 2000;\n\n/**\n * Throw a {@link MnemocyteError} with code `\"ABORTED\"` if `signal` is\n * already aborted. Safe to call with `undefined`.\n */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Operation was aborted.\",\n\t\t\t\"ABORTED\",\n\t\t\tsignal.reason,\n\t\t);\n\t}\n}\n\n/**\n * Heuristic default for whether an error should be retried.\n *\n * Conservative by design: only retries on common transient failure\n * indicators (network errors, 5xx-ish messages, `ECONN*` etc.). Never\n * retries on validation, configuration, or {@link MnemocyteError} of\n * code `\"VALIDATION\"` / `\"CONFIG\"` / `\"ABORTED\"`.\n */\nexport function defaultShouldRetry(error: unknown): boolean {\n\tif (error instanceof MnemocyteError) {\n\t\tif (\n\t\t\terror.code === \"VALIDATION\" ||\n\t\t\terror.code === \"CONFIG\" ||\n\t\t\terror.code === \"ABORTED\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"status\" in error &&\n\t\ttypeof (error as { status?: unknown }).status === \"number\" &&\n\t\t[429, 500, 502, 503, 504].includes((error as { status: number }).status)\n\t) {\n\t\treturn true;\n\t}\n\tif (error instanceof Error) {\n\t\tconst message = error.message.toLowerCase();\n\t\tif (\n\t\t\tmessage.includes(\"econn\") ||\n\t\t\tmessage.includes(\"etimedout\") ||\n\t\t\tmessage.includes(\"network\") ||\n\t\t\tmessage.includes(\"timeout\") ||\n\t\t\tmessage.includes(\"temporarily\") ||\n\t\t\tmessage.includes(\"rate limit\") ||\n\t\t\tmessage.includes(\"503\") ||\n\t\t\tmessage.includes(\"502\") ||\n\t\t\tmessage.includes(\"504\") ||\n\t\t\tmessage.includes(\"500\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Compute the backoff delay for the given retry attempt, using exponential\n * growth capped at {@link ProviderResilienceConfig.maxDelayMs}.\n *\n * `attempt` is 1-indexed: the delay before the first retry uses\n * `attempt = 1`, before the second retry `attempt = 2`, etc.\n */\nfunction computeDelayMs(\n\tattempt: number,\n\tbaseDelayMs: number,\n\tmaxDelayMs: number,\n): number {\n\tconst exponential = baseDelayMs * 2 ** (attempt - 1);\n\treturn Math.max(0, Math.min(maxDelayMs, exponential));\n}\n\n/**\n * Promise-based `setTimeout` that rejects with an `\"ABORTED\"`\n * {@link MnemocyteError} if `signal` aborts while waiting.\n */\nfunction delay(ms: number, signal: AbortSignal | undefined): Promise<void> {\n\tif (ms <= 0) {\n\t\tthrowIfAborted(signal);\n\t\treturn Promise.resolve();\n\t}\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(\n\t\t\t\tnew MnemocyteError(\"Operation was aborted.\", \"ABORTED\", signal?.reason),\n\t\t\t);\n\t\t};\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(\n\t\t\t\t\tnew MnemocyteError(\n\t\t\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t\tsignal.reason,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t});\n}\n\nfunction timeoutError(timeoutMs: number): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t`Provider call timed out after ${timeoutMs}ms.`,\n\t\t\"TIMEOUT\",\n\t);\n}\n\n/**\n * Run one provider attempt with a signal linked to the caller's signal and\n * Mnemocyte's configured timeout. Timeout aborts are actively propagated to\n * providers that honor `AbortSignal`.\n */\nfunction runAttempt<T>(\n\taction: (signal: AbortSignal | undefined) => Promise<T>,\n\ttimeoutMs: number,\n\tsignal: AbortSignal | undefined,\n): Promise<T> {\n\tif (timeoutMs <= 0 && !signal) {\n\t\treturn action(undefined);\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst controller = new AbortController();\n\t\tconst timer =\n\t\t\ttimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\tif (settled) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tcontroller.abort(timeoutError(timeoutMs));\n\t\t\t\t\t\treject(timeoutError(timeoutMs));\n\t\t\t\t\t}, timeoutMs)\n\t\t\t\t: undefined;\n\t\tconst onAbort = (): void => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\tcontroller.abort(signal?.reason);\n\t\t\treject(\n\t\t\t\tnew MnemocyteError(\"Operation was aborted.\", \"ABORTED\", signal?.reason),\n\t\t\t);\n\t\t};\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcontroller.abort(signal.reason);\n\t\t\t\treject(\n\t\t\t\t\tnew MnemocyteError(\n\t\t\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t\tsignal.reason,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t\taction(controller.signal).then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Options accepted by {@link withResilience}.\n */\nexport interface ResilienceCallOptions {\n\t/** External cancellation signal forwarded to each attempt. */\n\tsignal?: AbortSignal;\n\t/** Provider-level retry/timeout configuration. */\n\tresilience?: ProviderResilienceConfig;\n}\n\n/**\n * Run `action` with timeout, retry, and abort handling derived from\n * `options.resilience` and `options.signal`. Each retry attempt receives\n * a fresh `AbortSignal` linked to the caller's signal — so callers may\n * abort mid-retry and the in-flight attempt will cancel promptly if the\n * underlying provider honours signals.\n *\n * Errors from {@link MnemocyteError} with code `\"VALIDATION\"` /\n * `\"CONFIG\"` / `\"ABORTED\"` are never retried.\n */\nexport async function withResilience<T>(\n\taction: (signal: AbortSignal | undefined) => Promise<T>,\n\toptions: ResilienceCallOptions = {},\n): Promise<T> {\n\tconst config = options.resilience ?? {};\n\tconst timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\tconst retries = Math.max(0, config.retries ?? DEFAULT_RETRIES);\n\tconst baseDelayMs = Math.max(0, config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n\tconst maxDelayMs = Math.max(\n\t\tbaseDelayMs,\n\t\tconfig.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,\n\t);\n\tconst shouldRetry = config.shouldRetry ?? defaultShouldRetry;\n\tconst externalSignal = options.signal;\n\n\tthrowIfAborted(externalSignal);\n\n\tconst maxAttempts = retries + 1;\n\tlet lastError: unknown;\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n\t\tthrowIfAborted(externalSignal);\n\t\ttry {\n\t\t\treturn await runAttempt(action, timeoutMs, externalSignal);\n\t\t} catch (error) {\n\t\t\tlastError = error;\n\t\t\tif (error instanceof MnemocyteError && error.code === \"ABORTED\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (attempt >= maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (!shouldRetry(error, attempt)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst waitMs = computeDelayMs(attempt, baseDelayMs, maxDelayMs);\n\t\t\tawait delay(waitMs, externalSignal);\n\t\t}\n\t}\n\tthrow lastError;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport { 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}\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\tBuildContextInput,\n\tConsolidateInput,\n\tEmbedder,\n\tFindDuplicatesInput,\n\tListAuditLogInput,\n\tPruneInput,\n\tRecallInput,\n\tRememberInput,\n\tRetrievalConfig,\n\tRetrievalScoreWeights,\n} from \"../types.js\";\nimport { validateJsonObject } from \"./json.js\";\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 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: RememberInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tassertNonEmptyString(input.content, \"content\");\n\tif (input.metadata !== undefined) {\n\t\tvalidateJsonObject(input.metadata);\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}\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}\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 a {@link PruneInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} when no selector is supplied. Mnemocyte\n * deliberately rejects `prune({})` to avoid surprise full-table deletes.\n */\nexport function validatePruneInput(input: PruneInput): void {\n\tif (input.entityId !== undefined) {\n\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t}\n\tconst hasSelector =\n\t\tinput.entityId !== undefined ||\n\t\tinput.expired === true ||\n\t\tinput.superseded === true ||\n\t\tinput.createdBefore !== undefined ||\n\t\tinput.notAccessedSince !== undefined ||\n\t\t(input.types !== undefined && input.types.length > 0) ||\n\t\t(input.tags !== undefined && input.tags.length > 0) ||\n\t\tinput.maxImportance !== undefined;\n\tif (!hasSelector) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"prune requires at least one selector (entityId, expired, superseded, createdBefore, notAccessedSince, types, tags, or maxImportance).\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\n/**\n * 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}\n\n/**\n * Validate a {@link ConsolidateInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed inputs (empty `supersededIds`\n * or a `survivorId` appearing in `supersededIds`).\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\tfor (const id of input.supersededIds) {\n\t\tassertNonEmptyString(id, \"supersededIds[*]\");\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}\n","import { buildContext } from \"../context/builder.js\";\nimport { MnemocyteError } from \"../errors.js\";\nimport { observe } from \"../observability.js\";\nimport {\n\tcosineSimilarity,\n\tcreateLexicalScorer,\n\tcreateScoringConfig,\n\tDEFAULT_CANDIDATE_MULTIPLIER,\n\ttoScoredMemoryWithConfig,\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\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 { MemoryStore } from \"./store.js\";\nimport {\n\tassertLimit,\n\tassertMinScore,\n\tassertNonEmptyString,\n\tcontextInputToRecallInput,\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\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 createStoredMemory(\n\tconfig: MnemocyteConfig,\n\tinput: RememberInput,\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: cloneJsonObject(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: cloneJsonObject(metadata),\n\t\ttimestamp,\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\tlet closed = false;\n\n\tfunction assertOpen(): void {\n\t\tif (closed) {\n\t\t\tthrow new MnemocyteError(\"Mnemocyte client is closed.\", \"DB\");\n\t\t}\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\tasync function remember(input: RememberInput): Promise<Memory> {\n\t\tconst preparedInput: RememberInput = {\n\t\t\t...input,\n\t\t\tmetadata: cloneJsonObject(input.metadata ?? {}),\n\t\t};\n\t\treturn observe(\n\t\t\tconfig,\n\t\t\tstore.backend,\n\t\t\t\"remember\",\n\t\t\t{ entityId: preparedInput.entityId },\n\t\t\tasync () => {\n\t\t\t\tassertOpen();\n\t\t\t\tvalidateRememberInput(preparedInput);\n\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\tconst embedding = await embedOne(\n\t\t\t\t\tconfig.embedder,\n\t\t\t\t\tpreparedInput.content,\n\t\t\t\t\tproviderOptions(config, preparedInput.signal),\n\t\t\t\t);\n\t\t\t\tconst [memory] = await store.insertMemories([\n\t\t\t\t\tcreateStoredMemory(config, preparedInput, embedding, new Date()),\n\t\t\t\t]);\n\t\t\t\tif (!memory) {\n\t\t\t\t\tthrow new MnemocyteError(\"Memory insert returned no rows.\", \"DB\");\n\t\t\t\t}\n\t\t\t\tawait recordAudit([\n\t\t\t\t\tauditEvent(memory.entityId, \"memory.created\", {\n\t\t\t\t\t\tmemoryId: memory.id,\n\t\t\t\t\t\ttype: memory.type,\n\t\t\t\t\t\timportance: memory.importance,\n\t\t\t\t\t}),\n\t\t\t\t]);\n\t\t\t\treturn cloneMemory(memory);\n\t\t\t},\n\t\t\t(memory) => ({ memoryId: memory.id, count: 1 }),\n\t\t);\n\t}\n\n\tasync function rememberMany(\n\t\tinput: RememberManyInput | readonly RememberInput[],\n\t): Promise<Memory[]> {\n\t\tconst positional = isPositionalRememberManyInput(input);\n\t\tconst inputs = positional ? input : input.inputs;\n\t\tconst signal = positional ? input[0]?.signal : input.signal;\n\t\tconst preparedInputs = inputs.map(\n\t\t\t(item): RememberInput => ({\n\t\t\t\t...item,\n\t\t\t\tmetadata: cloneJsonObject(item.metadata ?? {}),\n\t\t\t}),\n\t\t);\n\t\treturn observe(\n\t\t\tconfig,\n\t\t\tstore.backend,\n\t\t\t\"rememberMany\",\n\t\t\t{ count: preparedInputs.length },\n\t\t\tasync () => {\n\t\t\t\tassertOpen();\n\t\t\t\tif (preparedInputs.length === 0) {\n\t\t\t\t\treturn [];\n\t\t\t\t}\n\t\t\t\tfor (const item of preparedInputs) {\n\t\t\t\t\tvalidateRememberInput(item);\n\t\t\t\t}\n\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\tconst embeddings = await embedMany(\n\t\t\t\t\tconfig.embedder,\n\t\t\t\t\tpreparedInputs.map((item) => item.content),\n\t\t\t\t\tproviderOptions(config, signal),\n\t\t\t\t);\n\t\t\t\tconst now = new Date();\n\t\t\t\tconst stored = preparedInputs.map((item, idx) =>\n\t\t\t\t\tcreateStoredMemory(config, item, embeddings[idx] as number[], now),\n\t\t\t\t);\n\t\t\t\tconst memories = await store.insertMemories(stored);\n\t\t\t\tawait recordAudit(\n\t\t\t\t\tmemories.map((memory) =>\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);\n\t\t\t\treturn memories.map(cloneMemory);\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\tasync recall(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"recall\",\n\t\t\t\t{ entityId: input.entityId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tvalidateRecallInput(input);\n\t\t\t\t\tconst limit = input.limit ?? config.defaults?.limit ?? DEFAULT_LIMIT;\n\t\t\t\t\tconst minScore =\n\t\t\t\t\t\tinput.minScore ?? config.defaults?.minScore ?? DEFAULT_MIN_SCORE;\n\t\t\t\t\tassertLimit(limit);\n\t\t\t\t\tassertMinScore(minScore);\n\t\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\t\tconst queryEmbedding = await embedOne(\n\t\t\t\t\t\tconfig.embedder,\n\t\t\t\t\t\tinput.query,\n\t\t\t\t\t\tproviderOptions(config, input.signal),\n\t\t\t\t\t);\n\t\t\t\t\tconst candidateMultiplier =\n\t\t\t\t\t\tconfig.retrieval?.candidateMultiplier ??\n\t\t\t\t\t\tDEFAULT_CANDIDATE_MULTIPLIER;\n\t\t\t\t\tconst candidateLimit = Math.max(limit, limit * candidateMultiplier);\n\t\t\t\t\tconst scoreLexical = createLexicalScorer(input.query);\n\t\t\t\t\tconst scoringConfig = createScoringConfig(config.retrieval);\n\t\t\t\t\tconst [vectorCandidates, lexicalCandidates] = await Promise.all([\n\t\t\t\t\t\tstore.vectorSearch({\n\t\t\t\t\t\t\t...input,\n\t\t\t\t\t\t\tembedding: queryEmbedding,\n\t\t\t\t\t\t\tlimit: candidateLimit,\n\t\t\t\t\t\t\tminScore: 0,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tstore.lexicalSearch({ ...input, limit: candidateLimit }),\n\t\t\t\t\t]);\n\t\t\t\t\tconst merged = new Map<string, ScoredCandidate>();\n\t\t\t\t\tfor (const candidate of vectorCandidates) {\n\t\t\t\t\t\tmerged.set(candidate.memory.id, {\n\t\t\t\t\t\t\tmemory: candidate.memory,\n\t\t\t\t\t\t\tvectorScore: candidate.vectorScore,\n\t\t\t\t\t\t\tlexicalScore: scoreLexical(candidate.memory.content),\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst lexicalOnly = lexicalCandidates.filter(\n\t\t\t\t\t\t(candidate) => !merged.has(candidate.memory.id),\n\t\t\t\t\t);\n\t\t\t\t\tconst lexicalOnlyEmbeddings = await store.getMemoryEmbeddings(\n\t\t\t\t\t\tlexicalOnly.map((candidate) => candidate.memory.id),\n\t\t\t\t\t);\n\t\t\t\t\tfor (const candidate of lexicalCandidates) {\n\t\t\t\t\t\tconst existing = merged.get(candidate.memory.id);\n\t\t\t\t\t\tif (existing) {\n\t\t\t\t\t\t\texisting.lexicalScore = candidate.lexicalScore;\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst embedding = lexicalOnlyEmbeddings.get(candidate.memory.id);\n\t\t\t\t\t\tconst similarity = embedding\n\t\t\t\t\t\t\t? cosineSimilarity(embedding, queryEmbedding)\n\t\t\t\t\t\t\t: 0;\n\t\t\t\t\t\tmerged.set(candidate.memory.id, {\n\t\t\t\t\t\t\tmemory: candidate.memory,\n\t\t\t\t\t\t\tvectorScore: Math.max(0, similarity),\n\t\t\t\t\t\t\tlexicalScore: candidate.lexicalScore,\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst scored: MemoryWithScore[] = Array.from(merged.values())\n\t\t\t\t\t\t.map((entry) =>\n\t\t\t\t\t\t\ttoScoredMemoryWithConfig(\n\t\t\t\t\t\t\t\tentry.memory,\n\t\t\t\t\t\t\t\tMath.max(0, entry.vectorScore),\n\t\t\t\t\t\t\t\tMath.max(0, entry.lexicalScore),\n\t\t\t\t\t\t\t\tinput,\n\t\t\t\t\t\t\t\tscoringConfig,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t)\n\t\t\t\t\t\t.filter((memory) => memory.score >= minScore)\n\t\t\t\t\t\t.sort((a, b) => b.score - a.score)\n\t\t\t\t\t\t.slice(0, limit);\n\t\t\t\t\tawait store.markMemoriesAccessed(scored.map((memory) => memory.id));\n\t\t\t\t\treturn scored;\n\t\t\t\t},\n\t\t\t\t(result) => ({ count: result.length }),\n\t\t\t);\n\t\t},\n\t\tasync buildContext(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"buildContext\",\n\t\t\t\t{ entityId: input.entityId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tvalidateBuildContextInput(input);\n\t\t\t\t\treturn buildContext({\n\t\t\t\t\t\tinput,\n\t\t\t\t\t\trecall: (contextInput) => {\n\t\t\t\t\t\t\tconst recallInput = contextInputToRecallInput(contextInput);\n\t\t\t\t\t\t\treturn client.recall(\n\t\t\t\t\t\t\t\tinput.signal === undefined\n\t\t\t\t\t\t\t\t\t? recallInput\n\t\t\t\t\t\t\t\t\t: { ...recallInput, signal: input.signal },\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\tasync forget(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"forget\",\n\t\t\t\t{ entityId: input.entityId, memoryId: input.memoryId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t\t\t\t\tassertNonEmptyString(input.memoryId, \"memoryId\");\n\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\tconst deleted = await store.deleteMemory(\n\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\tinput.memoryId,\n\t\t\t\t\t);\n\t\t\t\t\tif (!deleted) {\n\t\t\t\t\t\tthrow new MnemocyteError(\"Memory was not found.\", \"NOT_FOUND\");\n\t\t\t\t\t}\n\t\t\t\t\tawait recordAudit([\n\t\t\t\t\t\tauditEvent(input.entityId, \"memory.deleted\", {\n\t\t\t\t\t\t\tmemoryId: input.memoryId,\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\tasync forgetAll(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"forgetAll\",\n\t\t\t\t{ entityId: input.entityId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\tconst deletedCount = await store.deleteMemoriesForEntity(\n\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t);\n\t\t\t\t\tawait recordAudit([\n\t\t\t\t\t\tauditEvent(input.entityId, \"entity.cleared\", {\n\t\t\t\t\t\t\tcount: deletedCount,\n\t\t\t\t\t\t}),\n\t\t\t\t\t]);\n\t\t\t\t\treturn deletedCount;\n\t\t\t\t},\n\t\t\t\t(count) => ({ count }),\n\t\t\t).then(() => undefined);\n\t\t},\n\t\tasync prune(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"prune\",\n\t\t\t\tinput.entityId === undefined ? {} : { entityId: input.entityId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tvalidatePruneInput(input);\n\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\tconst result = await store.prune(input);\n\t\t\t\t\tif (\n\t\t\t\t\t\tresult.deletedCount > 0 &&\n\t\t\t\t\t\tinput.entityId !== undefined &&\n\t\t\t\t\t\tresult.dryRun === false\n\t\t\t\t\t) {\n\t\t\t\t\t\tawait recordAudit([\n\t\t\t\t\t\t\tauditEvent(input.entityId, \"memory.pruned\", {\n\t\t\t\t\t\t\t\tcount: result.deletedCount,\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 result;\n\t\t\t\t},\n\t\t\t\t(result) => ({ count: result.deletedCount }),\n\t\t\t);\n\t\t},\n\t\tasync findDuplicates(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"findDuplicates\",\n\t\t\t\t{ entityId: input.entityId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tvalidateFindDuplicatesInput(input);\n\t\t\t\t\tawait ensureEmbeddingCompatibility();\n\t\t\t\t\tconst pairs = await store.findDuplicatePairs(input);\n\t\t\t\t\treturn pairs.map(toDuplicatePair);\n\t\t\t\t},\n\t\t\t\t(result) => ({ count: result.length }),\n\t\t\t);\n\t\t},\n\t\tasync listAuditLog(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"listAuditLog\",\n\t\t\t\t{ entityId: input.entityId },\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tvalidateListAuditLogInput(input);\n\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\tconst events = await store.listAuditLog(input);\n\t\t\t\t\treturn events.map((event) => ({\n\t\t\t\t\t\tid: event.id,\n\t\t\t\t\t\tentityId: event.entityId,\n\t\t\t\t\t\tdescription: event.description,\n\t\t\t\t\t\tmetadata: cloneJsonObject(event.metadata),\n\t\t\t\t\t\ttimestamp: new Date(event.timestamp),\n\t\t\t\t\t}));\n\t\t\t\t},\n\t\t\t\t(result) => ({ count: result.length }),\n\t\t\t);\n\t\t},\n\t\tasync stats(input) {\n\t\t\treturn observe(\n\t\t\t\tconfig,\n\t\t\t\tstore.backend,\n\t\t\t\t\"stats\",\n\t\t\t\tinput?.entityId ? { entityId: input.entityId } : {},\n\t\t\t\tasync () => {\n\t\t\t\t\tassertOpen();\n\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\treturn store.stats(input, new Date());\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\texperimental: {\n\t\t\tasync consolidate(input: ConsolidateInput): Promise<ConsolidateResult> {\n\t\t\t\treturn observe(\n\t\t\t\t\tconfig,\n\t\t\t\t\tstore.backend,\n\t\t\t\t\t\"consolidate\",\n\t\t\t\t\t{ entityId: input.entityId, memoryId: input.survivorId },\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\tassertOpen();\n\t\t\t\t\t\tvalidateConsolidateInput(input);\n\t\t\t\t\t\tawait ensureSchema();\n\t\t\t\t\t\tconst survivor = await store.getMemory(\n\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t\tinput.survivorId,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (!survivor) {\n\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\"Survivor memory was not found.\",\n\t\t\t\t\t\t\t\t\"NOT_FOUND\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (survivor.supersededBy !== null) {\n\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\"Survivor memory is itself superseded.\",\n\t\t\t\t\t\t\t\t\"VALIDATION\",\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst targets = await store.loadConsolidationTargets(\n\t\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\t\tinput.supersededIds,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tconst foundIds = new Set(targets.map((target) => target.id));\n\t\t\t\t\t\tfor (const id of input.supersededIds) {\n\t\t\t\t\t\t\tif (!foundIds.has(id)) {\n\t\t\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\t\t\"Superseded memory was not found.\",\n\t\t\t\t\t\t\t\t\t\"NOT_FOUND\",\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\tconst losers = targets.filter(\n\t\t\t\t\t\t\t(target) => target.supersededBy === null,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tif (losers.length === 0) {\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\t\tsupersededCount: 0,\n\t\t\t\t\t\t\t\tsupersededIds: [],\n\t\t\t\t\t\t\t} satisfies ConsolidateResult;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst result = await store.consolidate({\n\t\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\tsurvivorTags: survivor.tags,\n\t\t\t\t\t\t\tsupersededIds: losers.map((loser) => loser.id),\n\t\t\t\t\t\t\tmergeTags: input.mergeTags !== false,\n\t\t\t\t\t\t\tnow: new Date(),\n\t\t\t\t\t\t\tauditEnabled: config.audit?.enabled === true,\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\tsupersededCount: result.supersededIds.length,\n\t\t\t\t\t\t\tsupersededIds: result.supersededIds,\n\t\t\t\t\t\t} satisfies ConsolidateResult;\n\t\t\t\t\t},\n\t\t\t\t\t(result) => ({ count: result.supersededCount }),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tasync close() {\n\t\t\treturn observe(config, store.backend, \"close\", {}, async () => {\n\t\t\t\tif (!closed) {\n\t\t\t\t\tclosed = true;\n\t\t\t\t\tawait store.close();\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t};\n\n\treturn client;\n}\n","import type {\n\tFindDuplicatesInput,\n\tMemory,\n\tPruneInput,\n\tRecallInput,\n} from \"../types.js\";\nimport { IMPORTANCE_RANK } from \"./defaults.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 {@link PruneInput}. 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: PruneInput,\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 { cosineSimilarity, createLexicalScorer } 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 {\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 type {\n\tMemoryStore,\n\tStoreConsolidateInput,\n\tStoreConsolidateResult,\n\tStoreDuplicatePair,\n\tStoreLexicalCandidate,\n\tStoreLexicalSearchInput,\n\tStoreVectorCandidate,\n\tStoreVectorSearchInput,\n} from \"./store.js\";\n\nfunction cloneStoredMemory(memory: StoredMemory): StoredMemory {\n\treturn {\n\t\t...cloneMemory(memory),\n\t\tembedding: [...memory.embedding],\n\t};\n}\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\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\tconst stored = cloneStoredMemory(row);\n\t\t\t\tmemories.set(stored.id, stored);\n\t\t\t\tinserted.push(cloneMemory(stored));\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 minScore = input.minScore ?? 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: Math.max(\n\t\t\t\t\t\t0,\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 >= minScore)\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\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}\n\t\t\t}\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\treturn memories.delete(memoryId);\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\tlet deleted = 0;\n\t\t\tfor (const [id, memory] of memories) {\n\t\t\t\tif (memory.entityId === entityId) {\n\t\t\t\t\tmemories.delete(id);\n\t\t\t\t\tdeleted += 1;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn deleted;\n\t\t},\n\t\tasync prune(input) {\n\t\t\tconst now = new Date();\n\t\t\tconst matched: string[] = [];\n\t\t\tfor (const memory of memories.values()) {\n\t\t\t\tif (matchesPruneFilter(memory, input, now)) {\n\t\t\t\t\tmatched.push(memory.id);\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst dryRun = input.dryRun === true;\n\t\t\tif (!dryRun) {\n\t\t\t\tfor (const id of matched) {\n\t\t\t\t\tmemories.delete(id);\n\t\t\t\t}\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};\n\t\t},\n\t\tasync findDuplicatePairs(input) {\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\tmatchesDuplicateFilter(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\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\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) {\n\t\t\tconst limit = input.limit ?? DEFAULT_AUDIT_LOG_LIMIT;\n\t\t\tconst indexed = auditLog.map((event, idx) => ({ event, idx }));\n\t\t\treturn indexed\n\t\t\t\t.filter(({ event }) => {\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\treturn true;\n\t\t\t\t})\n\t\t\t\t.sort((a, b) => {\n\t\t\t\t\tconst dt = b.event.timestamp.getTime() - a.event.timestamp.getTime();\n\t\t\t\t\treturn dt === 0 ? b.idx - a.idx : dt;\n\t\t\t\t})\n\t\t\t\t.slice(0, limit)\n\t\t\t\t.map(({ event }) => cloneAuditEvent(event));\n\t\t},\n\t\tasync getMemory(entityId, memoryId) {\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) {\n\t\t\treturn ids.flatMap((id) => {\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): Promise<StoreConsolidateResult> {\n\t\t\tconst survivor = memories.get(input.survivorId);\n\t\t\tconst newlySuperseded: string[] = [];\n\t\t\tfor (const id of input.supersededIds) {\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\tif (memory.supersededBy !== null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\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\tnewlySuperseded.push(memory.id);\n\t\t\t}\n\t\t\tif (survivor && input.mergeTags && newlySuperseded.length > 0) {\n\t\t\t\tconst mergedTags = new Set(input.survivorTags);\n\t\t\t\tfor (const id of newlySuperseded) {\n\t\t\t\t\tconst memory = memories.get(id);\n\t\t\t\t\tif (memory) {\n\t\t\t\t\t\tfor (const tag of memory.tags) {\n\t\t\t\t\t\t\tmergedTags.add(tag);\n\t\t\t\t\t\t}\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\tsurvivor.tags = [...mergedTags];\n\t\t\t\t\tsurvivor.updatedAt = input.now;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (input.auditEnabled) {\n\t\t\t\tfor (const id of newlySuperseded) {\n\t\t\t\t\tauditLog.push({\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: { memoryId: id, supersededBy: input.survivorId },\n\t\t\t\t\t\ttimestamp: input.now,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn { supersededIds: newlySuperseded };\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 { and, desc, eq, gt, lt } from \"drizzle-orm\";\nimport { MnemocyteError } from \"../../errors.js\";\nimport type { MnemocyteDatabase } from \"../index.js\";\nimport { type EventRow, eventsTable, type NewEventRow } from \"../schema.js\";\n\nexport interface EventFilter {\n\tentityId: string;\n\tlimit?: number;\n\tbefore?: Date;\n\tafter?: Date;\n}\n\nexport async function insertEvent(\n\tdb: MnemocyteDatabase,\n\trow: NewEventRow,\n): Promise<EventRow> {\n\tconst result = await db.insert(eventsTable).values(row).returning();\n\tconst inserted = result[0];\n\tif (!inserted) {\n\t\tthrow new MnemocyteError(\"Event insert returned no rows.\", \"DB\");\n\t}\n\treturn inserted;\n}\n\nexport async function listEvents(\n\tdb: MnemocyteDatabase,\n\tfilter: EventFilter,\n): Promise<EventRow[]> {\n\treturn db\n\t\t.select()\n\t\t.from(eventsTable)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(eventsTable.entityId, filter.entityId),\n\t\t\t\tfilter.before ? lt(eventsTable.timestamp, filter.before) : undefined,\n\t\t\t\tfilter.after ? gt(eventsTable.timestamp, filter.after) : undefined,\n\t\t\t),\n\t\t)\n\t\t.orderBy(desc(eventsTable.timestamp))\n\t\t.limit(filter.limit ?? 50);\n}\n","import {\n\tand,\n\tcount,\n\tcountDistinct,\n\teq,\n\tinArray,\n\tisNotNull,\n\tisNull,\n\tlt,\n\tor,\n\tsql,\n} from \"drizzle-orm\";\nimport type { ImportanceLevel, MemoryType } from \"../../types.js\";\nimport type { MnemocyteDatabase } from \"../index.js\";\nimport { type MemoryRow, memoriesTable, type NewMemoryRow } from \"../schema.js\";\nimport { formatVectorComponent } from \"../vector.js\";\n\nexport interface MemoryFilter {\n\tentityId: string;\n\ttypes?: readonly MemoryType[];\n\ttags?: readonly string[];\n\tbefore?: Date;\n\tafter?: Date;\n\tincludeSuperseded?: boolean;\n\tincludeExpired?: boolean;\n}\n\nexport interface VectorSearchInput extends MemoryFilter {\n\tembedding: readonly number[];\n\tlimit: number;\n\tminScore?: number;\n}\n\nexport interface LexicalSearchInput extends MemoryFilter {\n\tquery: string;\n\tlimit: number;\n}\n\nexport interface MemoryStatsCounts {\n\tmemoryCount: number;\n\tactiveMemoryCount: number;\n\texpiredMemoryCount: number;\n\tsupersededMemoryCount: number;\n}\n\nexport interface GlobalMemoryStatsCounts extends MemoryStatsCounts {\n\tentityCount: number;\n}\n\nfunction vectorLiteral(embedding: readonly number[]): string {\n\treturn `[${embedding.map(formatVectorComponent).join(\",\")}]`;\n}\n\ntype RawTimestamp = Date | string;\n\nexport type RecallMemoryRow = Omit<\n\tMemoryRow,\n\t| \"embedding\"\n\t| \"supersededAt\"\n\t| \"expiresAt\"\n\t| \"lastAccessedAt\"\n\t| \"createdAt\"\n\t| \"updatedAt\"\n> & {\n\tsupersededAt: RawTimestamp | null;\n\texpiresAt: RawTimestamp | null;\n\tlastAccessedAt: RawTimestamp | null;\n\tcreatedAt: RawTimestamp;\n\tupdatedAt: RawTimestamp;\n};\n\nexport type VectorSearchRow = RecallMemoryRow & { vectorScore: number };\n\nexport type LexicalSearchRow = RecallMemoryRow & { lexicalScore: number };\n\nfunction timestampParam(value: Date) {\n\treturn sql`${value.toISOString()}::timestamptz`;\n}\n\nfunction textArrayLiteral(values: readonly string[]) {\n\treturn sql`ARRAY[${sql.join(\n\t\tvalues.map((value) => sql`${value}`),\n\t\tsql`, `,\n\t)}]::text[]`;\n}\n\nfunction tagsContainAll(tags: readonly string[] | undefined) {\n\treturn tags && tags.length > 0\n\t\t? sql`${memoriesTable.tags} @> ${textArrayLiteral(tags)}`\n\t\t: undefined;\n}\n\nfunction rawTagsFilter(tags: readonly string[] | undefined) {\n\treturn tags && tags.length > 0\n\t\t? sql`AND tags @> ${textArrayLiteral(tags)}`\n\t\t: sql``;\n}\n\nfunction duplicateTagsFilter(tags: readonly string[] | undefined) {\n\treturn tags && tags.length > 0\n\t\t? sql`AND a.tags @> ${textArrayLiteral(tags)} AND b.tags @> ${textArrayLiteral(tags)}`\n\t\t: sql``;\n}\n\nfunction memoryStatsCountFields(now: Date) {\n\treturn {\n\t\tmemoryCount: count(),\n\t\tactiveMemoryCount: sql<number>`\n\t\t\t(count(*) FILTER (\n\t\t\t\tWHERE ${memoriesTable.supersededBy} IS NULL\n\t\t\t\t\tAND (${memoriesTable.expiresAt} IS NULL OR ${memoriesTable.expiresAt} > ${timestampParam(now)})\n\t\t\t))::int\n\t\t`.mapWith(Number),\n\t\texpiredMemoryCount: sql<number>`\n\t\t\t(count(*) FILTER (\n\t\t\t\tWHERE ${memoriesTable.expiresAt} IS NOT NULL\n\t\t\t\t\tAND ${memoriesTable.expiresAt} <= ${timestampParam(now)}\n\t\t\t))::int\n\t\t`.mapWith(Number),\n\t\tsupersededMemoryCount:\n\t\t\tsql<number>`(count(*) FILTER (WHERE ${memoriesTable.supersededBy} IS NOT NULL))::int`.mapWith(\n\t\t\t\tNumber,\n\t\t\t),\n\t};\n}\n\nfunction emptyMemoryStatsCounts(): MemoryStatsCounts {\n\treturn {\n\t\tmemoryCount: 0,\n\t\tactiveMemoryCount: 0,\n\t\texpiredMemoryCount: 0,\n\t\tsupersededMemoryCount: 0,\n\t};\n}\n\nexport async function insertMemories(\n\tdb: MnemocyteDatabase,\n\trows: NewMemoryRow[],\n): Promise<MemoryRow[]> {\n\tif (rows.length === 0) {\n\t\treturn [];\n\t}\n\treturn db.insert(memoriesTable).values(rows).returning();\n}\n\nexport async function getMemoryById(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tmemoryId: string,\n): Promise<MemoryRow | null> {\n\tconst result = await db\n\t\t.select()\n\t\t.from(memoriesTable)\n\t\t.where(\n\t\t\tand(eq(memoriesTable.entityId, entityId), eq(memoriesTable.id, memoryId)),\n\t\t)\n\t\t.limit(1);\n\treturn result[0] ?? null;\n}\n\nexport async function getEntityMemoryStatsCounts(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tnow: Date,\n): Promise<MemoryStatsCounts> {\n\tconst rows = await db\n\t\t.select(memoryStatsCountFields(now))\n\t\t.from(memoriesTable)\n\t\t.where(eq(memoriesTable.entityId, entityId));\n\treturn rows[0] ?? emptyMemoryStatsCounts();\n}\n\nexport async function getGlobalMemoryStatsCounts(\n\tdb: MnemocyteDatabase,\n\tnow: Date,\n): Promise<GlobalMemoryStatsCounts> {\n\tconst rows = await db\n\t\t.select({\n\t\t\tentityCount: countDistinct(memoriesTable.entityId),\n\t\t\t...memoryStatsCountFields(now),\n\t\t})\n\t\t.from(memoriesTable);\n\treturn rows[0] ?? { entityCount: 0, ...emptyMemoryStatsCounts() };\n}\n\nexport async function deleteMemory(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tmemoryId: string,\n): Promise<boolean> {\n\tconst result = await db\n\t\t.delete(memoriesTable)\n\t\t.where(\n\t\t\tand(eq(memoriesTable.entityId, entityId), eq(memoriesTable.id, memoryId)),\n\t\t)\n\t\t.returning({ id: memoriesTable.id });\n\treturn result.length > 0;\n}\n\nexport async function deleteMemoriesForEntity(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n): Promise<number> {\n\tconst result = await db\n\t\t.delete(memoriesTable)\n\t\t.where(eq(memoriesTable.entityId, entityId))\n\t\t.returning({ id: memoriesTable.id });\n\treturn result.length;\n}\n\nexport interface PruneFilter {\n\tentityId?: string;\n\texpired?: boolean;\n\tsuperseded?: boolean;\n\tcreatedBefore?: Date;\n\tnotAccessedSince?: Date;\n\ttypes?: readonly MemoryType[];\n\ttags?: readonly string[];\n\tmaxImportanceLevels?: readonly ImportanceLevel[];\n}\n\nfunction pruneConditions(filter: PruneFilter) {\n\treturn and(\n\t\tfilter.entityId !== undefined\n\t\t\t? eq(memoriesTable.entityId, filter.entityId)\n\t\t\t: undefined,\n\t\tfilter.expired\n\t\t\t? and(\n\t\t\t\t\tisNotNull(memoriesTable.expiresAt),\n\t\t\t\t\tsql`${memoriesTable.expiresAt} <= now()`,\n\t\t\t\t)\n\t\t\t: undefined,\n\t\tfilter.superseded ? isNotNull(memoriesTable.supersededBy) : undefined,\n\t\tfilter.createdBefore\n\t\t\t? lt(memoriesTable.createdAt, filter.createdBefore)\n\t\t\t: undefined,\n\t\tfilter.notAccessedSince\n\t\t\t? or(\n\t\t\t\t\tisNull(memoriesTable.lastAccessedAt),\n\t\t\t\t\tlt(memoriesTable.lastAccessedAt, filter.notAccessedSince),\n\t\t\t\t)\n\t\t\t: undefined,\n\t\tfilter.types && filter.types.length > 0\n\t\t\t? inArray(memoriesTable.type, [...filter.types])\n\t\t\t: undefined,\n\t\ttagsContainAll(filter.tags),\n\t\tfilter.maxImportanceLevels && filter.maxImportanceLevels.length > 0\n\t\t\t? inArray(memoriesTable.importance, [...filter.maxImportanceLevels])\n\t\t\t: undefined,\n\t);\n}\n\nexport async function countPruneMatches(\n\tdb: MnemocyteDatabase,\n\tfilter: PruneFilter,\n): Promise<number> {\n\treturn db.$count(memoriesTable, pruneConditions(filter));\n}\n\nexport async function pruneMemories(\n\tdb: MnemocyteDatabase,\n\tfilter: PruneFilter,\n): Promise<number> {\n\tconst result = await db\n\t\t.delete(memoriesTable)\n\t\t.where(pruneConditions(filter))\n\t\t.returning({ id: memoriesTable.id });\n\treturn result.length;\n}\n\nexport interface DuplicateSearchInput {\n\tentityId: string;\n\tthreshold: number;\n\tlimit: number;\n\ttypes?: readonly string[];\n\ttags?: readonly string[];\n\tincludeSuperseded?: boolean;\n\tincludeExpired?: boolean;\n}\n\nexport async function findDuplicatePairs(\n\tdb: MnemocyteDatabase,\n\tinput: DuplicateSearchInput,\n): Promise<Array<{ a: MemoryRow; b: MemoryRow; similarity: number }>> {\n\tconst rows = await db.execute(sql`\n\t\tSELECT\n\t\t\ta.id AS \"aId\",\n\t\t\ta.entity_id AS \"aEntityId\",\n\t\t\ta.content AS \"aContent\",\n\t\t\ta.type AS \"aType\",\n\t\t\ta.importance AS \"aImportance\",\n\t\t\ta.tags AS \"aTags\",\n\t\t\ta.source AS \"aSource\",\n\t\t\ta.metadata AS \"aMetadata\",\n\t\t\ta.confidence AS \"aConfidence\",\n\t\t\ta.embedding AS \"aEmbedding\",\n\t\t\ta.embedding_model AS \"aEmbeddingModel\",\n\t\t\ta.embedding_dimensions AS \"aEmbeddingDimensions\",\n\t\t\ta.superseded_by AS \"aSupersededBy\",\n\t\t\ta.superseded_at AS \"aSupersededAt\",\n\t\t\ta.expires_at AS \"aExpiresAt\",\n\t\t\ta.last_accessed_at AS \"aLastAccessedAt\",\n\t\t\ta.access_count AS \"aAccessCount\",\n\t\t\ta.created_at AS \"aCreatedAt\",\n\t\t\ta.updated_at AS \"aUpdatedAt\",\n\t\t\tb.id AS \"bId\",\n\t\t\tb.entity_id AS \"bEntityId\",\n\t\t\tb.content AS \"bContent\",\n\t\t\tb.type AS \"bType\",\n\t\t\tb.importance AS \"bImportance\",\n\t\t\tb.tags AS \"bTags\",\n\t\t\tb.source AS \"bSource\",\n\t\t\tb.metadata AS \"bMetadata\",\n\t\t\tb.confidence AS \"bConfidence\",\n\t\t\tb.embedding AS \"bEmbedding\",\n\t\t\tb.embedding_model AS \"bEmbeddingModel\",\n\t\t\tb.embedding_dimensions AS \"bEmbeddingDimensions\",\n\t\t\tb.superseded_by AS \"bSupersededBy\",\n\t\t\tb.superseded_at AS \"bSupersededAt\",\n\t\t\tb.expires_at AS \"bExpiresAt\",\n\t\t\tb.last_accessed_at AS \"bLastAccessedAt\",\n\t\t\tb.access_count AS \"bAccessCount\",\n\t\t\tb.created_at AS \"bCreatedAt\",\n\t\t\tb.updated_at AS \"bUpdatedAt\",\n\t\t\t1 - (a.embedding <=> b.embedding) AS \"similarity\"\n\t\tFROM mnemocyte_memories a\n\t\tJOIN mnemocyte_memories b\n\t\t\tON b.entity_id = a.entity_id\n\t\t\tAND a.id < b.id\n\t\t\tAND a.embedding IS NOT NULL\n\t\t\tAND b.embedding IS NOT NULL\n\t\tWHERE\n\t\t\ta.entity_id = ${input.entityId}\n\t\t\t${input.includeSuperseded ? sql`` : sql`AND a.superseded_by IS NULL AND b.superseded_by IS NULL`}\n\t\t\t${input.includeExpired ? sql`` : sql`AND (a.expires_at IS NULL OR a.expires_at > now()) AND (b.expires_at IS NULL OR b.expires_at > now())`}\n\t\t\t${\n\t\t\t\tinput.types && input.types.length > 0\n\t\t\t\t\t? sql`AND a.type IN (${sql.join(\n\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)}) AND b.type IN (${sql.join(\n\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)})`\n\t\t\t\t\t: sql``\n\t\t\t}\n\t\t\t${duplicateTagsFilter(input.tags)}\n\t\t\tAND 1 - (a.embedding <=> b.embedding) >= ${input.threshold}\n\t\tORDER BY \"similarity\" DESC\n\t\tLIMIT ${input.limit}\n\t`);\n\tconst records = rows as unknown as Array<Record<string, unknown>>;\n\treturn records.map((row) => {\n\t\tconst a = {\n\t\t\tid: row.aId,\n\t\t\tentityId: row.aEntityId,\n\t\t\tcontent: row.aContent,\n\t\t\ttype: row.aType,\n\t\t\timportance: row.aImportance,\n\t\t\ttags: row.aTags,\n\t\t\tsource: row.aSource,\n\t\t\tmetadata: row.aMetadata,\n\t\t\tconfidence: row.aConfidence,\n\t\t\tembedding: row.aEmbedding,\n\t\t\tembeddingModel: row.aEmbeddingModel,\n\t\t\tembeddingDimensions: row.aEmbeddingDimensions,\n\t\t\tsupersededBy: row.aSupersededBy,\n\t\t\tsupersededAt: row.aSupersededAt,\n\t\t\texpiresAt: row.aExpiresAt,\n\t\t\tlastAccessedAt: row.aLastAccessedAt,\n\t\t\taccessCount: row.aAccessCount,\n\t\t\tcreatedAt: row.aCreatedAt,\n\t\t\tupdatedAt: row.aUpdatedAt,\n\t\t} as unknown as MemoryRow;\n\t\tconst b = {\n\t\t\tid: row.bId,\n\t\t\tentityId: row.bEntityId,\n\t\t\tcontent: row.bContent,\n\t\t\ttype: row.bType,\n\t\t\timportance: row.bImportance,\n\t\t\ttags: row.bTags,\n\t\t\tsource: row.bSource,\n\t\t\tmetadata: row.bMetadata,\n\t\t\tconfidence: row.bConfidence,\n\t\t\tembedding: row.bEmbedding,\n\t\t\tembeddingModel: row.bEmbeddingModel,\n\t\t\tembeddingDimensions: row.bEmbeddingDimensions,\n\t\t\tsupersededBy: row.bSupersededBy,\n\t\t\tsupersededAt: row.bSupersededAt,\n\t\t\texpiresAt: row.bExpiresAt,\n\t\t\tlastAccessedAt: row.bLastAccessedAt,\n\t\t\taccessCount: row.bAccessCount,\n\t\t\tcreatedAt: row.bCreatedAt,\n\t\t\tupdatedAt: row.bUpdatedAt,\n\t\t} as unknown as MemoryRow;\n\t\treturn {\n\t\t\ta,\n\t\t\tb,\n\t\t\tsimilarity: Number(row.similarity) || 0,\n\t\t};\n\t});\n}\n\nexport interface SupersedeRow {\n\tid: string;\n\ttags: string[];\n}\n\nexport async function loadConsolidationTargets(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tids: readonly string[],\n): Promise<Array<{ id: string; tags: string[]; supersededBy: string | null }>> {\n\tif (ids.length === 0) {\n\t\treturn [];\n\t}\n\tconst rows = await db\n\t\t.select({\n\t\t\tid: memoriesTable.id,\n\t\t\ttags: memoriesTable.tags,\n\t\t\tsupersededBy: memoriesTable.supersededBy,\n\t\t})\n\t\t.from(memoriesTable)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, entityId),\n\t\t\t\tinArray(memoriesTable.id, [...ids]),\n\t\t\t),\n\t\t);\n\treturn rows;\n}\n\nexport async function markMemoriesSuperseded(\n\tdb: MnemocyteDatabase,\n\tparams: {\n\t\tsurvivorId: string;\n\t\tentityId: string;\n\t\tids: readonly string[];\n\t\tnow: Date;\n\t},\n): Promise<SupersedeRow[]> {\n\tif (params.ids.length === 0) {\n\t\treturn [];\n\t}\n\tconst result = await db\n\t\t.update(memoriesTable)\n\t\t.set({\n\t\t\tsupersededBy: params.survivorId,\n\t\t\tsupersededAt: params.now,\n\t\t\tupdatedAt: params.now,\n\t\t})\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, params.entityId),\n\t\t\t\tinArray(memoriesTable.id, [...params.ids]),\n\t\t\t\tisNull(memoriesTable.supersededBy),\n\t\t\t),\n\t\t)\n\t\t.returning({ id: memoriesTable.id, tags: memoriesTable.tags });\n\treturn result;\n}\n\nexport async function setMemoryTags(\n\tdb: MnemocyteDatabase,\n\tparams: {\n\t\tentityId: string;\n\t\tmemoryId: string;\n\t\ttags: readonly string[];\n\t\tnow: Date;\n\t},\n): Promise<void> {\n\tawait db\n\t\t.update(memoriesTable)\n\t\t.set({ tags: [...params.tags], updatedAt: params.now })\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, params.entityId),\n\t\t\t\teq(memoriesTable.id, params.memoryId),\n\t\t\t),\n\t\t);\n}\n\nexport async function markMemoriesAccessed(\n\tdb: MnemocyteDatabase,\n\tmemoryIds: readonly string[],\n): Promise<void> {\n\tconst now = new Date();\n\tif (memoryIds.length === 0) {\n\t\treturn;\n\t}\n\tawait db\n\t\t.update(memoriesTable)\n\t\t.set({\n\t\t\tlastAccessedAt: now,\n\t\t\taccessCount: sql`${memoriesTable.accessCount} + 1`,\n\t\t\tupdatedAt: now,\n\t\t})\n\t\t.where(inArray(memoriesTable.id, [...memoryIds]));\n}\n\nexport async function getMemoryEmbeddings(\n\tdb: MnemocyteDatabase,\n\tmemoryIds: readonly string[],\n): Promise<Map<string, number[]>> {\n\tif (memoryIds.length === 0) {\n\t\treturn new Map();\n\t}\n\tconst rows = await db\n\t\t.select({\n\t\t\tid: memoriesTable.id,\n\t\t\tembedding: memoriesTable.embedding,\n\t\t})\n\t\t.from(memoriesTable)\n\t\t.where(inArray(memoriesTable.id, [...memoryIds]));\n\treturn new Map(\n\t\trows.flatMap((row) => (row.embedding ? [[row.id, row.embedding]] : [])),\n\t);\n}\n\nexport async function vectorSearch(\n\tdb: MnemocyteDatabase,\n\tinput: VectorSearchInput,\n): Promise<VectorSearchRow[]> {\n\tconst embedding = vectorLiteral(input.embedding);\n\tconst minScore = input.minScore ?? 0;\n\tconst rows = await db.execute(sql`\n\t\tSELECT\n\t\t\tid,\n\t\t\tentity_id AS \"entityId\",\n\t\t\tcontent,\n\t\t\ttype,\n\t\t\timportance,\n\t\t\ttags,\n\t\t\tsource,\n\t\t\tmetadata,\n\t\t\tconfidence,\n\t\t\tembedding_model AS \"embeddingModel\",\n\t\t\tembedding_dimensions AS \"embeddingDimensions\",\n\t\t\tsuperseded_by AS \"supersededBy\",\n\t\t\tsuperseded_at AS \"supersededAt\",\n\t\t\texpires_at AS \"expiresAt\",\n\t\t\tlast_accessed_at AS \"lastAccessedAt\",\n\t\t\taccess_count AS \"accessCount\",\n\t\t\tcreated_at AS \"createdAt\",\n\t\t\tupdated_at AS \"updatedAt\",\n\t\t\t1 - (embedding <=> ${embedding}::vector) AS \"vectorScore\"\n\t\tFROM mnemocyte_memories\n\t\tWHERE\n\t\t\tentity_id = ${input.entityId}\n\t\t\tAND embedding IS NOT NULL\n\t\t\t${input.includeSuperseded ? sql`` : sql`AND superseded_by IS NULL`}\n\t\t\t${input.includeExpired ? sql`` : sql`AND (expires_at IS NULL OR expires_at > now())`}\n\t\t\t${\n\t\t\t\tinput.types && input.types.length > 0\n\t\t\t\t\t? sql`AND type IN (${sql.join(\n\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)})`\n\t\t\t\t\t: sql``\n\t\t\t}\n\t\t\t${rawTagsFilter(input.tags)}\n\t\t\t${input.before ? sql`AND created_at < ${timestampParam(input.before)}` : sql``}\n\t\t\t${input.after ? sql`AND created_at > ${timestampParam(input.after)}` : sql``}\n\t\t\tAND 1 - (embedding <=> ${embedding}::vector) >= ${minScore}\n\t\tORDER BY embedding <=> ${embedding}::vector\n\t\tLIMIT ${input.limit}\n\t`);\n\treturn rows as unknown as VectorSearchRow[];\n}\n\nexport async function lexicalSearch(\n\tdb: MnemocyteDatabase,\n\tinput: LexicalSearchInput,\n): Promise<LexicalSearchRow[]> {\n\tconst rows = await db.execute(sql`\n\t\tSELECT\n\t\t\tid,\n\t\t\tentity_id AS \"entityId\",\n\t\t\tcontent,\n\t\t\ttype,\n\t\t\timportance,\n\t\t\ttags,\n\t\t\tsource,\n\t\t\tmetadata,\n\t\t\tconfidence,\n\t\t\tembedding_model AS \"embeddingModel\",\n\t\t\tembedding_dimensions AS \"embeddingDimensions\",\n\t\t\tsuperseded_by AS \"supersededBy\",\n\t\t\tsuperseded_at AS \"supersededAt\",\n\t\t\texpires_at AS \"expiresAt\",\n\t\t\tlast_accessed_at AS \"lastAccessedAt\",\n\t\t\taccess_count AS \"accessCount\",\n\t\t\tcreated_at AS \"createdAt\",\n\t\t\tupdated_at AS \"updatedAt\",\n\t\t\tts_rank(to_tsvector('english', content), websearch_to_tsquery('english', ${input.query})) AS \"lexicalScore\"\n\t\tFROM mnemocyte_memories\n\t\tWHERE\n\t\t\tentity_id = ${input.entityId}\n\t\t\t${input.includeSuperseded ? sql`` : sql`AND superseded_by IS NULL`}\n\t\t\t${input.includeExpired ? sql`` : sql`AND (expires_at IS NULL OR expires_at > now())`}\n\t\t\t${\n\t\t\t\tinput.types && input.types.length > 0\n\t\t\t\t\t? sql`AND type IN (${sql.join(\n\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)})`\n\t\t\t\t\t: sql``\n\t\t\t}\n\t\t\t${rawTagsFilter(input.tags)}\n\t\t\t${input.before ? sql`AND created_at < ${timestampParam(input.before)}` : sql``}\n\t\t\t${input.after ? sql`AND created_at > ${timestampParam(input.after)}` : sql``}\n\t\t\tAND to_tsvector('english', content) @@ websearch_to_tsquery('english', ${input.query})\n\t\tORDER BY \"lexicalScore\" DESC\n\t\tLIMIT ${input.limit}\n\t`);\n\treturn rows as unknown as LexicalSearchRow[];\n}\n","import { eq } from \"drizzle-orm\";\nimport type { MnemocyteDatabase } from \"../index.js\";\nimport { type MetaRow, metaTable } from \"../schema.js\";\n\nexport const INSTALLATION_META_KEY = \"installation\";\n\nexport async function getInstallationMeta(\n\tdb: MnemocyteDatabase,\n): Promise<MetaRow | null> {\n\tconst rows = await db\n\t\t.select()\n\t\t.from(metaTable)\n\t\t.where(eq(metaTable.key, INSTALLATION_META_KEY))\n\t\t.limit(1);\n\treturn rows[0] ?? null;\n}\n","import type { MemoryRow } from \"../db/schema.js\";\nimport type { ImportanceLevel, Memory, MemoryType } from \"../types.js\";\nimport { cloneJsonObject } from \"./json.js\";\n\ntype MemoryRowTimestamp = Date | string;\n\ntype MemoryLikeRow = Omit<\n\tMemoryRow,\n\t| \"embedding\"\n\t| \"supersededAt\"\n\t| \"expiresAt\"\n\t| \"lastAccessedAt\"\n\t| \"createdAt\"\n\t| \"updatedAt\"\n> & {\n\tsupersededAt: MemoryRowTimestamp | null;\n\texpiresAt: MemoryRowTimestamp | null;\n\tlastAccessedAt: MemoryRowTimestamp | null;\n\tcreatedAt: MemoryRowTimestamp;\n\tupdatedAt: MemoryRowTimestamp;\n};\n\nfunction toDate(value: MemoryRowTimestamp): Date {\n\treturn value instanceof Date ? value : new Date(value);\n}\n\nfunction toNullableDate(value: MemoryRowTimestamp | null): Date | null {\n\treturn value === null ? null : toDate(value);\n}\n\nexport function rowToMemory(row: MemoryLikeRow): Memory {\n\treturn {\n\t\tid: row.id,\n\t\tentityId: row.entityId,\n\t\tcontent: row.content,\n\t\ttype: row.type as MemoryType,\n\t\timportance: row.importance as ImportanceLevel,\n\t\ttags: row.tags,\n\t\tsource: row.source,\n\t\tmetadata: cloneJsonObject(row.metadata),\n\t\tconfidence: row.confidence,\n\t\tembeddingModel: row.embeddingModel,\n\t\tembeddingDimensions: row.embeddingDimensions,\n\t\tsupersededBy: row.supersededBy,\n\t\tsupersededAt: toNullableDate(row.supersededAt),\n\t\texpiresAt: toNullableDate(row.expiresAt),\n\t\tlastAccessedAt: toNullableDate(row.lastAccessedAt),\n\t\taccessCount: row.accessCount,\n\t\tcreatedAt: toDate(row.createdAt),\n\t\tupdatedAt: toDate(row.updatedAt),\n\t};\n}\n","import type { DatabaseHandle } from \"../db/index.js\";\nimport { insertEvent, listEvents } from \"../db/queries/events.js\";\nimport {\n\tcountPruneMatches,\n\tdeleteMemoriesForEntity as deleteMemoriesForEntityQuery,\n\tdeleteMemory as deleteMemoryQuery,\n\tfindDuplicatePairs as findDuplicatePairsQuery,\n\tgetEntityMemoryStatsCounts,\n\tgetGlobalMemoryStatsCounts,\n\tgetMemoryById,\n\tgetMemoryEmbeddings as getMemoryEmbeddingsQuery,\n\tinsertMemories as insertMemoryRows,\n\tlexicalSearch as lexicalSearchQuery,\n\tloadConsolidationTargets,\n\tmarkMemoriesAccessed,\n\tmarkMemoriesSuperseded,\n\ttype PruneFilter,\n\tpruneMemories,\n\tsetMemoryTags,\n\tvectorSearch as vectorSearchQuery,\n} from \"../db/queries/memories.js\";\nimport { getInstallationMeta } from \"../db/queries/meta.js\";\nimport type { EventRow, NewMemoryRow } from \"../db/schema.js\";\nimport { MnemocyteError } from \"../errors.js\";\nimport type {\n\tAuditEvent,\n\tEmbedder,\n\tEntityStats,\n\tGlobalStats,\n\tImportanceLevel,\n\tMnemocyteClient,\n\tMnemocyteConfig,\n\tPruneInput,\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\tIMPORTANCE_RANK,\n} from \"./defaults.js\";\nimport { cloneJsonObject } from \"./json.js\";\nimport { rowToMemory } from \"./postgres-records.js\";\nimport { createEventId, type StoredMemory } from \"./records.js\";\nimport type {\n\tMemoryStore,\n\tStoreConsolidateInput,\n\tStoreConsolidateResult,\n\tStoreDuplicatePair,\n\tStoreLexicalCandidate,\n\tStoreLexicalSearchInput,\n\tStoreVectorCandidate,\n\tStoreVectorSearchInput,\n} from \"./store.js\";\n\nconst IMPORTANCE_LEVELS: readonly ImportanceLevel[] = [\n\t\"low\",\n\t\"normal\",\n\t\"high\",\n\t\"critical\",\n];\n\nconst MIGRATION_ERROR_CODES = new Set([\"42P01\", \"42703\", \"42704\", \"42883\"]);\n\nfunction rowToAuditEvent(row: EventRow): AuditEvent {\n\treturn {\n\t\tid: row.id,\n\t\tentityId: row.entityId,\n\t\tdescription: row.description,\n\t\tmetadata: cloneJsonObject(row.metadata),\n\t\ttimestamp: row.timestamp,\n\t};\n}\n\nfunction importanceCeilingLevels(\n\tmax: ImportanceLevel,\n): readonly ImportanceLevel[] {\n\treturn IMPORTANCE_LEVELS.filter(\n\t\t(level) => IMPORTANCE_RANK[level] <= IMPORTANCE_RANK[max],\n\t);\n}\n\nfunction hasPostgresErrorCode(error: unknown, code: string): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === code\n\t);\n}\n\nfunction getPostgresErrorCode(error: unknown): string | undefined {\n\treturn typeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\ttypeof (error as { code?: unknown }).code === \"string\"\n\t\t? (error as { code: string }).code\n\t\t: undefined;\n}\n\nfunction normalizePostgresError(error: unknown): MnemocyteError {\n\tif (error instanceof MnemocyteError) {\n\t\treturn error;\n\t}\n\tconst code = getPostgresErrorCode(error);\n\tif (code && MIGRATION_ERROR_CODES.has(code)) {\n\t\treturn new MnemocyteError(\n\t\t\t\"Postgres schema is missing or incompatible. Apply the bundled Mnemocyte migrations before using the Postgres backend.\",\n\t\t\t\"MIGRATION\",\n\t\t\terror,\n\t\t);\n\t}\n\treturn new MnemocyteError(\"Postgres operation failed.\", \"DB\", error);\n}\n\nasync function runPostgresOperation<T>(\n\toperation: () => Promise<T>,\n): Promise<T> {\n\ttry {\n\t\treturn await operation();\n\t} catch (error) {\n\t\tthrow normalizePostgresError(error);\n\t}\n}\n\nfunction toPruneFilter(input: PruneInput): PruneFilter {\n\tconst filter: PruneFilter = {};\n\tif (input.entityId !== undefined) {\n\t\tfilter.entityId = input.entityId;\n\t}\n\tif (input.expired === true) {\n\t\tfilter.expired = true;\n\t}\n\tif (input.superseded === true) {\n\t\tfilter.superseded = true;\n\t}\n\tif (input.createdBefore !== undefined) {\n\t\tfilter.createdBefore = input.createdBefore;\n\t}\n\tif (input.notAccessedSince !== undefined) {\n\t\tfilter.notAccessedSince = input.notAccessedSince;\n\t}\n\tif (input.types !== undefined && input.types.length > 0) {\n\t\tfilter.types = input.types;\n\t}\n\tif (input.tags !== undefined && input.tags.length > 0) {\n\t\tfilter.tags = input.tags;\n\t}\n\tif (input.maxImportance !== undefined) {\n\t\tfilter.maxImportanceLevels = importanceCeilingLevels(input.maxImportance);\n\t}\n\treturn filter;\n}\n\nfunction toMemoryRow(memory: StoredMemory): NewMemoryRow {\n\treturn {\n\t\t...memory,\n\t\ttags: [...memory.tags],\n\t\tmetadata: cloneJsonObject(memory.metadata),\n\t\tembedding: [...memory.embedding],\n\t};\n}\n\nexport function createPostgresStore(handle: DatabaseHandle): MemoryStore {\n\tlet schemaValidated = false;\n\tlet schemaValidationPromise: Promise<void> | undefined;\n\n\tasync function ensureEmbeddingCompatibility(\n\t\tembedder: Embedder,\n\t): Promise<void> {\n\t\tif (schemaValidated) {\n\t\t\treturn;\n\t\t}\n\t\tif (!schemaValidationPromise) {\n\t\t\tschemaValidationPromise = validateEmbeddingCompatibility(embedder).catch(\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tschemaValidationPromise = undefined;\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tawait schemaValidationPromise;\n\t}\n\n\tasync function validateEmbeddingCompatibility(\n\t\tembedder: Embedder,\n\t): Promise<void> {\n\t\tlet meta: Awaited<ReturnType<typeof getInstallationMeta>>;\n\t\ttry {\n\t\t\tmeta = await getInstallationMeta(handle.db);\n\t\t} catch (error) {\n\t\t\tif (hasPostgresErrorCode(error, \"42P01\")) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"mnemocyte_meta is missing. Apply the v0.2.0 migration or render a dimension-specific initial migration before using the Postgres backend.\",\n\t\t\t\t\t\"MIGRATION\",\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow normalizePostgresError(error);\n\t\t}\n\t\tif (!meta) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t'mnemocyte_meta is missing the \"installation\" row. Apply the v0.2.0 migration or render a dimension-specific initial migration before using the Postgres backend.',\n\t\t\t\t\"MIGRATION\",\n\t\t\t);\n\t\t}\n\t\tif (meta.embeddingDimensions !== embedder.dimensions) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`embedder.dimensions (${embedder.dimensions}) must match mnemocyte_meta.embedding_dimensions (${meta.embeddingDimensions}). Render and apply a migration for the selected embedding dimension, or configure an embedder that matches this installation.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t\tschemaValidated = true;\n\t}\n\n\treturn {\n\t\tbackend: \"postgres\",\n\t\tasync ensureSchema() {},\n\t\tensureEmbeddingCompatibility,\n\t\tasync insertMemories(memories) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await insertMemoryRows(\n\t\t\t\t\thandle.db,\n\t\t\t\t\tmemories.map(toMemoryRow),\n\t\t\t\t);\n\t\t\t\treturn rows.map(rowToMemory);\n\t\t\t});\n\t\t},\n\t\tasync vectorSearch(input: StoreVectorSearchInput) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await vectorSearchQuery(handle.db, input);\n\t\t\t\treturn rows.map(\n\t\t\t\t\t(row) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\tmemory: rowToMemory(row),\n\t\t\t\t\t\t\tvectorScore: row.vectorScore,\n\t\t\t\t\t\t}) satisfies StoreVectorCandidate,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tasync lexicalSearch(input: StoreLexicalSearchInput) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await lexicalSearchQuery(handle.db, input);\n\t\t\t\treturn rows.map(\n\t\t\t\t\t(row) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\tmemory: rowToMemory(row),\n\t\t\t\t\t\t\tlexicalScore: row.lexicalScore,\n\t\t\t\t\t\t}) satisfies StoreLexicalCandidate,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tasync getMemoryEmbeddings(memoryIds) {\n\t\t\treturn runPostgresOperation(() =>\n\t\t\t\tgetMemoryEmbeddingsQuery(handle.db, memoryIds),\n\t\t\t);\n\t\t},\n\t\tasync markMemoriesAccessed(memoryIds) {\n\t\t\treturn runPostgresOperation(() =>\n\t\t\t\tmarkMemoriesAccessed(handle.db, memoryIds),\n\t\t\t);\n\t\t},\n\t\tasync deleteMemory(entityId, memoryId) {\n\t\t\treturn runPostgresOperation(() =>\n\t\t\t\tdeleteMemoryQuery(handle.db, entityId, memoryId),\n\t\t\t);\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\treturn runPostgresOperation(() =>\n\t\t\t\tdeleteMemoriesForEntityQuery(handle.db, entityId),\n\t\t\t);\n\t\t},\n\t\tasync prune(input) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst filter = toPruneFilter(input);\n\t\t\t\tconst dryRun = input.dryRun === true;\n\t\t\t\tif (dryRun) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmatchedCount: await countPruneMatches(handle.db, filter),\n\t\t\t\t\t\tdeletedCount: 0,\n\t\t\t\t\t\tdryRun: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst deletedCount = await pruneMemories(handle.db, filter);\n\t\t\t\treturn {\n\t\t\t\t\tmatchedCount: deletedCount,\n\t\t\t\t\tdeletedCount,\n\t\t\t\t\tdryRun: false,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tasync findDuplicatePairs(input) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await findDuplicatePairsQuery(handle.db, {\n\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\tthreshold: input.threshold ?? DEFAULT_DUPLICATE_THRESHOLD,\n\t\t\t\t\tlimit: input.limit ?? DEFAULT_DUPLICATE_LIMIT,\n\t\t\t\t\t...(input.types === undefined ? {} : { types: input.types }),\n\t\t\t\t\t...(input.tags === undefined ? {} : { tags: input.tags }),\n\t\t\t\t\t...(input.includeSuperseded === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { includeSuperseded: input.includeSuperseded }),\n\t\t\t\t\t...(input.includeExpired === undefined\n\t\t\t\t\t\t? {}\n\t\t\t\t\t\t: { includeExpired: input.includeExpired }),\n\t\t\t\t});\n\t\t\t\treturn rows.map(\n\t\t\t\t\t(row) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\ta: rowToMemory(row.a),\n\t\t\t\t\t\t\tb: rowToMemory(row.b),\n\t\t\t\t\t\t\tsimilarity: Math.max(0, Math.min(1, row.similarity)),\n\t\t\t\t\t\t}) satisfies StoreDuplicatePair,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tasync addAuditEvents(events) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tfor (const event of events) {\n\t\t\t\t\tawait insertEvent(handle.db, {\n\t\t\t\t\t\tid: event.id,\n\t\t\t\t\t\tentityId: event.entityId,\n\t\t\t\t\t\tdescription: event.description,\n\t\t\t\t\t\tmetadata: cloneJsonObject(event.metadata),\n\t\t\t\t\t\ttimestamp: event.timestamp,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tasync listAuditLog(input) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await listEvents(handle.db, {\n\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\tlimit: input.limit ?? DEFAULT_AUDIT_LOG_LIMIT,\n\t\t\t\t\t...(input.before === undefined ? {} : { before: input.before }),\n\t\t\t\t\t...(input.after === undefined ? {} : { after: input.after }),\n\t\t\t\t});\n\t\t\t\treturn rows.map(rowToAuditEvent);\n\t\t\t});\n\t\t},\n\t\tasync getMemory(entityId, memoryId) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst row = await getMemoryById(handle.db, entityId, memoryId);\n\t\t\t\treturn row ? rowToMemory(row) : null;\n\t\t\t});\n\t\t},\n\t\tasync loadConsolidationTargets(entityId, ids) {\n\t\t\treturn runPostgresOperation(() =>\n\t\t\t\tloadConsolidationTargets(handle.db, entityId, ids),\n\t\t\t);\n\t\t},\n\t\tasync consolidate(\n\t\t\tinput: StoreConsolidateInput,\n\t\t): Promise<StoreConsolidateResult> {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst newSupersededIds = await handle.db.transaction(async (tx) => {\n\t\t\t\t\tconst updated = await markMemoriesSuperseded(tx, {\n\t\t\t\t\t\tsurvivorId: input.survivorId,\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\tids: input.supersededIds,\n\t\t\t\t\t\tnow: input.now,\n\t\t\t\t\t});\n\t\t\t\t\tconst ids = updated.map((row) => row.id);\n\t\t\t\t\tif (input.auditEnabled) {\n\t\t\t\t\t\tfor (const id of ids) {\n\t\t\t\t\t\t\tawait insertEvent(tx, {\n\t\t\t\t\t\t\t\tid: createEventId(),\n\t\t\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t\t\tdescription: \"memory.superseded\",\n\t\t\t\t\t\t\t\tmetadata: { memoryId: id, supersededBy: input.survivorId },\n\t\t\t\t\t\t\t\ttimestamp: input.now,\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\tif (input.mergeTags && updated.length > 0) {\n\t\t\t\t\t\tconst mergedTags = new Set(input.survivorTags);\n\t\t\t\t\t\tfor (const row of updated) {\n\t\t\t\t\t\t\tfor (const tag of row.tags) {\n\t\t\t\t\t\t\t\tmergedTags.add(tag);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (mergedTags.size !== input.survivorTags.length) {\n\t\t\t\t\t\t\tawait setMemoryTags(tx, {\n\t\t\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t\t\tmemoryId: input.survivorId,\n\t\t\t\t\t\t\t\ttags: [...mergedTags],\n\t\t\t\t\t\t\t\tnow: input.now,\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 ids;\n\t\t\t\t});\n\t\t\t\treturn { supersededIds: newSupersededIds };\n\t\t\t});\n\t\t},\n\t\tasync stats(input, now) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tif (input?.entityId) {\n\t\t\t\t\tconst counts = await getEntityMemoryStatsCounts(\n\t\t\t\t\t\thandle.db,\n\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t...counts,\n\t\t\t\t\t} satisfies EntityStats;\n\t\t\t\t}\n\t\t\t\treturn (await getGlobalMemoryStatsCounts(\n\t\t\t\t\thandle.db,\n\t\t\t\t\tnow,\n\t\t\t\t)) satisfies GlobalStats;\n\t\t\t});\n\t\t},\n\t\tasync close() {\n\t\t\treturn runPostgresOperation(() => handle.close());\n\t\t},\n\t};\n}\n\nexport function createPostgresClient(\n\tconfig: MnemocyteConfig,\n\thandle: DatabaseHandle,\n): MnemocyteClient {\n\treturn createMemoryClient(config, createPostgresStore(handle));\n}\n","import { createDatabase } from \"./db/index.js\";\nimport { createInMemoryClient } from \"./memory/in-memory.js\";\nimport { createPostgresClient } from \"./memory/postgres.js\";\nimport {\n\tassertEmbedder,\n\tassertNonEmptyString,\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.databaseUrl} is provided, a Postgres-backed\n * client is returned (requires the `pgvector` extension and the bundled\n * migration applied). Otherwise an in-memory client is returned, intended\n * for tests, demos, and short-lived processes.\n *\n * The returned client owns any underlying resources (e.g. the Postgres\n * connection pool). Call {@link MnemocyteClient.close} when finished to\n * release them.\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, or the database URL is malformed, or `\"VALIDATION\"` if\n * `databaseUrl` is explicitly 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\tif (config.databaseUrl !== undefined) {\n\t\tassertNonEmptyString(config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AAoB,MAAM,CAAC;AAC9D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACrYA,SAAgB,gBAAgB,QAA0C;CACzE,eAAe,OAAO,QAAQ;CAC9B,wBAAwB,OAAO,SAAS;CACxC,IAAI,OAAO,gBAAgB,KAAA,GAAW;EACrC,qBAAqB,OAAO,aAAa,aAAa;EACtD,OAAO,qBAAqB,QAAQ,eAAe,OAAO,WAAW,CAAC;CACvE;CACA,OAAO,qBAAqB,MAAM;AACnC"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["IMPORTANCE_LEVELS","timestampParam","insertMemoryRows","vectorSearchQuery","lexicalSearchQuery","getMemoryEmbeddingsQuery","deleteMemoryQuery","deleteMemoriesForEntityQuery","findDuplicatePairsQuery"],"sources":["../src/db/vector.ts","../src/db/schema.ts","../src/db/index.ts","../src/resilience.ts","../src/memory/json.ts","../src/memory/records.ts","../src/retrieval/scorer.ts","../src/context/formatter.ts","../src/context/tokens.ts","../src/context/builder.ts","../src/observability.ts","../src/memory/defaults.ts","../src/memory/embeddings.ts","../src/memory/store.ts","../src/memory/validation.ts","../src/memory/client-core.ts","../src/memory/deletion.ts","../src/memory/filters.ts","../src/memory/in-memory.ts","../src/db/cancellation.ts","../src/db/queries/events.ts","../src/db/queries/memories.ts","../src/db/queries/meta.ts","../src/memory/postgres-records.ts","../src/memory/postgres.ts","../src/client.ts"],"sourcesContent":["export function formatVectorComponent(value: number): string {\n\tif (!Number.isFinite(value)) {\n\t\tthrow new Error(\"Vector values must be finite numbers.\");\n\t}\n\treturn Object.is(value, -0) ? \"0\" : value.toString();\n}\n","import { sql } from \"drizzle-orm\";\nimport {\n\ttype AnyPgColumn,\n\tcustomType,\n\tindex,\n\tinteger,\n\tjsonb,\n\tpgTable,\n\treal,\n\ttext,\n\ttimestamp,\n} from \"drizzle-orm/pg-core\";\nimport type { JsonObject } from \"../types.js\";\nimport { formatVectorComponent } from \"./vector.js\";\n\nconst vector = customType<{\n\tdata: number[];\n\tdriverData: string;\n\tconfig: { dimensions?: number };\n}>({\n\tdataType(config) {\n\t\tconst dimensions = config?.dimensions ?? 1536;\n\t\treturn `vector(${dimensions})`;\n\t},\n\ttoDriver(value) {\n\t\treturn `[${value.map(formatVectorComponent).join(\",\")}]`;\n\t},\n\tfromDriver(value) {\n\t\treturn value.slice(1, -1).split(\",\").filter(Boolean).map(Number);\n\t},\n});\n\nexport const memoriesTable = pgTable(\n\t\"mnemocyte_memories\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tentityId: text(\"entity_id\").notNull(),\n\t\tcontent: text(\"content\").notNull(),\n\t\ttype: text(\"type\").notNull().default(\"fact\"),\n\t\timportance: text(\"importance\").notNull().default(\"normal\"),\n\t\ttags: text(\"tags\").array().notNull().default(sql`'{}'::text[]`),\n\t\tsource: text(\"source\"),\n\t\tmetadata: jsonb(\"metadata\").$type<JsonObject>().notNull().default({}),\n\t\tconfidence: real(\"confidence\").notNull().default(1),\n\t\tembedding: vector(\"embedding\", { dimensions: 1536 }),\n\t\tembeddingModel: text(\"embedding_model\").notNull(),\n\t\tembeddingDimensions: integer(\"embedding_dimensions\").notNull(),\n\t\tsupersededBy: text(\"superseded_by\").references(\n\t\t\t(): AnyPgColumn => memoriesTable.id,\n\t\t),\n\t\tsupersededAt: timestamp(\"superseded_at\", { withTimezone: true }),\n\t\texpiresAt: timestamp(\"expires_at\", { withTimezone: true }),\n\t\tlastAccessedAt: timestamp(\"last_accessed_at\", { withTimezone: true }),\n\t\taccessCount: integer(\"access_count\").notNull().default(0),\n\t\tcreatedAt: timestamp(\"created_at\", { withTimezone: true })\n\t\t\t.notNull()\n\t\t\t.defaultNow(),\n\t\tupdatedAt: timestamp(\"updated_at\", { withTimezone: true })\n\t\t\t.notNull()\n\t\t\t.defaultNow(),\n\t},\n\t(table) => [\n\t\tindex(\"mnemocyte_memories_entity_idx\").on(table.entityId),\n\t\tindex(\"mnemocyte_memories_entity_type_idx\").on(table.entityId, table.type),\n\t\tindex(\"mnemocyte_memories_embedding_hnsw_idx\").using(\n\t\t\t\"hnsw\",\n\t\t\ttable.embedding.op(\"vector_cosine_ops\"),\n\t\t),\n\t],\n);\n\nexport const eventsTable = pgTable(\n\t\"mnemocyte_events\",\n\t{\n\t\tid: text(\"id\").primaryKey(),\n\t\tentityId: text(\"entity_id\").notNull(),\n\t\tdescription: text(\"description\").notNull(),\n\t\tmetadata: jsonb(\"metadata\").$type<JsonObject>().notNull().default({}),\n\t\ttimestamp: timestamp(\"timestamp\", { withTimezone: true })\n\t\t\t.notNull()\n\t\t\t.defaultNow(),\n\t},\n\t(table) => [\n\t\tindex(\"mnemocyte_events_entity_time_idx\").on(\n\t\t\ttable.entityId,\n\t\t\ttable.timestamp,\n\t\t),\n\t],\n);\n\nexport const metaTable = pgTable(\"mnemocyte_meta\", {\n\tkey: text(\"key\").primaryKey(),\n\tembeddingDimensions: integer(\"embedding_dimensions\").notNull(),\n\tembeddingModel: text(\"embedding_model\"),\n});\n\nexport type MemoryRow = typeof memoriesTable.$inferSelect;\nexport type NewMemoryRow = typeof memoriesTable.$inferInsert;\nexport type EventRow = typeof eventsTable.$inferSelect;\nexport type NewEventRow = typeof eventsTable.$inferInsert;\nexport type MetaRow = typeof metaTable.$inferSelect;\n","import { drizzle, type PostgresJsDatabase } from \"drizzle-orm/postgres-js\";\nimport postgres from \"postgres\";\nimport { MnemocyteError } from \"../errors.js\";\nimport * as schema from \"./schema.js\";\n\nexport type MnemocyteDatabase = PostgresJsDatabase<typeof schema>;\n\nexport interface DatabaseHandle {\n\tdb: MnemocyteDatabase;\n\tclose(): Promise<void>;\n}\n\ntype PostgresSslMode =\n\t| \"require\"\n\t| \"prefer\"\n\t| \"allow\"\n\t| \"verify-full\"\n\t| \"disable\";\n\ntype ValidPostgresSsl =\n\t| \"require\"\n\t| \"prefer\"\n\t| \"allow\"\n\t| \"verify-full\"\n\t| boolean\n\t| { rejectUnauthorized: false };\n\nfunction parseSslFromUrl(url: URL): ValidPostgresSsl | undefined {\n\tconst mode = url.searchParams.get(\"sslmode\") as PostgresSslMode | null;\n\tif (!mode || mode === \"disable\") return undefined;\n\n\tif (mode === \"require\" || mode === \"prefer\" || mode === \"allow\") {\n\t\treturn { rejectUnauthorized: false };\n\t}\n\n\tif (mode === \"verify-full\") return \"verify-full\";\n\n\treturn undefined;\n}\n\nexport function createDatabase(databaseUrl: string): DatabaseHandle {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(databaseUrl);\n\t} catch (error) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl must be a valid Postgres connection URL.\",\n\t\t\t\"CONFIG\",\n\t\t\terror,\n\t\t);\n\t}\n\tif (url.protocol !== \"postgres:\" && url.protocol !== \"postgresql:\") {\n\t\tthrow new MnemocyteError(\n\t\t\t\"databaseUrl must use the postgres: or postgresql: protocol.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tconst ssl = parseSslFromUrl(url);\n\n\tconst isPooler =\n\t\turl.port === \"6543\" || url.searchParams.get(\"pgbouncer\") === \"true\";\n\n\tconst client = postgres(databaseUrl, {\n\t\tmax: 10,\n\t\tidle_timeout: 20,\n\t\tconnect_timeout: 10,\n\t\t...(ssl ? { ssl } : {}),\n\t\t...(isPooler ? { prepare: false } : {}),\n\t});\n\n\treturn {\n\t\tdb: drizzle(client, { schema }),\n\t\tasync close() {\n\t\t\tawait client.end();\n\t\t},\n\t};\n}\n","import { MnemocyteError } from \"./errors.js\";\nimport type { ProviderResilienceConfig } from \"./types.js\";\n\n/**\n * Default per-provider-call timeout. Disabled by default so that callers\n * who do not configure {@link ProviderResilienceConfig.timeoutMs} are\n * unaffected.\n */\nconst DEFAULT_TIMEOUT_MS = 0;\n/** Default number of retry attempts on transient provider failures. */\nconst DEFAULT_RETRIES = 0;\n/** Default base backoff delay used between retry attempts. */\nconst DEFAULT_BASE_DELAY_MS = 100;\n/** Default ceiling for retry backoff delay. */\nconst DEFAULT_MAX_DELAY_MS = 2000;\n\n/**\n * Throw a {@link MnemocyteError} with code `\"ABORTED\"` if `signal` is\n * already aborted. Safe to call with `undefined`.\n */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n\tif (signal?.aborted) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Operation was aborted.\",\n\t\t\t\"ABORTED\",\n\t\t\tsignal.reason,\n\t\t);\n\t}\n}\n\n/**\n * Heuristic default for whether an error should be retried.\n *\n * Conservative by design: only retries on common transient failure\n * indicators (network errors, 5xx-ish messages, `ECONN*` etc.). Never\n * retries on validation, configuration, or {@link MnemocyteError} of\n * code `\"VALIDATION\"` / `\"CONFIG\"` / `\"CONFLICT\"` / `\"ABORTED\"`.\n */\nexport function defaultShouldRetry(error: unknown): boolean {\n\tif (error instanceof MnemocyteError) {\n\t\tif (\n\t\t\terror.code === \"VALIDATION\" ||\n\t\t\terror.code === \"CONFIG\" ||\n\t\t\terror.code === \"CONFLICT\" ||\n\t\t\terror.code === \"ABORTED\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"status\" in error &&\n\t\ttypeof (error as { status?: unknown }).status === \"number\" &&\n\t\t[429, 500, 502, 503, 504].includes((error as { status: number }).status)\n\t) {\n\t\treturn true;\n\t}\n\tif (error instanceof Error) {\n\t\tconst message = error.message.toLowerCase();\n\t\tif (\n\t\t\tmessage.includes(\"econn\") ||\n\t\t\tmessage.includes(\"etimedout\") ||\n\t\t\tmessage.includes(\"network\") ||\n\t\t\tmessage.includes(\"timeout\") ||\n\t\t\tmessage.includes(\"temporarily\") ||\n\t\t\tmessage.includes(\"rate limit\") ||\n\t\t\tmessage.includes(\"503\") ||\n\t\t\tmessage.includes(\"502\") ||\n\t\t\tmessage.includes(\"504\") ||\n\t\t\tmessage.includes(\"500\")\n\t\t) {\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n/**\n * Compute the backoff delay for the given retry attempt, using exponential\n * growth capped at {@link ProviderResilienceConfig.maxDelayMs}.\n *\n * `attempt` is 1-indexed: the delay before the first retry uses\n * `attempt = 1`, before the second retry `attempt = 2`, etc.\n */\nfunction computeDelayMs(\n\tattempt: number,\n\tbaseDelayMs: number,\n\tmaxDelayMs: number,\n): number {\n\tconst exponential = baseDelayMs * 2 ** (attempt - 1);\n\treturn Math.max(0, Math.min(maxDelayMs, exponential));\n}\n\n/**\n * Promise-based `setTimeout` that rejects with an `\"ABORTED\"`\n * {@link MnemocyteError} if `signal` aborts while waiting.\n */\nfunction delay(ms: number, signal: AbortSignal | undefined): Promise<void> {\n\tif (ms <= 0) {\n\t\tthrowIfAborted(signal);\n\t\treturn Promise.resolve();\n\t}\n\treturn new Promise<void>((resolve, reject) => {\n\t\tconst timer = setTimeout(() => {\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\tresolve();\n\t\t}, ms);\n\t\tconst onAbort = (): void => {\n\t\t\tclearTimeout(timer);\n\t\t\treject(\n\t\t\t\tnew MnemocyteError(\"Operation was aborted.\", \"ABORTED\", signal?.reason),\n\t\t\t);\n\t\t};\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(\n\t\t\t\t\tnew MnemocyteError(\n\t\t\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t\tsignal.reason,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t});\n}\n\nfunction timeoutError(timeoutMs: number): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t`Provider call timed out after ${timeoutMs}ms.`,\n\t\t\"TIMEOUT\",\n\t);\n}\n\n/**\n * Run one provider attempt with a signal linked to the caller's signal and\n * Mnemocyte's configured timeout. Timeout aborts are actively propagated to\n * providers that honor `AbortSignal`.\n */\nfunction runAttempt<T>(\n\taction: (signal: AbortSignal | undefined) => Promise<T>,\n\ttimeoutMs: number,\n\tsignal: AbortSignal | undefined,\n): Promise<T> {\n\tif (timeoutMs <= 0 && !signal) {\n\t\treturn action(undefined);\n\t}\n\treturn new Promise<T>((resolve, reject) => {\n\t\tlet settled = false;\n\t\tconst controller = new AbortController();\n\t\tconst timer =\n\t\t\ttimeoutMs > 0\n\t\t\t\t? setTimeout(() => {\n\t\t\t\t\t\tif (settled) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsettled = true;\n\t\t\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\t\t\tcontroller.abort(timeoutError(timeoutMs));\n\t\t\t\t\t\treject(timeoutError(timeoutMs));\n\t\t\t\t\t}, timeoutMs)\n\t\t\t\t: undefined;\n\t\tconst onAbort = (): void => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tif (timer) {\n\t\t\t\tclearTimeout(timer);\n\t\t\t}\n\t\t\tcontroller.abort(signal?.reason);\n\t\t\treject(\n\t\t\t\tnew MnemocyteError(\"Operation was aborted.\", \"ABORTED\", signal?.reason),\n\t\t\t);\n\t\t};\n\t\tif (signal) {\n\t\t\tif (signal.aborted) {\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tcontroller.abort(signal.reason);\n\t\t\t\treject(\n\t\t\t\t\tnew MnemocyteError(\n\t\t\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t\tsignal.reason,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t}\n\t\taction(controller.signal).then(\n\t\t\t(value) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(value);\n\t\t\t},\n\t\t\t(error) => {\n\t\t\t\tif (settled) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tsettled = true;\n\t\t\t\tif (timer) {\n\t\t\t\t\tclearTimeout(timer);\n\t\t\t\t}\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\treject(error);\n\t\t\t},\n\t\t);\n\t});\n}\n\n/**\n * Options accepted by {@link withResilience}.\n */\nexport interface ResilienceCallOptions {\n\t/** External cancellation signal forwarded to each attempt. */\n\tsignal?: AbortSignal;\n\t/** Provider-level retry/timeout configuration. */\n\tresilience?: ProviderResilienceConfig;\n}\n\n/**\n * Run `action` with timeout, retry, and abort handling derived from\n * `options.resilience` and `options.signal`. Each retry attempt receives\n * a fresh `AbortSignal` linked to the caller's signal — so callers may\n * abort mid-retry and the in-flight attempt will cancel promptly if the\n * underlying provider honours signals.\n *\n * Errors from {@link MnemocyteError} with code `\"VALIDATION\"` /\n * `\"CONFIG\"` / `\"CONFLICT\"` / `\"ABORTED\"` are never retried.\n */\nexport async function withResilience<T>(\n\taction: (signal: AbortSignal | undefined) => Promise<T>,\n\toptions: ResilienceCallOptions = {},\n): Promise<T> {\n\tconst config = options.resilience ?? {};\n\tconst timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\tconst retries = Math.max(0, config.retries ?? DEFAULT_RETRIES);\n\tconst baseDelayMs = Math.max(0, config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n\tconst maxDelayMs = Math.max(\n\t\tbaseDelayMs,\n\t\tconfig.maxDelayMs ?? DEFAULT_MAX_DELAY_MS,\n\t);\n\tconst shouldRetry = config.shouldRetry ?? defaultShouldRetry;\n\tconst externalSignal = options.signal;\n\n\tthrowIfAborted(externalSignal);\n\n\tconst maxAttempts = retries + 1;\n\tlet lastError: unknown;\n\tfor (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n\t\tthrowIfAborted(externalSignal);\n\t\ttry {\n\t\t\treturn await runAttempt(action, timeoutMs, externalSignal);\n\t\t} catch (error) {\n\t\t\tlastError = error;\n\t\t\tif (error instanceof MnemocyteError && error.code === \"ABORTED\") {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (attempt >= maxAttempts) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tif (!shouldRetry(error, attempt)) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\tconst waitMs = computeDelayMs(attempt, baseDelayMs, maxDelayMs);\n\t\t\tawait delay(waitMs, externalSignal);\n\t\t}\n\t}\n\tthrow lastError;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport type { JsonObject, JsonValue } from \"../types.js\";\n\ndeclare const ownedJsonObject: unique symbol;\n\n/** Internal marker for a JSON object that Mnemocyte has validated and cloned. */\nexport type OwnedJsonObject = JsonObject & {\n\treadonly [ownedJsonObject]: true;\n};\n\nfunction invalidJsonValue(path: string, cause?: unknown): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t`${path} must contain only JSON-compatible value data.`,\n\t\t\"VALIDATION\",\n\t\tcause,\n\t);\n}\n\nfunction cloneJsonValue(\n\tvalue: unknown,\n\tpath: string,\n\tancestors: Set<object>,\n): JsonValue {\n\tif (\n\t\tvalue === null ||\n\t\ttypeof value === \"string\" ||\n\t\ttypeof value === \"boolean\"\n\t) {\n\t\treturn value;\n\t}\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\treturn Object.is(value, -0) ? 0 : value;\n\t}\n\tif (typeof value !== \"object\") {\n\t\tthrow invalidJsonValue(path);\n\t}\n\tif (ancestors.has(value)) {\n\t\tthrow invalidJsonValue(path);\n\t}\n\n\tancestors.add(value);\n\ttry {\n\t\tif (Array.isArray(value)) {\n\t\t\tif (\n\t\t\t\tObject.getOwnPropertySymbols(value).length > 0 ||\n\t\t\t\tObject.keys(value).some((key) => !/^(0|[1-9]\\d*)$/.test(key))\n\t\t\t) {\n\t\t\t\tthrow invalidJsonValue(path);\n\t\t\t}\n\t\t\treturn Array.from({ length: value.length }, (_, index) => {\n\t\t\t\tif (!Object.hasOwn(value, index)) {\n\t\t\t\t\tthrow invalidJsonValue(`${path}[${index}]`);\n\t\t\t\t}\n\t\t\t\treturn cloneJsonValue(value[index], `${path}[${index}]`, ancestors);\n\t\t\t});\n\t\t}\n\n\t\tconst prototype = Object.getPrototypeOf(value);\n\t\tif (prototype !== Object.prototype && prototype !== null) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\tconst descriptors = Object.getOwnPropertyDescriptors(value);\n\t\tconst entries: Array<[string, JsonValue]> = [];\n\t\tfor (const key of Reflect.ownKeys(descriptors)) {\n\t\t\tif (typeof key !== \"string\") {\n\t\t\t\tthrow invalidJsonValue(path);\n\t\t\t}\n\t\t\tconst descriptor = descriptors[key];\n\t\t\tif (\n\t\t\t\tdescriptor === undefined ||\n\t\t\t\tdescriptor.enumerable !== true ||\n\t\t\t\t!(\"value\" in descriptor)\n\t\t\t) {\n\t\t\t\tthrow invalidJsonValue(`${path}.${key}`);\n\t\t\t}\n\t\t\tentries.push([\n\t\t\t\tkey,\n\t\t\t\tcloneJsonValue(descriptor.value, `${path}.${key}`, ancestors),\n\t\t\t]);\n\t\t}\n\t\treturn Object.fromEntries(entries);\n\t} finally {\n\t\tancestors.delete(value);\n\t}\n}\n\n/** Validate and deep-clone a JSON-compatible object. */\nexport function cloneJsonObject(\n\tvalue: unknown,\n\tpath = \"metadata\",\n): OwnedJsonObject {\n\ttry {\n\t\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\t\tthrow invalidJsonValue(path);\n\t\t}\n\t\treturn cloneJsonValue(value, path, new Set()) as OwnedJsonObject;\n\t} catch (error) {\n\t\tif (error instanceof MnemocyteError) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow invalidJsonValue(path, error);\n\t}\n}\n","import type { Memory } from \"../types.js\";\nimport { cloneJsonObject } from \"./json.js\";\n\nexport interface StoredMemory extends Memory {\n\tembedding: number[];\n}\n\nexport function normalizeTags(tags: readonly string[] | undefined): string[] {\n\tif (!tags) {\n\t\treturn [];\n\t}\n\treturn [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];\n}\n\nexport function createId(): string {\n\treturn `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Generate a unique audit-event id (`evt_*`). */\nexport function createEventId(): string {\n\treturn `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;\n}\n\nexport function cloneMemory(memory: Memory): Memory {\n\treturn {\n\t\tid: memory.id,\n\t\tentityId: memory.entityId,\n\t\tcontent: memory.content,\n\t\ttype: memory.type,\n\t\timportance: memory.importance,\n\t\ttags: [...memory.tags],\n\t\tsource: memory.source,\n\t\tmetadata: cloneJsonObject(memory.metadata),\n\t\tconfidence: memory.confidence,\n\t\tembeddingModel: memory.embeddingModel,\n\t\tembeddingDimensions: memory.embeddingDimensions,\n\t\tsupersededBy: memory.supersededBy,\n\t\tsupersededAt: memory.supersededAt ? new Date(memory.supersededAt) : null,\n\t\texpiresAt: memory.expiresAt ? new Date(memory.expiresAt) : null,\n\t\tlastAccessedAt: memory.lastAccessedAt\n\t\t\t? new Date(memory.lastAccessedAt)\n\t\t\t: null,\n\t\taccessCount: memory.accessCount,\n\t\tcreatedAt: new Date(memory.createdAt),\n\t\tupdatedAt: new Date(memory.updatedAt),\n\t};\n}\n","import { cloneMemory } from \"../memory/records.js\";\nimport type {\n\tImportanceLevel,\n\tMemory,\n\tMemoryWithScore,\n\tRecallInput,\n\tRetrievalConfig,\n\tRetrievalScoreWeights,\n} from \"../types.js\";\n\nconst IMPORTANCE_SCORES: Record<ImportanceLevel, number> = {\n\tlow: 0,\n\tnormal: 0.5,\n\thigh: 0.8,\n\tcritical: 1,\n};\n\nexport const DEFAULT_RETRIEVAL_WEIGHTS: Readonly<\n\tRequired<RetrievalScoreWeights>\n> = {\n\tvector: 0.55,\n\tlexical: 0.2,\n\trecency: 0.1,\n\tconfidence: 0.05,\n\taccess: 0.05,\n\timportance: 0.05,\n};\n\nconst DEFAULT_RECENCY_HALF_LIFE_DAYS = 90;\nconst DEFAULT_ACCESS_SATURATION = 10;\nexport const DEFAULT_CANDIDATE_MULTIPLIER = 3;\n\nexport interface ScoringConfig {\n\tweights: Required<RetrievalScoreWeights>;\n\trecencyHalfLifeDays: number;\n\taccessSaturation: number;\n}\n\nexport function cosineSimilarity(\n\ta: readonly number[],\n\tb: readonly number[],\n): number {\n\tlet dot = 0;\n\tlet aMagnitude = 0;\n\tlet bMagnitude = 0;\n\tfor (let i = 0; i < a.length; i += 1) {\n\t\tconst av = a[i] ?? 0;\n\t\tconst bv = b[i] ?? 0;\n\t\tdot += av * bv;\n\t\taMagnitude += av * av;\n\t\tbMagnitude += bv * bv;\n\t}\n\tif (aMagnitude === 0 || bMagnitude === 0) {\n\t\treturn 0;\n\t}\n\treturn dot / (Math.sqrt(aMagnitude) * Math.sqrt(bMagnitude));\n}\n\nexport function tokenizeQuery(query: string): readonly string[] {\n\treturn query.toLowerCase().split(/\\s+/).filter(Boolean);\n}\n\nexport function lexicalScoreWithTerms(\n\tcontent: string,\n\tterms: readonly string[],\n): number {\n\tif (terms.length === 0) {\n\t\treturn 0;\n\t}\n\tconst lowerContent = content.toLowerCase();\n\tconst matches = terms.filter((term) => lowerContent.includes(term)).length;\n\treturn matches / terms.length;\n}\n\nexport function createLexicalScorer(\n\tquery: string,\n): (content: string) => number {\n\tconst terms = tokenizeQuery(query);\n\treturn (content) => lexicalScoreWithTerms(content, terms);\n}\n\nfunction clampScore(value: number): number {\n\tif (!Number.isFinite(value)) {\n\t\treturn 0;\n\t}\n\treturn Math.max(0, Math.min(1, value));\n}\n\nexport function toVectorScore(cosineSimilarity: number): number {\n\treturn clampScore(cosineSimilarity);\n}\n\nfunction normalizeWeights(\n\tweights: RetrievalScoreWeights | undefined,\n): Required<RetrievalScoreWeights> {\n\tconst merged = { ...DEFAULT_RETRIEVAL_WEIGHTS, ...weights };\n\tconst total =\n\t\tmerged.vector +\n\t\tmerged.lexical +\n\t\tmerged.recency +\n\t\tmerged.confidence +\n\t\tmerged.access +\n\t\tmerged.importance;\n\tif (total <= 0) {\n\t\treturn { ...DEFAULT_RETRIEVAL_WEIGHTS };\n\t}\n\treturn {\n\t\tvector: merged.vector / total,\n\t\tlexical: merged.lexical / total,\n\t\trecency: merged.recency / total,\n\t\tconfidence: merged.confidence / total,\n\t\taccess: merged.access / total,\n\t\timportance: merged.importance / total,\n\t};\n}\n\nexport function createScoringConfig(config?: RetrievalConfig): ScoringConfig {\n\treturn {\n\t\tweights: normalizeWeights(config?.weights),\n\t\trecencyHalfLifeDays:\n\t\t\tconfig?.recencyHalfLifeDays ?? DEFAULT_RECENCY_HALF_LIFE_DAYS,\n\t\taccessSaturation: config?.accessSaturation ?? DEFAULT_ACCESS_SATURATION,\n\t};\n}\n\nfunction recencyScore(createdAt: Date, halfLifeDays: number): number {\n\tconst ageMs = Date.now() - createdAt.getTime();\n\tconst ageDays = Math.max(0, ageMs / 86_400_000);\n\treturn Math.exp((-Math.LN2 * ageDays) / halfLifeDays);\n}\n\nfunction accessScore(accessCount: number, saturation: number): number {\n\tif (accessCount <= 0) {\n\t\treturn 0;\n\t}\n\treturn Math.min(1, Math.log1p(accessCount) / Math.log1p(saturation));\n}\n\nexport function toScoredMemoryWithConfig(\n\tmemory: Memory,\n\tvector: number,\n\tlexical: number,\n\tinput: RecallInput,\n\tconfig: ScoringConfig,\n): MemoryWithScore {\n\tconst { weights } = config;\n\tconst recency = recencyScore(memory.createdAt, config.recencyHalfLifeDays);\n\tconst confidence = clampScore(memory.confidence);\n\tconst access = accessScore(memory.accessCount, config.accessSaturation);\n\tconst importance = IMPORTANCE_SCORES[memory.importance];\n\tconst score = Math.max(\n\t\t0,\n\t\tMath.min(\n\t\t\t1,\n\t\t\tclampScore(vector) * weights.vector +\n\t\t\t\tclampScore(lexical) * weights.lexical +\n\t\t\t\trecency * weights.recency +\n\t\t\t\tconfidence * weights.confidence +\n\t\t\t\taccess * weights.access +\n\t\t\t\timportance * weights.importance,\n\t\t),\n\t);\n\treturn {\n\t\t...cloneMemory(memory),\n\t\tscore,\n\t\tscores: {\n\t\t\tvector: clampScore(vector),\n\t\t\tlexical: clampScore(lexical),\n\t\t\trecency,\n\t\t\tconfidence,\n\t\t\taccess,\n\t\t\timportance,\n\t\t},\n\t\texplanation: input.explain\n\t\t\t? {\n\t\t\t\t\tvectorScore: clampScore(vector),\n\t\t\t\t\tlexicalScore: clampScore(lexical),\n\t\t\t\t\trecencyScore: recency,\n\t\t\t\t\tconfidenceScore: confidence,\n\t\t\t\t\taccessScore: access,\n\t\t\t\t\timportanceScore: importance,\n\t\t\t\t\timportanceBoost: importance * weights.importance,\n\t\t\t\t\tweights,\n\t\t\t\t\tfinalScore: score,\n\t\t\t\t}\n\t\t\t: null,\n\t};\n}\n","import type { 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 type {\n\tFindDuplicatesInput,\n\tImportanceLevel,\n\tMemoryType,\n} from \"../types.js\";\n\nexport const DEFAULT_LIMIT = 10;\nexport const DEFAULT_MIN_SCORE = 0;\nexport const DEFAULT_TYPE: MemoryType = \"fact\";\nexport const DEFAULT_IMPORTANCE: ImportanceLevel = \"normal\";\n\n/**\n * Ordering of {@link ImportanceLevel} from least to most important. Used\n * by `prune({ maxImportance })` to compare a memory's importance against\n * the caller-supplied ceiling.\n */\nexport const IMPORTANCE_RANK: Record<ImportanceLevel, number> = {\n\tlow: 0,\n\tnormal: 1,\n\thigh: 2,\n\tcritical: 3,\n};\n\n/** Default cosine-similarity threshold for {@link FindDuplicatesInput}. */\nexport const DEFAULT_DUPLICATE_THRESHOLD = 0.95;\n/** Default cap on the number of duplicate pairs returned. */\nexport const DEFAULT_DUPLICATE_LIMIT = 100;\n/** Default cap on audit-log entries returned per `listAuditLog`. */\nexport const DEFAULT_AUDIT_LOG_LIMIT = 50;\n","import { MnemocyteError } from \"../errors.js\";\nimport { withResilience } from \"../resilience.js\";\nimport type { Embedder, ProviderResilienceConfig } from \"../types.js\";\n\nfunction validateEmbedding(\n\tembedding: readonly number[],\n\tdimensions: number,\n): void {\n\tif (embedding.length !== dimensions) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Embedder returned an embedding with unexpected dimensions.\",\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n\tif (embedding.some((component) => !Number.isFinite(component))) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Embedder returned an embedding with non-finite values.\",\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n\tif (embedding.every((component) => component === 0)) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Embedder returned an embedding with zero norm.\",\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n}\n\nexport async function embedOne(\n\tembedder: Embedder,\n\ttext: string,\n\toptions: {\n\t\tsignal?: AbortSignal;\n\t\tresilience?: ProviderResilienceConfig;\n\t} = {},\n): Promise<number[]> {\n\tlet embeddings: number[][];\n\ttry {\n\t\tembeddings = await withResilience(\n\t\t\t(signal) =>\n\t\t\t\tsignal === undefined\n\t\t\t\t\t? embedder.embed([text])\n\t\t\t\t\t: embedder.embed([text], { signal }),\n\t\t\t{\n\t\t\t\t...(options.signal === undefined ? {} : { signal: options.signal }),\n\t\t\t\t...(options.resilience === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { resilience: options.resilience }),\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof MnemocyteError &&\n\t\t\t(error.code === \"TIMEOUT\" || error.code === \"ABORTED\")\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new MnemocyteError(\"Failed to embed text.\", \"EMBEDDING\", error);\n\t}\n\tconst embedding = embeddings[0];\n\tif (!embedding) {\n\t\tthrow new MnemocyteError(\"Embedder returned no embedding.\", \"EMBEDDING\");\n\t}\n\tvalidateEmbedding(embedding, embedder.dimensions);\n\treturn embedding;\n}\n\nexport async function embedMany(\n\tembedder: Embedder,\n\ttexts: readonly string[],\n\toptions: {\n\t\tsignal?: AbortSignal;\n\t\tresilience?: ProviderResilienceConfig;\n\t} = {},\n): Promise<number[][]> {\n\tif (texts.length === 0) {\n\t\treturn [];\n\t}\n\tlet embeddings: number[][];\n\ttry {\n\t\tembeddings = await withResilience(\n\t\t\t(signal) =>\n\t\t\t\tsignal === undefined\n\t\t\t\t\t? embedder.embed(texts)\n\t\t\t\t\t: embedder.embed(texts, { signal }),\n\t\t\t{\n\t\t\t\t...(options.signal === undefined ? {} : { signal: options.signal }),\n\t\t\t\t...(options.resilience === undefined\n\t\t\t\t\t? {}\n\t\t\t\t\t: { resilience: options.resilience }),\n\t\t\t},\n\t\t);\n\t} catch (error) {\n\t\tif (\n\t\t\terror instanceof MnemocyteError &&\n\t\t\t(error.code === \"TIMEOUT\" || error.code === \"ABORTED\")\n\t\t) {\n\t\t\tthrow error;\n\t\t}\n\t\tthrow new MnemocyteError(\"Failed to embed texts.\", \"EMBEDDING\", error);\n\t}\n\tif (embeddings.length !== texts.length) {\n\t\tthrow new MnemocyteError(\n\t\t\t`Embedder returned ${embeddings.length} embeddings for ${texts.length} texts.`,\n\t\t\t\"EMBEDDING\",\n\t\t);\n\t}\n\tfor (const embedding of embeddings) {\n\t\tvalidateEmbedding(embedding, embedder.dimensions);\n\t}\n\treturn embeddings;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport type {\n\tAuditEvent,\n\tEmbedder,\n\tEntityStats,\n\tFindDuplicatesInput,\n\tGlobalStats,\n\tImportanceLevel,\n\tListAuditLogInput,\n\tMemory,\n\tMemoryType,\n\tMnemocyteBackend,\n\tPruneResult,\n\tRecallInput,\n} from \"../types.js\";\nimport type { StoredMemory } from \"./records.js\";\n\nexport interface StoreVectorSearchInput extends Omit<RecallInput, \"minScore\"> {\n\tembedding: readonly number[];\n\tlimit: number;\n\tminVectorScore?: number;\n}\n\nexport interface StoreLexicalSearchInput extends RecallInput {\n\tlimit: number;\n}\n\nexport interface StoreVectorCandidate {\n\tmemory: Memory;\n\t/** Finite cosine component clamped to the inclusive range `[0, 1]`. */\n\tvectorScore: number;\n}\n\nexport interface StoreLexicalCandidate {\n\tmemory: Memory;\n\tlexicalScore: number;\n}\n\nexport interface StoreDuplicatePair {\n\ta: Memory;\n\tb: Memory;\n\tsimilarity: number;\n}\n\nexport interface StoreAccessUpdate {\n\tid: string;\n\tlastAccessedAt: Date;\n\taccessCount: number;\n\tupdatedAt: Date;\n}\n\nexport interface StorePruneEntityDeletion {\n\tentityId: string;\n\tdeletedCount: number;\n}\n\nexport interface StorePruneResult extends PruneResult {\n\tdeletedByEntity: readonly StorePruneEntityDeletion[];\n}\n\nexport interface StoreConsolidationTarget {\n\tid: string;\n\ttags: readonly string[];\n\tsupersededBy: string | null;\n}\n\nexport interface StoreConsolidateInput {\n\tentityId: string;\n\tsurvivorId: string;\n\tsurvivorTags: readonly string[];\n\tsupersededIds: readonly string[];\n\tmergeTags: boolean;\n\tnow: Date;\n\tauditEnabled: boolean;\n}\n\nexport interface StoreConsolidateResult {\n\tsupersededIds: readonly string[];\n}\n\nexport interface StoreOperationOptions {\n\tsignal?: AbortSignal;\n}\n\nexport interface ValidatedPruneFilter {\n\treadonly entityId?: string;\n\treadonly expired?: true;\n\treadonly superseded?: true;\n\treadonly createdBefore?: Date;\n\treadonly notAccessedSince?: Date;\n\treadonly types?: readonly MemoryType[];\n\treadonly tags?: readonly string[];\n\treadonly maxImportance?: ImportanceLevel;\n\treadonly dryRun: boolean;\n}\n\nexport function hasPruneSelector(filter: ValidatedPruneFilter): boolean {\n\treturn (\n\t\tfilter.entityId !== undefined ||\n\t\tfilter.expired === true ||\n\t\tfilter.superseded === true ||\n\t\tfilter.createdBefore !== undefined ||\n\t\tfilter.notAccessedSince !== undefined ||\n\t\t(filter.types !== undefined && filter.types.length > 0) ||\n\t\t(filter.tags !== undefined && filter.tags.length > 0) ||\n\t\tfilter.maxImportance !== undefined\n\t);\n}\n\nexport function assertPruneFilterHasSelector(\n\tfilter: ValidatedPruneFilter,\n): void {\n\tif (!hasPruneSelector(filter)) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"prune requires at least one selector (entityId, expired, superseded, createdBefore, notAccessedSince, types, tags, or maxImportance).\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\n/**\n * Internal storage adapter boundary used by the shared client orchestration.\n *\n * This is intentionally not exported from the public package root in 0.3.x.\n * The public adapter surface is reserved for the later `drizzleStore(db)` line.\n */\nexport interface MemoryStore {\n\treadonly backend: MnemocyteBackend;\n\n\tensureSchema(): Promise<void>;\n\tensureEmbeddingCompatibility(embedder: Embedder): Promise<void>;\n\n\t/**\n\t * Takes ownership of freshly prepared rows and returns exactly one detached\n\t * public record for every input ID. Return order is not trusted; shared\n\t * orchestration validates the ID set and restores input order. Missing,\n\t * duplicate, or unknown returned IDs are storage-contract violations.\n\t * Callers must not mutate or reuse rows after passing them here.\n\t */\n\tinsertMemories(memories: readonly StoredMemory[]): Promise<Memory[]>;\n\tvectorSearch(input: StoreVectorSearchInput): Promise<StoreVectorCandidate[]>;\n\tlexicalSearch(\n\t\tinput: StoreLexicalSearchInput,\n\t): Promise<StoreLexicalCandidate[]>;\n\tgetMemoryEmbeddings(\n\t\tmemoryIds: readonly string[],\n\t): Promise<Map<string, number[]>>;\n\t/**\n\t * Returns exactly one post-update access record for every input ID. Return\n\t * order is not trusted and is normalized by shared orchestration.\n\t */\n\tmarkMemoriesAccessed(\n\t\tmemoryIds: readonly string[],\n\t): Promise<StoreAccessUpdate[]>;\n\n\t/** Throws `\"CONFLICT\"` when the selected memory has dependents. */\n\tdeleteMemory(entityId: string, memoryId: string): Promise<boolean>;\n\t/** Throws `\"CONFLICT\"` before deleting when any selected memory has dependents. */\n\tdeleteMemoriesForEntity(entityId: string): Promise<number>;\n\tprune(\n\t\tinput: ValidatedPruneFilter,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StorePruneResult>;\n\tfindDuplicatePairs(\n\t\tinput: FindDuplicatesInput,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StoreDuplicatePair[]>;\n\n\t/** Persists independent copies of audit events supplied by shared core. */\n\taddAuditEvents(events: readonly AuditEvent[]): Promise<void>;\n\t/** Returns detached audit events safe to expose through the public client. */\n\tlistAuditLog(\n\t\tinput: ListAuditLogInput,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<AuditEvent[]>;\n\n\tgetMemory(\n\t\tentityId: string,\n\t\tmemoryId: string,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<Memory | null>;\n\tloadConsolidationTargets(\n\t\tentityId: string,\n\t\tids: readonly string[],\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StoreConsolidationTarget[]>;\n\t/**\n\t * Applies one atomic consolidation. Throws `\"CONFLICT\"` before mutation\n\t * when any requested loser already points to a different survivor.\n\t */\n\tconsolidate(\n\t\tinput: StoreConsolidateInput,\n\t\toptions?: StoreOperationOptions,\n\t): Promise<StoreConsolidateResult>;\n\n\tstats(\n\t\tinput: { entityId?: string } | undefined,\n\t\tnow: Date,\n\t): Promise<EntityStats | GlobalStats>;\n\tclose(): Promise<void>;\n}\n","import { MnemocyteError } from \"../errors.js\";\nimport { DEFAULT_RETRIEVAL_WEIGHTS } from \"../retrieval/scorer.js\";\nimport type {\n\tAuditLogCursor,\n\tBuildContextInput,\n\tConsolidateInput,\n\tEmbedder,\n\tFindDuplicatesInput,\n\tImportanceLevel,\n\tListAuditLogInput,\n\tMemoryType,\n\tProviderResilienceConfig,\n\tPruneInput,\n\tRecallInput,\n\tRememberInput,\n\tRetrievalConfig,\n\tRetrievalScoreWeights,\n} from \"../types.js\";\nimport type { OwnedJsonObject } from \"./json.js\";\nimport {\n\tassertPruneFilterHasSelector,\n\ttype ValidatedPruneFilter,\n} from \"./store.js\";\n\nconst MEMORY_TYPES = [\n\t\"fact\",\n\t\"preference\",\n\t\"instruction\",\n\t\"backstory\",\n\t\"episode\",\n\t\"session\",\n] as const satisfies readonly MemoryType[];\n\nconst IMPORTANCE_LEVELS = [\n\t\"low\",\n\t\"normal\",\n\t\"high\",\n\t\"critical\",\n] as const satisfies readonly ImportanceLevel[];\n\nexport interface PreparedRememberInput extends Omit<RememberInput, \"metadata\"> {\n\tmetadata: OwnedJsonObject;\n}\n\nfunction isMemoryType(value: unknown): value is MemoryType {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\t(MEMORY_TYPES as readonly string[]).includes(value)\n\t);\n}\n\nfunction isImportanceLevel(value: unknown): value is ImportanceLevel {\n\treturn (\n\t\ttypeof value === \"string\" &&\n\t\t(IMPORTANCE_LEVELS as readonly string[]).includes(value)\n\t);\n}\n\nfunction assertMemoryType(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is MemoryType {\n\tif (!isMemoryType(value)) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be a known memory type.`,\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nfunction assertImportanceLevel(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is ImportanceLevel {\n\tif (!isImportanceLevel(value)) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be a known importance level.`,\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nfunction assertMemoryTypeArray(\n\tvalue: unknown,\n\tfield: string,\n): asserts value is readonly MemoryType[] {\n\tif (!Array.isArray(value)) {\n\t\tthrow new MnemocyteError(`${field} must be an array.`, \"VALIDATION\");\n\t}\n\tfor (const item of value) {\n\t\tif (!isMemoryType(item)) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`${field} must contain only known memory types.`,\n\t\t\t\t\"VALIDATION\",\n\t\t\t);\n\t\t}\n\t}\n}\n\nfunction assertValidDate(value: unknown, field: string): asserts value is Date {\n\tif (!(value instanceof Date) || !Number.isFinite(value.getTime())) {\n\t\tthrow new MnemocyteError(`${field} must be a valid Date.`, \"VALIDATION\");\n\t}\n}\n\nexport function assertNonEmptyString(\n\tvalue: unknown,\n\tfield: string,\n\tcode: \"CONFIG\" | \"VALIDATION\" = \"VALIDATION\",\n): asserts value is string {\n\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\tthrow new MnemocyteError(`${field} must be a non-empty string.`, code);\n\t}\n}\n\nexport function assertLimit(value: number): void {\n\tif (!Number.isInteger(value) || value < 1) {\n\t\tthrow new MnemocyteError(\"limit must be a positive integer.\", \"VALIDATION\");\n\t}\n}\n\nexport function assertMinScore(value: number): void {\n\tif (!Number.isFinite(value) || value < 0 || value > 1) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"minScore must be a number between 0 and 1.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nexport function assertEmbedder(embedder: Embedder): void {\n\tif (!embedder || typeof embedder.embed !== \"function\") {\n\t\tthrow new MnemocyteError(\n\t\t\t\"embedder with an embed function is required.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tassertNonEmptyString(embedder.model, \"embedder.model\", \"CONFIG\");\n\tif (!Number.isInteger(embedder.dimensions) || embedder.dimensions < 1) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"embedder.dimensions must be a positive integer.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nconst RETRIEVAL_WEIGHT_KEYS = [\n\t\"vector\",\n\t\"lexical\",\n\t\"recency\",\n\t\"confidence\",\n\t\"access\",\n\t\"importance\",\n] as const satisfies readonly (keyof RetrievalScoreWeights)[];\n\nfunction assertPositiveFiniteConfigValue(value: number, field: string): void {\n\tif (!Number.isFinite(value) || value <= 0) {\n\t\tthrow new MnemocyteError(\n\t\t\t`${field} must be a positive finite number.`,\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nexport function validateRetrievalConfig(\n\tconfig: RetrievalConfig | undefined,\n): void {\n\tif (config === undefined) {\n\t\treturn;\n\t}\n\n\tlet weightTotal = 0;\n\tfor (const key of RETRIEVAL_WEIGHT_KEYS) {\n\t\tconst weight = config.weights?.[key] ?? DEFAULT_RETRIEVAL_WEIGHTS[key];\n\t\tif (!Number.isFinite(weight) || weight < 0) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`retrieval.weights.${key} must be a non-negative finite number.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t\tweightTotal += weight;\n\t}\n\tif (weightTotal === 0) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"retrieval.weights must have an effective total greater than zero.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\n\tif (config.recencyHalfLifeDays !== undefined) {\n\t\tassertPositiveFiniteConfigValue(\n\t\t\tconfig.recencyHalfLifeDays,\n\t\t\t\"retrieval.recencyHalfLifeDays\",\n\t\t);\n\t}\n\tif (config.accessSaturation !== undefined) {\n\t\tassertPositiveFiniteConfigValue(\n\t\t\tconfig.accessSaturation,\n\t\t\t\"retrieval.accessSaturation\",\n\t\t);\n\t}\n\tif (\n\t\tconfig.candidateMultiplier !== undefined &&\n\t\t(!Number.isInteger(config.candidateMultiplier) ||\n\t\t\tconfig.candidateMultiplier < 1)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"retrieval.candidateMultiplier must be an integer greater than or equal to 1.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nexport function validateProviderResilienceConfig(\n\tconfig: ProviderResilienceConfig | undefined,\n): void {\n\tif (config === undefined) {\n\t\treturn;\n\t}\n\tif (typeof config !== \"object\" || config === null || Array.isArray(config)) {\n\t\tthrow new MnemocyteError(\"provider must be an object.\", \"CONFIG\");\n\t}\n\n\tfor (const [field, value] of [\n\t\t[\"provider.timeoutMs\", config.timeoutMs],\n\t\t[\"provider.baseDelayMs\", config.baseDelayMs],\n\t\t[\"provider.maxDelayMs\", config.maxDelayMs],\n\t] as const) {\n\t\tif (value !== undefined && (!Number.isFinite(value) || value < 0)) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`${field} must be a non-negative finite number.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t}\n\tif (\n\t\tconfig.retries !== undefined &&\n\t\t(!Number.isInteger(config.retries) || config.retries < 0)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"provider.retries must be a non-negative integer.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n\tif (\n\t\tconfig.shouldRetry !== undefined &&\n\t\ttypeof config.shouldRetry !== \"function\"\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"provider.shouldRetry must be a function.\",\n\t\t\t\"CONFIG\",\n\t\t);\n\t}\n}\n\nexport function validateBuildContextInput(input: BuildContextInput): void {\n\tif (\n\t\tinput.maxTokens !== undefined &&\n\t\t(!Number.isInteger(input.maxTokens) || input.maxTokens < 1)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"maxTokens must be a positive integer when supplied.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n}\n\nexport function validateRememberInput(input: PreparedRememberInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tassertNonEmptyString(input.content, \"content\");\n\tif (input.type !== undefined) {\n\t\tassertMemoryType(input.type, \"type\");\n\t}\n\tif (input.importance !== undefined) {\n\t\tassertImportanceLevel(input.importance, \"importance\");\n\t}\n\tif (input.tags !== undefined) {\n\t\tif (!Array.isArray(input.tags)) {\n\t\t\tthrow new MnemocyteError(\"tags must be an array.\", \"VALIDATION\");\n\t\t}\n\t\tfor (const tag of input.tags as readonly unknown[]) {\n\t\t\tif (typeof tag !== \"string\") {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"tags must contain only strings.\",\n\t\t\t\t\t\"VALIDATION\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\tif (input.source !== undefined && typeof input.source !== \"string\") {\n\t\tthrow new MnemocyteError(\"source must be a string.\", \"VALIDATION\");\n\t}\n\tif (\n\t\tinput.confidence !== undefined &&\n\t\t(!Number.isFinite(input.confidence) ||\n\t\t\tinput.confidence < 0 ||\n\t\t\tinput.confidence > 1)\n\t) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"confidence must be a number between 0 and 1.\",\n\t\t\t\"VALIDATION\",\n\t\t);\n\t}\n\tif (input.expiresAt !== undefined) {\n\t\tassertValidDate(input.expiresAt, \"expiresAt\");\n\t}\n}\n\nexport function validateRecallInput(input: RecallInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tassertNonEmptyString(input.query, \"query\");\n\tif (input.limit !== undefined) {\n\t\tassertLimit(input.limit);\n\t}\n\tif (input.minScore !== undefined) {\n\t\tassertMinScore(input.minScore);\n\t}\n\tif (input.types !== undefined) {\n\t\tassertMemoryTypeArray(input.types, \"types\");\n\t}\n}\n\nexport function contextInputToRecallInput(\n\tinput: BuildContextInput,\n): RecallInput {\n\treturn {\n\t\tentityId: input.entityId,\n\t\tquery: input.query,\n\t\t...(input.limit === undefined ? {} : { limit: input.limit }),\n\t\t...(input.minScore === undefined ? {} : { minScore: input.minScore }),\n\t\t...(input.types === undefined ? {} : { types: input.types }),\n\t\t...(input.tags === undefined ? {} : { tags: input.tags }),\n\t\t...(input.includeSuperseded === undefined\n\t\t\t? {}\n\t\t\t: { includeSuperseded: input.includeSuperseded }),\n\t\t...(input.includeExpired === undefined\n\t\t\t? {}\n\t\t\t: { includeExpired: input.includeExpired }),\n\t};\n}\n\n/**\n * Validate and normalize a {@link PruneInput}. Throws a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed fields or when normalization leaves no\n * effective selector, preventing surprise full-table deletes.\n */\nexport function validatePruneInput(input: PruneInput): ValidatedPruneFilter {\n\tif (input.entityId !== undefined) {\n\t\tassertNonEmptyString(input.entityId, \"entityId\");\n\t}\n\tfor (const [field, value] of [\n\t\t[\"expired\", input.expired],\n\t\t[\"superseded\", input.superseded],\n\t\t[\"dryRun\", input.dryRun],\n\t] as const) {\n\t\tif (value !== undefined && typeof value !== \"boolean\") {\n\t\t\tthrow new MnemocyteError(`${field} must be a boolean.`, \"VALIDATION\");\n\t\t}\n\t}\n\tfor (const [field, value] of [\n\t\t[\"createdBefore\", input.createdBefore],\n\t\t[\"notAccessedSince\", input.notAccessedSince],\n\t] as const) {\n\t\tif (value !== undefined) {\n\t\t\tassertValidDate(value, field);\n\t\t}\n\t}\n\tlet types: readonly MemoryType[] | undefined;\n\tif (input.types !== undefined) {\n\t\tassertMemoryTypeArray(input.types, \"types\");\n\t\tconst normalized = new Set<MemoryType>(input.types);\n\t\tif (normalized.size > 0) {\n\t\t\ttypes = [...normalized];\n\t\t}\n\t}\n\tlet tags: readonly string[] | undefined;\n\tif (input.tags !== undefined) {\n\t\tif (!Array.isArray(input.tags)) {\n\t\t\tthrow new MnemocyteError(\"tags must be an array.\", \"VALIDATION\");\n\t\t}\n\t\tconst normalized = new Set<string>();\n\t\tfor (const value of input.tags as readonly unknown[]) {\n\t\t\tif (typeof value !== \"string\" || value.trim().length === 0) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"tags must contain only non-empty strings.\",\n\t\t\t\t\t\"VALIDATION\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tnormalized.add(value.trim());\n\t\t}\n\t\tif (normalized.size > 0) {\n\t\t\ttags = [...normalized];\n\t\t}\n\t}\n\tif (input.maxImportance !== undefined) {\n\t\tassertImportanceLevel(input.maxImportance, \"maxImportance\");\n\t}\n\tif (\n\t\tinput.signal !== undefined &&\n\t\t(typeof input.signal !== \"object\" ||\n\t\t\tinput.signal === null ||\n\t\t\ttypeof input.signal.aborted !== \"boolean\" ||\n\t\t\ttypeof input.signal.addEventListener !== \"function\" ||\n\t\t\ttypeof input.signal.removeEventListener !== \"function\")\n\t) {\n\t\tthrow new MnemocyteError(\"signal must be an AbortSignal.\", \"VALIDATION\");\n\t}\n\tconst filter: ValidatedPruneFilter = {\n\t\t...(input.entityId === undefined ? {} : { entityId: input.entityId }),\n\t\t...(input.expired === true ? { expired: true as const } : {}),\n\t\t...(input.superseded === true ? { superseded: true as const } : {}),\n\t\t...(input.createdBefore === undefined\n\t\t\t? {}\n\t\t\t: { createdBefore: new Date(input.createdBefore) }),\n\t\t...(input.notAccessedSince === undefined\n\t\t\t? {}\n\t\t\t: { notAccessedSince: new Date(input.notAccessedSince) }),\n\t\t...(types === undefined ? {} : { types }),\n\t\t...(tags === undefined ? {} : { tags }),\n\t\t...(input.maxImportance === undefined\n\t\t\t? {}\n\t\t\t: { maxImportance: input.maxImportance }),\n\t\tdryRun: input.dryRun === true,\n\t};\n\tassertPruneFilterHasSelector(filter);\n\treturn filter;\n}\n\n/**\n * Validate a {@link FindDuplicatesInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed `threshold` / `limit` values.\n */\nexport function validateFindDuplicatesInput(input: FindDuplicatesInput): void {\n\tassertNonEmptyString(input.entityId, \"entityId\");\n\tif (input.threshold !== undefined) {\n\t\tif (\n\t\t\t!Number.isFinite(input.threshold) ||\n\t\t\tinput.threshold < 0 ||\n\t\t\tinput.threshold > 1\n\t\t) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t\"threshold must be a number between 0 and 1.\",\n\t\t\t\t\"VALIDATION\",\n\t\t\t);\n\t\t}\n\t}\n\tif (input.limit !== undefined) {\n\t\tassertLimit(input.limit);\n\t}\n\tif (input.types !== undefined) {\n\t\tassertMemoryTypeArray(input.types, \"types\");\n\t}\n}\n\n/**\n * Validate a {@link ConsolidateInput} and throw a `\"VALIDATION\"`\n * {@link MnemocyteError} for malformed inputs (empty `supersededIds`\n * or a `survivorId` appearing in `supersededIds`).\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\tfor (const id of input.supersededIds) {\n\t\tassertNonEmptyString(id, \"supersededIds[*]\");\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\tsurvivorTags: survivor.tags,\n\t\t\t\t\t\t\t\t\t\tsupersededIds: input.supersededIds,\n\t\t\t\t\t\t\t\t\t\tmergeTags: input.mergeTags !== false,\n\t\t\t\t\t\t\t\t\t\tnow: new Date(),\n\t\t\t\t\t\t\t\t\t\tauditEnabled: config.audit?.enabled === true,\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tstoreOptions(input.signal),\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tsurvivorId: survivor.id,\n\t\t\t\t\t\t\t\t\tsupersededCount: result.supersededIds.length,\n\t\t\t\t\t\t\t\t\tsupersededIds: result.supersededIds,\n\t\t\t\t\t\t\t\t} satisfies ConsolidateResult;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t(result) => ({ count: result.supersededCount }),\n\t\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t},\n\t\t},\n\t\tclose() {\n\t\t\tif (closePromise) {\n\t\t\t\treturn closePromise;\n\t\t\t}\n\t\t\tstate = \"closing\";\n\t\t\tclosePromise = observe(config, store.backend, \"close\", {}, async () => {\n\t\t\t\tawait waitForActiveOperations();\n\t\t\t\ttry {\n\t\t\t\t\tawait store.close();\n\t\t\t\t\tstate = \"closed\";\n\t\t\t\t} catch (error) {\n\t\t\t\t\tstate = \"open\";\n\t\t\t\t\tclosePromise = undefined;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\treturn closePromise;\n\t\t},\n\t};\n\n\treturn client;\n}\n","import { MnemocyteError } from \"../errors.js\";\n\nexport function memoryHasDependentsError(cause?: unknown): MnemocyteError {\n\treturn new MnemocyteError(\n\t\t\"Memory cannot be deleted while other memories reference it as their consolidation survivor.\",\n\t\t\"CONFLICT\",\n\t\tcause,\n\t);\n}\n","import 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\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 (survivor && input.mergeTags && newlySuperseded.length > 0) {\n\t\t\t\tconst mergedTags = new Set(input.survivorTags);\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 (survivor && 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 { SQL } from \"drizzle-orm\";\nimport { PgDialect } from \"drizzle-orm/pg-core\";\nimport type { Sql } from \"postgres\";\nimport { MnemocyteError } from \"../errors.js\";\nimport { throwIfAborted } from \"../resilience.js\";\nimport type { MnemocyteDatabase } from \"./index.js\";\n\nconst postgresDialect = new PgDialect();\n\ninterface CancelableQuery<T> extends PromiseLike<T> {\n\tcancel(): void;\n}\n\nasync function awaitCancelableQuery<T>(\n\tquery: CancelableQuery<T>,\n\tsignal: AbortSignal | undefined,\n): Promise<T> {\n\tthrowIfAborted(signal);\n\tif (!signal) {\n\t\treturn await query;\n\t}\n\tconst onAbort = (): void => {\n\t\tquery.cancel();\n\t};\n\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\ttry {\n\t\treturn await query;\n\t} catch (error) {\n\t\tif (signal.aborted) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t\"Operation was aborted.\",\n\t\t\t\t\"ABORTED\",\n\t\t\t\tsignal.reason,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t} finally {\n\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t}\n}\n\nexport async function executeCancelableSql<T>(\n\tdb: MnemocyteDatabase,\n\tstatement: SQL,\n\tsignal: AbortSignal | undefined,\n): Promise<T> {\n\tconst query = postgresDialect.sqlToQuery(statement);\n\tconst client = (db as MnemocyteDatabase & { $client?: Sql }).$client;\n\tif (!client) {\n\t\tthrow new MnemocyteError(\n\t\t\t\"Cancelable Postgres query requires the postgres.js client.\",\n\t\t\t\"DB\",\n\t\t);\n\t}\n\treturn (await awaitCancelableQuery(\n\t\tclient.unsafe(query.sql, query.params as never[]),\n\t\tsignal,\n\t)) as T;\n}\n","import { sql } from \"drizzle-orm\";\nimport { MnemocyteError } from \"../../errors.js\";\nimport type { AuditLogCursor } from \"../../types.js\";\nimport { executeCancelableSql } from \"../cancellation.js\";\nimport type { MnemocyteDatabase } from \"../index.js\";\nimport { type EventRow, eventsTable, type NewEventRow } from \"../schema.js\";\n\nexport interface EventFilter {\n\tentityId: string;\n\tlimit?: number;\n\tbefore?: Date;\n\tafter?: Date;\n\tbeforeCursor?: AuditLogCursor;\n\tafterCursor?: AuditLogCursor;\n}\n\nfunction timestampParam(value: Date) {\n\treturn sql`${value.toISOString()}::timestamptz`;\n}\n\nexport async function insertEvent(\n\tdb: MnemocyteDatabase,\n\trow: NewEventRow,\n): Promise<EventRow> {\n\tconst result = await db.insert(eventsTable).values(row).returning();\n\tconst inserted = result[0];\n\tif (!inserted) {\n\t\tthrow new MnemocyteError(\"Event insert returned no rows.\", \"DB\");\n\t}\n\treturn inserted;\n}\n\nexport async function listEvents(\n\tdb: MnemocyteDatabase,\n\tfilter: EventFilter,\n\tsignal?: AbortSignal,\n): Promise<EventRow[]> {\n\treturn executeCancelableSql<EventRow[]>(\n\t\tdb,\n\t\tsql`\n\t\t\tSELECT\n\t\t\t\tid,\n\t\t\t\tentity_id AS \"entityId\",\n\t\t\t\tdescription,\n\t\t\t\tmetadata,\n\t\t\t\ttimestamp\n\t\t\tFROM mnemocyte_events\n\t\t\tWHERE entity_id = ${filter.entityId}\n\t\t\t\t${filter.before ? sql`AND timestamp < ${timestampParam(filter.before)}` : sql``}\n\t\t\t\t${filter.after ? sql`AND timestamp > ${timestampParam(filter.after)}` : sql``}\n\t\t\t\t${\n\t\t\t\t\tfilter.beforeCursor\n\t\t\t\t\t\t? sql`AND (timestamp, id) < (${timestampParam(filter.beforeCursor.timestamp)}, ${filter.beforeCursor.id})`\n\t\t\t\t\t\t: sql``\n\t\t\t\t}\n\t\t\t\t${\n\t\t\t\t\tfilter.afterCursor\n\t\t\t\t\t\t? sql`AND (timestamp, id) > (${timestampParam(filter.afterCursor.timestamp)}, ${filter.afterCursor.id})`\n\t\t\t\t\t\t: sql``\n\t\t\t\t}\n\t\t\tORDER BY timestamp DESC, id DESC\n\t\t\tLIMIT ${filter.limit ?? 50}\n\t\t`,\n\t\tsignal,\n\t);\n}\n","import {\n\tand,\n\tcount,\n\tcountDistinct,\n\teq,\n\tinArray,\n\tisNotNull,\n\tisNull,\n\tlt,\n\tor,\n\ttype SQL,\n\tsql,\n} from \"drizzle-orm\";\nimport type { ImportanceLevel, MemoryType } from \"../../types.js\";\nimport { executeCancelableSql } from \"../cancellation.js\";\nimport type { MnemocyteDatabase } from \"../index.js\";\nimport { type MemoryRow, memoriesTable, type NewMemoryRow } from \"../schema.js\";\nimport { formatVectorComponent } from \"../vector.js\";\n\nexport interface MemoryFilter {\n\tentityId: string;\n\ttypes?: readonly MemoryType[];\n\ttags?: readonly string[];\n\tbefore?: Date;\n\tafter?: Date;\n\tincludeSuperseded?: boolean;\n\tincludeExpired?: boolean;\n}\n\nexport interface VectorSearchInput extends MemoryFilter {\n\tembedding: readonly number[];\n\tlimit: number;\n\tminVectorScore?: number;\n}\n\nexport interface LexicalSearchInput extends MemoryFilter {\n\tquery: string;\n\tlimit: number;\n}\n\nexport interface MemoryStatsCounts {\n\tmemoryCount: number;\n\tactiveMemoryCount: number;\n\texpiredMemoryCount: number;\n\tsupersededMemoryCount: number;\n}\n\nexport interface GuardedDeleteResult {\n\tmatchedCount: number;\n\tdeletedCount: number;\n\thasDependents: boolean;\n\tdeletedByEntity: Array<{ entityId: string; deletedCount: number }>;\n}\n\nexport interface GlobalMemoryStatsCounts extends MemoryStatsCounts {\n\tentityCount: number;\n}\n\nfunction vectorLiteral(embedding: readonly number[]): string {\n\treturn `[${embedding.map(formatVectorComponent).join(\",\")}]`;\n}\n\nfunction clampedVectorScore(embedding: string) {\n\tconst rawScore = sql`1 - (embedding <=> ${embedding}::vector)`;\n\treturn sql<number>`\n\t\tCASE\n\t\t\tWHEN ${rawScore} = 'NaN'::double precision\n\t\t\t\tOR ${rawScore} = 'Infinity'::double precision\n\t\t\t\tOR ${rawScore} = '-Infinity'::double precision\n\t\t\t\tTHEN 0::double precision\n\t\t\tELSE GREATEST(\n\t\t\t\t0::double precision,\n\t\t\t\tLEAST(1::double precision, ${rawScore})\n\t\t\t)\n\t\tEND\n\t`;\n}\n\ntype RawTimestamp = Date | string;\n\nexport type RecallMemoryRow = Omit<\n\tMemoryRow,\n\t| \"embedding\"\n\t| \"supersededAt\"\n\t| \"expiresAt\"\n\t| \"lastAccessedAt\"\n\t| \"createdAt\"\n\t| \"updatedAt\"\n> & {\n\tsupersededAt: RawTimestamp | null;\n\texpiresAt: RawTimestamp | null;\n\tlastAccessedAt: RawTimestamp | null;\n\tcreatedAt: RawTimestamp;\n\tupdatedAt: RawTimestamp;\n};\n\nexport type VectorSearchRow = RecallMemoryRow & { vectorScore: number };\n\nexport type LexicalSearchRow = RecallMemoryRow & { lexicalScore: number };\n\nfunction timestampParam(value: Date) {\n\treturn sql`${value.toISOString()}::timestamptz`;\n}\n\nfunction textArrayLiteral(values: readonly string[]) {\n\treturn sql`ARRAY[${sql.join(\n\t\tvalues.map((value) => sql`${value}`),\n\t\tsql`, `,\n\t)}]::text[]`;\n}\n\nfunction tagsContainAll(tags: readonly string[] | undefined) {\n\treturn tags && tags.length > 0\n\t\t? sql`${memoriesTable.tags} @> ${textArrayLiteral(tags)}`\n\t\t: undefined;\n}\n\nfunction rawTagsFilter(tags: readonly string[] | undefined) {\n\treturn tags && tags.length > 0\n\t\t? sql`AND tags @> ${textArrayLiteral(tags)}`\n\t\t: sql``;\n}\n\nfunction duplicateTagsFilter(tags: readonly string[] | undefined) {\n\treturn tags && tags.length > 0\n\t\t? sql`AND a.tags @> ${textArrayLiteral(tags)} AND b.tags @> ${textArrayLiteral(tags)}`\n\t\t: sql``;\n}\n\nfunction memoryStatsCountFields(now: Date) {\n\treturn {\n\t\tmemoryCount: count(),\n\t\tactiveMemoryCount: sql<number>`\n\t\t\t(count(*) FILTER (\n\t\t\t\tWHERE ${memoriesTable.supersededBy} IS NULL\n\t\t\t\t\tAND (${memoriesTable.expiresAt} IS NULL OR ${memoriesTable.expiresAt} > ${timestampParam(now)})\n\t\t\t))::int\n\t\t`.mapWith(Number),\n\t\texpiredMemoryCount: sql<number>`\n\t\t\t(count(*) FILTER (\n\t\t\t\tWHERE ${memoriesTable.expiresAt} IS NOT NULL\n\t\t\t\t\tAND ${memoriesTable.expiresAt} <= ${timestampParam(now)}\n\t\t\t))::int\n\t\t`.mapWith(Number),\n\t\tsupersededMemoryCount:\n\t\t\tsql<number>`(count(*) FILTER (WHERE ${memoriesTable.supersededBy} IS NOT NULL))::int`.mapWith(\n\t\t\t\tNumber,\n\t\t\t),\n\t};\n}\n\nfunction emptyMemoryStatsCounts(): MemoryStatsCounts {\n\treturn {\n\t\tmemoryCount: 0,\n\t\tactiveMemoryCount: 0,\n\t\texpiredMemoryCount: 0,\n\t\tsupersededMemoryCount: 0,\n\t};\n}\n\nexport async function insertMemories(\n\tdb: MnemocyteDatabase,\n\trows: NewMemoryRow[],\n): Promise<MemoryRow[]> {\n\tif (rows.length === 0) {\n\t\treturn [];\n\t}\n\treturn db.insert(memoriesTable).values(rows).returning();\n}\n\nexport async function getMemoryById(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tmemoryId: string,\n): Promise<MemoryRow | null> {\n\tconst result = await db\n\t\t.select()\n\t\t.from(memoriesTable)\n\t\t.where(\n\t\t\tand(eq(memoriesTable.entityId, entityId), eq(memoriesTable.id, memoryId)),\n\t\t)\n\t\t.limit(1);\n\treturn result[0] ?? null;\n}\n\nexport async function getEntityMemoryStatsCounts(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tnow: Date,\n): Promise<MemoryStatsCounts> {\n\tconst rows = await db\n\t\t.select(memoryStatsCountFields(now))\n\t\t.from(memoriesTable)\n\t\t.where(eq(memoriesTable.entityId, entityId));\n\treturn rows[0] ?? emptyMemoryStatsCounts();\n}\n\nexport async function getGlobalMemoryStatsCounts(\n\tdb: MnemocyteDatabase,\n\tnow: Date,\n): Promise<GlobalMemoryStatsCounts> {\n\tconst rows = await db\n\t\t.select({\n\t\t\tentityCount: countDistinct(memoriesTable.entityId),\n\t\t\t...memoryStatsCountFields(now),\n\t\t})\n\t\t.from(memoriesTable);\n\treturn rows[0] ?? { entityCount: 0, ...emptyMemoryStatsCounts() };\n}\n\nexport async function deleteMemory(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tmemoryId: string,\n): Promise<GuardedDeleteResult> {\n\treturn deleteMemoriesWithDependentGuard(\n\t\tdb,\n\t\tand(eq(memoriesTable.entityId, entityId), eq(memoriesTable.id, memoryId)),\n\t);\n}\n\nexport async function deleteMemoriesForEntity(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n): Promise<GuardedDeleteResult> {\n\treturn deleteMemoriesWithDependentGuard(\n\t\tdb,\n\t\teq(memoriesTable.entityId, entityId),\n\t);\n}\n\nexport interface PruneFilter {\n\tentityId?: string;\n\texpired?: boolean;\n\tsuperseded?: boolean;\n\tcreatedBefore?: Date;\n\tnotAccessedSince?: Date;\n\ttypes?: readonly MemoryType[];\n\ttags?: readonly string[];\n\tmaxImportanceLevels?: readonly ImportanceLevel[];\n}\n\nfunction pruneConditions(filter: PruneFilter) {\n\treturn and(\n\t\tfilter.entityId !== undefined\n\t\t\t? eq(memoriesTable.entityId, filter.entityId)\n\t\t\t: undefined,\n\t\tfilter.expired\n\t\t\t? and(\n\t\t\t\t\tisNotNull(memoriesTable.expiresAt),\n\t\t\t\t\tsql`${memoriesTable.expiresAt} <= now()`,\n\t\t\t\t)\n\t\t\t: undefined,\n\t\tfilter.superseded ? isNotNull(memoriesTable.supersededBy) : undefined,\n\t\tfilter.createdBefore\n\t\t\t? lt(memoriesTable.createdAt, filter.createdBefore)\n\t\t\t: undefined,\n\t\tfilter.notAccessedSince\n\t\t\t? or(\n\t\t\t\t\tisNull(memoriesTable.lastAccessedAt),\n\t\t\t\t\tlt(memoriesTable.lastAccessedAt, filter.notAccessedSince),\n\t\t\t\t)\n\t\t\t: undefined,\n\t\tfilter.types && filter.types.length > 0\n\t\t\t? inArray(memoriesTable.type, [...filter.types])\n\t\t\t: undefined,\n\t\ttagsContainAll(filter.tags),\n\t\tfilter.maxImportanceLevels && filter.maxImportanceLevels.length > 0\n\t\t\t? inArray(memoriesTable.importance, [...filter.maxImportanceLevels])\n\t\t\t: undefined,\n\t);\n}\n\nexport async function countPruneMatches(\n\tdb: MnemocyteDatabase,\n\tfilter: PruneFilter,\n\tsignal?: AbortSignal,\n): Promise<number> {\n\tconst conditions = pruneConditions(filter);\n\tconst rows = await executeCancelableSql<Array<{ count: number | string }>>(\n\t\tdb,\n\t\tsql`\n\t\t\tSELECT count(*)::int AS count\n\t\t\tFROM ${memoriesTable}\n\t\t\t${conditions ? sql`WHERE ${conditions}` : sql``}\n\t\t`,\n\t\tsignal,\n\t);\n\treturn Number(rows[0]?.count ?? 0);\n}\n\nexport async function pruneMemories(\n\tdb: MnemocyteDatabase,\n\tfilter: PruneFilter,\n\tsignal?: AbortSignal,\n): Promise<GuardedDeleteResult> {\n\tconst conditions = pruneConditions(filter);\n\treturn deleteMemoriesWithDependentGuard(db, conditions, signal);\n}\n\nasync function deleteMemoriesWithDependentGuard(\n\tdb: MnemocyteDatabase,\n\tconditions: SQL | undefined,\n\tsignal?: AbortSignal,\n): Promise<GuardedDeleteResult> {\n\tconst rows = await executeCancelableSql<\n\t\tArray<{\n\t\t\tmatchedCount: number | string;\n\t\t\tdeletedCount: number | string;\n\t\t\thasDependents: boolean;\n\t\t\tentityId: string | null;\n\t\t\tentityDeletedCount: number | string | null;\n\t\t}>\n\t>(\n\t\tdb,\n\t\tsql`\n\t\t\tWITH candidates AS MATERIALIZED (\n\t\t\t\tSELECT id, entity_id\n\t\t\t\tFROM ${memoriesTable}\n\t\t\t\t${conditions ? sql`WHERE ${conditions}` : sql``}\n\t\t\t),\n\t\t\tdependents AS MATERIALIZED (\n\t\t\t\tSELECT 1\n\t\t\t\tFROM ${memoriesTable} AS dependent\n\t\t\t\tINNER JOIN candidates AS target\n\t\t\t\t\tON dependent.superseded_by = target.id\n\t\t\t\tLIMIT 1\n\t\t\t),\n\t\t\tdeleted AS (\n\t\t\t\tDELETE FROM ${memoriesTable}\n\t\t\t\tWHERE ${memoriesTable.id} IN (SELECT id FROM candidates)\n\t\t\t\t\tAND NOT EXISTS (SELECT 1 FROM dependents)\n\t\t\t\tRETURNING id, entity_id\n\t\t\t),\n\t\t\tdeleted_counts AS (\n\t\t\t\tSELECT entity_id, count(*)::int AS deleted_count\n\t\t\t\tFROM deleted\n\t\t\t\tGROUP BY entity_id\n\t\t\t),\n\t\t\tsummary AS (\n\t\t\t\tSELECT\n\t\t\t\t\t(SELECT count(*)::int FROM candidates) AS matched_count,\n\t\t\t\t\t(SELECT count(*)::int FROM deleted) AS deleted_count,\n\t\t\t\t\tEXISTS (SELECT 1 FROM dependents) AS has_dependents\n\t\t\t)\n\t\t\tSELECT\n\t\t\t\tsummary.matched_count AS \"matchedCount\",\n\t\t\t\tsummary.deleted_count AS \"deletedCount\",\n\t\t\t\tsummary.has_dependents AS \"hasDependents\",\n\t\t\t\tdeleted_counts.entity_id AS \"entityId\",\n\t\t\t\tdeleted_counts.deleted_count AS \"entityDeletedCount\"\n\t\t\tFROM summary\n\t\t\tLEFT JOIN deleted_counts ON true\n\t\t\tORDER BY deleted_counts.entity_id\n\t\t`,\n\t\tsignal,\n\t);\n\tconst row = rows[0];\n\treturn {\n\t\tmatchedCount: Number(row?.matchedCount ?? 0),\n\t\tdeletedCount: Number(row?.deletedCount ?? 0),\n\t\thasDependents: row?.hasDependents === true,\n\t\tdeletedByEntity: rows.flatMap((detail) =>\n\t\t\tdetail.entityId === null\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tentityId: detail.entityId,\n\t\t\t\t\t\t\tdeletedCount: Number(detail.entityDeletedCount ?? 0),\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t),\n\t};\n}\n\nexport interface DuplicateSearchInput {\n\tentityId: string;\n\tthreshold: number;\n\tlimit: number;\n\ttypes?: readonly string[];\n\ttags?: readonly string[];\n\tincludeSuperseded?: boolean;\n\tincludeExpired?: boolean;\n}\n\nexport async function findDuplicatePairs(\n\tdb: MnemocyteDatabase,\n\tinput: DuplicateSearchInput,\n\tsignal?: AbortSignal,\n): Promise<Array<{ a: MemoryRow; b: MemoryRow; similarity: number }>> {\n\tconst rows = await executeCancelableSql<Array<Record<string, unknown>>>(\n\t\tdb,\n\t\tsql`\n\t\t\tSELECT\n\t\t\t\ta.id AS \"aId\",\n\t\t\t\ta.entity_id AS \"aEntityId\",\n\t\t\t\ta.content AS \"aContent\",\n\t\t\t\ta.type AS \"aType\",\n\t\t\t\ta.importance AS \"aImportance\",\n\t\t\t\ta.tags AS \"aTags\",\n\t\t\t\ta.source AS \"aSource\",\n\t\t\t\ta.metadata AS \"aMetadata\",\n\t\t\t\ta.confidence AS \"aConfidence\",\n\t\t\t\ta.embedding AS \"aEmbedding\",\n\t\t\t\ta.embedding_model AS \"aEmbeddingModel\",\n\t\t\t\ta.embedding_dimensions AS \"aEmbeddingDimensions\",\n\t\t\t\ta.superseded_by AS \"aSupersededBy\",\n\t\t\t\ta.superseded_at AS \"aSupersededAt\",\n\t\t\t\ta.expires_at AS \"aExpiresAt\",\n\t\t\t\ta.last_accessed_at AS \"aLastAccessedAt\",\n\t\t\t\ta.access_count AS \"aAccessCount\",\n\t\t\t\ta.created_at AS \"aCreatedAt\",\n\t\t\t\ta.updated_at AS \"aUpdatedAt\",\n\t\t\t\tb.id AS \"bId\",\n\t\t\t\tb.entity_id AS \"bEntityId\",\n\t\t\t\tb.content AS \"bContent\",\n\t\t\t\tb.type AS \"bType\",\n\t\t\t\tb.importance AS \"bImportance\",\n\t\t\t\tb.tags AS \"bTags\",\n\t\t\t\tb.source AS \"bSource\",\n\t\t\t\tb.metadata AS \"bMetadata\",\n\t\t\t\tb.confidence AS \"bConfidence\",\n\t\t\t\tb.embedding AS \"bEmbedding\",\n\t\t\t\tb.embedding_model AS \"bEmbeddingModel\",\n\t\t\t\tb.embedding_dimensions AS \"bEmbeddingDimensions\",\n\t\t\t\tb.superseded_by AS \"bSupersededBy\",\n\t\t\t\tb.superseded_at AS \"bSupersededAt\",\n\t\t\t\tb.expires_at AS \"bExpiresAt\",\n\t\t\t\tb.last_accessed_at AS \"bLastAccessedAt\",\n\t\t\t\tb.access_count AS \"bAccessCount\",\n\t\t\t\tb.created_at AS \"bCreatedAt\",\n\t\t\t\tb.updated_at AS \"bUpdatedAt\",\n\t\t\t\t1 - (a.embedding <=> b.embedding) AS \"similarity\"\n\t\t\tFROM mnemocyte_memories a\n\t\t\tJOIN mnemocyte_memories b\n\t\t\t\tON b.entity_id = a.entity_id\n\t\t\t\tAND a.id < b.id\n\t\t\t\tAND a.embedding IS NOT NULL\n\t\t\t\tAND b.embedding IS NOT NULL\n\t\t\tWHERE\n\t\t\t\ta.entity_id = ${input.entityId}\n\t\t\t\t${input.includeSuperseded ? sql`` : sql`AND a.superseded_by IS NULL AND b.superseded_by IS NULL`}\n\t\t\t\t${input.includeExpired ? sql`` : sql`AND (a.expires_at IS NULL OR a.expires_at > now()) AND (b.expires_at IS NULL OR b.expires_at > now())`}\n\t\t\t\t${\n\t\t\t\t\tinput.types && input.types.length > 0\n\t\t\t\t\t\t? sql`AND a.type IN (${sql.join(\n\t\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t\t)}) AND b.type IN (${sql.join(\n\t\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t\t)})`\n\t\t\t\t\t\t: sql``\n\t\t\t\t}\n\t\t\t\t${duplicateTagsFilter(input.tags)}\n\t\t\t\tAND 1 - (a.embedding <=> b.embedding) >= ${input.threshold}\n\t\t\tORDER BY \"similarity\" DESC\n\t\t\tLIMIT ${input.limit}\n\t\t`,\n\t\tsignal,\n\t);\n\treturn rows.map((row) => {\n\t\tconst a = {\n\t\t\tid: row.aId,\n\t\t\tentityId: row.aEntityId,\n\t\t\tcontent: row.aContent,\n\t\t\ttype: row.aType,\n\t\t\timportance: row.aImportance,\n\t\t\ttags: row.aTags,\n\t\t\tsource: row.aSource,\n\t\t\tmetadata: row.aMetadata,\n\t\t\tconfidence: row.aConfidence,\n\t\t\tembedding: row.aEmbedding,\n\t\t\tembeddingModel: row.aEmbeddingModel,\n\t\t\tembeddingDimensions: row.aEmbeddingDimensions,\n\t\t\tsupersededBy: row.aSupersededBy,\n\t\t\tsupersededAt: row.aSupersededAt,\n\t\t\texpiresAt: row.aExpiresAt,\n\t\t\tlastAccessedAt: row.aLastAccessedAt,\n\t\t\taccessCount: row.aAccessCount,\n\t\t\tcreatedAt: row.aCreatedAt,\n\t\t\tupdatedAt: row.aUpdatedAt,\n\t\t} as unknown as MemoryRow;\n\t\tconst b = {\n\t\t\tid: row.bId,\n\t\t\tentityId: row.bEntityId,\n\t\t\tcontent: row.bContent,\n\t\t\ttype: row.bType,\n\t\t\timportance: row.bImportance,\n\t\t\ttags: row.bTags,\n\t\t\tsource: row.bSource,\n\t\t\tmetadata: row.bMetadata,\n\t\t\tconfidence: row.bConfidence,\n\t\t\tembedding: row.bEmbedding,\n\t\t\tembeddingModel: row.bEmbeddingModel,\n\t\t\tembeddingDimensions: row.bEmbeddingDimensions,\n\t\t\tsupersededBy: row.bSupersededBy,\n\t\t\tsupersededAt: row.bSupersededAt,\n\t\t\texpiresAt: row.bExpiresAt,\n\t\t\tlastAccessedAt: row.bLastAccessedAt,\n\t\t\taccessCount: row.bAccessCount,\n\t\t\tcreatedAt: row.bCreatedAt,\n\t\t\tupdatedAt: row.bUpdatedAt,\n\t\t} as unknown as MemoryRow;\n\t\treturn {\n\t\t\ta,\n\t\t\tb,\n\t\t\tsimilarity: Number(row.similarity) || 0,\n\t\t};\n\t});\n}\n\nexport interface SupersedeRow {\n\tid: string;\n\ttags: string[];\n}\n\nexport async function loadConsolidationTargets(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tids: readonly string[],\n): Promise<Array<{ id: string; tags: string[]; supersededBy: string | null }>> {\n\tif (ids.length === 0) {\n\t\treturn [];\n\t}\n\tconst rows = await db\n\t\t.select({\n\t\t\tid: memoriesTable.id,\n\t\t\ttags: memoriesTable.tags,\n\t\t\tsupersededBy: memoriesTable.supersededBy,\n\t\t})\n\t\t.from(memoriesTable)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, entityId),\n\t\t\t\tinArray(memoriesTable.id, [...ids]),\n\t\t\t),\n\t\t);\n\treturn rows;\n}\n\nexport async function lockConsolidationTargets(\n\tdb: MnemocyteDatabase,\n\tentityId: string,\n\tids: readonly string[],\n): Promise<Array<{ id: string; tags: string[]; supersededBy: string | null }>> {\n\tif (ids.length === 0) {\n\t\treturn [];\n\t}\n\treturn db\n\t\t.select({\n\t\t\tid: memoriesTable.id,\n\t\t\ttags: memoriesTable.tags,\n\t\t\tsupersededBy: memoriesTable.supersededBy,\n\t\t})\n\t\t.from(memoriesTable)\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, entityId),\n\t\t\t\tinArray(memoriesTable.id, [...ids]),\n\t\t\t),\n\t\t)\n\t\t.orderBy(memoriesTable.id)\n\t\t.for(\"update\");\n}\n\nexport async function markMemoriesSuperseded(\n\tdb: MnemocyteDatabase,\n\tparams: {\n\t\tsurvivorId: string;\n\t\tentityId: string;\n\t\tids: readonly string[];\n\t\tnow: Date;\n\t},\n): Promise<SupersedeRow[]> {\n\tif (params.ids.length === 0) {\n\t\treturn [];\n\t}\n\tconst result = await db\n\t\t.update(memoriesTable)\n\t\t.set({\n\t\t\tsupersededBy: params.survivorId,\n\t\t\tsupersededAt: params.now,\n\t\t\tupdatedAt: params.now,\n\t\t})\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, params.entityId),\n\t\t\t\tinArray(memoriesTable.id, [...params.ids]),\n\t\t\t\tisNull(memoriesTable.supersededBy),\n\t\t\t),\n\t\t)\n\t\t.returning({ id: memoriesTable.id, tags: memoriesTable.tags });\n\treturn result;\n}\n\nexport async function setMemoryTags(\n\tdb: MnemocyteDatabase,\n\tparams: {\n\t\tentityId: string;\n\t\tmemoryId: string;\n\t\ttags: readonly string[];\n\t\tnow: Date;\n\t},\n): Promise<void> {\n\tawait db\n\t\t.update(memoriesTable)\n\t\t.set({ tags: [...params.tags], updatedAt: params.now })\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(memoriesTable.entityId, params.entityId),\n\t\t\t\teq(memoriesTable.id, params.memoryId),\n\t\t\t),\n\t\t);\n}\n\nexport async function markMemoriesAccessed(\n\tdb: MnemocyteDatabase,\n\tmemoryIds: readonly string[],\n): Promise<\n\tArray<{\n\t\tid: string;\n\t\tlastAccessedAt: Date | null;\n\t\taccessCount: number;\n\t\tupdatedAt: Date;\n\t}>\n> {\n\tconst now = new Date();\n\tif (memoryIds.length === 0) {\n\t\treturn [];\n\t}\n\treturn db\n\t\t.update(memoriesTable)\n\t\t.set({\n\t\t\tlastAccessedAt: now,\n\t\t\taccessCount: sql`${memoriesTable.accessCount} + 1`,\n\t\t\tupdatedAt: now,\n\t\t})\n\t\t.where(inArray(memoriesTable.id, [...memoryIds]))\n\t\t.returning({\n\t\t\tid: memoriesTable.id,\n\t\t\tlastAccessedAt: memoriesTable.lastAccessedAt,\n\t\t\taccessCount: memoriesTable.accessCount,\n\t\t\tupdatedAt: memoriesTable.updatedAt,\n\t\t});\n}\n\nexport async function getMemoryEmbeddings(\n\tdb: MnemocyteDatabase,\n\tmemoryIds: readonly string[],\n): Promise<Map<string, number[]>> {\n\tif (memoryIds.length === 0) {\n\t\treturn new Map();\n\t}\n\tconst rows = await db\n\t\t.select({\n\t\t\tid: memoriesTable.id,\n\t\t\tembedding: memoriesTable.embedding,\n\t\t})\n\t\t.from(memoriesTable)\n\t\t.where(inArray(memoriesTable.id, [...memoryIds]));\n\treturn new Map(\n\t\trows.flatMap((row) => (row.embedding ? [[row.id, row.embedding]] : [])),\n\t);\n}\n\nexport async function vectorSearch(\n\tdb: MnemocyteDatabase,\n\tinput: VectorSearchInput,\n): Promise<VectorSearchRow[]> {\n\tconst embedding = vectorLiteral(input.embedding);\n\tconst vectorScore = clampedVectorScore(embedding);\n\tconst minVectorScore = input.minVectorScore ?? 0;\n\tconst rows = await db.execute(sql`\n\t\tSELECT\n\t\t\tid,\n\t\t\tentity_id AS \"entityId\",\n\t\t\tcontent,\n\t\t\ttype,\n\t\t\timportance,\n\t\t\ttags,\n\t\t\tsource,\n\t\t\tmetadata,\n\t\t\tconfidence,\n\t\t\tembedding_model AS \"embeddingModel\",\n\t\t\tembedding_dimensions AS \"embeddingDimensions\",\n\t\t\tsuperseded_by AS \"supersededBy\",\n\t\t\tsuperseded_at AS \"supersededAt\",\n\t\t\texpires_at AS \"expiresAt\",\n\t\t\tlast_accessed_at AS \"lastAccessedAt\",\n\t\t\taccess_count AS \"accessCount\",\n\t\t\tcreated_at AS \"createdAt\",\n\t\t\tupdated_at AS \"updatedAt\",\n\t\t\t${vectorScore} AS \"vectorScore\"\n\t\tFROM mnemocyte_memories\n\t\tWHERE\n\t\t\tentity_id = ${input.entityId}\n\t\t\tAND embedding IS NOT NULL\n\t\t\t${input.includeSuperseded ? sql`` : sql`AND superseded_by IS NULL`}\n\t\t\t${input.includeExpired ? sql`` : sql`AND (expires_at IS NULL OR expires_at > now())`}\n\t\t\t${\n\t\t\t\tinput.types && input.types.length > 0\n\t\t\t\t\t? sql`AND type IN (${sql.join(\n\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)})`\n\t\t\t\t\t: sql``\n\t\t\t}\n\t\t\t${rawTagsFilter(input.tags)}\n\t\t\t${input.before ? sql`AND created_at < ${timestampParam(input.before)}` : sql``}\n\t\t\t${input.after ? sql`AND created_at > ${timestampParam(input.after)}` : sql``}\n\t\t\tAND ${vectorScore} >= ${minVectorScore}\n\t\tORDER BY embedding <=> ${embedding}::vector\n\t\tLIMIT ${input.limit}\n\t`);\n\treturn rows as unknown as VectorSearchRow[];\n}\n\nexport async function lexicalSearch(\n\tdb: MnemocyteDatabase,\n\tinput: LexicalSearchInput,\n): Promise<LexicalSearchRow[]> {\n\tconst rows = await db.execute(sql`\n\t\tSELECT\n\t\t\tid,\n\t\t\tentity_id AS \"entityId\",\n\t\t\tcontent,\n\t\t\ttype,\n\t\t\timportance,\n\t\t\ttags,\n\t\t\tsource,\n\t\t\tmetadata,\n\t\t\tconfidence,\n\t\t\tembedding_model AS \"embeddingModel\",\n\t\t\tembedding_dimensions AS \"embeddingDimensions\",\n\t\t\tsuperseded_by AS \"supersededBy\",\n\t\t\tsuperseded_at AS \"supersededAt\",\n\t\t\texpires_at AS \"expiresAt\",\n\t\t\tlast_accessed_at AS \"lastAccessedAt\",\n\t\t\taccess_count AS \"accessCount\",\n\t\t\tcreated_at AS \"createdAt\",\n\t\t\tupdated_at AS \"updatedAt\",\n\t\t\tts_rank(to_tsvector('english', content), websearch_to_tsquery('english', ${input.query})) AS \"lexicalScore\"\n\t\tFROM mnemocyte_memories\n\t\tWHERE\n\t\t\tentity_id = ${input.entityId}\n\t\t\t${input.includeSuperseded ? sql`` : sql`AND superseded_by IS NULL`}\n\t\t\t${input.includeExpired ? sql`` : sql`AND (expires_at IS NULL OR expires_at > now())`}\n\t\t\t${\n\t\t\t\tinput.types && input.types.length > 0\n\t\t\t\t\t? sql`AND type IN (${sql.join(\n\t\t\t\t\t\t\tinput.types.map((type) => sql`${type}`),\n\t\t\t\t\t\t\tsql`, `,\n\t\t\t\t\t\t)})`\n\t\t\t\t\t: sql``\n\t\t\t}\n\t\t\t${rawTagsFilter(input.tags)}\n\t\t\t${input.before ? sql`AND created_at < ${timestampParam(input.before)}` : sql``}\n\t\t\t${input.after ? sql`AND created_at > ${timestampParam(input.after)}` : sql``}\n\t\t\tAND to_tsvector('english', content) @@ websearch_to_tsquery('english', ${input.query})\n\t\tORDER BY \"lexicalScore\" DESC\n\t\tLIMIT ${input.limit}\n\t`);\n\treturn rows as unknown as LexicalSearchRow[];\n}\n","import { and, eq, isNull } from \"drizzle-orm\";\nimport type { MnemocyteDatabase } from \"../index.js\";\nimport { type MetaRow, memoriesTable, metaTable } from \"../schema.js\";\n\nexport const INSTALLATION_META_KEY = \"installation\";\n\nexport async function getInstallationMeta(\n\tdb: MnemocyteDatabase,\n): Promise<MetaRow | null> {\n\tconst rows = await db\n\t\t.select()\n\t\t.from(metaTable)\n\t\t.where(eq(metaTable.key, INSTALLATION_META_KEY))\n\t\t.limit(1);\n\treturn rows[0] ?? null;\n}\n\nexport async function getStoredEmbeddingModels(\n\tdb: MnemocyteDatabase,\n): Promise<string[]> {\n\tconst rows = await db\n\t\t.selectDistinct({ embeddingModel: memoriesTable.embeddingModel })\n\t\t.from(memoriesTable)\n\t\t.limit(2);\n\treturn rows.map((row) => row.embeddingModel);\n}\n\nexport async function recordInstallationEmbeddingModel(\n\tdb: MnemocyteDatabase,\n\tembeddingModel: string,\n): Promise<MetaRow | null> {\n\tconst rows = await db\n\t\t.update(metaTable)\n\t\t.set({ embeddingModel })\n\t\t.where(\n\t\t\tand(\n\t\t\t\teq(metaTable.key, INSTALLATION_META_KEY),\n\t\t\t\tisNull(metaTable.embeddingModel),\n\t\t\t),\n\t\t)\n\t\t.returning();\n\treturn rows[0] ?? null;\n}\n","import type { MemoryRow } from \"../db/schema.js\";\nimport type { ImportanceLevel, Memory, MemoryType } from \"../types.js\";\nimport { cloneJsonObject } from \"./json.js\";\n\ntype MemoryRowTimestamp = Date | string;\n\ntype MemoryLikeRow = Omit<\n\tMemoryRow,\n\t| \"embedding\"\n\t| \"supersededAt\"\n\t| \"expiresAt\"\n\t| \"lastAccessedAt\"\n\t| \"createdAt\"\n\t| \"updatedAt\"\n> & {\n\tsupersededAt: MemoryRowTimestamp | null;\n\texpiresAt: MemoryRowTimestamp | null;\n\tlastAccessedAt: MemoryRowTimestamp | null;\n\tcreatedAt: MemoryRowTimestamp;\n\tupdatedAt: MemoryRowTimestamp;\n};\n\nfunction toDate(value: MemoryRowTimestamp): Date {\n\treturn value instanceof Date ? value : new Date(value);\n}\n\nfunction toNullableDate(value: MemoryRowTimestamp | null): Date | null {\n\treturn value === null ? null : toDate(value);\n}\n\nexport function rowToMemory(row: MemoryLikeRow): Memory {\n\treturn {\n\t\tid: row.id,\n\t\tentityId: row.entityId,\n\t\tcontent: row.content,\n\t\ttype: row.type as MemoryType,\n\t\timportance: row.importance as ImportanceLevel,\n\t\ttags: row.tags,\n\t\tsource: row.source,\n\t\tmetadata: cloneJsonObject(row.metadata),\n\t\tconfidence: row.confidence,\n\t\tembeddingModel: row.embeddingModel,\n\t\tembeddingDimensions: row.embeddingDimensions,\n\t\tsupersededBy: row.supersededBy,\n\t\tsupersededAt: toNullableDate(row.supersededAt),\n\t\texpiresAt: toNullableDate(row.expiresAt),\n\t\tlastAccessedAt: toNullableDate(row.lastAccessedAt),\n\t\taccessCount: row.accessCount,\n\t\tcreatedAt: toDate(row.createdAt),\n\t\tupdatedAt: toDate(row.updatedAt),\n\t};\n}\n","import type { DatabaseHandle } from \"../db/index.js\";\nimport { insertEvent, listEvents } from \"../db/queries/events.js\";\nimport {\n\tcountPruneMatches,\n\tdeleteMemoriesForEntity as deleteMemoriesForEntityQuery,\n\tdeleteMemory as deleteMemoryQuery,\n\tfindDuplicatePairs as findDuplicatePairsQuery,\n\tgetEntityMemoryStatsCounts,\n\tgetGlobalMemoryStatsCounts,\n\tgetMemoryById,\n\tgetMemoryEmbeddings as getMemoryEmbeddingsQuery,\n\tinsertMemories as insertMemoryRows,\n\tlexicalSearch as lexicalSearchQuery,\n\tloadConsolidationTargets,\n\tlockConsolidationTargets,\n\tmarkMemoriesAccessed,\n\tmarkMemoriesSuperseded,\n\ttype PruneFilter,\n\tpruneMemories,\n\tsetMemoryTags,\n\tvectorSearch as vectorSearchQuery,\n} from \"../db/queries/memories.js\";\nimport {\n\tgetInstallationMeta,\n\tgetStoredEmbeddingModels,\n\trecordInstallationEmbeddingModel,\n} from \"../db/queries/meta.js\";\nimport type { EventRow, NewMemoryRow } from \"../db/schema.js\";\nimport { MnemocyteError } from \"../errors.js\";\nimport { throwIfAborted } from \"../resilience.js\";\nimport type {\n\tAuditEvent,\n\tEmbedder,\n\tEntityStats,\n\tGlobalStats,\n\tImportanceLevel,\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\tIMPORTANCE_RANK,\n} from \"./defaults.js\";\nimport { memoryHasDependentsError } from \"./deletion.js\";\nimport { cloneJsonObject } from \"./json.js\";\nimport { rowToMemory } from \"./postgres-records.js\";\nimport { createEventId, type StoredMemory } from \"./records.js\";\nimport {\n\tassertPruneFilterHasSelector,\n\ttype MemoryStore,\n\ttype StoreConsolidateInput,\n\ttype StoreConsolidateResult,\n\ttype StoreDuplicatePair,\n\ttype StoreLexicalCandidate,\n\ttype StoreLexicalSearchInput,\n\ttype StoreVectorCandidate,\n\ttype StoreVectorSearchInput,\n\ttype ValidatedPruneFilter,\n} from \"./store.js\";\n\nconst IMPORTANCE_LEVELS: readonly ImportanceLevel[] = [\n\t\"low\",\n\t\"normal\",\n\t\"high\",\n\t\"critical\",\n];\n\nconst MIGRATION_ERROR_CODES = new Set([\"42P01\", \"42703\", \"42704\", \"42883\"]);\nconst CONSOLIDATION_SURVIVOR_FOREIGN_KEY =\n\t\"mnemocyte_memories_superseded_by_mnemocyte_memories_id_fk\";\n\nfunction rowToAuditEvent(row: EventRow): AuditEvent {\n\treturn {\n\t\tid: row.id,\n\t\tentityId: row.entityId,\n\t\tdescription: row.description,\n\t\tmetadata: cloneJsonObject(row.metadata),\n\t\ttimestamp: new Date(row.timestamp),\n\t};\n}\n\nfunction importanceCeilingLevels(\n\tmax: ImportanceLevel,\n): readonly ImportanceLevel[] {\n\treturn IMPORTANCE_LEVELS.filter(\n\t\t(level) => IMPORTANCE_RANK[level] <= IMPORTANCE_RANK[max],\n\t);\n}\n\nfunction hasPostgresErrorCode(error: unknown, code: string): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\terror.code === code\n\t);\n}\n\nfunction hasPostgresConstraintName(error: unknown, name: string): boolean {\n\treturn (\n\t\ttypeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"constraint_name\" in error &&\n\t\terror.constraint_name === name\n\t);\n}\n\nfunction getPostgresErrorCode(error: unknown): string | undefined {\n\treturn typeof error === \"object\" &&\n\t\terror !== null &&\n\t\t\"code\" in error &&\n\t\ttypeof (error as { code?: unknown }).code === \"string\"\n\t\t? (error as { code: string }).code\n\t\t: undefined;\n}\n\nfunction normalizePostgresError(error: unknown): MnemocyteError {\n\tif (error instanceof MnemocyteError) {\n\t\treturn error;\n\t}\n\tconst code = getPostgresErrorCode(error);\n\tif (code && MIGRATION_ERROR_CODES.has(code)) {\n\t\treturn new MnemocyteError(\n\t\t\t\"Postgres schema is missing or incompatible. Apply the bundled Mnemocyte migrations before using the Postgres backend.\",\n\t\t\t\"MIGRATION\",\n\t\t\terror,\n\t\t);\n\t}\n\treturn new MnemocyteError(\"Postgres operation failed.\", \"DB\", error);\n}\n\nasync function runPostgresOperation<T>(\n\toperation: () => Promise<T>,\n): Promise<T> {\n\ttry {\n\t\treturn await operation();\n\t} catch (error) {\n\t\tthrow normalizePostgresError(error);\n\t}\n}\n\nasync function runPostgresDeleteOperation<T>(\n\toperation: () => Promise<T>,\n): Promise<T> {\n\ttry {\n\t\treturn await operation();\n\t} catch (error) {\n\t\tif (error instanceof MnemocyteError) {\n\t\t\tthrow error;\n\t\t}\n\t\tif (\n\t\t\thasPostgresErrorCode(error, \"23503\") &&\n\t\t\thasPostgresConstraintName(error, CONSOLIDATION_SURVIVOR_FOREIGN_KEY)\n\t\t) {\n\t\t\tthrow memoryHasDependentsError(error);\n\t\t}\n\t\tthrow normalizePostgresError(error);\n\t}\n}\n\nfunction toPruneFilter(input: ValidatedPruneFilter): PruneFilter {\n\tconst filter: PruneFilter = {};\n\tif (input.entityId !== undefined) {\n\t\tfilter.entityId = input.entityId;\n\t}\n\tif (input.expired === true) {\n\t\tfilter.expired = true;\n\t}\n\tif (input.superseded === true) {\n\t\tfilter.superseded = true;\n\t}\n\tif (input.createdBefore !== undefined) {\n\t\tfilter.createdBefore = input.createdBefore;\n\t}\n\tif (input.notAccessedSince !== undefined) {\n\t\tfilter.notAccessedSince = input.notAccessedSince;\n\t}\n\tif (input.types !== undefined && input.types.length > 0) {\n\t\tfilter.types = input.types;\n\t}\n\tif (input.tags !== undefined && input.tags.length > 0) {\n\t\tfilter.tags = input.tags;\n\t}\n\tif (input.maxImportance !== undefined) {\n\t\tfilter.maxImportanceLevels = importanceCeilingLevels(input.maxImportance);\n\t}\n\treturn filter;\n}\n\nfunction toMemoryRow(memory: StoredMemory): NewMemoryRow {\n\treturn {\n\t\t...memory,\n\t\ttags: [...memory.tags],\n\t\tembedding: [...memory.embedding],\n\t};\n}\n\nexport function createPostgresStore(handle: DatabaseHandle): MemoryStore {\n\tlet schemaValidated = false;\n\tlet schemaValidationPromise: Promise<void> | undefined;\n\n\tasync function ensureEmbeddingCompatibility(\n\t\tembedder: Embedder,\n\t): Promise<void> {\n\t\tif (schemaValidated) {\n\t\t\treturn;\n\t\t}\n\t\tif (!schemaValidationPromise) {\n\t\t\tschemaValidationPromise = validateEmbeddingCompatibility(embedder).catch(\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tschemaValidationPromise = undefined;\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tawait schemaValidationPromise;\n\t}\n\n\tasync function validateEmbeddingCompatibility(\n\t\tembedder: Embedder,\n\t): Promise<void> {\n\t\tlet meta: Awaited<ReturnType<typeof getInstallationMeta>>;\n\t\ttry {\n\t\t\tmeta = await getInstallationMeta(handle.db);\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\thasPostgresErrorCode(error, \"42P01\") ||\n\t\t\t\thasPostgresErrorCode(error, \"42703\")\n\t\t\t) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"Postgres embedding metadata is missing or outdated. Apply the bundled migrations through 0002_add_embedding_model.sql, or render a fresh dimension-specific initial migration, before using embedding-dependent operations.\",\n\t\t\t\t\t\"MIGRATION\",\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow normalizePostgresError(error);\n\t\t}\n\t\tif (!meta) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t'mnemocyte_meta is missing the \"installation\" row. Apply the bundled migrations, or render a fresh dimension-specific initial migration, before using embedding-dependent operations.',\n\t\t\t\t\"MIGRATION\",\n\t\t\t);\n\t\t}\n\t\tif (meta.embeddingDimensions !== embedder.dimensions) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`embedder.dimensions (${embedder.dimensions}) must match mnemocyte_meta.embedding_dimensions (${meta.embeddingDimensions}). Render and apply a migration for the selected embedding dimension, or configure an embedder that matches this installation.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t\tlet installationModel = meta.embeddingModel;\n\t\tif (installationModel === null) {\n\t\t\ttry {\n\t\t\t\tconst storedModels = await getStoredEmbeddingModels(handle.db);\n\t\t\t\tif (storedModels.length > 1) {\n\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\"mnemocyte_meta.embedding_model is unset, but stored memories contain multiple embedding_model values. Re-embed or remove the mixed historical rows, then explicitly record the installation model before using embedding-dependent operations.\",\n\t\t\t\t\t\t\"MIGRATION\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst inferredModel = storedModels[0] ?? embedder.model;\n\t\t\t\tconst recorded = await recordInstallationEmbeddingModel(\n\t\t\t\t\thandle.db,\n\t\t\t\t\tinferredModel,\n\t\t\t\t);\n\t\t\t\tif (recorded) {\n\t\t\t\t\tinstallationModel = recorded.embeddingModel;\n\t\t\t\t} else {\n\t\t\t\t\tconst concurrentlyRecorded = await getInstallationMeta(handle.db);\n\t\t\t\t\tinstallationModel = concurrentlyRecorded?.embeddingModel ?? null;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tthrow normalizePostgresError(error);\n\t\t\t}\n\t\t\tif (installationModel === null) {\n\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\"mnemocyte_meta.embedding_model could not be recorded. Verify the installation metadata row and retry.\",\n\t\t\t\t\t\"MIGRATION\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (installationModel !== embedder.model) {\n\t\t\tthrow new MnemocyteError(\n\t\t\t\t`embedder.model (\"${embedder.model}\") must match mnemocyte_meta.embedding_model (\"${installationModel}\"). Configure the recorded model, or explicitly re-embed existing memories and update the installation metadata.`,\n\t\t\t\t\"CONFIG\",\n\t\t\t);\n\t\t}\n\t\tschemaValidated = true;\n\t}\n\n\treturn {\n\t\tbackend: \"postgres\",\n\t\tasync ensureSchema() {},\n\t\tensureEmbeddingCompatibility,\n\t\tasync insertMemories(memories) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await insertMemoryRows(\n\t\t\t\t\thandle.db,\n\t\t\t\t\tmemories.map(toMemoryRow),\n\t\t\t\t);\n\t\t\t\treturn rows.map(rowToMemory);\n\t\t\t});\n\t\t},\n\t\tasync vectorSearch(input: StoreVectorSearchInput) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await vectorSearchQuery(handle.db, input);\n\t\t\t\treturn rows.map(\n\t\t\t\t\t(row) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\tmemory: rowToMemory(row),\n\t\t\t\t\t\t\tvectorScore: row.vectorScore,\n\t\t\t\t\t\t}) satisfies StoreVectorCandidate,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tasync lexicalSearch(input: StoreLexicalSearchInput) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await lexicalSearchQuery(handle.db, input);\n\t\t\t\treturn rows.map(\n\t\t\t\t\t(row) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\tmemory: rowToMemory(row),\n\t\t\t\t\t\t\tlexicalScore: row.lexicalScore,\n\t\t\t\t\t\t}) satisfies StoreLexicalCandidate,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tasync getMemoryEmbeddings(memoryIds) {\n\t\t\treturn runPostgresOperation(() =>\n\t\t\t\tgetMemoryEmbeddingsQuery(handle.db, memoryIds),\n\t\t\t);\n\t\t},\n\t\tasync markMemoriesAccessed(memoryIds) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await markMemoriesAccessed(handle.db, memoryIds);\n\t\t\t\treturn rows.map((row) => {\n\t\t\t\t\tif (row.lastAccessedAt === null) {\n\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\"Postgres access update returned no timestamp.\",\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...row,\n\t\t\t\t\t\tlastAccessedAt: row.lastAccessedAt,\n\t\t\t\t\t};\n\t\t\t\t});\n\t\t\t});\n\t\t},\n\t\tasync deleteMemory(entityId, memoryId) {\n\t\t\treturn runPostgresDeleteOperation(async () => {\n\t\t\t\tconst result = await deleteMemoryQuery(handle.db, entityId, memoryId);\n\t\t\t\tif (result.hasDependents) {\n\t\t\t\t\tthrow memoryHasDependentsError();\n\t\t\t\t}\n\t\t\t\treturn result.deletedCount > 0;\n\t\t\t});\n\t\t},\n\t\tasync deleteMemoriesForEntity(entityId) {\n\t\t\treturn runPostgresDeleteOperation(async () => {\n\t\t\t\tconst result = await deleteMemoriesForEntityQuery(handle.db, entityId);\n\t\t\t\tif (result.hasDependents) {\n\t\t\t\t\tthrow memoryHasDependentsError();\n\t\t\t\t}\n\t\t\t\treturn result.deletedCount;\n\t\t\t});\n\t\t},\n\t\tasync prune(input, options) {\n\t\t\treturn runPostgresDeleteOperation(async () => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tassertPruneFilterHasSelector(input);\n\t\t\t\tconst filter = toPruneFilter(input);\n\t\t\t\tconst dryRun = input.dryRun === true;\n\t\t\t\tif (dryRun) {\n\t\t\t\t\treturn {\n\t\t\t\t\t\tmatchedCount: await countPruneMatches(\n\t\t\t\t\t\t\thandle.db,\n\t\t\t\t\t\t\tfilter,\n\t\t\t\t\t\t\toptions?.signal,\n\t\t\t\t\t\t),\n\t\t\t\t\t\tdeletedCount: 0,\n\t\t\t\t\t\tdryRun: true,\n\t\t\t\t\t\tdeletedByEntity: [],\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst result = await pruneMemories(handle.db, filter, options?.signal);\n\t\t\t\tif (result.hasDependents) {\n\t\t\t\t\tthrow memoryHasDependentsError();\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tmatchedCount: result.matchedCount,\n\t\t\t\t\tdeletedCount: result.deletedCount,\n\t\t\t\t\tdryRun: false,\n\t\t\t\t\tdeletedByEntity: result.deletedByEntity,\n\t\t\t\t};\n\t\t\t});\n\t\t},\n\t\tasync findDuplicatePairs(input, options) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await findDuplicatePairsQuery(\n\t\t\t\t\thandle.db,\n\t\t\t\t\t{\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\tthreshold: input.threshold ?? DEFAULT_DUPLICATE_THRESHOLD,\n\t\t\t\t\t\tlimit: input.limit ?? DEFAULT_DUPLICATE_LIMIT,\n\t\t\t\t\t\t...(input.types === undefined ? {} : { types: input.types }),\n\t\t\t\t\t\t...(input.tags === undefined ? {} : { tags: input.tags }),\n\t\t\t\t\t\t...(input.includeSuperseded === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { includeSuperseded: input.includeSuperseded }),\n\t\t\t\t\t\t...(input.includeExpired === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { includeExpired: input.includeExpired }),\n\t\t\t\t\t},\n\t\t\t\t\toptions?.signal,\n\t\t\t\t);\n\t\t\t\treturn rows.map(\n\t\t\t\t\t(row) =>\n\t\t\t\t\t\t({\n\t\t\t\t\t\t\ta: rowToMemory(row.a),\n\t\t\t\t\t\t\tb: rowToMemory(row.b),\n\t\t\t\t\t\t\tsimilarity: Math.max(0, Math.min(1, row.similarity)),\n\t\t\t\t\t\t}) satisfies StoreDuplicatePair,\n\t\t\t\t);\n\t\t\t});\n\t\t},\n\t\tasync addAuditEvents(events) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tfor (const event of events) {\n\t\t\t\t\tawait insertEvent(handle.db, {\n\t\t\t\t\t\tid: event.id,\n\t\t\t\t\t\tentityId: event.entityId,\n\t\t\t\t\t\tdescription: event.description,\n\t\t\t\t\t\tmetadata: cloneJsonObject(event.metadata),\n\t\t\t\t\t\ttimestamp: event.timestamp,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tasync listAuditLog(input, options) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tconst rows = await listEvents(\n\t\t\t\t\thandle.db,\n\t\t\t\t\t{\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\tlimit: input.limit ?? DEFAULT_AUDIT_LOG_LIMIT,\n\t\t\t\t\t\t...(input.before === undefined ? {} : { before: input.before }),\n\t\t\t\t\t\t...(input.after === undefined ? {} : { after: input.after }),\n\t\t\t\t\t\t...(input.beforeCursor === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { beforeCursor: input.beforeCursor }),\n\t\t\t\t\t\t...(input.afterCursor === undefined\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: { afterCursor: input.afterCursor }),\n\t\t\t\t\t},\n\t\t\t\t\toptions?.signal,\n\t\t\t\t);\n\t\t\t\treturn rows.map(rowToAuditEvent);\n\t\t\t});\n\t\t},\n\t\tasync getMemory(entityId, memoryId, options) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst row = await getMemoryById(handle.db, entityId, memoryId);\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\treturn row ? rowToMemory(row) : null;\n\t\t\t});\n\t\t},\n\t\tasync loadConsolidationTargets(entityId, ids, options) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst targets = await loadConsolidationTargets(\n\t\t\t\t\thandle.db,\n\t\t\t\t\tentityId,\n\t\t\t\t\tids,\n\t\t\t\t);\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\treturn targets;\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\treturn runPostgresOperation(async () => {\n\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\tconst newSupersededIds = await handle.db.transaction(async (tx) => {\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tconst targets = await lockConsolidationTargets(\n\t\t\t\t\t\ttx,\n\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\tinput.supersededIds,\n\t\t\t\t\t);\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tif (\n\t\t\t\t\t\ttargets.some(\n\t\t\t\t\t\t\t(target) =>\n\t\t\t\t\t\t\t\ttarget.supersededBy !== null &&\n\t\t\t\t\t\t\t\ttarget.supersededBy !== input.survivorId,\n\t\t\t\t\t\t)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow new MnemocyteError(\n\t\t\t\t\t\t\t\"Superseded memory already belongs to a different survivor.\",\n\t\t\t\t\t\t\t\"CONFLICT\",\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tconst activeIds = targets\n\t\t\t\t\t\t.filter((target) => target.supersededBy === null)\n\t\t\t\t\t\t.map((target) => target.id);\n\t\t\t\t\tconst updated = await markMemoriesSuperseded(tx, {\n\t\t\t\t\t\tsurvivorId: input.survivorId,\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\tids: activeIds,\n\t\t\t\t\t\tnow: input.now,\n\t\t\t\t\t});\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\tconst ids = updated.map((row) => row.id);\n\t\t\t\t\tif (input.auditEnabled) {\n\t\t\t\t\t\tfor (const id of ids) {\n\t\t\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\t\t\tawait insertEvent(tx, {\n\t\t\t\t\t\t\t\tid: createEventId(),\n\t\t\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t\t\tdescription: \"memory.superseded\",\n\t\t\t\t\t\t\t\tmetadata: { memoryId: id, supersededBy: input.survivorId },\n\t\t\t\t\t\t\t\ttimestamp: input.now,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif (input.mergeTags && updated.length > 0) {\n\t\t\t\t\t\tconst mergedTags = new Set(input.survivorTags);\n\t\t\t\t\t\tfor (const row of updated) {\n\t\t\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\t\t\tfor (const tag of row.tags) {\n\t\t\t\t\t\t\t\tmergedTags.add(tag);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (mergedTags.size !== input.survivorTags.length) {\n\t\t\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\t\t\tawait setMemoryTags(tx, {\n\t\t\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t\t\tmemoryId: input.survivorId,\n\t\t\t\t\t\t\t\ttags: [...mergedTags],\n\t\t\t\t\t\t\t\tnow: input.now,\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tthrowIfAborted(options?.signal);\n\t\t\t\t\treturn ids;\n\t\t\t\t});\n\t\t\t\treturn { supersededIds: newSupersededIds };\n\t\t\t});\n\t\t},\n\t\tasync stats(input, now) {\n\t\t\treturn runPostgresOperation(async () => {\n\t\t\t\tif (input?.entityId) {\n\t\t\t\t\tconst counts = await getEntityMemoryStatsCounts(\n\t\t\t\t\t\thandle.db,\n\t\t\t\t\t\tinput.entityId,\n\t\t\t\t\t\tnow,\n\t\t\t\t\t);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tentityId: input.entityId,\n\t\t\t\t\t\t...counts,\n\t\t\t\t\t} satisfies EntityStats;\n\t\t\t\t}\n\t\t\t\treturn (await getGlobalMemoryStatsCounts(\n\t\t\t\t\thandle.db,\n\t\t\t\t\tnow,\n\t\t\t\t)) satisfies GlobalStats;\n\t\t\t});\n\t\t},\n\t\tasync close() {\n\t\t\treturn runPostgresOperation(() => handle.close());\n\t\t},\n\t};\n}\n\nexport function createPostgresClient(\n\tconfig: MnemocyteConfig,\n\thandle: DatabaseHandle,\n): MnemocyteClient {\n\treturn createMemoryClient(config, createPostgresStore(handle));\n}\n","import { createDatabase } from \"./db/index.js\";\nimport { createInMemoryClient } from \"./memory/in-memory.js\";\nimport { createPostgresClient } from \"./memory/postgres.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.databaseUrl} is provided, a Postgres-backed\n * client is returned (requires the `pgvector` extension and the bundled\n * migration applied). Otherwise an in-memory client is returned, intended\n * for tests, demos, and short-lived processes.\n *\n * The returned client owns any underlying resources (e.g. the Postgres\n * connection pool). Call {@link MnemocyteClient.close} when finished to\n * release them.\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 `\"VALIDATION\"` if\n * `databaseUrl` is explicitly 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) {\n\t\tassertNonEmptyString(config.databaseUrl, \"databaseUrl\");\n\t\treturn createPostgresClient(config, createDatabase(config.databaseUrl));\n\t}\n\treturn createInMemoryClient(config);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,SAAgB,sBAAsB,OAAuB;CAC5D,IAAI,CAAC,OAAO,SAAS,KAAK,GACzB,MAAM,IAAI,MAAM,uCAAuC;CAExD,OAAO,OAAO,GAAG,OAAO,EAAE,IAAI,MAAM,MAAM,SAAS;AACpD;;;;;;;;ACUA,MAAM,SAAS,WAIZ;CACF,SAAS,QAAQ;EAEhB,OAAO,UADY,QAAQ,cAAc,KACb;CAC7B;C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AO,SAAS,MAAM;CACjE;AACD;AAEA,eAAe,gBACd,QACA,OACgB;CAChB,IAAI;EACH,MAAM,OAAO,eAAe,UAAU,KAAK;CAC5C,QAAQ;EACP;CACD;AACD;AAEA,eAAe,qBACd,QACA,SACA,WACA,UACA,WACA,QACA,iBACa;CACb,MAAM,gBACL,QACA,aACC;EACC;EACA,OAAO;EACP;EACA,WAAW,IAAI,KAAK,SAAS;CAC9B,GACA,QACD,CACD;CACA,IAAI;EACH,MAAM,SAAS,MAAM,OAAO;EAC5B,MAAM,gBACL,QACA,aACC;GACC;GACA,OAAO;GACP;GACA,2BAAW,IAAI,KAAK;GACpB,YAAY,KAAK,IAAI,IAAI;EAC1B,GACA;GAAE,GAAG;GAAU,GAAG,kBAAkB,MAAM;EAAE,CAC7C,CACD;EACA,OAAO;CACR,SAAS,OAAO;EACf,MAAM,gBACL,QACA,aACC;GACC;GACA,OAAO;GACP;GACA,2BAAW,IAAI,KAAK;GACpB,YAAY,KAAK,IAAI,IAAI;GACzB;EACD,GACA,QACD,CACD;EACA,MAAM;CACP;AACD;AAEA,SAAgB,QACf,QACA,SACA,WACA,UACA,QACA,iBACa;CACb,OAAO,qBACN,QACA,SACA,WACA,UACA,KAAK,IAAI,GACT,QACA,eACD;AACD;AAEA,SAAgB,gBACf,QACA,SACA,WACA,UACA,SACA,QACA,iBACkB;CAClB,MAAM,YAAY,KAAK,IAAI;CAC3B,IAAI;EACH,MAAM,WAAW,QAAQ;EACzB,OAAO,qBACN,QACA,SACA,WACA,UACA,iBACM,OAAO,QAAQ,GACrB,eACD;CACD,SAAS,OAAO;EACf,OAAO,qBACN,QACA,SACA,WACA,UACA,WACA,YAAY;GACX,MAAM;EACP,CACD;CACD;AACD;;;;;;AChIA,MAAa,kBAAmD;CAC/D,KAAK;CACL,QAAQ;CACR,MAAM;CACN,UAAU;AACX;;;ACjBA,SAAS,kBACR,WACA,YACO;CACP,IAAI,UAAU,WAAW,YACxB,MAAM,IAAI,eACT,8DACA,WACD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