@mastra/convex 1.7.5-alpha.0 → 1.7.5-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/workflow-snapshot.d.ts.map +1 -1
- package/dist/{server-uHLma0g7.cjs → server-BxQKtmhb.cjs} +9 -2
- package/dist/server-BxQKtmhb.cjs.map +1 -0
- package/dist/{server-DCzSpppl.js → server-CedrKoHl.js} +9 -2
- package/dist/server-CedrKoHl.js.map +1 -0
- package/dist/storage/domains/memory/index.d.ts +1 -1
- package/dist/storage/domains/memory/index.d.ts.map +1 -1
- package/package.json +6 -7
- package/dist/server-DCzSpppl.js.map +0 -1
- package/dist/server-uHLma0g7.cjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-uHLma0g7.cjs","names":["mapInBatches","TABLE_BACKGROUND_TASKS","TABLE_THREADS","TABLE_MESSAGES","TABLE_RESOURCES","TABLE_WORKFLOW_SNAPSHOT","TABLE_SCORERS","TABLE_SCHEDULES","TABLE_SCHEDULE_TRIGGERS","TABLE_CHANNEL_INSTALLATIONS","TABLE_CHANNEL_CONFIG","err","v"],"sources":["../src/server/cache.ts","../src/server/index-map.ts","../src/server/observational-memory.ts","../src/server/run-fencing.ts","../src/server/workflow-snapshot.ts","../src/server/storage.ts","../src/server/native-vector.ts"],"sourcesContent":["import type { GenericMutationCtx as MutationCtx } from 'convex/server';\nimport { mutationGeneric } from 'convex/server';\nimport type { GenericId } from 'convex/values';\n\nimport type { CacheRequest, CacheResponse } from '../cache/types';\n\nconst CACHE_TABLE = 'mastra_cache';\nconst CACHE_LIST_TABLE = 'mastra_cache_list_items';\nconst CACHE_MUTATION_BATCH_SIZE = 25;\n\ntype CacheKind = 'value' | 'list' | 'counter' | 'deleted';\ntype CacheDoc = {\n _id: GenericId<string>;\n key: string;\n keyPrefix: string;\n kind: CacheKind;\n value?: string;\n counter?: number;\n expiresAt: number | null;\n};\ntype CacheListItem = {\n _id: GenericId<string>;\n key: string;\n keyPrefix: string;\n index: number;\n value: string;\n};\ntype DeleteBatchResult = {\n hasMore: boolean;\n};\n\nfunction encodeValue(value: unknown): string {\n // The cache wire format stores JSON strings; undefined is represented as null.\n return JSON.stringify(value === undefined ? null : value);\n}\n\nfunction decodeValue(value: string): unknown {\n return JSON.parse(value);\n}\n\nfunction isExpired(doc: { expiresAt: number | null }, now: number): boolean {\n return doc.expiresAt !== null && doc.expiresAt <= now;\n}\n\nfunction normalizeListRange(from: number, to: number, length: number): { from: number; to: number } | null {\n const normalizedFrom = from < 0 ? Math.max(length + from, 0) : from;\n const normalizedTo = to < 0 ? length + to : to;\n if (normalizedTo < normalizedFrom || normalizedFrom >= length) return null;\n return { from: normalizedFrom, to: normalizedTo };\n}\n\nasync function findCacheDoc(ctx: MutationCtx<any>, key: string): Promise<CacheDoc | null> {\n return (await ctx.db\n .query(CACHE_TABLE)\n .withIndex('by_key', (q: any) => q.eq('key', key))\n .first()) as CacheDoc | null;\n}\n\nasync function deleteCacheKey(ctx: MutationCtx<any>, key: string): Promise<DeleteBatchResult> {\n const [doc, listItems] = await Promise.all([\n findCacheDoc(ctx, key),\n ctx.db\n .query(CACHE_LIST_TABLE)\n .withIndex('by_key_index', (q: any) => q.eq('key', key))\n .take(CACHE_MUTATION_BATCH_SIZE + 1),\n ]);\n\n if (doc && doc.kind !== 'deleted') {\n await ctx.db.patch(doc._id, { kind: 'deleted' });\n }\n\n for (const item of listItems.slice(0, CACHE_MUTATION_BATCH_SIZE) as CacheListItem[]) {\n await ctx.db.delete(item._id);\n }\n\n const hasMore = listItems.length > CACHE_MUTATION_BATCH_SIZE;\n if (doc && !hasMore) {\n await ctx.db.delete(doc._id);\n }\n\n return {\n hasMore,\n };\n}\n\nasync function getLiveCacheDoc(\n ctx: MutationCtx<any>,\n key: string,\n now: number,\n): Promise<{ doc: CacheDoc | null; hasMore: boolean }> {\n const doc = await findCacheDoc(ctx, key);\n if (!doc) return { doc: null, hasMore: false };\n if (doc.kind === 'deleted') {\n const cleanup = await deleteCacheKey(ctx, key);\n return { doc: null, hasMore: cleanup.hasMore };\n }\n if (!isExpired(doc, now)) return { doc, hasMore: false };\n\n const cleanup = await deleteCacheKey(ctx, key);\n return { doc: null, hasMore: cleanup.hasMore };\n}\n\nasync function writeCacheDoc(\n ctx: MutationCtx<any>,\n key: string,\n existing: CacheDoc | null,\n patch: Omit<CacheDoc, '_id' | 'key'>,\n): Promise<CacheDoc> {\n if (existing) {\n await ctx.db.patch(existing._id, patch);\n return { ...existing, ...patch };\n }\n\n const _id = await ctx.db.insert(CACHE_TABLE, { key, ...patch });\n return { _id, key, ...patch };\n}\n\nasync function clearPrefix(ctx: MutationCtx<any>, keyPrefix: string): Promise<boolean> {\n const [docs, orphanListItems] = await Promise.all([\n ctx.db\n .query(CACHE_TABLE)\n .withIndex('by_key_prefix', (q: any) => q.eq('keyPrefix', keyPrefix))\n .take(CACHE_MUTATION_BATCH_SIZE + 1),\n ctx.db\n .query(CACHE_LIST_TABLE)\n .withIndex('by_key_prefix', (q: any) => q.eq('keyPrefix', keyPrefix))\n .take(1),\n ]);\n\n if (docs.length > 0) {\n for (const doc of docs.slice(0, CACHE_MUTATION_BATCH_SIZE) as CacheDoc[]) {\n if (doc.kind === 'list' || doc.kind === 'deleted') {\n const cleanup = await deleteCacheKey(ctx, doc.key);\n return cleanup.hasMore || docs.length > 1 || orphanListItems.length > 0;\n }\n\n await ctx.db.delete(doc._id);\n }\n\n return docs.length > CACHE_MUTATION_BATCH_SIZE || orphanListItems.length > 0;\n }\n\n const listItems = (await ctx.db\n .query(CACHE_LIST_TABLE)\n .withIndex('by_key_prefix', (q: any) => q.eq('keyPrefix', keyPrefix))\n .take(CACHE_MUTATION_BATCH_SIZE + 1)) as CacheListItem[];\n\n for (const item of listItems.slice(0, CACHE_MUTATION_BATCH_SIZE)) {\n await ctx.db.delete(item._id);\n }\n\n return listItems.length > CACHE_MUTATION_BATCH_SIZE;\n}\n\nexport async function handleCacheOperation(ctx: MutationCtx<any>, request: CacheRequest): Promise<CacheResponse> {\n const now = Date.now();\n\n switch (request.op) {\n case 'get': {\n const { doc, hasMore } = await getLiveCacheDoc(ctx, request.key, now);\n if (hasMore) return { ok: true, result: null, hasMore: true };\n if (!doc || doc.kind !== 'value') return { ok: true, result: null };\n return { ok: true, result: decodeValue(doc.value ?? 'null') };\n }\n\n case 'set': {\n let existing = await findCacheDoc(ctx, request.key);\n if (existing && (isExpired(existing, now) || existing.kind !== 'value')) {\n const cleanup = await deleteCacheKey(ctx, request.key);\n if (cleanup.hasMore) {\n return { ok: true, hasMore: true };\n }\n existing = null;\n }\n\n await writeCacheDoc(ctx, request.key, existing, {\n keyPrefix: request.keyPrefix,\n kind: 'value',\n value: encodeValue(request.value),\n expiresAt: request.expiresAt,\n });\n return { ok: true };\n }\n\n case 'listLength': {\n const { doc, hasMore } = await getLiveCacheDoc(ctx, request.key, now);\n if (hasMore) return { ok: true, result: 0, hasMore: true };\n if (!doc) return { ok: true, result: 0 };\n if (doc.kind !== 'list') return { ok: false, error: `${request.key} exists but is not an array` };\n\n return { ok: true, result: doc.counter ?? 0 };\n }\n\n case 'listPush': {\n let existing = await findCacheDoc(ctx, request.key);\n if (existing && (isExpired(existing, now) || existing.kind === 'deleted')) {\n const cleanup = await deleteCacheKey(ctx, request.key);\n if (cleanup.hasMore) {\n return { ok: true, hasMore: true };\n }\n existing = null;\n }\n if (existing && existing.kind !== 'list') {\n return { ok: false, error: `${request.key} exists but is not an array` };\n }\n\n const doc = existing\n ? await writeCacheDoc(ctx, request.key, existing, {\n kind: 'list',\n keyPrefix: request.keyPrefix,\n counter: (existing.counter ?? 0) + 1,\n expiresAt: request.expiresAt,\n })\n : await writeCacheDoc(ctx, request.key, null, {\n kind: 'list',\n keyPrefix: request.keyPrefix,\n counter: 1,\n expiresAt: request.expiresAt,\n });\n\n await ctx.db.insert(CACHE_LIST_TABLE, {\n key: request.key,\n keyPrefix: request.keyPrefix,\n index: (doc.counter ?? 1) - 1,\n value: encodeValue(request.value),\n });\n\n return { ok: true };\n }\n\n case 'listFromTo': {\n const { doc, hasMore } = await getLiveCacheDoc(ctx, request.key, now);\n if (hasMore) return { ok: true, result: [], hasMore: true };\n if (!doc || doc.kind !== 'list') return { ok: true, result: [] };\n\n const range = normalizeListRange(request.from, request.to, doc.counter ?? 0);\n if (!range) return { ok: true, result: [] };\n\n const query = ctx.db.query(CACHE_LIST_TABLE).withIndex('by_key_index', (q: any) => {\n return q.eq('key', request.key).gte('index', range.from).lte('index', range.to);\n });\n const items = (await query.collect()) as CacheListItem[];\n\n return { ok: true, result: items.map(item => decodeValue(item.value)) };\n }\n\n case 'delete': {\n const cleanup = await deleteCacheKey(ctx, request.key);\n return { ok: true, hasMore: cleanup.hasMore };\n }\n\n case 'clear': {\n const hasMore = await clearPrefix(ctx, request.keyPrefix);\n return { ok: true, hasMore };\n }\n\n case 'increment': {\n let existing = await findCacheDoc(ctx, request.key);\n if (existing && (isExpired(existing, now) || existing.kind === 'deleted')) {\n const cleanup = await deleteCacheKey(ctx, request.key);\n if (cleanup.hasMore) {\n return { ok: true, hasMore: true };\n }\n existing = null;\n }\n if (existing && existing.kind !== 'counter') {\n return { ok: false, error: `${request.key} exists but is not a number` };\n }\n\n const nextCounter = (existing?.counter ?? 0) + 1;\n await writeCacheDoc(ctx, request.key, existing, {\n kind: 'counter',\n keyPrefix: request.keyPrefix,\n counter: nextCounter,\n expiresAt: request.expiresAt,\n });\n\n return { ok: true, result: nextCounter };\n }\n }\n\n return { ok: false, error: `Unsupported operation ${(request as any).op}` };\n}\n\nexport const mastraCache = mutationGeneric(\n async (ctx, request: CacheRequest): Promise<CacheResponse> => handleCacheOperation(ctx, request),\n);\n","/**\n * Index definitions for automatic query optimization.\n *\n * Maps each typed Convex table to its available indexes and their field lists.\n * Indexes with more fields are listed first so the best (most specific) match\n * is preferred during selection.\n *\n * These must stay in sync with the index definitions in schema.ts.\n */\nimport type { EqualityFilter } from '../storage/types';\n\nexport const TABLE_INDEX_MAP: Record<string, Array<{ name: string; fields: string[] }>> = {\n mastra_messages: [\n { name: 'by_thread_created', fields: ['thread_id', 'createdAt'] },\n { name: 'by_thread', fields: ['thread_id'] },\n { name: 'by_resource', fields: ['resourceId'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_threads: [\n { name: 'by_resource', fields: ['resourceId'] },\n { name: 'by_created', fields: ['createdAt'] },\n { name: 'by_updated', fields: ['updatedAt'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_resources: [\n { name: 'by_updated', fields: ['updatedAt'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_workflow_snapshots: [\n { name: 'by_workflow_run', fields: ['workflow_name', 'run_id'] },\n { name: 'by_workflow', fields: ['workflow_name'] },\n { name: 'by_resource', fields: ['resourceId'] },\n { name: 'by_created', fields: ['createdAt'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_scorers: [\n { name: 'by_entity', fields: ['entityId', 'entityType'] },\n { name: 'by_scorer', fields: ['scorerId'] },\n { name: 'by_run', fields: ['runId'] },\n { name: 'by_created', fields: ['createdAt'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_schedules: [\n { name: 'by_workflow_status', fields: ['workflow_id', 'status'] },\n { name: 'by_workflow_id', fields: ['workflow_id'] },\n { name: 'by_owner', fields: ['owner_type', 'owner_id'] },\n { name: 'by_owner_id', fields: ['owner_id'] },\n { name: 'by_status_next_fire_at', fields: ['status', 'next_fire_at'] },\n { name: 'by_created', fields: ['created_at'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_schedule_triggers: [\n { name: 'by_schedule_actual', fields: ['schedule_id', 'actual_fire_at'] },\n { name: 'by_parent_trigger', fields: ['parent_trigger_id'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_channel_installations: [\n { name: 'by_platform_agent', fields: ['platform', 'agentId'] },\n { name: 'by_webhook', fields: ['webhookId'] },\n { name: 'by_platform', fields: ['platform'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_channel_config: [\n { name: 'by_platform', fields: ['platform'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_background_tasks: [\n { name: 'by_agent_status', fields: ['agent_id', 'status'] },\n { name: 'by_status_created', fields: ['status', 'createdAt'] },\n { name: 'by_run', fields: ['run_id'] },\n { name: 'by_tool_call', fields: ['tool_call_id'] },\n { name: 'by_thread', fields: ['thread_id'] },\n { name: 'by_resource', fields: ['resource_id'] },\n { name: 'by_tool', fields: ['tool_name'] },\n { name: 'by_created', fields: ['createdAt'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_vector_indexes: [\n { name: 'by_name', fields: ['indexName'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n mastra_observational_memory: [\n { name: 'by_lookup_key', fields: ['lookupKey', 'generationCount'] },\n { name: 'by_record_id', fields: ['id'] },\n ],\n};\n\n/**\n * Finds the best matching index for the given equality filters on a Convex table.\n *\n * Returns the index name and the subset of filters that form the index prefix,\n * or null when no index matches.\n *\n * The \"best\" index is the one whose prefix has the most consecutive fields\n * covered by the provided filters. For example, given filters for `thread_id`\n * and `createdAt` on mastra_messages, the composite `by_thread_created` index\n * (fields: [thread_id, createdAt]) is preferred over `by_thread` (fields: [thread_id]).\n */\nexport function findBestIndex(\n convexTable: string,\n filters: EqualityFilter[],\n): { indexName: string; indexedFilters: EqualityFilter[] } | null {\n const indexes = TABLE_INDEX_MAP[convexTable];\n if (!indexes || filters.length === 0) return null;\n\n const filtersByField = new Map<string, EqualityFilter>();\n for (const f of filters) {\n filtersByField.set(f.field, f);\n }\n\n let best: { indexName: string; indexedFilters: EqualityFilter[]; prefixLength: number } | null = null;\n\n for (const index of indexes) {\n let prefixLength = 0;\n const indexedFilters: EqualityFilter[] = [];\n\n for (const field of index.fields) {\n const filter = filtersByField.get(field);\n if (filter) {\n prefixLength++;\n indexedFilters.push(filter);\n } else {\n break;\n }\n }\n\n if (prefixLength > 0 && (!best || prefixLength > best.prefixLength)) {\n best = { indexName: index.name, indexedFilters, prefixLength };\n }\n }\n\n return best ? { indexName: best.indexName, indexedFilters: best.indexedFilters } : null;\n}\n","/**\n * Server-side observational memory operations for the generic Convex storage\n * mutation. All read-modify-write logic lives here so each operation is atomic\n * (Convex mutations are serializable transactions).\n *\n * Logic mirrors @mastra/core's in-memory reference implementation\n * (packages/core/src/storage/domains/memory/inmemory.ts) and the MongoDB\n * adapter. Pure helpers are exported for unit testing.\n *\n * This module is bundled into the user's Convex deployment: no Node.js APIs\n * and no value imports from @mastra/core.\n */\nimport type { GenericMutationCtx as MutationCtx } from 'convex/server';\n\nimport type { SerializedOMChunk, StorageRequest, StorageResponse } from '../storage/types';\n\ntype OMRequest = Extract<\n StorageRequest,\n {\n op:\n | 'omGetLatest'\n | 'omGetHistory'\n | 'omInitialize'\n | 'omCreateReflectionGeneration'\n | 'omSetPendingMessageTokens'\n | 'omSetBufferingObservationFlag'\n | 'omUpdateActive'\n | 'omAppendBufferedChunk'\n | 'omSwapBuffered'\n | 'omUpdateBufferedReflection'\n | 'omSwapBufferedReflection'\n | 'omUpdateConfig';\n }\n>;\n\nconst OM_QUERY_MAX_DOCS = 10000;\n\n/**\n * Parse the stored bufferedObservationChunks JSON string. Tolerates null,\n * missing, and malformed values by returning an empty array.\n */\nexport function parseStoredChunks(value: unknown): SerializedOMChunk[] {\n if (typeof value !== 'string' || !value) return [];\n try {\n const parsed = JSON.parse(value);\n return Array.isArray(parsed) ? parsed : [];\n } catch {\n return [];\n }\n}\n\n/**\n * Select how many buffered chunks to activate.\n *\n * Finds the chunk boundary closest to the activation target, biased over\n * (prefer removing slightly more than the target so remaining context lands at\n * or below the retention floor), with an overshoot safeguard that falls back\n * to the best under boundary. Ported from the core in-memory reference.\n */\nexport function selectActivationBoundary(\n chunks: Array<{ messageTokens?: number }>,\n opts: {\n activationRatio: number;\n messageTokensThreshold: number;\n currentPendingTokens: number;\n forceMaxActivation?: boolean;\n },\n): number {\n // Calculate target: how many message tokens to remove so that\n // (1 - activationRatio) * threshold worth of raw messages remain.\n // e.g., ratio=0.8, threshold=5000, pending=6000 → remove 6000 - 1000 = 5000\n const retentionFloor = opts.messageTokensThreshold * (1 - opts.activationRatio);\n const targetMessageTokens = Math.max(0, opts.currentPendingTokens - retentionFloor);\n\n // Track both best-over and best-under boundaries so we can fall back to\n // under if the over boundary would overshoot by too much.\n let cumulativeMessageTokens = 0;\n let bestOverBoundary = 0;\n let bestOverTokens = 0;\n let bestUnderBoundary = 0;\n let bestUnderTokens = 0;\n\n for (let i = 0; i < chunks.length; i++) {\n cumulativeMessageTokens += chunks[i]!.messageTokens ?? 0;\n const boundary = i + 1;\n\n if (cumulativeMessageTokens >= targetMessageTokens) {\n // Over or equal — track the closest (lowest) over boundary\n if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {\n bestOverBoundary = boundary;\n bestOverTokens = cumulativeMessageTokens;\n }\n } else {\n // Under — track the closest (highest) under boundary\n if (cumulativeMessageTokens > bestUnderTokens) {\n bestUnderBoundary = boundary;\n bestUnderTokens = cumulativeMessageTokens;\n }\n }\n }\n\n // Safeguard: if the over boundary would eat into more than 95% of the\n // retention floor, fall back to the best under boundary instead.\n // When forceMaxActivation is set (above blockAfter), still prefer the over\n // boundary, but never if it would leave fewer than the smaller of 1000\n // tokens or the retention floor remaining.\n const maxOvershoot = retentionFloor * 0.95;\n const overshoot = bestOverTokens - targetMessageTokens;\n const remainingAfterOver = opts.currentPendingTokens - bestOverTokens;\n const remainingAfterUnder = opts.currentPendingTokens - bestUnderTokens;\n // When activationRatio ≈ 1.0, retentionFloor is 0 and minRemaining becomes 0 — intentional for \"activate everything\" configs.\n const minRemaining = Math.min(1000, retentionFloor);\n\n if (opts.forceMaxActivation && bestOverBoundary > 0 && remainingAfterOver >= minRemaining) {\n return bestOverBoundary;\n }\n if (bestOverBoundary > 0 && overshoot <= maxOvershoot && remainingAfterOver >= minRemaining) {\n return bestOverBoundary;\n }\n if (bestUnderBoundary > 0 && remainingAfterUnder >= minRemaining) {\n return bestUnderBoundary;\n }\n if (bestOverBoundary > 0) {\n // All boundaries are over and exceed the safeguard — still activate\n // the closest over boundary (better than nothing)\n return bestOverBoundary;\n }\n return 1;\n}\n\n/**\n * Merge a buffered reflection with the observations added after the reflection\n * started. Lines 0..reflectedLineCount of activeObservations were reflected on\n * and are replaced by the reflection; later lines are appended as-is.\n */\nexport function mergeReflectionWithUnreflected(\n activeObservations: string,\n bufferedReflection: string,\n reflectedLineCount: number,\n): string {\n const allLines = (activeObservations || '').split('\\n');\n const unreflectedLines = allLines.slice(reflectedLineCount);\n const unreflectedContent = unreflectedLines.join('\\n').trim();\n return unreflectedContent ? `${bufferedReflection}\\n\\n${unreflectedContent}` : bufferedReflection;\n}\n\n// ---------------------------------------------------------------------------\n// Lifecycle rules. These mirror @mastra/core's shared observational memory\n// lifecycle helpers (packages/core/src/storage/domains/memory/observational-memory-lifecycle.ts),\n// which this bundle cannot import at runtime. A parity test keeps them identical.\n// ---------------------------------------------------------------------------\n\n/**\n * A buffered chunk stores `lastObservedAt = max message time + 1ms`; it is wholly covered by\n * the cursor iff `cursor >= chunk.lastObservedAt - 1ms`.\n */\nexport function isChunkCoveredByCursor(chunkLastObservedAt: string, cursor: string | null | undefined): boolean {\n if (!cursor) return false;\n return Date.parse(cursor) >= Date.parse(chunkLastObservedAt) - 1;\n}\n\n/** The later of two ISO cursors (`null` only when both are absent). */\nexport function maxCursor(a: string | null | undefined, b: string | null | undefined): string | null {\n if (!a) return b ?? null;\n if (!b) return a;\n return Date.parse(b) > Date.parse(a) ? b : a;\n}\n\n/**\n * New-generation text for a reflection built from `snapshot`: the reflection when the stored\n * text equals the snapshot; the reflection plus the appended tail when the stored text only\n * extends it; `null` (do not apply) after a non-append rewrite.\n */\nexport function planReflectionText(input: {\n storedObservations: string;\n storedObservationTokenCount: number;\n snapshotObservations: string;\n snapshotObservationTokenCount: number;\n reflection: string;\n tokenCount: number;\n}): { observations: string; tokenCount: number } | null {\n const stored = input.storedObservations ?? '';\n const snapshot = input.snapshotObservations ?? '';\n if (stored === snapshot) return { observations: input.reflection, tokenCount: input.tokenCount };\n if (!stored.startsWith(snapshot)) return null;\n const tail = stored.slice(snapshot.length).trimStart();\n if (!tail.trim()) return { observations: input.reflection, tokenCount: input.tokenCount };\n return {\n observations: input.reflection ? `${input.reflection}\\n\\n${tail}` : tail,\n tokenCount:\n input.tokenCount +\n Math.max(0, (input.storedObservationTokenCount ?? 0) - (input.snapshotObservationTokenCount ?? 0)),\n };\n}\n\n/** Whether the stored text equals or only extends the snapshot. */\nexport function isAppendOnly(storedObservations: string, snapshotObservations: string): boolean {\n const stored = storedObservations ?? '';\n const snapshot = snapshotObservations ?? '';\n return stored === snapshot || stored.startsWith(snapshot);\n}\n\ntype OMDoc = Record<string, any> & { _id: any };\n\n/** Canonical head order: generationCount DESC, createdAt ASC, id ASC. */\nfunction sortsBeforeAsHead(a: OMDoc, b: OMDoc): boolean {\n if (a.generationCount !== b.generationCount) return a.generationCount > b.generationCount;\n if (a.createdAt !== b.createdAt) return Date.parse(a.createdAt) < Date.parse(b.createdAt);\n return a.id < b.id;\n}\n\n/**\n * The canonical head of a lookup key. `by_lookup_key` orders ties by `_creationTime`, so when\n * the top two share a generation all tied rows are read and the canonical order picks one.\n */\nasync function getCanonicalHead(ctx: MutationCtx<any>, convexTable: string, lookupKey: string): Promise<OMDoc | null> {\n const top = (await ctx.db\n .query(convexTable)\n .withIndex('by_lookup_key', (q: any) => q.eq('lookupKey', lookupKey))\n .order('desc')\n .take(2)) as OMDoc[];\n if (top.length === 0) return null;\n if (top.length === 1 || top[1]!.generationCount !== top[0]!.generationCount) return top[0]!;\n const tied = (await ctx.db\n .query(convexTable)\n .withIndex('by_lookup_key', (q: any) => q.eq('lookupKey', lookupKey).eq('generationCount', top[0]!.generationCount))\n .collect()) as OMDoc[];\n return tied.reduce((best, doc) => (sortsBeforeAsHead(doc, best) ? doc : best));\n}\n\ntype Target = { kind: 'missing' } | { kind: 'live'; doc: OMDoc } | { kind: 'retired'; doc: OMDoc; head: OMDoc | null };\n\n/**\n * Liveness of the record a lifecycle write names. A record with `supersededBy` set is retired.\n * A record that is unmarked but is not its key's canonical head (left by an older adapter\n * version, which never set the marker) is marked superseded by the head here and treated as\n * retired, so a write never lands on it.\n */\nasync function resolveTarget(ctx: MutationCtx<any>, convexTable: string, id: string, now: string): Promise<Target> {\n const doc = (await findRecordById(ctx, convexTable, id)) as OMDoc | null;\n if (!doc) return { kind: 'missing' };\n const head = await getCanonicalHead(ctx, convexTable, doc.lookupKey);\n if (doc.supersededBy) return { kind: 'retired', doc, head };\n if (head && head.id !== doc.id) {\n await ctx.db.patch(doc._id, { supersededBy: head.id, updatedAt: now });\n return { kind: 'retired', doc, head };\n }\n return { kind: 'live', doc };\n}\n\n/** The live record a write aimed at `id` lands on (the head when `id` is retired). Throws when missing. */\nasync function resolveWriteTarget(ctx: MutationCtx<any>, convexTable: string, id: string, now: string): Promise<OMDoc> {\n const target = await resolveTarget(ctx, convexTable, id, now);\n if (target.kind === 'missing') return requireRecord(null, id);\n if (target.kind === 'live') return target.doc;\n if (!target.head) throw new Error(`Observational memory record ${id} is superseded but no live head was found`);\n return target.head;\n}\n\n/**\n * Create the next generation from the stored (live) record and retire it in the same mutation.\n * Buffered chunks move to the new generation; the cursor, buffering markers, flags, and\n * counters carry over; buffered reflection state does not.\n */\nasync function rollOver(\n ctx: MutationCtx<any>,\n convexTable: string,\n stored: OMDoc,\n args: { newId: string; observations: string; tokenCount: number; now: string; clearBufferedReflection: boolean },\n): Promise<Record<string, unknown>> {\n const newRecord = {\n id: args.newId,\n lookupKey: stored.lookupKey,\n scope: stored.scope,\n resourceId: stored.resourceId ?? null,\n threadId: stored.threadId ?? null,\n activeObservations: args.observations,\n activeObservationsPendingUpdate: null,\n originType: 'reflection',\n config: stored.config,\n generationCount: Number(stored.generationCount || 0) + 1,\n lastObservedAt: stored.lastObservedAt ?? null,\n lastReflectionAt: args.now,\n pendingMessageTokens: Number(stored.pendingMessageTokens || 0),\n totalTokensObserved: Number(stored.totalTokensObserved || 0),\n observationTokenCount: args.tokenCount,\n isObserving: false,\n isReflecting: false,\n bufferedObservationChunks: parseStoredChunks(stored.bufferedObservationChunks).length\n ? stored.bufferedObservationChunks\n : null,\n isBufferingObservation: Boolean(stored.isBufferingObservation),\n isBufferingReflection: false,\n lastBufferedAtTokens: Number(stored.lastBufferedAtTokens || 0),\n lastBufferedAtTime: stored.lastBufferedAtTime ?? null,\n observedTimezone: stored.observedTimezone ?? null,\n metadata: stored.metadata ?? null,\n supersededBy: null,\n createdAt: args.now,\n updatedAt: args.now,\n };\n await ctx.db.insert(convexTable, newRecord);\n await ctx.db.patch(stored._id, {\n supersededBy: args.newId,\n bufferedObservationChunks: null,\n ...(args.clearBufferedReflection\n ? {\n bufferedReflection: null,\n bufferedReflectionTokens: null,\n bufferedReflectionInputTokens: null,\n reflectedObservationLineCount: null,\n }\n : {}),\n updatedAt: args.now,\n });\n return newRecord;\n}\n\nfunction isPlainObj(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Deep-merge two plain config objects (source wins; undefined source values\n * are skipped). Mirrors MemoryStorage.deepMergeConfig in @mastra/core.\n */\nexport function deepMergeOMConfig(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n): Record<string, unknown> {\n const output: Record<string, unknown> = { ...target };\n for (const key of Object.keys(source)) {\n const tVal = target[key];\n const sVal = source[key];\n if (isPlainObj(tVal) && isPlainObj(sVal)) {\n output[key] = deepMergeOMConfig(tVal, sVal);\n } else if (sVal !== undefined) {\n output[key] = sVal;\n }\n }\n return output;\n}\n\nfunction parseJsonObject(value: unknown): Record<string, unknown> {\n if (typeof value !== 'string' || !value) return {};\n try {\n const parsed = JSON.parse(value);\n return isPlainObj(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nasync function findRecordById(ctx: MutationCtx<any>, convexTable: string, id: string) {\n return await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique();\n}\n\nfunction requireRecord(doc: unknown, id: string) {\n if (!doc) {\n throw new Error(`Observational memory record not found: ${id}`);\n }\n return doc as Record<string, any> & { _id: any };\n}\n\nconst EMPTY_SWAP_RESULT = {\n chunksActivated: 0,\n messageTokensActivated: 0,\n observationTokensActivated: 0,\n messagesActivated: 0,\n activatedCycleIds: [] as string[],\n activatedMessageIds: [] as string[],\n};\n\nexport async function handleObservationalMemoryOperation(\n ctx: MutationCtx<any>,\n convexTable: string,\n request: OMRequest,\n): Promise<StorageResponse> {\n switch (request.op) {\n case 'omGetLatest': {\n return { ok: true, result: await getCanonicalHead(ctx, convexTable, request.lookupKey) };\n }\n\n case 'omInitialize': {\n // One serializable mutation: concurrent initializations of a key create one record.\n const existing = await getCanonicalHead(ctx, convexTable, request.record.lookupKey);\n if (existing) return { ok: true, result: existing };\n await ctx.db.insert(convexTable, { ...request.record, supersededBy: null });\n return { ok: true, result: { ...request.record, supersededBy: null } };\n }\n\n case 'omCreateReflectionGeneration': {\n const { currentRecord, newId, reflection, tokenCount, now } = request;\n const target = await resolveTarget(ctx, convexTable, currentRecord.id, now);\n // Missing target: create nothing (the client returns its snapshot).\n if (target.kind === 'missing') return { ok: true, result: null };\n // A retired snapshot creates nothing; the caller adopts the head.\n if (target.kind === 'retired') return { ok: true, result: target.head };\n const stored = target.doc;\n const plan = planReflectionText({\n storedObservations: (stored.activeObservations as string) || '',\n storedObservationTokenCount: Number(stored.observationTokenCount || 0),\n snapshotObservations: currentRecord.activeObservations ?? '',\n snapshotObservationTokenCount: currentRecord.observationTokenCount ?? 0,\n reflection,\n tokenCount,\n });\n // The text was rewritten (not only appended to) since the snapshot: the reflection is stale.\n if (!plan) return { ok: true, result: stored };\n const newRecord = await rollOver(ctx, convexTable, stored, {\n newId,\n observations: plan.observations,\n tokenCount: plan.tokenCount,\n now,\n clearBufferedReflection: false,\n });\n return { ok: true, result: newRecord };\n }\n\n case 'omSetPendingMessageTokens': {\n const doc = await resolveWriteTarget(ctx, convexTable, request.id, request.updatedAt);\n await ctx.db.patch(doc._id, { pendingMessageTokens: request.tokenCount, updatedAt: request.updatedAt });\n return { ok: true };\n }\n\n case 'omSetBufferingObservationFlag': {\n const doc = await resolveWriteTarget(ctx, convexTable, request.id, request.updatedAt);\n await ctx.db.patch(doc._id, {\n isBufferingObservation: request.isBuffering,\n ...(request.lastBufferedAtTokens !== undefined ? { lastBufferedAtTokens: request.lastBufferedAtTokens } : {}),\n updatedAt: request.updatedAt,\n });\n return { ok: true };\n }\n\n case 'omGetHistory': {\n let docs =\n request.recordId !== undefined\n ? [await findRecordById(ctx, convexTable, request.recordId)].filter(\n (doc: any) => doc?.lookupKey === request.lookupKey,\n )\n : await ctx.db\n .query(convexTable)\n .withIndex('by_lookup_key', (q: any) => {\n // Bound generations in the index so the row cap applies to the requested range and direction.\n let range = q.eq('lookupKey', request.lookupKey);\n if (request.afterGeneration !== undefined) range = range.gt('generationCount', request.afterGeneration);\n if (request.beforeGeneration !== undefined)\n range = range.lt('generationCount', request.beforeGeneration);\n return range;\n })\n .order(request.sortDirection === 'ASC' ? 'asc' : 'desc')\n .take(OM_QUERY_MAX_DOCS);\n\n // createdAt is a UTC ISO string, so lexicographic comparison is chronological.\n if (request.from) {\n docs = docs.filter((doc: any) => typeof doc.createdAt === 'string' && doc.createdAt >= request.from!);\n }\n if (request.to) {\n docs = docs.filter((doc: any) => typeof doc.createdAt === 'string' && doc.createdAt <= request.to!);\n }\n if (request.groupId !== undefined) {\n const prefix = `<observation-group id=\"${request.groupId}\"`;\n docs = docs.filter(\n (doc: any) =>\n (typeof doc.activeObservations === 'string' && doc.activeObservations.includes(prefix)) ||\n parseStoredChunks(doc.bufferedObservationChunks).some(chunk => chunk.observations.includes(prefix)),\n );\n }\n if (request.beforeGeneration !== undefined) {\n docs = docs.filter((doc: any) => doc.generationCount < request.beforeGeneration!);\n }\n if (request.afterGeneration !== undefined) {\n docs = docs.filter((doc: any) => doc.generationCount > request.afterGeneration!);\n }\n const direction = request.sortDirection === 'ASC' ? 1 : -1;\n docs.sort(\n (a: any, b: any) =>\n direction * (a.generationCount - b.generationCount) ||\n a.createdAt.localeCompare(b.createdAt) ||\n a.id.localeCompare(b.id),\n );\n if (request.offset != null) {\n docs = docs.slice(request.offset);\n }\n return { ok: true, result: docs.slice(0, request.limit) };\n }\n\n case 'omUpdateActive': {\n const target = await resolveTarget(ctx, convexTable, request.id, request.updatedAt);\n if (target.kind === 'missing') requireRecord(null, request.id);\n if (target.kind !== 'live') return { ok: true, result: { applied: false, reason: 'retired' } };\n const doc = target.doc;\n if (\n request.expectedActiveObservations !== undefined &&\n request.expectedActiveObservations !== ((doc.activeObservations as string) || '')\n ) {\n return { ok: true, result: { applied: false, reason: 'conflict' } };\n }\n const safeTokenCount = Number.isFinite(request.tokenCount) && request.tokenCount >= 0 ? request.tokenCount : 0;\n\n await ctx.db.patch(doc._id, {\n activeObservations: request.observations,\n // The cursor never moves backward.\n lastObservedAt: maxCursor(doc.lastObservedAt, request.lastObservedAt),\n // Reset pending tokens since we've now observed them\n pendingMessageTokens: 0,\n observationTokenCount: safeTokenCount,\n totalTokensObserved: Number(doc.totalTokensObserved || 0) + safeTokenCount,\n observedMessageIds: request.observedMessageIds,\n updatedAt: request.updatedAt,\n });\n return { ok: true, result: { applied: true } };\n }\n\n case 'omAppendBufferedChunk': {\n // A retired id is redirected to the head.\n const doc = await resolveWriteTarget(ctx, convexTable, request.id, request.updatedAt);\n const chunks = parseStoredChunks(doc.bufferedObservationChunks);\n // Skip a retried append (same cycle) and a chunk the cursor already wholly covers.\n if (\n chunks.some(chunk => chunk.cycleId === request.chunk.cycleId) ||\n isChunkCoveredByCursor(request.chunk.lastObservedAt, doc.lastObservedAt)\n ) {\n return { ok: true, result: { persisted: false, recordId: doc.id } };\n }\n chunks.push(request.chunk);\n\n await ctx.db.patch(doc._id, {\n bufferedObservationChunks: JSON.stringify(chunks),\n // lastBufferedAtTime never moves backward.\n lastBufferedAtTime: maxCursor(doc.lastBufferedAtTime, request.lastBufferedAtTime),\n updatedAt: request.updatedAt,\n });\n return { ok: true, result: { persisted: true, recordId: doc.id } };\n }\n\n case 'omSwapBuffered': {\n const target = await resolveTarget(ctx, convexTable, request.id, request.now);\n if (target.kind === 'missing') requireRecord(null, request.id);\n // A retired record is frozen: activation reports it and writes nothing.\n if (target.kind !== 'live') return { ok: true, result: { ...EMPTY_SWAP_RESULT, retired: true } };\n const doc = target.doc;\n\n // Activation always works on the stored list, so a chunk appended after the caller read\n // the record is never dropped. Caller-provided chunks only override token weights.\n const refreshedWeights = new Map((request.bufferedChunks ?? []).map(chunk => [chunk.id, chunk.messageTokens]));\n const storedChunks = parseStoredChunks(doc.bufferedObservationChunks);\n const chunks = storedChunks.map(chunk => {\n const weight = refreshedWeights.get(chunk.id);\n return weight === undefined ? chunk : { ...chunk, messageTokens: weight };\n });\n // Nothing buffered (or already swapped) — report zero activation.\n if (chunks.length === 0) {\n return { ok: true, result: EMPTY_SWAP_RESULT };\n }\n\n const chunksToActivate = selectActivationBoundary(chunks, {\n activationRatio: request.activationRatio,\n messageTokensThreshold: request.messageTokensThreshold,\n currentPendingTokens: request.currentPendingTokens,\n forceMaxActivation: request.forceMaxActivation,\n });\n const activatedChunks = chunks.slice(0, chunksToActivate);\n const remainingChunks = storedChunks.slice(chunksToActivate);\n\n // Combine activated chunks into content\n const activatedContent = activatedChunks.map(c => c.observations).join('\\n\\n');\n const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);\n const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);\n const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + (c.messageIds?.length ?? 0), 0);\n const activatedCycleIds = activatedChunks.map(c => c.cycleId).filter((id): id is string => !!id);\n const activatedMessageIds = activatedChunks.flatMap(c => c.messageIds ?? []);\n\n // Derive lastObservedAt from the latest activated chunk, or use provided value\n const latestChunk = activatedChunks[activatedChunks.length - 1];\n const lastObservedAt = request.lastObservedAt ?? latestChunk?.lastObservedAt ?? request.now;\n\n // Append activated content to active observations with message boundary for cache stability\n const existingActive = (doc.activeObservations as string) || '';\n const boundary = `\\n\\n--- message boundary (${lastObservedAt}) ---\\n\\n`;\n const newActive = existingActive ? `${existingActive}${boundary}${activatedContent}` : activatedContent;\n\n // NOTE: We intentionally do NOT add activatedMessageIds to observedMessageIds.\n // observedMessageIds is used by getUnobservedMessages to filter future messages.\n // Since AI SDK may reuse message IDs for new content, adding them here would\n // permanently block new content from being observed. Instead, we return\n // activatedMessageIds so the caller can remove them from messageList directly.\n\n await ctx.db.patch(doc._id, {\n activeObservations: newActive,\n observationTokenCount: Number(doc.observationTokenCount || 0) + activatedTokens,\n // Decrement pending message tokens (clamped to zero)\n pendingMessageTokens: Math.max(0, Number(doc.pendingMessageTokens || 0) - activatedMessageTokens),\n bufferedObservationChunks: remainingChunks.length > 0 ? JSON.stringify(remainingChunks) : null,\n // The stored cursor never moves backward (a sync observation may already be past this chunk).\n lastObservedAt: maxCursor(doc.lastObservedAt, lastObservedAt),\n updatedAt: request.now,\n });\n\n // Use hints from the most recent activated chunk only — stale hints from older chunks are discarded\n const latestChunkHints = activatedChunks[activatedChunks.length - 1];\n\n return {\n ok: true,\n result: {\n chunksActivated: activatedChunks.length,\n messageTokensActivated: activatedMessageTokens,\n observationTokensActivated: activatedTokens,\n messagesActivated: activatedMessageCount,\n activatedCycleIds,\n activatedMessageIds,\n observations: activatedContent,\n perChunk: activatedChunks.map(c => ({\n cycleId: c.cycleId ?? '',\n messageTokens: c.messageTokens ?? 0,\n observationTokens: c.tokenCount,\n messageCount: c.messageIds?.length ?? 0,\n observations: c.observations,\n })),\n suggestedContinuation: latestChunkHints?.suggestedContinuation ?? undefined,\n currentTask: latestChunkHints?.currentTask ?? undefined,\n },\n };\n }\n\n case 'omUpdateBufferedReflection': {\n const doc = requireRecord(await findRecordById(ctx, convexTable, request.id), request.id);\n\n const existingContent = (doc.bufferedReflection as string) || '';\n await ctx.db.patch(doc._id, {\n bufferedReflection: existingContent ? `${existingContent}\\n\\n${request.reflection}` : request.reflection,\n bufferedReflectionTokens: Number(doc.bufferedReflectionTokens || 0) + request.tokenCount,\n bufferedReflectionInputTokens: Number(doc.bufferedReflectionInputTokens || 0) + request.inputTokenCount,\n reflectedObservationLineCount: request.reflectedObservationLineCount,\n updatedAt: request.updatedAt,\n });\n return { ok: true };\n }\n\n case 'omSwapBufferedReflection': {\n const { currentRecord, newId, tokenCount, now } = request;\n const target = await resolveTarget(ctx, convexTable, currentRecord.id, now);\n // Missing target: create nothing (the client returns its snapshot).\n if (target.kind === 'missing') return { ok: true, result: null };\n // A retired snapshot creates nothing; the caller adopts the head.\n if (target.kind === 'retired') return { ok: true, result: target.head };\n const stored = target.doc;\n\n const bufferedReflection = (stored.bufferedReflection as string) || '';\n if (!bufferedReflection) {\n throw new Error('No buffered reflection to swap');\n }\n const storedObservations = (stored.activeObservations as string) || '';\n // Only appends may have happened since the caller's snapshot; a rewrite invalidates the\n // reflected line count.\n if (!isAppendOnly(storedObservations, currentRecord.activeObservations ?? '')) {\n return { ok: true, result: stored };\n }\n\n const newObservations = mergeReflectionWithUnreflected(\n storedObservations,\n bufferedReflection,\n Number(stored.reflectedObservationLineCount || 0),\n );\n // tokenCount is computed by the processor from its snapshot; add tokens appended since.\n const carriedTokenCount =\n tokenCount +\n Math.max(0, Number(stored.observationTokenCount || 0) - (currentRecord.observationTokenCount ?? 0));\n\n const newRecord = await rollOver(ctx, convexTable, stored, {\n newId,\n observations: newObservations,\n tokenCount: carriedTokenCount,\n now,\n clearBufferedReflection: true,\n });\n return { ok: true, result: newRecord };\n }\n\n case 'omUpdateConfig': {\n const doc = requireRecord(await findRecordById(ctx, convexTable, request.id), request.id);\n\n const existing = parseJsonObject(doc.config);\n const incoming = parseJsonObject(request.config);\n const merged = deepMergeOMConfig(existing, incoming);\n\n await ctx.db.patch(doc._id, {\n config: JSON.stringify(merged),\n updatedAt: request.updatedAt,\n });\n return { ok: true };\n }\n }\n}\n","import type { GenericMutationCtx as MutationCtx } from 'convex/server';\nimport type { GenericId } from 'convex/values';\n\nimport type {\n RunClaimFence,\n RunClaimRequest,\n RunClaimResult,\n RunClaimTable,\n StorageRequest,\n StorageResponse,\n StoredRunClaim,\n} from '../storage/types';\n\n// Same value as core's RUN_FENCE_CONFLICT_ERROR_ID, which the client maps back\n// to RunFenceConflictError.\nexport const RUN_FENCE_CONFLICT_CODE = 'STORAGE_RUN_FENCE_CONFLICT';\n\nconst RUN_CLAIM_OPS = new Set<string>([\n 'claimRunOwnership',\n 'renewRunOwnership',\n 'releaseRunOwnership',\n 'getRunOwnership',\n 'raiseRunFence',\n 'retireRunFence',\n 'pruneRunClaims',\n 'fenced',\n]);\nconst RUN_CLAIM_TABLES = new Set<string>(['mastra_workflow_run_owners', 'mastra_memory_run_fences']);\nconst CLAIMS_TABLE = 'mastra_documents';\n\ntype ClaimDoc = { _id: GenericId<string>; record: StoredRunClaim };\n\nexport function isRunClaimRequest(request: StorageRequest | RunClaimRequest): request is RunClaimRequest {\n return RUN_CLAIM_OPS.has(request.op);\n}\n\nasync function findClaim(ctx: MutationCtx<any>, table: RunClaimTable, runId: string): Promise<ClaimDoc | null> {\n return ctx.db\n .query(CLAIMS_TABLE)\n .withIndex('by_table_primary', (q: any) => q.eq('table', table).eq('primaryKey', runId))\n .unique();\n}\n\nasync function writeClaim(\n ctx: MutationCtx<any>,\n table: RunClaimTable,\n doc: ClaimDoc | null,\n claim: StoredRunClaim,\n): Promise<StoredRunClaim> {\n const record = { id: claim.runId, ...claim };\n if (doc) {\n await ctx.db.patch(doc._id, { record });\n } else {\n await ctx.db.insert(CLAIMS_TABLE, { table, primaryKey: claim.runId, record });\n }\n return claim;\n}\n\nfunction holds(claim: StoredRunClaim | null, fence: RunClaimFence): claim is StoredRunClaim {\n return claim !== null && claim.generation === fence.generation && claim.ownerId === fence.ownerId;\n}\n\nfunction reply(applied: boolean, claim: StoredRunClaim | null, now: number): StorageResponse {\n const result: RunClaimResult = { applied, claim, now };\n return { ok: true, result };\n}\n\n/**\n * Runs a run fencing operation. Each reads and writes the run's claim in the\n * calling mutation, so Convex serializes it against every other claim\n * operation and fenced write on the same run. Leases are measured on the\n * mutation's clock.\n *\n * `route` runs the request a fenced operation wraps.\n */\nexport async function handleRunClaimOperation(\n ctx: MutationCtx<any>,\n request: RunClaimRequest,\n route: (ctx: MutationCtx<any>, request: StorageRequest) => Promise<StorageResponse>,\n): Promise<StorageResponse> {\n if (!RUN_CLAIM_TABLES.has(request.tableName)) {\n return { ok: false, error: `Unsupported run claim table ${request.tableName}` };\n }\n const now = Date.now();\n\n switch (request.op) {\n case 'claimRunOwnership': {\n const { tableName, runId, ownerId, leaseMs, force, expectedGeneration } = request;\n const doc = await findClaim(ctx, tableName, runId);\n const current = doc?.record ?? null;\n const leaseExpiresAt = now + leaseMs;\n if (!current) {\n if (expectedGeneration !== undefined && expectedGeneration !== 0) return reply(false, null, now);\n // The first generation comes from the clock, so a claim after this\n // claim is pruned still outranks a surviving fence.\n const claim = { runId, generation: Math.max(1, now), ownerId, leaseExpiresAt, updatedAt: now };\n return reply(true, await writeClaim(ctx, tableName, doc, claim), now);\n }\n if (expectedGeneration !== undefined && current.generation !== expectedGeneration) {\n return reply(false, current, now);\n }\n if (!force && current.leaseExpiresAt !== null && current.leaseExpiresAt > now) {\n return reply(false, current, now);\n }\n const claim = { runId, generation: current.generation + 1, ownerId, leaseExpiresAt, updatedAt: now };\n return reply(true, await writeClaim(ctx, tableName, doc, claim), now);\n }\n\n case 'renewRunOwnership': {\n const { tableName, fence, leaseMs } = request;\n const doc = await findClaim(ctx, tableName, fence.runId);\n const current = doc?.record ?? null;\n if (!holds(current, fence) || current.leaseExpiresAt === null) return reply(false, current, now);\n const claim = { ...current, leaseExpiresAt: now + leaseMs, updatedAt: now };\n return reply(true, await writeClaim(ctx, tableName, doc, claim), now);\n }\n\n case 'releaseRunOwnership': {\n const { tableName, fence } = request;\n const doc = await findClaim(ctx, tableName, fence.runId);\n const current = doc?.record ?? null;\n if (!holds(current, fence)) return reply(false, current, now);\n return reply(\n true,\n await writeClaim(ctx, tableName, doc, { ...current, leaseExpiresAt: null, updatedAt: now }),\n now,\n );\n }\n\n case 'getRunOwnership': {\n const doc = await findClaim(ctx, request.tableName, request.runId);\n return reply(true, doc?.record ?? null, now);\n }\n\n case 'raiseRunFence': {\n const { tableName, fence } = request;\n const doc = await findClaim(ctx, tableName, fence.runId);\n const current = doc?.record ?? null;\n // Raises an older fence, reaffirms our own, or creates a missing one.\n // Every write un-retires the fence.\n if (!current || current.generation < fence.generation || holds(current, fence)) {\n const claim = { ...fence, leaseExpiresAt: null, retiredAt: null };\n return reply(true, await writeClaim(ctx, tableName, doc, claim), now);\n }\n return reply(false, current, now);\n }\n\n case 'retireRunFence': {\n const { tableName, fence } = request;\n const doc = await findClaim(ctx, tableName, fence.runId);\n const current = doc?.record ?? null;\n if (!holds(current, fence)) return reply(false, current, now);\n return reply(true, await writeClaim(ctx, tableName, doc, { ...current, retiredAt: now }), now);\n }\n\n case 'pruneRunClaims': {\n const { tableName, column, cutoff, limit } = request;\n // A null or missing anchor sorts below every number, so require it to be set.\n const docs: ClaimDoc[] = await ctx.db\n .query(CLAIMS_TABLE)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName))\n .filter((q: any) => q.and(q.gt(q.field(`record.${column}`), null), q.lt(q.field(`record.${column}`), cutoff)))\n .take(limit);\n for (const doc of docs) await ctx.db.delete(doc._id);\n return { ok: true, result: docs.length };\n }\n\n case 'fenced': {\n const { tableName, fence, request: inner } = request;\n const doc = await findClaim(ctx, tableName, fence.runId);\n if (!holds(doc?.record ?? null, fence)) {\n return {\n ok: false,\n error: `Run ${fence.runId} is no longer claimed by generation ${fence.generation} of ${fence.ownerId}`,\n code: RUN_FENCE_CONFLICT_CODE,\n };\n }\n if (!inner) return { ok: true };\n if (RUN_CLAIM_OPS.has(inner.op)) {\n return { ok: false, error: `Unsupported fenced operation ${inner.op}` };\n }\n return route(ctx, inner);\n }\n }\n}\n","// NOTE: This mirrors packages/core/src/storage/workflow-snapshot.ts. The Convex\n// server runtime can't import @mastra/core, so keep both copies in sync.\nconst PENDING_MARKER_KEY = '__mastra_pending__';\n\nfunction isPendingMarker(val: unknown): boolean {\n return (\n val !== null &&\n typeof val === 'object' &&\n Object.prototype.hasOwnProperty.call(val, PENDING_MARKER_KEY) &&\n (val as Record<string, unknown>)[PENDING_MARKER_KEY] === true &&\n Object.keys(val).length === 1\n );\n}\n\n// Suspended forEach iteration results may come from multiple engines. Treat\n// StepResult-shaped suspended entries as resettable without relying only on\n// evented __workflow_meta, but avoid matching plain user outputs with only\n// status/payload fields.\nfunction isSuspendedStepResult(val: unknown): boolean {\n const result = val as Record<string, unknown> | null;\n\n return (\n val !== null &&\n typeof val === 'object' &&\n 'status' in val &&\n result?.status === 'suspended' &&\n ('suspendPayload' in val || 'suspendedAt' in val)\n );\n}\n\nfunction canResetWithPendingMarker(val: unknown): boolean {\n if (val == null || isPendingMarker(val)) {\n return true;\n }\n\n return isSuspendedStepResult(val);\n}\n\nexport function createEmptyWorkflowSnapshot(runId: string): Record<string, any> {\n return {\n context: {},\n activePaths: [],\n activeStepsPath: {},\n timestamp: Date.now(),\n suspendedPaths: {},\n resumeLabels: {},\n serializedStepGraph: [],\n value: {},\n waitingPaths: {},\n status: 'pending',\n runId,\n };\n}\n\nexport function mergeWorkflowStepResult({\n snapshot,\n stepId,\n result,\n requestContext,\n state,\n}: {\n snapshot: Record<string, any>;\n stepId: string;\n result: Record<string, any>;\n requestContext: Record<string, any>;\n state?: Record<string, any>;\n}): Record<string, any> {\n if (!snapshot?.context) {\n throw new Error(`Snapshot context not found for runId ${snapshot?.runId}`);\n }\n\n const existingResult = snapshot.context[stepId];\n if (\n existingResult &&\n 'output' in existingResult &&\n Array.isArray(existingResult.output) &&\n result &&\n typeof result === 'object' &&\n 'output' in result &&\n Array.isArray(result.output)\n ) {\n const existingOutput = existingResult.output as unknown[];\n const newOutput = result.output as unknown[];\n const mergedOutput = [...existingOutput];\n const hasPendingMarker = newOutput.some(isPendingMarker);\n for (let i = 0; i < Math.max(existingOutput.length, newOutput.length); i++) {\n if (i < newOutput.length) {\n const newVal = newOutput[i];\n if (isPendingMarker(newVal)) {\n if (i >= existingOutput.length || canResetWithPendingMarker(existingOutput[i])) {\n mergedOutput[i] = null;\n }\n } else if (newVal !== null && newVal !== undefined && !hasPendingMarker) {\n mergedOutput[i] = newVal;\n } else if (i >= existingOutput.length) {\n mergedOutput[i] = null;\n }\n }\n }\n snapshot.context[stepId] = {\n ...existingResult,\n // Pending-marker writes are reset commands built from an earlier snapshot,\n // so keep existing step-level fields and ignore sibling values they carry.\n ...(hasPendingMarker ? {} : result),\n output: mergedOutput,\n };\n } else {\n snapshot.context[stepId] = result;\n }\n\n if (state !== undefined) {\n snapshot.context.__state = state;\n }\n\n snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };\n return JSON.parse(JSON.stringify(snapshot.context));\n}\n","import {\n TABLE_WORKFLOW_SNAPSHOT,\n TABLE_MESSAGES,\n TABLE_THREADS,\n TABLE_RESOURCES,\n TABLE_SCORERS,\n TABLE_SCHEDULES,\n TABLE_SCHEDULE_TRIGGERS,\n TABLE_CHANNEL_INSTALLATIONS,\n TABLE_CHANNEL_CONFIG,\n TABLE_BACKGROUND_TASKS,\n} from '@mastra/core/storage/constants';\nimport type { GenericMutationCtx as MutationCtx } from 'convex/server';\nimport { mutationGeneric } from 'convex/server';\nimport type { GenericId } from 'convex/values';\n\nimport type { EqualityFilter, RunClaimRequest, StorageRequest, StorageResponse } from '../storage/types';\nimport { findBestIndex } from './index-map';\nimport { handleObservationalMemoryOperation } from './observational-memory';\nimport { handleRunClaimOperation, isRunClaimRequest } from './run-fencing';\nimport { createEmptyWorkflowSnapshot, mergeWorkflowStepResult } from './workflow-snapshot';\n\n// Vector-specific table names (not in @mastra/core)\nconst TABLE_VECTOR_INDEXES = 'mastra_vector_indexes';\nconst VECTOR_TABLE_PREFIX = 'mastra_vector_';\nconst CONVEX_TABLE_WORKFLOW_SNAPSHOTS = 'mastra_workflow_snapshots';\nconst CONVEX_TABLE_BACKGROUND_TASKS = 'mastra_background_tasks';\nconst CONVEX_TABLE_DOCUMENTS = 'mastra_documents';\n// Defined locally (not imported from core) because this file is bundled into\n// the user's Convex deployment and older cores in the peer range may not\n// export the observational memory constants.\nconst CONVEX_TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\nconst STORAGE_MUTATION_BATCH_SIZE = 25;\n// Keep this in sync with ConvexDB's loadMany client chunk size. The low cap\n// bounds full-doc responses per request; individual document size still matters.\nconst LOAD_MANY_MAX_IDS_PER_REQUEST = 10;\nconst DEFAULT_SCHEDULE_QUERY_LIMIT = 100;\n\ntype ConvexDocWithId = { _id: GenericId<string> };\ntype GenericDocumentDoc = ConvexDocWithId & { record: Record<string, unknown> };\ntype StorageRecord = Record<string, unknown> & { id?: unknown };\nconst BACKGROUND_TASK_FIELD_ALIASES: Record<string, string> = {\n tool_call_id: 'toolCallId',\n toolCallId: 'tool_call_id',\n tool_name: 'toolName',\n toolName: 'tool_name',\n agent_id: 'agentId',\n agentId: 'agent_id',\n run_id: 'runId',\n runId: 'run_id',\n thread_id: 'threadId',\n threadId: 'thread_id',\n resource_id: 'resourceId',\n resourceId: 'resource_id',\n suspend_payload: 'suspendPayload',\n suspendPayload: 'suspend_payload',\n retry_count: 'retryCount',\n retryCount: 'retry_count',\n max_retries: 'maxRetries',\n maxRetries: 'max_retries',\n timeout_ms: 'timeoutMs',\n timeoutMs: 'timeout_ms',\n};\n\nfunction normalizeScheduleQueryLimit(limit: number | undefined): number {\n if (limit == null || !Number.isFinite(limit)) return DEFAULT_SCHEDULE_QUERY_LIMIT;\n return Math.max(0, Math.floor(limit));\n}\n\nfunction normalizeLoadManyIds(ids: string[]): string[] {\n if (ids.length > LOAD_MANY_MAX_IDS_PER_REQUEST) {\n throw new Error(`loadMany supports at most ${LOAD_MANY_MAX_IDS_PER_REQUEST} ids per request`);\n }\n return [...new Set(ids)];\n}\n\nfunction applyConvexEqualityFilters(\n query: any,\n filters: EqualityFilter[] | undefined,\n indexedFields = new Set<string>(),\n) {\n const remainingFilters = filters?.filter(filter => !indexedFields.has(filter.field));\n if (!remainingFilters?.length) return query;\n\n return query.filter((q: any) => {\n const predicates = remainingFilters.map(filter => q.eq(q.field(filter.field), filter.value));\n return predicates.length === 1 ? predicates[0] : q.and(...predicates);\n });\n}\n\nasync function mapInBatches<TInput, TOutput>(\n inputs: TInput[],\n batchSize: number,\n mapper: (input: TInput) => Promise<TOutput>,\n): Promise<TOutput[]> {\n const results: TOutput[] = [];\n for (let index = 0; index < inputs.length; index += batchSize) {\n results.push(...(await Promise.all(inputs.slice(index, index + batchSize).map(mapper))));\n }\n return results;\n}\n\nasync function deleteDocs(ctx: MutationCtx<any>, docs: ConvexDocWithId[]): Promise<void> {\n await mapInBatches(docs, STORAGE_MUTATION_BATCH_SIZE, doc => ctx.db.delete(doc._id));\n}\n\nasync function findExistingDocsByIds(\n ids: string[],\n findDoc: (id: string) => Promise<ConvexDocWithId | null | undefined>,\n): Promise<ConvexDocWithId[]> {\n const docs = await mapInBatches([...new Set(ids)], STORAGE_MUTATION_BATCH_SIZE, findDoc);\n return docs.filter((doc): doc is ConvexDocWithId => Boolean(doc));\n}\n\nfunction isBackgroundTasksTable(convexTable: string, request: StorageRequest): boolean {\n return convexTable === CONVEX_TABLE_BACKGROUND_TASKS && request.tableName === TABLE_BACKGROUND_TASKS;\n}\n\nfunction matchesFilters(record: Record<string, unknown>, filters: EqualityFilter[]): boolean {\n return filters.every(filter => {\n if (record[filter.field] === filter.value) return true;\n const alternateField = BACKGROUND_TASK_FIELD_ALIASES[filter.field];\n return alternateField ? record[alternateField] === filter.value : false;\n });\n}\n\nfunction mergeLegacyRecord(record: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {\n const merged = { ...record };\n for (const [field, value] of Object.entries(patch)) {\n const alternateField = BACKGROUND_TASK_FIELD_ALIASES[field];\n if (alternateField) delete merged[alternateField];\n merged[field] = value;\n }\n return merged;\n}\n\nfunction stripPatchKeys(record: Record<string, unknown>, keys: string[]): Record<string, unknown> {\n const stripped = { ...record };\n for (const key of keys) delete stripped[key];\n return stripped;\n}\n\nfunction dedupeByRecordId(records: any[]): any[] {\n const seen = new Set<string>();\n return records.filter(record => {\n if (record?.id == null) return true;\n\n const id = String(record.id);\n if (seen.has(id)) return false;\n seen.add(id);\n return true;\n });\n}\n\nfunction isMissingBackgroundTaskSchemaError(error: unknown): boolean {\n const message = error instanceof Error ? error.message.toLowerCase() : String(error).toLowerCase();\n return (\n message.includes(CONVEX_TABLE_BACKGROUND_TASKS) &&\n (message.includes('does not exist') ||\n message.includes('not found') ||\n message.includes('not defined') ||\n message.includes('no such'))\n );\n}\n\nasync function findGenericDocumentById(\n ctx: MutationCtx<any>,\n tableName: string,\n id: string,\n): Promise<GenericDocumentDoc | null> {\n return await ctx.db\n .query(CONVEX_TABLE_DOCUMENTS)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName).eq('primaryKey', String(id)))\n .unique();\n}\n\nasync function findGenericDocumentsByTable(\n ctx: MutationCtx<any>,\n tableName: string,\n limit: number,\n): Promise<GenericDocumentDoc[]> {\n return await ctx.db\n .query(CONVEX_TABLE_DOCUMENTS)\n .withIndex('by_table', (q: any) => q.eq('table', tableName))\n .take(limit);\n}\n\nasync function filterLegacyRecordsWithoutTypedCopy(\n ctx: MutationCtx<any>,\n convexTable: string,\n legacyRecords: Record<string, unknown>[],\n): Promise<Record<string, unknown>[]> {\n const records = await mapInBatches(legacyRecords, STORAGE_MUTATION_BATCH_SIZE, async record => {\n if (record.id == null) return record;\n\n const typedDoc = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', String(record.id)))\n .unique();\n return typedDoc ? null : record;\n });\n\n return records.filter((record): record is Record<string, unknown> => Boolean(record));\n}\n\nfunction coalesceTypedRecordsForBatchInsert(records: StorageRecord[]): StorageRecord[] {\n const recordsById = new Map<string, StorageRecord>();\n for (const record of records) {\n const id = record.id;\n if (!id) continue;\n\n const key = String(id);\n recordsById.set(key, { ...(recordsById.get(key) ?? {}), ...record });\n }\n return [...recordsById.values()];\n}\n\n/**\n * Builds the patch for an upsert over an existing row.\n *\n * `id` is dropped because it is already set on the stored document.\n *\n * For workflow snapshots, `createdAt` is dropped as well so the stored creation\n * time survives. A snapshot is written repeatedly over the life of a run, and\n * callers cannot supply a trustworthy `createdAt` on a later save: a request\n * that read the row before another writer inserted it would carry its own\n * timestamp and overwrite the real one. patch() is a partial update, so leaving\n * the key out preserves whatever was stored on first insert. This mirrors the\n * SQL adapters, whose ON CONFLICT DO UPDATE omits createdAt from the SET list.\n *\n * Other tables keep their existing behaviour of writing the incoming createdAt.\n */\nfunction buildUpsertPatch(convexTable: string, record: StorageRecord): StorageRecord {\n const { id: _id, ...updateData } = record;\n if (convexTable === CONVEX_TABLE_WORKFLOW_SNAPSHOTS) {\n const { createdAt: _createdAt, ...withoutCreatedAt } = updateData;\n return withoutCreatedAt;\n }\n return updateData;\n}\n\nfunction coalesceLastRecordById(records: StorageRecord[]): StorageRecord[] {\n const recordsById = new Map<string, StorageRecord>();\n for (const record of records) {\n const id = record.id;\n if (!id) continue;\n recordsById.set(String(id), record);\n }\n return [...recordsById.values()];\n}\n\n/**\n * Determines which Convex table to use based on the logical table name.\n * Returns the Convex table name and whether it's a typed table or fallback.\n */\nfunction resolveTable(tableName: string): { convexTable: string; isTyped: boolean } {\n switch (tableName) {\n case TABLE_THREADS:\n return { convexTable: 'mastra_threads', isTyped: true };\n case TABLE_MESSAGES:\n return { convexTable: 'mastra_messages', isTyped: true };\n case TABLE_RESOURCES:\n return { convexTable: 'mastra_resources', isTyped: true };\n case TABLE_WORKFLOW_SNAPSHOT:\n return { convexTable: CONVEX_TABLE_WORKFLOW_SNAPSHOTS, isTyped: true };\n case TABLE_SCORERS:\n return { convexTable: 'mastra_scorers', isTyped: true };\n case TABLE_SCHEDULES:\n return { convexTable: 'mastra_schedules', isTyped: true };\n case TABLE_SCHEDULE_TRIGGERS:\n return { convexTable: 'mastra_schedule_triggers', isTyped: true };\n case TABLE_CHANNEL_INSTALLATIONS:\n return { convexTable: 'mastra_channel_installations', isTyped: true };\n case TABLE_CHANNEL_CONFIG:\n return { convexTable: 'mastra_channel_config', isTyped: true };\n case TABLE_BACKGROUND_TASKS:\n return { convexTable: CONVEX_TABLE_BACKGROUND_TASKS, isTyped: true };\n case TABLE_VECTOR_INDEXES:\n return { convexTable: 'mastra_vector_indexes', isTyped: true };\n case CONVEX_TABLE_OBSERVATIONAL_MEMORY:\n return { convexTable: CONVEX_TABLE_OBSERVATIONAL_MEMORY, isTyped: true };\n default:\n // Check if it's a vector data table\n if (tableName.startsWith(VECTOR_TABLE_PREFIX)) {\n return { convexTable: 'mastra_vectors', isTyped: true };\n }\n // Fallback to generic documents table for unknown tables\n return { convexTable: 'mastra_documents', isTyped: false };\n }\n}\n\n/**\n * Main storage mutation handler.\n * Routes operations to the appropriate typed table.\n */\nexport const mastraStorage = mutationGeneric(\n async (ctx, request: StorageRequest | RunClaimRequest): Promise<StorageResponse> => {\n if (isRunClaimRequest(request)) {\n return handleRunClaimOperation(ctx, request, routeStorageRequest);\n }\n return routeStorageRequest(ctx, request);\n },\n);\n\nasync function routeStorageRequest(ctx: MutationCtx<any>, request: StorageRequest): Promise<StorageResponse> {\n try {\n const { convexTable, isTyped } = resolveTable(request.tableName);\n\n // Handle vector data tables specially (but NOT vector_indexes which is a typed table)\n if (request.tableName.startsWith(VECTOR_TABLE_PREFIX) && request.tableName !== TABLE_VECTOR_INDEXES) {\n return await handleVectorOperation(ctx, request);\n }\n\n // Handle typed tables\n if (isTyped) {\n if (isBackgroundTasksTable(convexTable, request)) {\n try {\n return await handleTypedOperation(ctx, convexTable, request);\n } catch (error) {\n if (!isMissingBackgroundTaskSchemaError(error)) throw error;\n return handleGenericOperation(ctx, request);\n }\n }\n return handleTypedOperation(ctx, convexTable, request);\n }\n\n // Fallback to generic table for unknown tables\n return handleGenericOperation(ctx, request);\n } catch (error) {\n const err = error as Error;\n return {\n ok: false,\n error: err.message,\n };\n }\n}\n\nfunction parseStoredSnapshot(stored: unknown, runId: string): Record<string, any> {\n if (typeof stored === 'string') return JSON.parse(stored);\n return JSON.parse(JSON.stringify(stored ?? createEmptyWorkflowSnapshot(runId)));\n}\n\nfunction parseMetadataForMerge(metadata: unknown): Record<string, unknown> {\n if (metadata == null) return {};\n if (typeof metadata === 'string') {\n try {\n const parsed = JSON.parse(metadata);\n return parseMetadataForMerge(parsed);\n } catch {\n return {};\n }\n }\n if (typeof metadata === 'object' && !Array.isArray(metadata)) {\n return metadata as Record<string, unknown>;\n }\n return {};\n}\n\nfunction mergeMetadata(existing: unknown, update: Record<string, unknown> | undefined): Record<string, unknown> {\n return {\n ...parseMetadataForMerge(existing),\n ...(update ?? {}),\n };\n}\n\n/**\n * Handle operations on typed tables (threads, messages, etc.)\n * Records are stored with their `id` field as a regular field (not _id).\n * We query by the `id` field to find/update records.\n */\nexport async function handleTypedOperation(\n ctx: MutationCtx<any>,\n convexTable: string,\n request: StorageRequest,\n): Promise<StorageResponse> {\n switch (request.op) {\n case 'omGetLatest':\n case 'omGetHistory':\n case 'omInitialize':\n case 'omCreateReflectionGeneration':\n case 'omSetPendingMessageTokens':\n case 'omSetBufferingObservationFlag':\n case 'omUpdateActive':\n case 'omAppendBufferedChunk':\n case 'omSwapBuffered':\n case 'omUpdateBufferedReflection':\n case 'omSwapBufferedReflection':\n case 'omUpdateConfig': {\n if (convexTable !== CONVEX_TABLE_OBSERVATIONAL_MEMORY) {\n throw new Error(`${request.op} is only supported for ${CONVEX_TABLE_OBSERVATIONAL_MEMORY}`);\n }\n return handleObservationalMemoryOperation(ctx, convexTable, request);\n }\n\n case 'createSchedule': {\n if (convexTable !== 'mastra_schedules') {\n throw new Error(`createSchedule is only supported for mastra_schedules`);\n }\n const record = request.record;\n const id = record.id;\n if (!id) {\n throw new Error(`Schedule is missing an id`);\n }\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique();\n\n if (existing) {\n throw new Error(`Schedule with id \"${id}\" already exists`);\n }\n\n await ctx.db.insert(convexTable, record);\n return { ok: true };\n }\n\n case 'recordScheduleTrigger': {\n if (convexTable !== 'mastra_schedule_triggers') {\n throw new Error(`recordScheduleTrigger is only supported for mastra_schedule_triggers`);\n }\n const record = request.record;\n const id = record.id;\n if (!id) {\n throw new Error(`Schedule trigger is missing an id`);\n }\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique();\n\n if (existing) {\n throw new Error(`Schedule trigger with id \"${id}\" already exists`);\n }\n\n await ctx.db.insert(convexTable, record);\n return { ok: true };\n }\n\n case 'listDueSchedules': {\n if (convexTable !== 'mastra_schedules') {\n throw new Error(`listDueSchedules is only supported for mastra_schedules`);\n }\n const query = ctx.db\n .query(convexTable)\n .withIndex('by_status_next_fire_at', (q: any) => q.eq('status', 'active').lte('next_fire_at', request.now));\n const docs = await query.take(normalizeScheduleQueryLimit(request.limit));\n return { ok: true, result: docs };\n }\n\n case 'updateScheduleNextFire': {\n if (convexTable !== 'mastra_schedules') {\n throw new Error(`updateScheduleNextFire is only supported for mastra_schedules`);\n }\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', request.id))\n .unique();\n\n if (!existing || existing.status !== 'active' || existing.next_fire_at !== request.expectedNextFireAt) {\n return { ok: true, result: false };\n }\n\n await ctx.db.patch(existing._id, {\n next_fire_at: request.newNextFireAt,\n last_fire_at: request.lastFireAt,\n last_run_id: request.lastRunId,\n updated_at: Date.now(),\n ...(request.newStatus ? { status: request.newStatus } : {}),\n });\n\n return { ok: true, result: true };\n }\n\n case 'updateSchedule': {\n if (convexTable !== 'mastra_schedules') {\n throw new Error(`updateSchedule is only supported for mastra_schedules`);\n }\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', request.id))\n .unique();\n\n if (!existing) {\n throw new Error(`Schedule ${request.id} not found`);\n }\n\n await ctx.db.patch(existing._id, request.patch);\n return { ok: true, result: { ...existing, ...request.patch } };\n }\n\n case 'listScheduleTriggers': {\n if (convexTable !== 'mastra_schedule_triggers') {\n throw new Error(`listScheduleTriggers is only supported for mastra_schedule_triggers`);\n }\n\n const query = ctx.db\n .query(convexTable)\n .withIndex('by_schedule_actual', (q: any) => {\n let builder = q.eq('schedule_id', request.scheduleId);\n if (request.fromActualFireAt != null) {\n builder = builder.gte('actual_fire_at', request.fromActualFireAt);\n }\n if (request.toActualFireAt != null) {\n builder = builder.lt('actual_fire_at', request.toActualFireAt);\n }\n return builder;\n })\n .order('desc');\n const docs = await query.take(normalizeScheduleQueryLimit(request.limit));\n return { ok: true, result: docs };\n }\n\n case 'deleteScheduleTriggers': {\n if (convexTable !== 'mastra_schedule_triggers') {\n throw new Error(`deleteScheduleTriggers is only supported for mastra_schedule_triggers`);\n }\n\n const docs = await ctx.db\n .query(convexTable)\n .withIndex('by_schedule_actual', (q: any) => q.eq('schedule_id', request.scheduleId))\n .take(STORAGE_MUTATION_BATCH_SIZE + 1);\n const hasMore = docs.length > STORAGE_MUTATION_BATCH_SIZE;\n const docsToDelete = hasMore ? docs.slice(0, STORAGE_MUTATION_BATCH_SIZE) : docs;\n\n await deleteDocs(ctx, docsToDelete);\n return { ok: true, hasMore };\n }\n\n case 'insert': {\n const record = request.record;\n const id = record.id;\n if (!id) {\n throw new Error(`Record is missing an id`);\n }\n\n // Find existing record by id field using index\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique();\n\n if (existing) {\n await ctx.db.patch(existing._id, buildUpsertPatch(convexTable, record));\n } else {\n // Insert new - include id as a regular field\n await ctx.db.insert(convexTable, record);\n }\n return { ok: true };\n }\n\n case 'batchInsert': {\n const records = coalesceTypedRecordsForBatchInsert(request.records);\n await mapInBatches(records, STORAGE_MUTATION_BATCH_SIZE, async record => {\n const id = record.id;\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique();\n\n if (existing) {\n await ctx.db.patch(existing._id, buildUpsertPatch(convexTable, record));\n } else {\n await ctx.db.insert(convexTable, record);\n }\n });\n return { ok: true };\n }\n\n case 'updateThread': {\n if (convexTable !== 'mastra_threads') {\n return { ok: false, error: `Unsupported operation ${request.op} for table ${request.tableName}` };\n }\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', request.id))\n .unique();\n\n if (!existing) {\n return { ok: true, result: null };\n }\n\n // patch() is a partial update, so leaving a key out preserves the stored\n // value. Writing back the title read a moment ago would clobber one\n // generated in between; same for metadata on a title-only update.\n const patchRecord: { title?: string; metadata?: Record<string, any>; updatedAt: string } = {\n updatedAt: request.updatedAt,\n };\n if (request.title !== undefined) {\n patchRecord.title = request.title;\n }\n if (request.metadata !== undefined) {\n patchRecord.metadata = mergeMetadata(existing.metadata, request.metadata);\n }\n await ctx.db.patch(existing._id, patchRecord);\n return { ok: true, result: { ...existing, ...patchRecord } };\n }\n\n case 'updateResource': {\n if (convexTable !== 'mastra_resources') {\n return { ok: false, error: `Unsupported operation ${request.op} for table ${request.tableName}` };\n }\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', request.resourceId))\n .unique();\n\n if (!existing) {\n const record = {\n id: request.resourceId,\n ...(request.workingMemory !== undefined ? { workingMemory: request.workingMemory } : {}),\n metadata: request.metadata ?? {},\n createdAt: request.createdAt,\n updatedAt: request.updatedAt,\n };\n await ctx.db.insert(convexTable, record);\n return { ok: true, result: record };\n }\n\n const patchRecord: Record<string, unknown> = {\n updatedAt: request.updatedAt,\n };\n if (request.workingMemory !== undefined) {\n patchRecord.workingMemory = request.workingMemory;\n }\n if (request.metadata !== undefined) {\n patchRecord.metadata = mergeMetadata(existing.metadata, request.metadata);\n }\n\n await ctx.db.patch(existing._id, patchRecord);\n return { ok: true, result: { ...existing, ...patchRecord } };\n }\n\n case 'patch': {\n const patchRecord = stripPatchKeys(request.record, ['id']);\n // Treat a missing field as `null` before comparing: rows written before a\n // nullable field existed have no key at all, and an expectation of `null`\n // (e.g. `expectedOwnerId: null` for an unowned task) must still match them.\n const matchesExpected = (record: Record<string, any>) =>\n !request.expected || Object.entries(request.expected).every(([key, value]) => (record[key] ?? null) === value);\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', request.id))\n .unique();\n\n if (!existing) {\n if (isBackgroundTasksTable(convexTable, request)) {\n const legacy = await findGenericDocumentById(ctx, request.tableName, request.id);\n if (legacy && matchesExpected(legacy.record)) {\n await ctx.db.patch(legacy._id, { record: mergeLegacyRecord(legacy.record, patchRecord) });\n return { ok: true, result: true };\n }\n }\n return { ok: true, result: false };\n }\n\n if (!matchesExpected(existing)) return { ok: true, result: false };\n await ctx.db.patch(existing._id, patchRecord);\n if (isBackgroundTasksTable(convexTable, request)) {\n const legacy = await findGenericDocumentById(ctx, request.tableName, request.id);\n if (legacy) {\n await ctx.db.delete(legacy._id);\n }\n }\n return { ok: true, result: true };\n }\n\n case 'load': {\n const keys = request.keys;\n if (keys.id) {\n // Find by id field using index\n const doc = await ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', keys.id))\n .unique();\n if (!doc && isBackgroundTasksTable(convexTable, request)) {\n const legacy = await findGenericDocumentById(ctx, request.tableName, String(keys.id));\n return { ok: true, result: legacy?.record ?? null };\n }\n return { ok: true, result: doc || null };\n }\n\n if (\n convexTable === CONVEX_TABLE_WORKFLOW_SNAPSHOTS &&\n typeof keys.workflow_name === 'string' &&\n typeof keys.run_id === 'string'\n ) {\n const doc = await ctx.db\n .query(convexTable)\n .withIndex('by_workflow_run', (q: any) => q.eq('workflow_name', keys.workflow_name).eq('run_id', keys.run_id))\n .unique();\n return { ok: true, result: doc || null };\n }\n\n // Query by other fields - use take() to avoid 32k limit\n const docs = await ctx.db.query(convexTable).take(10000);\n const match = docs.find((doc: any) => Object.entries(keys).every(([key, value]) => doc[key] === value));\n return { ok: true, result: match || null };\n }\n\n case 'loadMany': {\n const ids = normalizeLoadManyIds(request.ids);\n const docs = await mapInBatches(ids, STORAGE_MUTATION_BATCH_SIZE, id =>\n ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique(),\n );\n const typedDocs = docs.filter(Boolean);\n\n if (!isBackgroundTasksTable(convexTable, request)) {\n return { ok: true, result: typedDocs };\n }\n\n const typedDocsById = new Map(typedDocs.map(doc => [String((doc as Record<string, unknown>).id), doc]));\n const legacyDocs = await mapInBatches(\n ids.filter(id => !typedDocsById.has(id)),\n STORAGE_MUTATION_BATCH_SIZE,\n id => findGenericDocumentById(ctx, request.tableName, id),\n );\n const legacyRecordsById = new Map(\n legacyDocs\n .filter((doc): doc is GenericDocumentDoc => Boolean(doc))\n .map(doc => [String(doc.record.id), doc.record]),\n );\n return {\n ok: true,\n result: ids.map(id => typedDocsById.get(id) ?? legacyRecordsById.get(id)).filter(Boolean),\n };\n }\n\n case 'queryTable': {\n // Use take() to avoid hitting Convex's 32k document limit\n const maxDocs = request.limit ? Math.min(request.limit * 2, 10000) : 10000;\n\n // Build query with index if hint provided for efficient filtering\n let query: any;\n let indexedFields = new Set<string>();\n if (request.indexHint) {\n const hint = request.indexHint;\n if (hint.index === 'by_workflow') {\n query = ctx.db\n .query(convexTable)\n .withIndex('by_workflow', (q: any) => q.eq('workflow_name', hint.workflowName));\n } else if (hint.index === 'by_workflow_run') {\n query = ctx.db\n .query(convexTable)\n .withIndex('by_workflow_run', (q: any) =>\n q.eq('workflow_name', hint.workflowName).eq('run_id', hint.runId),\n );\n } else {\n query = ctx.db.query(convexTable);\n }\n } else if (request.filters && request.filters.length > 0) {\n const match = findBestIndex(convexTable, request.filters);\n if (match) {\n query = ctx.db.query(convexTable).withIndex(match.indexName, (q: any) => {\n let builder = q;\n for (const filter of match.indexedFilters) {\n builder = builder.eq(filter.field, filter.value);\n }\n return builder;\n });\n indexedFields = new Set(match.indexedFilters.map(filter => filter.field));\n } else {\n query = ctx.db.query(convexTable);\n }\n } else {\n query = ctx.db.query(convexTable);\n }\n\n let docs = await applyConvexEqualityFilters(query, request.filters, indexedFields).take(maxDocs);\n\n if (isBackgroundTasksTable(convexTable, request)) {\n const legacyDocs = await findGenericDocumentsByTable(ctx, request.tableName, maxDocs);\n let legacyRecords = legacyDocs.map(doc => doc.record);\n if (request.filters && request.filters.length > 0) {\n legacyRecords = legacyRecords.filter(record => matchesFilters(record, request.filters!));\n }\n legacyRecords = await filterLegacyRecordsWithoutTypedCopy(ctx, convexTable, legacyRecords);\n docs.push(...legacyRecords);\n docs = dedupeByRecordId(docs);\n }\n\n // Apply limit if provided\n if (request.limit) {\n docs = docs.slice(0, request.limit);\n }\n\n return { ok: true, result: docs };\n }\n\n case 'clearTable':\n case 'dropTable': {\n // Delete a small batch per call to stay within Convex's 1-second mutation timeout.\n // Client must call repeatedly until hasMore is false.\n const docs = await ctx.db.query(convexTable).take(STORAGE_MUTATION_BATCH_SIZE + 1);\n const hasMore = docs.length > STORAGE_MUTATION_BATCH_SIZE;\n let docsToDelete = hasMore ? docs.slice(0, STORAGE_MUTATION_BATCH_SIZE) : docs;\n let legacyHasMore = false;\n\n if (\n !hasMore &&\n docsToDelete.length < STORAGE_MUTATION_BATCH_SIZE &&\n isBackgroundTasksTable(convexTable, request)\n ) {\n const remainingBatchSize = STORAGE_MUTATION_BATCH_SIZE - docsToDelete.length;\n const legacyDocs = await findGenericDocumentsByTable(ctx, request.tableName, remainingBatchSize + 1);\n legacyHasMore = legacyDocs.length > remainingBatchSize;\n docsToDelete = docsToDelete.concat(legacyHasMore ? legacyDocs.slice(0, remainingBatchSize) : legacyDocs);\n }\n\n await deleteDocs(ctx, docsToDelete);\n return { ok: true, hasMore: hasMore || legacyHasMore };\n }\n\n case 'deleteMany': {\n const docsToDelete = await findExistingDocsByIds(request.ids, id =>\n ctx.db\n .query(convexTable)\n .withIndex('by_record_id', (q: any) => q.eq('id', id))\n .unique(),\n );\n if (isBackgroundTasksTable(convexTable, request)) {\n docsToDelete.push(\n ...(await findExistingDocsByIds(request.ids, id => findGenericDocumentById(ctx, request.tableName, id))),\n );\n }\n await deleteDocs(ctx, docsToDelete);\n return { ok: true };\n }\n\n case 'mergeWorkflowStepResult': {\n if (convexTable !== CONVEX_TABLE_WORKFLOW_SNAPSHOTS) {\n return { ok: false, error: `Unsupported operation ${request.op} for table ${request.tableName}` };\n }\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_workflow_run', (q: any) =>\n q.eq('workflow_name', request.workflowName).eq('run_id', request.runId),\n )\n .unique();\n\n if (!existing) {\n return { ok: false, error: `Workflow snapshot not found for runId ${request.runId}` };\n }\n\n const snapshot = parseStoredSnapshot(existing.snapshot, request.runId);\n if (!snapshot.context) {\n return { ok: false, error: `Snapshot for runId ${request.runId} is missing or has invalid context` };\n }\n\n const context = mergeWorkflowStepResult({\n snapshot,\n stepId: request.stepId,\n result: JSON.parse(request.result),\n requestContext: JSON.parse(request.requestContext),\n state: request.state === undefined ? undefined : JSON.parse(request.state),\n });\n\n await ctx.db.patch(existing._id, {\n snapshot: JSON.stringify(snapshot),\n updatedAt: new Date().toISOString(),\n });\n\n return { ok: true, result: JSON.stringify(context) };\n }\n\n case 'mergeWorkflowState': {\n if (convexTable !== CONVEX_TABLE_WORKFLOW_SNAPSHOTS) {\n return { ok: false, error: `Unsupported operation ${request.op} for table ${request.tableName}` };\n }\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_workflow_run', (q: any) =>\n q.eq('workflow_name', request.workflowName).eq('run_id', request.runId),\n )\n .unique();\n\n if (!existing) {\n return { ok: false, error: `Workflow snapshot not found for runId ${request.runId}` };\n }\n\n const snapshot = parseStoredSnapshot(existing.snapshot, request.runId);\n if (!snapshot.context) {\n return { ok: false, error: `Snapshot for runId ${request.runId} is missing or has invalid context` };\n }\n\n // `expectedStatus` is a compare-and-set guard, not state. Convex mutations are\n // serializable, so checking it here keeps the guard and the write atomic. It is stripped\n // from the merge so it can never be persisted into the snapshot. An empty result signals\n // \"guard did not match\" to the caller.\n const { expectedStatus, ...state } = JSON.parse(request.opts);\n if (expectedStatus !== undefined) {\n const expected = Array.isArray(expectedStatus) ? expectedStatus : [expectedStatus];\n if (!expected.includes(snapshot.status)) {\n return { ok: true, result: '' };\n }\n }\n\n const mergedSnapshot = { ...snapshot, ...state };\n await ctx.db.patch(existing._id, {\n snapshot: JSON.stringify(mergedSnapshot),\n updatedAt: new Date().toISOString(),\n });\n\n return { ok: true, result: JSON.stringify(mergedSnapshot) };\n }\n\n default:\n return { ok: false, error: `Unsupported operation ${(request as any).op}` };\n }\n}\n\n/**\n * Handle operations on the vectors table.\n * Vectors are stored with indexName to support multiple indexes.\n */\nasync function handleVectorOperation(ctx: MutationCtx<any>, request: StorageRequest): Promise<StorageResponse> {\n // Extract the index name from the table name (e.g., \"mastra_vector_myindex\" -> \"myindex\")\n const indexName = request.tableName.replace(VECTOR_TABLE_PREFIX, '');\n const convexTable = 'mastra_vectors';\n\n switch (request.op) {\n case 'insert': {\n const record = request.record;\n const id = record.id;\n if (!id) {\n throw new Error(`Vector record is missing an id`);\n }\n\n // Find existing by composite key (indexName, id) to scope per index\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_index_id', (q: any) => q.eq('indexName', indexName).eq('id', id))\n .unique();\n\n if (existing) {\n await ctx.db.patch(existing._id, {\n embedding: record.embedding,\n metadata: record.metadata,\n });\n } else {\n await ctx.db.insert(convexTable, {\n id,\n indexName,\n embedding: record.embedding,\n metadata: record.metadata,\n });\n }\n return { ok: true };\n }\n\n case 'batchInsert': {\n const records = coalesceLastRecordById(request.records);\n await mapInBatches(records, STORAGE_MUTATION_BATCH_SIZE, async record => {\n const id = record.id;\n\n // Find existing by composite key (indexName, id) to scope per index\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_index_id', (q: any) => q.eq('indexName', indexName).eq('id', id))\n .unique();\n\n if (existing) {\n await ctx.db.patch(existing._id, {\n embedding: record.embedding,\n metadata: record.metadata,\n });\n } else {\n await ctx.db.insert(convexTable, {\n id,\n indexName,\n embedding: record.embedding,\n metadata: record.metadata,\n });\n }\n });\n return { ok: true };\n }\n\n case 'patch': {\n const patchRecord = stripPatchKeys(request.record, ['id', 'indexName']);\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_index_id', (q: any) => q.eq('indexName', indexName).eq('id', request.id))\n .unique();\n\n if (!existing) {\n return { ok: true, result: false };\n }\n\n await ctx.db.patch(existing._id, patchRecord);\n return { ok: true, result: true };\n }\n\n case 'load': {\n const keys = request.keys;\n if (keys.id) {\n // Use composite key (indexName, id) to scope lookup per index\n const doc = await ctx.db\n .query(convexTable)\n .withIndex('by_index_id', (q: any) => q.eq('indexName', indexName).eq('id', keys.id))\n .unique();\n return { ok: true, result: doc || null };\n }\n return { ok: true, result: null };\n }\n\n case 'loadMany': {\n const docs = await findExistingDocsByIds(normalizeLoadManyIds(request.ids), id =>\n ctx.db\n .query(convexTable)\n .withIndex('by_index_id', (q: any) => q.eq('indexName', indexName).eq('id', id))\n .unique(),\n );\n return { ok: true, result: docs };\n }\n\n case 'queryTable': {\n if (request.cursor !== undefined && request.pageSize === undefined) {\n throw new Error('queryTable cursor requires pageSize');\n }\n\n if (request.pageSize !== undefined) {\n if (!Number.isInteger(request.pageSize) || request.pageSize <= 0) {\n throw new Error('queryTable pageSize must be a positive integer');\n }\n if (request.limit !== undefined) {\n throw new Error('queryTable limit cannot be combined with pageSize');\n }\n\n const page = await ctx.db\n .query(convexTable)\n .withIndex('by_index', (q: any) => q.eq('indexName', indexName))\n .paginate({ cursor: request.cursor ?? null, numItems: request.pageSize });\n\n let docs = page.page;\n\n // Apply filters if provided\n if (request.filters && request.filters.length > 0) {\n docs = docs.filter((doc: any) => request.filters!.every(filter => doc[filter.field] === filter.value));\n }\n\n return {\n ok: true,\n result: docs,\n hasMore: !page.isDone,\n continuationCursor: page.continueCursor,\n };\n }\n\n // Use take() to avoid hitting Convex's 32k document limit\n const maxDocs = request.limit ? Math.min(request.limit * 2, 10000) : 10000;\n let docs = await ctx.db\n .query(convexTable)\n .withIndex('by_index', (q: any) => q.eq('indexName', indexName))\n .take(maxDocs);\n\n // Apply filters if provided\n if (request.filters && request.filters.length > 0) {\n docs = docs.filter((doc: any) => request.filters!.every(filter => doc[filter.field] === filter.value));\n }\n\n // Apply limit if provided\n if (request.limit) {\n docs = docs.slice(0, request.limit);\n }\n\n return { ok: true, result: docs };\n }\n\n case 'clearTable':\n case 'dropTable': {\n // Delete a small batch per call to stay within Convex's 1-second mutation timeout.\n // Client must call repeatedly until hasMore is false.\n const docs = await ctx.db\n .query(convexTable)\n .withIndex('by_index', (q: any) => q.eq('indexName', indexName))\n .take(STORAGE_MUTATION_BATCH_SIZE + 1);\n const hasMore = docs.length > STORAGE_MUTATION_BATCH_SIZE;\n const docsToDelete = hasMore ? docs.slice(0, STORAGE_MUTATION_BATCH_SIZE) : docs;\n\n await deleteDocs(ctx, docsToDelete);\n return { ok: true, hasMore };\n }\n\n case 'deleteMany': {\n const docsToDelete = await findExistingDocsByIds(request.ids, id =>\n // Use composite key (indexName, id) to scope deletion per index\n ctx.db\n .query(convexTable)\n .withIndex('by_index_id', (q: any) => q.eq('indexName', indexName).eq('id', id))\n .unique(),\n );\n await deleteDocs(ctx, docsToDelete);\n return { ok: true };\n }\n\n default:\n return { ok: false, error: `Unsupported operation ${(request as any).op}` };\n }\n}\n\n/**\n * Handle operations on the generic documents table.\n * Used as fallback for unknown table names.\n */\nasync function handleGenericOperation(ctx: MutationCtx<any>, request: StorageRequest): Promise<StorageResponse> {\n const tableName = request.tableName;\n const convexTable = 'mastra_documents';\n\n switch (request.op) {\n case 'insert': {\n const record = request.record;\n if (!record.id) {\n throw new Error(`Record for table ${tableName} is missing an id`);\n }\n const primaryKey = String(record.id);\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName).eq('primaryKey', primaryKey))\n .unique();\n\n if (existing) {\n await ctx.db.patch(existing._id, { record });\n } else {\n await ctx.db.insert(convexTable, {\n table: tableName,\n primaryKey,\n record,\n });\n }\n return { ok: true };\n }\n\n case 'batchInsert': {\n const records = coalesceLastRecordById(request.records);\n await mapInBatches(records, STORAGE_MUTATION_BATCH_SIZE, async record => {\n const primaryKey = String(record.id);\n\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName).eq('primaryKey', primaryKey))\n .unique();\n\n if (existing) {\n await ctx.db.patch(existing._id, { record });\n } else {\n await ctx.db.insert(convexTable, {\n table: tableName,\n primaryKey,\n record,\n });\n }\n });\n return { ok: true };\n }\n\n case 'patch': {\n const patchRecord = stripPatchKeys(request.record, ['id']);\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName).eq('primaryKey', String(request.id)))\n .unique();\n\n if (!existing) {\n return { ok: true, result: false };\n }\n\n await ctx.db.patch(existing._id, {\n record:\n tableName === TABLE_BACKGROUND_TASKS\n ? mergeLegacyRecord(existing.record, patchRecord)\n : { ...existing.record, ...patchRecord },\n });\n return { ok: true, result: true };\n }\n\n case 'load': {\n const keys = request.keys;\n if (keys.id) {\n const existing = await ctx.db\n .query(convexTable)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName).eq('primaryKey', String(keys.id)))\n .unique();\n return { ok: true, result: existing ? existing.record : null };\n }\n\n const docs = await ctx.db\n .query(convexTable)\n .withIndex('by_table', (q: any) => q.eq('table', tableName))\n .take(10000);\n const match = docs.find((doc: any) => Object.entries(keys).every(([key, value]) => doc.record?.[key] === value));\n return { ok: true, result: match ? match.record : null };\n }\n\n case 'loadMany': {\n const docs = await mapInBatches(normalizeLoadManyIds(request.ids), STORAGE_MUTATION_BATCH_SIZE, id =>\n findGenericDocumentById(ctx, tableName, id),\n );\n return {\n ok: true,\n result: docs.filter((doc): doc is GenericDocumentDoc => Boolean(doc)).map(doc => doc.record),\n };\n }\n\n case 'queryTable': {\n // Use take() to avoid hitting Convex's 32k document limit\n const maxDocs = request.limit ? Math.min(request.limit * 2, 10000) : 10000;\n const docs = await ctx.db\n .query(convexTable)\n .withIndex('by_table', (q: any) => q.eq('table', tableName))\n .take(maxDocs);\n\n let records = docs.map((doc: any) => doc.record);\n\n if (request.filters && request.filters.length > 0) {\n records = records.filter((record: any) =>\n tableName === TABLE_BACKGROUND_TASKS\n ? matchesFilters(record, request.filters!)\n : request.filters!.every(filter => record?.[filter.field] === filter.value),\n );\n }\n\n if (request.limit) {\n records = records.slice(0, request.limit);\n }\n\n return { ok: true, result: records };\n }\n\n case 'clearTable':\n case 'dropTable': {\n // Delete a small batch per call to stay within Convex's 1-second mutation timeout.\n // Client must call repeatedly until hasMore is false.\n const docs = await ctx.db\n .query(convexTable)\n .withIndex('by_table', (q: any) => q.eq('table', tableName))\n .take(STORAGE_MUTATION_BATCH_SIZE + 1);\n const hasMore = docs.length > STORAGE_MUTATION_BATCH_SIZE;\n const docsToDelete = hasMore ? docs.slice(0, STORAGE_MUTATION_BATCH_SIZE) : docs;\n\n await deleteDocs(ctx, docsToDelete);\n return { ok: true, hasMore };\n }\n\n case 'deleteMany': {\n const docsToDelete = await findExistingDocsByIds(request.ids, id =>\n ctx.db\n .query(convexTable)\n .withIndex('by_table_primary', (q: any) => q.eq('table', tableName).eq('primaryKey', String(id)))\n .unique(),\n );\n await deleteDocs(ctx, docsToDelete);\n return { ok: true };\n }\n\n default:\n return { ok: false, error: `Unsupported operation ${(request as any).op}` };\n }\n}\n","import { actionGeneric, mutationGeneric, queryGeneric } from 'convex/server';\nimport { v } from 'convex/values';\nimport type { GenericId } from 'convex/values';\n\ntype NativeVectorFilterValue = string | number | boolean | null;\ntype NativeVectorFilterClause = {\n field: string;\n value: NativeVectorFilterValue;\n};\ntype NativeVectorFilter = NativeVectorFilterClause | { $or: NativeVectorFilterClause[] };\n\ntype NativeVectorIndexConfig = {\n tableName: string;\n vectorIndexName: string;\n dimension?: number;\n idField?: string;\n idIndexName?: string;\n vectorField?: string;\n metadataField?: string;\n filterFields?: string[];\n};\n\ntype NativeVectorDocument = Record<string, any> & {\n _id?: GenericId<string>;\n};\n\nconst DEFAULT_ID_FIELD = 'id';\nconst DEFAULT_ID_INDEX = 'by_record_id';\nconst DEFAULT_VECTOR_FIELD = 'embedding';\nconst DEFAULT_METADATA_FIELD = 'metadata';\nconst NATIVE_VECTOR_BATCH_SIZE = 25;\nconst MAX_CONVEX_VECTOR_RESULTS = 256;\n\nconst nativeVectorFilterValueValidator = v.union(v.string(), v.number(), v.boolean(), v.null());\nconst nativeVectorFilterClauseValidator = v.object({\n field: v.string(),\n value: nativeVectorFilterValueValidator,\n});\nconst nativeVectorFilterValidator = v.union(\n nativeVectorFilterClauseValidator,\n v.object({ $or: v.array(nativeVectorFilterClauseValidator) }),\n);\nconst nativeVectorIndexConfigValidator = v.object({\n tableName: v.string(),\n vectorIndexName: v.string(),\n dimension: v.optional(v.number()),\n idField: v.optional(v.string()),\n idIndexName: v.optional(v.string()),\n vectorField: v.optional(v.string()),\n metadataField: v.optional(v.string()),\n filterFields: v.optional(v.array(v.string())),\n});\n\nfunction idField(config: NativeVectorIndexConfig): string {\n return config.idField ?? DEFAULT_ID_FIELD;\n}\n\nfunction idIndexName(config: NativeVectorIndexConfig): string {\n return config.idIndexName ?? DEFAULT_ID_INDEX;\n}\n\nfunction vectorField(config: NativeVectorIndexConfig): string {\n return config.vectorField ?? DEFAULT_VECTOR_FIELD;\n}\n\nfunction metadataField(config: NativeVectorIndexConfig): string {\n return config.metadataField ?? DEFAULT_METADATA_FIELD;\n}\n\nfunction asTableName(tableName: string): any {\n return tableName as any;\n}\n\nfunction asConvexId(id: string): GenericId<string> {\n return id as GenericId<string>;\n}\n\nfunction pickFilterFields(metadata: Record<string, any> | undefined, filterFields: string[] | undefined) {\n const fields: Record<string, any> = {};\n if (!metadata || !filterFields) return fields;\n\n for (const field of filterFields) {\n const value = metadata[field];\n if (value !== undefined) {\n fields[field] = value;\n }\n }\n\n return fields;\n}\n\nfunction isMetadataRecord(value: unknown): value is Record<string, any> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validateMetadataArray(metadata: unknown, idsLength: number): Array<Record<string, any>> | undefined {\n if (metadata === undefined) return undefined;\n if (!Array.isArray(metadata)) {\n throw new Error('Native vector upsert: metadata must be an array matching ids when provided');\n }\n if (metadata.length !== idsLength) {\n throw new Error(`Native vector upsert: metadata length (${metadata.length}) must match ids length (${idsLength})`);\n }\n if (!metadata.every(isMetadataRecord)) {\n throw new Error('Native vector upsert: metadata entries must be objects when provided');\n }\n return metadata;\n}\n\nfunction validateMetadataRecord(metadata: unknown): Record<string, any> | undefined {\n if (metadata === undefined) return undefined;\n if (!isMetadataRecord(metadata)) {\n throw new Error('Native vector update: metadata must be an object when provided');\n }\n return metadata;\n}\n\nfunction clearMissingFilterFields(\n patch: Record<string, any>,\n metadata: Record<string, any>,\n filterFields: string[] | undefined,\n) {\n if (!filterFields) return;\n\n for (const field of filterFields) {\n if (metadata[field] === undefined) {\n patch[field] = undefined;\n }\n }\n}\n\nfunction omitVectorField(doc: NativeVectorDocument, config: NativeVectorIndexConfig): NativeVectorDocument {\n const { [vectorField(config)]: _, ...docWithoutVector } = doc;\n return docWithoutVector;\n}\n\nfunction buildRecord({\n config,\n id,\n vector,\n metadata,\n}: {\n config: NativeVectorIndexConfig;\n id: string;\n vector: number[];\n metadata?: Record<string, any>;\n}) {\n return {\n [idField(config)]: id,\n [vectorField(config)]: vector,\n ...(metadata !== undefined ? { [metadataField(config)]: metadata } : {}),\n ...pickFilterFields(metadata, config.filterFields),\n };\n}\n\nasync function findByRecordId(\n ctx: any,\n config: NativeVectorIndexConfig,\n id: string,\n): Promise<NativeVectorDocument | null> {\n return ctx.db\n .query(asTableName(config.tableName))\n .withIndex(idIndexName(config), (q: any) => q.eq(idField(config), id))\n .unique();\n}\n\nasync function mapInBatches<TInput, TOutput>(\n inputs: TInput[],\n mapper: (input: TInput, index: number) => Promise<TOutput>,\n): Promise<TOutput[]> {\n const results: TOutput[] = [];\n for (let index = 0; index < inputs.length; index += NATIVE_VECTOR_BATCH_SIZE) {\n results.push(\n ...(await Promise.all(\n inputs\n .slice(index, index + NATIVE_VECTOR_BATCH_SIZE)\n .map((input, batchIndex) => mapper(input, index + batchIndex)),\n )),\n );\n }\n return results;\n}\n\nfunction buildVectorFilter(q: any, filter?: NativeVectorFilter) {\n if (!filter) return undefined;\n\n if ('$or' in filter) {\n return q.or(...filter.$or.map(clause => q.eq(clause.field, clause.value)));\n }\n\n return q.eq(filter.field, filter.value);\n}\n\nexport const mastraNativeVectorAction = actionGeneric({\n args: {\n config: nativeVectorIndexConfigValidator,\n vector: v.array(v.number()),\n limit: v.optional(v.number()),\n filter: v.optional(nativeVectorFilterValidator),\n },\n handler: async (ctx, args: any) => {\n const config = args.config as NativeVectorIndexConfig;\n const limit = args.limit as number | undefined;\n const filter = args.filter as NativeVectorFilter | undefined;\n\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > MAX_CONVEX_VECTOR_RESULTS)) {\n throw new Error(`Native vector query: limit must be an integer between 1 and ${MAX_CONVEX_VECTOR_RESULTS}`);\n }\n\n const results = await ctx.vectorSearch(asTableName(config.tableName), config.vectorIndexName as any, {\n vector: args.vector,\n ...(limit !== undefined ? { limit } : {}),\n ...(filter ? { filter: (q: any) => buildVectorFilter(q, filter) } : {}),\n });\n\n return results.map(result => ({\n id: String(result._id),\n score: result._score,\n }));\n },\n});\n\nexport const mastraNativeVectorQuery = queryGeneric({\n args: {\n op: v.union(v.literal('getByConvexIds'), v.literal('describe'), v.literal('listByIds')),\n config: nativeVectorIndexConfigValidator,\n ids: v.optional(v.array(v.string())),\n includeVector: v.optional(v.boolean()),\n countLimit: v.optional(v.number()),\n },\n handler: async (ctx, args: any) => {\n const config = args.config as NativeVectorIndexConfig;\n\n switch (args.op as string) {\n case 'getByConvexIds': {\n const ids = args.ids as string[];\n if (!ids) {\n throw new Error('Native vector query: ids are required');\n }\n const includeVector = args.includeVector === true;\n const docs = await mapInBatches(ids, id => ctx.db.get(asConvexId(id)));\n return docs\n .filter((doc): doc is NativeVectorDocument => Boolean(doc))\n .map(doc => (includeVector ? doc : omitVectorField(doc, config)));\n }\n\n case 'describe': {\n const limit = Math.max(1, Math.min(args.countLimit ?? 10000, 10000));\n const docs = await ctx.db.query(asTableName(config.tableName)).take(limit + 1);\n return {\n count: Math.min(docs.length, limit),\n countIsLimited: docs.length > limit,\n };\n }\n\n case 'listByIds': {\n const ids = args.ids as string[];\n if (!ids) {\n throw new Error('Native vector query: ids are required');\n }\n return mapInBatches(ids, id => findByRecordId(ctx, config, id));\n }\n\n default:\n throw new Error(`Unsupported native vector query operation: ${args.op}`);\n }\n },\n});\n\nexport const mastraNativeVectorMutation = mutationGeneric({\n args: {\n op: v.union(v.literal('upsert'), v.literal('updateById'), v.literal('deleteByIds')),\n config: nativeVectorIndexConfigValidator,\n ids: v.optional(v.array(v.string())),\n vectors: v.optional(v.array(v.array(v.number()))),\n metadata: v.optional(v.any()),\n id: v.optional(v.string()),\n vector: v.optional(v.array(v.number())),\n },\n handler: async (ctx, args: any) => {\n const config = args.config as NativeVectorIndexConfig;\n\n switch (args.op as string) {\n case 'upsert': {\n const ids = args.ids as string[];\n const vectors = args.vectors as number[][];\n\n if (!ids || !vectors) {\n throw new Error('Native vector upsert: ids and vectors are required');\n }\n if (vectors.length !== ids.length) {\n throw new Error(\n `Native vector upsert: vectors length (${vectors.length}) must match ids length (${ids.length})`,\n );\n }\n const metadata = validateMetadataArray(args.metadata, ids.length);\n if (new Set(ids).size !== ids.length) {\n throw new Error('Native vector upsert: ids must be unique');\n }\n\n await mapInBatches(ids, async (id, index) => {\n const record = buildRecord({\n config,\n id,\n vector: vectors[index]!,\n metadata: metadata?.[index],\n });\n const existing = await findByRecordId(ctx, config, id);\n if (existing?._id) {\n const { _id: _, _creationTime: __, ...patch } = record as NativeVectorDocument;\n if (metadata?.[index] !== undefined) {\n clearMissingFilterFields(patch, metadata[index]!, config.filterFields);\n }\n await ctx.db.patch(existing._id, patch);\n } else {\n await ctx.db.insert(asTableName(config.tableName), record);\n }\n });\n return { ok: true };\n }\n\n case 'updateById': {\n if (!args.id) {\n throw new Error('Native vector update: id is required');\n }\n const existing = await findByRecordId(ctx, config, args.id);\n if (!existing?._id) return { ok: true };\n\n const patch: Record<string, any> = {};\n if (args.vector) patch[vectorField(config)] = args.vector;\n const metadata = validateMetadataRecord(args.metadata);\n if (metadata !== undefined) {\n const existingMetadata = isMetadataRecord(existing[metadataField(config)])\n ? existing[metadataField(config)]\n : {};\n patch[metadataField(config)] = { ...existingMetadata, ...metadata };\n Object.assign(patch, pickFilterFields(patch[metadataField(config)], config.filterFields));\n }\n\n if (Object.keys(patch).length > 0) {\n await ctx.db.patch(existing._id, patch);\n }\n return { ok: true };\n }\n\n case 'deleteByIds': {\n const ids = args.ids as string[];\n if (!ids) {\n throw new Error('Native vector deleteByIds: ids are required');\n }\n const docs = await mapInBatches(ids, id => findByRecordId(ctx, config, id));\n await mapInBatches(\n docs.filter((doc): doc is NativeVectorDocument & { _id: GenericId<string> } => Boolean(doc?._id)),\n doc => ctx.db.delete(doc._id),\n );\n return { ok: true };\n }\n\n default:\n throw new Error(`Unsupported native vector mutation operation: ${args.op}`);\n }\n },\n});\n"],"mappings":";;;;;AAMA,MAAM,cAAc;AAC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