@usewhisper/mcp-server 0.1.0 → 0.3.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.
Files changed (70) hide show
  1. package/README.md +26 -24
  2. package/dist/autosubscribe-6EDKPBE2.js +4068 -0
  3. package/dist/autosubscribe-GHO6YR5A.js +4068 -0
  4. package/dist/autosubscribe-ISDETQIB.js +436 -0
  5. package/dist/autosubscribe-ISDETQIB.js.map +1 -0
  6. package/dist/chunk-3WGYBAYR.js +8387 -0
  7. package/dist/chunk-52VJYCZ7.js +455 -0
  8. package/dist/chunk-5KBZQHDL.js +189 -0
  9. package/dist/chunk-5KIJNY6Z.js +370 -0
  10. package/dist/chunk-7SN3CKDK.js +1076 -0
  11. package/dist/chunk-B3VWOHUA.js +271 -0
  12. package/dist/chunk-C57DHKTL.js +459 -0
  13. package/dist/chunk-EI5CE3EY.js +616 -0
  14. package/dist/chunk-FTWUJBAH.js +387 -0
  15. package/dist/chunk-FTWUJBAH.js.map +1 -0
  16. package/dist/chunk-H3HSKH2P.js +4841 -0
  17. package/dist/chunk-JO3ORBZD.js +616 -0
  18. package/dist/chunk-L6DXSM2U.js +457 -0
  19. package/dist/chunk-L6DXSM2U.js.map +1 -0
  20. package/dist/chunk-LMEYV4JD.js +368 -0
  21. package/dist/chunk-MEFLJ4PV.js +8385 -0
  22. package/dist/chunk-OBLI4FE4.js +276 -0
  23. package/dist/chunk-OBLI4FE4.js.map +1 -0
  24. package/dist/chunk-PPGYJJED.js +271 -0
  25. package/dist/chunk-QGM4M3NI.js +37 -0
  26. package/dist/chunk-T7KMSTWP.js +399 -0
  27. package/dist/chunk-TWEIYHI6.js +399 -0
  28. package/dist/chunk-UYWE7HSU.js +369 -0
  29. package/dist/chunk-UYWE7HSU.js.map +1 -0
  30. package/dist/chunk-X2DL2GWT.js +33 -0
  31. package/dist/chunk-X2DL2GWT.js.map +1 -0
  32. package/dist/chunk-X7HNNNJJ.js +1079 -0
  33. package/dist/consolidation-2GCKI4RE.js +220 -0
  34. package/dist/consolidation-4JOPW6BG.js +220 -0
  35. package/dist/consolidation-FOVQTWNQ.js +222 -0
  36. package/dist/consolidation-IFQ52E44.js +210 -0
  37. package/dist/consolidation-IFQ52E44.js.map +1 -0
  38. package/dist/context-sharing-4ITCNKG4.js +307 -0
  39. package/dist/context-sharing-6CCFIAKL.js +276 -0
  40. package/dist/context-sharing-6CCFIAKL.js.map +1 -0
  41. package/dist/context-sharing-GYKLXHZA.js +307 -0
  42. package/dist/context-sharing-PH64JTXS.js +308 -0
  43. package/dist/context-sharing-Y6LTZZOF.js +307 -0
  44. package/dist/cost-optimization-6OIKRSBV.js +196 -0
  45. package/dist/cost-optimization-6OIKRSBV.js.map +1 -0
  46. package/dist/cost-optimization-7DVSTL6R.js +307 -0
  47. package/dist/cost-optimization-BH5NAX33.js +287 -0
  48. package/dist/cost-optimization-BH5NAX33.js.map +1 -0
  49. package/dist/cost-optimization-F3L5BS5F.js +303 -0
  50. package/dist/ingest-2LPTWUUM.js +16 -0
  51. package/dist/ingest-7T5FAZNC.js +15 -0
  52. package/dist/ingest-EBNIE7XB.js +15 -0
  53. package/dist/ingest-FSHT5BCS.js +15 -0
  54. package/dist/ingest-QE2BTV72.js +15 -0
  55. package/dist/ingest-QE2BTV72.js.map +1 -0
  56. package/dist/oracle-3RLQF3DP.js +259 -0
  57. package/dist/oracle-FKRTQUUG.js +282 -0
  58. package/dist/oracle-J47QCSEW.js +263 -0
  59. package/dist/oracle-MDP5MZRC.js +257 -0
  60. package/dist/oracle-MDP5MZRC.js.map +1 -0
  61. package/dist/search-BLVHWLWC.js +14 -0
  62. package/dist/search-CZ5NYL5B.js +13 -0
  63. package/dist/search-CZ5NYL5B.js.map +1 -0
  64. package/dist/search-EG6TYWWW.js +13 -0
  65. package/dist/search-I22QQA7T.js +13 -0
  66. package/dist/search-T7H5G6DW.js +13 -0
  67. package/dist/server.d.ts +2 -0
  68. package/dist/server.js +914 -1503
  69. package/dist/server.js.map +1 -1
  70. package/package.json +6 -7
@@ -0,0 +1,276 @@
1
+ import {
2
+ buildRelationGraph,
3
+ calculateTemporalRelevance,
4
+ parseTemporalQuery
5
+ } from "./chunk-UYWE7HSU.js";
6
+ import {
7
+ db,
8
+ embedSingle
9
+ } from "./chunk-X2DL2GWT.js";
10
+
11
+ // src/engine/memory/search.ts
12
+ async function searchMemories(params) {
13
+ const {
14
+ query,
15
+ questionDate,
16
+ userId,
17
+ projectId,
18
+ orgId,
19
+ sessionId,
20
+ topK = 10,
21
+ includeInactive = false,
22
+ memoryTypes
23
+ } = params;
24
+ const temporal = params.temporalFilter || await parseTemporalQuery(query, questionDate);
25
+ const queryEmbedding = await embedSingle(query);
26
+ const semanticResults = await vectorSearchMemories({
27
+ embedding: queryEmbedding,
28
+ userId,
29
+ projectId,
30
+ orgId,
31
+ sessionId,
32
+ temporal,
33
+ includeInactive,
34
+ memoryTypes,
35
+ limit: topK * 3
36
+ // Get more for reranking
37
+ });
38
+ if (semanticResults.length === 0) {
39
+ return [];
40
+ }
41
+ const enriched = await enrichWithRelations(semanticResults, topK * 2);
42
+ const scored = enriched.map((memory) => ({
43
+ ...memory,
44
+ temporalScore: memory.documentDate ? calculateTemporalRelevance(memory.documentDate, questionDate) : 0.5
45
+ }));
46
+ const combined = scored.map((m) => ({
47
+ ...m,
48
+ finalScore: m.similarity * 0.7 + m.temporalScore * 0.3
49
+ }));
50
+ combined.sort((a, b) => b.finalScore - a.finalScore);
51
+ const topMemories = combined.slice(0, topK);
52
+ const results = await injectSourceChunks(topMemories);
53
+ return results;
54
+ }
55
+ async function vectorSearchMemories(params) {
56
+ const {
57
+ embedding,
58
+ userId,
59
+ projectId,
60
+ orgId,
61
+ sessionId,
62
+ temporal,
63
+ includeInactive,
64
+ memoryTypes,
65
+ limit
66
+ } = params;
67
+ const whereConditions = [
68
+ { projectId }
69
+ ];
70
+ if (orgId) {
71
+ whereConditions.push({ orgId });
72
+ }
73
+ if (userId) {
74
+ whereConditions.push({ userId });
75
+ }
76
+ if (sessionId) {
77
+ whereConditions.push({ sessionId });
78
+ }
79
+ if (!includeInactive) {
80
+ whereConditions.push({ isActive: true });
81
+ }
82
+ whereConditions.push({
83
+ OR: [
84
+ { validUntil: null },
85
+ { validUntil: { gt: /* @__PURE__ */ new Date() } }
86
+ ]
87
+ });
88
+ if (memoryTypes && memoryTypes.length > 0) {
89
+ whereConditions.push({
90
+ memoryType: { in: memoryTypes }
91
+ });
92
+ }
93
+ if (temporal.hasTemporalConstraint && temporal.dateRange) {
94
+ whereConditions.push({
95
+ documentDate: {
96
+ gte: temporal.dateRange.start,
97
+ lte: temporal.dateRange.end
98
+ }
99
+ });
100
+ }
101
+ const embeddingStr = `[${embedding.join(",")}]`;
102
+ const results = await db.$queryRaw`
103
+ SELECT
104
+ id,
105
+ content,
106
+ "memoryType",
107
+ "entityMentions",
108
+ confidence,
109
+ version,
110
+ "documentDate",
111
+ "eventDate",
112
+ "validFrom",
113
+ "validUntil",
114
+ "sourceChunkId",
115
+ metadata,
116
+ 1 - (embedding <=> ${embeddingStr}::vector) as similarity
117
+ FROM memories
118
+ WHERE
119
+ "projectId" = ${projectId}
120
+ ${orgId ? db.$queryRaw`AND "orgId" = ${orgId}` : db.$queryRaw``}
121
+ ${userId ? db.$queryRaw`AND "userId" = ${userId}` : db.$queryRaw``}
122
+ ${sessionId ? db.$queryRaw`AND "sessionId" = ${sessionId}` : db.$queryRaw``}
123
+ ${!includeInactive ? db.$queryRaw`AND "isActive" = true` : db.$queryRaw``}
124
+ AND ("validUntil" IS NULL OR "validUntil" > NOW())
125
+ ${memoryTypes && memoryTypes.length > 0 ? db.$queryRaw`AND "memoryType" = ANY(${memoryTypes})` : db.$queryRaw``}
126
+ ${temporal.hasTemporalConstraint && temporal.dateRange ? db.$queryRaw`AND "documentDate" >= ${temporal.dateRange.start} AND "documentDate" <= ${temporal.dateRange.end}` : db.$queryRaw``}
127
+ ORDER BY similarity DESC
128
+ LIMIT ${limit}
129
+ `;
130
+ return results;
131
+ }
132
+ async function enrichWithRelations(memories, maxTotal) {
133
+ if (memories.length === 0) {
134
+ return [];
135
+ }
136
+ const memoryIds = memories.map((m) => m.id);
137
+ const relations = await db.memoryRelation.findMany({
138
+ where: {
139
+ OR: [
140
+ { fromMemoryId: { in: memoryIds } },
141
+ { toMemoryId: { in: memoryIds } }
142
+ ]
143
+ }
144
+ });
145
+ if (relations.length === 0) {
146
+ return memories;
147
+ }
148
+ const graph = buildRelationGraph(relations);
149
+ const relatedIds = /* @__PURE__ */ new Set();
150
+ for (const memory of memories) {
151
+ const neighbors = graph.get(memory.id) || [];
152
+ for (const neighbor of neighbors.slice(0, 3)) {
153
+ relatedIds.add(neighbor.memoryId);
154
+ }
155
+ }
156
+ memoryIds.forEach((id) => relatedIds.delete(id));
157
+ if (relatedIds.size === 0) {
158
+ return memories;
159
+ }
160
+ const related = await db.memory.findMany({
161
+ where: {
162
+ id: { in: Array.from(relatedIds) },
163
+ isActive: true
164
+ },
165
+ take: maxTotal - memories.length
166
+ });
167
+ const relatedWithScores = related.map((m) => ({
168
+ ...m,
169
+ similarity: 0.6,
170
+ // Lower score for related but not directly matched
171
+ isRelated: true
172
+ }));
173
+ return [...memories, ...relatedWithScores];
174
+ }
175
+ async function injectSourceChunks(memories) {
176
+ const chunkIds = memories.map((m) => m.sourceChunkId).filter((id) => id !== null);
177
+ if (chunkIds.length === 0) {
178
+ return memories.map((m) => ({
179
+ memory: {
180
+ id: m.id,
181
+ content: m.content,
182
+ memoryType: m.memoryType,
183
+ entityMentions: m.entityMentions || [],
184
+ confidence: m.confidence,
185
+ version: m.version,
186
+ temporal: {
187
+ documentDate: m.documentDate,
188
+ eventDate: m.eventDate,
189
+ validFrom: m.validFrom,
190
+ validUntil: m.validUntil
191
+ }
192
+ },
193
+ similarity: m.similarity
194
+ }));
195
+ }
196
+ const chunks = await db.chunk.findMany({
197
+ where: {
198
+ id: { in: chunkIds }
199
+ },
200
+ select: {
201
+ id: true,
202
+ content: true,
203
+ metadata: true
204
+ }
205
+ });
206
+ const chunkMap = new Map(chunks.map((c) => [c.id, c]));
207
+ return memories.map((m) => ({
208
+ memory: {
209
+ id: m.id,
210
+ content: m.content,
211
+ memoryType: m.memoryType,
212
+ entityMentions: m.entityMentions || [],
213
+ confidence: m.confidence,
214
+ version: m.version,
215
+ temporal: {
216
+ documentDate: m.documentDate,
217
+ eventDate: m.eventDate,
218
+ validFrom: m.validFrom,
219
+ validUntil: m.validUntil
220
+ }
221
+ },
222
+ chunk: m.sourceChunkId && chunkMap.has(m.sourceChunkId) ? {
223
+ id: chunkMap.get(m.sourceChunkId).id,
224
+ content: chunkMap.get(m.sourceChunkId).content,
225
+ metadata: chunkMap.get(m.sourceChunkId).metadata
226
+ } : void 0,
227
+ similarity: m.similarity,
228
+ relations: m.isRelated ? [] : void 0
229
+ }));
230
+ }
231
+ async function getSessionMemories(params) {
232
+ const { sessionId, projectId, limit = 50, sinceDate } = params;
233
+ const where = {
234
+ sessionId,
235
+ projectId,
236
+ isActive: true
237
+ };
238
+ if (sinceDate) {
239
+ where.createdAt = { gte: sinceDate };
240
+ }
241
+ return db.memory.findMany({
242
+ where,
243
+ orderBy: {
244
+ createdAt: "desc"
245
+ },
246
+ take: limit
247
+ });
248
+ }
249
+ async function getUserProfile(params) {
250
+ const { userId, projectId, memoryTypes } = params;
251
+ const where = {
252
+ userId,
253
+ projectId,
254
+ isActive: true,
255
+ scope: "USER"
256
+ // Long-term user-level memories
257
+ };
258
+ if (memoryTypes) {
259
+ where.memoryType = { in: memoryTypes };
260
+ }
261
+ return db.memory.findMany({
262
+ where,
263
+ orderBy: {
264
+ importance: "desc"
265
+ },
266
+ take: 100
267
+ // Top 100 most important user memories
268
+ });
269
+ }
270
+
271
+ export {
272
+ searchMemories,
273
+ getSessionMemories,
274
+ getUserProfile
275
+ };
276
+ //# sourceMappingURL=chunk-OBLI4FE4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/engine/memory/search.ts"],"sourcesContent":["/**\n * SOTA Memory Search Engine\n * Memory-first hybrid search with temporal filtering and graph traversal\n * Beats Supermemory's 81.6% and targets 85%+ on LongMemEval\n */\n\nimport { db } from \"../../db/index.js\";\nimport { embed, embedSingle } from \"../embeddings.js\";\nimport { parseTemporalQuery, calculateTemporalRelevance } from \"./temporal.js\";\nimport { buildRelationGraph } from \"./relations.js\";\nimport type { MemorySearchParams, MemorySearchResult } from \"./types.js\";\n\n/**\n * Main memory search function\n * Implements memory-first hybrid approach from Supermemory\n */\nexport async function searchMemories(\n params: MemorySearchParams\n): Promise<MemorySearchResult[]> {\n const {\n query,\n questionDate,\n userId,\n projectId,\n orgId,\n sessionId,\n topK = 10,\n includeInactive = false,\n memoryTypes,\n } = params;\n\n // Step 1: Parse temporal constraints from query\n const temporal = params.temporalFilter || await parseTemporalQuery(query, questionDate);\n\n // Step 2: Embed query for semantic search\n const queryEmbedding = await embedSingle(query);\n\n // Step 3: Vector search on memories (NOT chunks!)\n const semanticResults = await vectorSearchMemories({\n embedding: queryEmbedding,\n userId,\n projectId,\n orgId,\n sessionId,\n temporal,\n includeInactive,\n memoryTypes,\n limit: topK * 3, // Get more for reranking\n });\n\n if (semanticResults.length === 0) {\n return [];\n }\n\n // Step 4: Graph traversal - enrich with related memories\n const enriched = await enrichWithRelations(semanticResults, topK * 2);\n\n // Step 5: Temporal relevance scoring\n const scored = enriched.map((memory) => ({\n ...memory,\n temporalScore: memory.documentDate\n ? calculateTemporalRelevance(memory.documentDate, questionDate)\n : 0.5,\n }));\n\n // Step 6: Combine scores (semantic + temporal)\n const combined = scored.map((m) => ({\n ...m,\n finalScore: m.similarity * 0.7 + m.temporalScore * 0.3,\n }));\n\n // Step 7: Sort by final score\n combined.sort((a, b) => b.finalScore - a.finalScore);\n\n // Step 8: Take top K\n const topMemories = combined.slice(0, topK);\n\n // Step 9: Inject source chunks for context\n const results = await injectSourceChunks(topMemories);\n\n return results;\n}\n\n/**\n * Vector search on memories table\n */\nasync function vectorSearchMemories(params: {\n embedding: number[];\n userId?: string;\n projectId: string;\n orgId?: string;\n sessionId?: string;\n temporal: { hasTemporalConstraint: boolean; dateRange?: { start: Date; end: Date } };\n includeInactive: boolean;\n memoryTypes?: string[];\n limit: number;\n}): Promise<any[]> {\n const {\n embedding,\n userId,\n projectId,\n orgId,\n sessionId,\n temporal,\n includeInactive,\n memoryTypes,\n limit,\n } = params;\n\n // Build where clause\n const whereConditions: any[] = [\n { projectId },\n ];\n\n if (orgId) {\n whereConditions.push({ orgId });\n }\n\n if (userId) {\n whereConditions.push({ userId });\n }\n\n if (sessionId) {\n whereConditions.push({ sessionId });\n }\n\n if (!includeInactive) {\n whereConditions.push({ isActive: true });\n }\n\n // Only get current versions (validUntil = null)\n whereConditions.push({\n OR: [\n { validUntil: null },\n { validUntil: { gt: new Date() } },\n ],\n });\n\n if (memoryTypes && memoryTypes.length > 0) {\n whereConditions.push({\n memoryType: { in: memoryTypes },\n });\n }\n\n // Temporal filtering\n if (temporal.hasTemporalConstraint && temporal.dateRange) {\n whereConditions.push({\n documentDate: {\n gte: temporal.dateRange.start,\n lte: temporal.dateRange.end,\n },\n });\n }\n\n // Vector similarity search using Prisma raw SQL\n // Note: Adjust this based on your actual vector column setup\n const embeddingStr = `[${embedding.join(\",\")}]`;\n\n const results = await db.$queryRaw`\n SELECT\n id,\n content,\n \"memoryType\",\n \"entityMentions\",\n confidence,\n version,\n \"documentDate\",\n \"eventDate\",\n \"validFrom\",\n \"validUntil\",\n \"sourceChunkId\",\n metadata,\n 1 - (embedding <=> ${embeddingStr}::vector) as similarity\n FROM memories\n WHERE\n \"projectId\" = ${projectId}\n ${orgId ? db.$queryRaw`AND \"orgId\" = ${orgId}` : db.$queryRaw``}\n ${userId ? db.$queryRaw`AND \"userId\" = ${userId}` : db.$queryRaw``}\n ${sessionId ? db.$queryRaw`AND \"sessionId\" = ${sessionId}` : db.$queryRaw``}\n ${!includeInactive ? db.$queryRaw`AND \"isActive\" = true` : db.$queryRaw``}\n AND (\"validUntil\" IS NULL OR \"validUntil\" > NOW())\n ${memoryTypes && memoryTypes.length > 0\n ? db.$queryRaw`AND \"memoryType\" = ANY(${memoryTypes})`\n : db.$queryRaw``}\n ${temporal.hasTemporalConstraint && temporal.dateRange\n ? db.$queryRaw`AND \"documentDate\" >= ${temporal.dateRange.start} AND \"documentDate\" <= ${temporal.dateRange.end}`\n : db.$queryRaw``}\n ORDER BY similarity DESC\n LIMIT ${limit}\n `;\n\n return results as any[];\n}\n\n/**\n * Enrich memories with related memories via graph traversal\n * Follows \"extends\", \"derives\", \"supports\" relations\n */\nasync function enrichWithRelations(\n memories: any[],\n maxTotal: number\n): Promise<any[]> {\n if (memories.length === 0) {\n return [];\n }\n\n const memoryIds = memories.map((m) => m.id);\n\n // Get all relations for these memories\n const relations = await db.memoryRelation.findMany({\n where: {\n OR: [\n { fromMemoryId: { in: memoryIds } },\n { toMemoryId: { in: memoryIds } },\n ],\n },\n });\n\n if (relations.length === 0) {\n return memories;\n }\n\n // Build graph\n const graph = buildRelationGraph(relations);\n\n // Collect related memory IDs\n const relatedIds = new Set<string>();\n\n for (const memory of memories) {\n const neighbors = graph.get(memory.id) || [];\n\n // Add neighbors (but limit to avoid explosion)\n for (const neighbor of neighbors.slice(0, 3)) {\n // Max 3 per memory\n relatedIds.add(neighbor.memoryId);\n }\n }\n\n // Remove already included memories\n memoryIds.forEach((id) => relatedIds.delete(id));\n\n if (relatedIds.size === 0) {\n return memories;\n }\n\n // Fetch related memories\n const related = await db.memory.findMany({\n where: {\n id: { in: Array.from(relatedIds) },\n isActive: true,\n },\n take: maxTotal - memories.length,\n });\n\n // Assign lower similarity scores to related memories\n const relatedWithScores = related.map((m: any) => ({\n ...m,\n similarity: 0.6, // Lower score for related but not directly matched\n isRelated: true,\n }));\n\n return [...memories, ...relatedWithScores];\n}\n\n/**\n * Inject source chunks for top memories\n * Provides full context for LLM\n */\nasync function injectSourceChunks(\n memories: any[]\n): Promise<MemorySearchResult[]> {\n const chunkIds = memories\n .map((m) => m.sourceChunkId)\n .filter((id): id is string => id !== null);\n\n if (chunkIds.length === 0) {\n // Return memories without chunks\n return memories.map((m) => ({\n memory: {\n id: m.id,\n content: m.content,\n memoryType: m.memoryType,\n entityMentions: m.entityMentions || [],\n confidence: m.confidence,\n version: m.version,\n temporal: {\n documentDate: m.documentDate,\n eventDate: m.eventDate,\n validFrom: m.validFrom,\n validUntil: m.validUntil,\n },\n },\n similarity: m.similarity,\n }));\n }\n\n // Fetch chunks\n const chunks = await db.chunk.findMany({\n where: {\n id: { in: chunkIds },\n },\n select: {\n id: true,\n content: true,\n metadata: true,\n },\n });\n\n const chunkMap = new Map(chunks.map((c) => [c.id, c]));\n\n // Map memories to results with chunks\n return memories.map((m) => ({\n memory: {\n id: m.id,\n content: m.content,\n memoryType: m.memoryType,\n entityMentions: m.entityMentions || [],\n confidence: m.confidence,\n version: m.version,\n temporal: {\n documentDate: m.documentDate,\n eventDate: m.eventDate,\n validFrom: m.validFrom,\n validUntil: m.validUntil,\n },\n },\n chunk: m.sourceChunkId && chunkMap.has(m.sourceChunkId)\n ? {\n id: chunkMap.get(m.sourceChunkId)!.id,\n content: chunkMap.get(m.sourceChunkId)!.content,\n metadata: chunkMap.get(m.sourceChunkId)!.metadata,\n }\n : undefined,\n similarity: m.similarity,\n relations: m.isRelated ? [] : undefined,\n }));\n}\n\n/**\n * Session-based memory query\n * Gets recent memories from a session for context building\n */\nexport async function getSessionMemories(params: {\n sessionId: string;\n projectId: string;\n limit?: number;\n sinceDate?: Date;\n}): Promise<any[]> {\n const { sessionId, projectId, limit = 50, sinceDate } = params;\n\n const where: any = {\n sessionId,\n projectId,\n isActive: true,\n };\n\n if (sinceDate) {\n where.createdAt = { gte: sinceDate };\n }\n\n return db.memory.findMany({\n where,\n orderBy: {\n createdAt: \"desc\",\n },\n take: limit,\n });\n}\n\n/**\n * User profile memory query\n * Gets long-term user preferences and facts\n */\nexport async function getUserProfile(params: {\n userId: string;\n projectId: string;\n memoryTypes?: string[];\n}): Promise<any[]> {\n const { userId, projectId, memoryTypes } = params;\n\n const where: any = {\n userId,\n projectId,\n isActive: true,\n scope: \"USER\", // Long-term user-level memories\n };\n\n if (memoryTypes) {\n where.memoryType = { in: memoryTypes };\n }\n\n return db.memory.findMany({\n where,\n orderBy: {\n importance: \"desc\",\n },\n take: 100, // Top 100 most important user memories\n });\n}\n"],"mappings":";;;;;;;;;;;AAgBA,eAAsB,eACpB,QAC+B;AAC/B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP,kBAAkB;AAAA,IAClB;AAAA,EACF,IAAI;AAGJ,QAAM,WAAW,OAAO,kBAAkB,MAAM,mBAAmB,OAAO,YAAY;AAGtF,QAAM,iBAAiB,MAAM,YAAY,KAAK;AAG9C,QAAM,kBAAkB,MAAM,qBAAqB;AAAA,IACjD,WAAW;AAAA,IACX;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO,OAAO;AAAA;AAAA,EAChB,CAAC;AAED,MAAI,gBAAgB,WAAW,GAAG;AAChC,WAAO,CAAC;AAAA,EACV;AAGA,QAAM,WAAW,MAAM,oBAAoB,iBAAiB,OAAO,CAAC;AAGpE,QAAM,SAAS,SAAS,IAAI,CAAC,YAAY;AAAA,IACvC,GAAG;AAAA,IACH,eAAe,OAAO,eAClB,2BAA2B,OAAO,cAAc,YAAY,IAC5D;AAAA,EACN,EAAE;AAGF,QAAM,WAAW,OAAO,IAAI,CAAC,OAAO;AAAA,IAClC,GAAG;AAAA,IACH,YAAY,EAAE,aAAa,MAAM,EAAE,gBAAgB;AAAA,EACrD,EAAE;AAGF,WAAS,KAAK,CAAC,GAAG,MAAM,EAAE,aAAa,EAAE,UAAU;AAGnD,QAAM,cAAc,SAAS,MAAM,GAAG,IAAI;AAG1C,QAAM,UAAU,MAAM,mBAAmB,WAAW;AAEp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Y;AAAA,IACd;AAAA,IACA,MAAM;AAAA;AAAA,EACR,CAAC;AACH;","names":[]}
@@ -0,0 +1,271 @@
1
+ import {
2
+ buildRelationGraph,
3
+ calculateTemporalRelevance,
4
+ parseTemporalQuery
5
+ } from "./chunk-LMEYV4JD.js";
6
+ import {
7
+ db,
8
+ embedSingle
9
+ } from "./chunk-3WGYBAYR.js";
10
+
11
+ // ../src/engine/memory/search.ts
12
+ async function searchMemories(params) {
13
+ const {
14
+ query,
15
+ questionDate,
16
+ userId,
17
+ projectId,
18
+ orgId,
19
+ sessionId,
20
+ topK = 10,
21
+ includeInactive = false,
22
+ memoryTypes
23
+ } = params;
24
+ const temporal = params.temporalFilter || await parseTemporalQuery(query, questionDate);
25
+ const queryEmbedding = await embedSingle(query);
26
+ const semanticResults = await vectorSearchMemories({
27
+ embedding: queryEmbedding,
28
+ userId,
29
+ projectId,
30
+ orgId,
31
+ sessionId,
32
+ temporal,
33
+ includeInactive,
34
+ memoryTypes,
35
+ limit: topK * 3
36
+ // Get more for reranking
37
+ });
38
+ if (semanticResults.length === 0) {
39
+ return [];
40
+ }
41
+ const enriched = await enrichWithRelations(semanticResults, topK * 2);
42
+ const scored = enriched.map((memory) => ({
43
+ ...memory,
44
+ temporalScore: memory.documentDate ? calculateTemporalRelevance(memory.documentDate, questionDate) : 0.5
45
+ }));
46
+ const combined = scored.map((m) => ({
47
+ ...m,
48
+ finalScore: m.similarity * 0.7 + m.temporalScore * 0.3
49
+ }));
50
+ combined.sort((a, b) => b.finalScore - a.finalScore);
51
+ const topMemories = combined.slice(0, topK);
52
+ const results = await injectSourceChunks(topMemories);
53
+ return results;
54
+ }
55
+ async function vectorSearchMemories(params) {
56
+ const {
57
+ embedding,
58
+ userId,
59
+ projectId,
60
+ orgId,
61
+ sessionId,
62
+ temporal,
63
+ includeInactive,
64
+ memoryTypes,
65
+ limit
66
+ } = params;
67
+ const whereConditions = [
68
+ { projectId }
69
+ ];
70
+ if (orgId) {
71
+ whereConditions.push({ orgId });
72
+ }
73
+ if (userId) {
74
+ whereConditions.push({ userId });
75
+ }
76
+ if (sessionId) {
77
+ whereConditions.push({ sessionId });
78
+ }
79
+ if (!includeInactive) {
80
+ whereConditions.push({ isActive: true });
81
+ }
82
+ whereConditions.push({
83
+ OR: [
84
+ { validUntil: null },
85
+ { validUntil: { gt: /* @__PURE__ */ new Date() } }
86
+ ]
87
+ });
88
+ if (memoryTypes && memoryTypes.length > 0) {
89
+ whereConditions.push({
90
+ memoryType: { in: memoryTypes }
91
+ });
92
+ }
93
+ if (temporal.hasTemporalConstraint && temporal.dateRange) {
94
+ whereConditions.push({
95
+ documentDate: {
96
+ gte: temporal.dateRange.start,
97
+ lte: temporal.dateRange.end
98
+ }
99
+ });
100
+ }
101
+ const embeddingStr = `[${embedding.join(",")}]`;
102
+ const results = await db.$queryRaw`
103
+ SELECT
104
+ id,
105
+ content,
106
+ "memoryType",
107
+ "entityMentions",
108
+ confidence,
109
+ version,
110
+ "documentDate",
111
+ "eventDate",
112
+ "validFrom",
113
+ "validUntil",
114
+ "sourceChunkId",
115
+ metadata,
116
+ 1 - (embedding <=> ${embeddingStr}::vector) as similarity
117
+ FROM memories
118
+ WHERE
119
+ "projectId" = ${projectId}
120
+ ${orgId ? db.$queryRaw`AND "orgId" = ${orgId}` : db.$queryRaw``}
121
+ ${userId ? db.$queryRaw`AND "userId" = ${userId}` : db.$queryRaw``}
122
+ ${sessionId ? db.$queryRaw`AND "sessionId" = ${sessionId}` : db.$queryRaw``}
123
+ ${!includeInactive ? db.$queryRaw`AND "isActive" = true` : db.$queryRaw``}
124
+ AND ("validUntil" IS NULL OR "validUntil" > NOW())
125
+ ${memoryTypes && memoryTypes.length > 0 ? db.$queryRaw`AND "memoryType" = ANY(${memoryTypes})` : db.$queryRaw``}
126
+ ${temporal.hasTemporalConstraint && temporal.dateRange ? db.$queryRaw`AND "documentDate" >= ${temporal.dateRange.start} AND "documentDate" <= ${temporal.dateRange.end}` : db.$queryRaw``}
127
+ ORDER BY similarity DESC
128
+ LIMIT ${limit}
129
+ `;
130
+ return results;
131
+ }
132
+ async function enrichWithRelations(memories, maxTotal) {
133
+ if (memories.length === 0) {
134
+ return [];
135
+ }
136
+ const memoryIds = memories.map((m) => m.id);
137
+ const relations = await db.memoryRelation.findMany({
138
+ where: {
139
+ OR: [
140
+ { fromMemoryId: { in: memoryIds } },
141
+ { toMemoryId: { in: memoryIds } }
142
+ ]
143
+ }
144
+ });
145
+ if (relations.length === 0) {
146
+ return memories;
147
+ }
148
+ const graph = buildRelationGraph(relations);
149
+ const relatedIds = /* @__PURE__ */ new Set();
150
+ for (const memory of memories) {
151
+ const neighbors = graph.get(memory.id) || [];
152
+ for (const neighbor of neighbors.slice(0, 3)) {
153
+ relatedIds.add(neighbor.memoryId);
154
+ }
155
+ }
156
+ memoryIds.forEach((id) => relatedIds.delete(id));
157
+ if (relatedIds.size === 0) {
158
+ return memories;
159
+ }
160
+ const related = await db.memory.findMany({
161
+ where: {
162
+ id: { in: Array.from(relatedIds) },
163
+ isActive: true
164
+ },
165
+ take: maxTotal - memories.length
166
+ });
167
+ const relatedWithScores = related.map((m) => ({
168
+ ...m,
169
+ similarity: 0.6,
170
+ // Lower score for related but not directly matched
171
+ isRelated: true
172
+ }));
173
+ return [...memories, ...relatedWithScores];
174
+ }
175
+ async function injectSourceChunks(memories) {
176
+ const chunkIds = memories.map((m) => m.sourceChunkId).filter((id) => id !== null);
177
+ if (chunkIds.length === 0) {
178
+ return memories.map((m) => ({
179
+ memory: {
180
+ id: m.id,
181
+ content: m.content,
182
+ memoryType: m.memoryType,
183
+ entityMentions: m.entityMentions || [],
184
+ confidence: m.confidence,
185
+ version: m.version,
186
+ temporal: {
187
+ documentDate: m.documentDate,
188
+ eventDate: m.eventDate,
189
+ validFrom: m.validFrom,
190
+ validUntil: m.validUntil
191
+ }
192
+ },
193
+ similarity: m.similarity
194
+ }));
195
+ }
196
+ const chunks = await db.chunk.findMany({
197
+ where: {
198
+ id: { in: chunkIds }
199
+ },
200
+ select: {
201
+ id: true,
202
+ content: true,
203
+ metadata: true
204
+ }
205
+ });
206
+ const chunkMap = new Map(chunks.map((c) => [c.id, c]));
207
+ return memories.map((m) => ({
208
+ memory: {
209
+ id: m.id,
210
+ content: m.content,
211
+ memoryType: m.memoryType,
212
+ entityMentions: m.entityMentions || [],
213
+ confidence: m.confidence,
214
+ version: m.version,
215
+ temporal: {
216
+ documentDate: m.documentDate,
217
+ eventDate: m.eventDate,
218
+ validFrom: m.validFrom,
219
+ validUntil: m.validUntil
220
+ }
221
+ },
222
+ chunk: m.sourceChunkId && chunkMap.has(m.sourceChunkId) ? {
223
+ id: chunkMap.get(m.sourceChunkId).id,
224
+ content: chunkMap.get(m.sourceChunkId).content,
225
+ metadata: chunkMap.get(m.sourceChunkId).metadata
226
+ } : void 0,
227
+ similarity: m.similarity,
228
+ relations: m.isRelated ? [] : void 0
229
+ }));
230
+ }
231
+ async function getSessionMemories(params) {
232
+ const { sessionId, projectId, limit = 50, sinceDate } = params;
233
+ const where = {
234
+ sessionId,
235
+ projectId,
236
+ isActive: true
237
+ };
238
+ if (sinceDate) {
239
+ where.createdAt = { gte: sinceDate };
240
+ }
241
+ return db.memory.findMany({
242
+ where,
243
+ orderBy: {
244
+ createdAt: "desc"
245
+ },
246
+ take: limit
247
+ });
248
+ }
249
+ async function getUserProfile(params) {
250
+ const { userId, projectId, memoryTypes, limit = 50 } = params;
251
+ const where = {
252
+ userId,
253
+ projectId,
254
+ isActive: true,
255
+ scope: "USER"
256
+ };
257
+ if (memoryTypes) {
258
+ where.memoryType = { in: memoryTypes };
259
+ }
260
+ return db.memory.findMany({
261
+ where,
262
+ orderBy: { importance: "desc" },
263
+ take: Math.min(limit, 100)
264
+ });
265
+ }
266
+
267
+ export {
268
+ searchMemories,
269
+ getSessionMemories,
270
+ getUserProfile
271
+ };
@@ -0,0 +1,37 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __copyProps = (to, from, except, desc) => {
17
+ if (from && typeof from === "object" || typeof from === "function") {
18
+ for (let key of __getOwnPropNames(from))
19
+ if (!__hasOwnProp.call(to, key) && key !== except)
20
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
+ }
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ export {
34
+ __require,
35
+ __commonJS,
36
+ __toESM
37
+ };