{"version":3,"sources":["../src/evals/types.ts","../src/storage/domains/observability/tracing.ts","../src/storage/types.ts","../src/storage/constants.ts"],"names":["z","SpanType","dbTimestamps","paginationInfoSchema","TraceStatus","spanContextFields","metadataField","tagsField","traceIdField","spanIdField","dateRangeSchema","sortDirectionSchema","paginationArgsSchema","getZodTypeName","getZodInnerType"],"mappings":";;;;;;AAmBO,IAAM,sBAAsBA,IAAA,CAAE,IAAA,CAAK,CAAC,MAAA,EAAQ,MAAM,CAAC;AAInD,IAAM,uBAAA,GAA0BA,IAAA,CAAE,IAAA,CAAK,CAAC,OAAA,EAAS,UAAA,EAAY,GAAG,MAAA,CAAO,MAAA,CAAOC,0BAAQ,CAAC,CAI7F;AAQM,IAAM,oBAAA,GAAuBD,KAAE,MAAA,CAAO;AAAA,EAC3C,WAAA,EAAaA,KAAE,MAAA,EAAO;AAAA,EACtB,MAAA,EAAQA,KAAE,MAAA;AACZ,CAAC;AASD,IAAM,YAAA,GAAeA,KAAE,MAAA,CAAOA,IAAA,CAAE,QAAO,EAAGA,IAAA,CAAE,SAAS,CAAA;AAGrD,IAAM,oBAAA,GAAuB,aAAa,QAAA,EAAS;AAM5C,IAAM,kBAAA,GAAqBA,KAAE,MAAA,CAAO;AAAA,EACzC,KAAA,EAAOA,IAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,KAAA,EAAOA,IAAA,CAAE,OAAA,EAAQ,CAAE,QAAA,EAAS;AAAA,EAC5B,MAAA,EAAQA,KAAE,OAAA,EAAQ;AAAA,EAClB,iBAAA,EAAmB,oBAAA;AAAA,EACnB,cAAA,EAAgB;AAAA;AAAA;AAGlB,CAAC;AAQM,IAAM,sBAAA,GAAyBA,KAAE,MAAA,CAAO;AAAA,EAC7C,KAAA,EAAOA,IAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC3B,MAAA,EAAQ,YAAA;AAAA,EACR,KAAA,EAAOA,KAAE,OAAA,EAAQ;AAAA,EACjB,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AAG,4BAAA;AAAA,EAC/B,CAAC,wBAAwB,GAAG,yBAAA;AAAA,EAC5B,CAAC,gCAAgC,GAAG,iCAAA;AAAA,EACpC,CAAC,iBAAiB,GAAG,kBAAA;AAAA,EACrB,CAAC,yBAAyB,GAAG,0BAAA;AAAA,EAC7B,CAAC,iBAAiB,GAAG,kBAAA;AAAA,EACrB,CAAC,yBAAyB,GAAG,0BAAA;AAAA,EAC7B,CAAC,gBAAgB,GAAG,iBAAA;AAAA,EACpB,CAAC,wBAAwB,GAAG,yBAAA;AAAA,EAC5B,CAAC,YAAY,GAAG,aAAA;AAAA,EAChB,CAAC,oBAAoB,GAAG,qBAAA;AAAA,EACxB,CAAC,iBAAiB,GAAG,kBAAA;AAAA,EACrB,CAAC,cAAc,GAAG,eAAA;AAAA,EAClB,CAAC,mBAAmB,GAAG,oBAAA;AAAA,EACvB,CAAC,sBAAsB,GAAG,uBAAA;AAAA,EAC1B,CAAC,iBAAiB,GAAG,kBAAA;AAAA,EACrB,CAAC,wBAAwB,GAAG;AAC9B;AAMO,IAAM,aAAA,GAAkE;AAAA,EAC7E,CAAC,mBAAmB,GAAG,EAAE,OAAA,EAAS,sBAAsB,mBAAA,EAAqB,CAAC,IAAA,EAAM,gBAAgB,CAAA;AACtG;AAMO,IAAM,iCAAA,GAAoC;AAAA,EAC/C,CAAC,0BAA0B,GAAG;AAChC","file":"chunk-HCHNDDHM.cjs","sourcesContent":["import type { CoreMessage, CoreSystemMessage } from '@internal/ai-sdk-v4';\nimport { z } from 'zod/v4';\nimport type { MastraDBMessage } from '../agent';\nimport { SpanType } from '../observability';\nimport type { ObservabilityContext } from '../observability';\nimport type { SpanRecord } from '../storage/domains/observability/tracing';\nimport { dbTimestamps, paginationInfoSchema } from '../storage/domains/shared';\nimport type { StepResult } from '../workflows/types';\n\n// ============================================================================\n// Sampling Config\n// ============================================================================\n\nexport type ScoringSamplingConfig = { type: 'none' } | { type: 'ratio'; rate: number };\n\n// ============================================================================\n// Scoring Source & Entity Type\n// ============================================================================\n\nexport const scoringSourceSchema = z.enum(['LIVE', 'TEST']);\n\nexport type ScoringSource = z.infer<typeof scoringSourceSchema>;\n\nexport const scoringEntityTypeSchema = z.enum(['AGENT', 'WORKFLOW', ...Object.values(SpanType)] as [\n  string,\n  string,\n  ...string[],\n]);\n\nexport type ScoringEntityType = z.infer<typeof scoringEntityTypeSchema>;\n\n// ============================================================================\n// Scoring Prompts\n// ============================================================================\n\nexport const scoringPromptsSchema = z.object({\n  description: z.string(),\n  prompt: z.string(),\n});\n\nexport type ScoringPrompts = z.infer<typeof scoringPromptsSchema>;\n\n// ============================================================================\n// Shared Record Schemas\n// ============================================================================\n\n/** Reusable schema for required record fields (e.g., scorer, entity) */\nconst recordSchema = z.record(z.string(), z.unknown());\n\n/** Reusable schema for optional record fields (e.g., metadata, additionalContext) */\nconst optionalRecordSchema = recordSchema.optional();\n\n// ============================================================================\n// Base Scoring Input (used for scorer functions)\n// ============================================================================\n\nexport const scoringInputSchema = z.object({\n  runId: z.string().optional(),\n  input: z.unknown().optional(),\n  output: z.unknown(),\n  additionalContext: optionalRecordSchema,\n  requestContext: optionalRecordSchema,\n  // Note: observabilityContext is not serializable, so we don't include it in the schema\n  // It's added at runtime when needed\n});\n\nexport type ScoringInput = z.infer<typeof scoringInputSchema> & Partial<ObservabilityContext>;\n\n// ============================================================================\n// Scoring Hook Input\n// ============================================================================\n\nexport const scoringHookInputSchema = z.object({\n  runId: z.string().optional(),\n  scorer: recordSchema,\n  input: z.unknown(),\n  output: z.unknown(),\n  metadata: optionalRecordSchema,\n  additionalContext: optionalRecordSchema,\n  source: scoringSourceSchema,\n  entity: recordSchema,\n  entityType: scoringEntityTypeSchema,\n  requestContext: optionalRecordSchema,\n  structuredOutput: z.boolean().optional(),\n  traceId: z.string().optional(),\n  spanId: z.string().optional(),\n  resourceId: z.string().optional(),\n  threadId: z.string().optional(),\n  // Note: observabilityContext is not serializable, so we don't include it in the schema\n});\n\nexport type ScoringHookInput = z.infer<typeof scoringHookInputSchema> & Partial<ObservabilityContext>;\n\n// ============================================================================\n// Extract Step Result\n// ============================================================================\n\nexport const scoringExtractStepResultSchema = optionalRecordSchema;\n\nexport type ScoringExtractStepResult = z.infer<typeof scoringExtractStepResultSchema>;\n\n// ============================================================================\n// Analyze Step Result (Score Result)\n// ============================================================================\n\nexport const scoringValueSchema = z.number();\n\nexport const scoreResultSchema = z.object({\n  result: optionalRecordSchema,\n  score: scoringValueSchema,\n  prompt: z.string().optional(),\n});\n\nexport type ScoringAnalyzeStepResult = z.infer<typeof scoreResultSchema>;\n\n// ============================================================================\n// Composite Input Types (for scorer step functions)\n// ============================================================================\n\nexport const scoringInputWithExtractStepResultSchema = scoringInputSchema.extend({\n  runId: z.string(), // Required in this context\n  extractStepResult: optionalRecordSchema,\n  extractPrompt: z.string().optional(),\n});\n\nexport type ScoringInputWithExtractStepResult<TExtract = any> = Omit<\n  z.infer<typeof scoringInputWithExtractStepResultSchema>,\n  'extractStepResult'\n> & {\n  extractStepResult?: TExtract;\n} & Partial<ObservabilityContext>;\n\nexport const scoringInputWithExtractStepResultAndAnalyzeStepResultSchema =\n  scoringInputWithExtractStepResultSchema.extend({\n    score: z.number(),\n    analyzeStepResult: optionalRecordSchema,\n    analyzePrompt: z.string().optional(),\n  });\n\nexport type ScoringInputWithExtractStepResultAndAnalyzeStepResult<TExtract = any, TScore = any> = Omit<\n  z.infer<typeof scoringInputWithExtractStepResultAndAnalyzeStepResultSchema>,\n  'extractStepResult' | 'analyzeStepResult'\n> & {\n  extractStepResult?: TExtract;\n  analyzeStepResult?: TScore;\n} & Partial<ObservabilityContext>;\n\nexport const scoringInputWithExtractStepResultAndScoreAndReasonSchema =\n  scoringInputWithExtractStepResultAndAnalyzeStepResultSchema.extend({\n    reason: z.string().optional(),\n    reasonPrompt: z.string().optional(),\n  });\n\nexport type ScoringInputWithExtractStepResultAndScoreAndReason = z.infer<\n  typeof scoringInputWithExtractStepResultAndScoreAndReasonSchema\n> &\n  Partial<ObservabilityContext>;\n\n// ============================================================================\n// Score Row Data (stored in DB)\n// ============================================================================\n\nexport const scoreRowDataSchema = z.object({\n  id: z.string(),\n  scorerId: z.string(),\n  entityId: z.string(),\n\n  // From ScoringInputWithExtractStepResultAndScoreAndReason\n  runId: z.string(),\n  input: z.unknown().optional(),\n  output: z.unknown(),\n  additionalContext: optionalRecordSchema,\n  requestContext: optionalRecordSchema,\n  extractStepResult: optionalRecordSchema,\n  extractPrompt: z.string().optional(),\n  score: z.number(),\n  analyzeStepResult: optionalRecordSchema,\n  analyzePrompt: z.string().optional(),\n  reason: z.string().optional(),\n  reasonPrompt: z.string().optional(),\n\n  // From ScoringHookInput\n  scorer: recordSchema,\n  metadata: optionalRecordSchema,\n  source: scoringSourceSchema,\n  entity: recordSchema,\n  entityType: scoringEntityTypeSchema.optional(),\n  structuredOutput: z.boolean().optional(),\n  traceId: z.string().optional(),\n  spanId: z.string().optional(),\n  resourceId: z.string().optional(),\n  threadId: z.string().optional(),\n\n  // Additional ScoreRowData fields\n  preprocessStepResult: optionalRecordSchema,\n  preprocessPrompt: z.string().optional(),\n  generateScorePrompt: z.string().optional(),\n  generateReasonPrompt: z.string().optional(),\n\n  // Timestamps\n  ...dbTimestamps,\n});\n\nexport type ScoreRowData = z.infer<typeof scoreRowDataSchema>;\n\n// ============================================================================\n// Save Score Payload (for creating new scores)\n// ============================================================================\n\nexport const saveScorePayloadSchema = scoreRowDataSchema.omit({\n  id: true,\n  createdAt: true,\n  updatedAt: true,\n});\n\nexport type SaveScorePayload = z.infer<typeof saveScorePayloadSchema>;\n\n// ============================================================================\n// List Scores Response\n// ============================================================================\n\nexport const listScoresResponseSchema = z.object({\n  pagination: paginationInfoSchema,\n  scores: z.array(scoreRowDataSchema),\n});\n\nexport type ListScoresResponse = z.infer<typeof listScoresResponseSchema>;\n\nexport type ExtractionStepFn = (input: ScoringInput) => Promise<Record<string, any>>;\n\nexport type AnalyzeStepFn = (input: ScoringInputWithExtractStepResult) => Promise<ScoringAnalyzeStepResult>;\n\nexport type ReasonStepFn = (\n  input: ScoringInputWithExtractStepResultAndAnalyzeStepResult,\n) => Promise<{ reason: string; reasonPrompt?: string } | null>;\n\nexport type ScorerOptions = {\n  name: string;\n  description: string;\n  extract?: ExtractionStepFn;\n  analyze: AnalyzeStepFn;\n  reason?: ReasonStepFn;\n  metadata?: Record<string, any>;\n  isLLMScorer?: boolean;\n};\n\nexport type ScorerRunInputForAgent = {\n  inputMessages: MastraDBMessage[];\n  rememberedMessages: MastraDBMessage[];\n  systemMessages: CoreMessage[];\n  taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n};\n\nexport type ScorerRunOutputForAgent = MastraDBMessage[];\n\n// ============================================================================\n// Trajectory Types — Discriminated Union\n// ============================================================================\n\n/**\n * Base properties shared by all trajectory step types.\n */\nexport type TrajectoryStepBase = {\n  /** Name of the tool called, model used, or step executed */\n  name: string;\n  /** Duration of this step in milliseconds */\n  durationMs?: number;\n  /** Additional metadata about this step */\n  metadata?: Record<string, unknown>;\n  /** Nested child steps (e.g., tool calls inside a workflow step, or steps inside an agent run) */\n  children?: TrajectoryStep[];\n};\n\n// --- Individual step types ---\n\nexport type ToolCallStep = TrajectoryStepBase & {\n  stepType: 'tool_call';\n  /** Arguments passed to the tool */\n  toolArgs?: Record<string, unknown>;\n  /** Result returned by the tool */\n  toolResult?: Record<string, unknown>;\n  /** Whether the tool call succeeded */\n  success?: boolean;\n};\n\nexport type McpToolCallStep = TrajectoryStepBase & {\n  stepType: 'mcp_tool_call';\n  /** Arguments passed to the MCP tool */\n  toolArgs?: Record<string, unknown>;\n  /** Result returned by the MCP tool */\n  toolResult?: Record<string, unknown>;\n  /** The MCP server that handled this tool call */\n  mcpServer?: string;\n  /** Whether the tool call succeeded */\n  success?: boolean;\n};\n\nexport type ModelGenerationStep = TrajectoryStepBase & {\n  stepType: 'model_generation';\n  /** The model ID used for generation */\n  modelId?: string;\n  /** Number of prompt tokens consumed */\n  promptTokens?: number;\n  /** Number of completion tokens generated */\n  completionTokens?: number;\n  /** Reason the generation finished (e.g., 'stop', 'tool-calls') */\n  finishReason?: string;\n};\n\nexport type AgentRunStep = TrajectoryStepBase & {\n  stepType: 'agent_run';\n  /** The ID of the agent that was run */\n  agentId?: string;\n};\n\nexport type WorkflowStepStep = TrajectoryStepBase & {\n  stepType: 'workflow_step';\n  /** The step ID within the workflow */\n  stepId?: string;\n  /** Status of the step (e.g., 'success', 'failed', 'suspended') */\n  status?: string;\n  /** Output data from the step */\n  output?: Record<string, unknown>;\n};\n\nexport type WorkflowRunStep = TrajectoryStepBase & {\n  stepType: 'workflow_run';\n  /** The ID of the workflow that was run */\n  workflowId?: string;\n  /** Status of the workflow run */\n  status?: string;\n};\n\nexport type WorkflowConditionalStep = TrajectoryStepBase & {\n  stepType: 'workflow_conditional';\n  /** Number of conditions evaluated */\n  conditionCount?: number;\n  /** Steps selected by the conditional */\n  selectedSteps?: string[];\n};\n\nexport type WorkflowParallelStep = TrajectoryStepBase & {\n  stepType: 'workflow_parallel';\n  /** Number of parallel branches */\n  branchCount?: number;\n  /** Steps that ran in parallel */\n  parallelSteps?: string[];\n};\n\nexport type WorkflowLoopStep = TrajectoryStepBase & {\n  stepType: 'workflow_loop';\n  /** Type of loop (e.g., 'dowhile', 'dountil') */\n  loopType?: string;\n  /** Total number of iterations executed */\n  totalIterations?: number;\n};\n\nexport type WorkflowSleepStep = TrajectoryStepBase & {\n  stepType: 'workflow_sleep';\n  /** Sleep duration in milliseconds */\n  sleepDurationMs?: number;\n  /** Type of sleep */\n  sleepType?: string;\n};\n\nexport type WorkflowWaitEventStep = TrajectoryStepBase & {\n  stepType: 'workflow_wait_event';\n  /** Name of the event being waited on */\n  eventName?: string;\n  /** Whether the event was received */\n  eventReceived?: boolean;\n};\n\nexport type ProcessorRunStep = TrajectoryStepBase & {\n  stepType: 'processor_run';\n  /** The ID of the processor that was run */\n  processorId?: string;\n};\n\n/**\n * A single step in an agent's or workflow's trajectory.\n * Discriminated union on `stepType` — each variant carries properties specific\n * to that kind of action.\n */\nexport type TrajectoryStep =\n  | ToolCallStep\n  | McpToolCallStep\n  | ModelGenerationStep\n  | AgentRunStep\n  | WorkflowStepStep\n  | WorkflowRunStep\n  | WorkflowConditionalStep\n  | WorkflowParallelStep\n  | WorkflowLoopStep\n  | WorkflowSleepStep\n  | WorkflowWaitEventStep\n  | ProcessorRunStep;\n\n/**\n * The type of action taken in a trajectory step.\n * Derived from the discriminated union for convenience.\n */\nexport type TrajectoryStepType = TrajectoryStep['stepType'];\n\n/**\n * A complete trajectory: the ordered sequence of steps an agent or workflow took\n * to go from input to output.\n */\nexport type Trajectory = {\n  /** Ordered list of steps taken */\n  steps: TrajectoryStep[];\n  /** Total duration of the full trajectory in milliseconds */\n  totalDurationMs?: number;\n  /** The raw agent output messages, preserved for scorers that need text context */\n  rawOutput?: ScorerRunOutputForAgent;\n  /** The raw workflow result, preserved for scorers that need workflow-specific data */\n  rawWorkflowResult?: {\n    stepResults: Record<string, StepResult<any, any, any, any>>;\n    stepExecutionPath?: string[];\n  };\n};\n\n/**\n * Configuration for trajectory comparison behavior.\n */\nexport type TrajectoryComparisonOptions = {\n  /**\n   * How to compare step ordering.\n   * - 'strict': exact match (same steps, same order, no extras)\n   * - 'relaxed': subsequence match (extra steps OK, order matters)\n   * - 'unordered': just check presence (don't care about order)\n   * @default 'relaxed'\n   */\n  ordering?: 'strict' | 'relaxed' | 'unordered';\n  /**\n   * Whether to allow repeated steps in the trajectory.\n   * When false, repeated steps (loops) are penalized.\n   * @default true\n   */\n  allowRepeatedSteps?: boolean;\n};\n\n/**\n * Discriminated union mirroring `TrajectoryStep` — specify a `stepType` for autocomplete\n * on that variant's fields (e.g., `toolArgs` for `tool_call`). All variant-specific fields\n * are optional; only specified fields are used for comparison.\n *\n * Omit `stepType` to match any step by name only.\n *\n * @example\n * ```ts\n * // Match any step named 'search'\n * { name: 'search' }\n *\n * // Match a tool_call with specific args (autocomplete for toolArgs, toolResult, success)\n * { name: 'search', stepType: 'tool_call', toolArgs: { query: 'weather' } }\n *\n * // Match an agent run with nested expectations for its children\n * {\n *   name: 'researchAgent',\n *   stepType: 'agent_run',\n *   children: {\n *     ordering: 'unordered',\n *     steps: [\n *       { name: 'search', stepType: 'tool_call' },\n *       { name: 'summarize', stepType: 'tool_call' },\n *     ],\n *   },\n * }\n * ```\n */\n/**\n * Utility type: derive an expected-step variant from an actual TrajectoryStep variant.\n *\n * - Keeps `name` and `stepType` required (for discriminant narrowing)\n * - Makes all other variant-specific fields optional\n * - Drops `durationMs` and `metadata` (not useful for expectations)\n * - Replaces `children: TrajectoryStep[]` with `children: TrajectoryExpectation`\n */\ntype ToExpected<T extends TrajectoryStep> = Pick<T, 'name' | 'stepType'> &\n  Partial<Omit<T, 'name' | 'stepType' | 'children' | 'durationMs' | 'metadata'>> & {\n    /** Nested trajectory expectation for this step's children */\n    children?: TrajectoryExpectation;\n  };\n\n/**\n * Expected step with no specific `stepType` — matches any step by name only.\n * Use this when you don't care about the step type, just the name.\n */\ntype ExpectedGenericStep = {\n  /** Step name to match (tool name, agent ID, workflow step name, etc.) */\n  name: string;\n  /** Must be omitted for generic matching */\n  stepType?: undefined;\n  /** Nested trajectory expectation for this step's children */\n  children?: TrajectoryExpectation;\n};\n\n/**\n * A step expectation for trajectory evaluation.\n *\n * Discriminated union derived from `TrajectoryStep` — when you specify a `stepType`,\n * you get autocomplete for that variant's fields (e.g., `toolArgs` for `tool_call`).\n * Omit `stepType` to match any step by name only.\n *\n * @example\n * ```ts\n * // Name-only matching (any step type)\n * { name: 'search' }\n *\n * // Type-narrowed with autocomplete for toolArgs, toolResult, success\n * { name: 'search', stepType: 'tool_call', toolArgs: { query: 'weather' } }\n *\n * // Nested expectations for a sub-agent\n * {\n *   name: 'research-agent',\n *   stepType: 'agent_run',\n *   children: {\n *     ordering: 'unordered',\n *     steps: [\n *       { name: 'search', stepType: 'tool_call' },\n *       { name: 'summarize', stepType: 'tool_call' },\n *     ],\n *   },\n * }\n * ```\n */\nexport type ExpectedStep =\n  | ToExpected<ToolCallStep>\n  | ToExpected<McpToolCallStep>\n  | ToExpected<ModelGenerationStep>\n  | ToExpected<AgentRunStep>\n  | ToExpected<WorkflowStepStep>\n  | ToExpected<WorkflowRunStep>\n  | ToExpected<WorkflowConditionalStep>\n  | ToExpected<WorkflowParallelStep>\n  | ToExpected<WorkflowLoopStep>\n  | ToExpected<WorkflowSleepStep>\n  | ToExpected<WorkflowWaitEventStep>\n  | ToExpected<ProcessorRunStep>\n  | ExpectedGenericStep;\n\n/**\n * Full trajectory expectation config for the unified trajectory scorer.\n * Can be set as constructor defaults (agent-level) or per dataset item (prompt-specific).\n * Per-item values override constructor defaults.\n */\nexport type TrajectoryExpectation = {\n  // --- Accuracy ---\n\n  /** Expected steps for accuracy checking */\n  steps?: ExpectedStep[];\n\n  /**\n   * How to compare step ordering.\n   * - 'strict': exact match (same steps, same order, no extras)\n   * - 'relaxed': subsequence match (extra steps OK, order matters)\n   * - 'unordered': just check presence (don't care about order)\n   * @default 'relaxed'\n   */\n  ordering?: 'strict' | 'relaxed' | 'unordered';\n\n  /** Whether to allow repeated steps in accuracy evaluation. @default true */\n  allowRepeatedSteps?: boolean;\n\n  // --- Efficiency ---\n\n  /** Maximum number of steps allowed */\n  maxSteps?: number;\n\n  /** Maximum total tokens across all model_generation steps */\n  maxTotalTokens?: number;\n\n  /** Maximum total duration in milliseconds */\n  maxTotalDurationMs?: number;\n\n  /** Whether to penalize redundant calls (same tool + same args consecutively). @default true */\n  noRedundantCalls?: boolean;\n\n  // --- Blacklist ---\n\n  /** Tool names that should never appear in the trajectory */\n  blacklistedTools?: string[];\n\n  /** Tool name sequences that should never appear (contiguous subsequences) */\n  blacklistedSequences?: string[][];\n\n  // --- Tool failure tolerance ---\n\n  /** Maximum acceptable retries per tool before penalizing. @default 2 */\n  maxRetriesPerTool?: number;\n};\n\n// ============================================================================\n// Trajectory Extraction — Agent\n// ============================================================================\n\n/**\n * Extracts a Trajectory from agent output messages by walking through\n * tool invocations.\n *\n * This is called automatically by `runEvals` when using `AgentScorerConfig.trajectory`\n * scorers — trajectory scorers receive a pre-extracted `Trajectory` as their `output`\n * instead of raw `MastraDBMessage[]`.\n *\n * @param output - The raw agent output messages\n * @returns A Trajectory with ToolCallStep entries extracted from tool invocations\n */\nexport function extractTrajectory(output: ScorerRunOutputForAgent): Trajectory {\n  const steps: ToolCallStep[] = [];\n\n  for (const message of output) {\n    const toolInvocations = message?.content?.toolInvocations;\n    if (!toolInvocations) continue;\n\n    for (const invocation of toolInvocations) {\n      if (invocation && invocation.toolName && (invocation.state === 'result' || invocation.state === 'call')) {\n        const toolArgs =\n          invocation.args != null && typeof invocation.args === 'object' && !Array.isArray(invocation.args)\n            ? (invocation.args as Record<string, unknown>)\n            : invocation.args != null\n              ? { value: invocation.args }\n              : undefined;\n\n        const rawResult = invocation.state === 'result' ? invocation.result : undefined;\n        const toolResult =\n          rawResult != null && typeof rawResult === 'object' && !Array.isArray(rawResult)\n            ? (rawResult as Record<string, unknown>)\n            : rawResult != null\n              ? { value: rawResult }\n              : undefined;\n\n        steps.push({\n          stepType: 'tool_call',\n          name: invocation.toolName,\n          toolArgs,\n          toolResult,\n          success: invocation.state === 'result',\n        });\n      }\n    }\n  }\n\n  return { steps, rawOutput: output };\n}\n\n// ============================================================================\n// Trajectory Extraction — Workflow\n// ============================================================================\n\n/**\n * Extracts a Trajectory from workflow step results.\n *\n * Converts the `stepResults` record (and optional `stepExecutionPath` ordering)\n * into a flat list of `WorkflowStepStep` entries. Each step captures its status,\n * output, and timing.\n *\n * This is called automatically by `runEvals` when using `WorkflowScorerConfig.trajectory`\n * scorers.\n *\n * @param stepResults - The workflow step results record\n * @param stepExecutionPath - Optional ordered list of step IDs for execution ordering\n * @returns A Trajectory with WorkflowStepStep entries\n */\nexport function extractWorkflowTrajectory(\n  stepResults: Record<string, StepResult<any, any, any, any>>,\n  stepExecutionPath?: string[],\n): Trajectory {\n  const steps: WorkflowStepStep[] = [];\n\n  // Use stepExecutionPath ordering when available, fall back to stepResults keys\n  const stepIds = stepExecutionPath ?? Object.keys(stepResults);\n\n  let totalStartedAt: number | undefined;\n  let totalEndedAt: number | undefined;\n\n  for (const stepId of stepIds) {\n    const result = stepResults[stepId];\n    if (!result) continue;\n\n    // Track overall timing\n    if (result.startedAt != null) {\n      if (totalStartedAt == null || result.startedAt < totalStartedAt) {\n        totalStartedAt = result.startedAt;\n      }\n    }\n\n    const endedAt = 'endedAt' in result ? (result as { endedAt?: number }).endedAt : undefined;\n    if (endedAt != null) {\n      if (totalEndedAt == null || endedAt > totalEndedAt) {\n        totalEndedAt = endedAt;\n      }\n    }\n\n    const durationMs = result.startedAt != null && endedAt != null ? endedAt - result.startedAt : undefined;\n\n    const output =\n      'output' in result && result.output != null && typeof result.output === 'object' && !Array.isArray(result.output)\n        ? (result.output as Record<string, unknown>)\n        : 'output' in result && result.output != null\n          ? { value: result.output }\n          : undefined;\n\n    steps.push({\n      stepType: 'workflow_step',\n      name: stepId,\n      stepId,\n      status: result.status,\n      output,\n      durationMs,\n      metadata: result.metadata as Record<string, unknown> | undefined,\n    });\n  }\n\n  const totalDurationMs = totalStartedAt != null && totalEndedAt != null ? totalEndedAt - totalStartedAt : undefined;\n\n  return {\n    steps,\n    totalDurationMs,\n    rawWorkflowResult: { stepResults, stepExecutionPath },\n  };\n}\n\n// ============================================================================\n// Trajectory Extraction — From Trace (Hierarchical)\n// ============================================================================\n\n/**\n * Span types that are considered noise and should be skipped during\n * trace-to-trajectory conversion (internal implementation details, not\n * meaningful trajectory steps).\n */\nconst SKIPPED_SPAN_TYPES = new Set([\n  SpanType.SCORER_RUN,\n  SpanType.SCORER_STEP,\n  SpanType.GENERIC,\n  SpanType.MODEL_STEP,\n  SpanType.MODEL_CHUNK,\n  SpanType.WORKFLOW_CONDITIONAL_EVAL,\n]);\n\ntype SpanTreeNode = {\n  span: SpanRecord;\n  children: SpanTreeNode[];\n};\n\n/**\n * Converts a `SpanTreeNode` to `TrajectoryStep` entries.\n *\n * Returns an array because a skipped span promotes its children into the\n * parent's list rather than dropping them entirely.\n */\nfunction spanToTrajectorySteps(node: SpanTreeNode): TrajectoryStep[] {\n  const { span, children: childNodes } = node;\n\n  if (SKIPPED_SPAN_TYPES.has(span.spanType)) {\n    // Promote children of skipped spans so their subtree is preserved\n    return childNodes.flatMap(spanToTrajectorySteps);\n  }\n\n  const durationMs =\n    span.endedAt != null && span.startedAt != null ? span.endedAt.getTime() - span.startedAt.getTime() : undefined;\n\n  const childSteps = childNodes.flatMap(spanToTrajectorySteps);\n\n  const base: TrajectoryStepBase = {\n    name: span.name,\n    durationMs,\n    metadata: span.metadata as Record<string, unknown> | undefined,\n    ...(childSteps.length > 0 ? { children: childSteps } : {}),\n  };\n\n  const attrs = (span.attributes ?? {}) as Record<string, unknown>;\n\n  switch (span.spanType) {\n    case SpanType.TOOL_CALL: {\n      const toolArgs = toRecordOrUndefined(span.input);\n      const toolResult = toRecordOrUndefined(span.output);\n      return [\n        {\n          ...base,\n          stepType: 'tool_call' as const,\n          toolArgs,\n          toolResult,\n          success: typeof attrs.success === 'boolean' ? attrs.success : undefined,\n        },\n      ];\n    }\n\n    case SpanType.MCP_TOOL_CALL: {\n      const toolArgs = toRecordOrUndefined(span.input);\n      const toolResult = toRecordOrUndefined(span.output);\n      return [\n        {\n          ...base,\n          stepType: 'mcp_tool_call' as const,\n          toolArgs,\n          toolResult,\n          mcpServer: typeof attrs.mcpServer === 'string' ? attrs.mcpServer : undefined,\n          success: typeof attrs.success === 'boolean' ? attrs.success : undefined,\n        },\n      ];\n    }\n\n    case SpanType.MODEL_GENERATION: {\n      const usage = attrs.usage as { inputTokens?: number; outputTokens?: number } | undefined;\n      return [\n        {\n          ...base,\n          stepType: 'model_generation' as const,\n          modelId: typeof attrs.model === 'string' ? attrs.model : undefined,\n          promptTokens: usage?.inputTokens,\n          completionTokens: usage?.outputTokens,\n          finishReason: typeof attrs.finishReason === 'string' ? attrs.finishReason : undefined,\n        },\n      ];\n    }\n\n    case SpanType.AGENT_RUN:\n      return [{ ...base, stepType: 'agent_run' as const, agentId: span.entityId ?? undefined }];\n\n    case SpanType.WORKFLOW_RUN:\n      return [{ ...base, stepType: 'workflow_run' as const, workflowId: span.entityId ?? undefined }];\n\n    case SpanType.WORKFLOW_STEP: {\n      const output = toRecordOrUndefined(span.output);\n      return [{ ...base, stepType: 'workflow_step' as const, stepId: span.name, output }];\n    }\n\n    case SpanType.WORKFLOW_CONDITIONAL:\n      return [{ ...base, stepType: 'workflow_conditional' as const }];\n\n    case SpanType.WORKFLOW_PARALLEL:\n      return [{ ...base, stepType: 'workflow_parallel' as const }];\n\n    case SpanType.WORKFLOW_LOOP:\n      return [{ ...base, stepType: 'workflow_loop' as const }];\n\n    case SpanType.WORKFLOW_SLEEP:\n      return [{ ...base, stepType: 'workflow_sleep' as const }];\n\n    case SpanType.WORKFLOW_WAIT_EVENT:\n      return [{ ...base, stepType: 'workflow_wait_event' as const }];\n\n    case SpanType.PROCESSOR_RUN:\n      return [{ ...base, stepType: 'processor_run' as const }];\n\n    default:\n      // Unknown span type — promote children if any\n      return childSteps;\n  }\n}\n\n/**\n * Safely converts a value to `Record<string, unknown>` or returns undefined.\n */\nfunction toRecordOrUndefined(value: unknown): Record<string, unknown> | undefined {\n  if (value == null) return undefined;\n  if (typeof value === 'object' && !Array.isArray(value)) {\n    return value as Record<string, unknown>;\n  }\n  return { value };\n}\n\n/**\n * Extracts a hierarchical Trajectory from trace spans (as returned by the\n * observability store's `getTrace()`).\n *\n * Builds a parent-child tree from `parentSpanId` references, then recursively\n * converts each span to the appropriate `TrajectoryStep` discriminated union\n * type with nested `children`.\n *\n * Noise spans (`generic`, `model_step`, `model_chunk`, `workflow_conditional_eval`)\n * are automatically skipped.\n *\n * This is used by `runEvals` when storage is available to produce richer,\n * hierarchical trajectories that include nested agent runs, tool calls, and\n * model generations inside workflow or agent steps.\n *\n * @param spans - Flat array of span records from `getTrace().spans`\n * @param rootSpanId - Optional span ID to use as root. If omitted, spans with\n *   no parent are used as roots.\n * @returns A Trajectory with hierarchical TrajectoryStep entries\n *\n * @example\n * ```ts\n * const trace = await observabilityStore.getTrace({ traceId });\n * const trajectory = extractTrajectoryFromTrace(trace.spans, workflowSpanId);\n * ```\n */\nexport function extractTrajectoryFromTrace(spans: SpanRecord[], rootSpanId?: string): Trajectory {\n  if (spans.length === 0) {\n    return { steps: [] };\n  }\n\n  // Build lookup map\n  const nodeMap = new Map<string, SpanTreeNode>();\n  for (const span of spans) {\n    nodeMap.set(span.spanId, { span, children: [] });\n  }\n\n  // Attach children to parents\n  const roots: SpanTreeNode[] = [];\n  for (const span of spans) {\n    const node = nodeMap.get(span.spanId)!;\n    if (span.parentSpanId && nodeMap.has(span.parentSpanId)) {\n      nodeMap.get(span.parentSpanId)!.children.push(node);\n    } else {\n      roots.push(node);\n    }\n  }\n\n  // Sort children by start time\n  for (const node of nodeMap.values()) {\n    node.children.sort((a, b) => a.span.startedAt.getTime() - b.span.startedAt.getTime());\n  }\n\n  // Find the root to start from\n  let targetRoots: SpanTreeNode[];\n  if (rootSpanId) {\n    const rootNode = nodeMap.get(rootSpanId);\n    targetRoots = rootNode ? [rootNode] : roots;\n  } else {\n    targetRoots = roots;\n  }\n\n  // If the target is a single root span (e.g., a workflow_run or agent_run),\n  // convert its children directly as the trajectory steps (the root itself\n  // is the \"container\", not a step in the trajectory)\n  let stepsToConvert: SpanTreeNode[];\n  if (targetRoots.length === 1) {\n    const root = targetRoots[0]!;\n    // If root is a container span type, use its children as trajectory steps\n    const containerTypes = new Set([SpanType.WORKFLOW_RUN, SpanType.AGENT_RUN]);\n    if (containerTypes.has(root.span.spanType)) {\n      stepsToConvert = root.children;\n    } else {\n      stepsToConvert = targetRoots;\n    }\n  } else {\n    stepsToConvert = targetRoots;\n  }\n\n  const steps = stepsToConvert.flatMap(spanToTrajectorySteps);\n\n  // Calculate total duration from the root span(s)\n  let totalDurationMs: number | undefined;\n  if (targetRoots.length === 1) {\n    const root = targetRoots[0]!.span;\n    if (root.endedAt && root.startedAt) {\n      totalDurationMs = root.endedAt.getTime() - root.startedAt.getTime();\n    }\n  }\n\n  return { steps, totalDurationMs };\n}\n","import { z } from 'zod/v4';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } from '../../../observability/types';\nimport {\n  spanContextFields,\n  dateRangeSchema,\n  dbTimestamps,\n  metadataField,\n  paginationArgsSchema,\n  paginationInfoSchema,\n  sortDirectionSchema,\n  tagsField,\n  traceIdField,\n  spanIdField,\n} from '../shared';\n\nexport { traceIdField, spanIdField };\n\n// ============================================================================\n// Helper utilities for creating omit key objects from schema shapes\n// ============================================================================\n\n/**\n * Creates an omit key object from a Zod schema shape.\n * This allows dynamically deriving omit keys from existing schema definitions.\n */\nconst createOmitKeys = <T extends z.ZodRawShape>(shape: T): { [K in keyof T]: true } =>\n  Object.fromEntries(Object.keys(shape).map(k => [k, true])) as { [K in keyof T]: true };\n\n// ============================================================================\n// Primitive Field Definitions\n// ============================================================================\n\nconst spanNameField = z.string().describe('Human-readable span name');\nconst parentSpanIdField = z.string().describe('Parent span reference (null = root span)');\nconst spanTypeField = z.nativeEnum(SpanType).describe('Span type (e.g., WORKFLOW_RUN, AGENT_RUN, TOOL_CALL, etc.)');\nconst attributesField = z\n  .record(z.string(), z.unknown())\n  .describe('Span-type specific attributes (e.g., model, tokens, tools)');\nconst linksField = z.array(z.unknown()).describe('References to related spans in other traces');\nconst inputField = z.unknown().describe('Input data passed to the span');\nconst outputField = z.unknown().describe('Output data returned from the span');\nconst errorField = z.unknown().describe('Error info - presence indicates failure (status derived from this)');\nconst isEventField = z.boolean().describe('Whether this is an event (point-in-time) vs a span (duration)');\nconst startedAtField = z.date().describe('When the span started');\nconst endedAtField = z.date().describe('When the span ended (null = running, status derived from this)');\n\n/** Derived status of a trace, computed from the root span's error and endedAt fields. */\nexport enum TraceStatus {\n  SUCCESS = 'success',\n  ERROR = 'error',\n  RUNNING = 'running',\n}\n\nconst traceStatusField = z.nativeEnum(TraceStatus).describe('Current status of the trace');\n\nconst hasChildErrorField = z\n  .preprocess(v => {\n    // Handle string \"true\"/\"false\" from query params correctly\n    // z.coerce.boolean() would convert \"false\" to true (Boolean(\"false\") === true)\n    if (v === 'true') return true;\n    if (v === 'false') return false;\n    return v;\n  }, z.boolean())\n  .describe('True if any span in the trace encountered an error');\n\n// ============================================================================\n// Shared Fields (used by both spanRecordSchema and tracesFilterSchema)\n// ============================================================================\n\n/**\n * All optional fields shared between span records and trace filters.\n * Built from spanContextFields plus span-specific metadata/tags.\n * Note: When filtering traces, these fields are matched against the root span.\n */\nconst sharedFields = {\n  ...spanContextFields,\n  metadata: metadataField.nullish(),\n  tags: tagsField.nullish(),\n} as const;\n\n// ============================================================================\n// Span Record Schema (for storage)\n// ============================================================================\n\n/** Shape containing trace and span identifier fields */\nexport const spanIds = {\n  traceId: traceIdField,\n  spanId: spanIdField,\n} as const satisfies z.ZodRawShape;\n\n/** Schema for span identifiers (traceId and spanId) */\nexport const spanIdsSchema = z.object({\n  ...spanIds,\n});\n\n/** Span identifier pair (traceId and spanId) */\nexport type SpanIds = z.infer<typeof spanIdsSchema>;\n\n// Omit key objects derived from schema shapes for use with .omit()\nconst omitDbTimestamps = createOmitKeys(dbTimestamps);\nconst omitSpanIds = createOmitKeys(spanIds);\n\n/** Schema for a complete span record as stored in the database */\nexport const spanRecordSchema = z\n  .object({\n    // Required identifiers\n    ...spanIds,\n    name: spanNameField,\n    spanType: spanTypeField,\n    isEvent: isEventField,\n    startedAt: startedAtField,\n\n    // Shared fields\n    parentSpanId: parentSpanIdField.nullish(),\n    ...sharedFields,\n\n    // Experimentation\n    experimentId: z.string().nullish().describe('Experiment or eval run identifier'),\n\n    // Additional span-specific nullish fields\n    attributes: attributesField.nullish(),\n    links: linksField.nullish(),\n    input: inputField.nullish(),\n    output: outputField.nullish(),\n    error: errorField.nullish(),\n    endedAt: endedAtField.nullish(),\n    requestContext: z.record(z.string(), z.unknown()).nullish().describe('Request context data'),\n\n    // Database timestamps\n    ...dbTimestamps,\n  })\n  .describe('Span record data');\n\n/** Complete span record as stored in the database */\nexport type SpanRecord = z.infer<typeof spanRecordSchema>;\n\n// ============================================================================\n// Trace Span Schema (SpanRecord + computed status for list responses)\n// ============================================================================\n\n/**\n * Computes the trace status from a root span's error and endedAt fields.\n * - ERROR: if error is present (regardless of endedAt)\n * - RUNNING: if endedAt is null/undefined and no error\n * - SUCCESS: if endedAt is present and no error\n */\nexport function computeTraceStatus(span: SpanRecord): TraceStatus {\n  if (span.error != null) return TraceStatus.ERROR;\n  if (span.endedAt == null) return TraceStatus.RUNNING;\n  return TraceStatus.SUCCESS;\n}\n\n/** Schema for a trace span (root span with computed status) */\nexport const traceSpanSchema = spanRecordSchema\n  .extend({\n    status: traceStatusField,\n  })\n  .describe('Trace span with computed status (root spans only)');\n\n/** Trace span (root span with computed status) */\nexport type TraceSpan = z.infer<typeof traceSpanSchema>;\n\n/**\n * Converts a SpanRecord to a TraceSpan by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpan(span: SpanRecord): TraceSpan {\n  return {\n    ...span,\n    status: computeTraceStatus(span),\n  };\n}\n\n/**\n * Converts an array of SpanRecords to TraceSpans by adding computed status.\n * Used when returning root spans from listTraces.\n */\nexport function toTraceSpans(spans: SpanRecord[]): TraceSpan[] {\n  return spans.map(toTraceSpan);\n}\n\n// ============================================================================\n// Storage Operation Schemas\n// ============================================================================\n\n/**\n * Schema for creating a span (without db timestamps)\n */\nexport const createSpanRecordSchema = spanRecordSchema.omit(omitDbTimestamps);\n\n/** Span record for creation (excludes db timestamps) */\nexport type CreateSpanRecord = z.infer<typeof createSpanRecordSchema>;\n\n/**\n * Schema for createSpan operation arguments\n */\nexport const createSpanArgsSchema = z\n  .object({\n    span: createSpanRecordSchema,\n  })\n  .describe('Arguments for creating a single span');\n\n/** Arguments for creating a single span */\nexport type CreateSpanArgs = z.infer<typeof createSpanArgsSchema>;\n\n/**\n * Schema for batchCreateSpans operation arguments\n */\nexport const batchCreateSpansArgsSchema = z\n  .object({\n    records: z.array(createSpanRecordSchema),\n  })\n  .describe('Arguments for batch creating spans');\n\n/** Arguments for batch creating multiple spans */\nexport type BatchCreateSpansArgs = z.infer<typeof batchCreateSpansArgsSchema>;\n\n/**\n * Schema for getSpan operation arguments\n */\nexport const getSpanArgsSchema = z\n  .object({\n    traceId: traceIdField.min(1),\n    spanId: spanIdField.min(1),\n  })\n  .describe('Arguments for getting a single span');\n\n/** Arguments for retrieving a single span */\nexport type GetSpanArgs = z.infer<typeof getSpanArgsSchema>;\n\n/**\n * Response schema for getSpan operation\n */\nexport const getSpanResponseSchema = z.object({\n  span: spanRecordSchema,\n});\n\n/** Response containing a single span */\nexport type GetSpanResponse = z.infer<typeof getSpanResponseSchema>;\n\n/**\n * Schema for getRootSpan operation arguments\n */\nexport const getRootSpanArgsSchema = z\n  .object({\n    traceId: traceIdField.min(1),\n  })\n  .describe('Arguments for getting a root span');\n\n/** Arguments for retrieving a root span */\nexport type GetRootSpanArgs = z.infer<typeof getRootSpanArgsSchema>;\n\n/**\n * Response schema for getRootSpan operation\n */\nexport const getRootSpanResponseSchema = z.object({\n  span: spanRecordSchema,\n});\n\n/** Response containing a single root span */\nexport type GetRootSpanResponse = z.infer<typeof getRootSpanResponseSchema>;\n\n/**\n * Schema for getTrace operation arguments\n */\nexport const getTraceArgsSchema = z\n  .object({\n    traceId: traceIdField.min(1),\n  })\n  .describe('Arguments for getting a single trace');\n\n/** Arguments for retrieving a single trace */\nexport type GetTraceArgs = z.infer<typeof getTraceArgsSchema>;\n\n/**\n * Response schema for getTrace operation\n */\nexport const getTraceResponseSchema = z.object({\n  traceId: traceIdField,\n  spans: z.array(spanRecordSchema),\n});\n\n/** Response containing a trace with all its spans */\nexport type GetTraceResponse = z.infer<typeof getTraceResponseSchema>;\n\n/** Alias for GetTraceResponse -- a trace with all its spans. */\nexport type TraceRecord = GetTraceResponse;\n\n/** Schema for filtering traces in list queries */\nexport const tracesFilterSchema = z\n  .object({\n    // Date range filters\n    startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n    endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n    // Span type filter\n    spanType: spanTypeField.optional(),\n\n    // Shared fields\n    ...sharedFields,\n\n    // Filter-specific derived status fields\n    status: traceStatusField.optional(),\n    hasChildError: hasChildErrorField.optional(),\n  })\n  .describe('Filters for querying traces');\n\n/**\n * Fields available for ordering trace results\n */\nexport const tracesOrderByFieldSchema = z\n  .enum(['startedAt', 'endedAt'])\n  .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\n/**\n * Order by configuration for trace queries\n * Follows the existing StorageOrderBy pattern\n * Defaults to startedAt desc (newest first)\n */\nexport const tracesOrderBySchema = z\n  .object({\n    field: tracesOrderByFieldSchema.default('startedAt').describe('Field to order by'),\n    direction: sortDirectionSchema.default('DESC').describe('Sort direction'),\n  })\n  .describe('Order by configuration');\n\n/**\n * Arguments for listing traces\n */\nexport const listTracesArgsSchema = z\n  .object({\n    filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n    pagination: paginationArgsSchema.default({ page: 0, perPage: 10 }).describe('Pagination settings'),\n    orderBy: tracesOrderBySchema\n      .default({ field: 'startedAt', direction: 'DESC' })\n      .describe('Ordering configuration (defaults to startedAt desc)'),\n  })\n  .describe('Arguments for listing traces');\n\n/** Arguments for listing traces with optional filters, pagination, and ordering */\nexport type ListTracesArgs = z.input<typeof listTracesArgsSchema>;\n\n/** Schema for listTraces operation response */\nexport const listTracesResponseSchema = z.object({\n  pagination: paginationInfoSchema,\n  spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/**\n * Schema for updating a span (without db timestamps and span IDs)\n */\nexport const updateSpanRecordSchema = createSpanRecordSchema.omit(omitSpanIds);\n\n/** Partial span data for updates (excludes db timestamps and span IDs) */\nexport type UpdateSpanRecord = z.infer<typeof updateSpanRecordSchema>;\n\n/**\n * Schema for updateSpan operation arguments\n */\nexport const updateSpanArgsSchema = z\n  .object({\n    spanId: spanIdField,\n    traceId: traceIdField,\n    updates: updateSpanRecordSchema.partial(),\n  })\n  .describe('Arguments for updating a single span');\n\n/** Arguments for updating a single span */\nexport type UpdateSpanArgs = z.infer<typeof updateSpanArgsSchema>;\n\n/**\n * Schema for batchUpdateSpans operation arguments\n */\nexport const batchUpdateSpansArgsSchema = z\n  .object({\n    records: z.array(\n      z.object({\n        traceId: traceIdField,\n        spanId: spanIdField,\n        updates: updateSpanRecordSchema.partial(),\n      }),\n    ),\n  })\n  .describe('Arguments for batch updating spans');\n\n/** Arguments for batch updating multiple spans */\nexport type BatchUpdateSpansArgs = z.infer<typeof batchUpdateSpansArgsSchema>;\n\n/**\n * Schema for batchDeleteTraces operation arguments\n */\nexport const batchDeleteTracesArgsSchema = z\n  .object({\n    traceIds: z.array(traceIdField),\n  })\n  .describe('Arguments for batch deleting traces');\n\n/** Arguments for batch deleting multiple traces */\nexport type BatchDeleteTracesArgs = z.infer<typeof batchDeleteTracesArgsSchema>;\n\n// ============================================================================\n// Scoring related schemas\n// ============================================================================\n\n/** Schema for listScoresBySpan operation response */\nexport const listScoresBySpanResponseSchema = z.object({\n  pagination: paginationInfoSchema,\n  scores: z.array(scoreRowDataSchema),\n});\n\n/** Schema for scoreTraces operation request */\nexport const scoreTracesRequestSchema = z.object({\n  scorerName: z.string().min(1),\n  targets: z\n    .array(\n      z.object({\n        traceId: traceIdField,\n        spanId: spanIdField.optional(),\n      }),\n    )\n    .min(1),\n});\n\n/** Request to score traces using a specific scorer */\nexport type ScoreTracesRequest = z.infer<typeof scoreTracesRequestSchema>;\n\n/** Schema for scoreTraces operation response */\nexport const scoreTracesResponseSchema = z.object({\n  status: z.string(),\n  message: z.string(),\n  traceCount: z.number(),\n});\n\n/** Response from scoring traces */\nexport type ScoreTracesResponse = z.infer<typeof scoreTracesResponseSchema>;\n","import type { z } from 'zod/v4';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig } from '../evals/types';\nimport type { MastraDBMessage, StorageThreadType, SerializedMemoryConfig } from '../memory/types';\nimport type { ProcessorPhase } from '../processor-provider';\nimport { getZodInnerType, getZodTypeName } from '../utils/zod-utils';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from '../workflows';\n\nexport type StoragePagination = {\n  page: number;\n  perPage: number | false;\n};\n\nexport type StorageColumnType = 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'float' | 'bigint' | 'boolean';\n\nexport interface StorageColumn {\n  type: StorageColumnType;\n  primaryKey?: boolean;\n  nullable?: boolean;\n  references?: {\n    table: string;\n    column: string;\n  };\n}\n\nexport interface StorageTableConfig {\n  columns: Record<string, StorageColumn>;\n  compositePrimaryKey?: string[];\n}\nexport interface WorkflowRuns {\n  runs: WorkflowRun[];\n  total: number;\n}\n\nexport interface StorageWorkflowRun {\n  workflow_name: string;\n  run_id: string;\n  resourceId?: string;\n  snapshot: WorkflowRunState | string;\n  createdAt: Date;\n  updatedAt: Date;\n}\nexport interface WorkflowRun {\n  workflowName: string;\n  runId: string;\n  snapshot: WorkflowRunState | string;\n  createdAt: Date;\n  updatedAt: Date;\n  resourceId?: string;\n}\n\nexport type PaginationInfo = {\n  total: number;\n  page: number;\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * When `false`, all matching records are returned in a single response.\n   */\n  perPage: number | false;\n  hasMore: boolean;\n};\n\nexport type MastraMessageFormat = 'v1' | 'v2';\n\n/**\n * Common options for listing messages (pagination, filtering, ordering)\n */\ntype StorageListMessagesOptions = {\n  include?: {\n    id: string;\n    threadId?: string;\n    withPreviousMessages?: number;\n    withNextMessages?: number;\n  }[];\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 40 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  filter?: {\n    dateRange?: {\n      start?: Date;\n      end?: Date;\n      /**\n       * When true, excludes the start date from results (uses > instead of >=).\n       * Useful for cursor-based pagination to avoid duplicates.\n       * @default false\n       */\n      startExclusive?: boolean;\n      /**\n       * When true, excludes the end date from results (uses < instead of <=).\n       * Useful for cursor-based pagination to avoid duplicates.\n       * @default false\n       */\n      endExclusive?: boolean;\n    };\n  };\n  orderBy?: StorageOrderBy<'createdAt'>;\n};\n\n/**\n * Input for listing messages by thread ID.\n * The resource ID can be optionally provided to filter messages within the thread.\n */\nexport type StorageListMessagesInput = StorageListMessagesOptions & {\n  /**\n   * Thread ID(s) to query messages from.\n   */\n  threadId: string | string[];\n  /**\n   * Optional resource ID to further filter messages within the thread(s).\n   */\n  resourceId?: string;\n};\n\nexport type StorageListMessagesOutput = PaginationInfo & {\n  messages: MastraDBMessage[];\n};\n\n/**\n * Input for listing messages by resource ID only (across all threads).\n * Used by Observational Memory and LongMemEval for resource-scoped queries.\n */\nexport type StorageListMessagesByResourceIdInput = StorageListMessagesOptions & {\n  /**\n   * Resource ID to query ALL messages for the resource across all threads.\n   */\n  resourceId: string;\n};\n\nexport type StorageListWorkflowRunsInput = {\n  workflowName?: string;\n  fromDate?: Date;\n  toDate?: Date;\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * When undefined, returns all workflow runs without pagination.\n   * When both perPage and page are provided, pagination is applied.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * When both perPage and page are provided, pagination is applied.\n   * When either is undefined, all results are returned.\n   */\n  page?: number;\n  resourceId?: string;\n  status?: WorkflowRunStatus;\n};\n\nexport type StorageListThreadsInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter options for querying threads.\n   */\n  filter?: {\n    /**\n     * Filter threads by resource ID.\n     */\n    resourceId?: string;\n    /**\n     * Filter threads by metadata key-value pairs.\n     * All specified key-value pairs must match (AND logic).\n     */\n    metadata?: Record<string, unknown>;\n  };\n};\n\nexport type StorageListThreadsOutput = PaginationInfo & {\n  threads: StorageThreadType[];\n};\n\n/**\n * Metadata stored on cloned threads to track their origin\n */\nexport type ThreadCloneMetadata = {\n  /** ID of the thread this was cloned from */\n  sourceThreadId: string;\n  /** Timestamp when the clone was created */\n  clonedAt: Date;\n  /** ID of the last message included in the clone (if messages were copied) */\n  lastMessageId?: string;\n};\n\n/**\n * Input options for cloning a thread\n */\nexport type StorageCloneThreadInput = {\n  /** ID of the thread to clone */\n  sourceThreadId: string;\n  /** ID for the new cloned thread (if not provided, a random UUID will be generated) */\n  newThreadId?: string;\n  /** Resource ID for the new thread (defaults to source thread's resourceId) */\n  resourceId?: string;\n  /** Title for the new cloned thread */\n  title?: string;\n  /** Additional metadata to merge with clone metadata */\n  metadata?: Record<string, unknown>;\n  /** Options for filtering which messages to include */\n  options?: {\n    /** Maximum number of messages to copy (from most recent) */\n    messageLimit?: number;\n    /** Filter messages by date range or specific IDs */\n    messageFilter?: {\n      /** Only include messages created on or after this date */\n      startDate?: Date;\n      /** Only include messages created on or before this date */\n      endDate?: Date;\n      /** Only include messages with these specific IDs */\n      messageIds?: string[];\n    };\n  };\n};\n\n/**\n * Output from cloning a thread\n */\nexport type StorageCloneThreadOutput = {\n  /** The newly created cloned thread */\n  thread: StorageThreadType;\n  /** The messages that were copied to the new thread */\n  clonedMessages: MastraDBMessage[];\n  /** Map from source message IDs to cloned message IDs (used for OM remapping) */\n  messageIdMap?: Record<string, string>;\n};\n\nexport type StorageResourceType = {\n  id: string;\n  workingMemory?: string;\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n};\n\nexport type StorageMessageType = {\n  id: string;\n  thread_id: string;\n  content: string;\n  role: string;\n  type: string;\n  createdAt: Date;\n  resourceId: string | null;\n};\n\nexport interface StorageOrderBy<TField extends ThreadOrderBy = ThreadOrderBy> {\n  field?: TField;\n  direction?: ThreadSortDirection;\n}\n\nexport interface ThreadSortOptions {\n  orderBy?: ThreadOrderBy;\n  sortDirection?: ThreadSortDirection;\n}\n\nexport type ThreadOrderBy = 'createdAt' | 'updatedAt';\n\nexport type ThreadSortDirection = 'ASC' | 'DESC';\n\n// Agent Storage Types\n\n/**\n * Per-tool configuration stored in agent snapshots.\n * Allows overriding the tool description for this specific agent.\n */\nexport interface StorageToolConfig {\n  /** Custom description override for this tool in this agent context */\n  description?: string;\n  /** Conditional rules for when this tool should be available */\n  rules?: RuleGroup;\n}\n\n/**\n * Per-MCP-client tool configuration stored in agent snapshots.\n * Specifies which tools from an MCP client are enabled and their overrides.\n * When `tools` is omitted, all tools from the MCP client/server are included.\n */\nexport interface StorageMCPClientToolsConfig {\n  /** When omitted, all tools from the source are included. */\n  tools?: Record<string, StorageToolConfig>;\n}\n\n/**\n * Scorer reference with optional sampling configuration\n */\nexport interface StorageScorerConfig {\n  /** Custom description override for this scorer in this agent context */\n  description?: string;\n  /** Sampling configuration for this scorer */\n  sampling?: ScoringSamplingConfig;\n  /** Conditional rules for when this scorer should be active */\n  rules?: RuleGroup;\n}\n\n/**\n * Model configuration stored in agent snapshots.\n */\nexport interface StorageModelConfig {\n  /** Model provider (e.g., 'openai', 'anthropic') */\n  provider: string;\n  /** Model name (e.g., 'gpt-4o', 'claude-3-opus') */\n  name: string;\n  /** Temperature for generation */\n  temperature?: number;\n  /** Top-p sampling parameter */\n  topP?: number;\n  /** Frequency penalty */\n  frequencyPenalty?: number;\n  /** Presence penalty */\n  presencePenalty?: number;\n  /** Maximum completion tokens */\n  maxCompletionTokens?: number;\n  /** Additional provider-specific options */\n  [key: string]: unknown;\n}\n\n/**\n * Default options stored in agent snapshots.\n * Based on AgentExecutionOptionsBase but omitting non-serializable properties.\n *\n * Non-serializable properties that are omitted:\n * - Callbacks (onStepFinish, onFinish, onChunk, onError, onAbort, prepareStep)\n * - Runtime objects (requestContext, abortSignal, tracingContext)\n * - Functions and processor instances (inputProcessors, outputProcessors, clientTools, scorers)\n * - Tools/toolsets (contain functions, stored separately as references)\n * - Complex types (context, memory, instructions, system, stopWhen)\n */\nexport type StorageDefaultOptions = Omit<\n  AgentExecutionOptionsBase<any>,\n  // Callback functions\n  | 'onStepFinish'\n  | 'onFinish'\n  | 'onChunk'\n  | 'onError'\n  | 'onAbort'\n  | 'prepareStep'\n  // Runtime objects\n  | 'abortSignal'\n  | 'requestContext'\n  | 'tracingContext'\n  // Functions and processor instances\n  | 'inputProcessors'\n  | 'outputProcessors'\n  | 'clientTools'\n  | 'scorers'\n  | 'toolsets'\n  // Complex types\n  | 'context' // ModelMessage includes complex content types (images, files)\n  | 'memory' // AgentMemoryOption might contain runtime memory instances\n  | 'instructions' // SystemMessage can be arrays or complex message objects\n  | 'system' // SystemMessage can be arrays or complex message objects\n  | 'stopWhen' // StopCondition is a complex union type from AI SDK\n  | 'providerOptions' // ProviderOptions includes provider-specific types from external packages\n>;\n\n/**\n * A conditional variant: a value paired with an optional RuleGroup.\n * When rules are present, the value is only used if rules evaluate to true against the request context.\n * When rules are absent, the variant acts as the default/fallback.\n */\nexport interface StorageConditionalVariant<T> {\n  value: T;\n  rules?: RuleGroup;\n}\n\n/**\n * A field that can be either a static value or an array of conditional variants.\n * When an array of variants, all matching variants accumulate:\n * arrays are concatenated and objects are shallow-merged.\n * A variant with no rules always matches (acts as the default/base).\n */\nexport type StorageConditionalField<T> = T | StorageConditionalVariant<T>[];\n\n/**\n * Agent version snapshot type containing ALL agent configuration fields.\n * These fields live exclusively in version snapshot rows, not on the agent record.\n */\nexport interface StorageAgentSnapshotType {\n  /** Display name of the agent */\n  name: string;\n  /** Purpose description */\n  description?: string;\n  /** System instructions/prompt — plain string for backward compatibility, or array of instruction blocks */\n  instructions: string | AgentInstructionBlock[];\n  /** Model configuration (provider, name, etc.) — static or conditional on request context */\n  model: StorageConditionalField<StorageModelConfig>;\n  /** Tool keys with optional per-tool config — static or conditional on request context */\n  tools?: StorageConditionalField<Record<string, StorageToolConfig>>;\n  /** Default options for generate/stream calls — static or conditional on request context */\n  defaultOptions?: StorageConditionalField<StorageDefaultOptions>;\n  /** Workflow keys with optional per-workflow config — static or conditional on request context */\n  workflows?: StorageConditionalField<Record<string, StorageToolConfig>>;\n  /** Agent keys with optional per-agent config — static or conditional on request context */\n  agents?: StorageConditionalField<Record<string, StorageToolConfig>>;\n  /**\n   * Map of tool provider IDs to their tool configurations.\n   * Keys are provider IDs (e.g., \"composio\"), values configure which tools from that provider to include.\n   * Static or conditional on request context.\n   */\n  integrationTools?: StorageConditionalField<Record<string, StorageMCPClientToolsConfig>>;\n  /** Processor graph for input processing — static or conditional on request context */\n  inputProcessors?: StorageConditionalField<StoredProcessorGraph>;\n  /** Processor graph for output processing — static or conditional on request context */\n  outputProcessors?: StorageConditionalField<StoredProcessorGraph>;\n  /** Memory configuration object — static or conditional on request context */\n  memory?: StorageConditionalField<SerializedMemoryConfig>;\n  /** Scorer keys with optional sampling config — static or conditional on request context */\n  scorers?: StorageConditionalField<Record<string, StorageScorerConfig>>;\n  /** Map of stored MCP client IDs to their tool configurations — static or conditional on request context */\n  mcpClients?: StorageConditionalField<Record<string, StorageMCPClientToolsConfig>>;\n  /** Workspace reference — ID of a stored workspace or inline config — static or conditional on request context */\n  workspace?: StorageConditionalField<StorageWorkspaceRef>;\n  /** Skill entity IDs with optional per-skill overrides — static or conditional on request context */\n  skills?: StorageConditionalField<Record<string, StorageSkillConfig>>;\n  /** Skill format for system message injection (default: 'xml') */\n  skillsFormat?: 'xml' | 'json' | 'markdown';\n  /** JSON Schema for validating request context values. Stored as JSON Schema since Zod is not serializable. */\n  requestContextSchema?: Record<string, unknown>;\n}\n\n/**\n * Thin agent record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageAgentSnapshotType).\n */\nexport interface StorageAgentType {\n  /** Unique, immutable identifier */\n  id: string;\n  /** Agent status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to agent_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the agent */\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Resolved agent type that combines the thin agent record with version snapshot config.\n * Returned by getAgentByIdResolved and listAgentsResolved.\n */\nexport type StorageResolvedAgentType = StorageAgentType &\n  StorageAgentSnapshotType & {\n    /** The version ID that was resolved (populated by resolveEntity) */\n    resolvedVersionId?: string;\n  };\n\n/**\n * Input for creating a new agent. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateAgentInput = {\n  /** Unique identifier for the agent */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the agent */\n  metadata?: Record<string, unknown>;\n} & StorageAgentSnapshotType;\n\n/**\n * Input for updating an agent. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into agent-record updates vs new-version creation.\n *\n * Memory can be set to `null` to explicitly disable/remove memory from the agent.\n */\nexport type StorageUpdateAgentInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the agent */\n  metadata?: Record<string, unknown>;\n  /** FK to agent_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Agent status: 'draft' or 'published' */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<Omit<StorageAgentSnapshotType, 'memory'>> & {\n    /** Memory configuration object (static or conditional), or null to disable memory */\n    memory?: StorageConditionalField<SerializedMemoryConfig> | null;\n  };\n\nexport type StorageListAgentsInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter agents by author identifier (indexed for fast lookups).\n   * Only agents with matching authorId will be returned.\n   */\n  authorId?: string;\n  /**\n   * Filter agents by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n  /**\n   * Filter agents by status.\n   * Defaults to 'published' if not specified.\n   */\n  status?: 'draft' | 'published' | 'archived';\n};\n\nexport type StorageListAgentsOutput = PaginationInfo & {\n  agents: StorageAgentType[];\n};\n\nexport type StorageListAgentsResolvedOutput = PaginationInfo & {\n  agents: StorageResolvedAgentType[];\n};\n\n// ============================================\n// Prompt Block Storage Types\n// ============================================\n\n/** Instruction block discriminated union, stored in agent snapshots */\nexport type AgentInstructionBlock =\n  | { type: 'text'; content: string }\n  | { type: 'prompt_block_ref'; id: string }\n  | { type: 'prompt_block'; content: string; rules?: RuleGroup };\n\n/** Condition operators for rule evaluation */\nexport type ConditionOperator =\n  | 'equals'\n  | 'not_equals'\n  | 'contains'\n  | 'not_contains'\n  | 'greater_than'\n  | 'less_than'\n  | 'greater_than_or_equal'\n  | 'less_than_or_equal'\n  | 'in'\n  | 'not_in'\n  | 'exists'\n  | 'not_exists';\n\n/** Leaf rule: evaluates a single condition against a context field */\nexport interface Rule {\n  field: string;\n  operator: ConditionOperator;\n  value?: unknown;\n}\n\n/**\n * Rule group with a fixed nesting depth of 3 levels.\n * Depth is capped to keep TypeScript and Zod/JSON-Schema types aligned\n * (recursive types cause infinite-depth issues in JSON Schema generation).\n *\n * Innermost groups (depth 2) may only contain leaf Rules.\n * Mid-level groups (depth 1) may contain Rules or depth-2 groups.\n * Top-level groups (depth 0, exported as `RuleGroup`) may contain Rules or depth-1 groups.\n */\nexport interface RuleGroupDepth2 {\n  operator: 'AND' | 'OR';\n  conditions: Rule[];\n}\n\nexport interface RuleGroupDepth1 {\n  operator: 'AND' | 'OR';\n  conditions: (Rule | RuleGroupDepth2)[];\n}\n\nexport interface RuleGroup {\n  operator: 'AND' | 'OR';\n  conditions: (Rule | RuleGroupDepth1)[];\n}\n\n// ============================================================================\n// Stored Processor Graph Types\n// ============================================================================\n\n/**\n * A single processor step in a stored processor graph.\n * Each step references a ProcessorProvider by ID and stores its configuration.\n */\nexport interface ProcessorGraphStep {\n  /** Unique ID for this step within the graph */\n  id: string;\n  /** The ProcessorProvider ID that created this processor */\n  providerId: string;\n  /** Configuration matching the provider's configSchema, validated at creation time */\n  config: Record<string, unknown>;\n  /** Which processor phases to enable (subset of the provider's availablePhases) */\n  enabledPhases: ProcessorPhase[];\n}\n\n/**\n * Processor graph entry and condition types with a fixed nesting depth of 3 levels.\n * Depth is capped to keep TypeScript and Zod/JSON-Schema types aligned\n * (recursive types cause infinite-depth issues in JSON Schema generation).\n *\n * Innermost entries (depth 3) may only be step entries.\n * Mid-level entries (depth 2) may contain step, parallel, or conditional — children limited to depth 3.\n * Top-level entries (depth 1, exported as `ProcessorGraphEntry`) may contain step, parallel, or conditional — children limited to depth 2.\n */\n\n/** Depth 3 (leaf): only step entries allowed */\nexport type ProcessorGraphEntryDepth3 = { type: 'step'; step: ProcessorGraphStep };\n\n/** Condition at depth 2 — children are depth 3 entries */\nexport interface ProcessorGraphConditionDepth2 {\n  steps: ProcessorGraphEntryDepth3[];\n  rules?: RuleGroup;\n}\n\n/** Depth 2: step, parallel, and conditional — children limited to depth 3 */\nexport type ProcessorGraphEntryDepth2 =\n  | { type: 'step'; step: ProcessorGraphStep }\n  | { type: 'parallel'; branches: ProcessorGraphEntryDepth3[][] }\n  | { type: 'conditional'; conditions: ProcessorGraphConditionDepth2[] };\n\n/** Condition at depth 1 — children are depth 2 entries */\nexport interface ProcessorGraphCondition {\n  /** The steps to execute if this condition's rules match */\n  steps: ProcessorGraphEntryDepth2[];\n  /** Rules to evaluate against the previous step's output. If absent, this is the default branch. */\n  rules?: RuleGroup;\n}\n\n/** Depth 1 (top-level): step, parallel, and conditional — children limited to depth 2 */\nexport type ProcessorGraphEntry =\n  | { type: 'step'; step: ProcessorGraphStep }\n  | { type: 'parallel'; branches: ProcessorGraphEntryDepth2[][] }\n  | { type: 'conditional'; conditions: ProcessorGraphCondition[] };\n\n/**\n * A stored processor graph representing a pipeline of processors.\n * The entries are ordered: sequential flow is array order, with parallel/conditional branching.\n */\nexport interface StoredProcessorGraph {\n  steps: ProcessorGraphEntry[];\n}\n\n/**\n * Thin prompt block record (metadata only).\n * All configuration lives in version snapshots (StoragePromptBlockSnapshotType).\n */\nexport interface StoragePromptBlockType {\n  /** Unique identifier */\n  id: string;\n  /** Block status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to prompt_block_versions.id — the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata */\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Prompt block version snapshot containing the content fields.\n * These fields live exclusively in version snapshot rows.\n */\nexport interface StoragePromptBlockSnapshotType {\n  /** Display name of the prompt block */\n  name: string;\n  /** Purpose description */\n  description?: string;\n  /** Template content with {{variable}} interpolation */\n  content: string;\n  /** Rules for conditional inclusion */\n  rules?: RuleGroup;\n  /** JSON Schema for validating request context values. Defines available variables for {{variableName}} interpolation and conditions. */\n  requestContextSchema?: Record<string, unknown>;\n}\n\n/** Resolved prompt block: thin record merged with active version snapshot */\nexport type StorageResolvedPromptBlockType = StoragePromptBlockType &\n  StoragePromptBlockSnapshotType & {\n    resolvedVersionId?: string;\n  };\n\n/** Input for creating a new prompt block */\nexport type StorageCreatePromptBlockInput = {\n  /** Unique identifier for the prompt block */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata */\n  metadata?: Record<string, unknown>;\n} & StoragePromptBlockSnapshotType;\n\n/** Input for updating a prompt block */\nexport type StorageUpdatePromptBlockInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata */\n  metadata?: Record<string, unknown>;\n  /** FK to prompt_block_versions.id — the currently active version */\n  activeVersionId?: string;\n  /** Block status */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<StoragePromptBlockSnapshotType>;\n\nexport type StorageListPromptBlocksInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter prompt blocks by author identifier.\n   */\n  authorId?: string;\n  /**\n   * Filter prompt blocks by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n  /**\n   * Filter prompt blocks by status.\n   * Defaults to 'published' if not specified.\n   */\n  status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin prompt block records */\nexport type StorageListPromptBlocksOutput = PaginationInfo & {\n  promptBlocks: StoragePromptBlockType[];\n};\n\n/** Paginated list output for resolved prompt blocks */\nexport type StorageListPromptBlocksResolvedOutput = PaginationInfo & {\n  promptBlocks: StorageResolvedPromptBlockType[];\n};\n\n// ============================================\n// Stored Scorer Types\n// ============================================\n\n/**\n * Scorer type discriminator.\n * - 'llm-judge': Custom LLM-as-judge scorer with user-provided instructions\n * - Preset types: Built-in scorers from @mastra/evals (e.g., 'bias', 'toxicity', 'faithfulness')\n */\nexport type StoredScorerType =\n  | 'llm-judge'\n  | 'answer-relevancy'\n  | 'answer-similarity'\n  | 'bias'\n  | 'context-precision'\n  | 'context-relevance'\n  | 'faithfulness'\n  | 'hallucination'\n  | 'noise-sensitivity'\n  | 'prompt-alignment'\n  | 'tool-call-accuracy'\n  | 'toxicity';\n\n/**\n * Stored scorer version snapshot containing ALL scorer configuration fields.\n * These fields live exclusively in version snapshot rows, not on the scorer record.\n */\nexport interface StorageScorerDefinitionSnapshotType {\n  /** Display name of the scorer */\n  name: string;\n  /** Purpose description */\n  description?: string;\n  /** Scorer type — determines how the scorer is instantiated at runtime */\n  type: StoredScorerType;\n  /** Model configuration — used for LLM judge; for presets, overrides the default model */\n  model?: StorageModelConfig;\n  /** System instructions for the judge LLM (used when type === 'llm-judge') */\n  instructions?: string;\n  /** Score range configuration (used when type === 'llm-judge') */\n  scoreRange?: {\n    /** Minimum score value (default: 0) */\n    min?: number;\n    /** Maximum score value (default: 1) */\n    max?: number;\n  };\n  /** Serializable config options for preset scorers (e.g., { scale: 10, context: [...] }) */\n  presetConfig?: Record<string, unknown>;\n  /** Default sampling configuration */\n  defaultSampling?: ScoringSamplingConfig;\n}\n\n/**\n * Thin stored scorer record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageScorerDefinitionSnapshotType).\n */\nexport interface StorageScorerDefinitionType {\n  /** Unique, immutable identifier */\n  id: string;\n  /** Scorer status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to scorer_definition_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the scorer */\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Resolved stored scorer type that combines the thin record with version snapshot config.\n * Returned by getScorerDefinitionByIdResolved and listScorerDefinitionsResolved.\n */\nexport type StorageResolvedScorerDefinitionType = StorageScorerDefinitionType &\n  StorageScorerDefinitionSnapshotType & {\n    /** The version ID that was resolved (populated by resolveEntity) */\n    resolvedVersionId?: string;\n  };\n\n/**\n * Input for creating a new stored scorer. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateScorerDefinitionInput = {\n  /** Unique identifier for the scorer */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the scorer */\n  metadata?: Record<string, unknown>;\n} & StorageScorerDefinitionSnapshotType;\n\n/**\n * Input for updating a stored scorer. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateScorerDefinitionInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the scorer */\n  metadata?: Record<string, unknown>;\n  /** FK to scorer_definition_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Scorer status */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageScorerDefinitionSnapshotType>;\n\nexport type StorageListScorerDefinitionsInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter scorers by author identifier.\n   */\n  authorId?: string;\n  /**\n   * Filter scorers by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n  /**\n   * Filter scorers by status.\n   * Defaults to 'published' if not specified.\n   */\n  status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin stored scorer records */\nexport type StorageListScorerDefinitionsOutput = PaginationInfo & {\n  scorerDefinitions: StorageScorerDefinitionType[];\n};\n\n/** Paginated list output for resolved stored scorers */\nexport type StorageListScorerDefinitionsResolvedOutput = PaginationInfo & {\n  scorerDefinitions: StorageResolvedScorerDefinitionType[];\n};\n\n// Basic Index Management Types\nexport interface CreateIndexOptions {\n  name: string;\n  table: string;\n  columns: string[];\n  unique?: boolean;\n  concurrent?: boolean;\n  /**\n   * SQL WHERE clause for creating partial indexes.\n   * @internal Reserved for internal use only. Callers must pre-validate this value.\n   * DDL statements cannot use parameterized queries for WHERE clauses, so this value\n   * is concatenated directly into the SQL. Any user-facing usage must validate input.\n   */\n  where?: string;\n  method?: 'btree' | 'hash' | 'gin' | 'gist' | 'spgist' | 'brin';\n  opclass?: string; // Operator class for GIN/GIST indexes\n  storage?: Record<string, any>; // Storage parameters\n  tablespace?: string; // Tablespace name\n}\n\nexport interface IndexInfo {\n  name: string;\n  table: string;\n  columns: string[];\n  unique: boolean;\n  size: string;\n  definition: string;\n}\n\nexport interface StorageIndexStats extends IndexInfo {\n  scans: number; // Number of index scans\n  tuples_read: number; // Number of tuples read\n  tuples_fetched: number; // Number of tuples fetched\n  last_used?: Date; // Last time index was used\n  method?: string; // Index method (btree, hash, etc)\n}\n\n// ============================================\n// Observational Memory Types\n// ============================================\n\n/**\n * Scope of observational memory\n */\nexport type ObservationalMemoryScope = 'thread' | 'resource';\n\n/**\n * How the observational memory record was created\n */\nexport type ObservationalMemoryOriginType = 'initial' | 'reflection';\n\n/**\n * A chunk of buffered observations from a single observation cycle.\n * Multiple chunks can accumulate before being activated together.\n */\nexport interface BufferedObservationChunk {\n  /** Unique identifier for this chunk */\n  id: string;\n  /** Cycle ID for linking to UI buffering markers */\n  cycleId: string;\n  /** The observation text content */\n  observations: string;\n  /** Token count of this chunk's observations */\n  tokenCount: number;\n  /** Message IDs that were observed in this chunk */\n  messageIds: string[];\n  /** Token count of the messages that were observed (for activation calculation) */\n  messageTokens: number;\n  /** When the messages were last observed */\n  lastObservedAt: Date;\n  /** When this chunk was created */\n  createdAt: Date;\n  /** Optional suggested continuation from the observer */\n  suggestedContinuation?: string;\n  /** Optional current task context */\n  currentTask?: string;\n  /** Optional thread title from observer output */\n  threadTitle?: string;\n}\n\n/**\n * Input for creating a new buffered observation chunk.\n */\nexport interface BufferedObservationChunkInput {\n  /** Cycle ID for linking to UI buffering markers */\n  cycleId: string;\n  /** The observation text content */\n  observations: string;\n  /** Token count of this chunk's observations */\n  tokenCount: number;\n  /** Message IDs that were observed in this chunk */\n  messageIds: string[];\n  /** Token count of the messages that were observed (for activation calculation) */\n  messageTokens: number;\n  /** When the messages were observed */\n  lastObservedAt: Date;\n  /** Optional suggested continuation from the observer */\n  suggestedContinuation?: string;\n  /** Optional current task context */\n  currentTask?: string;\n  /** Optional thread title from observer output */\n  threadTitle?: string;\n}\n\n/**\n * Core database record for observational memory\n *\n * For resource scope: One active record per resource, containing observations from ALL threads.\n * For thread scope: One record per thread.\n *\n * Derived values (not stored, computed at runtime):\n * - reflectionCount: count records with originType: 'reflection'\n * - lastReflectionAt: createdAt of most recent reflection record\n * - previousGeneration: record with next-oldest createdAt\n */\n\n/** Options for filtering observational memory history queries. */\nexport interface ObservationalMemoryHistoryOptions {\n  /** Only return records created at or after this date */\n  from?: Date;\n  /** Only return records created at or before this date */\n  to?: Date;\n  /** Number of records to skip (for pagination) */\n  offset?: number;\n}\n\nexport interface ObservationalMemoryRecord {\n  // Identity\n  /** Unique record ID */\n  id: string;\n  /** Memory scope - thread or resource */\n  scope: ObservationalMemoryScope;\n  /** Thread ID (null for resource scope) */\n  threadId: string | null;\n  /** Resource ID (always present) */\n  resourceId: string;\n\n  // Timestamps (top-level for easy querying)\n  /** When this record was created */\n  createdAt: Date;\n  /** When this record was last updated */\n  updatedAt: Date;\n  /**\n   * Single cursor for message loading - when we last observed ANY thread for this resource.\n   * Undefined means no observations have been made yet (all messages are \"unobserved\").\n   */\n  lastObservedAt?: Date;\n\n  // Generation tracking\n  /** How this record was created */\n  originType: ObservationalMemoryOriginType;\n  /** Generation counter - incremented each time a reflection creates a new record */\n  generationCount: number;\n\n  // Observation content\n  /**\n   * Currently active observations.\n   * For resource scope: Contains <thread id=\"...\">...</thread> sections for attribution.\n   * For thread scope: Plain observation text.\n   */\n  activeObservations: string;\n  /**\n   * Array of buffered observation chunks waiting to be activated.\n   * Each chunk represents observations from a single observation cycle.\n   * Multiple chunks can accumulate before being activated together.\n   */\n  bufferedObservationChunks?: BufferedObservationChunk[];\n  /**\n   * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n   * Observations waiting to be activated (async buffering)\n   */\n  bufferedObservations?: string;\n  /**\n   * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n   * Token count of buffered observations\n   */\n  bufferedObservationTokens?: number;\n  /**\n   * @deprecated Use bufferedObservationChunks instead. Legacy field for backwards compatibility.\n   * Message IDs being processed in async buffering\n   */\n  bufferedMessageIds?: string[];\n  /** Reflection waiting to be swapped in (async buffering) */\n  bufferedReflection?: string;\n  /** Token count of buffered reflection (post-compression output) */\n  bufferedReflectionTokens?: number;\n  /** Observation tokens that were fed into the reflector (pre-compression input) */\n  bufferedReflectionInputTokens?: number;\n  /**\n   * The number of lines in activeObservations that were reflected on\n   * when the buffered reflection was created. Used at activation time\n   * to separate reflected vs unreflected observations.\n   */\n  reflectedObservationLineCount?: number;\n\n  /**\n   * Message IDs observed in the current generation.\n   * Used as a safeguard against re-observation if timestamp filtering fails.\n   * Reset on reflection (new generation starts fresh).\n   */\n  observedMessageIds?: string[];\n\n  /**\n   * The timezone used when formatting dates for the Observer agent.\n   * Stored for debugging and auditing observation dates.\n   * Example: \"America/Los_Angeles\", \"Europe/London\"\n   */\n  observedTimezone?: string;\n\n  // Token tracking\n  /** Running total of all tokens observed */\n  totalTokensObserved: number;\n  /** Current size of active observations */\n  observationTokenCount: number;\n  /** Accumulated tokens from pending (unobserved) messages across sessions */\n  pendingMessageTokens: number;\n\n  // State flags\n  /** Is a reflection currently in progress? */\n  isReflecting: boolean;\n  /** Is observation currently in progress? */\n  isObserving: boolean;\n  /** Is async observation buffering currently in progress? */\n  isBufferingObservation: boolean;\n  /** Is async reflection buffering currently in progress? */\n  isBufferingReflection: boolean;\n  /**\n   * The pending message token count at which the last async observation buffer was triggered.\n   * Used to determine when the next bufferTokens interval is crossed.\n   * Persisted so new instances (created per request) can pick up where the last left off.\n   */\n  lastBufferedAtTokens: number;\n  /**\n   * Timestamp cursor for buffered messages.\n   * Set to the max message timestamp (+1ms) of the last successfully buffered chunk.\n   * Used to filter out already-buffered messages when starting the next buffer.\n   * Reset on activation.\n   */\n  lastBufferedAtTime: Date | null;\n\n  // Configuration\n  /** Current configuration (stored as JSON) */\n  config: Record<string, unknown>;\n\n  // Extensible metadata (app-specific, optional)\n  /** Optional metadata for app-specific extensions */\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Input for creating a new observational memory record\n */\nexport interface CreateObservationalMemoryInput {\n  threadId: string | null;\n  resourceId: string;\n  scope: ObservationalMemoryScope;\n  config: Record<string, unknown>;\n  /** The timezone used when formatting dates for the Observer agent (e.g., \"America/Los_Angeles\") */\n  observedTimezone?: string;\n}\n\n/**\n * Input for updating active observations.\n * Uses cursor-based message tracking via lastObservedAt instead of message IDs.\n */\nexport interface UpdateActiveObservationsInput {\n  id: string;\n  observations: string;\n  tokenCount: number;\n  /** Timestamp when these observations were created (for cursor-based message loading) */\n  lastObservedAt: Date;\n  /**\n   * IDs of messages that were observed in this cycle.\n   * Stored in record metadata as a safeguard against re-observation on process restart.\n   * These are appended to any existing IDs and pruned to only include IDs newer than lastObservedAt.\n   */\n  observedMessageIds?: string[];\n  /**\n   * The timezone used when formatting dates for the Observer agent.\n   * Captured from Intl.DateTimeFormat().resolvedOptions().timeZone\n   */\n  observedTimezone?: string;\n}\n\n/**\n * Input for updating buffered observations.\n * Used when async buffering is enabled via `bufferTokens` config.\n * Adds a new chunk to the bufferedObservationChunks array.\n */\nexport interface UpdateBufferedObservationsInput {\n  id: string;\n  /** The observation chunk to add to the buffer */\n  chunk: BufferedObservationChunkInput;\n  /** Timestamp cursor for the last buffered message boundary. Set to max message timestamp + 1ms. */\n  lastBufferedAtTime?: Date;\n}\n\n/**\n * Input for swapping buffered observations to active.\n * Supports partial activation via `activationRatio`.\n */\nexport interface SwapBufferedToActiveInput {\n  id: string;\n  /**\n   * Normalized ratio (0-1) controlling how much context to activate.\n   * `1 - activationRatio` is the fraction of the threshold to keep as raw messages.\n   * Target tokens to remove = `currentPendingTokens - messageTokensThreshold * (1 - activationRatio)`.\n   * Chunks are selected by boundary, biased over the target (to ensure remaining context stays at or below the retention floor).\n   *\n   * Note: this is always a ratio. The caller resolves absolute `bufferActivation` values (> 1)\n   * into the equivalent ratio before passing to the storage layer.\n   */\n  activationRatio: number;\n  /**\n   * The message token threshold (e.g., observation.messageTokens config value).\n   * Used with `activationRatio` to compute the retention floor.\n   */\n  messageTokensThreshold: number;\n  /**\n   * Current total pending message tokens in the context window.\n   * Used to compute how many tokens need to be removed to reach the retention floor.\n   */\n  currentPendingTokens: number;\n  /**\n   * When true, prefer removing more chunks (above `blockAfter`), while still respecting\n   * the minimum remaining tokens safeguard (min(1000, retention floor)).\n   */\n  forceMaxActivation?: boolean;\n  /**\n   * Optional timestamp to use as lastObservedAt after swap.\n   * If not provided, the adapter will use the lastObservedAt from the latest activated chunk.\n   */\n  lastObservedAt?: Date;\n  /**\n   * Refreshed buffered chunks with up-to-date messageTokens.\n   * When provided, the storage layer uses these instead of the persisted chunks\n   * for activation boundary selection, so stale token weights don't cause\n   * over- or under-activation.\n   */\n  bufferedChunks?: BufferedObservationChunk[];\n}\n\n/**\n * Result from swapping buffered observations to active.\n * Contains info about what was activated for UI feedback.\n */\nexport interface SwapBufferedToActiveResult {\n  /** Number of chunks that were activated */\n  chunksActivated: number;\n  /** Total message tokens from activated chunks (context cleared) */\n  messageTokensActivated: number;\n  /** Total observation tokens from activated chunks */\n  observationTokensActivated: number;\n  /** Total messages from activated chunks */\n  messagesActivated: number;\n  /** CycleIds of the activated chunks (for linking UI markers) */\n  activatedCycleIds: string[];\n  /** All message IDs from activated chunks (for removing from context) */\n  activatedMessageIds: string[];\n  /** Concatenated observations from activated chunks (for UI display) */\n  observations?: string;\n  /** Per-chunk breakdown for individual UI markers */\n  perChunk?: Array<{\n    cycleId: string;\n    messageTokens: number;\n    observationTokens: number;\n    messageCount: number;\n    observations: string;\n  }>;\n  /** Suggested continuation from the most recent activated chunk (if any) */\n  suggestedContinuation?: string;\n  /** Current task from the most recent activated chunk (if any) */\n  currentTask?: string;\n}\n\n/**\n * Input for updating buffered reflection.\n * Used when async reflection buffering is enabled via `bufferTokens` config.\n */\nexport interface UpdateBufferedReflectionInput {\n  id: string;\n  reflection: string;\n  /** Token count of the buffered reflection (post-compression output) */\n  tokenCount: number;\n  /** Observation tokens that were fed into the reflector (pre-compression input) */\n  inputTokenCount: number;\n  /**\n   * The number of lines in activeObservations at the time of reflection.\n   * Used at activation time to know which observations were already reflected on.\n   */\n  reflectedObservationLineCount: number;\n}\n\n/**\n * Input for swapping buffered reflection to active (creates new generation).\n * Uses the stored `reflectedObservationLineCount` to determine which observations\n * were already reflected on, replaces those with the buffered reflection,\n * and appends any unreflected observations that were added after the reflection started.\n */\nexport interface SwapBufferedReflectionToActiveInput {\n  currentRecord: ObservationalMemoryRecord;\n  /**\n   * Token count for the combined new activeObservations (bufferedReflection + unreflected).\n   * Computed by the processor using its token counter before calling the adapter.\n   */\n  tokenCount: number;\n}\n\n/**\n * Input for creating a reflection generation (creates a new record, archives the old one)\n */\nexport interface CreateReflectionGenerationInput {\n  currentRecord: ObservationalMemoryRecord;\n  reflection: string;\n  tokenCount: number;\n}\n\n/**\n * Input for updating the config of an existing observational memory record.\n * The provided config is deep-merged into the record's existing config.\n */\nexport interface UpdateObservationalMemoryConfigInput {\n  id: string;\n  config: Record<string, unknown>;\n}\n\n// ============================================\n// MCP Client Storage Types\n// ============================================\n\n/**\n * Serializable MCP server transport definition for storage.\n * Only includes fields that can be safely serialized to JSON.\n * Non-serializable fields (fetch, authProvider, logger, etc.) must be\n * provided via code-defined MCP clients.\n */\nexport interface StorageMCPServerConfig {\n  /** Transport type discriminator */\n  type: 'stdio' | 'http';\n  /** Command to execute (stdio transport) */\n  command?: string;\n  /** Arguments to pass to the command (stdio transport) */\n  args?: string[];\n  /** Environment variables for the subprocess (stdio transport) */\n  env?: Record<string, string>;\n  /** URL of the MCP server endpoint (http transport) — stored as string */\n  url?: string;\n  /** Timeout in milliseconds for server operations */\n  timeout?: number;\n  /**\n   * Optional tool selection/filtering at the server level.\n   * When provided, only tools listed here are exposed by this server.\n   * When omitted, all tools from the server are exposed.\n   */\n  tools?: Record<string, StorageToolConfig>;\n}\n\n/**\n * MCP client version snapshot containing ALL configuration fields.\n * These fields live exclusively in version snapshot rows, not on the MCP client record.\n */\nexport interface StorageMCPClientSnapshotType {\n  /** Display name of the MCP client configuration */\n  name: string;\n  /** Purpose description */\n  description?: string;\n  /** MCP servers keyed by server name */\n  servers: Record<string, StorageMCPServerConfig>;\n}\n\n/**\n * Thin stored MCP client record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageMCPClientSnapshotType).\n */\nexport interface StorageMCPClientType {\n  /** Unique, immutable identifier */\n  id: string;\n  /** Client status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to mcp_client_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the MCP client */\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Resolved stored MCP client type that combines the thin record with version snapshot config.\n * Returned by getMCPClientByIdResolved and listMCPClientsResolved.\n */\nexport type StorageResolvedMCPClientType = StorageMCPClientType &\n  StorageMCPClientSnapshotType & {\n    resolvedVersionId?: string;\n  };\n\n/**\n * Input for creating a new stored MCP client. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateMCPClientInput = {\n  /** Unique identifier for the MCP client */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the MCP client */\n  metadata?: Record<string, unknown>;\n} & StorageMCPClientSnapshotType;\n\n/**\n * Input for updating a stored MCP client. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateMCPClientInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the MCP client */\n  metadata?: Record<string, unknown>;\n  /** FK to mcp_client_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Client status */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageMCPClientSnapshotType>;\n\nexport type StorageListMCPClientsInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter MCP clients by author identifier.\n   */\n  authorId?: string;\n  /**\n   * Filter MCP clients by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n  /**\n   * Filter MCP clients by status.\n   * Defaults to 'published' if not specified.\n   */\n  status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin stored MCP client records */\nexport type StorageListMCPClientsOutput = PaginationInfo & {\n  mcpClients: StorageMCPClientType[];\n};\n\n/** Paginated list output for resolved stored MCP clients */\nexport type StorageListMCPClientsResolvedOutput = PaginationInfo & {\n  mcpClients: StorageResolvedMCPClientType[];\n};\n\n// ============================================\n// MCP Server Storage Types\n// ============================================\n\n/**\n * MCP server version snapshot containing ALL configuration fields.\n * These fields live exclusively in version snapshot rows, not on the MCP server record.\n *\n * Serializable metadata from MCPServerConfig. Non-serializable fields (tools, agents, workflows)\n * are stored as reference keys and resolved at hydration time.\n */\nexport interface StorageMCPServerSnapshotType {\n  /** Display name of the MCP server */\n  name: string;\n  /** Semantic version string */\n  version: string;\n  /** Purpose description */\n  description?: string;\n  /** Instructions describing how to use the server */\n  instructions?: string;\n  /** Repository information for the server's source code */\n  repository?: {\n    url: string;\n    type?: string;\n    directory?: string;\n  };\n  /** Release date of this server version (ISO 8601 string) */\n  releaseDate?: string;\n  /** Whether this version is the latest available */\n  isLatest?: boolean;\n  /** Canonical packaging format (e.g., 'npm', 'docker', 'pypi', 'crates') */\n  packageCanonical?: string;\n  /**\n   * Tool keys to include on this MCP server.\n   * Keys are tool IDs registered in Mastra, values provide optional config overrides.\n   */\n  tools?: Record<string, StorageToolConfig>;\n  /**\n   * Agent keys to expose as tools on this MCP server.\n   * Keys are agent IDs registered in Mastra, values provide optional config overrides.\n   */\n  agents?: Record<string, StorageToolConfig>;\n  /**\n   * Workflow keys to expose as tools on this MCP server.\n   * Keys are workflow IDs registered in Mastra, values provide optional config overrides.\n   */\n  workflows?: Record<string, StorageToolConfig>;\n}\n\n/**\n * Thin stored MCP server record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageMCPServerSnapshotType).\n */\nexport interface StorageMCPServerType {\n  /** Unique, immutable identifier */\n  id: string;\n  /** Server status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to mcp_server_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the MCP server */\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Resolved stored MCP server type that combines the thin record with version snapshot config.\n * Returned by getMCPServerByIdResolved and listMCPServersResolved.\n */\nexport type StorageResolvedMCPServerType = StorageMCPServerType &\n  StorageMCPServerSnapshotType & {\n    resolvedVersionId?: string;\n  };\n\n/**\n * Input for creating a new stored MCP server. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateMCPServerInput = {\n  /** Unique identifier for the MCP server */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the MCP server */\n  metadata?: Record<string, unknown>;\n} & StorageMCPServerSnapshotType;\n\n/**\n * Input for updating a stored MCP server. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateMCPServerInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the MCP server */\n  metadata?: Record<string, unknown>;\n  /** FK to mcp_server_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Server status */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageMCPServerSnapshotType>;\n\nexport type StorageListMCPServersInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter MCP servers by author identifier.\n   */\n  authorId?: string;\n  /**\n   * Filter MCP servers by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n  /**\n   * Filter MCP servers by status.\n   * Defaults to 'published' if not specified.\n   */\n  status?: 'draft' | 'published' | 'archived';\n};\n\n/** Paginated list output for thin stored MCP server records */\nexport type StorageListMCPServersOutput = PaginationInfo & {\n  mcpServers: StorageMCPServerType[];\n};\n\n/** Paginated list output for resolved stored MCP servers */\nexport type StorageListMCPServersResolvedOutput = PaginationInfo & {\n  mcpServers: StorageResolvedMCPServerType[];\n};\n\n// ============================================\n// Workspace Storage Types\n// ============================================\n\n/**\n * Serializable filesystem configuration for storage.\n * References a provider type string that the editor resolves at hydration time.\n */\nexport interface StorageFilesystemConfig {\n  /** Provider type identifier (e.g., 's3', 'gcs', 'local') — resolved by the editor's filesystem registry */\n  provider: string;\n  /** Provider-specific configuration (bucket, basePath, etc.) */\n  config: Record<string, unknown>;\n  /** Whether the filesystem is read-only */\n  readOnly?: boolean;\n}\n\n/**\n * Serializable sandbox configuration for storage.\n * References a provider type string that the editor resolves at hydration time.\n */\nexport interface StorageSandboxConfig {\n  /** Provider type identifier (e.g., 'e2b') — resolved by the editor's sandbox registry */\n  provider: string;\n  /** Provider-specific configuration */\n  config: Record<string, unknown>;\n}\n\n/**\n * Serializable search configuration for storage.\n * References vector store and embedder by provider/name rather than runtime instances.\n */\nexport interface StorageSearchConfig {\n  /** Vector store provider identifier (e.g., 'pg', 'pinecone') */\n  vectorProvider?: string;\n  /** Vector store provider-specific configuration */\n  vectorConfig?: Record<string, unknown>;\n  /** Embedder provider identifier (e.g., 'openai', 'fastembed') */\n  embedderProvider?: string;\n  /** Embedder model name */\n  embedderModel?: string;\n  /** Embedder provider-specific configuration */\n  embedderConfig?: Record<string, unknown>;\n  /** BM25 keyword search config — true for defaults, or object for custom params */\n  bm25?: boolean | { k1?: number; b?: number };\n  /** Custom index name for the vector store */\n  searchIndexName?: string;\n  /** Paths to auto-index on init */\n  autoIndexPaths?: string[];\n}\n\n/**\n * Serializable per-tool configuration for workspace tools.\n */\nexport interface StorageWorkspaceToolConfig {\n  /** Whether the tool is enabled (default: true) */\n  enabled?: boolean;\n  /** Whether the tool requires user approval before execution (default: false) */\n  requireApproval?: boolean;\n  /** For write tools: require reading a file before writing to it */\n  requireReadBeforeWrite?: boolean;\n}\n\n/**\n * Serializable workspace tools configuration for storage.\n */\nexport interface StorageWorkspaceToolsConfig {\n  /** Default: whether all tools are enabled (default: true) */\n  enabled?: boolean;\n  /** Default: whether all tools require user approval (default: false) */\n  requireApproval?: boolean;\n  /** Per-tool overrides, keyed by workspace tool name */\n  tools?: Record<string, StorageWorkspaceToolConfig>;\n}\n\n/**\n * Workspace version snapshot type containing ALL workspace configuration fields.\n * These fields live exclusively in version snapshot rows, not on the workspace record.\n */\nexport interface StorageWorkspaceSnapshotType {\n  /** Display name of the workspace */\n  name: string;\n  /** Purpose description */\n  description?: string;\n  /** Primary filesystem configuration */\n  filesystem?: StorageFilesystemConfig;\n  /** Sandbox configuration */\n  sandbox?: StorageSandboxConfig;\n  /** Mounted filesystems keyed by mount path */\n  mounts?: Record<string, StorageFilesystemConfig>;\n  /** Search configuration (vector, embedder, BM25) */\n  search?: StorageSearchConfig;\n  /** Skill entity IDs assigned to this workspace */\n  skills?: string[];\n  /** Workspace tool configuration */\n  tools?: StorageWorkspaceToolsConfig;\n  /** Auto-sync between fs and sandbox (default: false) */\n  autoSync?: boolean;\n  /** Timeout for individual operations in milliseconds */\n  operationTimeout?: number;\n}\n\n/**\n * Thin workspace record type containing only metadata fields.\n * All configuration lives in version snapshots (StorageWorkspaceSnapshotType).\n */\nexport interface StorageWorkspaceType {\n  /** Unique, immutable identifier */\n  id: string;\n  /** Workspace status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to workspace_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the workspace */\n  metadata?: Record<string, unknown>;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Resolved workspace type that combines the thin record with version snapshot config.\n * Returned by getWorkspaceByIdResolved and listWorkspacesResolved.\n */\nexport type StorageResolvedWorkspaceType = StorageWorkspaceType &\n  StorageWorkspaceSnapshotType & {\n    resolvedVersionId?: string;\n  };\n\n/**\n * Input for creating a new workspace. Flat union of thin record fields\n * and initial configuration (used to create version 1).\n */\nexport type StorageCreateWorkspaceInput = {\n  /** Unique identifier for the workspace */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the workspace */\n  metadata?: Record<string, unknown>;\n} & StorageWorkspaceSnapshotType;\n\n/**\n * Input for updating a workspace. Includes metadata-level fields and optional config fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateWorkspaceInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** Additional metadata for the workspace */\n  metadata?: Record<string, unknown>;\n  /** FK to workspace_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Workspace status */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageWorkspaceSnapshotType>;\n\nexport type StorageListWorkspacesInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter workspaces by author identifier.\n   */\n  authorId?: string;\n  /**\n   * Filter workspaces by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin workspace records */\nexport type StorageListWorkspacesOutput = PaginationInfo & {\n  workspaces: StorageWorkspaceType[];\n};\n\n/** Paginated list output for resolved workspaces */\nexport type StorageListWorkspacesResolvedOutput = PaginationInfo & {\n  workspaces: StorageResolvedWorkspaceType[];\n};\n\n// ============================================\n// Skill Storage Types\n// ============================================\n\n/**\n * Serializable content source for skill storage.\n * Mirrors the runtime ContentSource but stored as plain JSON.\n */\nexport type StorageContentSource =\n  | { type: 'external'; packagePath: string }\n  | { type: 'local'; projectPath: string }\n  | { type: 'managed'; mastraPath: string };\n\n/**\n * Skill version snapshot type containing ALL skill definition fields.\n * These fields live exclusively in version snapshot rows, not on the skill record.\n */\nexport interface StorageSkillSnapshotType {\n  /** Skill name (1-64 chars, lowercase, hyphens only) */\n  name: string;\n  /** Description of what the skill does and when to use it */\n  description: string;\n  /** Markdown instructions from SKILL.md body */\n  instructions: string;\n  /** Optional license identifier */\n  license?: string;\n  /** Optional compatibility requirements */\n  compatibility?: unknown;\n  /** Source of the skill */\n  source?: StorageContentSource;\n  /** List of reference file paths */\n  references?: string[];\n  /** List of script file paths */\n  scripts?: string[];\n  /** List of asset file paths */\n  assets?: string[];\n  /** Optional arbitrary metadata */\n  metadata?: Record<string, unknown>;\n  /** Content-addressable file tree manifest for this skill version */\n  tree?: SkillVersionTree;\n}\n\n/**\n * Thin skill record type containing only metadata fields.\n * All definition content lives in version snapshots (StorageSkillSnapshotType).\n */\nexport interface StorageSkillType {\n  /** Unique, immutable identifier */\n  id: string;\n  /** Skill status: 'draft' on creation, 'published' when a version is activated */\n  status: 'draft' | 'published' | 'archived';\n  /** FK to skill_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/**\n * Resolved skill type that combines the thin record with version snapshot content.\n * Returned by getSkillByIdResolved and listSkillsResolved.\n */\nexport type StorageResolvedSkillType = StorageSkillType &\n  StorageSkillSnapshotType & {\n    resolvedVersionId?: string;\n  };\n\n/**\n * Input for creating a new skill. Flat union of thin record fields\n * and initial content (used to create version 1).\n */\nexport type StorageCreateSkillInput = {\n  /** Unique identifier for the skill */\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n} & StorageSkillSnapshotType;\n\n/**\n * Input for updating a skill. Includes metadata-level fields and optional content fields.\n * The handler layer separates these into record updates vs new-version creation.\n */\nexport type StorageUpdateSkillInput = {\n  id: string;\n  /** Author identifier for multi-tenant filtering */\n  authorId?: string;\n  /** FK to skill_versions.id - the currently active version */\n  activeVersionId?: string;\n  /** Skill status */\n  status?: 'draft' | 'published' | 'archived';\n} & Partial<StorageSkillSnapshotType>;\n\nexport type StorageListSkillsInput = {\n  /**\n   * Number of items per page, or `false` to fetch all records without pagination limit.\n   * Defaults to 100 if not specified.\n   */\n  perPage?: number | false;\n  /**\n   * Zero-indexed page number for pagination.\n   * Defaults to 0 if not specified.\n   */\n  page?: number;\n  orderBy?: StorageOrderBy;\n  /**\n   * Filter skills by author identifier.\n   */\n  authorId?: string;\n  /**\n   * Filter skills by metadata key-value pairs.\n   * All specified key-value pairs must match (AND logic).\n   */\n  metadata?: Record<string, unknown>;\n};\n\n/** Paginated list output for thin skill records */\nexport type StorageListSkillsOutput = PaginationInfo & {\n  skills: StorageSkillType[];\n};\n\n/** Paginated list output for resolved skills */\nexport type StorageListSkillsResolvedOutput = PaginationInfo & {\n  skills: StorageResolvedSkillType[];\n};\n\n/**\n * Per-skill configuration stored in agent snapshots.\n * Allows overriding skill description and instructions for a specific agent context.\n */\nexport interface StorageSkillConfig {\n  /** Custom description override for this skill in this agent context */\n  description?: string;\n  /** Custom instructions override for this skill in this agent context */\n  instructions?: string;\n  /** Pin to a specific version ID. Takes precedence over strategy. */\n  pin?: string;\n  /** Resolution strategy: 'latest' = latest published version, 'live' = read from filesystem */\n  strategy?: 'latest' | 'live';\n}\n\n/**\n * A single entry in a skill version's file tree manifest.\n * Maps a file path to its content-addressable blob hash.\n */\nexport interface SkillVersionTreeEntry {\n  /** SHA-256 hash of the file content (content-addressable key) */\n  blobHash: string;\n  /** File size in bytes */\n  size: number;\n  /** Optional MIME type */\n  mimeType?: string;\n  /**\n   * Content encoding used in the blob store.\n   * - 'utf-8' (default): content stored as UTF-8 text\n   * - 'base64': content stored as base64-encoded string (for binary files like images)\n   */\n  encoding?: 'utf-8' | 'base64';\n}\n\n/**\n * Complete file tree manifest for a skill version.\n * Maps relative file paths to their blob entries.\n * This is stored as JSONB on the skill version row.\n *\n * Example:\n * {\n *   \"SKILL.md\": { blobHash: \"abc123...\", size: 1024, mimeType: \"text/markdown\" },\n *   \"references/api.md\": { blobHash: \"def456...\", size: 512, mimeType: \"text/markdown\" },\n *   \"scripts/setup.sh\": { blobHash: \"ghi789...\", size: 256, mimeType: \"text/x-shellscript\" }\n * }\n */\nexport interface SkillVersionTree {\n  entries: Record<string, SkillVersionTreeEntry>;\n}\n\n/**\n * A stored blob entry in the content-addressable blob store.\n */\nexport interface StorageBlobEntry {\n  /** SHA-256 hash of the content (primary key) */\n  hash: string;\n  /** The file content (text) */\n  content: string;\n  /** File size in bytes */\n  size: number;\n  /** Optional MIME type */\n  mimeType?: string;\n  /** When the blob was first stored */\n  createdAt: Date;\n}\n\n/**\n * Workspace reference configuration stored in agent snapshots.\n * Can reference a stored workspace by ID or provide inline workspace config.\n */\nexport type StorageWorkspaceRef =\n  | { type: 'id'; workspaceId: string }\n  | { type: 'inline'; config: StorageWorkspaceSnapshotType };\n\n// ============================================\n// Workflow Storage Types\n// ============================================\n\nexport interface UpdateWorkflowStateOptions {\n  status: WorkflowRunStatus;\n  result?: StepResult<any, any, any, any>;\n  error?: SerializedError;\n  suspendedPaths?: Record<string, number[]>;\n  waitingPaths?: Record<string, number[]>;\n  resumeLabels?: Record<string, { stepId: string; foreachIndex?: number }>;\n  /**\n   * Tracing context for span continuity during suspend/resume.\n   * Persisted when workflow suspends to enable linking resumed spans\n   * as children of the original suspended span.\n   */\n  tracingContext?: {\n    traceId?: string;\n    spanId?: string;\n    parentSpanId?: string;\n  };\n}\n\nfunction unwrapSchema(schema: z.ZodTypeAny): { base: z.ZodTypeAny; nullable: boolean } {\n  let current = schema;\n  let nullable = false;\n\n  while (true) {\n    const typeName = getZodTypeName(current);\n    if (!typeName) break;\n\n    if (typeName === 'ZodNullable' || typeName === 'ZodOptional') {\n      nullable = true;\n    }\n\n    const inner = getZodInnerType(current, typeName);\n    if (!inner) break;\n    current = inner;\n  }\n\n  return { base: current, nullable };\n}\n\n/**\n * Extract checks array from Zod schema, compatible with both Zod 3 and Zod 4.\n * Zod 3 uses _def.checks with {kind: \"...\"} objects\n * Zod 4 uses _zod.def.checks with {def: {check: \"...\", format: \"...\"}} objects\n */\nfunction getZodChecks(schema: z.ZodTypeAny): Array<{ kind: string }> {\n  // Zod 4 structure: checks have def.check instead of kind\n  if ('_zod' in schema) {\n    const zodV4 = schema as { _zod?: { def?: { checks?: unknown[] } } };\n    const checks = zodV4._zod?.def?.checks;\n\n    if (checks && Array.isArray(checks)) {\n      return checks.map((check: unknown) => {\n        // Type guard for Zod v4 check structure\n        if (\n          typeof check === 'object' &&\n          check !== null &&\n          'def' in check &&\n          typeof check.def === 'object' &&\n          check.def !== null\n        ) {\n          const def = check.def as Record<string, unknown>;\n\n          // For number checks in Zod 4, format:\"safeint\" means int()\n          if (def.check === 'number_format' && def.format === 'safeint') {\n            return { kind: 'int' };\n          }\n\n          // For string checks in Zod 4, check type is the format name\n          if (def.check === 'string_format' && typeof def.format === 'string') {\n            return { kind: def.format }; // e.g., \"uuid\", \"email\", etc.\n          }\n\n          // Generic mapping: use the check type as kind\n          return { kind: typeof def.check === 'string' ? def.check : 'unknown' };\n        }\n\n        return { kind: 'unknown' };\n      });\n    }\n  }\n\n  // Zod 3 structure: checks already have kind property\n  if ('_def' in schema) {\n    const zodV3 = schema as { _def?: { checks?: Array<{ kind: string }> } };\n    const checks = zodV3._def?.checks;\n\n    if (checks && Array.isArray(checks)) {\n      return checks;\n    }\n  }\n\n  return [];\n}\n\nfunction zodToStorageType(schema: z.ZodTypeAny): StorageColumnType {\n  const typeName = getZodTypeName(schema);\n\n  if (typeName === 'ZodString') {\n    // Check for UUID validation\n    const checks = getZodChecks(schema);\n    if (checks.some(c => c.kind === 'uuid')) {\n      return 'uuid';\n    }\n    return 'text';\n  }\n  if (typeName === 'ZodNativeEnum' || typeName === 'ZodEnum') {\n    return 'text';\n  }\n  if (typeName === 'ZodNumber') {\n    // Check for integer validation\n    const checks = getZodChecks(schema);\n    return checks.some(c => c.kind === 'int') ? 'integer' : 'float';\n  }\n  // Both ZodBigInt (v3) and ZodBigint (v4) should map to bigint\n  if (typeName === 'ZodBigInt' || typeName === 'ZodBigint') {\n    return 'bigint';\n  }\n  if (typeName === 'ZodDate') {\n    return 'timestamp';\n  }\n  if (typeName === 'ZodBoolean') {\n    return 'boolean';\n  }\n  // fall back for objects/records/unknown\n  return 'jsonb';\n}\n\n/**\n * Converts a zod schema into a database schema\n * @param zObject A zod schema object\n * @returns database schema record with StorageColumns\n */\nexport function buildStorageSchema<Shape extends z.ZodRawShape>(\n  zObject: z.ZodObject<Shape>,\n): Record<keyof Shape & string, StorageColumn> {\n  const shape = zObject.shape;\n  const result: Record<string, StorageColumn> = {};\n\n  for (const [key, field] of Object.entries(shape)) {\n    const { base, nullable } = unwrapSchema(field as z.ZodTypeAny);\n    result[key] = {\n      type: zodToStorageType(base),\n      nullable,\n    };\n  }\n\n  return result as Record<keyof Shape & string, StorageColumn>;\n}\n\n// ============================================\n// Dataset Types\n// ============================================\n\nexport type TargetType = 'agent' | 'workflow' | 'scorer' | 'processor';\n\nexport interface DatasetRecord {\n  id: string;\n  name: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  inputSchema?: Record<string, unknown>;\n  groundTruthSchema?: Record<string, unknown>;\n  requestContextSchema?: Record<string, unknown>;\n  tags?: string[] | null;\n  targetType?: TargetType | null;\n  targetIds?: string[] | null;\n  scorerIds?: string[] | null;\n  version: number;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport interface DatasetItemSource {\n  type: 'csv' | 'json' | 'trace' | 'llm' | 'experiment-result';\n  referenceId?: string;\n}\n\nexport interface DatasetItem {\n  id: string;\n  datasetId: string;\n  datasetVersion: number;\n  input: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  source?: DatasetItemSource;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport interface DatasetItemRow {\n  id: string;\n  datasetId: string;\n  datasetVersion: number;\n  validTo: number | null;\n  isDeleted: boolean;\n  input: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  source?: DatasetItemSource;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport interface DatasetVersion {\n  id: string;\n  datasetId: string;\n  version: number;\n  createdAt: Date;\n}\n\n// Dataset CRUD Input/Output Types\n\nexport interface CreateDatasetInput {\n  name: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  inputSchema?: Record<string, unknown> | null;\n  groundTruthSchema?: Record<string, unknown> | null;\n  requestContextSchema?: Record<string, unknown> | null;\n  targetType?: TargetType;\n  targetIds?: string[];\n  scorerIds?: string[];\n}\n\nexport interface UpdateDatasetInput {\n  id: string;\n  name?: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  inputSchema?: Record<string, unknown> | null;\n  groundTruthSchema?: Record<string, unknown> | null;\n  requestContextSchema?: Record<string, unknown> | null;\n  tags?: string[] | null;\n  targetType?: TargetType | null;\n  targetIds?: string[] | null;\n  scorerIds?: string[] | null;\n}\n\nexport interface AddDatasetItemInput {\n  datasetId: string;\n  input: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  source?: DatasetItemSource;\n}\n\nexport interface UpdateDatasetItemInput {\n  id: string;\n  datasetId: string;\n  input?: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  source?: DatasetItemSource;\n}\n\nexport interface ListDatasetsInput {\n  pagination: StoragePagination;\n}\n\nexport interface ListDatasetsOutput {\n  datasets: DatasetRecord[];\n  pagination: PaginationInfo;\n}\n\nexport interface ListDatasetItemsInput {\n  datasetId: string;\n  version?: number;\n  search?: string;\n  pagination: StoragePagination;\n}\n\nexport interface ListDatasetItemsOutput {\n  items: DatasetItem[];\n  pagination: PaginationInfo;\n}\n\nexport interface ListDatasetVersionsInput {\n  datasetId: string;\n  pagination: StoragePagination;\n}\n\nexport interface ListDatasetVersionsOutput {\n  versions: DatasetVersion[];\n  pagination: PaginationInfo;\n}\n\nexport interface BatchInsertItemsInput {\n  datasetId: string;\n  items: Array<{\n    input: unknown;\n    groundTruth?: unknown;\n    expectedTrajectory?: unknown;\n    requestContext?: Record<string, unknown>;\n    metadata?: Record<string, unknown>;\n    source?: DatasetItemSource;\n  }>;\n}\n\nexport interface BatchDeleteItemsInput {\n  datasetId: string;\n  itemIds: string[];\n}\n\n// ============================================\n// Experiment Types (Dataset Experiments)\n// ============================================\n\nexport type ExperimentStatus = 'pending' | 'running' | 'completed' | 'failed';\n\nexport interface Experiment {\n  id: string;\n  name?: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  datasetId: string | null;\n  datasetVersion: number | null;\n  targetType: TargetType;\n  targetId: string;\n  status: ExperimentStatus;\n  totalItems: number;\n  succeededCount: number;\n  failedCount: number;\n  skippedCount: number;\n  agentVersion?: string | null;\n  startedAt: Date | null;\n  completedAt: Date | null;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport type ExperimentResultStatus = 'needs-review' | 'reviewed' | 'complete';\n\nexport interface ExperimentResult {\n  id: string;\n  experimentId: string;\n  itemId: string;\n  itemDatasetVersion: number | null;\n  input: unknown;\n  output: unknown | null;\n  groundTruth: unknown | null;\n  error: { message: string; stack?: string; code?: string } | null;\n  startedAt: Date;\n  completedAt: Date;\n  retryCount: number;\n  traceId: string | null;\n  status: ExperimentResultStatus | null;\n  tags: string[] | null;\n  createdAt: Date;\n}\n\nexport interface UpdateExperimentResultInput {\n  id: string;\n  /** When provided, the update will only succeed if the result belongs to this experiment */\n  experimentId?: string;\n  status?: ExperimentResultStatus | null;\n  tags?: string[] | null;\n}\n\nexport interface CreateExperimentInput {\n  id?: string;\n  name?: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  datasetId: string | null;\n  datasetVersion: number | null;\n  agentVersion?: string;\n  targetType: TargetType;\n  targetId: string;\n  totalItems: number;\n}\n\nexport interface UpdateExperimentInput {\n  id: string;\n  name?: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  status?: ExperimentStatus;\n  totalItems?: number;\n  succeededCount?: number;\n  failedCount?: number;\n  skippedCount?: number;\n  startedAt?: Date;\n  completedAt?: Date;\n}\n\nexport interface AddExperimentResultInput {\n  id?: string;\n  experimentId: string;\n  itemId: string;\n  itemDatasetVersion: number | null;\n  input: unknown;\n  output: unknown | null;\n  groundTruth: unknown | null;\n  error: { message: string; stack?: string; code?: string } | null;\n  startedAt: Date;\n  completedAt: Date;\n  retryCount: number;\n  traceId?: string | null;\n  status?: ExperimentResultStatus | null;\n  tags?: string[] | null;\n}\n\nexport interface ListExperimentsInput {\n  datasetId?: string;\n  targetType?: TargetType;\n  targetId?: string;\n  agentVersion?: string;\n  status?: ExperimentStatus;\n  pagination: StoragePagination;\n}\n\nexport interface ListExperimentsOutput {\n  experiments: Experiment[];\n  pagination: PaginationInfo;\n}\n\nexport interface ListExperimentResultsInput {\n  experimentId: string;\n  traceId?: string;\n  status?: ExperimentResultStatus;\n  pagination: StoragePagination;\n}\n\nexport interface ListExperimentResultsOutput {\n  results: ExperimentResult[];\n  pagination: PaginationInfo;\n}\n\nexport interface ExperimentReviewCounts {\n  experimentId: string;\n  total: number;\n  needsReview: number;\n  reviewed: number;\n  complete: number;\n}\n","import { spanRecordSchema } from './domains/observability';\nimport { buildStorageSchema } from './types';\nimport type { StorageColumn, StorageTableConfig } from './types';\n\nexport const TABLE_WORKFLOW_SNAPSHOT = 'mastra_workflow_snapshot';\nexport const TABLE_MESSAGES = 'mastra_messages';\nexport const TABLE_THREADS = 'mastra_threads';\nexport const TABLE_TRACES = 'mastra_traces';\nexport const TABLE_RESOURCES = 'mastra_resources';\nexport const TABLE_SCORERS = 'mastra_scorers';\nexport const TABLE_SPANS = 'mastra_ai_spans';\nexport const TABLE_AGENTS = 'mastra_agents';\nexport const TABLE_AGENT_VERSIONS = 'mastra_agent_versions';\nexport const TABLE_OBSERVATIONAL_MEMORY = 'mastra_observational_memory';\nexport const TABLE_PROMPT_BLOCKS = 'mastra_prompt_blocks';\nexport const TABLE_PROMPT_BLOCK_VERSIONS = 'mastra_prompt_block_versions';\nexport const TABLE_SCORER_DEFINITIONS = 'mastra_scorer_definitions';\nexport const TABLE_SCORER_DEFINITION_VERSIONS = 'mastra_scorer_definition_versions';\nexport const TABLE_MCP_CLIENTS = 'mastra_mcp_clients';\nexport const TABLE_MCP_CLIENT_VERSIONS = 'mastra_mcp_client_versions';\nexport const TABLE_MCP_SERVERS = 'mastra_mcp_servers';\nexport const TABLE_MCP_SERVER_VERSIONS = 'mastra_mcp_server_versions';\nexport const TABLE_WORKSPACES = 'mastra_workspaces';\nexport const TABLE_WORKSPACE_VERSIONS = 'mastra_workspace_versions';\nexport const TABLE_SKILLS = 'mastra_skills';\nexport const TABLE_SKILL_VERSIONS = 'mastra_skill_versions';\nexport const TABLE_SKILL_BLOBS = 'mastra_skill_blobs';\n\n// Dataset tables\nexport const TABLE_DATASETS = 'mastra_datasets';\nexport const TABLE_DATASET_ITEMS = 'mastra_dataset_items';\nexport const TABLE_DATASET_VERSIONS = 'mastra_dataset_versions';\n\n// Experiment tables\nexport const TABLE_EXPERIMENTS = 'mastra_experiments';\nexport const TABLE_EXPERIMENT_RESULTS = 'mastra_experiment_results';\n\n/** Union of all core table name constants. */\nexport type TABLE_NAMES =\n  | typeof TABLE_WORKFLOW_SNAPSHOT\n  | typeof TABLE_MESSAGES\n  | typeof TABLE_THREADS\n  | typeof TABLE_TRACES\n  | typeof TABLE_RESOURCES\n  | typeof TABLE_SCORERS\n  | typeof TABLE_SPANS\n  | typeof TABLE_AGENTS\n  | typeof TABLE_AGENT_VERSIONS\n  | typeof TABLE_PROMPT_BLOCKS\n  | typeof TABLE_PROMPT_BLOCK_VERSIONS\n  | typeof TABLE_SCORER_DEFINITIONS\n  | typeof TABLE_SCORER_DEFINITION_VERSIONS\n  | typeof TABLE_MCP_CLIENTS\n  | typeof TABLE_MCP_CLIENT_VERSIONS\n  | typeof TABLE_MCP_SERVERS\n  | typeof TABLE_MCP_SERVER_VERSIONS\n  | typeof TABLE_WORKSPACES\n  | typeof TABLE_WORKSPACE_VERSIONS\n  | typeof TABLE_SKILLS\n  | typeof TABLE_SKILL_VERSIONS\n  | typeof TABLE_SKILL_BLOBS\n  | typeof TABLE_DATASETS\n  | typeof TABLE_DATASET_ITEMS\n  | typeof TABLE_DATASET_VERSIONS\n  | typeof TABLE_EXPERIMENTS\n  | typeof TABLE_EXPERIMENT_RESULTS;\n\nexport const SCORERS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  scorerId: { type: 'text' },\n  traceId: { type: 'text', nullable: true },\n  spanId: { type: 'text', nullable: true },\n  runId: { type: 'text' },\n  scorer: { type: 'jsonb' },\n  preprocessStepResult: { type: 'jsonb', nullable: true },\n  extractStepResult: { type: 'jsonb', nullable: true },\n  analyzeStepResult: { type: 'jsonb', nullable: true },\n  score: { type: 'float' },\n  reason: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  preprocessPrompt: { type: 'text', nullable: true },\n  extractPrompt: { type: 'text', nullable: true },\n  generateScorePrompt: { type: 'text', nullable: true },\n  generateReasonPrompt: { type: 'text', nullable: true },\n  analyzePrompt: { type: 'text', nullable: true },\n\n  // Deprecated\n  reasonPrompt: { type: 'text', nullable: true },\n  input: { type: 'jsonb' },\n  output: { type: 'jsonb' }, // MESSAGE OUTPUT\n  additionalContext: { type: 'jsonb', nullable: true }, // DATA FROM THE CONTEXT PARAM ON AN AGENT\n  requestContext: { type: 'jsonb', nullable: true }, // THE EVALUATE Request Context FOR THE RUN\n  /**\n   * Things you can evaluate\n   */\n  entityType: { type: 'text', nullable: true }, // WORKFLOW, AGENT, TOOL, STEP, NETWORK\n  entity: { type: 'jsonb', nullable: true }, // MINIMAL JSON DATA ABOUT WORKFLOW, AGENT, TOOL, STEP, NETWORK\n  entityId: { type: 'text', nullable: true },\n  source: { type: 'text' },\n  resourceId: { type: 'text', nullable: true },\n  threadId: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp' },\n  updatedAt: { type: 'timestamp' },\n};\n\nexport const SPAN_SCHEMA = buildStorageSchema(spanRecordSchema);\n\n/**\n * @deprecated Use SPAN_SCHEMA instead. This legacy schema is retained only for migration purposes.\n * @internal\n */\nexport const OLD_SPAN_SCHEMA: Record<string, StorageColumn> = {\n  // Composite primary key of traceId and spanId\n  traceId: { type: 'text', nullable: false },\n  spanId: { type: 'text', nullable: false },\n  parentSpanId: { type: 'text', nullable: true },\n  name: { type: 'text', nullable: false },\n  scope: { type: 'jsonb', nullable: true }, // Mastra package info {\"core-version\": \"0.1.0\"}\n  spanType: { type: 'text', nullable: false }, // WORKFLOW_RUN, WORKFLOW_STEP, AGENT_RUN, AGENT_STEP, TOOL_RUN, TOOL_STEP, etc.\n  attributes: { type: 'jsonb', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  links: { type: 'jsonb', nullable: true },\n  input: { type: 'jsonb', nullable: true },\n  output: { type: 'jsonb', nullable: true },\n  error: { type: 'jsonb', nullable: true },\n  startedAt: { type: 'timestamp', nullable: false }, // When the span started\n  endedAt: { type: 'timestamp', nullable: true }, // When the span ended\n  createdAt: { type: 'timestamp', nullable: false }, // The time the database record was created\n  updatedAt: { type: 'timestamp', nullable: true }, // The time the database record was last updated\n  isEvent: { type: 'boolean', nullable: false },\n};\n\nexport const AGENTS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft' or 'published'\n  activeVersionId: { type: 'text', nullable: true }, // FK to agent_versions.id\n  authorId: { type: 'text', nullable: true }, // Author identifier for multi-tenant filtering\n  metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const AGENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true }, // UUID\n  agentId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  // Agent config fields\n  name: { type: 'text', nullable: false }, // Agent display name\n  description: { type: 'text', nullable: true },\n  instructions: { type: 'text', nullable: false },\n  model: { type: 'jsonb', nullable: false },\n  tools: { type: 'jsonb', nullable: true },\n  defaultOptions: { type: 'jsonb', nullable: true },\n  workflows: { type: 'jsonb', nullable: true },\n  agents: { type: 'jsonb', nullable: true },\n  integrationTools: { type: 'jsonb', nullable: true },\n  inputProcessors: { type: 'jsonb', nullable: true },\n  outputProcessors: { type: 'jsonb', nullable: true },\n  memory: { type: 'jsonb', nullable: true },\n  scorers: { type: 'jsonb', nullable: true },\n  mcpClients: { type: 'jsonb', nullable: true },\n  requestContextSchema: { type: 'jsonb', nullable: true },\n  workspace: { type: 'jsonb', nullable: true },\n  skills: { type: 'jsonb', nullable: true },\n  skillsFormat: { type: 'text', nullable: true },\n  // Version metadata\n  changedFields: { type: 'jsonb', nullable: true }, // Array of field names\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCKS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n  activeVersionId: { type: 'text', nullable: true }, // FK to prompt_block_versions.id\n  authorId: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const PROMPT_BLOCK_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  blockId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  name: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: true },\n  content: { type: 'text', nullable: false },\n  rules: { type: 'jsonb', nullable: true },\n  requestContextSchema: { type: 'jsonb', nullable: true },\n  changedFields: { type: 'jsonb', nullable: true },\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n  activeVersionId: { type: 'text', nullable: true }, // FK to scorer_definition_versions.id\n  authorId: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SCORER_DEFINITION_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  scorerDefinitionId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  name: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: true },\n  type: { type: 'text', nullable: false }, // 'llm-judge', 'bias', 'toxicity', etc.\n  model: { type: 'jsonb', nullable: true },\n  instructions: { type: 'text', nullable: true },\n  scoreRange: { type: 'jsonb', nullable: true },\n  presetConfig: { type: 'jsonb', nullable: true },\n  defaultSampling: { type: 'jsonb', nullable: true },\n  changedFields: { type: 'jsonb', nullable: true },\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_CLIENTS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n  activeVersionId: { type: 'text', nullable: true }, // FK to mcp_client_versions.id\n  authorId: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_CLIENT_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  mcpClientId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  name: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: true },\n  servers: { type: 'jsonb', nullable: false },\n  changedFields: { type: 'jsonb', nullable: true },\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_SERVERS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n  activeVersionId: { type: 'text', nullable: true }, // FK to mcp_server_versions.id\n  authorId: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const MCP_SERVER_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  mcpServerId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  name: { type: 'text', nullable: false },\n  version: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: true },\n  instructions: { type: 'text', nullable: true },\n  repository: { type: 'jsonb', nullable: true },\n  releaseDate: { type: 'text', nullable: true },\n  isLatest: { type: 'boolean', nullable: true },\n  packageCanonical: { type: 'text', nullable: true },\n  tools: { type: 'jsonb', nullable: true },\n  agents: { type: 'jsonb', nullable: true },\n  workflows: { type: 'jsonb', nullable: true },\n  changedFields: { type: 'jsonb', nullable: true },\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const WORKSPACES_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n  activeVersionId: { type: 'text', nullable: true }, // FK to workspace_versions.id\n  authorId: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const WORKSPACE_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  workspaceId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  name: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: true },\n  filesystem: { type: 'jsonb', nullable: true },\n  sandbox: { type: 'jsonb', nullable: true },\n  mounts: { type: 'jsonb', nullable: true },\n  search: { type: 'jsonb', nullable: true },\n  skills: { type: 'jsonb', nullable: true },\n  tools: { type: 'jsonb', nullable: true },\n  autoSync: { type: 'boolean', nullable: true },\n  operationTimeout: { type: 'integer', nullable: true },\n  changedFields: { type: 'jsonb', nullable: true },\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SKILLS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  status: { type: 'text', nullable: false }, // 'draft', 'published', or 'archived'\n  activeVersionId: { type: 'text', nullable: true }, // FK to skill_versions.id\n  authorId: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SKILL_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  skillId: { type: 'text', nullable: false },\n  versionNumber: { type: 'integer', nullable: false },\n  name: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: false },\n  instructions: { type: 'text', nullable: false },\n  license: { type: 'text', nullable: true },\n  compatibility: { type: 'jsonb', nullable: true },\n  source: { type: 'jsonb', nullable: true },\n  references: { type: 'jsonb', nullable: true },\n  scripts: { type: 'jsonb', nullable: true },\n  assets: { type: 'jsonb', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  tree: { type: 'jsonb', nullable: true },\n  changedFields: { type: 'jsonb', nullable: true },\n  changeMessage: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const SKILL_BLOBS_SCHEMA: Record<string, StorageColumn> = {\n  hash: { type: 'text', nullable: false, primaryKey: true },\n  content: { type: 'text', nullable: false },\n  size: { type: 'integer', nullable: false },\n  mimeType: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\nexport const OBSERVATIONAL_MEMORY_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  lookupKey: { type: 'text', nullable: false }, // 'resource:{resourceId}' or 'thread:{threadId}'\n  scope: { type: 'text', nullable: false }, // 'resource' or 'thread'\n  resourceId: { type: 'text', nullable: true },\n  threadId: { type: 'text', nullable: true },\n  activeObservations: { type: 'text', nullable: false }, // JSON array of observations\n  activeObservationsPendingUpdate: { type: 'text', nullable: true }, // JSON array, used during updates\n  originType: { type: 'text', nullable: false }, // 'initialization', 'observation', or 'reflection'\n  config: { type: 'text', nullable: false }, // JSON object\n  generationCount: { type: 'integer', nullable: false },\n  lastObservedAt: { type: 'timestamp', nullable: true },\n  lastReflectionAt: { type: 'timestamp', nullable: true },\n  pendingMessageTokens: { type: 'integer', nullable: false }, // Token count\n  totalTokensObserved: { type: 'integer', nullable: false }, // Running total of all observed tokens\n  observationTokenCount: { type: 'integer', nullable: false }, // Current observation size in tokens\n  isObserving: { type: 'boolean', nullable: false },\n  isReflecting: { type: 'boolean', nullable: false },\n  observedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs already observed\n  observedTimezone: { type: 'text', nullable: true }, // Timezone used for Observer date formatting (e.g., \"America/Los_Angeles\")\n  // Async buffering columns\n  bufferedObservations: { type: 'text', nullable: true }, // JSON string of buffered observation content\n  bufferedObservationTokens: { type: 'integer', nullable: true }, // Token count of buffered observations\n  bufferedMessageIds: { type: 'jsonb', nullable: true }, // JSON array of message IDs in the buffer\n  bufferedReflection: { type: 'text', nullable: true }, // JSON string of buffered reflection content\n  bufferedReflectionTokens: { type: 'integer', nullable: true }, // Token count of buffered reflection (post-compression)\n  bufferedReflectionInputTokens: { type: 'integer', nullable: true }, // Token count of observations fed to reflector (pre-compression)\n  reflectedObservationLineCount: { type: 'integer', nullable: true }, // Number of observation lines that were reflected on during async buffering\n  bufferedObservationChunks: { type: 'jsonb', nullable: true }, // JSON array of BufferedObservationChunk objects\n  isBufferingObservation: { type: 'boolean', nullable: false },\n  isBufferingReflection: { type: 'boolean', nullable: false },\n  lastBufferedAtTokens: { type: 'integer', nullable: false },\n  lastBufferedAtTime: { type: 'timestamp', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\n// Dataset schemas\nexport const DATASETS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  name: { type: 'text', nullable: false },\n  description: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  inputSchema: { type: 'jsonb', nullable: true },\n  groundTruthSchema: { type: 'jsonb', nullable: true },\n  requestContextSchema: { type: 'jsonb', nullable: true },\n  tags: { type: 'jsonb', nullable: true },\n  targetType: { type: 'text', nullable: true },\n  targetIds: { type: 'jsonb', nullable: true },\n  scorerIds: { type: 'jsonb', nullable: true },\n  version: { type: 'integer', nullable: false },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const DATASET_ITEMS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false },\n  datasetId: { type: 'text', nullable: false, references: { table: 'mastra_datasets', column: 'id' } },\n  datasetVersion: { type: 'integer', nullable: false },\n  validTo: { type: 'integer', nullable: true },\n  isDeleted: { type: 'boolean', nullable: false },\n  input: { type: 'jsonb', nullable: false },\n  groundTruth: { type: 'jsonb', nullable: true },\n  requestContext: { type: 'jsonb', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  source: { type: 'jsonb', nullable: true },\n  expectedTrajectory: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const DATASET_VERSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  datasetId: { type: 'text', nullable: false, references: { table: 'mastra_datasets', column: 'id' } },\n  version: { type: 'integer', nullable: false },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\n// Experiment schemas\nexport const EXPERIMENTS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  name: { type: 'text', nullable: true },\n  description: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  datasetId: { type: 'text', nullable: true, references: { table: 'mastra_datasets', column: 'id' } },\n  datasetVersion: { type: 'integer', nullable: true },\n  targetType: { type: 'text', nullable: false },\n  targetId: { type: 'text', nullable: false },\n  status: { type: 'text', nullable: false },\n  totalItems: { type: 'integer', nullable: false },\n  succeededCount: { type: 'integer', nullable: false },\n  failedCount: { type: 'integer', nullable: false },\n  skippedCount: { type: 'integer', nullable: false },\n  startedAt: { type: 'timestamp', nullable: true },\n  completedAt: { type: 'timestamp', nullable: true },\n  agentVersion: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const EXPERIMENT_RESULTS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  experimentId: { type: 'text', nullable: false, references: { table: 'mastra_experiments', column: 'id' } },\n  itemId: { type: 'text', nullable: false, references: { table: 'mastra_dataset_items', column: 'id' } },\n  itemDatasetVersion: { type: 'integer', nullable: true },\n  input: { type: 'jsonb', nullable: false },\n  output: { type: 'jsonb', nullable: true },\n  groundTruth: { type: 'jsonb', nullable: true },\n  error: { type: 'jsonb', nullable: true },\n  startedAt: { type: 'timestamp', nullable: false },\n  completedAt: { type: 'timestamp', nullable: false },\n  retryCount: { type: 'integer', nullable: false },\n  traceId: { type: 'text', nullable: true },\n  status: { type: 'text', nullable: true },\n  tags: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Schema definitions for all core tables.\n */\nexport const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>> = {\n  [TABLE_WORKFLOW_SNAPSHOT]: {\n    workflow_name: {\n      type: 'text',\n    },\n    run_id: {\n      type: 'text',\n    },\n    resourceId: { type: 'text', nullable: true },\n    snapshot: {\n      type: 'jsonb',\n    },\n    createdAt: {\n      type: 'timestamp',\n    },\n    updatedAt: {\n      type: 'timestamp',\n    },\n  },\n  [TABLE_SCORERS]: SCORERS_SCHEMA,\n  [TABLE_THREADS]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    resourceId: { type: 'text', nullable: false },\n    title: { type: 'text', nullable: false },\n    metadata: { type: 'jsonb', nullable: true },\n    createdAt: { type: 'timestamp', nullable: false },\n    updatedAt: { type: 'timestamp', nullable: false },\n  },\n  [TABLE_MESSAGES]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    thread_id: { type: 'text', nullable: false },\n    content: { type: 'text', nullable: false },\n    role: { type: 'text', nullable: false },\n    type: { type: 'text', nullable: false },\n    createdAt: { type: 'timestamp', nullable: false },\n    resourceId: { type: 'text', nullable: true },\n  },\n  [TABLE_SPANS]: SPAN_SCHEMA,\n  [TABLE_TRACES]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    parentSpanId: { type: 'text', nullable: true },\n    name: { type: 'text', nullable: false },\n    traceId: { type: 'text', nullable: false },\n    scope: { type: 'text', nullable: false },\n    kind: { type: 'integer', nullable: false },\n    attributes: { type: 'jsonb', nullable: true },\n    status: { type: 'jsonb', nullable: true },\n    events: { type: 'jsonb', nullable: true },\n    links: { type: 'jsonb', nullable: true },\n    other: { type: 'text', nullable: true },\n    startTime: { type: 'bigint', nullable: false },\n    endTime: { type: 'bigint', nullable: false },\n    createdAt: { type: 'timestamp', nullable: false },\n  },\n  [TABLE_RESOURCES]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    workingMemory: { type: 'text', nullable: true },\n    metadata: { type: 'jsonb', nullable: true },\n    createdAt: { type: 'timestamp', nullable: false },\n    updatedAt: { type: 'timestamp', nullable: false },\n  },\n  [TABLE_AGENTS]: AGENTS_SCHEMA,\n  [TABLE_AGENT_VERSIONS]: AGENT_VERSIONS_SCHEMA,\n  [TABLE_PROMPT_BLOCKS]: PROMPT_BLOCKS_SCHEMA,\n  [TABLE_PROMPT_BLOCK_VERSIONS]: PROMPT_BLOCK_VERSIONS_SCHEMA,\n  [TABLE_SCORER_DEFINITIONS]: SCORER_DEFINITIONS_SCHEMA,\n  [TABLE_SCORER_DEFINITION_VERSIONS]: SCORER_DEFINITION_VERSIONS_SCHEMA,\n  [TABLE_MCP_CLIENTS]: MCP_CLIENTS_SCHEMA,\n  [TABLE_MCP_CLIENT_VERSIONS]: MCP_CLIENT_VERSIONS_SCHEMA,\n  [TABLE_MCP_SERVERS]: MCP_SERVERS_SCHEMA,\n  [TABLE_MCP_SERVER_VERSIONS]: MCP_SERVER_VERSIONS_SCHEMA,\n  [TABLE_WORKSPACES]: WORKSPACES_SCHEMA,\n  [TABLE_WORKSPACE_VERSIONS]: WORKSPACE_VERSIONS_SCHEMA,\n  [TABLE_SKILLS]: SKILLS_SCHEMA,\n  [TABLE_SKILL_VERSIONS]: SKILL_VERSIONS_SCHEMA,\n  [TABLE_SKILL_BLOBS]: SKILL_BLOBS_SCHEMA,\n  [TABLE_DATASETS]: DATASETS_SCHEMA,\n  [TABLE_DATASET_ITEMS]: DATASET_ITEMS_SCHEMA,\n  [TABLE_DATASET_VERSIONS]: DATASET_VERSIONS_SCHEMA,\n  [TABLE_EXPERIMENTS]: EXPERIMENTS_SCHEMA,\n  [TABLE_EXPERIMENT_RESULTS]: EXPERIMENT_RESULTS_SCHEMA,\n};\n\n/**\n * Table-level config for tables that need composite primary keys or other table-level settings.\n * Keyed by table name. Tables not listed here use single-column PKs from their schema.\n */\nexport const TABLE_CONFIGS: Partial<Record<TABLE_NAMES, StorageTableConfig>> = {\n  [TABLE_DATASET_ITEMS]: { columns: DATASET_ITEMS_SCHEMA, compositePrimaryKey: ['id', 'datasetVersion'] },\n};\n\n/**\n * Schema for the observational memory table.\n * Exported separately as OM is optional and not part of TABLE_NAMES.\n */\nexport const OBSERVATIONAL_MEMORY_TABLE_SCHEMA = {\n  [TABLE_OBSERVATIONAL_MEMORY]: OBSERVATIONAL_MEMORY_SCHEMA,\n};\n"]}