{"version":3,"file":"constants-CHm1eNBE.cjs","names":["z","SpanType","dbTimestamps","paginationInfoSchema","getZodTypeName","getZodInnerType","zodV4","zodV3","z","SpanType","spanContextFields","metadataField","tagsField","traceIdField","spanIdField","dbTimestamps","dateRangeSchema","sortDirectionSchema","listModeSchema","paginationArgsSchema","deltaCursorSchema","deltaLimitSchema","refineObservabilityListMode","normalizeObservabilityListArgs","paginationInfoSchema","deltaInfoSchema"],"sources":["../src/evals/types.ts","../src/storage/types.ts","../src/storage/domains/observability/tracing.ts","../src/storage/constants.ts"],"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([\n  'AGENT',\n  'WORKFLOW',\n  'TRAJECTORY',\n  'STEP',\n  ...Object.values(SpanType),\n] as [string, string, ...string[]]);\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  // Tenancy: organizationId arrives via ObservabilityContext; projectId is scores-specific.\n  projectId: 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  // Multi-tenant scope. `resourceId` is overloaded (memory end-user), so tenancy\n  // uses dedicated fields: organizationId (account) + projectId (project scope).\n  organizationId: z.string().nullish(),\n  projectId: z.string().nullish(),\n  // Batch handle shared across all per-trace scores produced by one batch scoring\n  // call. `runId` stays per-execution; `batchId` groups the batch.\n  batchId: z.string().nullish(),\n  // Dataset provenance: links a baseline score back to the curated dataset item it\n  // scored, so scores can join to ground truth without re-running the agent.\n  datasetId: z.string().nullish(),\n  datasetItemId: z.string().nullish(),\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 ProviderToolCallStep = TrajectoryStepBase & {\n  stepType: 'provider_tool_call';\n  /** Arguments passed to the server-side tool */\n  toolArgs?: Record<string, unknown>;\n  /** Result returned by the server-side tool */\n  toolResult?: Record<string, unknown>;\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  | ProviderToolCallStep\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    // Prefer the legacy toolInvocations array when present; fall back to\n    // V2 content.parts for messages that only store tool calls there.\n    const legacy = message?.content?.toolInvocations;\n    const fromParts = legacy\n      ? undefined\n      : message?.content?.parts\n          ?.filter((p): p is Extract<typeof p, { type: 'tool-invocation' }> => p.type === 'tool-invocation')\n          .map(p => p.toolInvocation);\n    const toolInvocations = legacy ?? fromParts;\n    if (!toolInvocations?.length) 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_INFERENCE,\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.PROVIDER_TOOL_CALL: {\n      const toolArgs = toRecordOrUndefined(span.input);\n      const toolResult = toRecordOrUndefined(span.output);\n      return [\n        {\n          ...base,\n          stepType: 'provider_tool_call' as const,\n          toolArgs,\n          toolResult,\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 type { z } from 'zod/v4';\nimport type { AgentExecutionOptionsBase } from '../agent/agent.types';\nimport type { SerializedError } from '../error';\nimport type { ScoringSamplingConfig, ScoringSource } 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\nexport type StorageMetadataFilterValue = string | number | boolean | null;\n\nexport type StorageMetadataFilter = Record<string, StorageMetadataFilterValue>;\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     * Filter messages by shallow scalar metadata key-value pairs from message content metadata.\n     * All specified key-value pairs must match with exact type equality (AND logic).\n     * Keys must start with a letter or underscore, contain only letters, numbers, and underscores,\n     * be at most 128 characters, and cannot be `__proto__`, `prototype`, or `constructor`.\n     */\n    metadata?: StorageMetadataFilter;\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 * One pinned connection on a tool provider config (per-agent snapshot).\n * Adapter-native `connectionId` is the join key into the\n * `mastra_tool_provider_connections` storage table.\n */\nexport interface StorageToolProviderConfigConnection {\n  kind: 'author' | 'invoker' | 'platform';\n  connectionId: string;\n  toolkit: string;\n  label?: string;\n  scope?: StorageToolProviderConnectionScope;\n}\n\n/**\n * Per-tool metadata (toolkit + optional description override) for a tool\n * provider's selected tools.\n */\nexport interface StorageToolProviderToolMeta {\n  toolkit?: string;\n  description?: string;\n}\n\n/**\n * Stored shape for one tool provider's configuration on one agent.\n * Keyed by tool slug for `tools` and by toolkit slug for `connections`.\n */\nexport interface StorageToolProviderConfig {\n  tools: Record<string, StorageToolProviderToolMeta>;\n  connections: Record<string, StorageToolProviderConfigConnection[]>;\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  | 'requireToolApproval' // can be a function at runtime; stored options must be serializable\n> & {\n  /**\n   * Stored agents only support a boolean here. Function-based approval policies are runtime-only\n   * and cannot be serialized, so they are intentionally excluded from stored default options.\n   */\n  requireToolApproval?: boolean;\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  /**\n   * Tool provider configs keyed by provider id (e.g. `'composio'`).\n   * Each config selects tool slugs and pins per-toolkit connections.\n   * Static or conditional on request context.\n   */\n  toolProviders?: StorageConditionalField<Record<string, StorageToolProviderConfig>>;\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  /** Browser reference — inline browser config — static or conditional on request context */\n  browser?: StorageConditionalField<StorageBrowserRef>;\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 */\n/**\n * Visibility of a stored agent.\n * - `private`: only the owner (or admins) can read the record.\n * - `public`: any authenticated caller with `agents:read` can read the record.\n */\nexport type StorageVisibility = 'private' | 'public';\n\nexport const STORAGE_VISIBILITY_VALUES = ['private', 'public'] as const satisfies readonly StorageVisibility[];\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  /**\n   * Visibility of the stored agent. `private` limits access to the owner / admins;\n   * `public` allows any authenticated caller with `agents:read` to read.\n   * May be undefined for legacy records created before visibility was introduced.\n   */\n  visibility?: StorageVisibility;\n  /** Additional metadata for the agent */\n  metadata?: Record<string, unknown>;\n  /**\n   * Denormalized count of favorites on this agent. Maintained by the favorites\n   * storage domain. Optional; treat undefined as 0 for legacy rows.\n   */\n  favoriteCount?: number;\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  /** Visibility of the stored agent (defaults to 'private' when an authorId is set) */\n  visibility?: StorageVisibility;\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  /** Visibility of the stored agent */\n  visibility?: StorageVisibility;\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' | 'browser'>> & {\n    /** Memory configuration object (static or conditional), or null to disable memory */\n    memory?: StorageConditionalField<SerializedMemoryConfig> | null;\n    /** Browser configuration (inline ref), or null to disable browser */\n    browser?: StorageConditionalField<StorageBrowserRef> | 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 visibility (exact match).\n   */\n  visibility?: StorageVisibility;\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   * Restrict results to this set of agent IDs. Used by the favorites feature\n   * to fetch a specific subset of favorited agents. When provided as an\n   * empty array, the result is empty.\n   */\n  entityIds?: string[];\n  /**\n   * When set, agents favorited by this user are returned first, ordered\n   * by `(is_favorited DESC, <existing orderBy>, id ASC)` over the full\n   * candidate set before pagination. Implementations that don't support\n   * favorited-first sort treat this as undefined.\n   */\n  pinFavoritedFor?: string;\n  /**\n   * When true, only agents favorited by `pinFavoritedFor` are returned.\n   * Requires `pinFavoritedFor` to be set. SQL backends collapse this into\n   * the same JOIN used for favorited-first sort.\n   */\n  favoritedOnly?: boolean;\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  /** Organization identifier for multi-tenant scoping */\n  organizationId?: string;\n  /** Project identifier for multi-tenant scoping */\n  projectId?: 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  /** Organization identifier for multi-tenant scoping */\n  organizationId?: string;\n  /** Project identifier for multi-tenant scoping */\n  projectId?: 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 organization identifier (multi-tenant scoping).\n   */\n  organizationId?: string;\n  /**\n   * Filter scorers by project identifier (multi-tenant scoping).\n   */\n  projectId?: 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  /** Values extracted during this buffered observation cycle. */\n  extractedValues?: Record<string, unknown>;\n  /** Extractor failures from this buffered observation cycle. */\n  extractionFailures?: Array<{ slug: string; error: 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  /** Values extracted during this buffered observation cycle. */\n  extractedValues?: Record<string, unknown>;\n  /** Extractor failures from this buffered observation cycle. */\n  extractionFailures?: Array<{ slug: string; error: 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 * A node in the skill file tree (folder or file with inline content).\n * Used for round-tripping the full file structure through the UI.\n */\nexport interface StorageSkillFileNode {\n  id?: string;\n  name: string;\n  type: 'file' | 'folder';\n  content?: string;\n  children?: StorageSkillFileNode[];\n}\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  /** Full file tree structure (folders, files with content) for round-tripping in the UI */\n  files?: StorageSkillFileNode[];\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  /**\n   * Access control: 'private' = only owner/admins, 'public' = anyone.\n   * May be undefined for legacy records created before visibility was introduced.\n   */\n  visibility?: StorageVisibility;\n  /**\n   * Denormalized count of favorites on this skill. Maintained by the favorites\n   * storage domain. Optional; treat undefined as 0 for legacy rows.\n   */\n  favoriteCount?: number;\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  /** Access control visibility */\n  visibility?: StorageVisibility;\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  /** Access control visibility */\n  visibility?: StorageVisibility;\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 visibility (exact match).\n   */\n  visibility?: StorageVisibility;\n  /**\n   * Filter skills by status (exact match).\n   */\n  status?: StorageSkillType['status'];\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   * Restrict results to this set of skill IDs. Used by the favorites feature\n   * to fetch a specific subset of favorited skills. When provided as an\n   * empty array, the result is empty.\n   */\n  entityIds?: string[];\n  /**\n   * When set, skills favorited by this user are returned first, ordered\n   * by `(is_favorited DESC, <existing orderBy>, id ASC)` over the full\n   * candidate set before pagination. Implementations that don't support\n   * favorited-first sort treat this as undefined.\n   */\n  pinFavoritedFor?: string;\n  /**\n   * When true, only skills favorited by `pinFavoritedFor` are returned.\n   * Requires `pinFavoritedFor` to be set. SQL backends collapse this into\n   * the same JOIN used for favorited-first sort.\n   */\n  favoritedOnly?: boolean;\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, provide inline workspace config,\n * or name a registered workspace provider to build the entire workspace.\n */\nexport type StorageWorkspaceRef =\n  | { type: 'id'; workspaceId: string }\n  | { type: 'inline'; config: StorageWorkspaceSnapshotType }\n  | { type: 'provider'; provider: string; config: Record<string, unknown> };\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  activePaths?: Array<number>;\n  activeStepsPath?: Record<string, 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// Browser Configuration Types\n// ============================================\n\n/**\n * Browser configuration stored in agent snapshots.\n *\n * Only stable, declarative configuration is persisted here. Runtime/security\n * concerns (cdpUrl, scope, profile, executablePath) belong in the BrowserProvider\n * registration where they're set per-instance via `createBrowser`.\n *\n * Runtime-only options (onLaunch, onClose, cdpUrl as function) are never stored.\n */\nexport interface StorageBrowserConfig {\n  /** Provider type identifier (e.g., 'stagehand', 'playwright') — resolved by the editor's browser registry */\n  provider: string;\n\n  /**\n   * Whether to run the browser in headless mode (no visible UI).\n   * @default true\n   */\n  headless?: boolean;\n\n  /**\n   * Browser viewport dimensions.\n   * Controls the size of the browser window and how websites render.\n   */\n  viewport?: {\n    width: number;\n    height: number;\n  };\n\n  /**\n   * Default timeout in milliseconds for browser operations.\n   * @default 10000 (10 seconds)\n   */\n  timeout?: number;\n\n  /**\n   * Screencast options for streaming browser frames.\n   */\n  screencast?: {\n    /** Image format (default: 'jpeg') */\n    format?: 'jpeg' | 'png';\n    /** JPEG quality 0-100 (default: 80) */\n    quality?: number;\n    /** Max width in pixels (default: 1280) */\n    maxWidth?: number;\n    /** Max height in pixels (default: 720) */\n    maxHeight?: number;\n    /** Capture every Nth frame (default: 1) */\n    everyNthFrame?: number;\n  };\n}\n\n/**\n * Browser reference configuration stored in agent snapshots.\n * Provides inline browser config that the editor resolves at hydration time.\n */\nexport type StorageBrowserRef = { type: 'inline'; config: StorageBrowserConfig };\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  /** Multi-tenant organization/account scope. */\n  organizationId?: string | null;\n  /** Platform project scope. Pairs with {@link DatasetRecord.organizationId} to form the dataset's tenancy bucket. */\n  projectId?: string | null;\n  /** Recurring-problem fingerprint (e.g. detector-emitted candidate key). */\n  candidateKey?: string | null;\n  /** Incident-specific identifier minted by the detector. */\n  candidateId?: string | null;\n  version: number;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\nexport interface DatasetItemSource {\n  type: 'csv' | 'json' | 'trace' | 'llm' | 'experiment-result' | 'candidate-screener';\n  referenceId?: string;\n}\n\n/**\n * A single static tool mock authored on a dataset item (output-only in v1).\n * Structurally mirrors `ItemToolMock` in the experiment engine; kept local here\n * to avoid a storage→datasets import cycle.\n */\nexport interface DatasetItemToolMock {\n  toolName: string;\n  args: Record<string, unknown>;\n  output: unknown;\n  /** Argument matching mode. `strict` (default) deep-equals args; `ignore` matches on toolName only. */\n  matchArgs?: 'strict' | 'ignore';\n}\n\n/**\n * Diagnostic receipt for tool-mock usage on a single experiment result.\n * Structurally mirrors `ToolMockReport` in the experiment engine.\n */\nexport type DatasetUnmockedToolPolicy = 'allow' | 'deny';\n\nexport interface DatasetToolMockReport {\n  served: { mockIndex: number; toolName: string; args: unknown }[];\n  unconsumed: { mockIndex: number; toolName: string; args: unknown }[];\n  liveCalls: { toolName: string; args: unknown }[];\n  failure?: {\n    code: 'TOOL_MOCK_MISMATCH' | 'TOOL_MOCK_EXHAUSTED' | 'TOOL_MOCK_NOT_DECLARED';\n    toolName: string;\n    args: unknown;\n  };\n}\n\nexport interface DatasetItem {\n  id: string;\n  datasetId: string;\n  datasetVersion: number;\n  /** Caller-defined, dataset-local logical identity. Immutable after insertion. */\n  externalId?: string | null;\n  /** Inherited from the parent dataset at insert time. */\n  organizationId?: string | null;\n  /** Inherited from the parent dataset at insert time. */\n  projectId?: string | null;\n  input: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  toolMocks?: DatasetItemToolMock[];\n  unmockedToolPolicy?: DatasetUnmockedToolPolicy;\n  scorerIds?: string[];\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  /** Caller-defined, dataset-local logical identity. Immutable across SCD-2 history. */\n  externalId?: string | null;\n  /** Inherited from the parent dataset at insert time. */\n  organizationId?: string | null;\n  /** Inherited from the parent dataset at insert time. */\n  projectId?: string | null;\n  validTo: number | null;\n  isDeleted: boolean;\n  input: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  toolMocks?: DatasetItemToolMock[];\n  unmockedToolPolicy?: DatasetUnmockedToolPolicy;\n  scorerIds?: string[];\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  /**\n   * Optional caller-defined durable identity. When provided, storage adapters atomically create\n   * the dataset or return the compatible dataset that already owns this ID.\n   */\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  /**\n   * Discriminator for the target this dataset's items will be replayed against.\n   * Optional because a dataset can exist purely as a collection of items\n   * (e.g. emitted by a detector for a target kind OSS doesn't yet know how to\n   * run). Datasets created without a {@link TargetType} are **not\n   * experiment-eligible**: the experiment runner requires a non-null\n   * {@link CreateExperimentInput.targetType} to resolve an executor, so a\n   * downstream consumer must either set this on create or refuse to run an\n   * experiment against the dataset.\n   */\n  targetType?: TargetType;\n  targetIds?: string[];\n  scorerIds?: string[];\n  /**\n   * Multi-tenant organization/account scope. Stamped onto every item inserted into this dataset.\n   * Immutable after create — items inherit this from the parent dataset on every write, so changing\n   * it later would corrupt SCD-2 tombstone history. Intentionally absent from {@link UpdateDatasetInput}.\n   */\n  organizationId?: string | null;\n  /**\n   * Platform project scope. Stamped onto every item inserted into this dataset.\n   * Pairs with {@link CreateDatasetInput.organizationId} to form the (organizationId, projectId)\n   * tenancy bucket. Immutable after create — see {@link CreateDatasetInput.organizationId}.\n   */\n  projectId?: string | null;\n  /**\n   * Recurring-problem fingerprint (e.g. detector-emitted candidate key).\n   * Immutable after create — pairs with {@link CreateDatasetInput.candidateId} to identify\n   * the dataset's source incident and must not drift over the dataset's lifetime.\n   */\n  candidateKey?: string | null;\n  /**\n   * Incident-specific identifier minted by the detector.\n   * Immutable after create — see {@link CreateDatasetInput.candidateKey}.\n   */\n  candidateId?: string | null;\n}\n\n/**\n * Update input for a dataset. Tenancy ({@link CreateDatasetInput.organizationId},\n * {@link CreateDatasetInput.projectId}) and candidate identity\n * ({@link CreateDatasetInput.candidateKey}, {@link CreateDatasetInput.candidateId})\n * are intentionally omitted from the payload: they are set once at create time and must\n * remain immutable so item SCD-2 history (which inherits these fields per-write from the\n * parent dataset) stays consistent across the dataset's lifetime.\n *\n * The optional `filters` field is a *read scope*, not a payload update — when provided,\n * the update is only applied if the target dataset row also matches the tenancy filters.\n * Callers that know the tenant should pass this to prevent cross-tenant updates via a\n * leaked dataset ID.\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  /** Tenancy read-scope. When set, the update only applies if the row matches; otherwise it is treated as NOT_FOUND. */\n  filters?: DatasetTenancyFilters;\n}\n\n/**\n * The mutable, user-supplied payload portion of a dataset item.\n *\n * Identity (`id`, `datasetId`) and storage-managed audit fields (`datasetVersion`,\n * `organizationId`, `projectId`, `createdAt`, `updatedAt`) live on {@link DatasetItem}\n * and are not part of the payload.\n *\n * Used as the base shape for {@link AddDatasetItemInput} and\n * {@link BatchInsertItemsInput.items}, and (as `Partial<…>`) for\n * {@link UpdateDatasetItemInput}.\n */\nexport interface DatasetItemPayload {\n  /**\n   * Optional caller-defined identity scoped to this dataset. Reusing an identity\n   * with the originally accepted payload is idempotent; incompatible reuse fails.\n   */\n  externalId?: string;\n  input: unknown;\n  groundTruth?: unknown;\n  expectedTrajectory?: unknown;\n  toolMocks?: DatasetItemToolMock[];\n  /** Overrides the experiment's handling of tool calls not declared in `toolMocks`. */\n  unmockedToolPolicy?: DatasetUnmockedToolPolicy;\n  scorerIds?: string[];\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  source?: DatasetItemSource;\n}\n\nexport interface AddDatasetItemInput extends DatasetItemPayload {\n  datasetId: string;\n  /**\n   * Tenancy read-scope for the parent dataset. When set, the insert is rejected\n   * (NOT_FOUND) if the parent dataset row does not match the tenancy filters —\n   * prevents adding items to a dataset in another tenant via a leaked datasetId.\n   */\n  filters?: DatasetTenancyFilters;\n}\n\n/**\n * Update input for a dataset item. All payload fields are optional; only the\n * provided fields are patched.\n *\n * The optional `filters` field is a tenancy read-scope for the parent dataset;\n * see {@link AddDatasetItemInput.filters}.\n */\nexport interface UpdateDatasetItemInput extends Partial<Omit<DatasetItemPayload, 'externalId' | 'scorerIds'>> {\n  id: string;\n  datasetId: string;\n  scorerIds?: string[] | null;\n  filters?: DatasetTenancyFilters;\n}\n\nexport interface DatasetItemIdentityConflictDetail {\n  index: number;\n  externalId: string;\n  existingItemId: string;\n  reason: 'payload_mismatch' | 'deleted';\n}\n\n/**\n * Delete input for a single dataset item. The optional `filters` field is a\n * tenancy read-scope for the parent dataset; see {@link AddDatasetItemInput.filters}.\n */\nexport interface DeleteDatasetItemInput {\n  id: string;\n  datasetId: string;\n  filters?: DatasetTenancyFilters;\n}\n\nexport interface DatasetTenancyFilters {\n  organizationId?: string;\n  projectId?: string;\n}\n\nexport interface ListDatasetsFilters extends DatasetTenancyFilters {\n  candidateKey?: string;\n  candidateId?: string;\n  /**\n   * Filter by dataset target type (agent | workflow | scorer | processor).\n   */\n  targetType?: TargetType;\n  /**\n   * Filter to datasets whose `targetIds` intersect this list. A dataset\n   * matches if any of its targetIds is in this array. An empty array is\n   * treated as \"no filter\" (matches all datasets), not \"match none\".\n   */\n  targetIds?: string[];\n  /**\n   * Substring match on dataset `name`, case-insensitive.\n   */\n  name?: string;\n}\n\nexport interface ListDatasetsInput {\n  pagination: StoragePagination;\n  filters?: ListDatasetsFilters;\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  filters?: DatasetTenancyFilters;\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: DatasetItemPayload[];\n  /** Tenancy read-scope for the parent dataset; see {@link AddDatasetItemInput.filters}. */\n  filters?: DatasetTenancyFilters;\n}\n\nexport interface BatchDeleteItemsInput {\n  datasetId: string;\n  itemIds: string[];\n  /** Tenancy read-scope for the parent dataset; see {@link AddDatasetItemInput.filters}. */\n  filters?: DatasetTenancyFilters;\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  /**\n   * The kind of executor this experiment runs against (agent / workflow / scorer / processor).\n   *\n   * Required: an experiment by definition replays inputs against a specific target, so the runner\n   * always needs a target type to resolve the executor. This differs from\n   * {@link CreateDatasetInput.targetType} (optional) — a dataset can exist without a designated\n   * target, but a dataset without one is not experiment-eligible.\n   */\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  /** Multi-tenant organization/account scope. Hydrated from the parent dataset on create. */\n  organizationId?: string | null;\n  /** Platform project scope. Pairs with {@link Experiment.organizationId} to form the experiment's tenancy bucket. */\n  projectId?: 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  comment?: string | null;\n  toolMockReport?: DatasetToolMockReport | null;\n  /** Multi-tenant organization/account scope. Denormalized from the parent experiment for efficient tenancy-scoped queries. */\n  organizationId?: string | null;\n  /** Platform project scope. Pairs with {@link ExperimentResult.organizationId} to form the result's tenancy bucket. */\n  projectId?: 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  comment?: 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  /**\n   * Discriminator for the target this experiment runs against. Required because\n   * an experiment by definition replays inputs through a specific target; the\n   * runner uses this to resolve the correct executor. Datasets whose\n   * {@link CreateDatasetInput.targetType} is absent are not experiment-eligible.\n   */\n  targetType: TargetType;\n  targetId: string;\n  totalItems: number;\n  /**\n   * Multi-tenant organization/account scope. Should be hydrated from the parent\n   * dataset on create so experiments inherit their dataset's tenancy bucket.\n   */\n  organizationId?: string | null;\n  /**\n   * Platform project scope. Pairs with {@link CreateExperimentInput.organizationId}\n   * to form the (organizationId, projectId) tenancy bucket. Hydrated from the\n   * parent dataset on create.\n   */\n  projectId?: string | null;\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   * Tool mock diagnostics for this item run. `null`/`undefined` both mean \"no\n   * report\" (the item ran without tool mocks). A present report means the item\n   * ran with mocks — see `served`/`unconsumed`/`liveCalls`/`failure`.\n   */\n  toolMockReport?: DatasetToolMockReport | null;\n  /** Multi-tenant organization/account scope. Should be hydrated from the parent experiment on insert. */\n  organizationId?: string | null;\n  /** Platform project scope. Hydrated from the parent experiment on insert. */\n  projectId?: string | null;\n}\n\n/**\n * Multi-tenant scoping filters for experiment queries. Mirrors\n * {@link DatasetTenancyFilters} so the experiments domain can be queried\n * within a tenancy bucket using the same shape.\n */\nexport interface ExperimentTenancyFilters {\n  organizationId?: string;\n  projectId?: string;\n}\n\n/**\n * Multi-tenant scoping filters for score queries. Mirrors\n * {@link DatasetTenancyFilters} so the scores domain can be queried\n * within a tenancy bucket using the same shape.\n */\nexport interface ScoreTenancyFilters {\n  organizationId?: string;\n  projectId?: string;\n}\n\nexport interface ListScoresByScorerIdInput {\n  scorerId: string;\n  pagination: StoragePagination;\n  entityId?: string;\n  entityType?: string;\n  source?: ScoringSource;\n  filters?: ScoreTenancyFilters;\n}\n\nexport interface ListScoresByRunIdInput {\n  runId: string;\n  pagination: StoragePagination;\n  filters?: ScoreTenancyFilters;\n}\n\nexport interface ListScoresByEntityIdInput {\n  entityId: string;\n  entityType: string;\n  pagination: StoragePagination;\n  filters?: ScoreTenancyFilters;\n}\n\nexport interface ListScoresBySpanInput {\n  traceId: string;\n  spanId: string;\n  pagination: StoragePagination;\n  filters?: ScoreTenancyFilters;\n}\n\nexport interface ListExperimentsInput {\n  datasetId?: string;\n  targetType?: TargetType;\n  targetId?: string;\n  agentVersion?: string;\n  status?: ExperimentStatus;\n  /** Multi-tenant scoping filters. See {@link ExperimentTenancyFilters}. */\n  filters?: ExperimentTenancyFilters;\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  /** Multi-tenant scoping filters. See {@link ExperimentTenancyFilters}. */\n  filters?: ExperimentTenancyFilters;\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\n// ============================================\n// Favorites Storage Types\n// ============================================\n\n/**\n * Entity types that can be favorited.\n * Currently agents and skills; extend here when other entities opt in.\n */\nexport type StorageFavoriteEntityType = 'agent' | 'skill';\n\nexport const STORAGE_FAVORITE_ENTITY_TYPES = ['agent', 'skill'] as const satisfies readonly StorageFavoriteEntityType[];\n\n/**\n * A single favorite row: one user favoriting one entity. Composite primary key is\n * `(userId, entityType, entityId)`. Idempotent — re-favoriting is a no-op.\n */\nexport interface StorageFavoriteType {\n  /** Caller identifier (matches authorId conventions used elsewhere). */\n  userId: string;\n  /** Type of entity being favorited. */\n  entityType: StorageFavoriteEntityType;\n  /** ID of the entity being favorited. */\n  entityId: string;\n  /** Timestamp the favorite was created. */\n  createdAt: Date;\n}\n\n/** Identifier for a favorite row, used by lookup and delete operations. */\nexport type StorageFavoriteKey = {\n  userId: string;\n  entityType: StorageFavoriteEntityType;\n  entityId: string;\n};\n\n/**\n * Input to look up which entities in a candidate set are favorited by a given\n * user. Used to annotate list responses without N+1 queries.\n */\nexport type StorageIsFavoritedBatchInput = {\n  userId: string;\n  entityType: StorageFavoriteEntityType;\n  entityIds: string[];\n};\n\n/** Input to list all entity IDs favorited by a given user, optionally scoped by entity type. */\nexport type StorageListFavoritesInput = {\n  userId: string;\n  entityType: StorageFavoriteEntityType;\n};\n\n/**\n * Input to remove all favorites for a given entity. Called by hard-delete handlers\n * so favorite rows do not orphan the deleted entity.\n */\nexport type StorageDeleteFavoritesForEntityInput = {\n  entityType: StorageFavoriteEntityType;\n  entityId: string;\n};\n\n/** Identity bucketing for a persisted tool provider connection row. */\nexport type StorageToolProviderConnectionScope = 'shared' | 'per-author' | 'caller-supplied';\n\n/**\n * A persisted tool provider connection row. Stores a per-author, provider-agnostic\n * label so the UI can surface a stable name (e.g. \"Work Gmail\") for the same\n * `connectionId` across agents. Unique on `(authorId, providerId, connectionId)`.\n */\nexport interface StorageToolProviderConnection {\n  /**\n   * Author/owner the connection belongs to. `'default'` when auth is disabled.\n   * Set to the shared bucket id when `scope === 'shared'`. When\n   * `scope === 'caller-supplied'`, this is a host-app end-user identifier\n   * forwarded via request context.\n   */\n  authorId: string;\n  /** Tool provider id, e.g. `'composio'`. */\n  providerId: string;\n  /** Toolkit slug, e.g. `'gmail'`. */\n  toolkit: string;\n  /** Adapter-native connection identifier (e.g. Composio `ca_...`). */\n  connectionId: string;\n  /** User-supplied display label. `null` when the user hasn't named it yet. */\n  label: string | null;\n  /**\n   * Identity bucketing. `'per-author'` is the default; `'shared'` makes the\n   * row visible to all callers regardless of resolved authorId; `'caller-supplied'`\n   * means `authorId` is a host-app end-user identifier forwarded via request context.\n   */\n  scope: StorageToolProviderConnectionScope;\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/** Input to upsert a tool provider connection row. Idempotent on `(authorId, providerId, connectionId)`. */\nexport type StorageUpsertToolProviderConnectionInput = {\n  authorId: string;\n  providerId: string;\n  toolkit: string;\n  connectionId: string;\n  label: string | null;\n  /** Defaults to `'per-author'` when omitted. */\n  scope?: StorageToolProviderConnectionScope;\n};\n\n/** Lookup key for a single tool provider connection row. */\nexport type StorageToolProviderConnectionKey = {\n  authorId: string;\n  providerId: string;\n  connectionId: string;\n};\n\n/** Input for listing tool provider connections, optionally scoped by author/provider/toolkit. */\nexport type StorageListToolProviderConnectionsInput = {\n  /** Omit to list across all authors (admin cross-author listing). */\n  authorId?: string;\n  providerId?: string;\n  toolkit?: string;\n  /** Optional scope filter. Omit to list rows of any scope. */\n  scope?: StorageToolProviderConnectionScope;\n};\n\n/** Input for deleting a single tool provider connection row. */\nexport type StorageDeleteToolProviderConnectionInput = {\n  authorId: string;\n  providerId: string;\n  connectionId: string;\n};\n","import { z } from 'zod/v4';\nimport { scoreRowDataSchema } from '../../../evals/types';\nimport { SpanType } from '../../../observability/types';\nimport {\n  deltaLimitSchema,\n  deltaInfoSchema,\n  spanContextFields,\n  dateRangeSchema,\n  dbTimestamps,\n  deltaCursorSchema,\n  listModeSchema,\n  metadataField,\n  normalizeObservabilityListArgs,\n  paginationArgsSchema,\n  paginationInfoSchema,\n  refineObservabilityListMode,\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: { error?: unknown; endedAt?: Date | string | null }): 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 getSpans (batch) operation arguments.\n *\n * Fetches multiple spans in a trace by spanId in one call. Used to power the\n * progressive-disclosure path in {@link getBranchArgsSchema}: walk the\n * lightweight {@link getStructureResponseSchema} to find which spanIds belong\n * to a branch, then fetch only those with full data instead of pulling the\n * entire trace.\n */\nexport const getSpansArgsSchema = z\n  .object({\n    traceId: traceIdField.min(1),\n    spanIds: z.array(spanIdField.min(1)).min(1).describe('Span IDs to fetch within the trace'),\n  })\n  .describe('Arguments for batch-fetching spans by spanId within a trace');\n\n/** Arguments for batch-fetching spans by spanId */\nexport type GetSpansArgs = z.infer<typeof getSpansArgsSchema>;\n\n/** Response schema for getSpans operation */\nexport const getSpansResponseSchema = z.object({\n  traceId: traceIdField,\n  spans: z.array(spanRecordSchema),\n});\n\n/** Response containing the requested spans (order is not guaranteed) */\nexport type GetSpansResponse = z.infer<typeof getSpansResponseSchema>;\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/**\n * Schema for getBranch operation arguments.\n *\n * Returns the subtree rooted at `spanId`. When `depth` is omitted the full\n * descendant subtree is returned; with a finite `depth` only that many levels\n * below the anchor are returned (depth: 0 → only the anchor span; depth: 1 →\n * anchor plus immediate children; etc).\n */\nexport const getBranchArgsSchema = z\n  .object({\n    traceId: traceIdField.min(1),\n    spanId: spanIdField.min(1),\n    depth: z.coerce\n      .number()\n      .int()\n      .min(0)\n      .optional()\n      .describe('Maximum descendant levels below the anchor span (omit for full subtree)'),\n  })\n  .describe('Arguments for getting a span branch (subtree rooted at a span)');\n\n/** Arguments for retrieving the subtree rooted at a span */\nexport type GetBranchArgs = z.input<typeof getBranchArgsSchema>;\n\n/**\n * Response schema for getBranch operation. Mirrors getTrace -- a flat list of\n * spans, traversal-agnostic. The anchor span is included as the first matching\n * span; callers reconstruct the tree via parentSpanId.\n */\nexport const getBranchResponseSchema = z.object({\n  traceId: traceIdField,\n  spans: z.array(spanRecordSchema),\n});\n\n/** Response containing the subtree rooted at a span */\nexport type GetBranchResponse = z.infer<typeof getBranchResponseSchema>;\n\n/**\n * Extracts the subtree rooted at `anchorSpanId` from a flat list of trace\n * spans. The anchor itself is included as the first element; descendants are\n * walked via `parentSpanId` and returned sorted by `startedAt` ascending after\n * the anchor. When `maxDepth` is provided, only that many levels of\n * descendants are returned (anchor counts as depth 0).\n *\n * Cycles in `parentSpanId` (which shouldn't happen in well-formed traces but\n * could surface from corrupted data) are handled by tracking visited spanIds\n * and skipping any span seen during this walk.\n *\n * Returns an empty array if the anchor isn't in the input.\n *\n * Generic over the span shape so it works on both full {@link SpanRecord}\n * lists (e.g. result of `getTrace`) and lightweight skeletons (result of\n * `getStructure`).\n */\nexport function extractBranchSpans<\n  T extends { spanId: string; parentSpanId?: string | null | undefined; startedAt: Date },\n>(spans: T[], anchorSpanId: string, maxDepth?: number): T[] {\n  const anchor = spans.find(s => s.spanId === anchorSpanId);\n  if (!anchor) return [];\n\n  // Build parentSpanId → children index for O(1) descent.\n  const childrenByParent = new Map<string, T[]>();\n  for (const span of spans) {\n    if (span.parentSpanId == null) continue;\n    const bucket = childrenByParent.get(span.parentSpanId);\n    if (bucket) {\n      bucket.push(span);\n    } else {\n      childrenByParent.set(span.parentSpanId, [span]);\n    }\n  }\n\n  const visited = new Set<string>([anchor.spanId]);\n  const descendants: T[] = [];\n  // BFS so depth bounding is straightforward; visited set prevents\n  // infinite loops on malformed (cyclic) parent chains.\n  let frontier: T[] = [anchor];\n  let depth = 0;\n  while (frontier.length > 0) {\n    if (maxDepth != null && depth >= maxDepth) break;\n    const next: T[] = [];\n    for (const span of frontier) {\n      const children = childrenByParent.get(span.spanId);\n      if (!children) continue;\n      for (const child of children) {\n        if (visited.has(child.spanId)) continue;\n        visited.add(child.spanId);\n        descendants.push(child);\n        next.push(child);\n      }\n    }\n    frontier = next;\n    depth++;\n  }\n\n  // Sort descendants by startedAt; keep the anchor at index 0 regardless of\n  // whether some descendant happens to have an earlier startedAt (clock skew,\n  // out-of-order isEvent spans, etc).\n  descendants.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());\n  return [anchor, ...descendants];\n}\n\n// ============================================================================\n// Lightweight Span & Trace Schemas (for timeline rendering)\n// ============================================================================\n\n/**\n * Lightweight span record containing only the fields needed for timeline rendering.\n * Excludes heavy fields: input, output, attributes, metadata, tags, links.\n * This reduces per-span payload from ~17KB to ~370 bytes (~97% reduction).\n */\nexport const lightSpanRecordSchema = z\n  .object({\n    // Required identifiers\n    ...spanIds,\n    name: spanNameField,\n    spanType: spanTypeField,\n    isEvent: isEventField,\n    startedAt: startedAtField,\n\n    // Nullish fields needed for timeline/status\n    parentSpanId: parentSpanIdField.nullish(),\n    endedAt: endedAtField.nullish(),\n    error: errorField.nullish(),\n\n    // Entity context (needed by TraceKeysAndValues on root span)\n    entityType: spanContextFields.entityType,\n    entityId: spanContextFields.entityId,\n    entityName: spanContextFields.entityName,\n\n    // Database timestamps\n    ...dbTimestamps,\n  })\n  .describe(\n    'Lightweight span record for timeline rendering (excludes input, output, attributes, metadata, tags, links)',\n  );\n\n/** Lightweight span record for timeline rendering */\nexport type LightSpanRecord = z.infer<typeof lightSpanRecordSchema>;\n\n/**\n * Response schema for getStructure operation.\n * Returns a trace with lightweight spans (only fields needed for timeline).\n */\nexport const getStructureResponseSchema = z.object({\n  traceId: traceIdField,\n  spans: z.array(lightSpanRecordSchema),\n});\n\n/** Response containing a trace with lightweight spans for timeline rendering */\nexport type GetStructureResponse = z.infer<typeof getStructureResponseSchema>;\n\n/** @deprecated Use {@link getStructureResponseSchema} instead. */\nexport const getTraceLightResponseSchema = getStructureResponseSchema;\n/** @deprecated Use {@link GetStructureResponse} instead. */\nexport type GetTraceLightResponse = GetStructureResponse;\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    // Identifier filter (matches the root span's trace identifier)\n    traceId: traceIdField.optional().describe('Filter by trace ID (matches root span)'),\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    mode: listModeSchema.optional(),\n    filters: tracesFilterSchema.optional().describe('Optional filters to apply'),\n    pagination: paginationArgsSchema.optional(),\n    orderBy: tracesOrderBySchema.optional(),\n    after: deltaCursorSchema.optional(),\n    limit: deltaLimitSchema,\n  })\n  .strict()\n  .superRefine(refineObservabilityListMode)\n  .transform(value =>\n    normalizeObservabilityListArgs<z.output<typeof tracesFilterSchema>, z.output<typeof tracesOrderBySchema>>(value, {\n      orderBy: { field: 'startedAt', direction: 'DESC' } as const,\n    }),\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.optional(),\n  delta: deltaInfoSchema.optional(),\n  deltaCursor: deltaCursorSchema.optional(),\n  spans: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated root spans with computed status. Trace delta mode returns only new trace rows. */\nexport type ListTracesResponse = z.infer<typeof listTracesResponseSchema>;\n\n/** Schema for listTracesLight operation response */\nexport const listTracesLightResponseSchema = z.object({\n  pagination: paginationInfoSchema,\n  spans: z.array(lightSpanRecordSchema),\n});\n\n/** Response containing paginated lightweight root spans */\nexport type ListTracesLightResponse = z.infer<typeof listTracesLightResponseSchema>;\n\n// ============================================================================\n// Trace branches (anchor spans surfaced as listable rows, including non-root)\n// ============================================================================\n\n/**\n * Span types that anchor a listable trace branch -- the spans a user thinks\n * about when looking for a specific run (agent/workflow/tool/etc.),\n * regardless of whether the entity ran as the root of its trace or nested\n * under a parent. Each row in {@link listBranchesArgsSchema} corresponds to\n * one such anchor span; the subtree below it is fetched via\n * {@link getBranchArgsSchema}.\n *\n * Excludes sub-operation spans (model_step, workflow_step, scorer_step,\n * memory_operation, rag_*, etc.) which are internal to a containing branch\n * rather than separately listable.\n */\nexport const BRANCH_SPAN_TYPES = [\n  SpanType.AGENT_RUN,\n  SpanType.WORKFLOW_RUN,\n  SpanType.PROCESSOR_RUN,\n  SpanType.SCORER_RUN,\n  SpanType.RAG_INGESTION,\n  SpanType.TOOL_CALL,\n  SpanType.MCP_TOOL_CALL,\n  SpanType.PROVIDER_TOOL_CALL,\n] as const satisfies readonly SpanType[];\n\n/** Set form of {@link BRANCH_SPAN_TYPES} for fast membership checks. */\nexport const BRANCH_SPAN_TYPE_SET: ReadonlySet<SpanType> = new Set(BRANCH_SPAN_TYPES);\n\n/** Schema for filtering branch anchor spans in list queries. */\nexport const branchesFilterSchema = z\n  .object({\n    // Date range filters apply to the branch anchor span itself\n    startedAt: dateRangeSchema.optional().describe('Filter by span start time range'),\n    endedAt: dateRangeSchema.optional().describe('Filter by span end time range'),\n\n    // Narrow within the branch span-type set; if omitted, all of them match\n    spanType: spanTypeField.optional(),\n\n    // Identifier filters\n    traceId: traceIdField.optional().describe('Filter by parent trace ID'),\n\n    // Per-span context fields (apply to the anchor span, not the trace root)\n    ...sharedFields,\n\n    // Derived status filter (computed from this anchor's own error/endedAt)\n    status: traceStatusField.optional(),\n  })\n  .describe('Filters for querying trace branches');\n\nexport const branchesOrderByFieldSchema = z\n  .enum(['startedAt', 'endedAt'])\n  .describe(\"Field to order by: 'startedAt' | 'endedAt'\");\n\nexport const branchesOrderBySchema = z\n  .object({\n    field: branchesOrderByFieldSchema.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 trace branches.\n *\n * Each row is a single branch anchor span ({@link BRANCH_SPAN_TYPES}),\n * including ones nested under a different root entity. Use this when you\n * want every run of a given agent/processor/tool regardless of how it was\n * triggered. Use {@link listTracesArgsSchema} when you want one row per\n * trace, and {@link getBranchArgsSchema} to expand a single branch into its\n * subtree.\n */\nexport const listBranchesArgsSchema = z\n  .object({\n    mode: listModeSchema.optional(),\n    filters: branchesFilterSchema.optional().describe('Optional filters to apply'),\n    pagination: paginationArgsSchema.optional(),\n    orderBy: branchesOrderBySchema.optional(),\n    after: deltaCursorSchema.optional(),\n    limit: deltaLimitSchema,\n  })\n  .strict()\n  .superRefine(refineObservabilityListMode)\n  .transform(value =>\n    normalizeObservabilityListArgs<z.output<typeof branchesFilterSchema>, z.output<typeof branchesOrderBySchema>>(\n      value,\n      {\n        orderBy: { field: 'startedAt', direction: 'DESC' } as const,\n      },\n    ),\n  )\n  .describe('Arguments for listing trace branches.');\n\n/** Arguments for listing branches with optional filters, pagination, and ordering */\nexport type ListBranchesArgs = z.input<typeof listBranchesArgsSchema>;\n\n/**\n * Schema for listBranches operation response. Each row is a single branch\n * anchor span -- repeated runs of the same entity within one parent trace\n * surface as separate rows.\n */\nexport const listBranchesResponseSchema = z.object({\n  pagination: paginationInfoSchema.optional(),\n  delta: deltaInfoSchema.optional(),\n  deltaCursor: deltaCursorSchema.optional(),\n  branches: z.array(traceSpanSchema),\n});\n\n/** Response containing paginated branch anchor spans with computed status. Branch delta mode returns only new branch rows. */\nexport type ListBranchesResponse = z.infer<typeof listBranchesResponseSchema>;\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 { 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';\nexport const TABLE_FAVORITES = 'mastra_favorites';\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';\nexport const TABLE_BACKGROUND_TASKS = 'mastra_background_tasks';\n\n// Schedules tables\nexport const TABLE_SCHEDULES = 'mastra_schedules';\nexport const TABLE_SCHEDULE_TRIGGERS = 'mastra_schedule_triggers';\n\n// Static workflow definitions (chat-built / studio-saved workflows)\nexport const TABLE_WORKFLOW_DEFINITIONS = 'mastra_workflow_definitions';\n\n// Channel tables\nexport const TABLE_CHANNEL_INSTALLATIONS = 'mastra_channel_installations';\nexport const TABLE_CHANNEL_CONFIG = 'mastra_channel_config';\n\n// Tool provider connections\nexport const TABLE_TOOL_PROVIDER_CONNECTIONS = 'mastra_tool_provider_connections';\n\n// Notifications\nexport const TABLE_NOTIFICATIONS = 'mastra_notifications';\n\n// Harness sessions\nexport const TABLE_HARNESS_SESSIONS = 'mastra_harness_sessions';\n\n// Thread state (per-thread, per-type durable state; e.g. the task list)\nexport const TABLE_THREAD_STATE = 'mastra_thread_state';\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  | typeof TABLE_BACKGROUND_TASKS\n  | typeof TABLE_FAVORITES\n  | typeof TABLE_SCHEDULES\n  | typeof TABLE_SCHEDULE_TRIGGERS\n  | typeof TABLE_CHANNEL_INSTALLATIONS\n  | typeof TABLE_CHANNEL_CONFIG\n  | typeof TABLE_TOOL_PROVIDER_CONNECTIONS\n  | typeof TABLE_NOTIFICATIONS\n  | typeof TABLE_HARNESS_SESSIONS\n  | typeof TABLE_THREAD_STATE\n  | typeof TABLE_WORKFLOW_DEFINITIONS;\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  organizationId: { type: 'text', nullable: true },\n  projectId: { type: 'text', nullable: true },\n  // Batch handle: groups all per-trace scores produced by one batch scoring call.\n  // Each score keeps its own per-execution `runId`; `batchId` is shared across the batch.\n  batchId: { type: 'text', nullable: true },\n  // Dataset provenance: which curated dataset item this score was produced against.\n  // Lets baseline scores join back to dataset items (ground truth) without re-running.\n  datasetId: { type: 'text', nullable: true },\n  datasetItemId: { 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  visibility: { type: 'text', nullable: true }, // 'private' | 'public' | null (legacy)\n  metadata: { type: 'jsonb', nullable: true }, // Additional metadata for the agent\n  favoriteCount: { type: 'integer', nullable: true }, // Denormalised count of favorites for this 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  toolProviders: { 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  browser: { type: 'jsonb', 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  organizationId: { type: 'text', nullable: true },\n  projectId: { 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 WORKFLOW_DEFINITIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  description: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  inputSchema: { type: 'jsonb', nullable: false },\n  outputSchema: { type: 'jsonb', nullable: false },\n  stateSchema: { type: 'jsonb', nullable: true },\n  requestContextSchema: { type: 'jsonb', nullable: true },\n  graph: { type: 'jsonb', nullable: false },\n  status: { type: 'text', nullable: false }, // 'active' | 'archived'\n  source: { type: 'text', nullable: false }, // always 'storage' for now\n  authorId: { type: 'text', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { 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  visibility: { type: 'text', nullable: true }, // 'private' | 'public' | null (legacy)\n  favoriteCount: { type: 'integer', nullable: true }, // Denormalised count of favorites for this skill\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const FAVORITES_SCHEMA: Record<string, StorageColumn> = {\n  userId: { type: 'text', nullable: false },\n  entityType: { type: 'text', nullable: false }, // 'agent' | 'skill'\n  entityId: { type: 'text', nullable: false },\n  createdAt: { type: 'timestamp', nullable: false },\n};\n\n/**\n * Per-author registry of authorized tool provider connections. Stores a stable\n * user-supplied label across agents. Composite primary key on\n * (authorId, providerId, connectionId). `scope` buckets identity:\n * 'per-author' (default), 'shared' (visible to all callers), or\n * 'caller-supplied' (authorId is a host-app end-user id forwarded via request\n * context).\n */\nexport const TOOL_PROVIDER_CONNECTIONS_SCHEMA: Record<string, StorageColumn> = {\n  authorId: { type: 'text', nullable: false },\n  providerId: { type: 'text', nullable: false },\n  connectionId: { type: 'text', nullable: false },\n  toolkit: { type: 'text', nullable: false },\n  label: { type: 'text', nullable: true },\n  scope: { type: 'text', nullable: false },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n};\n\nexport const NOTIFICATIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false },\n  threadId: { type: 'text', nullable: false },\n  source: { type: 'text', nullable: false },\n  kind: { type: 'text', nullable: false },\n  priority: { type: 'text', nullable: false },\n  status: { type: 'text', nullable: false },\n  summary: { type: 'text', nullable: false },\n  payload: { type: 'jsonb', nullable: true },\n  resourceId: { type: 'text', nullable: true },\n  agentId: { type: 'text', nullable: true },\n  sourceId: { type: 'text', nullable: true },\n  dedupeKey: { type: 'text', nullable: true },\n  coalesceKey: { type: 'text', nullable: true },\n  coalescedCount: { type: 'integer', nullable: false },\n  attributes: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  updatedAt: { type: 'timestamp', nullable: false },\n  deliveredAt: { type: 'timestamp', nullable: true },\n  seenAt: { type: 'timestamp', nullable: true },\n  dismissedAt: { type: 'timestamp', nullable: true },\n  archivedAt: { type: 'timestamp', nullable: true },\n  discardedAt: { type: 'timestamp', nullable: true },\n  deliverAt: { type: 'timestamp', nullable: true },\n  summaryAt: { type: 'timestamp', nullable: true },\n  deliveryReason: { type: 'text', nullable: true },\n  deliveryAttempts: { type: 'integer', nullable: false },\n  lastDeliveryAttemptAt: { type: 'timestamp', nullable: true },\n  lastDeliveryError: { type: 'text', nullable: true },\n  deliveredSignalId: { type: 'text', nullable: true },\n  summarySignalId: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n};\n\nexport const HARNESS_SESSIONS_SCHEMA: Record<string, StorageColumn> = {\n  id: { type: 'text', nullable: false, primaryKey: true },\n  ownerId: { type: 'text', nullable: false },\n  resourceId: { type: 'text', nullable: false },\n  threadId: { type: 'text', nullable: false },\n  parentSessionId: { type: 'text', nullable: true },\n  subagentDepth: { type: 'integer', nullable: true },\n  source: { type: 'jsonb', nullable: true },\n  origin: { type: 'text', nullable: false },\n  runtimeCompatibilityGeneration: { type: 'text', nullable: true },\n  modeId: { type: 'text', nullable: false },\n  modelId: { type: 'text', nullable: false },\n  title: { type: 'text', nullable: true },\n  metadata: { type: 'jsonb', nullable: true },\n  state: { type: 'jsonb', nullable: true },\n  pending: { type: 'jsonb', nullable: true },\n  createdAt: { type: 'timestamp', nullable: false },\n  lastActivityAt: { type: 'timestamp', nullable: false },\n  closingAt: { type: 'timestamp', nullable: true },\n  closeDeadlineAt: { type: 'timestamp', nullable: true },\n  closedAt: { type: 'timestamp', nullable: true },\n  deletedAt: { type: 'timestamp', nullable: true },\n};\n\nexport const THREAD_STATE_SCHEMA: Record<string, StorageColumn> = {\n  threadId: { type: 'text', nullable: false },\n  type: { type: 'text', nullable: false },\n  value: { type: 'jsonb', nullable: false },\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  files: { 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  organizationId: { type: 'text', nullable: true },\n  projectId: { type: 'text', nullable: true },\n  candidateKey: { type: 'text', nullable: true },\n  candidateId: { type: 'text', 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  externalId: { type: 'text', nullable: true },\n  organizationId: { type: 'text', nullable: true },\n  projectId: { type: 'text', nullable: true },\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  toolMocks: { type: 'jsonb', nullable: true },\n  unmockedToolPolicy: { type: 'text', nullable: true },\n  scorerIds: { 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  organizationId: { type: 'text', nullable: true },\n  projectId: { 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  comment: { type: 'text', nullable: true },\n  toolMockReport: { type: 'jsonb', nullable: true },\n  organizationId: { type: 'text', nullable: true },\n  projectId: { type: 'text', 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  [TABLE_FAVORITES]: FAVORITES_SCHEMA,\n  [TABLE_BACKGROUND_TASKS]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    tool_call_id: { type: 'text', nullable: false },\n    tool_name: { type: 'text', nullable: false },\n    agent_id: { type: 'text', nullable: false },\n    run_id: { type: 'text', nullable: false },\n    thread_id: { type: 'text', nullable: true },\n    resource_id: { type: 'text', nullable: true },\n    status: { type: 'text', nullable: false },\n    args: { type: 'jsonb', nullable: false },\n    result: { type: 'jsonb', nullable: true },\n    error: { type: 'jsonb', nullable: true },\n    suspend_payload: { type: 'jsonb', nullable: true },\n    retry_count: { type: 'integer', nullable: false },\n    max_retries: { type: 'integer', nullable: false },\n    timeout_ms: { type: 'integer', nullable: false },\n    createdAt: { type: 'timestamp', nullable: false },\n    startedAt: { type: 'timestamp', nullable: true },\n    suspendedAt: { type: 'timestamp', nullable: true },\n    completedAt: { type: 'timestamp', nullable: true },\n  },\n  [TABLE_SCHEDULES]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    target: { type: 'jsonb', nullable: false },\n    cron: { type: 'text', nullable: false },\n    timezone: { type: 'text', nullable: true },\n    status: { type: 'text', nullable: false },\n    next_fire_at: { type: 'bigint', nullable: false },\n    last_fire_at: { type: 'bigint', nullable: true },\n    last_run_id: { type: 'text', nullable: true },\n    created_at: { type: 'bigint', nullable: false },\n    updated_at: { type: 'bigint', nullable: false },\n    metadata: { type: 'jsonb', nullable: true },\n    owner_type: { type: 'text', nullable: true },\n    owner_id: { type: 'text', nullable: true },\n  },\n  [TABLE_SCHEDULE_TRIGGERS]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    schedule_id: { type: 'text', nullable: false },\n    run_id: { type: 'text', nullable: true },\n    scheduled_fire_at: { type: 'bigint', nullable: false },\n    actual_fire_at: { type: 'bigint', nullable: false },\n    outcome: { type: 'text', nullable: false },\n    error: { type: 'text', nullable: true },\n    trigger_kind: { type: 'text', nullable: false },\n    parent_trigger_id: { type: 'text', nullable: true },\n    metadata: { type: 'jsonb', nullable: true },\n  },\n  [TABLE_CHANNEL_INSTALLATIONS]: {\n    id: { type: 'text', nullable: false, primaryKey: true },\n    platform: { type: 'text', nullable: false },\n    agentId: { type: 'text', nullable: false },\n    status: { type: 'text', nullable: false },\n    webhookId: { type: 'text', nullable: true },\n    data: { type: 'jsonb', nullable: false },\n    configHash: { type: 'text', nullable: true },\n    error: { type: 'text', nullable: true },\n    createdAt: { type: 'timestamp', nullable: false },\n    updatedAt: { type: 'timestamp', nullable: false },\n  },\n  [TABLE_CHANNEL_CONFIG]: {\n    platform: { type: 'text', nullable: false, primaryKey: true },\n    data: { type: 'jsonb', nullable: false },\n    updatedAt: { type: 'timestamp', nullable: false },\n  },\n  [TABLE_TOOL_PROVIDER_CONNECTIONS]: TOOL_PROVIDER_CONNECTIONS_SCHEMA,\n  [TABLE_NOTIFICATIONS]: NOTIFICATIONS_SCHEMA,\n  [TABLE_HARNESS_SESSIONS]: HARNESS_SESSIONS_SCHEMA,\n  [TABLE_THREAD_STATE]: THREAD_STATE_SCHEMA,\n  [TABLE_WORKFLOW_DEFINITIONS]: WORKFLOW_DEFINITIONS_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  [TABLE_FAVORITES]: { columns: FAVORITES_SCHEMA, compositePrimaryKey: ['userId', 'entityType', 'entityId'] },\n  [TABLE_TOOL_PROVIDER_CONNECTIONS]: {\n    columns: TOOL_PROVIDER_CONNECTIONS_SCHEMA,\n    compositePrimaryKey: ['authorId', 'providerId', 'connectionId'],\n  },\n  [TABLE_NOTIFICATIONS]: { columns: NOTIFICATIONS_SCHEMA, compositePrimaryKey: ['threadId', 'id'] },\n  [TABLE_THREAD_STATE]: { columns: THREAD_STATE_SCHEMA, compositePrimaryKey: ['threadId', 'type'] },\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"],"mappings":";;;;;AAmBA,MAAa,sBAAsBA,OAAAA,EAAE,KAAK,CAAC,QAAQ,MAAM,CAAC;AAI1D,MAAa,0BAA0BA,OAAAA,EAAE,KAAK;CAC5C;CACA;CACA;CACA;CACA,GAAG,OAAO,OAAOC,gBAAAA,QAAQ;AAC3B,CAAkC;AAQlC,MAAa,uBAAuBD,OAAAA,EAAE,OAAO;CAC3C,aAAaA,OAAAA,EAAE,OAAO;CACtB,QAAQA,OAAAA,EAAE,OAAO;AACnB,CAAC;;AASD,MAAM,eAAeA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC;;AAGrD,MAAM,uBAAuB,aAAa,SAAS;AAMnD,MAAa,qBAAqBA,OAAAA,EAAE,OAAO;CACzC,OAAOA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,OAAOA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC5B,QAAQA,OAAAA,EAAE,QAAQ;CAClB,mBAAmB;CACnB,gBAAgB;AAGlB,CAAC;AAQD,MAAa,yBAAyBA,OAAAA,EAAE,OAAO;CAC7C,OAAOA,OAAAA,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,QAAQ;CACR,OAAOA,OAAAA,EAAE,QAAQ;CACjB,QAAQA,OAAAA,EAAE,QAAQ;CAClB,UAAU;CACV,mBAAmB;CACnB,QAAQ;CACR,QAAQ;CACR,YAAY;CACZ,gBAAgB;CAChB,kBAAkBA,OAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CACvC,SA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