{"version":3,"file":"storage-DBpVHkrA.cjs","names":["StorageDomain","#storage","#domains","#readyDomains","#domainErrors","#domainInitPromises","#ensureStorageReady","#initDomain","#storageReady","#storageInitPromise","StorageDomain","MastraError","ErrorDomain","ErrorCategory","getBranchArgsSchema","extractBranchSpans","SAFE_METADATA_KEY_PATTERN","MAX_METADATA_KEY_LENGTH","DISALLOWED_METADATA_KEYS","TABLE_SCHEMAS","TABLE_SCORERS","coreFeatures","MastraError","ErrorDomain","ErrorCategory","BRANCH_SPAN_TYPE_SET","listTracesArgsSchema","toTraceSpans","listBranchesArgsSchema","toTraceSpan","listMetricsArgsSchema","EntityType","listLogsArgsSchema","listScoresArgsSchema","listFeedbackArgsSchema","EntityType","StorageDomain","MastraBase","#blobs","StorageDomain","#installations","#configs","z","MastraError","MastraError","StorageDomain","MastraError","ErrorDomain","ErrorCategory","createDatasetItemBatchPlan","matchesTenancy","normalizePerPage","calculatePagination","StorageDomain","normalizePerPage","calculatePagination","StorageDomain","#sessions","StorageDomain","normalizePerPage","calculatePagination","MessageList","StorageDomain","StorageDomain","MastraError","ErrorDomain","ErrorCategory","normalizePerPage","calculatePagination","MastraBase","StorageDomain","StorageDomain","normalizePerPage","MastraCompositeStore","#db","InMemoryDB","InMemoryAgentsStorage","InMemoryNotificationsStorage","InMemoryPromptBlocksStorage","InMemoryScorerDefinitionsStorage","InMemoryMCPClientsStorage","InMemoryMCPServersStorage","InMemoryWorkspacesStorage","InMemorySkillsStorage","InMemoryFavoritesStorage","InMemoryThreadStateStorage","sep","MastraCompositeStore","#dir","#db","FilesystemAgentsStorage","FilesystemPromptBlocksStorage","FilesystemScorerDefinitionsStorage","FilesystemMCPClientsStorage","FilesystemMCPServersStorage","FilesystemWorkspacesStorage","FilesystemSkillsStorage","MastraBase","MastraError","ErrorDomain","ErrorCategory"],"sources":["../src/storage/factory-storage.ts","../src/storage/domains/observability/base.ts","../src/storage/utils.ts","../src/storage/domains/observability/inmemory.ts","../src/storage/domains/observability/record-builders.ts","../src/storage/domains/background-tasks/base.ts","../src/storage/domains/background-tasks/inmemory.ts","../src/storage/domains/blobs/base.ts","../src/storage/domains/blobs/inmemory.ts","../src/storage/domains/channels/base.ts","../src/storage/domains/channels/inmemory.ts","../src/datasets/validation/errors.ts","../src/datasets/validation/validator.ts","../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/fast-deep-equal/3.1.3/57fbe5fd6f7d3bd61519466ad102884cc9e5511fabd9777317b6582805433878/node_modules/fast-deep-equal/index.js","../src/storage/domains/datasets/identity.ts","../src/storage/domains/datasets/serialization.ts","../src/storage/domains/datasets/base.ts","../src/storage/domains/datasets/inmemory.ts","../src/storage/domains/experiments/base.ts","../src/storage/domains/experiments/inmemory.ts","../src/storage/domains/harness/base.ts","../src/storage/domains/harness/inmemory.ts","../src/storage/domains/memory/base.ts","../src/storage/domains/memory/inmemory.ts","../src/storage/domains/schedules/base.ts","../src/storage/domains/schedules/inmemory.ts","../src/storage/domains/scores/base.ts","../src/storage/domains/scores/inmemory.ts","../src/storage/domains/tool-provider-connections/base.ts","../src/storage/domains/tool-provider-connections/inmemory.ts","../src/storage/domains/workflow-definitions/base.ts","../src/storage/domains/workflow-definitions/inmemory.ts","../src/storage/workflow-snapshot.ts","../src/storage/domains/workflows/base.ts","../src/storage/domains/workflows/inmemory.ts","../src/storage/mock.ts","../src/storage/filesystem-db.ts","../src/storage/filesystem.ts","../src/storage/providers/github.ts","../src/storage/domains/operations/base.ts","../src/storage/domains/operations/inmemory.ts"],"sourcesContent":["/**\n * FactoryStorage — a pluggable application-storage backend contract.\n *\n * One `FactoryStorage` instance powers both sides of an application\n * deployment's persistence:\n *\n * - **Agent state** (threads, messages, memory, observational memory) via\n *   {@link FactoryStorage.getMastraStorage}, which callers feed to the\n *   Mastra instance and all agent-related wiring.\n * - **App tables** (application-owned collections: settings, audit trails,\n *   work items, integration state, ...) via the generic\n *   {@link FactoryStorageOps} query surface plus declarative\n *   {@link CollectionSchema} DDL mapping.\n *\n * App-table domains are written once against `ops`; backends implement the\n * small query surface once (M + N, not M × N). Nothing outside a backend\n * implementation may branch on the database dialect — optional capabilities\n * such as {@link FactoryStorage.authDatabase} are feature-gated on presence.\n *\n * Contract discipline: the ops surface is deliberately small — equality-filter\n * CRUD, conflict-key upsert, ordered/limit/keyset-cursor lists, and atomic\n * read-modify-write. Anything not expressible here is a deliberate, reviewed\n * contract extension — never raw SQL from a domain.\n *\n * Store packages (`@mastra/pg`, `@mastra/libsql`) ship implementations next\n * to their `MastraCompositeStore` adapters, sharing one connection between\n * agent state and app tables.\n */\n\nimport type { MastraCompositeStore } from './base';\nimport { StorageDomain } from './domains/base';\n\n/** Values storable in (and filterable on) a collection column. */\nexport type CollectionValue = string | number | boolean | Date | null;\n\n/**\n * Row filter: column → required value. Multiple entries AND together.\n * - A {@link CollectionValue} matches by equality; `null` matches SQL `IS NULL`.\n * - `{ in: [...] }` matches any of the listed values (SQL `IN`).\n * - `{}` matches every row.\n *\n * Column names must be declared in the collection's schema — backends reject\n * unknown collections/columns instead of interpolating them.\n */\nexport type CollectionWhere = Record<string, CollectionValue | { in: CollectionValue[] }>;\n\n/**\n * Keyset cursor for stable pagination: the `orderBy` column values of the\n * last row of the previous page, in the same order as `orderBy`. The next\n * page contains rows strictly after that position in the sort order.\n */\nexport interface CollectionCursor {\n  values: CollectionValue[];\n}\n\nexport interface CollectionListOptions {\n  /** Sort order; required when `cursor` is set. */\n  orderBy?: [column: string, dir: 'asc' | 'desc'][];\n  limit?: number;\n  /** Keyset cursor over the `orderBy` columns (see {@link CollectionCursor}). */\n  cursor?: CollectionCursor;\n}\n\n/**\n * Closed column-type union, mapped to backend-native types.\n *\n * `uuid-pk` declares the collection's generated primary key: the ops layer\n * assigns a UUID client-side on insert when the caller doesn't provide one,\n * so every backend produces identical rows. A collection may instead mark one\n * caller-supplied column with `primaryKey: true` (natural keys, e.g. a\n * session id).\n *\n * Value normalization is part of the contract regardless of dialect:\n * `timestamp` columns round-trip as `Date`, `json` as parsed values,\n * `boolean` as booleans, and `bigint` as JS numbers (safe integers — e.g.\n * GitHub ids fit well inside 2^53).\n */\nexport type CollectionColumnType = 'text' | 'bigint' | 'integer' | 'boolean' | 'json' | 'timestamp' | 'uuid-pk';\n\nexport interface CollectionColumnSpec {\n  type: CollectionColumnType;\n  /** Columns are NOT NULL unless marked nullable. */\n  nullable?: boolean;\n  /**\n   * Natural primary key (caller-supplied on insert). Mutually exclusive with\n   * a `uuid-pk` column; exactly one primary key per collection.\n   */\n  primaryKey?: boolean;\n  /**\n   * DDL-level default literal. Required when additively introducing a\n   * NOT NULL column to a collection that may already have rows (e.g.\n   * `actor_type text NOT NULL DEFAULT 'human'`).\n   */\n  default?: string | number | boolean;\n}\n\n/**\n * Unique index. The optional partial forms cover the two shapes app schemas\n * need: `whereNotNull` (unique per non-null natural key) and `whereNull`\n * (unique per scope where an owner column is absent).\n */\nexport interface CollectionUniqueIndexSpec {\n  name: string;\n  columns: string[];\n  /** Index only rows where this column IS NOT NULL. */\n  whereNotNull?: string;\n  /** Index only rows where this column IS NULL. */\n  whereNull?: string;\n}\n\nexport interface CollectionIndexSpec {\n  name: string;\n  columns: string[];\n}\n\n/**\n * Declarative collection definition, mapped to backend DDL by\n * {@link FactoryStorage.ensureCollections}. Evolution is additive only:\n * re-running with new columns/indexes adds them; nothing is dropped or\n * retyped.\n */\nexport interface CollectionSchema {\n  name: string;\n  /** Column name → spec. Rows returned by ops are keyed by these names. */\n  columns: Record<string, CollectionColumnSpec>;\n  uniqueIndexes?: CollectionUniqueIndexSpec[];\n  indexes?: CollectionIndexSpec[];\n}\n\n/**\n * Tagged database handle for auth libraries (e.g. better-auth). Consumers\n * narrow on `dialect` to build their driver adapter — a supported contract,\n * unlike sniffing store internals. `custom` passes an adapter/instance the\n * auth library accepts as-is.\n */\nexport type FactoryAuthDatabase =\n  | { dialect: 'postgres'; pool: unknown }\n  | { dialect: 'libsql'; client: unknown }\n  | { dialect: 'custom'; database: unknown };\n\n/**\n * Thrown by `insertOne`/`upsertOne` when a unique constraint rejects the row.\n * Backends map their native duplicate-key errors onto this type so domains\n * can implement insert-or-recover races portably.\n */\nexport class UniqueViolationError extends Error {\n  readonly collection: string;\n\n  constructor(collection: string, options?: { cause?: unknown }) {\n    super(`Unique constraint violation on collection '${collection}'`, options);\n    this.name = 'UniqueViolationError';\n    this.collection = collection;\n  }\n}\n\n/**\n * The generic query surface app-table domains are written against.\n *\n * Rows (`T`) are plain objects keyed by schema column names; domains own any\n * mapping to their public camelCase shapes. All methods throw if the\n * collection (or any referenced column) was not registered via\n * `ensureCollections`.\n */\nexport interface FactoryStorageOps {\n  findOne<T extends Record<string, unknown>>(collection: string, where: CollectionWhere): Promise<T | null>;\n\n  findMany<T extends Record<string, unknown>>(\n    collection: string,\n    where: CollectionWhere,\n    opts?: CollectionListOptions,\n  ): Promise<T[]>;\n\n  /**\n   * Insert one row, returning it (with the generated `uuid-pk` populated).\n   * Throws {@link UniqueViolationError} on any unique-constraint conflict.\n   */\n  insertOne<T extends Record<string, unknown>>(collection: string, row: Partial<T>): Promise<T>;\n\n  /**\n   * Insert, or update the existing row that matches `conflictKeys` (which\n   * must be covered by a unique index). Non-key columns present in `row`\n   * replace the stored values; the existing primary key is preserved.\n   */\n  upsertOne<T extends Record<string, unknown>>(collection: string, conflictKeys: string[], row: Partial<T>): Promise<T>;\n\n  /** Set columns on every matching row. Returns the number of rows updated. */\n  updateMany(collection: string, where: CollectionWhere, set: Record<string, unknown>): Promise<number>;\n\n  /** Delete every matching row. Returns the number of rows deleted. */\n  deleteMany(collection: string, where: CollectionWhere): Promise<number>;\n\n  /**\n   * Atomic read-modify-write of one matching row. `fn` receives the current\n   * row and returns the columns to set — or `null` to abort without writing\n   * (the unmodified row is returned; use a closure flag to distinguish abort\n   * from success). Returns `null` when no row matches.\n   *\n   * Isolation: pg runs `fn` inside a `SELECT ... FOR UPDATE` transaction;\n   * libsql serializes through its single-writer path. Either way, concurrent\n   * `updateAtomic` calls on the same row never lose each other's writes.\n   */\n  updateAtomic<T extends Record<string, unknown>>(\n    collection: string,\n    where: CollectionWhere,\n    fn: (row: T) => Partial<T> | null | Promise<Partial<T> | null>,\n  ): Promise<T | null>;\n}\n\n/**\n * Base class for application domains owned by a {@link FactoryStorage}.\n * Domains are bound once when registered and share their owner's connection.\n */\nexport abstract class FactoryStorageDomain extends StorageDomain {\n  override readonly name: string;\n  #storage?: FactoryStorage;\n\n  protected constructor(name: string) {\n    if (!name.trim()) {\n      throw new Error('Factory storage domain name must not be empty');\n    }\n    super({ component: 'STORAGE', name });\n    this.name = name;\n  }\n\n  /** @internal Bound by {@link FactoryStorage.registerDomain}. */\n  __bindFactoryStorage(storage: FactoryStorage): void {\n    if (this.#storage && this.#storage !== storage) {\n      throw new Error(`Factory storage domain '${this.name}' is already bound to another storage instance`);\n    }\n    this.#storage = storage;\n  }\n\n  protected get storage(): FactoryStorage {\n    if (!this.#storage) {\n      throw new Error(`Factory storage domain '${this.name}' has not been registered`);\n    }\n    return this.#storage;\n  }\n\n  /**\n   * Initialize this domain (via its owning storage) if it hasn't been yet.\n   * Lets consumers holding a domain handle run the same fail-soft readiness\n   * check as {@link FactoryStorage.ensureDomainReady} without also needing a\n   * reference to the storage backend.\n   */\n  ensureReady(): Promise<void> {\n    return this.storage.ensureDomainReady(this.name);\n  }\n\n  protected get ops(): FactoryStorageOps {\n    return this.storage.ops;\n  }\n\n  protected ensureCollections(schemas: CollectionSchema[]): Promise<void> {\n    return this.storage.ensureCollections(schemas);\n  }\n}\n\n/**\n * A pluggable application-storage backend: one database powering agent state\n * (via {@link getMastraStorage}) and app-owned collections (via {@link ops}).\n */\nexport abstract class FactoryStorage {\n  readonly #domains = new Map<string, FactoryStorageDomain>();\n  readonly #readyDomains = new Set<string>();\n  readonly #domainErrors = new Map<string, unknown>();\n  readonly #domainInitPromises = new Map<string, Promise<void>>();\n  #storageReady = false;\n  #storageInitPromise?: Promise<void>;\n\n  /**\n   * Agent-state store (threads, messages, memory, OM) for this database,\n   * sharing this backend's connection. Callers pass the result to the Mastra\n   * instance and all agent-related wiring. Lazily constructed; returns the\n   * same instance on repeat calls.\n   */\n  abstract getMastraStorage(): MastraCompositeStore;\n\n  /** Open/validate the backend, then initialize registered domains fail-soft. */\n  async init(): Promise<void> {\n    await this.#ensureStorageReady();\n    await Promise.all([...this.#domains.keys()].map(name => this.#initDomain(name).catch(() => undefined)));\n  }\n\n  /** Backend-specific connection initialization. */\n  protected abstract initStorage(): Promise<void>;\n\n  registerDomain<T extends FactoryStorageDomain>(domain: T): T {\n    if (this.#domains.has(domain.name)) {\n      throw new Error(`Factory storage domain '${domain.name}' is already registered`);\n    }\n    domain.__bindFactoryStorage(this);\n    this.#domains.set(domain.name, domain);\n    return domain;\n  }\n\n  getDomain<T extends FactoryStorageDomain = FactoryStorageDomain>(name: string): T {\n    const domain = this.#domains.get(name);\n    if (!domain) {\n      throw new Error(`Factory storage domain '${name}' is not registered`);\n    }\n    return domain as T;\n  }\n\n  hasDomain(name: string): boolean {\n    return this.#domains.has(name);\n  }\n\n  domainNames(): string[] {\n    return [...this.#domains.keys()];\n  }\n\n  isDomainReady(name: string): boolean {\n    return this.#readyDomains.has(name);\n  }\n\n  domainInitError(name: string): unknown {\n    return this.#domainErrors.get(name);\n  }\n\n  async ensureDomainReady(name: string): Promise<void> {\n    this.getDomain(name);\n    await this.#ensureStorageReady();\n    await this.#initDomain(name);\n  }\n\n  /**\n   * Map each domain's declarative schema to backend DDL. Idempotent and\n   * additive: safe to re-run, never drops or retypes anything. Registers the\n   * schemas so `ops` can validate identifiers and normalize values.\n   */\n  abstract ensureCollections(schemas: CollectionSchema[]): Promise<void>;\n\n  /** The generic query surface domains are written against. */\n  abstract readonly ops: FactoryStorageOps;\n\n  /**\n   * Run a group of app-table operations atomically. The callback receives an\n   * ops instance bound to the transaction; callers must not use `this.ops`\n   * inside it. Serializable callbacks may be retried after a serialization\n   * failure and therefore must contain database operations only.\n   */\n  abstract withTransaction<T>(\n    fn: (ops: FactoryStorageOps) => Promise<T>,\n    options?: { isolationLevel?: 'serializable' },\n  ): Promise<T>;\n\n  /** Release the backend's connections (tests, shutdown). */\n  abstract close(): Promise<void>;\n\n  // ---- optional capabilities (feature-gate on presence, never on dialect) ----\n\n  /**\n   * A tagged database handle auth libraries can consume (see\n   * {@link FactoryAuthDatabase}). Absent → auth integrations require a\n   * user-provided instance.\n   */\n  authDatabase?(): FactoryAuthDatabase;\n\n  async #ensureStorageReady(): Promise<void> {\n    if (this.#storageReady) return;\n    if (this.#storageInitPromise) return this.#storageInitPromise;\n\n    const initPromise = (async () => {\n      await this.initStorage();\n      this.#storageReady = true;\n    })();\n    this.#storageInitPromise = initPromise;\n\n    try {\n      await initPromise;\n    } finally {\n      if (this.#storageInitPromise === initPromise) {\n        this.#storageInitPromise = undefined;\n      }\n    }\n  }\n\n  #initDomain(name: string): Promise<void> {\n    if (this.#readyDomains.has(name)) return Promise.resolve();\n    const pending = this.#domainInitPromises.get(name);\n    if (pending) return pending;\n\n    const domain = this.getDomain(name);\n    this.#domainErrors.delete(name);\n    const initPromise = (async () => {\n      try {\n        await domain.init();\n        this.#readyDomains.add(name);\n      } catch (error) {\n        this.#domainErrors.set(name, error);\n        throw error;\n      } finally {\n        this.#domainInitPromises.delete(name);\n      }\n    })();\n    this.#domainInitPromises.set(name, initPromise);\n    return initPromise;\n  }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\nimport { StorageDomain } from '../base';\nimport type {\n  GetEntityTypesArgs,\n  GetEntityTypesResponse,\n  GetEntityNamesArgs,\n  GetEntityNamesResponse,\n  GetServiceNamesArgs,\n  GetServiceNamesResponse,\n  GetEnvironmentsArgs,\n  GetEnvironmentsResponse,\n  GetTagsArgs,\n  GetTagsResponse,\n  GetMetricNamesArgs,\n  GetMetricNamesResponse,\n  GetMetricLabelKeysArgs,\n  GetMetricLabelKeysResponse,\n  GetMetricLabelValuesArgs,\n  GetMetricLabelValuesResponse,\n} from './discovery';\nimport type {\n  BatchCreateFeedbackArgs,\n  CreateFeedbackArgs,\n  ListFeedbackArgs,\n  ListFeedbackResponse,\n  GetFeedbackAggregateArgs,\n  GetFeedbackAggregateResponse,\n  GetFeedbackBreakdownArgs,\n  GetFeedbackBreakdownResponse,\n  GetFeedbackTimeSeriesArgs,\n  GetFeedbackTimeSeriesResponse,\n  GetFeedbackPercentilesArgs,\n  GetFeedbackPercentilesResponse,\n} from './feedback';\nimport type { BatchCreateLogsArgs, ListLogsArgs, ListLogsResponse } from './logs';\nimport type {\n  BatchCreateMetricsArgs,\n  ListMetricsArgs,\n  ListMetricsResponse,\n  GetMetricAggregateArgs,\n  GetMetricAggregateResponse,\n  GetMetricBreakdownArgs,\n  GetMetricBreakdownResponse,\n  GetMetricTimeSeriesArgs,\n  GetMetricTimeSeriesResponse,\n  GetMetricPercentilesArgs,\n  GetMetricPercentilesResponse,\n} from './metrics';\nimport type {\n  BatchCreateScoresArgs,\n  CreateScoreArgs,\n  ListScoresArgs,\n  ListScoresResponse,\n  ScoreRecord,\n  GetScoreAggregateArgs,\n  GetScoreAggregateResponse,\n  GetScoreBreakdownArgs,\n  GetScoreBreakdownResponse,\n  GetScoreTimeSeriesArgs,\n  GetScoreTimeSeriesResponse,\n  GetScorePercentilesArgs,\n  GetScorePercentilesResponse,\n} from './scores';\nimport type {\n  BatchCreateSpansArgs,\n  BatchDeleteTracesArgs,\n  BatchUpdateSpansArgs,\n  CreateSpanArgs,\n  GetBranchArgs,\n  GetBranchResponse,\n  GetRootSpanArgs,\n  GetRootSpanResponse,\n  GetSpanArgs,\n  GetSpanResponse,\n  GetSpansArgs,\n  GetSpansResponse,\n  GetStructureResponse,\n  GetTraceArgs,\n  GetTraceResponse,\n  GetTraceLightResponse,\n  ListBranchesArgs,\n  ListBranchesResponse,\n  ListTracesArgs,\n  ListTracesLightResponse,\n  ListTracesResponse,\n  UpdateSpanArgs,\n} from './tracing';\nimport { extractBranchSpans, getBranchArgsSchema } from './tracing';\nimport type { ObservabilityStorageStrategy, TracingStorageStrategy } from './types';\n\nexport type ObservabilityStorageFeature = 'delta-polling' | 'metrics' | 'logs';\n\n/**\n * Base storage class for observability data (traces, metrics, logs, scores, feedback).\n * Not abstract -- provides default implementations that throw \"not implemented\" errors.\n * Storage adapters override only the methods they support.\n */\nexport class ObservabilityStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'OBSERVABILITY',\n    });\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    // Default no-op - subclasses override\n  }\n\n  /**\n   * Provides hints for tracing strategy selection by the MastraStorageExporter.\n   * Storage adapters can override this to specify their preferred and supported strategies.\n   */\n  public get observabilityStrategy(): {\n    preferred: ObservabilityStorageStrategy;\n    supported: ObservabilityStorageStrategy[];\n  } {\n    return {\n      preferred: 'batch-with-updates', // Default for most SQL stores\n      supported: ['realtime', 'batch-with-updates', 'insert-only'],\n    };\n  }\n\n  /**\n   * Provides hints for tracing strategy selection by the MastraStorageExporter.\n   * Storage adapters can override this to specify their preferred and supported strategies.\n   * @deprecated Use {@link observabilityStrategy} instead.\n   * @see {@link observabilityStrategy} for the replacement property.\n   */\n  public get tracingStrategy(): {\n    preferred: TracingStorageStrategy;\n    supported: TracingStorageStrategy[];\n  } {\n    return this.observabilityStrategy;\n  }\n\n  /**\n   * Reports the tracing strategy currently in effect for this attached observability store.\n   *\n   * Single-strategy stores can rely on the default implementation. Multi-strategy stores\n   * should override this getter only when they can determine the actual configured mode\n   * from storage-owned configuration, not exporter state.\n   */\n  public get runtimeTracingStrategy(): TracingStorageStrategy | undefined {\n    const supportedStrategies = this.observabilityStrategy.supported;\n    return supportedStrategies.length === 1 ? supportedStrategies[0] : undefined;\n  }\n\n  /**\n   * Optional feature list for observability storage APIs.\n   * Stores should override this to opt in to the APIs they support explicitly.\n   * Older stores and older package versions will simply omit it, which keeps page mode working.\n   */\n  public getFeatures(): readonly ObservabilityStorageFeature[] | undefined {\n    return undefined;\n  }\n\n  /**\n   * Creates a single Span record in the storage provider.\n   */\n  async createSpan(_args: CreateSpanArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_CREATE_SPAN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support creating spans',\n    });\n  }\n\n  /**\n   * Updates a single Span with partial data. Primarily used for realtime trace creation.\n   *\n   * @deprecated This method only works with stores that support span updates,\n   * It will be removed in the future. Instead try to add all data to a span before\n   * ending it.\n   */\n  async updateSpan(_args: UpdateSpanArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_UPDATE_SPAN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support updating spans',\n    });\n  }\n\n  /**\n   * Retrieves a single span.\n   */\n  async getSpan(_args: GetSpanArgs): Promise<GetSpanResponse | null> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SPAN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support getting spans',\n    });\n  }\n\n  /**\n   * Retrieves a single root span.\n   */\n  async getRootSpan(_args: GetRootSpanArgs): Promise<GetRootSpanResponse | null> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_ROOT_SPAN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support getting root spans',\n    });\n  }\n\n  /**\n   * Retrieves a single trace with all its associated spans.\n   */\n  async getTrace(_args: GetTraceArgs): Promise<GetTraceResponse | null> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_TRACE_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support getting traces',\n    });\n  }\n\n  /**\n   * Retrieves the structural skeleton of a trace -- parent/child links, span\n   * type, timing, and status -- with heavy fields (input, output, attributes,\n   * metadata, tags, links) excluded. Intended for waterfall/timeline rendering\n   * where the full payload would be wasteful.\n   *\n   * Default implementation forwards to {@link getTraceLight} (the legacy\n   * override surface). Backends should override either method -- the response\n   * shape is identical, and the unimplemented one delegates to the\n   * implemented one. The cycle guard is what makes that safe.\n   */\n  async getStructure(args: GetTraceArgs): Promise<GetStructureResponse | null> {\n    if (this.getTraceLight === ObservabilityStorage.prototype.getTraceLight) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_STORAGE_GET_STRUCTURE_NOT_IMPLEMENTED',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.SYSTEM,\n        text: 'This storage provider does not support getting trace structure',\n      });\n    }\n    return this.getTraceLight(args);\n  }\n\n  /**\n   * @deprecated Use {@link getStructure} instead. Default implementation\n   * forwards to {@link getStructure} so backends that only override the\n   * canonical name still work for legacy callers.\n   */\n  async getTraceLight(args: GetTraceArgs): Promise<GetTraceLightResponse | null> {\n    if (this.getStructure === ObservabilityStorage.prototype.getStructure) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_STORAGE_GET_TRACE_LIGHT_NOT_IMPLEMENTED',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.SYSTEM,\n        text: 'This storage provider does not support getting lightweight traces',\n      });\n    }\n    return this.getStructure(args);\n  }\n\n  /**\n   * Retrieves the subtree of spans rooted at a given span, optionally bounded\n   * to `depth` levels of descendants.\n   *\n   * Default implementation prefers a two-step path: fetch the lightweight\n   * structure to determine which spans belong to the branch, then batch-fetch\n   * only those with full data. This avoids pulling the entire trace when the\n   * branch is a small slice of a large trace. Backends that don't yet\n   * implement {@link getStructure} or {@link getSpans} fall back to fetching\n   * the full trace and walking it in memory.\n   */\n  async getBranch(args: GetBranchArgs): Promise<GetBranchResponse | null> {\n    const parsed = getBranchArgsSchema.parse(args);\n\n    // Optimized path: skeleton walk → batch fetch the branch's spans.\n    try {\n      const skeleton = await this.getStructure({ traceId: parsed.traceId });\n      if (!skeleton) return null;\n      const branchSpanIds = extractBranchSpans(skeleton.spans, parsed.spanId, parsed.depth).map(s => s.spanId);\n      if (branchSpanIds.length === 0) return null;\n      const { spans } = await this.getSpans({ traceId: parsed.traceId, spanIds: branchSpanIds });\n      if (spans.length === 0) return null;\n      spans.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());\n      return { traceId: parsed.traceId, spans };\n    } catch (error) {\n      const isFallbackTrigger =\n        error instanceof MastraError &&\n        (error.id === 'OBSERVABILITY_STORAGE_GET_STRUCTURE_NOT_IMPLEMENTED' ||\n          error.id === 'OBSERVABILITY_STORAGE_GET_TRACE_LIGHT_NOT_IMPLEMENTED' ||\n          error.id === 'OBSERVABILITY_STORAGE_GET_SPANS_NOT_IMPLEMENTED');\n      if (!isFallbackTrigger) throw error;\n    }\n\n    // Fallback: pull the whole trace, walk in memory.\n    const trace = await this.getTrace({ traceId: parsed.traceId });\n    if (!trace) return null;\n    const spans = extractBranchSpans(trace.spans, parsed.spanId, parsed.depth);\n    if (spans.length === 0) return null;\n    return { traceId: parsed.traceId, spans };\n  }\n\n  /**\n   * Batch-fetches spans by spanId within a single trace. Used by the\n   * optimized {@link getBranch} path to fetch only the spans that belong to\n   * the requested branch (after walking the lightweight structure to identify\n   * them) instead of pulling the entire trace.\n   */\n  async getSpans(_args: GetSpansArgs): Promise<GetSpansResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SPANS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch-fetching spans',\n    });\n  }\n\n  /**\n   * Retrieves a list of traces with optional filtering.\n   */\n  async listTraces(_args: ListTracesArgs): Promise<ListTracesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_TRACES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing traces',\n    });\n  }\n\n  /**\n   * Retrieves a lightweight list of traces with optional filtering.\n   */\n  async listTracesLight(_args: ListTracesArgs): Promise<ListTracesLightResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_TRACES_LIGHT_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing lightweight traces',\n    });\n  }\n\n  /**\n   * Lists trace branches across all traces. Unlike {@link listTraces} (which\n   * returns one row per root-rooted trace), each row here is a single branch\n   * anchor span, including ones nested under a different root entity -- useful\n   * for \"show me every run of agent X\" regardless of caller. Pairs with\n   * {@link getBranch} to expand a single branch into its subtree.\n   */\n  async listBranches(_args: ListBranchesArgs): Promise<ListBranchesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_BRANCHES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing trace branches',\n    });\n  }\n\n  /**\n   * Creates multiple Spans in a single batch.\n   */\n  async batchCreateSpans(_args: BatchCreateSpansArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_CREATE_SPAN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch creating spans',\n    });\n  }\n\n  /**\n   * Updates multiple Spans in a single batch.\n   */\n  async batchUpdateSpans(_args: BatchUpdateSpansArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_UPDATE_SPANS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch updating spans',\n    });\n  }\n\n  /**\n   * Deletes multiple traces and all their associated spans in a single batch operation.\n   */\n  async batchDeleteTraces(_args: BatchDeleteTracesArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_DELETE_TRACES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch deleting traces',\n    });\n  }\n\n  // ============================================================================\n  // Logs\n  // ============================================================================\n\n  /**\n   * Creates multiple log records in a single batch.\n   */\n  async batchCreateLogs(_args: BatchCreateLogsArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_CREATE_LOGS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch creating logs',\n    });\n  }\n\n  /**\n   * Retrieves a list of logs with optional filtering.\n   */\n  async listLogs(_args: ListLogsArgs): Promise<ListLogsResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_LOGS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing logs',\n    });\n  }\n\n  // ============================================================================\n  // Metrics\n  // ============================================================================\n\n  /**\n   * Creates multiple metric observations in a single batch.\n   */\n  async batchCreateMetrics(_args: BatchCreateMetricsArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_CREATE_METRICS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch creating metrics',\n    });\n  }\n\n  async listMetrics(_args: ListMetricsArgs): Promise<ListMetricsResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_METRICS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing metrics',\n    });\n  }\n\n  async getMetricAggregate(_args: GetMetricAggregateArgs): Promise<GetMetricAggregateResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_METRIC_AGGREGATE_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support metric aggregation',\n    });\n  }\n\n  async getMetricBreakdown(_args: GetMetricBreakdownArgs): Promise<GetMetricBreakdownResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_METRIC_BREAKDOWN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support metric breakdown',\n    });\n  }\n\n  async getMetricTimeSeries(_args: GetMetricTimeSeriesArgs): Promise<GetMetricTimeSeriesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_METRIC_TIME_SERIES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support metric time series',\n    });\n  }\n\n  async getMetricPercentiles(_args: GetMetricPercentilesArgs): Promise<GetMetricPercentilesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_METRIC_PERCENTILES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support metric percentiles',\n    });\n  }\n\n  // ============================================================================\n  // Discovery / Metadata Methods\n  // ============================================================================\n\n  async getMetricNames(_args: GetMetricNamesArgs): Promise<GetMetricNamesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_METRIC_NAMES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support metric name discovery',\n    });\n  }\n\n  async getMetricLabelKeys(_args: GetMetricLabelKeysArgs): Promise<GetMetricLabelKeysResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_METRIC_LABEL_KEYS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support metric label key discovery',\n    });\n  }\n\n  async getMetricLabelValues(_args: GetMetricLabelValuesArgs): Promise<GetMetricLabelValuesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_LABEL_VALUES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support label value discovery',\n    });\n  }\n\n  async getEntityTypes(_args: GetEntityTypesArgs): Promise<GetEntityTypesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_ENTITY_TYPES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support entity type discovery',\n    });\n  }\n\n  async getEntityNames(_args: GetEntityNamesArgs): Promise<GetEntityNamesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_ENTITY_NAMES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support entity name discovery',\n    });\n  }\n\n  async getServiceNames(_args: GetServiceNamesArgs): Promise<GetServiceNamesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SERVICE_NAMES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support service name discovery',\n    });\n  }\n\n  async getEnvironments(_args: GetEnvironmentsArgs): Promise<GetEnvironmentsResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_ENVIRONMENTS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support environment discovery',\n    });\n  }\n\n  async getTags(_args: GetTagsArgs): Promise<GetTagsResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_TAGS_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support tag discovery',\n    });\n  }\n\n  // ============================================================================\n  // Scores\n  // ============================================================================\n\n  /**\n   * Creates a single score record.\n   */\n  async createScore(_args: CreateScoreArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_CREATE_SCORE_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support creating scores',\n    });\n  }\n\n  /**\n   * Creates multiple score observations in a single batch.\n   */\n  async batchCreateScores(_args: BatchCreateScoresArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_CREATE_SCORES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch creating scores',\n    });\n  }\n\n  /**\n   * Retrieves a list of scores with optional filtering.\n   */\n  async listScores(_args: ListScoresArgs): Promise<ListScoresResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_SCORES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing scores',\n    });\n  }\n\n  /**\n   * Retrieves a single score by its score ID.\n   */\n  async getScoreById(_scoreId: string): Promise<ScoreRecord | null> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SCORE_BY_ID_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support getting scores by ID',\n    });\n  }\n\n  async getScoreAggregate(_args: GetScoreAggregateArgs): Promise<GetScoreAggregateResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SCORE_AGGREGATE_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support score aggregation',\n    });\n  }\n\n  async getScoreBreakdown(_args: GetScoreBreakdownArgs): Promise<GetScoreBreakdownResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SCORE_BREAKDOWN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support score breakdown',\n    });\n  }\n\n  async getScoreTimeSeries(_args: GetScoreTimeSeriesArgs): Promise<GetScoreTimeSeriesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SCORE_TIME_SERIES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support score time series',\n    });\n  }\n\n  async getScorePercentiles(_args: GetScorePercentilesArgs): Promise<GetScorePercentilesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_SCORE_PERCENTILES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support score percentiles',\n    });\n  }\n\n  // ============================================================================\n  // Feedback\n  // ============================================================================\n\n  /**\n   * Creates a single feedback record.\n   */\n  async createFeedback(_args: CreateFeedbackArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_CREATE_FEEDBACK_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support creating feedback',\n    });\n  }\n\n  /**\n   * Creates multiple feedback observations in a single batch.\n   */\n  async batchCreateFeedback(_args: BatchCreateFeedbackArgs): Promise<void> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_BATCH_CREATE_FEEDBACK_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support batch creating feedback',\n    });\n  }\n\n  /**\n   * Retrieves a list of feedback with optional filtering.\n   */\n  async listFeedback(_args: ListFeedbackArgs): Promise<ListFeedbackResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_LIST_FEEDBACK_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support listing feedback',\n    });\n  }\n\n  async getFeedbackAggregate(_args: GetFeedbackAggregateArgs): Promise<GetFeedbackAggregateResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_FEEDBACK_AGGREGATE_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support feedback aggregation',\n    });\n  }\n\n  async getFeedbackBreakdown(_args: GetFeedbackBreakdownArgs): Promise<GetFeedbackBreakdownResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_FEEDBACK_BREAKDOWN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support feedback breakdown',\n    });\n  }\n\n  async getFeedbackTimeSeries(_args: GetFeedbackTimeSeriesArgs): Promise<GetFeedbackTimeSeriesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_FEEDBACK_TIME_SERIES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support feedback time series',\n    });\n  }\n\n  async getFeedbackPercentiles(_args: GetFeedbackPercentilesArgs): Promise<GetFeedbackPercentilesResponse> {\n    throw new MastraError({\n      id: 'OBSERVABILITY_STORAGE_GET_FEEDBACK_PERCENTILES_NOT_IMPLEMENTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support feedback percentiles',\n    });\n  }\n}\n","import type { ScoreRowData } from '../evals/types';\nimport { TABLE_SCHEMAS, TABLE_SCORERS } from './constants';\nimport type { TABLE_NAMES } from './constants';\nimport type { Duration } from './retention';\nimport type { StorageColumn, StorageMetadataFilter } from './types';\n\n/**\n * Canonical store names for type safety.\n * Provides autocomplete suggestions while still accepting any string.\n */\nexport type StoreName =\n  | 'PG'\n  | 'MSSQL'\n  | 'LIBSQL'\n  | 'MONGODB'\n  | 'CLICKHOUSE'\n  | 'CLOUDFLARE'\n  | 'CLOUDFLARE_D1'\n  | 'DYNAMODB'\n  | 'LANCE'\n  | 'UPSTASH'\n  | 'ASTRA'\n  | 'CHROMA'\n  | 'COUCHBASE'\n  | 'OPENSEARCH'\n  | 'PINECONE'\n  | 'QDRANT'\n  | 'S3'\n  | 'TURBOPUFFER'\n  | 'VECTORIZE'\n  | (string & {});\n\nexport function hasErrorCode(error: unknown, codes: ReadonlySet<string | number>): boolean {\n  const seen = new Set<object>();\n  let current: unknown = error;\n  while (current && typeof current === 'object' && !seen.has(current)) {\n    seen.add(current);\n    if ('code' in current && codes.has((current as { code: string | number }).code)) return true;\n    current = 'cause' in current ? (current as { cause?: unknown }).cause : undefined;\n  }\n  return false;\n}\n\nconst DURATION_UNIT_MS: Record<string, number> = {\n  ms: 1,\n  s: 1000,\n  m: 60 * 1000,\n  h: 60 * 60 * 1000,\n  d: 24 * 60 * 60 * 1000,\n  w: 7 * 24 * 60 * 60 * 1000,\n};\n\n/**\n * Parses a retention {@link Duration} into milliseconds.\n *\n * Accepts a raw number of milliseconds or a `<number><unit>` string where unit\n * is one of `ms`, `s`, `m`, `h`, `d`, `w`.\n *\n * @throws Error if the input is not a valid duration.\n */\nexport function parseDuration(duration: Duration): number {\n  if (typeof duration === 'number') {\n    if (!Number.isFinite(duration) || duration < 0) {\n      throw new Error(`Invalid retention duration: ${duration}. Must be a non-negative finite number of milliseconds.`);\n    }\n    return duration;\n  }\n\n  const match = /^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)$/.exec(duration);\n  if (!match) {\n    throw new Error(\n      `Invalid retention duration: \"${duration}\". Expected a number of milliseconds or a \"<number><unit>\" string (ms, s, m, h, d, w).`,\n    );\n  }\n\n  const value = Number(match[1]);\n  const unit = match[2]!;\n  return value * DURATION_UNIT_MS[unit]!;\n}\n\nexport function safelyParseJSON(input: any): any {\n  // If already an object (and not null), return as-is\n  if (input && typeof input === 'object') return input;\n  if (input == null) return {};\n  // If it's a string, try to parse\n  if (typeof input === 'string') {\n    try {\n      return JSON.parse(input);\n    } catch {\n      return input;\n    }\n  }\n  // For anything else (number, boolean, etc.), return empty object\n  return {};\n}\n\nconst SAFE_METADATA_KEY_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nconst MAX_METADATA_KEY_LENGTH = 128;\nconst DISALLOWED_METADATA_KEYS = new Set(['__proto__', 'prototype', 'constructor']);\n\nexport function validateStorageMetadataFilter(\n  metadata: StorageMetadataFilter | undefined,\n): StorageMetadataFilter | undefined {\n  if (metadata === undefined) return undefined;\n  if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) {\n    throw new TypeError('Metadata filter must be an object.');\n  }\n\n  const entries = Object.entries(metadata);\n  for (const [key, value] of entries) {\n    if (\n      key.length > MAX_METADATA_KEY_LENGTH ||\n      !SAFE_METADATA_KEY_PATTERN.test(key) ||\n      DISALLOWED_METADATA_KEYS.has(key)\n    ) {\n      throw new TypeError(`Invalid metadata filter key \"${key}\".`);\n    }\n    if (\n      value !== null &&\n      typeof value !== 'string' &&\n      typeof value !== 'boolean' &&\n      !(typeof value === 'number' && Number.isFinite(value))\n    ) {\n      throw new TypeError(\n        `Invalid metadata filter value for key \"${key}\". Values must be string, finite number, boolean, or null.`,\n      );\n    }\n  }\n\n  return entries.length > 0 ? metadata : undefined;\n}\n\nexport function storageMessageMatchesMetadataFilter(\n  content: unknown,\n  filter: StorageMetadataFilter | undefined,\n): boolean {\n  if (!filter) return true;\n  const parsedContent = typeof content === 'string' ? safelyParseJSON(content) : content;\n  if (!parsedContent || typeof parsedContent !== 'object' || Array.isArray(parsedContent)) return false;\n  const metadata = (parsedContent as { metadata?: unknown }).metadata;\n  if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata)) return false;\n\n  const metadataRecord = metadata as Record<string, unknown>;\n  return Object.entries(filter).every(\n    ([key, expected]) => Object.prototype.hasOwnProperty.call(metadataRecord, key) && metadataRecord[key] === expected,\n  );\n}\n\n/**\n * Options for transforming storage rows\n */\nexport interface TransformRowOptions {\n  /**\n   * Preferred source fields for timestamps (e.g., { createdAt: 'createdAtZ' } means use createdAtZ if available, else createdAt)\n   */\n  preferredTimestampFields?: Record<string, string>;\n\n  /**\n   * Convert timestamp strings to Date objects (default: false for backwards compatibility)\n   */\n  convertTimestamps?: boolean;\n\n  /**\n   * Pattern to treat as null (e.g., '_null_' for ClickHouse)\n   */\n  nullValuePattern?: string;\n\n  /**\n   * Custom field mappings from source to target (e.g., { entity: 'entityData' } for DynamoDB)\n   */\n  fieldMappings?: Record<string, string>;\n}\n\n/**\n * Generic schema-driven row transformer.\n * Uses TABLE_SCHEMAS to determine field types and apply appropriate transformations:\n * - 'jsonb' fields: parsed from JSON strings using safelyParseJSON\n * - 'timestamp' fields: optionally converted to Date objects\n *\n * @param row - The raw row from storage\n * @param tableName - The table name to look up schema from TABLE_SCHEMAS\n * @param options - Optional configuration for store-specific behavior\n * @returns Transformed row with proper types\n */\nexport function transformRow<T = Record<string, any>>(\n  row: Record<string, any>,\n  tableName: TABLE_NAMES,\n  options: TransformRowOptions = {},\n): T {\n  const { preferredTimestampFields = {}, convertTimestamps = false, nullValuePattern, fieldMappings = {} } = options;\n\n  const tableSchema = TABLE_SCHEMAS[tableName];\n  const result: Record<string, any> = {};\n\n  for (const [key, columnSchema] of Object.entries(tableSchema)) {\n    // Handle field mappings (e.g., entityData -> entity for DynamoDB)\n    const sourceKey = fieldMappings[key] ?? key;\n    let value = row[sourceKey];\n\n    // Handle preferred timestamp sources (e.g., use createdAtZ if available, else createdAt)\n    if (preferredTimestampFields[key]) {\n      value = row[preferredTimestampFields[key]] ?? value;\n    }\n\n    // Skip null/undefined values\n    if (value === undefined || value === null) {\n      continue;\n    }\n\n    // Skip null pattern values (e.g., ClickHouse's '_null_')\n    if (nullValuePattern && value === nullValuePattern) {\n      continue;\n    }\n\n    // Transform based on column type\n    if (columnSchema.type === 'jsonb') {\n      if (typeof value === 'string') {\n        result[key] = safelyParseJSON(value);\n      } else if (typeof value === 'object') {\n        result[key] = value; // Already parsed\n      } else {\n        result[key] = value;\n      }\n    } else if (columnSchema.type === 'timestamp' && convertTimestamps && typeof value === 'string') {\n      result[key] = new Date(value);\n    } else {\n      result[key] = value;\n    }\n  }\n\n  return result as T;\n}\n\n/**\n * Transform a raw score row from storage to ScoreRowData.\n * Convenience wrapper around transformRow for the scores table (TABLE_SCORERS).\n *\n * @param row - The raw row from storage\n * @param options - Optional configuration for store-specific behavior\n * @returns Transformed ScoreRowData\n */\nexport function transformScoreRow(row: Record<string, any>, options: TransformRowOptions = {}): ScoreRowData {\n  return transformRow<ScoreRowData>(row, TABLE_SCORERS, options);\n}\n\n/**\n * Converts a string to UPPER_SNAKE_CASE, preserving word boundaries from camelCase, PascalCase, kebab-case, etc.\n */\nfunction toUpperSnakeCase(str: string): string {\n  return (\n    str\n      // Insert underscore before uppercase letters that follow lowercase letters (camelCase -> camel_Case)\n      .replace(/([a-z])([A-Z])/g, '$1_$2')\n      // Insert underscore before uppercase letters that are followed by lowercase letters (XMLParser -> XML_Parser)\n      .replace(/([A-Z])([A-Z][a-z])/g, '$1_$2')\n      // Convert to uppercase\n      .toUpperCase()\n      // Replace any non-alphanumeric characters with underscore\n      .replace(/[^A-Z0-9]+/g, '_')\n      // Remove leading/trailing underscores\n      .replace(/^_+|_+$/g, '')\n  );\n}\n\n/**\n * Generates a standardized error ID for storage and vector operations.\n *\n * Formats:\n * - Storage: MASTRA_STORAGE_{STORE}_{OPERATION}_{STATUS}\n * - Vector:  MASTRA_VECTOR_{STORE}_{OPERATION}_{STATUS}\n *\n * This function auto-normalizes inputs to UPPER_SNAKE_CASE for flexibility.\n * The store parameter is type-checked against canonical store names for IDE autocomplete.\n *\n * @param type - The operation type ('storage' or 'vector')\n * @param store - The store adapter name (type-checked canonical names)\n * @param operation - The operation that failed (e.g., 'LIST_THREADS_BY_RESOURCE_ID', 'QUERY')\n * @param status - The status/error type (e.g., 'FAILED', 'INVALID_THREAD_ID', 'DUPLICATE_KEY')\n *\n * @example\n * ```ts\n * // Storage operations\n * createStoreErrorId('storage', 'PG', 'LIST_THREADS', 'FAILED')\n * // Returns: 'MASTRA_STORAGE_PG_LIST_THREADS_FAILED'\n *\n * // Vector operations\n * createStoreErrorId('vector', 'CHROMA', 'QUERY', 'FAILED')\n * // Returns: 'MASTRA_VECTOR_CHROMA_QUERY_FAILED'\n *\n * // Auto-normalizes any casing\n * createStoreErrorId('storage', 'PG', 'listMessagesById', 'failed')\n * // Returns: 'MASTRA_STORAGE_PG_LIST_MESSAGES_BY_ID_FAILED'\n * ```\n */\nexport function createStoreErrorId(\n  type: 'storage' | 'vector',\n  store: StoreName,\n  operation: string,\n  status: string,\n): Uppercase<string> {\n  const normalizedStore = toUpperSnakeCase(store);\n  const normalizedOperation = toUpperSnakeCase(operation);\n  const normalizedStatus = toUpperSnakeCase(status);\n  const typePrefix = type === 'storage' ? 'STORAGE' : 'VECTOR';\n\n  return `MASTRA_${typePrefix}_${normalizedStore}_${normalizedOperation}_${normalizedStatus}` as Uppercase<string>;\n}\n\nexport function createStorageErrorId(store: StoreName, operation: string, status: string): Uppercase<string> {\n  return createStoreErrorId('storage', store, operation, status);\n}\n\nexport function createVectorErrorId(store: StoreName, operation: string, status: string): Uppercase<string> {\n  return createStoreErrorId('vector', store, operation, status);\n}\n\nexport function getSqlType(type: StorageColumn['type']): string {\n  switch (type) {\n    case 'text':\n      return 'TEXT';\n    case 'timestamp':\n      return 'TIMESTAMP';\n    case 'float':\n      return 'FLOAT';\n    case 'integer':\n      return 'INTEGER';\n    case 'bigint':\n      return 'BIGINT';\n    case 'jsonb':\n      return 'JSONB';\n    case 'boolean':\n      return 'BOOLEAN';\n    default:\n      return 'TEXT';\n  }\n}\n\nexport function getDefaultValue(type: StorageColumn['type']): string {\n  switch (type) {\n    case 'text':\n    case 'uuid':\n      return \"DEFAULT ''\";\n    case 'timestamp':\n      return \"DEFAULT '1970-01-01 00:00:00'\";\n    case 'integer':\n    case 'bigint':\n    case 'float':\n      return 'DEFAULT 0';\n    case 'jsonb':\n      return \"DEFAULT '{}'\";\n    case 'boolean':\n      return 'DEFAULT FALSE';\n    default:\n      return \"DEFAULT ''\";\n  }\n}\n\nexport function ensureDate(date: Date | string | undefined): Date | undefined {\n  if (!date) return undefined;\n  return date instanceof Date ? date : new Date(date);\n}\n\nexport function serializeDate(date: Date | string | undefined): string | undefined {\n  if (!date) return undefined;\n  const dateObj = ensureDate(date);\n  return dateObj?.toISOString();\n}\n\n/**\n * Date range filter configuration for in-memory filtering operations.\n */\nexport interface DateRangeFilter {\n  start?: Date | string;\n  end?: Date | string;\n  startExclusive?: boolean;\n  endExclusive?: boolean;\n}\n\n/**\n * Filter an array of items by date range. Used by in-memory storage adapters.\n *\n * This provides a consistent implementation of date range filtering with\n * support for inclusive/exclusive bounds across all storage adapters.\n *\n * @param items - Array of items to filter\n * @param getCreatedAt - Function to extract the createdAt date from an item\n * @param dateRange - Optional date range filter configuration\n * @returns Filtered array of items\n *\n * @example\n * ```ts\n * const filtered = filterByDateRange(\n *   messages,\n *   (msg) => new Date(msg.createdAt),\n *   { start: new Date('2024-01-01'), startExclusive: true }\n * );\n * ```\n */\nexport function filterByDateRange<T>(items: T[], getCreatedAt: (item: T) => Date, dateRange?: DateRangeFilter): T[] {\n  if (!dateRange) return items;\n\n  let result = items;\n\n  if (dateRange.start) {\n    const startTime = ensureDate(dateRange.start)!.getTime();\n    result = result.filter(item => {\n      const itemTime = getCreatedAt(item).getTime();\n      return dateRange.startExclusive ? itemTime > startTime : itemTime >= startTime;\n    });\n  }\n\n  if (dateRange.end) {\n    const endTime = ensureDate(dateRange.end)!.getTime();\n    result = result.filter(item => {\n      const itemTime = getCreatedAt(item).getTime();\n      return dateRange.endExclusive ? itemTime < endTime : itemTime <= endTime;\n    });\n  }\n\n  return result;\n}\n\n/**\n * Deep equality check for JSON values.\n * Compares primitives, arrays, objects, and Date instances recursively.\n *\n * @param a - First value to compare\n * @param b - Second value to compare\n * @returns true if values are deeply equal, false otherwise\n */\nexport function jsonValueEquals(a: unknown, b: unknown): boolean {\n  if (a === undefined || b === undefined) {\n    return a === b;\n  }\n  if (a === null || b === null) {\n    return a === b;\n  }\n  if (typeof a !== typeof b) {\n    return false;\n  }\n  // Handle Date objects\n  if (a instanceof Date && b instanceof Date) {\n    return a.getTime() === b.getTime();\n  }\n  if (a instanceof Date || b instanceof Date) {\n    return false; // One is Date, other is not\n  }\n  if (typeof a === 'object') {\n    if (Array.isArray(a) && Array.isArray(b)) {\n      if (a.length !== b.length) return false;\n      return a.every((val, i) => jsonValueEquals(val, b[i]));\n    }\n    if (Array.isArray(a) || Array.isArray(b)) {\n      return false;\n    }\n    const aKeys = Object.keys(a as object);\n    const bKeys = Object.keys(b as object);\n    if (aKeys.length !== bKeys.length) return false;\n    return aKeys.every(key =>\n      jsonValueEquals((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key]),\n    );\n  }\n  return a === b;\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\nimport { coreFeatures } from '../../../features';\nimport { EntityType } from '../../../observability';\nimport { jsonValueEquals } from '../../utils';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { ObservabilityStorage } from './base';\nimport type {\n  GetEntityTypesArgs,\n  GetEntityTypesResponse,\n  GetEntityNamesArgs,\n  GetEntityNamesResponse,\n  GetServiceNamesArgs,\n  GetServiceNamesResponse,\n  GetEnvironmentsArgs,\n  GetEnvironmentsResponse,\n  GetTagsArgs,\n  GetTagsResponse,\n  GetMetricNamesArgs,\n  GetMetricNamesResponse,\n  GetMetricLabelKeysArgs,\n  GetMetricLabelKeysResponse,\n  GetMetricLabelValuesArgs,\n  GetMetricLabelValuesResponse,\n} from './discovery';\nimport { listFeedbackArgsSchema } from './feedback';\nimport type {\n  BatchCreateFeedbackArgs,\n  CreateFeedbackArgs,\n  FeedbackFilter,\n  GetFeedbackAggregateArgs,\n  GetFeedbackAggregateResponse,\n  GetFeedbackBreakdownArgs,\n  GetFeedbackBreakdownResponse,\n  GetFeedbackPercentilesArgs,\n  GetFeedbackPercentilesResponse,\n  GetFeedbackTimeSeriesArgs,\n  GetFeedbackTimeSeriesResponse,\n  ListFeedbackArgs,\n  ListFeedbackResponse,\n  FeedbackRecord,\n} from './feedback';\nimport { listLogsArgsSchema } from './logs';\nimport type { BatchCreateLogsArgs, ListLogsArgs, ListLogsResponse, LogRecord } from './logs';\nimport type {\n  BatchCreateMetricsArgs,\n  MetricRecord,\n  ListMetricsArgs,\n  ListMetricsResponse,\n  GetMetricAggregateArgs,\n  GetMetricAggregateResponse,\n  GetMetricBreakdownArgs,\n  GetMetricBreakdownResponse,\n  GetMetricTimeSeriesArgs,\n  GetMetricTimeSeriesResponse,\n  GetMetricPercentilesArgs,\n  GetMetricPercentilesResponse,\n  AggregationType,\n} from './metrics';\nimport { listMetricsArgsSchema } from './metrics';\nimport { listScoresArgsSchema } from './scores';\nimport type {\n  BatchCreateScoresArgs,\n  CreateScoreArgs,\n  GetScoreAggregateArgs,\n  GetScoreAggregateResponse,\n  GetScoreBreakdownArgs,\n  GetScoreBreakdownResponse,\n  GetScorePercentilesArgs,\n  GetScorePercentilesResponse,\n  GetScoreTimeSeriesArgs,\n  GetScoreTimeSeriesResponse,\n  ListScoresArgs,\n  ListScoresResponse,\n  ScoreRecord,\n} from './scores';\nimport type {\n  BatchCreateSpansArgs,\n  BatchDeleteTracesArgs,\n  BatchUpdateSpansArgs,\n  CreateSpanArgs,\n  CreateSpanRecord,\n  GetRootSpanArgs,\n  GetRootSpanResponse,\n  GetSpanArgs,\n  GetSpanResponse,\n  GetSpansArgs,\n  GetSpansResponse,\n  GetStructureResponse,\n  GetTraceArgs,\n  GetTraceResponse,\n  LightSpanRecord,\n  ListBranchesArgs,\n  ListBranchesResponse,\n  ListTracesArgs,\n  ListTracesLightResponse,\n  ListTracesResponse,\n  SpanRecord,\n  UpdateSpanArgs,\n} from './tracing';\n\nimport {\n  BRANCH_SPAN_TYPE_SET,\n  listBranchesArgsSchema,\n  listTracesArgsSchema,\n  TraceStatus,\n  toTraceSpan,\n  toTraceSpans,\n} from './tracing';\n\nconst OBSERVABILITY_DELTA_POLLING_FEATURE = 'observability-delta-polling';\n\n/**\n * Internal structure for storing a trace with computed properties for efficient filtering\n */\nexport interface TraceEntry {\n  /** All spans in this trace, keyed by spanId */\n  spans: Record<string, SpanRecord>;\n  /** Root span for this trace (parentSpanId === null) */\n  rootSpan: SpanRecord | null;\n  /** Computed trace status based on root span state */\n  status: TraceStatus;\n  /** True if any span in the trace has an error */\n  hasChildError: boolean;\n}\n\n/** In-memory implementation of ObservabilityStorage for testing and development. */\nexport class ObservabilityInMemory extends ObservabilityStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  override getFeatures() {\n    if (!this.deltaPollingFeatureEnabled()) {\n      return undefined;\n    }\n\n    return ['delta-polling'] as const;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.traces.clear();\n    this.db.metricRecords.length = 0;\n    this.db.logRecords.length = 0;\n    this.db.scoreRecords.length = 0;\n    this.db.feedbackRecords.length = 0;\n    this.db.observabilityNextCursorId = 1;\n    this.db.traceCursorIds.clear();\n    this.db.branchCursorIds.clear();\n    this.db.metricCursorIds.clear();\n    this.db.logCursorIds.clear();\n    this.db.scoreCursorIds.clear();\n    this.db.feedbackCursorIds.clear();\n  }\n\n  private deltaPollingFeatureEnabled(): boolean {\n    return coreFeatures.has(OBSERVABILITY_DELTA_POLLING_FEATURE);\n  }\n\n  private assertDeltaPollingEnabled(): void {\n    if (this.deltaPollingFeatureEnabled()) {\n      return;\n    }\n\n    throw new MastraError({\n      id: 'OBSERVABILITY_DELTA_POLLING_NOT_SUPPORTED',\n      domain: ErrorDomain.MASTRA_OBSERVABILITY,\n      category: ErrorCategory.SYSTEM,\n      text: 'This storage provider does not support observability delta polling',\n    });\n  }\n\n  private allocateObservabilityCursorId(): number {\n    const cursorId = this.db.observabilityNextCursorId;\n    this.db.observabilityNextCursorId += 1;\n    return cursorId;\n  }\n\n  /**\n   * Upserts a record into an append-only collection keyed by an id field.\n   *\n   * If an existing record with the same id is found, it is replaced in place\n   * (preserving its cursor id so delta polling does not re-emit it). Otherwise\n   * the record is appended and a fresh cursor id is allocated.\n   */\n  private upsertByIdField<T extends Record<string, unknown>>(\n    records: T[],\n    cursorIds: Map<T, number>,\n    record: T,\n    idField: keyof T,\n  ): void {\n    const id = record[idField];\n    if (id == null) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_MISSING_RECORD_ID',\n        domain: ErrorDomain.STORAGE,\n        category: ErrorCategory.USER,\n        text: `Observability record is missing required id field '${String(idField)}'`,\n      });\n    }\n    const existingIndex = records.findIndex(existing => existing[idField] === id);\n    if (existingIndex !== -1) {\n      const previous = records[existingIndex]!;\n      const cursorId = cursorIds.get(previous);\n      cursorIds.delete(previous);\n      records[existingIndex] = record;\n      if (cursorId !== undefined) {\n        cursorIds.set(record, cursorId);\n      }\n      return;\n    }\n    records.push(record);\n    cursorIds.set(record, this.allocateObservabilityCursorId());\n  }\n\n  private encodeDeltaCursor(cursorId?: number | null): string {\n    return (cursorId ?? 0).toString();\n  }\n\n  private decodeDeltaCursor(cursor: string): number {\n    if (!/^\\d+$/.test(cursor)) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_INVALID_DELTA_CURSOR',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.USER,\n        text: 'Invalid observability delta cursor',\n      });\n    }\n\n    const cursorId = Number.parseInt(cursor, 10);\n    if (!Number.isInteger(cursorId) || cursorId < 0) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_INVALID_DELTA_CURSOR',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.USER,\n        text: 'Invalid observability delta cursor',\n      });\n    }\n\n    return cursorId;\n  }\n\n  private pageDeltaCursor(cursorId: number | null): { deltaCursor?: string } {\n    if (!this.deltaPollingFeatureEnabled()) {\n      return {};\n    }\n\n    return { deltaCursor: this.encodeDeltaCursor(cursorId) };\n  }\n\n  private maxMatchingCursorId<T extends object>(\n    rows: Iterable<T>,\n    cursorIds: Map<T, number>,\n    matches: (row: T) => boolean,\n  ): number | null {\n    let maxCursorId: number | null = null;\n\n    for (const row of rows) {\n      const cursorId = cursorIds.get(row);\n      if (cursorId === undefined || !matches(row)) {\n        continue;\n      }\n\n      if (maxCursorId === null || cursorId > maxCursorId) {\n        maxCursorId = cursorId;\n      }\n    }\n\n    return maxCursorId;\n  }\n\n  private createBranchCursorKey(traceId: string, spanId: string): string {\n    return `${traceId}\\u0000${spanId}`;\n  }\n\n  private maybeRegisterTraceCursor(traceEntry: TraceEntry): void {\n    const rootSpan = traceEntry.rootSpan;\n    if (!rootSpan) {\n      return;\n    }\n\n    if (!this.db.traceCursorIds.has(rootSpan.traceId)) {\n      this.db.traceCursorIds.set(rootSpan.traceId, this.allocateObservabilityCursorId());\n    }\n  }\n\n  private maybeRegisterBranchCursor(span: SpanRecord): void {\n    if (!BRANCH_SPAN_TYPE_SET.has(span.spanType)) {\n      return;\n    }\n\n    const key = this.createBranchCursorKey(span.traceId, span.spanId);\n    if (!this.db.branchCursorIds.has(key)) {\n      this.db.branchCursorIds.set(key, this.allocateObservabilityCursorId());\n    }\n  }\n\n  private buildDeltaResponse<T>(\n    rows: Array<{ cursorId: number; row: T }>,\n    limit: number,\n    fallbackCursorId: number | null,\n  ): { rows: T[]; delta: { limit: number; hasMore: boolean }; deltaCursor: string } {\n    const visibleRows = rows.slice(0, limit);\n    const hasMore = rows.length > limit;\n\n    return {\n      rows: visibleRows.map(entry => entry.row),\n      delta: { limit, hasMore },\n      deltaCursor:\n        visibleRows.length > 0\n          ? this.encodeDeltaCursor(visibleRows[visibleRows.length - 1]!.cursorId)\n          : this.encodeDeltaCursor(fallbackCursorId),\n    };\n  }\n\n  private listAppendOnlyDelta<T extends object>(\n    rows: T[],\n    cursorIds: Map<T, number>,\n    matches: (row: T) => boolean,\n    after: string | undefined,\n    limit: number,\n  ): { rows: T[]; delta: { limit: number; hasMore: boolean }; deltaCursor: string } {\n    const currentCursorId = this.maxMatchingCursorId(rows, cursorIds, matches);\n    const streamCursorId = this.maxMatchingCursorId(rows, cursorIds, () => true);\n    const fallbackCursorId = currentCursorId ?? streamCursorId;\n\n    if (after === undefined) {\n      return {\n        rows: [],\n        delta: { limit, hasMore: false },\n        deltaCursor: this.encodeDeltaCursor(fallbackCursorId),\n      };\n    }\n\n    const afterCursorId = this.decodeDeltaCursor(after);\n    const matchingRows = rows\n      .flatMap(row => {\n        const cursorId = cursorIds.get(row);\n        if (cursorId === undefined || cursorId <= afterCursorId || !matches(row)) {\n          return [];\n        }\n\n        return [{ cursorId, row }];\n      })\n      .sort((a, b) => a.cursorId - b.cursorId)\n      .slice(0, limit + 1);\n\n    return this.buildDeltaResponse(matchingRows, limit, fallbackCursorId);\n  }\n\n  private getTraceCursorId(traceId: string, filters: ListTracesArgs['filters']): number | null {\n    const cursorId = this.db.traceCursorIds.get(traceId);\n    const traceEntry = this.db.traces.get(traceId);\n    if (cursorId === undefined || !traceEntry?.rootSpan || !this.traceMatchesFilters(traceEntry, filters)) {\n      return null;\n    }\n\n    return cursorId;\n  }\n\n  private getMaxTraceCursorId(filters: ListTracesArgs['filters']): number | null {\n    let maxCursorId: number | null = null;\n\n    for (const traceId of this.db.traceCursorIds.keys()) {\n      const cursorId = this.getTraceCursorId(traceId, filters);\n      if (cursorId === null) {\n        continue;\n      }\n\n      if (maxCursorId === null || cursorId > maxCursorId) {\n        maxCursorId = cursorId;\n      }\n    }\n\n    return maxCursorId;\n  }\n\n  private getMaxTraceStreamCursorId(): number | null {\n    let maxCursorId: number | null = null;\n\n    for (const cursorId of this.db.traceCursorIds.values()) {\n      if (maxCursorId === null || cursorId > maxCursorId) {\n        maxCursorId = cursorId;\n      }\n    }\n\n    return maxCursorId;\n  }\n\n  private getBranchCursorId(key: string, filters: ListBranchesArgs['filters']): number | null {\n    const cursorId = this.db.branchCursorIds.get(key);\n    if (cursorId === undefined) {\n      return null;\n    }\n\n    const [traceId, spanId] = key.split('\\u0000');\n    if (!traceId || !spanId) {\n      return null;\n    }\n\n    const traceEntry = this.db.traces.get(traceId);\n    const span = traceEntry?.spans[spanId];\n    if (!span || !this.spanMatchesBranchFilters(span, filters)) {\n      return null;\n    }\n\n    return cursorId;\n  }\n\n  private getMaxBranchCursorId(filters: ListBranchesArgs['filters']): number | null {\n    let maxCursorId: number | null = null;\n\n    for (const key of this.db.branchCursorIds.keys()) {\n      const cursorId = this.getBranchCursorId(key, filters);\n      if (cursorId === null) {\n        continue;\n      }\n\n      if (maxCursorId === null || cursorId > maxCursorId) {\n        maxCursorId = cursorId;\n      }\n    }\n\n    return maxCursorId;\n  }\n\n  private getMaxBranchStreamCursorId(): number | null {\n    let maxCursorId: number | null = null;\n\n    for (const cursorId of this.db.branchCursorIds.values()) {\n      if (maxCursorId === null || cursorId > maxCursorId) {\n        maxCursorId = cursorId;\n      }\n    }\n\n    return maxCursorId;\n  }\n\n  async createSpan(args: CreateSpanArgs): Promise<void> {\n    const { span } = args;\n    this.validateCreateSpan(span);\n    const now = new Date();\n    const record: SpanRecord = {\n      ...span,\n      createdAt: now,\n      updatedAt: now,\n    };\n\n    this.upsertSpanToTrace(record);\n  }\n\n  async batchCreateSpans(args: BatchCreateSpansArgs): Promise<void> {\n    const now = new Date();\n    for (const span of args.records) {\n      this.validateCreateSpan(span);\n      const record: SpanRecord = {\n        ...span,\n        createdAt: now,\n        updatedAt: now,\n      };\n      this.upsertSpanToTrace(record);\n    }\n  }\n\n  private validateCreateSpan(record: CreateSpanRecord): void {\n    if (!record.spanId) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_SPAN_ID_REQUIRED',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.SYSTEM,\n        text: 'Span ID is required for creating a span',\n      });\n    }\n\n    if (!record.traceId) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_TRACE_ID_REQUIRED',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.SYSTEM,\n        text: 'Trace ID is required for creating a span',\n      });\n    }\n  }\n\n  /**\n   * Inserts or updates a span in the trace and recomputes trace-level properties\n   */\n  private upsertSpanToTrace(span: SpanRecord): void {\n    const { traceId, spanId } = span;\n    let traceEntry = this.db.traces.get(traceId);\n\n    if (!traceEntry) {\n      traceEntry = {\n        spans: {},\n        rootSpan: null,\n        status: TraceStatus.RUNNING,\n        hasChildError: false,\n      };\n      this.db.traces.set(traceId, traceEntry);\n    }\n\n    traceEntry.spans[spanId] = span;\n\n    // Update root span if this is a root span\n    if (span.parentSpanId == null) {\n      traceEntry.rootSpan = span;\n    }\n\n    this.recomputeTraceProperties(traceEntry);\n    this.maybeRegisterTraceCursor(traceEntry);\n    this.maybeRegisterBranchCursor(span);\n  }\n\n  /**\n   * Recomputes derived trace properties from all spans\n   */\n  private recomputeTraceProperties(traceEntry: TraceEntry): void {\n    const spans = Object.values(traceEntry.spans);\n    if (spans.length === 0) return;\n\n    // Compute hasChildError (use != null to catch both null and undefined)\n    traceEntry.hasChildError = spans.some(s => s.error != null);\n\n    // Compute status from root span\n    const rootSpan = traceEntry.rootSpan;\n    if (rootSpan) {\n      if (rootSpan.error != null) {\n        traceEntry.status = TraceStatus.ERROR;\n      } else if (rootSpan.endedAt == null) {\n        traceEntry.status = TraceStatus.RUNNING;\n      } else {\n        traceEntry.status = TraceStatus.SUCCESS;\n      }\n    } else {\n      // No root span yet, consider it running\n      traceEntry.status = TraceStatus.RUNNING;\n    }\n  }\n\n  async getSpan(args: GetSpanArgs): Promise<GetSpanResponse | null> {\n    const { traceId, spanId } = args;\n    const traceEntry = this.db.traces.get(traceId);\n    if (!traceEntry) {\n      return null;\n    }\n\n    const span = traceEntry.spans[spanId];\n    if (!span) {\n      return null;\n    }\n\n    return { span };\n  }\n\n  async getSpans(args: GetSpansArgs): Promise<GetSpansResponse> {\n    const { traceId, spanIds } = args;\n    const traceEntry = this.db.traces.get(traceId);\n    if (!traceEntry) {\n      return { traceId, spans: [] };\n    }\n\n    const spans: SpanRecord[] = [];\n    for (const spanId of spanIds) {\n      const span = traceEntry.spans[spanId];\n      if (span) spans.push(span);\n    }\n\n    return { traceId, spans };\n  }\n\n  async getRootSpan(args: GetRootSpanArgs): Promise<GetRootSpanResponse | null> {\n    const { traceId } = args;\n    const traceEntry = this.db.traces.get(traceId);\n    if (!traceEntry || !traceEntry.rootSpan) {\n      return null;\n    }\n\n    return { span: traceEntry.rootSpan };\n  }\n\n  async getTrace(args: GetTraceArgs): Promise<GetTraceResponse | null> {\n    const { traceId } = args;\n    const traceEntry = this.db.traces.get(traceId);\n    if (!traceEntry) {\n      return null;\n    }\n\n    const spans = Object.values(traceEntry.spans);\n    if (spans.length === 0) {\n      return null;\n    }\n\n    // Sort spans by startedAt\n    spans.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());\n\n    return {\n      traceId,\n      spans,\n    };\n  }\n\n  async getTraceLight(args: GetTraceArgs): Promise<GetStructureResponse | null> {\n    const { traceId } = args;\n    const traceEntry = this.db.traces.get(traceId);\n    if (!traceEntry) {\n      return null;\n    }\n\n    const spans = Object.values(traceEntry.spans);\n    if (spans.length === 0) {\n      return null;\n    }\n\n    // Sort spans by startedAt\n    spans.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());\n\n    return {\n      traceId,\n      spans: spans.map(\n        (span): LightSpanRecord => ({\n          traceId: span.traceId,\n          spanId: span.spanId,\n          parentSpanId: span.parentSpanId,\n          name: span.name,\n          spanType: span.spanType,\n          isEvent: span.isEvent,\n          startedAt: span.startedAt,\n          endedAt: span.endedAt,\n          error: span.error,\n          entityType: span.entityType,\n          entityId: span.entityId,\n          entityName: span.entityName,\n          createdAt: span.createdAt,\n          updatedAt: span.updatedAt,\n        }),\n      ),\n    };\n  }\n\n  private getMatchingRootSpans(args: ListTracesArgs): {\n    paged: SpanRecord[];\n    total: number;\n    page: number;\n    perPage: number;\n    hasMore: boolean;\n  } {\n    const { filters, pagination, orderBy } = listTracesArgsSchema.parse(args);\n    const matchingRootSpans: SpanRecord[] = [];\n\n    for (const [, traceEntry] of this.db.traces) {\n      if (!traceEntry.rootSpan) continue;\n\n      if (this.traceMatchesFilters(traceEntry, filters)) {\n        matchingRootSpans.push(traceEntry.rootSpan);\n      }\n    }\n\n    const { field: sortField, direction: sortDirection } = orderBy;\n\n    matchingRootSpans.sort((a, b) => {\n      if (sortField === 'endedAt') {\n        const aVal = a.endedAt;\n        const bVal = b.endedAt;\n\n        // Handle nullish values (running spans with null endedAt)\n        // For endedAt DESC: NULLs FIRST (running spans on top when viewing newest)\n        // For endedAt ASC: NULLs LAST (running spans at end when viewing oldest)\n        if (aVal == null && bVal == null) return 0;\n        if (aVal == null) return sortDirection === 'DESC' ? -1 : 1;\n        if (bVal == null) return sortDirection === 'DESC' ? 1 : -1;\n\n        const diff = aVal.getTime() - bVal.getTime();\n        return sortDirection === 'DESC' ? -diff : diff;\n      } else {\n        // startedAt is never null (required field)\n        const diff = a.startedAt.getTime() - b.startedAt.getTime();\n        return sortDirection === 'DESC' ? -diff : diff;\n      }\n    });\n\n    // Apply pagination\n    const total = matchingRootSpans.length;\n    const { page, perPage } = pagination;\n    const start = page * perPage;\n    const end = start + perPage;\n\n    const paged = matchingRootSpans.slice(start, end);\n\n    return { paged, total, page, perPage, hasMore: end < total };\n  }\n\n  async listTraces(args: ListTracesArgs): Promise<ListTracesResponse> {\n    const { mode, filters, after, limit } = listTracesArgsSchema.parse(args);\n\n    if (mode === 'delta') {\n      this.assertDeltaPollingEnabled();\n      const currentCursorId = this.getMaxTraceCursorId(filters);\n      const fallbackCursorId = currentCursorId ?? this.getMaxTraceStreamCursorId();\n\n      if (after === undefined) {\n        return {\n          spans: [],\n          delta: { limit, hasMore: false },\n          deltaCursor: this.encodeDeltaCursor(fallbackCursorId),\n        };\n      }\n\n      const afterCursorId = this.decodeDeltaCursor(after);\n      const matchingRootSpans = Array.from(this.db.traceCursorIds.entries())\n        .flatMap(([traceId, cursorId]) => {\n          if (cursorId <= afterCursorId) {\n            return [];\n          }\n\n          const traceEntry = this.db.traces.get(traceId);\n          if (!traceEntry?.rootSpan || !this.traceMatchesFilters(traceEntry, filters)) {\n            return [];\n          }\n\n          return [{ cursorId, row: traceEntry.rootSpan }];\n        })\n        .sort((a, b) => a.cursorId - b.cursorId)\n        .slice(0, limit + 1);\n\n      const deltaResponse = this.buildDeltaResponse(matchingRootSpans, limit, fallbackCursorId);\n      return {\n        spans: toTraceSpans(deltaResponse.rows),\n        delta: deltaResponse.delta,\n        deltaCursor: deltaResponse.deltaCursor,\n      };\n    }\n\n    const { paged, total, page, perPage, hasMore } = this.getMatchingRootSpans(args);\n\n    return {\n      spans: toTraceSpans(paged),\n      pagination: { total, page, perPage, hasMore },\n      ...this.pageDeltaCursor(this.getMaxTraceCursorId(filters) ?? this.getMaxTraceStreamCursorId()),\n    };\n  }\n\n  async listTracesLight(args: ListTracesArgs): Promise<ListTracesLightResponse> {\n    const { paged, total, page, perPage, hasMore } = this.getMatchingRootSpans(args);\n\n    return {\n      spans: paged.map(span => ({\n        traceId: span.traceId,\n        spanId: span.spanId,\n        parentSpanId: span.parentSpanId,\n        name: span.name,\n        spanType: span.spanType,\n        isEvent: span.isEvent,\n        startedAt: span.startedAt,\n        endedAt: span.endedAt,\n        error: span.error,\n        entityType: span.entityType,\n        entityId: span.entityId,\n        entityName: span.entityName,\n        createdAt: span.createdAt,\n        updatedAt: span.updatedAt,\n      })),\n      pagination: { total, page, perPage, hasMore },\n    };\n  }\n\n  /**\n   * Check if a trace matches all provided filters\n   */\n  private traceMatchesFilters(traceEntry: TraceEntry, filters: ListTracesArgs['filters']): boolean {\n    if (!filters) return true;\n\n    const rootSpan = traceEntry.rootSpan;\n    if (!rootSpan) return false;\n\n    // Date range filters on startedAt (based on root span)\n    if (filters.startedAt) {\n      if (\n        filters.startedAt.start &&\n        (filters.startedAt.startExclusive\n          ? rootSpan.startedAt <= filters.startedAt.start\n          : rootSpan.startedAt < filters.startedAt.start)\n      ) {\n        return false;\n      }\n      if (\n        filters.startedAt.end &&\n        (filters.startedAt.endExclusive\n          ? rootSpan.startedAt >= filters.startedAt.end\n          : rootSpan.startedAt > filters.startedAt.end)\n      ) {\n        return false;\n      }\n    }\n\n    // Date range filters on endedAt (based on root span)\n    if (filters.endedAt) {\n      // If root span is still running (endedAt is nullish), it doesn't match endedAt filters\n      if (rootSpan.endedAt == null) {\n        return false;\n      }\n      if (\n        filters.endedAt.start &&\n        (filters.endedAt.startExclusive\n          ? rootSpan.endedAt <= filters.endedAt.start\n          : rootSpan.endedAt < filters.endedAt.start)\n      ) {\n        return false;\n      }\n      if (\n        filters.endedAt.end &&\n        (filters.endedAt.endExclusive\n          ? rootSpan.endedAt >= filters.endedAt.end\n          : rootSpan.endedAt > filters.endedAt.end)\n      ) {\n        return false;\n      }\n    }\n\n    // Span type filter (on root span)\n    if (filters.spanType !== undefined && rootSpan.spanType !== filters.spanType) {\n      return false;\n    }\n\n    // Entity filters\n    if (filters.entityType !== undefined && rootSpan.entityType !== filters.entityType) {\n      return false;\n    }\n    if (filters.entityId !== undefined && rootSpan.entityId !== filters.entityId) {\n      return false;\n    }\n    if (filters.entityName !== undefined && rootSpan.entityName !== filters.entityName) {\n      return false;\n    }\n    if (filters.entityVersionId !== undefined && rootSpan.entityVersionId !== filters.entityVersionId) {\n      return false;\n    }\n\n    // Experimentation\n    if (filters.experimentId !== undefined && rootSpan.experimentId !== filters.experimentId) {\n      return false;\n    }\n\n    // Identity & Tenancy filters\n    if (filters.userId !== undefined && rootSpan.userId !== filters.userId) {\n      return false;\n    }\n    if (filters.organizationId !== undefined && rootSpan.organizationId !== filters.organizationId) {\n      return false;\n    }\n    if (filters.resourceId !== undefined && rootSpan.resourceId !== filters.resourceId) {\n      return false;\n    }\n\n    // Correlation ID filters\n    if (filters.runId !== undefined && rootSpan.runId !== filters.runId) {\n      return false;\n    }\n    if (filters.sessionId !== undefined && rootSpan.sessionId !== filters.sessionId) {\n      return false;\n    }\n    if (filters.threadId !== undefined && rootSpan.threadId !== filters.threadId) {\n      return false;\n    }\n    if (filters.requestId !== undefined && rootSpan.requestId !== filters.requestId) {\n      return false;\n    }\n\n    // Deployment context filters\n    if (filters.environment !== undefined && rootSpan.environment !== filters.environment) {\n      return false;\n    }\n    if (filters.source !== undefined && rootSpan.source !== filters.source) {\n      return false;\n    }\n    if (filters.serviceName !== undefined && rootSpan.serviceName !== filters.serviceName) {\n      return false;\n    }\n\n    // Scope filter (partial match - all provided keys must match)\n    // Use != null to handle both null and undefined (nullish filter fields)\n    if (filters.scope != null && rootSpan.scope != null) {\n      for (const [key, value] of Object.entries(filters.scope)) {\n        if (!jsonValueEquals(rootSpan.scope[key], value)) {\n          return false;\n        }\n      }\n    } else if (filters.scope != null && rootSpan.scope == null) {\n      return false;\n    }\n\n    // Metadata filter (partial match - all provided keys must match)\n    // Use != null to handle both null and undefined (nullish filter fields)\n    if (filters.metadata != null && rootSpan.metadata != null) {\n      for (const [key, value] of Object.entries(filters.metadata)) {\n        if (!jsonValueEquals(rootSpan.metadata[key], value)) {\n          return false;\n        }\n      }\n    } else if (filters.metadata != null && rootSpan.metadata == null) {\n      return false;\n    }\n\n    // Tags filter (all provided tags must be present)\n    // Use != null to handle both null and undefined (nullish filter fields)\n    if (filters.tags != null && filters.tags.length > 0) {\n      if (rootSpan.tags == null) {\n        return false;\n      }\n      for (const tag of filters.tags) {\n        if (!rootSpan.tags.includes(tag)) {\n          return false;\n        }\n      }\n    }\n\n    // Derived status filter\n    if (filters.status !== undefined && traceEntry.status !== filters.status) {\n      return false;\n    }\n\n    // Has child error filter\n    if (filters.hasChildError !== undefined && traceEntry.hasChildError !== filters.hasChildError) {\n      return false;\n    }\n\n    return true;\n  }\n\n  async listBranches(args: ListBranchesArgs): Promise<ListBranchesResponse> {\n    const { mode, filters, pagination, orderBy, after, limit } = listBranchesArgsSchema.parse(args);\n\n    if (mode === 'delta') {\n      this.assertDeltaPollingEnabled();\n      const currentCursorId = this.getMaxBranchCursorId(filters);\n      const fallbackCursorId = currentCursorId ?? this.getMaxBranchStreamCursorId();\n\n      if (after === undefined) {\n        return {\n          branches: [],\n          delta: { limit, hasMore: false },\n          deltaCursor: this.encodeDeltaCursor(fallbackCursorId),\n        };\n      }\n\n      const afterCursorId = this.decodeDeltaCursor(after);\n      const matches = Array.from(this.db.branchCursorIds.entries())\n        .flatMap(([key, cursorId]) => {\n          if (cursorId <= afterCursorId) {\n            return [];\n          }\n\n          const [traceId, spanId] = key.split('\\u0000');\n          if (!traceId || !spanId) {\n            return [];\n          }\n\n          const traceEntry = this.db.traces.get(traceId);\n          const span = traceEntry?.spans[spanId];\n          if (!span || !this.spanMatchesBranchFilters(span, filters)) {\n            return [];\n          }\n\n          return [{ cursorId, row: span }];\n        })\n        .sort((a, b) => a.cursorId - b.cursorId)\n        .slice(0, limit + 1);\n\n      const deltaResponse = this.buildDeltaResponse(matches, limit, fallbackCursorId);\n      return {\n        branches: deltaResponse.rows.map(toTraceSpan),\n        delta: deltaResponse.delta,\n        deltaCursor: deltaResponse.deltaCursor,\n      };\n    }\n\n    const allowedSpanTypes = filters?.spanType\n      ? BRANCH_SPAN_TYPE_SET.has(filters.spanType)\n        ? new Set([filters.spanType])\n        : new Set<typeof filters.spanType>()\n      : BRANCH_SPAN_TYPE_SET;\n\n    const matches: SpanRecord[] = [];\n    for (const [, traceEntry] of this.db.traces) {\n      for (const span of Object.values(traceEntry.spans)) {\n        if (!allowedSpanTypes.has(span.spanType)) continue;\n        if (!this.spanMatchesBranchFilters(span, filters)) continue;\n        matches.push(span);\n      }\n    }\n\n    const { field: sortField, direction: sortDirection } = orderBy;\n    matches.sort((a, b) => {\n      if (sortField === 'endedAt') {\n        const aVal = a.endedAt;\n        const bVal = b.endedAt;\n        if (aVal == null && bVal == null) return 0;\n        if (aVal == null) return sortDirection === 'DESC' ? -1 : 1;\n        if (bVal == null) return sortDirection === 'DESC' ? 1 : -1;\n        const diff = aVal.getTime() - bVal.getTime();\n        return sortDirection === 'DESC' ? -diff : diff;\n      }\n      const diff = a.startedAt.getTime() - b.startedAt.getTime();\n      return sortDirection === 'DESC' ? -diff : diff;\n    });\n\n    const total = matches.length;\n    const { page, perPage } = pagination;\n    const start = page * perPage;\n    const end = start + perPage;\n    const paged = matches.slice(start, end);\n\n    return {\n      pagination: { total, page, perPage, hasMore: end < total },\n      branches: paged.map(toTraceSpan),\n      ...this.pageDeltaCursor(this.getMaxBranchCursorId(filters) ?? this.getMaxBranchStreamCursorId()),\n    };\n  }\n\n  /**\n   * Check if a single anchor span matches all provided branch filters. All\n   * predicates apply to the span itself (not the trace root) -- this is the\n   * key difference from {@link traceMatchesFilters}.\n   */\n  private spanMatchesBranchFilters(span: SpanRecord, filters: ListBranchesArgs['filters']): boolean {\n    if (!filters) return true;\n\n    if (filters.startedAt) {\n      if (filters.startedAt.start && span.startedAt < filters.startedAt.start) return false;\n      if (filters.startedAt.end && span.startedAt > filters.startedAt.end) return false;\n    }\n    if (filters.endedAt) {\n      if (span.endedAt == null) return false;\n      if (filters.endedAt.start && span.endedAt < filters.endedAt.start) return false;\n      if (filters.endedAt.end && span.endedAt > filters.endedAt.end) return false;\n    }\n\n    if (filters.traceId !== undefined && span.traceId !== filters.traceId) return false;\n\n    if (filters.entityType !== undefined && span.entityType !== filters.entityType) return false;\n    if (filters.entityId !== undefined && span.entityId !== filters.entityId) return false;\n    if (filters.entityName !== undefined && span.entityName !== filters.entityName) return false;\n    if (filters.entityVersionId !== undefined && span.entityVersionId !== filters.entityVersionId) return false;\n    if (filters.parentEntityType !== undefined && span.parentEntityType !== filters.parentEntityType) return false;\n    if (filters.parentEntityId !== undefined && span.parentEntityId !== filters.parentEntityId) return false;\n    if (filters.parentEntityName !== undefined && span.parentEntityName !== filters.parentEntityName) return false;\n    if (filters.parentEntityVersionId !== undefined && span.parentEntityVersionId !== filters.parentEntityVersionId)\n      return false;\n    if (filters.rootEntityType !== undefined && span.rootEntityType !== filters.rootEntityType) return false;\n    if (filters.rootEntityId !== undefined && span.rootEntityId !== filters.rootEntityId) return false;\n    if (filters.rootEntityName !== undefined && span.rootEntityName !== filters.rootEntityName) return false;\n    if (filters.rootEntityVersionId !== undefined && span.rootEntityVersionId !== filters.rootEntityVersionId)\n      return false;\n\n    if (filters.experimentId !== undefined && span.experimentId !== filters.experimentId) return false;\n    if (filters.userId !== undefined && span.userId !== filters.userId) return false;\n    if (filters.organizationId !== undefined && span.organizationId !== filters.organizationId) return false;\n    if (filters.resourceId !== undefined && span.resourceId !== filters.resourceId) return false;\n    if (filters.runId !== undefined && span.runId !== filters.runId) return false;\n    if (filters.sessionId !== undefined && span.sessionId !== filters.sessionId) return false;\n    if (filters.threadId !== undefined && span.threadId !== filters.threadId) return false;\n    if (filters.requestId !== undefined && span.requestId !== filters.requestId) return false;\n    if (filters.environment !== undefined && span.environment !== filters.environment) return false;\n    if (filters.source !== undefined && span.source !== filters.source) return false;\n    if (filters.serviceName !== undefined && span.serviceName !== filters.serviceName) return false;\n\n    if (filters.scope != null && span.scope != null) {\n      for (const [key, value] of Object.entries(filters.scope)) {\n        if (!jsonValueEquals(span.scope[key], value)) return false;\n      }\n    } else if (filters.scope != null && span.scope == null) {\n      return false;\n    }\n\n    if (filters.metadata != null && span.metadata != null) {\n      for (const [key, value] of Object.entries(filters.metadata)) {\n        if (!jsonValueEquals(span.metadata[key], value)) return false;\n      }\n    } else if (filters.metadata != null && span.metadata == null) {\n      return false;\n    }\n\n    if (filters.tags != null && filters.tags.length > 0) {\n      if (span.tags == null) return false;\n      for (const tag of filters.tags) {\n        if (!span.tags.includes(tag)) return false;\n      }\n    }\n\n    if (filters.status !== undefined) {\n      const spanStatus = toTraceSpan(span).status;\n      if (spanStatus !== filters.status) return false;\n    }\n\n    return true;\n  }\n\n  async updateSpan(args: UpdateSpanArgs): Promise<void> {\n    const { traceId, spanId, updates } = args;\n    const traceEntry = this.db.traces.get(traceId);\n\n    if (!traceEntry) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_UPDATE_SPAN_NOT_FOUND',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.SYSTEM,\n        text: 'Trace not found for span update',\n      });\n    }\n\n    const span = traceEntry.spans[spanId];\n    if (!span) {\n      throw new MastraError({\n        id: 'OBSERVABILITY_UPDATE_SPAN_NOT_FOUND',\n        domain: ErrorDomain.MASTRA_OBSERVABILITY,\n        category: ErrorCategory.SYSTEM,\n        text: 'Span not found for update',\n      });\n    }\n\n    const updatedSpan: SpanRecord = {\n      ...span,\n      ...updates,\n      updatedAt: new Date(),\n    };\n\n    traceEntry.spans[spanId] = updatedSpan;\n\n    // Update root span reference if this is the root span\n    if (updatedSpan.parentSpanId == null) {\n      traceEntry.rootSpan = updatedSpan;\n    }\n\n    this.recomputeTraceProperties(traceEntry);\n    this.maybeRegisterTraceCursor(traceEntry);\n    this.maybeRegisterBranchCursor(updatedSpan);\n  }\n\n  async batchUpdateSpans(args: BatchUpdateSpansArgs): Promise<void> {\n    for (const record of args.records) {\n      await this.updateSpan(record);\n    }\n  }\n\n  async batchDeleteTraces(args: BatchDeleteTracesArgs): Promise<void> {\n    for (const traceId of args.traceIds) {\n      const traceEntry = this.db.traces.get(traceId);\n      if (traceEntry) {\n        this.db.traceCursorIds.delete(traceId);\n        for (const spanId of Object.keys(traceEntry.spans)) {\n          this.db.branchCursorIds.delete(this.createBranchCursorKey(traceId, spanId));\n        }\n      }\n      this.db.traces.delete(traceId);\n    }\n  }\n\n  // ============================================================================\n  // Metrics\n  // ============================================================================\n\n  async batchCreateMetrics(args: BatchCreateMetricsArgs): Promise<void> {\n    for (const metric of args.metrics) {\n      const record = metric as MetricRecord;\n      this.upsertByIdField(this.db.metricRecords, this.db.metricCursorIds, record, 'metricId');\n    }\n  }\n\n  async listMetrics(args: ListMetricsArgs): Promise<ListMetricsResponse> {\n    const { mode, filters, pagination, orderBy, after, limit } = listMetricsArgsSchema.parse(args);\n\n    if (mode === 'delta') {\n      this.assertDeltaPollingEnabled();\n      const deltaResponse = this.listAppendOnlyDelta(\n        this.db.metricRecords,\n        this.db.metricCursorIds,\n        metric => this.metricMatchesFilters(metric, filters as Record<string, unknown>),\n        after,\n        limit,\n      );\n\n      return {\n        metrics: deltaResponse.rows,\n        delta: deltaResponse.delta,\n        deltaCursor: deltaResponse.deltaCursor,\n      };\n    }\n\n    let matching = this.filterMetrics(filters as Record<string, unknown>);\n\n    const dir = orderBy.direction === 'DESC' ? -1 : 1;\n    matching.sort((a, b) => dir * (a.timestamp.getTime() - b.timestamp.getTime()));\n\n    const total = matching.length;\n    const page = Number(pagination.page);\n    const perPage = Number(pagination.perPage);\n    const start = page * perPage;\n\n    return {\n      metrics: matching.slice(start, start + perPage),\n      pagination: { total, page, perPage, hasMore: start + perPage < total },\n      ...this.pageDeltaCursor(\n        this.maxMatchingCursorId(this.db.metricRecords, this.db.metricCursorIds, metric =>\n          this.metricMatchesFilters(metric, filters as Record<string, unknown>),\n        ),\n      ),\n    };\n  }\n\n  private filterMetrics(filters?: Record<string, unknown>): MetricRecord[] {\n    if (!filters) return [...this.db.metricRecords];\n    return this.db.metricRecords.filter(metric => this.metricMatchesFilters(metric, filters));\n  }\n\n  private metricMatchesFilters(m: MetricRecord, filters?: Record<string, unknown>): boolean {\n    if (!filters) return true;\n    if (filters.timestamp) {\n      const ts = filters.timestamp as { start?: Date; end?: Date; startExclusive?: boolean; endExclusive?: boolean };\n      if (ts.start && (ts.startExclusive ? m.timestamp <= ts.start : m.timestamp < ts.start)) return false;\n      if (ts.end && (ts.endExclusive ? m.timestamp >= ts.end : m.timestamp > ts.end)) return false;\n    }\n    if (filters.name != null) {\n      if (!(filters.name as string[]).includes(m.name)) return false;\n    }\n    if (filters.traceId !== undefined && m.traceId !== filters.traceId) return false;\n    if (Array.isArray(filters.traceIds) && !filters.traceIds.includes(m.traceId)) return false;\n    if (filters.spanId !== undefined && m.spanId !== filters.spanId) return false;\n    if (filters.provider !== undefined && m.provider !== filters.provider) return false;\n    if (filters.model !== undefined && m.model !== filters.model) return false;\n    if (filters.costUnit !== undefined && m.costUnit !== filters.costUnit) return false;\n    if (filters.entityType !== undefined && m.entityType !== filters.entityType) return false;\n    if (filters.entityName !== undefined && m.entityName !== filters.entityName) return false;\n    if (filters.entityVersionId !== undefined && m.entityVersionId !== filters.entityVersionId) return false;\n    if (filters.parentEntityVersionId !== undefined && m.parentEntityVersionId !== filters.parentEntityVersionId)\n      return false;\n    if (filters.rootEntityVersionId !== undefined && m.rootEntityVersionId !== filters.rootEntityVersionId)\n      return false;\n    if (filters.userId !== undefined && m.userId !== filters.userId) return false;\n    if (filters.organizationId !== undefined && m.organizationId !== filters.organizationId) return false;\n    if (filters.resourceId !== undefined && m.resourceId !== filters.resourceId) return false;\n    if (filters.runId !== undefined && m.runId !== filters.runId) return false;\n    if (filters.sessionId !== undefined && m.sessionId !== filters.sessionId) return false;\n    if (filters.threadId !== undefined && m.threadId !== filters.threadId) return false;\n    if (filters.requestId !== undefined && m.requestId !== filters.requestId) return false;\n    if (filters.experimentId !== undefined && m.experimentId !== filters.experimentId) return false;\n    if (filters.serviceName !== undefined && m.serviceName !== filters.serviceName) return false;\n    if (filters.environment !== undefined && m.environment !== filters.environment) return false;\n    const metricExecutionSource = m.executionSource ?? m.source ?? null;\n    if (filters.executionSource !== undefined && metricExecutionSource !== filters.executionSource) return false;\n    if (filters.source !== undefined && metricExecutionSource !== filters.source) return false;\n    if (filters.parentEntityType !== undefined && m.parentEntityType !== filters.parentEntityType) return false;\n    if (filters.parentEntityName !== undefined && m.parentEntityName !== filters.parentEntityName) return false;\n    if (filters.rootEntityType !== undefined && m.rootEntityType !== filters.rootEntityType) return false;\n    if (filters.rootEntityName !== undefined && m.rootEntityName !== filters.rootEntityName) return false;\n    if (filters.tags != null && Array.isArray(filters.tags) && filters.tags.length > 0) {\n      if (m.tags == null) return false;\n      for (const tag of filters.tags) {\n        if (!m.tags.includes(tag)) return false;\n      }\n    }\n    if (filters.labels) {\n      const labelFilters = filters.labels as Record<string, string>;\n      for (const [k, v] of Object.entries(labelFilters)) {\n        if (m.labels[k] !== v) return false;\n      }\n    }\n    return true;\n  }\n\n  private aggregate(\n    values: number[],\n    type: AggregationType,\n    timestamps?: number[],\n    distinctValues?: Array<string | number | null | undefined>,\n  ): number | null {\n    if (type === 'count_distinct') {\n      if (!distinctValues) return 0;\n      const set = new Set<string | number>();\n      for (const v of distinctValues) {\n        if (v === null || v === undefined) continue;\n        set.add(v);\n      }\n      return set.size;\n    }\n    if (values.length === 0) return null;\n    switch (type) {\n      case 'sum':\n        return values.reduce((a, b) => a + b, 0);\n      case 'avg':\n        return values.reduce((a, b) => a + b, 0) / values.length;\n      case 'min':\n        return Math.min(...values);\n      case 'max':\n        return Math.max(...values);\n      case 'count':\n        return values.length;\n      case 'last': {\n        if (!timestamps || timestamps.length !== values.length) {\n          return values[values.length - 1]!;\n        }\n\n        let latestIndex = 0;\n        let latestTimestamp = timestamps[0]!;\n\n        for (let i = 1; i < timestamps.length; i++) {\n          const timestamp = timestamps[i]!;\n          if (timestamp >= latestTimestamp) {\n            latestTimestamp = timestamp;\n            latestIndex = i;\n          }\n        }\n\n        return values[latestIndex]!;\n      }\n      default:\n        return values.reduce((a, b) => a + b, 0);\n    }\n  }\n\n  private extractDistinctValues(\n    records: MetricRecord[],\n    distinctColumn: string | undefined,\n  ): Array<string | number | null | undefined> | undefined {\n    if (!distinctColumn) return undefined;\n    return records.map(r => {\n      const raw = (r as unknown as Record<string, unknown>)[distinctColumn];\n      if (raw === null || raw === undefined) return null;\n      if (typeof raw === 'string' || typeof raw === 'number') return raw;\n      return String(raw);\n    });\n  }\n\n  private interpolatePercentile(sortedValues: number[], percentile: number): number {\n    if (sortedValues.length === 0) return 0;\n\n    const position = percentile * (sortedValues.length - 1);\n    const lowerIndex = Math.floor(position);\n    const upperIndex = Math.ceil(position);\n    const lowerValue = sortedValues[lowerIndex]!;\n    const upperValue = sortedValues[upperIndex]!;\n\n    if (lowerIndex === upperIndex) {\n      return lowerValue;\n    }\n\n    return lowerValue + (upperValue - lowerValue) * (position - lowerIndex);\n  }\n\n  /**\n   * Cost is returned alongside value-based OLAP results so callers can derive\n   * token and monetary views from the same filtered scan.\n   */\n  private summarizeCost(records: MetricRecord[]): { estimatedCost: number | null; costUnit: string | null } {\n    const costValues = records\n      .map(record => record.estimatedCost)\n      .filter((value): value is number => typeof value === 'number' && Number.isFinite(value));\n    const costUnits = new Set(\n      records.map(record => record.costUnit).filter((unit): unit is string => typeof unit === 'string'),\n    );\n\n    return {\n      estimatedCost: costValues.length > 0 ? costValues.reduce((sum, value) => sum + value, 0) : null,\n      costUnit: costUnits.size === 1 ? Array.from(costUnits)[0]! : null,\n    };\n  }\n\n  async getMetricAggregate(args: GetMetricAggregateArgs): Promise<GetMetricAggregateResponse> {\n    const names = Array.isArray(args.name) ? args.name : [args.name];\n    const filtered = this.filterMetrics(args.filters as Record<string, unknown>).filter(m => names.includes(m.name));\n    const value = this.aggregate(\n      filtered.map(m => m.value),\n      args.aggregation,\n      undefined,\n      this.extractDistinctValues(filtered, args.distinctColumn),\n    );\n    const costSummary = this.summarizeCost(filtered);\n\n    if (args.comparePeriod && args.filters?.timestamp) {\n      const ts = args.filters.timestamp;\n      if (ts.start && ts.end) {\n        const duration = ts.end.getTime() - ts.start.getTime();\n        let prevStart: Date;\n        let prevEnd: Date;\n\n        switch (args.comparePeriod) {\n          case 'previous_period':\n            prevStart = new Date(ts.start.getTime() - duration);\n            prevEnd = new Date(ts.end.getTime() - duration);\n            break;\n          case 'previous_day':\n            prevStart = new Date(ts.start.getTime() - 86400000);\n            prevEnd = new Date(ts.end.getTime() - 86400000);\n            break;\n          case 'previous_week':\n            prevStart = new Date(ts.start.getTime() - 604800000);\n            prevEnd = new Date(ts.end.getTime() - 604800000);\n            break;\n        }\n\n        const prevFiltered = this.filterMetrics({\n          ...(args.filters as Record<string, unknown>),\n          timestamp: { ...ts, start: prevStart, end: prevEnd },\n        }).filter(m => names.includes(m.name));\n        const previousValue = this.aggregate(\n          prevFiltered.map(m => m.value),\n          args.aggregation,\n          undefined,\n          this.extractDistinctValues(prevFiltered, args.distinctColumn),\n        );\n        const previousCostSummary = this.summarizeCost(prevFiltered);\n\n        let changePercent: number | null = null;\n        if (previousValue !== null && previousValue !== 0 && value !== null) {\n          changePercent = ((value - previousValue) / Math.abs(previousValue)) * 100;\n        }\n\n        let costChangePercent: number | null = null;\n        if (\n          previousCostSummary.estimatedCost !== null &&\n          previousCostSummary.estimatedCost !== 0 &&\n          costSummary.estimatedCost !== null\n        ) {\n          costChangePercent =\n            ((costSummary.estimatedCost - previousCostSummary.estimatedCost) /\n              Math.abs(previousCostSummary.estimatedCost)) *\n            100;\n        }\n\n        return {\n          value,\n          estimatedCost: costSummary.estimatedCost,\n          costUnit: costSummary.costUnit,\n          previousValue,\n          previousEstimatedCost: previousCostSummary.estimatedCost,\n          changePercent,\n          costChangePercent,\n        };\n      }\n    }\n\n    return { value, estimatedCost: costSummary.estimatedCost, costUnit: costSummary.costUnit };\n  }\n\n  async getMetricBreakdown(args: GetMetricBreakdownArgs): Promise<GetMetricBreakdownResponse> {\n    const names = Array.isArray(args.name) ? args.name : [args.name];\n    const filtered = this.filterMetrics(args.filters as Record<string, unknown>).filter(m => names.includes(m.name));\n\n    const groupMap = new Map<string, MetricRecord[]>();\n    for (const m of filtered) {\n      const dims: Record<string, string | null> = {};\n      for (const col of args.groupBy) {\n        dims[col] = ((m as Record<string, unknown>)[col] as string | null | undefined) ?? m.labels[col] ?? null;\n      }\n      const key = JSON.stringify(dims);\n      if (!groupMap.has(key)) groupMap.set(key, []);\n      groupMap.get(key)!.push(m);\n    }\n\n    const groups = Array.from(groupMap.entries()).map(([key, records]) => {\n      const costSummary = this.summarizeCost(records);\n      return {\n        dimensions: JSON.parse(key) as Record<string, string | null>,\n        value:\n          this.aggregate(\n            records.map(record => record.value),\n            args.aggregation,\n            undefined,\n            this.extractDistinctValues(records, args.distinctColumn),\n          ) ?? 0,\n        estimatedCost: costSummary.estimatedCost,\n        costUnit: costSummary.costUnit,\n      };\n    });\n\n    const direction = args.orderDirection === 'ASC' ? 1 : -1;\n    groups.sort((a, b) => (a.value - b.value) * direction);\n\n    const limited = typeof args.limit === 'number' ? groups.slice(0, args.limit) : groups;\n    return { groups: limited };\n  }\n\n  async getMetricTimeSeries(args: GetMetricTimeSeriesArgs): Promise<GetMetricTimeSeriesResponse> {\n    const names = Array.isArray(args.name) ? args.name : [args.name];\n    const filtered = this.filterMetrics(args.filters as Record<string, unknown>).filter(m => names.includes(m.name));\n\n    const intervalMs = this.intervalToMs(args.interval);\n\n    if (args.groupBy && args.groupBy.length > 0) {\n      // Keep colliding display names (label values containing `|`) on separate\n      // series by keying on the original value tuple instead of the joined\n      // display string.\n      const seriesMap = new Map<string, { displayName: string; buckets: Map<number, MetricRecord[]> }>();\n      for (const m of filtered) {\n        const values = args.groupBy.map(col => String((m as Record<string, unknown>)[col] ?? m.labels[col] ?? ''));\n        const key = JSON.stringify(values);\n        const displayName = values.join('|');\n        let entry = seriesMap.get(key);\n        if (!entry) {\n          entry = { displayName, buckets: new Map() };\n          seriesMap.set(key, entry);\n        }\n        const bucket = Math.floor(m.timestamp.getTime() / intervalMs) * intervalMs;\n        if (!entry.buckets.has(bucket)) entry.buckets.set(bucket, []);\n        entry.buckets.get(bucket)!.push(m);\n      }\n\n      return {\n        series: Array.from(seriesMap.values()).map(({ displayName, buckets }) => {\n          const seriesRecords = Array.from(buckets.values()).flat();\n          const costSummary = this.summarizeCost(seriesRecords);\n          return {\n            name: displayName,\n            costUnit: costSummary.costUnit,\n            points: Array.from(buckets.entries())\n              .sort(([a], [b]) => a - b)\n              .map(([ts, records]) => ({\n                timestamp: new Date(ts),\n                value:\n                  this.aggregate(\n                    records.map(record => record.value),\n                    args.aggregation,\n                    undefined,\n                    this.extractDistinctValues(records, args.distinctColumn),\n                  ) ?? 0,\n                estimatedCost: this.summarizeCost(records).estimatedCost,\n              })),\n          };\n        }),\n      };\n    }\n\n    const bucketMap = new Map<number, MetricRecord[]>();\n    for (const m of filtered) {\n      const bucket = Math.floor(m.timestamp.getTime() / intervalMs) * intervalMs;\n      if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n      bucketMap.get(bucket)!.push(m);\n    }\n\n    const metricName = Array.isArray(args.name) ? args.name.join(',') : args.name;\n    const costSummary = this.summarizeCost(filtered);\n    return {\n      series: [\n        {\n          name: metricName,\n          costUnit: costSummary.costUnit,\n          points: Array.from(bucketMap.entries())\n            .sort(([a], [b]) => a - b)\n            .map(([ts, records]) => ({\n              timestamp: new Date(ts),\n              value:\n                this.aggregate(\n                  records.map(record => record.value),\n                  args.aggregation,\n                  undefined,\n                  this.extractDistinctValues(records, args.distinctColumn),\n                ) ?? 0,\n              estimatedCost: this.summarizeCost(records).estimatedCost,\n            })),\n        },\n      ],\n    };\n  }\n\n  async getMetricPercentiles(args: GetMetricPercentilesArgs): Promise<GetMetricPercentilesResponse> {\n    const filtered = this.filterMetrics(args.filters as Record<string, unknown>).filter(m => m.name === args.name);\n    const intervalMs = this.intervalToMs(args.interval);\n\n    const bucketMap = new Map<number, number[]>();\n    for (const m of filtered) {\n      const bucket = Math.floor(m.timestamp.getTime() / intervalMs) * intervalMs;\n      if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n      bucketMap.get(bucket)!.push(m.value);\n    }\n\n    const sortedBuckets = Array.from(bucketMap.entries()).sort(([a], [b]) => a - b);\n\n    return {\n      series: args.percentiles.map(p => ({\n        percentile: p,\n        points: sortedBuckets.map(([ts, values]) => {\n          const sorted = [...values].sort((a, b) => a - b);\n          const idx = Math.min(Math.floor(p * sorted.length), sorted.length - 1);\n          return { timestamp: new Date(ts), value: sorted[idx] ?? 0 };\n        }),\n      })),\n    };\n  }\n\n  private intervalToMs(interval: string): number {\n    switch (interval) {\n      case '1m':\n        return 60_000;\n      case '5m':\n        return 300_000;\n      case '15m':\n        return 900_000;\n      case '1h':\n        return 3_600_000;\n      case '1d':\n        return 86_400_000;\n      default:\n        return 3_600_000;\n    }\n  }\n\n  // ============================================================================\n  // Discovery / Metadata Methods\n  // ============================================================================\n\n  async getMetricNames(args: GetMetricNamesArgs): Promise<GetMetricNamesResponse> {\n    const nameSet = new Set<string>();\n    for (const m of this.db.metricRecords) {\n      if (args.prefix && !m.name.startsWith(args.prefix)) continue;\n      nameSet.add(m.name);\n    }\n    let names = Array.from(nameSet).sort();\n    if (args.limit) names = names.slice(0, args.limit);\n    return { names };\n  }\n\n  async getMetricLabelKeys(args: GetMetricLabelKeysArgs): Promise<GetMetricLabelKeysResponse> {\n    const keySet = new Set<string>();\n    for (const m of this.db.metricRecords) {\n      if (m.name !== args.metricName) continue;\n      for (const key of Object.keys(m.labels)) {\n        keySet.add(key);\n      }\n    }\n    return { keys: Array.from(keySet).sort() };\n  }\n\n  async getMetricLabelValues(args: GetMetricLabelValuesArgs): Promise<GetMetricLabelValuesResponse> {\n    const valueSet = new Set<string>();\n    for (const m of this.db.metricRecords) {\n      if (m.name !== args.metricName) continue;\n      const val = m.labels[args.labelKey];\n      if (val === undefined) continue;\n      if (args.prefix && !val.startsWith(args.prefix)) continue;\n      valueSet.add(val);\n    }\n    let values = Array.from(valueSet).sort();\n    if (args.limit) values = values.slice(0, args.limit);\n    return { values };\n  }\n\n  /**\n   * Iterates every record across spans, logs, and metrics with shared\n   * context fields. Discovery operations need to surface entities and\n   * dimensions emitted on any observability surface, not just spans.\n   */\n  private *iterateObservabilityContextRecords(): Generator<{\n    entityType?: string | null;\n    entityName?: string | null;\n    serviceName?: string | null;\n    environment?: string | null;\n    tags?: readonly string[] | null;\n  }> {\n    for (const [, traceEntry] of this.db.traces) {\n      for (const span of Object.values(traceEntry.spans)) {\n        yield span;\n      }\n    }\n    for (const log of this.db.logRecords) {\n      yield log as unknown as { entityType?: string | null };\n    }\n    for (const metric of this.db.metricRecords) {\n      yield metric as unknown as { entityType?: string | null };\n    }\n  }\n\n  async getEntityTypes(_args: GetEntityTypesArgs): Promise<GetEntityTypesResponse> {\n    const validTypes = new Set(Object.values(EntityType));\n    const typeSet = new Set<EntityType>();\n    for (const record of this.iterateObservabilityContextRecords()) {\n      if (record.entityType && validTypes.has(record.entityType as EntityType)) {\n        typeSet.add(record.entityType as EntityType);\n      }\n    }\n    return { entityTypes: Array.from(typeSet).sort() };\n  }\n\n  async getEntityNames(args: GetEntityNamesArgs): Promise<GetEntityNamesResponse> {\n    const nameSet = new Set<string>();\n    for (const record of this.iterateObservabilityContextRecords()) {\n      if (!record.entityName) continue;\n      if (args.entityType && record.entityType !== args.entityType) continue;\n      nameSet.add(record.entityName);\n    }\n    return { names: Array.from(nameSet).sort() };\n  }\n\n  async getServiceNames(_args: GetServiceNamesArgs): Promise<GetServiceNamesResponse> {\n    const nameSet = new Set<string>();\n    for (const record of this.iterateObservabilityContextRecords()) {\n      if (record.serviceName) nameSet.add(record.serviceName);\n    }\n    return { serviceNames: Array.from(nameSet).sort() };\n  }\n\n  async getEnvironments(_args: GetEnvironmentsArgs): Promise<GetEnvironmentsResponse> {\n    const envSet = new Set<string>();\n    for (const record of this.iterateObservabilityContextRecords()) {\n      if (record.environment) envSet.add(record.environment);\n    }\n    return { environments: Array.from(envSet).sort() };\n  }\n\n  async getTags(args: GetTagsArgs): Promise<GetTagsResponse> {\n    const tagSet = new Set<string>();\n    for (const record of this.iterateObservabilityContextRecords()) {\n      if (!record.tags) continue;\n      if (args.entityType && record.entityType !== args.entityType) continue;\n      for (const tag of record.tags) {\n        tagSet.add(tag);\n      }\n    }\n    return { tags: Array.from(tagSet).sort() };\n  }\n\n  // ============================================================================\n  // Logs\n  // ============================================================================\n\n  async batchCreateLogs(args: BatchCreateLogsArgs): Promise<void> {\n    for (const log of args.logs) {\n      const record = log as LogRecord;\n      this.upsertByIdField(this.db.logRecords, this.db.logCursorIds, record, 'logId');\n    }\n  }\n\n  async listLogs(args: ListLogsArgs): Promise<ListLogsResponse> {\n    const { mode, filters, pagination, orderBy, after, limit } = listLogsArgsSchema.parse(args);\n\n    if (mode === 'delta') {\n      this.assertDeltaPollingEnabled();\n      const deltaResponse = this.listAppendOnlyDelta(\n        this.db.logRecords,\n        this.db.logCursorIds,\n        log => this.logMatchesFilters(log, filters),\n        after,\n        limit,\n      );\n\n      return {\n        logs: deltaResponse.rows,\n        delta: deltaResponse.delta,\n        deltaCursor: deltaResponse.deltaCursor,\n      };\n    }\n\n    let matching = this.db.logRecords.filter(log => this.logMatchesFilters(log, filters));\n\n    // Sort\n    const dir = orderBy.direction === 'DESC' ? -1 : 1;\n    matching.sort((a, b) => dir * (a.timestamp.getTime() - b.timestamp.getTime()));\n\n    // Paginate\n    const total = matching.length;\n    const page = Number(pagination.page);\n    const perPage = Number(pagination.perPage);\n    const start = page * perPage;\n\n    return {\n      logs: matching.slice(start, start + perPage),\n      pagination: { total, page, perPage, hasMore: start + perPage < total },\n      ...this.pageDeltaCursor(\n        this.maxMatchingCursorId(this.db.logRecords, this.db.logCursorIds, log => this.logMatchesFilters(log, filters)),\n      ),\n    };\n  }\n\n  private logMatchesFilters(log: LogRecord, filters?: ListLogsArgs['filters']): boolean {\n    if (!filters) return true;\n\n    if (filters.timestamp) {\n      if (\n        filters.timestamp.start &&\n        (filters.timestamp.startExclusive\n          ? log.timestamp <= filters.timestamp.start\n          : log.timestamp < filters.timestamp.start)\n      ) {\n        return false;\n      }\n      if (\n        filters.timestamp.end &&\n        (filters.timestamp.endExclusive\n          ? log.timestamp >= filters.timestamp.end\n          : log.timestamp > filters.timestamp.end)\n      ) {\n        return false;\n      }\n    }\n    if (filters.level !== undefined) {\n      const levels = Array.isArray(filters.level) ? filters.level : [filters.level];\n      if (!levels.includes(log.level)) return false;\n    }\n    if (filters.traceId !== undefined && log.traceId !== filters.traceId) return false;\n    if (filters.spanId !== undefined && log.spanId !== filters.spanId) return false;\n    if (filters.entityType !== undefined && log.entityType !== filters.entityType) return false;\n    if (filters.entityName !== undefined && log.entityName !== filters.entityName) return false;\n    if (filters.entityVersionId !== undefined && log.entityVersionId !== filters.entityVersionId) return false;\n    if (filters.parentEntityVersionId !== undefined && log.parentEntityVersionId !== filters.parentEntityVersionId)\n      return false;\n    if (filters.rootEntityVersionId !== undefined && log.rootEntityVersionId !== filters.rootEntityVersionId)\n      return false;\n    if (filters.userId !== undefined && log.userId !== filters.userId) return false;\n    if (filters.organizationId !== undefined && log.organizationId !== filters.organizationId) return false;\n    if (filters.resourceId !== undefined && log.resourceId !== filters.resourceId) return false;\n    if (filters.runId !== undefined && log.runId !== filters.runId) return false;\n    if (filters.sessionId !== undefined && log.sessionId !== filters.sessionId) return false;\n    if (filters.threadId !== undefined && log.threadId !== filters.threadId) return false;\n    if (filters.requestId !== undefined && log.requestId !== filters.requestId) return false;\n    if (filters.parentEntityType !== undefined && log.parentEntityType !== filters.parentEntityType) return false;\n    if (filters.parentEntityName !== undefined && log.parentEntityName !== filters.parentEntityName) return false;\n    if (filters.rootEntityType !== undefined && log.rootEntityType !== filters.rootEntityType) return false;\n    if (filters.rootEntityName !== undefined && log.rootEntityName !== filters.rootEntityName) return false;\n    if (filters.serviceName !== undefined && log.serviceName !== filters.serviceName) return false;\n    if (filters.environment !== undefined && log.environment !== filters.environment) return false;\n    const logExecutionSource = log.executionSource ?? log.source ?? null;\n    if (filters.executionSource !== undefined && logExecutionSource !== filters.executionSource) return false;\n    if (filters.source !== undefined && logExecutionSource !== filters.source) return false;\n    if (filters.experimentId !== undefined && log.experimentId !== filters.experimentId) return false;\n    if (filters.tags != null && filters.tags.length > 0) {\n      if (log.tags == null) return false;\n      for (const tag of filters.tags) {\n        if (!log.tags.includes(tag)) return false;\n      }\n    }\n\n    return true;\n  }\n\n  // ============================================================================\n  // Scores\n  // ============================================================================\n\n  async createScore(args: CreateScoreArgs): Promise<void> {\n    const scoreSource = args.score.scoreSource ?? args.score.source ?? null;\n    const record = {\n      ...args.score,\n      scoreSource,\n      source: scoreSource,\n    } as ScoreRecord;\n    this.upsertByIdField(this.db.scoreRecords, this.db.scoreCursorIds, record, 'scoreId');\n  }\n\n  async batchCreateScores(args: BatchCreateScoresArgs): Promise<void> {\n    for (const score of args.scores) {\n      const scoreSource = score.scoreSource ?? score.source ?? null;\n      const record = {\n        ...score,\n        scoreSource,\n        source: scoreSource,\n      } as ScoreRecord;\n      this.upsertByIdField(this.db.scoreRecords, this.db.scoreCursorIds, record, 'scoreId');\n    }\n  }\n\n  async listScores(args: ListScoresArgs): Promise<ListScoresResponse> {\n    const { mode, filters, pagination, orderBy, after, limit } = listScoresArgsSchema.parse(args);\n\n    if (mode === 'delta') {\n      this.assertDeltaPollingEnabled();\n      const deltaResponse = this.listAppendOnlyDelta(\n        this.db.scoreRecords,\n        this.db.scoreCursorIds,\n        score => this.scoreMatchesFilters(score, filters),\n        after,\n        limit,\n      );\n\n      return {\n        scores: deltaResponse.rows,\n        delta: deltaResponse.delta,\n        deltaCursor: deltaResponse.deltaCursor,\n      };\n    }\n\n    let matching = this.db.scoreRecords.filter(score => this.scoreMatchesFilters(score, filters));\n\n    // Sort\n    const dir = orderBy.direction === 'DESC' ? -1 : 1;\n    if (orderBy.field === 'score') {\n      matching.sort((a, b) => dir * (a.score - b.score));\n    } else {\n      matching.sort((a, b) => dir * (a.timestamp.getTime() - b.timestamp.getTime()));\n    }\n\n    // Paginate\n    const total = matching.length;\n    const page = Number(pagination.page);\n    const perPage = Number(pagination.perPage);\n    const start = page * perPage;\n\n    return {\n      scores: matching.slice(start, start + perPage),\n      pagination: { total, page, perPage, hasMore: start + perPage < total },\n      ...this.pageDeltaCursor(\n        this.maxMatchingCursorId(this.db.scoreRecords, this.db.scoreCursorIds, score =>\n          this.scoreMatchesFilters(score, filters),\n        ),\n      ),\n    };\n  }\n\n  async getScoreById(scoreId: string): Promise<ScoreRecord | null> {\n    return this.db.scoreRecords.find(score => score.scoreId === scoreId) ?? null;\n  }\n\n  private scoreMatchesFilters(score: ScoreRecord, filters?: ListScoresArgs['filters']): boolean {\n    if (!filters) return true;\n\n    if (filters.timestamp) {\n      if (filters.timestamp.start && score.timestamp < filters.timestamp.start) return false;\n      if (filters.timestamp.end && score.timestamp > filters.timestamp.end) return false;\n    }\n    if (filters.traceId !== undefined && score.traceId !== filters.traceId) return false;\n    if (filters.spanId !== undefined && score.spanId !== filters.spanId) return false;\n    if (filters.entityType !== undefined && score.entityType !== filters.entityType) return false;\n    if (filters.entityName !== undefined && score.entityName !== filters.entityName) return false;\n    if (filters.entityVersionId !== undefined && score.entityVersionId !== filters.entityVersionId) return false;\n    if (filters.parentEntityVersionId !== undefined && score.parentEntityVersionId !== filters.parentEntityVersionId)\n      return false;\n    if (filters.rootEntityVersionId !== undefined && score.rootEntityVersionId !== filters.rootEntityVersionId)\n      return false;\n    if (filters.userId !== undefined && score.userId !== filters.userId) return false;\n    if (filters.organizationId !== undefined && score.organizationId !== filters.organizationId) return false;\n    if (filters.resourceId !== undefined && score.resourceId !== filters.resourceId) return false;\n    if (filters.runId !== undefined && score.runId !== filters.runId) return false;\n    if (filters.sessionId !== undefined && score.sessionId !== filters.sessionId) return false;\n    if (filters.threadId !== undefined && score.threadId !== filters.threadId) return false;\n    if (filters.requestId !== undefined && score.requestId !== filters.requestId) return false;\n    if (filters.parentEntityType !== undefined && score.parentEntityType !== filters.parentEntityType) return false;\n    if (filters.parentEntityName !== undefined && score.parentEntityName !== filters.parentEntityName) return false;\n    if (filters.rootEntityType !== undefined && score.rootEntityType !== filters.rootEntityType) return false;\n    if (filters.rootEntityName !== undefined && score.rootEntityName !== filters.rootEntityName) return false;\n    if (filters.serviceName !== undefined && score.serviceName !== filters.serviceName) return false;\n    if (filters.environment !== undefined && score.environment !== filters.environment) return false;\n    if (filters.executionSource !== undefined && score.executionSource !== filters.executionSource) return false;\n    if (filters.scorerId !== undefined) {\n      const names = Array.isArray(filters.scorerId) ? filters.scorerId : [filters.scorerId];\n      if (!names.includes(score.scorerId)) return false;\n    }\n    const scoreSource = score.scoreSource ?? score.source ?? null;\n    if (filters.scoreSource !== undefined && scoreSource !== filters.scoreSource) return false;\n    if (filters.source !== undefined && scoreSource !== filters.source) return false;\n    if (filters.experimentId !== undefined && score.experimentId !== filters.experimentId) return false;\n    if (filters.tags != null && filters.tags.length > 0) {\n      if (score.tags == null) return false;\n      for (const tag of filters.tags) {\n        if (!score.tags.includes(tag)) return false;\n      }\n    }\n\n    return true;\n  }\n\n  async getScoreAggregate(args: GetScoreAggregateArgs): Promise<GetScoreAggregateResponse> {\n    const filtered = this.db.scoreRecords\n      .filter(score => this.scoreMatchesFilters(score, args.filters))\n      .filter(score => score.scorerId === args.scorerId)\n      .filter(score => (args.scoreSource ? (score.scoreSource ?? score.source ?? null) === args.scoreSource : true));\n    const value = this.aggregate(\n      filtered.map(score => score.score),\n      args.aggregation,\n      filtered.map(score => score.timestamp.getTime()),\n    );\n\n    if (args.comparePeriod && args.filters?.timestamp) {\n      const previousRange = this.getComparisonDateRange(args.comparePeriod, args.filters.timestamp);\n      if (previousRange) {\n        const previousFiltered = this.db.scoreRecords\n          .filter(score =>\n            this.scoreMatchesFilters(score, {\n              ...(args.filters ?? {}),\n              timestamp: previousRange,\n            }),\n          )\n          .filter(score => score.scorerId === args.scorerId)\n          .filter(score =>\n            args.scoreSource ? (score.scoreSource ?? score.source ?? null) === args.scoreSource : true,\n          );\n\n        const previousValue = this.aggregate(\n          previousFiltered.map(score => score.score),\n          args.aggregation,\n          previousFiltered.map(score => score.timestamp.getTime()),\n        );\n\n        let changePercent: number | null = null;\n        if (previousValue !== null && previousValue !== 0 && value !== null) {\n          changePercent = ((value - previousValue) / Math.abs(previousValue)) * 100;\n        }\n\n        return { value, previousValue, changePercent };\n      }\n    }\n\n    return { value };\n  }\n\n  async getScoreBreakdown(args: GetScoreBreakdownArgs): Promise<GetScoreBreakdownResponse> {\n    const filtered = this.db.scoreRecords\n      .filter(score => this.scoreMatchesFilters(score, args.filters))\n      .filter(score => score.scorerId === args.scorerId)\n      .filter(score => (args.scoreSource ? (score.scoreSource ?? score.source ?? null) === args.scoreSource : true));\n\n    const groupMap = new Map<string, ScoreRecord[]>();\n    for (const score of filtered) {\n      const dims: Record<string, string | null> = {};\n      for (const col of args.groupBy) {\n        const value = (score as Record<string, unknown>)[col];\n        dims[col] = value === null || value === undefined ? null : String(value);\n      }\n      const key = JSON.stringify(dims);\n      if (!groupMap.has(key)) groupMap.set(key, []);\n      groupMap.get(key)!.push(score);\n    }\n\n    const groups = Array.from(groupMap.entries()).map(([key, records]) => ({\n      dimensions: JSON.parse(key) as Record<string, string | null>,\n      value:\n        this.aggregate(\n          records.map(record => record.score),\n          args.aggregation,\n          records.map(record => record.timestamp.getTime()),\n        ) ?? 0,\n    }));\n    groups.sort((a, b) => b.value - a.value);\n\n    return { groups };\n  }\n\n  async getScoreTimeSeries(args: GetScoreTimeSeriesArgs): Promise<GetScoreTimeSeriesResponse> {\n    const filtered = this.db.scoreRecords\n      .filter(score => this.scoreMatchesFilters(score, args.filters))\n      .filter(score => score.scorerId === args.scorerId)\n      .filter(score => (args.scoreSource ? (score.scoreSource ?? score.source ?? null) === args.scoreSource : true));\n    const intervalMs = this.intervalToMs(args.interval);\n\n    if (args.groupBy && args.groupBy.length > 0) {\n      const seriesMap = new Map<string, Map<number, ScoreRecord[]>>();\n      const seriesNames = new Map<string, string>();\n\n      for (const score of filtered) {\n        const values = args.groupBy.map(col => (score as Record<string, unknown>)[col] ?? '');\n        const key = JSON.stringify(values);\n        if (!seriesMap.has(key)) seriesMap.set(key, new Map());\n        if (!seriesNames.has(key)) {\n          seriesNames.set(\n            key,\n            values.map(value => (value === null || value === undefined ? '' : String(value))).join('|'),\n          );\n        }\n        const bucket = Math.floor(score.timestamp.getTime() / intervalMs) * intervalMs;\n        const bucketMap = seriesMap.get(key)!;\n        if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n        bucketMap.get(bucket)!.push(score);\n      }\n\n      return {\n        series: Array.from(seriesMap.entries()).map(([key, bucketMap]) => ({\n          name: seriesNames.get(key)!,\n          points: Array.from(bucketMap.entries())\n            .sort(([a], [b]) => a - b)\n            .map(([ts, records]) => ({\n              timestamp: new Date(ts),\n              value:\n                this.aggregate(\n                  records.map(record => record.score),\n                  args.aggregation,\n                  records.map(record => record.timestamp.getTime()),\n                ) ?? 0,\n            })),\n        })),\n      };\n    }\n\n    const bucketMap = new Map<number, ScoreRecord[]>();\n    for (const score of filtered) {\n      const bucket = Math.floor(score.timestamp.getTime() / intervalMs) * intervalMs;\n      if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n      bucketMap.get(bucket)!.push(score);\n    }\n\n    return {\n      series: [\n        {\n          name: args.scoreSource ? `${args.scorerId}|${args.scoreSource}` : args.scorerId,\n          points: Array.from(bucketMap.entries())\n            .sort(([a], [b]) => a - b)\n            .map(([ts, records]) => ({\n              timestamp: new Date(ts),\n              value:\n                this.aggregate(\n                  records.map(record => record.score),\n                  args.aggregation,\n                  records.map(record => record.timestamp.getTime()),\n                ) ?? 0,\n            })),\n        },\n      ],\n    };\n  }\n\n  async getScorePercentiles(args: GetScorePercentilesArgs): Promise<GetScorePercentilesResponse> {\n    const filtered = this.db.scoreRecords\n      .filter(score => this.scoreMatchesFilters(score, args.filters))\n      .filter(score => score.scorerId === args.scorerId)\n      .filter(score => (args.scoreSource ? (score.scoreSource ?? score.source ?? null) === args.scoreSource : true));\n    const intervalMs = this.intervalToMs(args.interval);\n\n    const bucketMap = new Map<number, number[]>();\n    for (const score of filtered) {\n      const bucket = Math.floor(score.timestamp.getTime() / intervalMs) * intervalMs;\n      if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n      bucketMap.get(bucket)!.push(score.score);\n    }\n\n    const sortedBuckets = Array.from(bucketMap.entries()).sort(([a], [b]) => a - b);\n\n    return {\n      series: args.percentiles.map(percentile => ({\n        percentile,\n        points: sortedBuckets.map(([ts, values]) => {\n          const sorted = [...values].sort((a, b) => a - b);\n          return { timestamp: new Date(ts), value: this.interpolatePercentile(sorted, percentile) };\n        }),\n      })),\n    };\n  }\n\n  private getNumericFeedbackValue(value: FeedbackRecord['value']): number | null {\n    if (typeof value === 'number') {\n      return Number.isFinite(value) ? value : null;\n    }\n\n    if (typeof value === 'string') {\n      const trimmed = value.trim();\n      if (trimmed.length === 0) return null;\n      const numeric = Number(trimmed);\n      return Number.isFinite(numeric) ? numeric : null;\n    }\n\n    return null;\n  }\n\n  private getComparisonDateRange(\n    comparePeriod: 'previous_period' | 'previous_day' | 'previous_week',\n    timestamp: { start?: Date; end?: Date; startExclusive?: boolean; endExclusive?: boolean },\n  ): { start: Date; end: Date; startExclusive?: boolean; endExclusive?: boolean } | null {\n    if (!timestamp.start || !timestamp.end) return null;\n\n    const duration = timestamp.end.getTime() - timestamp.start.getTime();\n    switch (comparePeriod) {\n      case 'previous_period':\n        return {\n          start: new Date(timestamp.start.getTime() - duration),\n          end: new Date(timestamp.end.getTime() - duration),\n          startExclusive: timestamp.startExclusive,\n          endExclusive: timestamp.endExclusive,\n        };\n      case 'previous_day':\n        return {\n          start: new Date(timestamp.start.getTime() - 86_400_000),\n          end: new Date(timestamp.end.getTime() - 86_400_000),\n          startExclusive: timestamp.startExclusive,\n          endExclusive: timestamp.endExclusive,\n        };\n      case 'previous_week':\n        return {\n          start: new Date(timestamp.start.getTime() - 604_800_000),\n          end: new Date(timestamp.end.getTime() - 604_800_000),\n          startExclusive: timestamp.startExclusive,\n          endExclusive: timestamp.endExclusive,\n        };\n    }\n  }\n\n  // ============================================================================\n  // Feedback\n  // ============================================================================\n\n  async createFeedback(args: CreateFeedbackArgs): Promise<void> {\n    const record = {\n      ...args.feedback,\n      feedbackSource: args.feedback.feedbackSource ?? args.feedback.source ?? '',\n      source: args.feedback.feedbackSource ?? args.feedback.source ?? '',\n      feedbackUserId:\n        args.feedback.feedbackUserId ??\n        args.feedback.userId ??\n        (typeof args.feedback.metadata?.userId === 'string' ? args.feedback.metadata.userId : null),\n    } as FeedbackRecord;\n    this.upsertByIdField(this.db.feedbackRecords, this.db.feedbackCursorIds, record, 'feedbackId');\n  }\n\n  async batchCreateFeedback(args: BatchCreateFeedbackArgs): Promise<void> {\n    for (const fb of args.feedbacks) {\n      const record = {\n        ...fb,\n        feedbackSource: fb.feedbackSource ?? fb.source ?? '',\n        source: fb.feedbackSource ?? fb.source ?? '',\n        feedbackUserId:\n          fb.feedbackUserId ?? fb.userId ?? (typeof fb.metadata?.userId === 'string' ? fb.metadata.userId : null),\n      } as FeedbackRecord;\n      this.upsertByIdField(this.db.feedbackRecords, this.db.feedbackCursorIds, record, 'feedbackId');\n    }\n  }\n\n  async listFeedback(args: ListFeedbackArgs): Promise<ListFeedbackResponse> {\n    const { mode, filters, pagination, orderBy, after, limit } = listFeedbackArgsSchema.parse(args);\n\n    if (mode === 'delta') {\n      this.assertDeltaPollingEnabled();\n      const deltaResponse = this.listAppendOnlyDelta(\n        this.db.feedbackRecords,\n        this.db.feedbackCursorIds,\n        feedback => this.feedbackMatchesFilters(feedback, filters),\n        after,\n        limit,\n      );\n\n      return {\n        feedback: deltaResponse.rows,\n        delta: deltaResponse.delta,\n        deltaCursor: deltaResponse.deltaCursor,\n      };\n    }\n\n    let matching = this.db.feedbackRecords.filter(fb => this.feedbackMatchesFilters(fb, filters));\n\n    // Sort\n    const dir = orderBy.direction === 'DESC' ? -1 : 1;\n    matching.sort((a, b) => dir * (a.timestamp.getTime() - b.timestamp.getTime()));\n\n    // Paginate\n    const total = matching.length;\n    const page = Number(pagination.page);\n    const perPage = Number(pagination.perPage);\n    const start = page * perPage;\n\n    return {\n      feedback: matching.slice(start, start + perPage),\n      pagination: { total, page, perPage, hasMore: start + perPage < total },\n      ...this.pageDeltaCursor(\n        this.maxMatchingCursorId(this.db.feedbackRecords, this.db.feedbackCursorIds, feedback =>\n          this.feedbackMatchesFilters(feedback, filters),\n        ),\n      ),\n    };\n  }\n\n  async getFeedbackAggregate(args: GetFeedbackAggregateArgs): Promise<GetFeedbackAggregateResponse> {\n    const filtered = this.db.feedbackRecords\n      .filter(feedback => this.feedbackMatchesFilters(feedback, args.filters))\n      .filter(feedback => feedback.feedbackType === args.feedbackType)\n      .filter(feedback =>\n        args.feedbackSource ? (feedback.feedbackSource ?? feedback.source ?? '') === args.feedbackSource : true,\n      );\n    const numericEntries = filtered.flatMap(feedback => {\n      const numericValue = this.getNumericFeedbackValue(feedback.value);\n      return numericValue === null ? [] : [{ numericValue, timestamp: feedback.timestamp.getTime() }];\n    });\n    const value = this.aggregate(\n      numericEntries.map(entry => entry.numericValue),\n      args.aggregation,\n      numericEntries.map(entry => entry.timestamp),\n    );\n\n    if (args.comparePeriod && args.filters?.timestamp) {\n      const previousRange = this.getComparisonDateRange(args.comparePeriod, args.filters.timestamp);\n      if (previousRange) {\n        const previousNumericEntries = this.db.feedbackRecords\n          .filter(feedback =>\n            this.feedbackMatchesFilters(feedback, {\n              ...(args.filters ?? {}),\n              timestamp: previousRange,\n            }),\n          )\n          .filter(feedback => feedback.feedbackType === args.feedbackType)\n          .filter(feedback =>\n            args.feedbackSource ? (feedback.feedbackSource ?? feedback.source ?? '') === args.feedbackSource : true,\n          )\n          .flatMap(feedback => {\n            const numericValue = this.getNumericFeedbackValue(feedback.value);\n            return numericValue === null ? [] : [{ numericValue, timestamp: feedback.timestamp.getTime() }];\n          });\n\n        const previousValue = this.aggregate(\n          previousNumericEntries.map(entry => entry.numericValue),\n          args.aggregation,\n          previousNumericEntries.map(entry => entry.timestamp),\n        );\n        let changePercent: number | null = null;\n        if (previousValue !== null && previousValue !== 0 && value !== null) {\n          changePercent = ((value - previousValue) / Math.abs(previousValue)) * 100;\n        }\n\n        return { value, previousValue, changePercent };\n      }\n    }\n\n    return { value };\n  }\n\n  async getFeedbackBreakdown(args: GetFeedbackBreakdownArgs): Promise<GetFeedbackBreakdownResponse> {\n    const filtered = this.db.feedbackRecords\n      .filter(feedback => this.feedbackMatchesFilters(feedback, args.filters))\n      .filter(feedback => feedback.feedbackType === args.feedbackType)\n      .filter(feedback =>\n        args.feedbackSource ? (feedback.feedbackSource ?? feedback.source ?? '') === args.feedbackSource : true,\n      )\n      .filter(feedback => this.getNumericFeedbackValue(feedback.value) !== null);\n\n    const groupMap = new Map<string, FeedbackRecord[]>();\n    for (const feedback of filtered) {\n      const dims: Record<string, string | null> = {};\n      for (const col of args.groupBy) {\n        const rawValue = (feedback as Record<string, unknown>)[col];\n        dims[col] = rawValue === null || rawValue === undefined ? null : String(rawValue);\n      }\n      const key = JSON.stringify(dims);\n      if (!groupMap.has(key)) groupMap.set(key, []);\n      groupMap.get(key)!.push(feedback);\n    }\n\n    const groups = Array.from(groupMap.entries()).map(([key, records]) => ({\n      dimensions: JSON.parse(key) as Record<string, string | null>,\n      value: (() => {\n        const numericEntries = records.flatMap(record => {\n          const numericValue = this.getNumericFeedbackValue(record.value);\n          return numericValue === null ? [] : [{ numericValue, timestamp: record.timestamp.getTime() }];\n        });\n\n        return (\n          this.aggregate(\n            numericEntries.map(entry => entry.numericValue),\n            args.aggregation,\n            numericEntries.map(entry => entry.timestamp),\n          ) ?? 0\n        );\n      })(),\n    }));\n    groups.sort((a, b) => b.value - a.value);\n\n    return { groups };\n  }\n\n  async getFeedbackTimeSeries(args: GetFeedbackTimeSeriesArgs): Promise<GetFeedbackTimeSeriesResponse> {\n    const filtered = this.db.feedbackRecords\n      .filter(feedback => this.feedbackMatchesFilters(feedback, args.filters))\n      .filter(feedback => feedback.feedbackType === args.feedbackType)\n      .filter(feedback =>\n        args.feedbackSource ? (feedback.feedbackSource ?? feedback.source ?? '') === args.feedbackSource : true,\n      )\n      .filter(feedback => this.getNumericFeedbackValue(feedback.value) !== null);\n    const intervalMs = this.intervalToMs(args.interval);\n\n    if (args.groupBy && args.groupBy.length > 0) {\n      const seriesMap = new Map<string, Map<number, FeedbackRecord[]>>();\n      const seriesNames = new Map<string, string>();\n\n      for (const feedback of filtered) {\n        const values = args.groupBy.map(col => (feedback as Record<string, unknown>)[col] ?? '');\n        const key = JSON.stringify(values);\n        if (!seriesMap.has(key)) seriesMap.set(key, new Map());\n        if (!seriesNames.has(key)) {\n          seriesNames.set(\n            key,\n            values.map(value => (value === null || value === undefined ? '' : String(value))).join('|'),\n          );\n        }\n        const bucket = Math.floor(feedback.timestamp.getTime() / intervalMs) * intervalMs;\n        const bucketMap = seriesMap.get(key)!;\n        if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n        bucketMap.get(bucket)!.push(feedback);\n      }\n\n      return {\n        series: Array.from(seriesMap.entries()).map(([key, bucketMap]) => ({\n          name: seriesNames.get(key)!,\n          points: Array.from(bucketMap.entries())\n            .sort(([a], [b]) => a - b)\n            .map(([ts, records]) => ({\n              timestamp: new Date(ts),\n              value: (() => {\n                const numericEntries = records.flatMap(record => {\n                  const numericValue = this.getNumericFeedbackValue(record.value);\n                  return numericValue === null ? [] : [{ numericValue, timestamp: record.timestamp.getTime() }];\n                });\n\n                return (\n                  this.aggregate(\n                    numericEntries.map(entry => entry.numericValue),\n                    args.aggregation,\n                    numericEntries.map(entry => entry.timestamp),\n                  ) ?? 0\n                );\n              })(),\n            })),\n        })),\n      };\n    }\n\n    const bucketMap = new Map<number, FeedbackRecord[]>();\n    for (const feedback of filtered) {\n      const bucket = Math.floor(feedback.timestamp.getTime() / intervalMs) * intervalMs;\n      if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n      bucketMap.get(bucket)!.push(feedback);\n    }\n\n    return {\n      series: [\n        {\n          name: args.feedbackSource ? `${args.feedbackType}|${args.feedbackSource}` : args.feedbackType,\n          points: Array.from(bucketMap.entries())\n            .sort(([a], [b]) => a - b)\n            .map(([ts, records]) => ({\n              timestamp: new Date(ts),\n              value: (() => {\n                const numericEntries = records.flatMap(record => {\n                  const numericValue = this.getNumericFeedbackValue(record.value);\n                  return numericValue === null ? [] : [{ numericValue, timestamp: record.timestamp.getTime() }];\n                });\n\n                return (\n                  this.aggregate(\n                    numericEntries.map(entry => entry.numericValue),\n                    args.aggregation,\n                    numericEntries.map(entry => entry.timestamp),\n                  ) ?? 0\n                );\n              })(),\n            })),\n        },\n      ],\n    };\n  }\n\n  async getFeedbackPercentiles(args: GetFeedbackPercentilesArgs): Promise<GetFeedbackPercentilesResponse> {\n    const filtered = this.db.feedbackRecords\n      .filter(feedback => this.feedbackMatchesFilters(feedback, args.filters))\n      .filter(feedback => feedback.feedbackType === args.feedbackType)\n      .filter(feedback =>\n        args.feedbackSource ? (feedback.feedbackSource ?? feedback.source ?? '') === args.feedbackSource : true,\n      );\n    const intervalMs = this.intervalToMs(args.interval);\n\n    const bucketMap = new Map<number, number[]>();\n    for (const feedback of filtered) {\n      const numericValue = this.getNumericFeedbackValue(feedback.value);\n      if (numericValue === null) continue;\n      const bucket = Math.floor(feedback.timestamp.getTime() / intervalMs) * intervalMs;\n      if (!bucketMap.has(bucket)) bucketMap.set(bucket, []);\n      bucketMap.get(bucket)!.push(numericValue);\n    }\n\n    const sortedBuckets = Array.from(bucketMap.entries()).sort(([a], [b]) => a - b);\n\n    return {\n      series: args.percentiles.map(percentile => ({\n        percentile,\n        points: sortedBuckets.map(([ts, values]) => {\n          const sorted = [...values].sort((a, b) => a - b);\n          return { timestamp: new Date(ts), value: this.interpolatePercentile(sorted, percentile) };\n        }),\n      })),\n    };\n  }\n\n  private feedbackMatchesFilters(fb: FeedbackRecord, filters?: FeedbackFilter): boolean {\n    if (!filters) return true;\n\n    if (filters.timestamp) {\n      if (filters.timestamp.start && fb.timestamp < filters.timestamp.start) return false;\n      if (filters.timestamp.end && fb.timestamp > filters.timestamp.end) return false;\n    }\n    if (filters.traceId !== undefined && fb.traceId !== filters.traceId) return false;\n    if (filters.spanId !== undefined && fb.spanId !== filters.spanId) return false;\n    if (filters.entityType !== undefined && fb.entityType !== filters.entityType) return false;\n    if (filters.entityName !== undefined && fb.entityName !== filters.entityName) return false;\n    if (filters.entityVersionId !== undefined && fb.entityVersionId !== filters.entityVersionId) return false;\n    if (filters.parentEntityVersionId !== undefined && fb.parentEntityVersionId !== filters.parentEntityVersionId)\n      return false;\n    if (filters.rootEntityVersionId !== undefined && fb.rootEntityVersionId !== filters.rootEntityVersionId)\n      return false;\n    if (filters.userId !== undefined && fb.userId !== filters.userId) return false;\n    if (filters.organizationId !== undefined && fb.organizationId !== filters.organizationId) return false;\n    if (filters.resourceId !== undefined && fb.resourceId !== filters.resourceId) return false;\n    if (filters.runId !== undefined && fb.runId !== filters.runId) return false;\n    if (filters.sessionId !== undefined && fb.sessionId !== filters.sessionId) return false;\n    if (filters.threadId !== undefined && fb.threadId !== filters.threadId) return false;\n    if (filters.requestId !== undefined && fb.requestId !== filters.requestId) return false;\n    if (filters.parentEntityType !== undefined && fb.parentEntityType !== filters.parentEntityType) return false;\n    if (filters.parentEntityName !== undefined && fb.parentEntityName !== filters.parentEntityName) return false;\n    if (filters.rootEntityType !== undefined && fb.rootEntityType !== filters.rootEntityType) return false;\n    if (filters.rootEntityName !== undefined && fb.rootEntityName !== filters.rootEntityName) return false;\n    if (filters.serviceName !== undefined && fb.serviceName !== filters.serviceName) return false;\n    if (filters.environment !== undefined && fb.environment !== filters.environment) return false;\n    if (filters.executionSource !== undefined && fb.executionSource !== filters.executionSource) return false;\n    if (filters.feedbackType !== undefined) {\n      const types = Array.isArray(filters.feedbackType) ? filters.feedbackType : [filters.feedbackType];\n      if (!types.includes(fb.feedbackType)) return false;\n    }\n    const feedbackSource = fb.feedbackSource ?? fb.source ?? '';\n    if (filters.feedbackSource !== undefined && feedbackSource !== filters.feedbackSource) return false;\n    if (filters.source !== undefined && feedbackSource !== filters.source) return false;\n    if (filters.experimentId !== undefined && fb.experimentId !== filters.experimentId) return false;\n    if (filters.feedbackUserId !== undefined && fb.feedbackUserId !== filters.feedbackUserId) return false;\n    if (filters.tags != null && filters.tags.length > 0) {\n      if (fb.tags == null) return false;\n      for (const tag of filters.tags) {\n        if (!fb.tags.includes(tag)) return false;\n      }\n    }\n\n    return true;\n  }\n}\n","import type {\n  AnyExportedSpan,\n  MetricEvent,\n  LogEvent,\n  ScoreEvent,\n  FeedbackEvent,\n} from '../../../observability/index.js';\nimport type { CorrelationContext } from '../../../observability/types/core.js';\nimport { EntityType } from '../../../observability/types/tracing.js';\nimport type { CreateFeedbackRecord } from './feedback.js';\nimport type { CreateLogRecord } from './logs.js';\nimport type { CreateMetricRecord } from './metrics.js';\nimport type { CreateScoreRecord } from './scores.js';\nimport type { CreateSpanRecord, UpdateSpanRecord } from './tracing.js';\n\n// ============================================================================\n// Shared helpers for extracting typed fields from untyped metadata/labels\n// ============================================================================\n\nconst entityTypeValues = new Set(Object.values(EntityType));\n\n/** Safely cast string to EntityType, returning null if invalid */\nexport function toEntityType(value: string | undefined | null): EntityType | null {\n  if (value && entityTypeValues.has(value as EntityType)) {\n    return value as EntityType;\n  }\n  return null;\n}\n\n/** Extract a string from an unknown value, returning null if not a string. */\nexport function getStringOrNull(value: unknown): string | null {\n  return typeof value === 'string' ? value : null;\n}\n\n/** Extract a plain object from an unknown value, returning null if not an object. */\nexport function getObjectOrNull(value: unknown): Record<string, any> | null {\n  return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, any>) : null;\n}\n\n// ============================================================================\n// Span attribute serialization\n// ============================================================================\n\n/**\n * Serializes span attributes to a plain JSON-safe object.\n * Handles Date objects and nested structures.\n */\nexport function serializeSpanAttributes(span: AnyExportedSpan): Record<string, any> | null {\n  if (!span.attributes) {\n    return null;\n  }\n\n  try {\n    return JSON.parse(\n      JSON.stringify(span.attributes, (_key, value) => {\n        if (value instanceof Date) {\n          return value.toISOString();\n        }\n        return value;\n      }),\n    );\n  } catch {\n    return null;\n  }\n}\n\ntype CorrelationRecordFields = Pick<\n  CreateLogRecord,\n  | 'tags'\n  | 'entityType'\n  | 'entityId'\n  | 'entityName'\n  | 'entityVersionId'\n  | 'parentEntityType'\n  | 'parentEntityId'\n  | 'parentEntityName'\n  | 'parentEntityVersionId'\n  | 'rootEntityType'\n  | 'rootEntityId'\n  | 'rootEntityName'\n  | 'rootEntityVersionId'\n  | 'userId'\n  | 'organizationId'\n  | 'resourceId'\n  | 'runId'\n  | 'sessionId'\n  | 'threadId'\n  | 'requestId'\n  | 'environment'\n  | 'executionSource'\n  | 'serviceName'\n  | 'experimentId'\n>;\n\nfunction buildCorrelationRecordFields(context: CorrelationContext | undefined): CorrelationRecordFields {\n  return {\n    tags: context?.tags ?? null,\n    entityType: context?.entityType ?? null,\n    entityId: context?.entityId ?? null,\n    entityName: context?.entityName ?? null,\n    entityVersionId: context?.entityVersionId ?? null,\n    parentEntityType: context?.parentEntityType ?? null,\n    parentEntityId: context?.parentEntityId ?? null,\n    parentEntityName: context?.parentEntityName ?? null,\n    parentEntityVersionId: context?.parentEntityVersionId ?? null,\n    rootEntityType: context?.rootEntityType ?? null,\n    rootEntityId: context?.rootEntityId ?? null,\n    rootEntityName: context?.rootEntityName ?? null,\n    rootEntityVersionId: context?.rootEntityVersionId ?? null,\n    userId: context?.userId ?? null,\n    organizationId: context?.organizationId ?? null,\n    resourceId: context?.resourceId ?? null,\n    runId: context?.runId ?? null,\n    sessionId: context?.sessionId ?? null,\n    threadId: context?.threadId ?? null,\n    requestId: context?.requestId ?? null,\n    environment: context?.environment ?? null,\n    executionSource: context?.source ?? null,\n    serviceName: context?.serviceName ?? null,\n    experimentId: context?.experimentId ?? null,\n  };\n}\n\nfunction buildLegacyMetricLabelCorrelationFields(labels: Record<string, string>): Partial<CorrelationRecordFields> {\n  return {\n    entityType: toEntityType(labels.entity_type),\n    entityName: getStringOrNull(labels.entity_name),\n    parentEntityType: toEntityType(labels.parent_type),\n    parentEntityName: getStringOrNull(labels.parent_name),\n    serviceName: getStringOrNull(labels.service_name),\n  };\n}\n\nfunction stripLegacyMetricCorrelationLabels(labels: Record<string, string>): Record<string, string> {\n  const sanitized = { ...labels };\n  delete sanitized.entity_type;\n  delete sanitized.entity_name;\n  delete sanitized.parent_type;\n  delete sanitized.parent_name;\n  delete sanitized.service_name;\n  return sanitized;\n}\n\nfunction buildLegacyLogMetadataCorrelationFields(\n  metadata: Record<string, any> | null,\n): Partial<CorrelationRecordFields> {\n  return {\n    entityType: toEntityType(getStringOrNull(metadata?.entity_type) ?? undefined),\n    entityName: getStringOrNull(metadata?.entity_name),\n    parentEntityType: toEntityType(getStringOrNull(metadata?.parent_type) ?? undefined),\n    parentEntityName: getStringOrNull(metadata?.parent_name),\n    rootEntityType: toEntityType(getStringOrNull(metadata?.root_type) ?? undefined),\n    rootEntityName: getStringOrNull(metadata?.root_name),\n    environment: getStringOrNull(metadata?.environment),\n    executionSource: getStringOrNull(metadata?.source),\n    serviceName: getStringOrNull(metadata?.service_name),\n  };\n}\n\n// ============================================================================\n// Event → Record builders\n// ============================================================================\n\n/** Convert an exported span to a CreateSpanRecord */\nexport function buildCreateSpanRecord(span: AnyExportedSpan): CreateSpanRecord {\n  const metadata = span.metadata ?? {};\n\n  return {\n    traceId: span.traceId,\n    spanId: span.id,\n    parentSpanId: span.parentSpanId ?? null,\n    name: span.name,\n\n    // Entity identification - from span\n    entityType: span.entityType ?? null,\n    entityId: span.entityId ?? null,\n    entityName: span.entityName ?? null,\n    entityVersionId: getStringOrNull(metadata.entityVersionId),\n\n    // Identity & Tenancy - extracted from metadata if present\n    userId: getStringOrNull(metadata.userId),\n    organizationId: getStringOrNull(metadata.organizationId),\n    resourceId: getStringOrNull(metadata.resourceId),\n\n    // Correlation IDs - extracted from metadata if present\n    runId: getStringOrNull(metadata.runId),\n    sessionId: getStringOrNull(metadata.sessionId),\n    threadId: getStringOrNull(metadata.threadId),\n    requestId: getStringOrNull(metadata.requestId),\n\n    // Deployment context - extracted from metadata if present\n    environment: getStringOrNull(metadata.environment),\n    source: getStringOrNull(metadata.source),\n    serviceName: getStringOrNull(metadata.serviceName),\n    scope: getObjectOrNull(metadata.scope),\n\n    // Experimentation\n    experimentId: getStringOrNull(metadata.experimentId),\n\n    // Span data\n    spanType: span.type,\n    attributes: serializeSpanAttributes(span),\n    metadata: span.metadata ?? null,\n    tags: span.tags ?? null,\n    links: null,\n    input: span.input ?? null,\n    output: span.output ?? null,\n    error: span.errorInfo ?? null,\n    isEvent: span.isEvent,\n\n    // Request context\n    requestContext: span.requestContext ?? null,\n\n    // Timestamps\n    startedAt: span.startTime,\n    endedAt: span.endTime ?? null,\n  };\n}\n\n/** Convert an exported span to a partial UpdateSpanRecord */\nexport function buildUpdateSpanRecord(span: AnyExportedSpan): Partial<UpdateSpanRecord> {\n  return {\n    name: span.name,\n    scope: null,\n    attributes: serializeSpanAttributes(span),\n    metadata: span.metadata ?? null,\n    links: null,\n    endedAt: span.endTime ?? null,\n    input: span.input,\n    output: span.output,\n    error: span.errorInfo ?? null,\n  };\n}\n\n/** Convert a MetricEvent to a CreateMetricRecord. */\nexport function buildMetricRecord(event: MetricEvent): CreateMetricRecord {\n  const m = event.metric;\n  const labels = stripLegacyMetricCorrelationLabels(m.labels);\n  const correlationFields = buildCorrelationRecordFields(m.correlationContext);\n  const legacyCorrelationFields = buildLegacyMetricLabelCorrelationFields(m.labels);\n  const cost = m.costContext;\n\n  return {\n    metricId: m.metricId,\n    timestamp: m.timestamp,\n    name: m.name,\n    value: m.value,\n    labels,\n    traceId: m.traceId ?? m.correlationContext?.traceId ?? null,\n    spanId: m.spanId ?? m.correlationContext?.spanId ?? null,\n    ...correlationFields,\n    scope: null,\n    entityType: correlationFields.entityType ?? legacyCorrelationFields.entityType ?? null,\n    entityName: correlationFields.entityName ?? legacyCorrelationFields.entityName ?? null,\n    parentEntityType: correlationFields.parentEntityType ?? legacyCorrelationFields.parentEntityType ?? null,\n    parentEntityName: correlationFields.parentEntityName ?? legacyCorrelationFields.parentEntityName ?? null,\n    serviceName: correlationFields.serviceName ?? legacyCorrelationFields.serviceName ?? null,\n    provider: cost?.provider ?? null,\n    model: cost?.model ?? null,\n    estimatedCost: cost?.estimatedCost ?? null,\n    costUnit: cost?.costUnit ?? null,\n    costMetadata: cost?.costMetadata ?? null,\n    metadata: m.metadata ?? null,\n  };\n}\n\n/** Convert a LogEvent to a CreateLogRecord */\nexport function buildLogRecord(event: LogEvent): CreateLogRecord {\n  const l = event.log;\n  const correlationFields = buildCorrelationRecordFields(l.correlationContext);\n  const legacyCorrelationFields = buildLegacyLogMetadataCorrelationFields(l.metadata ?? null);\n\n  return {\n    logId: l.logId,\n    timestamp: l.timestamp,\n    level: l.level,\n    message: l.message,\n    data: l.data ?? null,\n    ...correlationFields,\n    traceId: l.traceId ?? l.correlationContext?.traceId ?? null,\n    spanId: l.spanId ?? l.correlationContext?.spanId ?? null,\n    tags: correlationFields.tags ?? l.tags ?? null,\n    entityType: correlationFields.entityType ?? legacyCorrelationFields.entityType ?? null,\n    entityName: correlationFields.entityName ?? legacyCorrelationFields.entityName ?? null,\n    parentEntityType: correlationFields.parentEntityType ?? legacyCorrelationFields.parentEntityType ?? null,\n    parentEntityName: correlationFields.parentEntityName ?? legacyCorrelationFields.parentEntityName ?? null,\n    rootEntityType: correlationFields.rootEntityType ?? legacyCorrelationFields.rootEntityType ?? null,\n    rootEntityName: correlationFields.rootEntityName ?? legacyCorrelationFields.rootEntityName ?? null,\n    environment: correlationFields.environment ?? legacyCorrelationFields.environment ?? null,\n    executionSource: correlationFields.executionSource ?? legacyCorrelationFields.executionSource ?? null,\n    serviceName: correlationFields.serviceName ?? legacyCorrelationFields.serviceName ?? null,\n    scope: null,\n    metadata: l.metadata ?? null,\n  };\n}\n\n/** Convert a ScoreEvent to a CreateScoreRecord */\nexport function buildScoreRecord(event: ScoreEvent): CreateScoreRecord {\n  const s = event.score;\n  const correlationFields = buildCorrelationRecordFields(s.correlationContext);\n  return {\n    scoreId: s.scoreId,\n    timestamp: s.timestamp,\n    traceId: s.traceId ?? s.correlationContext?.traceId ?? null,\n    spanId: s.spanId ?? s.correlationContext?.spanId ?? null,\n    scorerId: s.scorerId,\n    scorerName: s.scorerName ?? null,\n    scorerVersion: s.scorerVersion ?? null,\n    scoreSource: s.scoreSource ?? s.source ?? null,\n    source: s.scoreSource ?? s.source ?? null,\n    score: s.score,\n    reason: s.reason ?? null,\n    ...correlationFields,\n    entityType: correlationFields.entityType ?? s.targetEntityType ?? null,\n    experimentId: correlationFields.experimentId ?? s.experimentId ?? null,\n    scope: null,\n    scoreTraceId: s.scoreTraceId ?? null,\n    metadata: s.metadata ?? null,\n  };\n}\n\n/** Convert a FeedbackEvent to a CreateFeedbackRecord */\nexport function buildFeedbackRecord(event: FeedbackEvent): CreateFeedbackRecord {\n  const fb = event.feedback;\n  const correlationFields = buildCorrelationRecordFields(fb.correlationContext);\n  return {\n    feedbackId: fb.feedbackId,\n    timestamp: fb.timestamp,\n    traceId: fb.traceId ?? fb.correlationContext?.traceId ?? null,\n    spanId: fb.spanId ?? fb.correlationContext?.spanId ?? null,\n    feedbackSource: fb.feedbackSource ?? fb.source ?? '',\n    source: fb.feedbackSource ?? fb.source ?? '',\n    feedbackType: fb.feedbackType,\n    value: fb.value,\n    comment: fb.comment ?? null,\n    ...correlationFields,\n    experimentId: correlationFields.experimentId ?? fb.experimentId ?? null,\n    feedbackUserId:\n      fb.feedbackUserId ?? fb.userId ?? (typeof fb.metadata?.userId === 'string' ? fb.metadata.userId : null),\n    scope: null,\n    sourceId: fb.sourceId ?? null,\n    metadata: fb.metadata ?? null,\n  };\n}\n","import type { BackgroundTask, TaskFilter, TaskListResult, UpdateBackgroundTask } from '../../../background-tasks/types';\nimport { StorageDomain } from '../base';\n\n/**\n * Abstract storage domain for background tasks.\n * Handles persistence of task state — creation, status updates, querying, and cleanup.\n */\nexport abstract class BackgroundTasksStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'BACKGROUND_TASKS',\n    });\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    // Default no-op - subclasses override\n  }\n\n  /** Insert a new task record. */\n  abstract createTask(task: BackgroundTask): Promise<void>;\n\n  /**\n   * Partial update of a task record.\n   * Only the provided fields are updated; others are left unchanged.\n   */\n  abstract updateTask(taskId: string, update: UpdateBackgroundTask): Promise<void>;\n\n  /** Get a single task by ID. Returns null if not found. */\n  abstract getTask(taskId: string): Promise<BackgroundTask | null>;\n\n  /**\n   * Query tasks with filters, ordering, and pagination.\n   * Returns tasks matching all provided filter criteria.\n   */\n  abstract listTasks(filter: TaskFilter): Promise<TaskListResult>;\n\n  /**\n   * Delete a particular task by ID.\n   * Used for cleanup of old completed/failed records.\n   */\n  abstract deleteTask(taskId: string): Promise<void>;\n\n  /**\n   * Delete tasks matching the filter criteria.\n   * Used for cleanup of old completed/failed records.\n   */\n  abstract deleteTasks(filter: TaskFilter): Promise<void>;\n\n  /** Count tasks currently in 'running' status across all agents. */\n  abstract getRunningCount(): Promise<number>;\n\n  /** Count tasks currently in 'running' status for a specific agent. */\n  abstract getRunningCountByAgent(agentId: string): Promise<number>;\n}\n","import type { BackgroundTask, TaskFilter, TaskListResult, UpdateBackgroundTask } from '../../../background-tasks/types';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { BackgroundTasksStorage } from './base';\n\nexport class BackgroundTasksInMemory extends BackgroundTasksStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.backgroundTasks.clear();\n  }\n\n  async createTask(task: BackgroundTask): Promise<void> {\n    this.db.backgroundTasks.set(task.id, { ...task });\n  }\n\n  async updateTask(taskId: string, update: UpdateBackgroundTask): Promise<void> {\n    const existing = this.db.backgroundTasks.get(taskId);\n    if (!existing) return;\n    this.db.backgroundTasks.set(taskId, { ...existing, ...update });\n  }\n\n  async getTask(taskId: string): Promise<BackgroundTask | null> {\n    const task = this.db.backgroundTasks.get(taskId);\n    return task ? { ...task } : null;\n  }\n\n  async listTasks(filter: TaskFilter): Promise<TaskListResult> {\n    let tasks = Array.from(this.db.backgroundTasks.values());\n\n    // Apply filters\n    if (filter.status) {\n      const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];\n      tasks = tasks.filter(t => statuses.includes(t.status));\n    }\n    if (filter.agentId) {\n      tasks = tasks.filter(t => t.agentId === filter.agentId);\n    }\n    if (filter.threadId) {\n      tasks = tasks.filter(t => t.threadId === filter.threadId);\n    }\n    if (filter.resourceId) {\n      tasks = tasks.filter(t => t.resourceId === filter.resourceId);\n    }\n    if (filter.toolName) {\n      tasks = tasks.filter(t => t.toolName === filter.toolName);\n    }\n    if (filter.toolCallId) {\n      tasks = tasks.filter(t => t.toolCallId === filter.toolCallId);\n    }\n    if (filter.runId) {\n      tasks = tasks.filter(t => t.runId === filter.runId);\n    }\n\n    // Date range filtering\n    const dateCol = filter.dateFilterBy ?? 'createdAt';\n    if (filter.fromDate) {\n      tasks = tasks.filter(t => {\n        const val = t[dateCol];\n        return val != null && val >= filter.fromDate!;\n      });\n    }\n    if (filter.toDate) {\n      tasks = tasks.filter(t => {\n        const val = t[dateCol];\n        return val != null && val < filter.toDate!;\n      });\n    }\n\n    // Sort\n    const orderBy = filter.orderBy ?? 'createdAt';\n    const direction = filter.orderDirection ?? 'asc';\n    tasks.sort((a, b) => {\n      const aVal = a[orderBy]?.getTime() ?? 0;\n      const bVal = b[orderBy]?.getTime() ?? 0;\n      return direction === 'asc' ? aVal - bVal : bVal - aVal;\n    });\n\n    // Total count before pagination\n    const total = tasks.length;\n\n    // Pagination\n    if (filter.page != null && filter.perPage != null) {\n      const start = filter.page * filter.perPage;\n      tasks = tasks.slice(start, start + filter.perPage);\n    } else if (filter.perPage != null) {\n      tasks = tasks.slice(0, filter.perPage);\n    }\n\n    // Return copies to prevent external mutation\n    return { tasks: tasks.map(t => ({ ...t })), total };\n  }\n\n  async deleteTask(taskId: string): Promise<void> {\n    this.db.backgroundTasks.delete(taskId);\n  }\n\n  async deleteTasks(filter: TaskFilter): Promise<void> {\n    const { tasks } = await this.listTasks(filter);\n    for (const task of tasks) {\n      this.db.backgroundTasks.delete(task.id);\n    }\n  }\n\n  async getRunningCount(): Promise<number> {\n    let count = 0;\n    for (const task of this.db.backgroundTasks.values()) {\n      if (task.status === 'running') count++;\n    }\n    return count;\n  }\n\n  async getRunningCountByAgent(agentId: string): Promise<number> {\n    let count = 0;\n    for (const task of this.db.backgroundTasks.values()) {\n      if (task.status === 'running' && task.agentId === agentId) count++;\n    }\n    return count;\n  }\n}\n","import { MastraBase } from '../../../base';\nimport type { StorageBlobEntry } from '../../types';\n\n/**\n * Abstract base class for content-addressable blob storage.\n * Used to store file contents for skill versioning.\n *\n * Blobs are keyed by their SHA-256 hash, providing natural deduplication.\n */\nexport abstract class BlobStore extends MastraBase {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'BLOBS',\n    });\n  }\n\n  /**\n   * Initialize the blob store (create tables, etc).\n   */\n  abstract init(): Promise<void>;\n\n  /**\n   * Store a blob. If the hash already exists, this is a no-op.\n   */\n  abstract put(entry: StorageBlobEntry): Promise<void>;\n\n  /**\n   * Retrieve a blob by its hash.\n   * Returns null if not found.\n   */\n  abstract get(hash: string): Promise<StorageBlobEntry | null>;\n\n  /**\n   * Check if a blob exists by hash.\n   */\n  abstract has(hash: string): Promise<boolean>;\n\n  /**\n   * Delete a blob by hash.\n   * Returns true if the blob was deleted, false if it didn't exist.\n   */\n  abstract delete(hash: string): Promise<boolean>;\n\n  /**\n   * Store multiple blobs in a batch. Skips any that already exist.\n   */\n  abstract putMany(entries: StorageBlobEntry[]): Promise<void>;\n\n  /**\n   * Retrieve multiple blobs by their hashes.\n   * Returns a Map of hash -> entry. Missing hashes are omitted.\n   */\n  abstract getMany(hashes: string[]): Promise<Map<string, StorageBlobEntry>>;\n\n  /**\n   * Delete all blobs. Used for testing.\n   */\n  abstract dangerouslyClearAll(): Promise<void>;\n}\n","import type { StorageBlobEntry } from '../../types';\nimport { BlobStore } from './base';\n\n/**\n * In-memory implementation of BlobStore for testing.\n */\nexport class InMemoryBlobStore extends BlobStore {\n  readonly #blobs = new Map<string, StorageBlobEntry>();\n\n  async init(): Promise<void> {\n    // No-op for in-memory store\n  }\n\n  async put(entry: StorageBlobEntry): Promise<void> {\n    if (!this.#blobs.has(entry.hash)) {\n      this.#blobs.set(entry.hash, entry);\n    }\n  }\n\n  async get(hash: string): Promise<StorageBlobEntry | null> {\n    return this.#blobs.get(hash) ?? null;\n  }\n\n  async has(hash: string): Promise<boolean> {\n    return this.#blobs.has(hash);\n  }\n\n  async delete(hash: string): Promise<boolean> {\n    return this.#blobs.delete(hash);\n  }\n\n  async putMany(entries: StorageBlobEntry[]): Promise<void> {\n    for (const entry of entries) {\n      await this.put(entry);\n    }\n  }\n\n  async getMany(hashes: string[]): Promise<Map<string, StorageBlobEntry>> {\n    const result = new Map<string, StorageBlobEntry>();\n    for (const hash of hashes) {\n      const blob = this.#blobs.get(hash);\n      if (blob) {\n        result.set(hash, blob);\n      }\n    }\n    return result;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.#blobs.clear();\n  }\n}\n","import { StorageDomain } from '../base';\n\n/**\n * Generic channel installation record.\n * Stores platform-specific data as JSON for flexibility.\n */\nexport interface ChannelInstallation {\n  /** Unique installation ID */\n  id: string;\n  /** Platform identifier (e.g., 'slack', 'discord') */\n  platform: string;\n  /** Agent ID this installation is for */\n  agentId: string;\n  /** Installation status */\n  status: 'pending' | 'active' | 'error';\n  /** Webhook ID for routing inbound requests */\n  webhookId?: string;\n  /** Platform-specific data (tokens, team info, etc.) - stored encrypted */\n  data: Record<string, unknown>;\n  /** Hash of the agent's channel config + baseUrl - used to detect changes */\n  configHash?: string;\n  /** Error message if status is 'error' */\n  error?: string;\n  /** When the installation was created */\n  createdAt: Date;\n  /** When the installation was last updated */\n  updatedAt: Date;\n}\n\n/**\n * Platform-level configuration for channel integrations.\n * Stores admin credentials needed for app factory (e.g., Slack App Configuration Tokens).\n * Each platform defines its own config shape - stored as encrypted JSON.\n */\nexport interface ChannelConfig {\n  /** Platform identifier (e.g., 'slack', 'telegram', 'discord') */\n  platform: string;\n  /** Platform-specific configuration data - stored encrypted */\n  data: Record<string, unknown>;\n  /** When the config was last updated */\n  updatedAt: Date;\n}\n\n/**\n * Storage domain for channel installations and configuration.\n * Provides persistence for multi-platform channel integrations.\n */\nexport abstract class ChannelsStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'CHANNELS',\n    });\n  }\n\n  /**\n   * Save or update a channel installation.\n   */\n  abstract saveInstallation(installation: ChannelInstallation): Promise<void>;\n\n  /**\n   * Get an installation by ID.\n   */\n  abstract getInstallation(id: string): Promise<ChannelInstallation | null>;\n\n  /**\n   * Get an installation by platform and agent ID.\n   */\n  abstract getInstallationByAgent(platform: string, agentId: string): Promise<ChannelInstallation | null>;\n\n  /**\n   * Get an installation by webhook ID (for routing inbound requests).\n   */\n  abstract getInstallationByWebhookId(webhookId: string): Promise<ChannelInstallation | null>;\n\n  /**\n   * List all installations for a platform.\n   */\n  abstract listInstallations(platform: string): Promise<ChannelInstallation[]>;\n\n  /**\n   * Delete an installation.\n   */\n  abstract deleteInstallation(id: string): Promise<void>;\n\n  /**\n   * Save platform configuration (e.g., Slack App Configuration Tokens, Telegram parent bot token).\n   */\n  abstract saveConfig(config: ChannelConfig): Promise<void>;\n\n  /**\n   * Get platform configuration.\n   */\n  abstract getConfig(platform: string): Promise<ChannelConfig | null>;\n\n  /**\n   * Delete platform configuration.\n   */\n  abstract deleteConfig(platform: string): Promise<void>;\n}\n","import type { ChannelInstallation, ChannelConfig } from './base';\nimport { ChannelsStorage } from './base';\n\n/**\n * In-memory implementation of ChannelsStorage.\n * Useful for development and testing.\n */\nexport class InMemoryChannelsStorage extends ChannelsStorage {\n  #installations = new Map<string, ChannelInstallation>();\n  #configs = new Map<string, ChannelConfig>();\n\n  async saveInstallation(installation: ChannelInstallation): Promise<void> {\n    this.#installations.set(installation.id, { ...installation });\n  }\n\n  async getInstallation(id: string): Promise<ChannelInstallation | null> {\n    const inst = this.#installations.get(id);\n    return inst ? { ...inst } : null;\n  }\n\n  async getInstallationByAgent(platform: string, agentId: string): Promise<ChannelInstallation | null> {\n    const statusPriority = { active: 0, pending: 1, error: 2 } as const;\n    let best: ChannelInstallation | null = null;\n    for (const installation of this.#installations.values()) {\n      if (installation.platform === platform && installation.agentId === agentId) {\n        if (!best || (statusPriority[installation.status] ?? 3) < (statusPriority[best.status] ?? 3)) {\n          best = installation;\n        }\n      }\n    }\n    return best ? { ...best } : null;\n  }\n\n  async getInstallationByWebhookId(webhookId: string): Promise<ChannelInstallation | null> {\n    for (const installation of this.#installations.values()) {\n      if (installation.webhookId === webhookId) {\n        return { ...installation };\n      }\n    }\n    return null;\n  }\n\n  async listInstallations(platform: string): Promise<ChannelInstallation[]> {\n    const results: ChannelInstallation[] = [];\n    for (const installation of this.#installations.values()) {\n      if (installation.platform === platform) {\n        results.push({ ...installation });\n      }\n    }\n    return results;\n  }\n\n  async deleteInstallation(id: string): Promise<void> {\n    this.#installations.delete(id);\n  }\n\n  async saveConfig(config: ChannelConfig): Promise<void> {\n    this.#configs.set(config.platform, { ...config });\n  }\n\n  async getConfig(platform: string): Promise<ChannelConfig | null> {\n    const config = this.#configs.get(platform);\n    return config ? { ...config } : null;\n  }\n\n  async deleteConfig(platform: string): Promise<void> {\n    this.#configs.delete(platform);\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.#installations.clear();\n    this.#configs.clear();\n  }\n}\n","/** Field-level validation error */\nexport interface FieldError {\n  /** JSON Pointer path, e.g., \"/name\" or \"/address/city\" */\n  path: string;\n  /** Zod error code, e.g., \"invalid_type\", \"too_small\" */\n  code: string;\n  /** Human-readable error message */\n  message: string;\n}\n\n/** Schema validation error with field details */\nexport class SchemaValidationError extends Error {\n  constructor(\n    public readonly field: 'input' | 'groundTruth',\n    public readonly errors: FieldError[],\n  ) {\n    const summary = errors\n      .slice(0, 3)\n      .map(e => e.message)\n      .join('; ');\n    super(`Validation failed for ${field}: ${summary}`);\n    this.name = 'SchemaValidationError';\n  }\n}\n\n/** Batch validation result for multiple items */\nexport interface BatchValidationResult {\n  valid: Array<{ index: number; data: unknown }>;\n  invalid: Array<{\n    index: number;\n    data: unknown;\n    field: 'input' | 'groundTruth';\n    errors: FieldError[];\n  }>;\n}\n\n/** Error thrown when schema update would invalidate existing items */\nexport class SchemaUpdateValidationError extends Error {\n  constructor(\n    public readonly failingItems: Array<{\n      index: number;\n      data: unknown;\n      field: 'input' | 'groundTruth';\n      errors: FieldError[];\n    }>,\n  ) {\n    const count = failingItems.length;\n    super(`Cannot update schema: ${count} existing item(s) would fail validation`);\n    this.name = 'SchemaUpdateValidationError';\n  }\n}\n","import { jsonSchemaToZod } from '@mastra/schema-compat/json-to-zod';\nimport type { JSONSchema7 } from 'json-schema';\nimport type { ZodSchema, ZodError, ZodIssue } from 'zod/v4';\nimport { z } from 'zod/v4';\nimport { SchemaValidationError } from './errors';\nimport type { FieldError, BatchValidationResult } from './errors';\n\n/**\n * Convert JSON Schema string to runtime Zod schema.\n * Uses Function() to evaluate the generated Zod code - same pattern as workflow validation.\n */\nfunction resolveZodSchema(zodString: string): ZodSchema {\n  return Function('z', `\"use strict\";return (${zodString});`)(z);\n}\n\n/** Schema validator with compilation caching */\nexport class SchemaValidator {\n  private cache = new Map<string, ZodSchema>();\n\n  /** Get or compile validator for schema */\n  private getValidator(schema: JSONSchema7, cacheKey: string): ZodSchema {\n    let zodSchema = this.cache.get(cacheKey);\n    if (!zodSchema) {\n      const zodString = jsonSchemaToZod(schema);\n      zodSchema = resolveZodSchema(zodString);\n      this.cache.set(cacheKey, zodSchema);\n    }\n    return zodSchema;\n  }\n\n  /** Clear cached validator (call when schema changes) */\n  clearCache(cacheKey: string): void {\n    this.cache.delete(cacheKey);\n  }\n\n  /** Validate data against schema */\n  validate(data: unknown, schema: JSONSchema7, field: 'input' | 'groundTruth', cacheKey: string): void {\n    const zodSchema = this.getValidator(schema, cacheKey);\n    const result = zodSchema.safeParse(data);\n    if (!result.success) {\n      throw new SchemaValidationError(field, this.formatErrors(result.error));\n    }\n  }\n\n  /** Validate multiple items, returning valid/invalid split */\n  validateBatch(\n    items: Array<{ input: unknown; groundTruth?: unknown }>,\n    inputSchema: JSONSchema7 | null | undefined,\n    outputSchema: JSONSchema7 | null | undefined,\n    cacheKeyPrefix: string,\n    maxErrors = 10,\n  ): BatchValidationResult {\n    const result: BatchValidationResult = { valid: [], invalid: [] };\n\n    // Pre-compile schemas for performance\n    const inputValidator = inputSchema ? this.getValidator(inputSchema, `${cacheKeyPrefix}:input`) : null;\n    const outputValidator = outputSchema ? this.getValidator(outputSchema, `${cacheKeyPrefix}:output`) : null;\n\n    for (const [i, item] of items.entries()) {\n      let hasError = false;\n\n      // Validate input if schema enabled\n      if (inputValidator) {\n        const inputResult = inputValidator.safeParse(item.input);\n        if (!inputResult.success) {\n          result.invalid.push({\n            index: i,\n            data: item,\n            field: 'input',\n            errors: this.formatErrors(inputResult.error),\n          });\n          hasError = true;\n          if (result.invalid.length >= maxErrors) break;\n        }\n      }\n\n      // Validate groundTruth if schema enabled and value provided\n      if (!hasError && outputValidator && item.groundTruth !== undefined) {\n        const outputResult = outputValidator.safeParse(item.groundTruth);\n        if (!outputResult.success) {\n          result.invalid.push({\n            index: i,\n            data: item,\n            field: 'groundTruth',\n            errors: this.formatErrors(outputResult.error),\n          });\n          hasError = true;\n          if (result.invalid.length >= maxErrors) break;\n        }\n      }\n\n      if (!hasError) {\n        result.valid.push({ index: i, data: item });\n      }\n    }\n\n    return result;\n  }\n\n  /** Format Zod errors to FieldError array */\n  private formatErrors(error: ZodError): FieldError[] {\n    return error.issues.slice(0, 5).map((issue: ZodIssue) => ({\n      // Convert Zod path array to JSON Pointer string\n      path: issue.path.length > 0 ? '/' + issue.path.join('/') : '/',\n      code: issue.code,\n      message: issue.message,\n    }));\n  }\n}\n\n/** Singleton validator instance */\nlet validatorInstance: SchemaValidator | null = null;\n\n/** Get or create validator instance */\nexport function getSchemaValidator(): SchemaValidator {\n  if (!validatorInstance) {\n    validatorInstance = new SchemaValidator();\n  }\n  return validatorInstance;\n}\n\n/** Create new validator (for testing) */\nexport function createValidator(): SchemaValidator {\n  return new SchemaValidator();\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n  if (a === b) return true;\n\n  if (a && b && typeof a == 'object' && typeof b == 'object') {\n    if (a.constructor !== b.constructor) return false;\n\n    var length, i, keys;\n    if (Array.isArray(a)) {\n      length = a.length;\n      if (length != b.length) return false;\n      for (i = length; i-- !== 0;)\n        if (!equal(a[i], b[i])) return false;\n      return true;\n    }\n\n\n\n    if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n    if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n    if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n    keys = Object.keys(a);\n    length = keys.length;\n    if (length !== Object.keys(b).length) return false;\n\n    for (i = length; i-- !== 0;)\n      if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n    for (i = length; i-- !== 0;) {\n      var key = keys[i];\n\n      if (!equal(a[key], b[key])) return false;\n    }\n\n    return true;\n  }\n\n  // true if both NaN, false otherwise\n  return a!==a && b!==b;\n};\n","import deepEqual from 'fast-deep-equal';\n\nimport { MastraError } from '../../../error';\nimport type {\n  BatchInsertItemsInput,\n  DatasetItemIdentityConflictDetail,\n  DatasetItemPayload,\n  DatasetItemRow,\n} from '../../types';\n\nconst payloadFields = [\n  'input',\n  'groundTruth',\n  'expectedTrajectory',\n  'toolMocks',\n  'unmockedToolPolicy',\n  'scorerIds',\n  'requestContext',\n  'metadata',\n  'source',\n] as const;\n\nfunction canonicalPayload(payload: DatasetItemPayload | DatasetItemRow): Record<string, unknown> {\n  return Object.fromEntries(payloadFields.map(field => [field, payload[field] ?? null]));\n}\n\nexport function datasetItemPayloadsEqual(submitted: DatasetItemPayload, accepted: DatasetItemRow): boolean {\n  return deepEqual(canonicalPayload(submitted), canonicalPayload(accepted));\n}\n\nexport class DatasetItemIdentityConflictError extends MastraError {\n  readonly conflicts: DatasetItemIdentityConflictDetail[];\n\n  constructor(conflicts: DatasetItemIdentityConflictDetail[]) {\n    super({\n      id: 'DATASET_ITEM_IDENTITY_CONFLICT',\n      text: 'One or more dataset item identities conflict with previously accepted items.',\n      domain: 'STORAGE',\n      category: 'USER',\n    });\n    this.conflicts = conflicts;\n  }\n}\n\nexport function createDatasetItemIdentityConflictError(\n  conflicts: DatasetItemIdentityConflictDetail[],\n): DatasetItemIdentityConflictError {\n  return new DatasetItemIdentityConflictError(conflicts);\n}\n\nexport interface DatasetItemBatchPlan {\n  inserts: Array<{ id: string; item: BatchInsertItemsInput['items'][number] }>;\n  resolvedIds: string[];\n  existingCurrentItems: Map<string, DatasetItemRow>;\n}\n\nexport function planDatasetItemBatch(\n  items: BatchInsertItemsInput['items'],\n  historyRows: DatasetItemRow[],\n  createId: () => string,\n): DatasetItemBatchPlan {\n  const accepted = new Map<string, { first: DatasetItemRow; current: DatasetItemRow | null }>();\n  for (const row of historyRows.sort((a, b) => a.datasetVersion - b.datasetVersion)) {\n    if (!row.externalId) continue;\n    const entry = accepted.get(row.externalId);\n    if (entry && entry.first.id !== row.id) {\n      throw new Error(`Dataset item identity history is corrupt for externalId: ${row.externalId}`);\n    }\n    if (!entry) accepted.set(row.externalId, { first: row, current: null });\n    if (row.validTo === null) accepted.get(row.externalId)!.current = row.isDeleted ? null : row;\n  }\n\n  const conflicts: DatasetItemIdentityConflictDetail[] = [];\n  const inserts: DatasetItemBatchPlan['inserts'] = [];\n  const resolvedIds: string[] = [];\n  const existingCurrentItems = new Map<string, DatasetItemRow>();\n  const requestLocal = new Map<string, DatasetItemBatchPlan['inserts'][number]>();\n\n  for (const [index, item] of items.entries()) {\n    if (!item.externalId) {\n      const insert = { id: createId(), item };\n      inserts.push(insert);\n      resolvedIds.push(insert.id);\n      continue;\n    }\n    const stored = accepted.get(item.externalId);\n    if (stored) {\n      if (!stored.current) {\n        conflicts.push({ index, externalId: item.externalId, existingItemId: stored.first.id, reason: 'deleted' });\n      } else if (!datasetItemPayloadsEqual(item, stored.first)) {\n        conflicts.push({\n          index,\n          externalId: item.externalId,\n          existingItemId: stored.first.id,\n          reason: 'payload_mismatch',\n        });\n      } else {\n        existingCurrentItems.set(stored.first.id, stored.current);\n      }\n      resolvedIds.push(stored.first.id);\n      continue;\n    }\n    const local = requestLocal.get(item.externalId);\n    if (local) {\n      const acceptedRow = {\n        ...local.item,\n        id: local.id,\n        datasetId: '',\n        datasetVersion: 0,\n        validTo: null,\n        isDeleted: false,\n        createdAt: new Date(0),\n        updatedAt: new Date(0),\n      } satisfies DatasetItemRow;\n      if (!datasetItemPayloadsEqual(item, acceptedRow)) {\n        conflicts.push({ index, externalId: item.externalId, existingItemId: local.id, reason: 'payload_mismatch' });\n      }\n      resolvedIds.push(local.id);\n      continue;\n    }\n    const insert = { id: createId(), item };\n    inserts.push(insert);\n    requestLocal.set(item.externalId, insert);\n    resolvedIds.push(insert.id);\n  }\n  if (conflicts.length) throw createDatasetItemIdentityConflictError(conflicts);\n  return { inserts, resolvedIds, existingCurrentItems };\n}\n\nexport function validateDatasetItemExternalId(externalId: string | undefined): void {\n  if (externalId === '') {\n    throw new MastraError({\n      id: 'DATASET_ITEM_EXTERNAL_ID_INVALID',\n      text: 'Dataset item externalId must be a non-empty string.',\n      domain: 'STORAGE',\n      category: 'USER',\n    });\n  }\n}\n","import { MastraError } from '../../../error';\nimport type { DatasetItemPayload, UpdateDatasetItemInput } from '../../types';\n\ninterface SerializationIssue {\n  path: string;\n  reason: string;\n  referencePath?: string;\n}\n\nfunction formatPath(parent: string, key: string): string {\n  return /^[A-Za-z_$][\\w$]*$/.test(key) ? `${parent}.${key}` : `${parent}[${JSON.stringify(key)}]`;\n}\n\nfunction findSerializationIssue(\n  value: unknown,\n  path: string,\n  ancestors: WeakMap<object, string>,\n): SerializationIssue | undefined {\n  switch (typeof value) {\n    case 'undefined':\n      return { path, reason: `undefined value at ${path} would be silently dropped or nulled` };\n    case 'function':\n      return { path, reason: `function at ${path} would be silently dropped` };\n    case 'symbol':\n      return { path, reason: `symbol at ${path} would be silently dropped` };\n    case 'bigint':\n      return { path, reason: `bigint at ${path} cannot be serialized` };\n    case 'number':\n      return Number.isFinite(value)\n        ? undefined\n        : { path, reason: `non-finite number ${value} at ${path} would become null` };\n  }\n\n  if (value === null || typeof value !== 'object') return undefined;\n\n  const referencePath = ancestors.get(value);\n  if (referencePath) {\n    return { path, referencePath, reason: `circular reference at ${path} references ${referencePath}` };\n  }\n\n  if (!Array.isArray(value)) {\n    const proto = Object.getPrototypeOf(value);\n    if (proto !== Object.prototype && proto !== null) {\n      // Date, Map, Set, class instances, custom toJSON() objects, etc. change\n      // shape during JSON persistence, so identical retries would no longer\n      // deep-equal the persisted payload. Require explicit conversion instead.\n      const constructorName = (value as object).constructor?.name || 'unknown class';\n      return { path, reason: `non-plain object (${constructorName}) at ${path} would change during JSON persistence` };\n    }\n  }\n\n  ancestors.set(value, path);\n  try {\n    if (Array.isArray(value)) {\n      for (const [index, item] of value.entries()) {\n        const issue = findSerializationIssue(item, `${path}[${index}]`, ancestors);\n        if (issue) return issue;\n      }\n    } else {\n      for (const key of Object.keys(value)) {\n        const issue = findSerializationIssue((value as Record<string, unknown>)[key], formatPath(path, key), ancestors);\n        if (issue) return issue;\n      }\n    }\n  } finally {\n    ancestors.delete(value);\n  }\n\n  return undefined;\n}\n\ntype SerializableDatasetItemPayload = Partial<Omit<DatasetItemPayload, 'scorerIds'>> &\n  Pick<UpdateDatasetItemInput, 'scorerIds'>;\n\nexport function validateDatasetItemPayloadSerialization(payload: SerializableDatasetItemPayload, path: string): void {\n  const ancestors = new WeakMap<object, string>();\n  ancestors.set(payload, path);\n\n  for (const key of Object.keys(payload)) {\n    const fieldValue = (payload as Record<string, unknown>)[key];\n    // Omitted optional fields: only nested undefined values are lossy.\n    if (fieldValue === undefined) continue;\n\n    const issue = findSerializationIssue(fieldValue, formatPath(path, key), ancestors);\n    if (issue) {\n      throw new MastraError({\n        id: 'DATASET_ITEM_PAYLOAD_NOT_SERIALIZABLE',\n        text: `Dataset item payload must be JSON-serializable: ${issue.reason}.`,\n        domain: 'STORAGE',\n        category: 'USER',\n        details: issue.referencePath\n          ? { path: issue.path, referencePath: issue.referencePath }\n          : { path: issue.path, reason: issue.reason },\n      });\n    }\n  }\n\n  try {\n    JSON.stringify(payload);\n  } catch (error) {\n    throw new MastraError({\n      id: 'DATASET_ITEM_PAYLOAD_NOT_SERIALIZABLE',\n      text: `Dataset item payload at ${path} must be JSON-serializable: ${error instanceof Error ? error.message : String(error)}`,\n      domain: 'STORAGE',\n      category: 'USER',\n      details: { path },\n    });\n  }\n}\n","import { getSchemaValidator, SchemaUpdateValidationError } from '../../../datasets/validation';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\nimport type {\n  DatasetRecord,\n  DatasetItem,\n  DatasetItemRow,\n  DatasetVersion,\n  CreateDatasetInput,\n  UpdateDatasetInput,\n  AddDatasetItemInput,\n  UpdateDatasetItemInput,\n  DeleteDatasetItemInput,\n  ListDatasetsInput,\n  ListDatasetsOutput,\n  ListDatasetItemsInput,\n  ListDatasetItemsOutput,\n  ListDatasetVersionsInput,\n  ListDatasetVersionsOutput,\n  BatchInsertItemsInput,\n  BatchDeleteItemsInput,\n  DatasetTenancyFilters,\n} from '../../types';\nimport { StorageDomain } from '../base';\nimport { planDatasetItemBatch as createDatasetItemBatchPlan, validateDatasetItemExternalId } from './identity';\nimport type { DatasetItemBatchPlan } from './identity';\nimport { validateDatasetItemPayloadSerialization } from './serialization';\n\nconst DATASET_IMMUTABLE_FIELDS = ['organizationId', 'projectId', 'candidateKey', 'candidateId'] as const;\n\n/**\n * Abstract base class for datasets storage domain.\n * Provides the contract for dataset and dataset item CRUD operations.\n *\n * Schema validation is handled in this base class via Template Method pattern.\n * Subclasses implement protected _do* methods for actual storage operations,\n * including SCD-2 versioning (version bump, row ops, dataset_version insert).\n */\nexport abstract class DatasetsStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'DATASETS',\n    });\n  }\n\n  protected validateCallerDefinedDatasetId(id: string): void {\n    if (id.length === 0) {\n      throw new MastraError({\n        id: 'DATASET_INVALID_ID',\n        domain: ErrorDomain.STORAGE,\n        category: ErrorCategory.USER,\n        details: { id },\n        text: 'Caller-defined dataset ID must not be empty',\n      });\n    }\n  }\n\n  /**\n   * Returns an existing dataset when a caller-defined ID is reused compatibly.\n   * Optional immutable fields normalize omitted and null values to the same value.\n   */\n  protected resolveExistingDataset(existing: DatasetRecord, input: CreateDatasetInput & { id: string }): DatasetRecord {\n    const hasConflict = DATASET_IMMUTABLE_FIELDS.some(field => (existing[field] ?? null) !== (input[field] ?? null));\n\n    if (hasConflict) {\n      throw new MastraError({\n        id: 'DATASET_ID_CONFLICT',\n        domain: ErrorDomain.STORAGE,\n        category: ErrorCategory.USER,\n        details: {\n          id: input.id,\n          reason: 'IMMUTABLE_FIELDS_MISMATCH',\n        },\n        text: `Dataset ID \"${input.id}\" is already in use with incompatible immutable fields`,\n      });\n    }\n\n    return existing;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    // Default no-op - subclasses override\n  }\n\n  // Dataset CRUD\n  abstract createDataset(input: CreateDatasetInput): Promise<DatasetRecord>;\n  /**\n   * Fetch a dataset by ID. When `filters` is provided, the row is only returned\n   * if it also matches the tenancy filters — returns `null` on mismatch (never\n   * throws, to avoid leaking existence across tenants via error timing/text).\n   */\n  abstract getDatasetById(args: { id: string; filters?: DatasetTenancyFilters }): Promise<DatasetRecord | null>;\n  /**\n   * Delete a dataset. When `filters` is provided, the delete is a silent no-op\n   * if the row does not match the tenancy filters. Never throws on mismatch.\n   */\n  abstract deleteDataset(args: { id: string; filters?: DatasetTenancyFilters }): Promise<void>;\n  abstract listDatasets(args: ListDatasetsInput): Promise<ListDatasetsOutput>;\n\n  /**\n   * Update a dataset. Validates existing items against new schemas if schemas are changing.\n   * Subclasses implement _doUpdateDataset for actual storage operation.\n   */\n  async updateDataset(args: UpdateDatasetInput): Promise<DatasetRecord> {\n    const existing = await this.getDatasetById({ id: args.id, filters: args.filters });\n    if (!existing) {\n      throw new Error(`Dataset not found: ${args.id}`);\n    }\n\n    // Check if schemas are being added or modified\n    const inputSchemaChanging =\n      args.inputSchema !== undefined && JSON.stringify(args.inputSchema) !== JSON.stringify(existing.inputSchema);\n    const groundTruthSchemaChanging =\n      args.groundTruthSchema !== undefined &&\n      JSON.stringify(args.groundTruthSchema) !== JSON.stringify(existing.groundTruthSchema);\n\n    // If schemas changing, validate all existing items against new schemas\n    if (inputSchemaChanging || groundTruthSchemaChanging) {\n      const itemsResult = await this.listItems({\n        datasetId: args.id,\n        pagination: { page: 0, perPage: false }, // Get all items\n      });\n      const items = itemsResult.items;\n\n      if (items.length > 0) {\n        const validator = getSchemaValidator();\n        const newInputSchema = args.inputSchema !== undefined ? args.inputSchema : existing.inputSchema;\n        const newOutputSchema =\n          args.groundTruthSchema !== undefined ? args.groundTruthSchema : existing.groundTruthSchema;\n\n        const result = validator.validateBatch(\n          items.map(i => ({ input: i.input, groundTruth: i.groundTruth })),\n          newInputSchema,\n          newOutputSchema,\n          `dataset:${args.id}:schema-update`,\n          10, // Max 10 errors to report\n        );\n\n        if (result.invalid.length > 0) {\n          throw new SchemaUpdateValidationError(result.invalid);\n        }\n\n        // Clear old cache since schema changed\n        validator.clearCache(`dataset:${args.id}:input`);\n        validator.clearCache(`dataset:${args.id}:output`);\n      }\n    }\n\n    return this._doUpdateDataset(args);\n  }\n\n  /** Subclasses implement actual storage update logic */\n  protected abstract _doUpdateDataset(args: UpdateDatasetInput): Promise<DatasetRecord>;\n\n  /**\n   * Add an item to a dataset. Validates input/groundTruth against dataset schemas.\n   * Subclasses implement _doAddItem which handles SCD-2 versioning internally.\n   */\n  async addItem(args: AddDatasetItemInput): Promise<DatasetItem> {\n    const { datasetId, filters, ...item } = args;\n    const [result] = await this.batchInsertItems({ datasetId, filters, items: [item] });\n    return result!;\n  }\n\n  /** Subclasses implement actual storage add logic with SCD-2 versioning */\n  protected abstract _doAddItem(args: AddDatasetItemInput): Promise<DatasetItem>;\n\n  /**\n   * Update an item in a dataset. Validates changed fields against dataset schemas.\n   * Subclasses implement _doUpdateItem which handles SCD-2 versioning internally.\n   */\n  async updateItem(args: UpdateDatasetItemInput): Promise<DatasetItem> {\n    const dataset = await this.getDatasetById({ id: args.datasetId, filters: args.filters });\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${args.datasetId}`);\n    }\n\n    const { id: _id, datasetId: _datasetId, filters: _filters, ...payload } = args;\n    validateDatasetItemPayloadSerialization(payload, 'item');\n\n    // Validate new values against schemas if enabled\n    const validator = getSchemaValidator();\n    const cacheKey = `dataset:${args.datasetId}`;\n\n    if (args.input !== undefined && dataset.inputSchema) {\n      validator.validate(args.input, dataset.inputSchema, 'input', `${cacheKey}:input`);\n    }\n\n    if (args.groundTruth !== undefined && dataset.groundTruthSchema) {\n      validator.validate(args.groundTruth, dataset.groundTruthSchema, 'groundTruth', `${cacheKey}:output`);\n    }\n\n    return this._doUpdateItem(args);\n  }\n\n  /** Subclasses implement actual storage update logic with SCD-2 versioning */\n  protected abstract _doUpdateItem(args: UpdateDatasetItemInput): Promise<DatasetItem>;\n\n  /**\n   * Delete an item from a dataset. Creates a tombstone row via SCD-2.\n   * Subclasses implement _doDeleteItem which handles SCD-2 versioning internally.\n   *\n   * When `args.filters` is set, the delete is a silent no-op if the parent\n   * dataset row does not match the tenancy filters — prevents deleting items\n   * from a dataset in another tenant via a leaked datasetId.\n   */\n  async deleteItem(args: DeleteDatasetItemInput): Promise<void> {\n    if (args.filters) {\n      const dataset = await this.getDatasetById({ id: args.datasetId, filters: args.filters });\n      if (!dataset) return;\n    }\n    return this._doDeleteItem(args);\n  }\n\n  /** Subclasses implement actual storage delete logic with SCD-2 versioning */\n  protected abstract _doDeleteItem(args: DeleteDatasetItemInput): Promise<void>;\n\n  abstract listItems(args: ListDatasetItemsInput): Promise<ListDatasetItemsOutput>;\n  abstract getItemById(args: { id: string; datasetVersion?: number }): Promise<DatasetItem | null>;\n\n  // SCD-2 queries\n  abstract getItemsByVersion(args: { datasetId: string; version: number }): Promise<DatasetItem[]>;\n  abstract getItemHistory(itemId: string): Promise<DatasetItemRow[]>;\n\n  // Dataset version methods\n  abstract createDatasetVersion(datasetId: string, version: number): Promise<DatasetVersion>;\n  abstract listDatasetVersions(input: ListDatasetVersionsInput): Promise<ListDatasetVersionsOutput>;\n\n  /**\n   * Batch insert items to a dataset. Validates all items against dataset schemas,\n   * then delegates to subclass which handles SCD-2 versioning internally.\n   */\n  async batchInsertItems(input: BatchInsertItemsInput): Promise<DatasetItem[]> {\n    const dataset = await this.getDatasetById({ id: input.datasetId, filters: input.filters });\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${input.datasetId}`);\n    }\n\n    // Validate all items against schemas\n    const validator = getSchemaValidator();\n    const cacheKey = `dataset:${input.datasetId}`;\n\n    for (const [index, itemData] of input.items.entries()) {\n      validateDatasetItemExternalId(itemData.externalId);\n      validateDatasetItemPayloadSerialization(itemData, `items[${index}]`);\n      if (dataset.inputSchema) {\n        validator.validate(itemData.input, dataset.inputSchema, 'input', `${cacheKey}:input`);\n      }\n      if (dataset.groundTruthSchema && itemData.groundTruth !== undefined) {\n        validator.validate(itemData.groundTruth, dataset.groundTruthSchema, 'groundTruth', `${cacheKey}:output`);\n      }\n    }\n\n    return this._doBatchInsertItems(input);\n  }\n\n  protected planDatasetItemBatch(\n    items: BatchInsertItemsInput['items'],\n    historyRows: DatasetItemRow[],\n    createId: () => string,\n  ): DatasetItemBatchPlan {\n    return createDatasetItemBatchPlan(items, historyRows, createId);\n  }\n\n  protected datasetItemFromRow(row: DatasetItemRow): DatasetItem {\n    const { validTo: _validTo, isDeleted: _isDeleted, ...item } = row;\n    return item;\n  }\n\n  /** Subclasses implement batch insert with SCD-2 versioning */\n  protected abstract _doBatchInsertItems(input: BatchInsertItemsInput): Promise<DatasetItem[]>;\n\n  /**\n   * Batch delete items from a dataset. Creates tombstone rows via SCD-2.\n   * Subclasses implement _doBatchDeleteItems which handles SCD-2 versioning internally.\n   */\n  async batchDeleteItems(input: BatchDeleteItemsInput): Promise<void> {\n    const dataset = await this.getDatasetById({ id: input.datasetId, filters: input.filters });\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${input.datasetId}`);\n    }\n\n    return this._doBatchDeleteItems(input);\n  }\n\n  /** Subclasses implement batch delete with SCD-2 versioning */\n  protected abstract _doBatchDeleteItems(input: BatchDeleteItemsInput): Promise<void>;\n}\n","import { calculatePagination, normalizePerPage } from '../../base';\nimport type {\n  DatasetRecord,\n  DatasetItem,\n  DatasetItemRow,\n  DatasetVersion,\n  CreateDatasetInput,\n  UpdateDatasetInput,\n  AddDatasetItemInput,\n  UpdateDatasetItemInput,\n  DeleteDatasetItemInput,\n  ListDatasetsInput,\n  ListDatasetsOutput,\n  ListDatasetItemsInput,\n  ListDatasetItemsOutput,\n  ListDatasetVersionsInput,\n  ListDatasetVersionsOutput,\n  BatchInsertItemsInput,\n  BatchDeleteItemsInput,\n  DatasetTenancyFilters,\n} from '../../types';\n\nfunction matchesTenancy(\n  record: { organizationId?: string | null; projectId?: string | null },\n  filters: DatasetTenancyFilters | undefined,\n): boolean {\n  if (!filters) return true;\n  if (filters.organizationId !== undefined && record.organizationId !== filters.organizationId) return false;\n  if (filters.projectId !== undefined && record.projectId !== filters.projectId) return false;\n  return true;\n}\nimport type { InMemoryDB } from '../inmemory-db';\nimport { DatasetsStorage } from './base';\nimport { createDatasetItemIdentityConflictError, datasetItemPayloadsEqual } from './identity';\n\n/** Convert a storage row to the public DatasetItem type (strips validTo/isDeleted) */\nfunction toDatasetItem(row: DatasetItemRow): DatasetItem {\n  return {\n    id: row.id,\n    datasetId: row.datasetId,\n    datasetVersion: row.datasetVersion,\n    externalId: row.externalId,\n    organizationId: row.organizationId,\n    projectId: row.projectId,\n    input: row.input,\n    groundTruth: row.groundTruth,\n    expectedTrajectory: row.expectedTrajectory,\n    toolMocks: row.toolMocks,\n    unmockedToolPolicy: row.unmockedToolPolicy,\n    scorerIds: row.scorerIds,\n    requestContext: row.requestContext,\n    metadata: row.metadata,\n    source: row.source,\n    createdAt: row.createdAt,\n    updatedAt: row.updatedAt,\n  };\n}\n\n/** Internal record that allows null schemas (for \"clear schema\" semantics) */\ntype InternalDatasetRecord = Omit<DatasetRecord, 'inputSchema' | 'groundTruthSchema' | 'requestContextSchema'> & {\n  inputSchema?: Record<string, unknown> | null;\n  groundTruthSchema?: Record<string, unknown> | null;\n  requestContextSchema?: Record<string, unknown> | null;\n};\n\n/** Normalize internal record (which may have null schemas) to public DatasetRecord */\nfunction toDatasetRecord(record: InternalDatasetRecord): DatasetRecord {\n  return {\n    ...record,\n    inputSchema: record.inputSchema ?? undefined,\n    groundTruthSchema: record.groundTruthSchema ?? undefined,\n    requestContextSchema: record.requestContextSchema ?? undefined,\n  };\n}\n\nexport class DatasetsInMemory extends DatasetsStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.datasets.clear();\n    this.db.datasetItems.clear();\n    this.db.datasetVersions.clear();\n  }\n\n  // Dataset CRUD\n  async createDataset(input: CreateDatasetInput): Promise<DatasetRecord> {\n    const id = input.id ?? crypto.randomUUID();\n    if (input.id !== undefined) {\n      this.validateCallerDefinedDatasetId(input.id);\n      const existing = this.db.datasets.get(input.id);\n      if (existing) {\n        return this.resolveExistingDataset(toDatasetRecord(existing), { ...input, id: input.id });\n      }\n    }\n\n    const now = new Date();\n    const dataset = {\n      id,\n      name: input.name,\n      description: input.description,\n      metadata: input.metadata,\n      inputSchema: input.inputSchema,\n      groundTruthSchema: input.groundTruthSchema,\n      requestContextSchema: input.requestContextSchema,\n      targetType: input.targetType,\n      targetIds: input.targetIds,\n      scorerIds: input.scorerIds ?? null,\n      organizationId: input.organizationId ?? null,\n      projectId: input.projectId ?? null,\n      candidateKey: input.candidateKey ?? null,\n      candidateId: input.candidateId ?? null,\n      version: 0,\n      createdAt: now,\n      updatedAt: now,\n    } as DatasetRecord;\n    this.db.datasets.set(id, dataset);\n    return toDatasetRecord(dataset);\n  }\n\n  async getDatasetById({\n    id,\n    filters,\n  }: {\n    id: string;\n    filters?: DatasetTenancyFilters;\n  }): Promise<DatasetRecord | null> {\n    const record = this.db.datasets.get(id);\n    if (!record) return null;\n    if (!matchesTenancy(record, filters)) return null;\n    return toDatasetRecord(record);\n  }\n\n  protected async _doUpdateDataset(args: UpdateDatasetInput): Promise<DatasetRecord> {\n    const existing = this.db.datasets.get(args.id);\n    if (!existing) {\n      throw new Error(`Dataset not found: ${args.id}`);\n    }\n\n    const updated = {\n      ...existing,\n      name: args.name ?? existing.name,\n      description: args.description ?? existing.description,\n      metadata: args.metadata ?? existing.metadata,\n      inputSchema: args.inputSchema !== undefined ? args.inputSchema : existing.inputSchema,\n      groundTruthSchema: args.groundTruthSchema !== undefined ? args.groundTruthSchema : existing.groundTruthSchema,\n      requestContextSchema:\n        args.requestContextSchema !== undefined ? args.requestContextSchema : existing.requestContextSchema,\n      tags: args.tags !== undefined ? args.tags : existing.tags,\n      targetType: args.targetType !== undefined ? args.targetType : existing.targetType,\n      targetIds: args.targetIds !== undefined ? args.targetIds : existing.targetIds,\n      scorerIds: args.scorerIds !== undefined ? args.scorerIds : existing.scorerIds,\n      // Tenancy and candidate identity are immutable after creation.\n      updatedAt: new Date(),\n    } as DatasetRecord;\n    this.db.datasets.set(args.id, updated);\n    return toDatasetRecord(updated);\n  }\n\n  async deleteDataset({ id, filters }: { id: string; filters?: DatasetTenancyFilters }): Promise<void> {\n    const existing = this.db.datasets.get(id);\n    if (!existing) return;\n    if (!matchesTenancy(existing, filters)) return;\n\n    // Cascade: delete items and versions\n    for (const [itemId, rows] of this.db.datasetItems) {\n      if (rows.length > 0 && rows[0]!.datasetId === id) {\n        this.db.datasetItems.delete(itemId);\n      }\n    }\n    for (const [vId, v] of this.db.datasetVersions) {\n      if (v.datasetId === id) {\n        this.db.datasetVersions.delete(vId);\n      }\n    }\n\n    // F3 fix: detach experiments (SET NULL) instead of deleting them\n    for (const [expId, exp] of this.db.experiments) {\n      if (exp.datasetId === id) {\n        this.db.experiments.set(expId, { ...exp, datasetId: null, datasetVersion: null });\n      }\n    }\n\n    this.db.datasets.delete(id);\n  }\n\n  async listDatasets(args: ListDatasetsInput): Promise<ListDatasetsOutput> {\n    let datasets = Array.from(this.db.datasets.values());\n\n    if (args.filters) {\n      const { organizationId, projectId, candidateKey, candidateId, targetType, targetIds, name } = args.filters;\n      const nameLower = name?.toLowerCase();\n      const targetIdsSet = targetIds && targetIds.length > 0 ? new Set(targetIds) : undefined;\n      datasets = datasets.filter(d => {\n        if (organizationId !== undefined && d.organizationId !== organizationId) return false;\n        if (projectId !== undefined && d.projectId !== projectId) return false;\n        if (candidateKey !== undefined && d.candidateKey !== candidateKey) return false;\n        if (candidateId !== undefined && d.candidateId !== candidateId) return false;\n        if (targetType !== undefined && d.targetType !== targetType) return false;\n        if (targetIdsSet) {\n          if (!d.targetIds || !d.targetIds.some(id => targetIdsSet.has(id))) return false;\n        }\n        if (nameLower !== undefined && !d.name.toLowerCase().includes(nameLower)) return false;\n        return true;\n      });\n    }\n\n    // Sort by createdAt descending (newest first)\n    datasets.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n    const { page, perPage: perPageInput } = args.pagination;\n    const perPage = normalizePerPage(perPageInput, 100);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? datasets.length : start + perPage;\n\n    return {\n      datasets: datasets.slice(start, end).map(toDatasetRecord),\n      pagination: {\n        total: datasets.length,\n        page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : datasets.length > end,\n      },\n    };\n  }\n\n  // --- SCD-2 item mutations ---\n\n  protected async _doAddItem(args: AddDatasetItemInput): Promise<DatasetItem> {\n    const dataset = this.db.datasets.get(args.datasetId);\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${args.datasetId}`);\n    }\n\n    // Bump version (T3.7, T3.26 — only bumps version, not updatedAt)\n    const newVersion = dataset.version + 1;\n    this.db.datasets.set(args.datasetId, { ...dataset, version: newVersion });\n\n    const now = new Date();\n    const id = crypto.randomUUID();\n    const row: DatasetItemRow = {\n      id,\n      datasetId: args.datasetId,\n      datasetVersion: newVersion,\n      externalId: args.externalId ?? null,\n      // Tenancy inherited from parent dataset (Option B — never settable per item)\n      organizationId: dataset.organizationId ?? null,\n      projectId: dataset.projectId ?? null,\n      validTo: null,\n      isDeleted: false,\n      input: args.input,\n      groundTruth: args.groundTruth,\n      expectedTrajectory: args.expectedTrajectory,\n      toolMocks: args.toolMocks,\n      unmockedToolPolicy: args.unmockedToolPolicy,\n      scorerIds: args.scorerIds,\n      requestContext: args.requestContext,\n      metadata: args.metadata,\n      source: args.source,\n      createdAt: now,\n      updatedAt: now,\n    };\n\n    this.db.datasetItems.set(id, [row]);\n\n    // T3.11 — every mutation inserts exactly one dataset_version row\n    await this.createDatasetVersion(args.datasetId, newVersion);\n\n    return toDatasetItem(row);\n  }\n\n  protected async _doUpdateItem(args: UpdateDatasetItemInput): Promise<DatasetItem> {\n    const rows = this.db.datasetItems.get(args.id);\n    if (!rows || rows.length === 0) {\n      throw new Error(`Item not found: ${args.id}`);\n    }\n\n    const currentRow = rows.find(r => r.validTo === null && !r.isDeleted);\n    if (!currentRow) {\n      throw new Error(`Item not found: ${args.id}`);\n    }\n    if (currentRow.datasetId !== args.datasetId) {\n      throw new Error(`Item ${args.id} does not belong to dataset ${args.datasetId}`);\n    }\n\n    const dataset = this.db.datasets.get(args.datasetId);\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${args.datasetId}`);\n    }\n\n    // Bump version (T3.26)\n    const newVersion = dataset.version + 1;\n    this.db.datasets.set(args.datasetId, { ...dataset, version: newVersion });\n\n    // T3.8 — close old row\n    currentRow.validTo = newVersion;\n\n    // T3.8 — insert new row with same id\n    const now = new Date();\n    const newRow: DatasetItemRow = {\n      id: args.id,\n      datasetId: args.datasetId,\n      datasetVersion: newVersion,\n      externalId: currentRow.externalId ?? null,\n      // Re-inherit tenancy from parent dataset (handles dataset-level retroactive tenancy backfill)\n      organizationId: dataset.organizationId ?? null,\n      projectId: dataset.projectId ?? null,\n      validTo: null,\n      isDeleted: false,\n      input: args.input !== undefined ? args.input : currentRow.input,\n      groundTruth: args.groundTruth !== undefined ? args.groundTruth : currentRow.groundTruth,\n      expectedTrajectory:\n        args.expectedTrajectory !== undefined ? args.expectedTrajectory : currentRow.expectedTrajectory,\n      toolMocks: args.toolMocks !== undefined ? args.toolMocks : currentRow.toolMocks,\n      unmockedToolPolicy:\n        args.unmockedToolPolicy !== undefined ? args.unmockedToolPolicy : currentRow.unmockedToolPolicy,\n      scorerIds: args.scorerIds !== undefined ? (args.scorerIds ?? undefined) : currentRow.scorerIds,\n      requestContext: args.requestContext !== undefined ? args.requestContext : currentRow.requestContext,\n      metadata: args.metadata !== undefined ? args.metadata : currentRow.metadata,\n      source: args.source !== undefined ? args.source : currentRow.source,\n      createdAt: currentRow.createdAt,\n      updatedAt: now,\n    };\n    rows.push(newRow);\n\n    // T3.11\n    await this.createDatasetVersion(args.datasetId, newVersion);\n\n    return toDatasetItem(newRow);\n  }\n\n  protected async _doDeleteItem({ id, datasetId }: DeleteDatasetItemInput): Promise<void> {\n    const rows = this.db.datasetItems.get(id);\n    if (!rows || rows.length === 0) {\n      return; // no-op if item doesn't exist\n    }\n\n    const currentRow = rows.find(r => r.validTo === null && !r.isDeleted);\n    if (!currentRow) {\n      return; // already deleted\n    }\n    if (currentRow.datasetId !== datasetId) {\n      throw new Error(`Item ${id} does not belong to dataset ${datasetId}`);\n    }\n\n    const dataset = this.db.datasets.get(datasetId);\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${datasetId}`);\n    }\n\n    // Bump version (T3.26)\n    const newVersion = dataset.version + 1;\n    this.db.datasets.set(datasetId, { ...dataset, version: newVersion });\n\n    // T3.9 — close old row\n    currentRow.validTo = newVersion;\n\n    // T3.9 — insert tombstone.\n    // Tenancy is read from the prior current row rather than re-fetched from\n    // the parent dataset (the pattern used by every DB adapter). This is\n    // deliberate and safe: tenancy is immutable post-create on both datasets\n    // and items (see CreateDatasetInput / UpdateDatasetInput in ../../types.ts),\n    // so currentRow.organizationId / currentRow.projectId are guaranteed to\n    // equal dataset.organizationId / dataset.projectId. Keep this branch in\n    // sync with the DB adapters if that invariant ever changes.\n    const now = new Date();\n    rows.push({\n      id,\n      datasetId,\n      datasetVersion: newVersion,\n      externalId: currentRow.externalId ?? null,\n      organizationId: currentRow.organizationId ?? null,\n      projectId: currentRow.projectId ?? null,\n      validTo: null,\n      isDeleted: true,\n      input: currentRow.input,\n      groundTruth: currentRow.groundTruth,\n      expectedTrajectory: currentRow.expectedTrajectory,\n      toolMocks: currentRow.toolMocks,\n      unmockedToolPolicy: currentRow.unmockedToolPolicy,\n      scorerIds: currentRow.scorerIds,\n      requestContext: currentRow.requestContext,\n      metadata: currentRow.metadata,\n      source: currentRow.source,\n      createdAt: currentRow.createdAt,\n      updatedAt: now,\n    });\n\n    // T3.11\n    await this.createDatasetVersion(datasetId, newVersion);\n  }\n\n  // --- SCD-2 queries ---\n\n  async getItemById(args: { id: string; datasetVersion?: number }): Promise<DatasetItem | null> {\n    const rows = this.db.datasetItems.get(args.id);\n    if (!rows || rows.length === 0) return null;\n\n    if (args.datasetVersion !== undefined) {\n      // T3.13 — exact version match, exclude deleted\n      const row = rows.find(r => r.datasetVersion === args.datasetVersion && !r.isDeleted);\n      return row ? toDatasetItem(row) : null;\n    }\n\n    // T3.12 — current row (validTo IS NULL AND isDeleted = false)\n    const current = rows.find(r => r.validTo === null && !r.isDeleted);\n    return current ? toDatasetItem(current) : null;\n  }\n\n  async getItemsByVersion({ datasetId, version }: { datasetId: string; version: number }): Promise<DatasetItem[]> {\n    // T3.14 — SCD-2 range query: items visible at version N\n    const items: DatasetItem[] = [];\n\n    for (const rows of this.db.datasetItems.values()) {\n      if (rows.length === 0 || rows[0]!.datasetId !== datasetId) continue;\n\n      // Find the row visible at this version:\n      // datasetVersion <= N AND (validTo IS NULL OR validTo > N) AND isDeleted = false\n      const visible = rows.find(\n        r => r.datasetVersion <= version && (r.validTo === null || r.validTo > version) && !r.isDeleted,\n      );\n      if (visible) {\n        items.push(toDatasetItem(visible));\n      }\n    }\n\n    items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.id.localeCompare(a.id));\n    return items;\n  }\n\n  async getItemHistory(itemId: string): Promise<DatasetItemRow[]> {\n    // ALL rows including tombstones, ordered by datasetVersion DESC (newest first)\n    const rows = this.db.datasetItems.get(itemId);\n    if (!rows) return [];\n    return [...rows].sort((a, b) => b.datasetVersion - a.datasetVersion);\n  }\n\n  async listItems(args: ListDatasetItemsInput): Promise<ListDatasetItemsOutput> {\n    let items: DatasetItem[];\n\n    if (args.version !== undefined) {\n      // SCD-2 time-travel query\n      items = await this.getItemsByVersion({ datasetId: args.datasetId, version: args.version });\n    } else {\n      // T3.16 — current items only (validTo IS NULL AND isDeleted = false)\n      items = [];\n      for (const rows of this.db.datasetItems.values()) {\n        if (rows.length === 0 || rows[0]!.datasetId !== args.datasetId) continue;\n        const current = rows.find(r => r.validTo === null && !r.isDeleted);\n        if (current) {\n          items.push(toDatasetItem(current));\n        }\n      }\n    }\n\n    if (args.filters) {\n      const { organizationId, projectId } = args.filters;\n      items = items.filter(item => {\n        if (organizationId !== undefined && item.organizationId !== organizationId) return false;\n        if (projectId !== undefined && item.projectId !== projectId) return false;\n        return true;\n      });\n    }\n\n    // Filter by search term if specified (case-insensitive partial match on input/groundTruth)\n    if (args.search) {\n      const searchLower = args.search.toLowerCase();\n      items = items.filter(item => {\n        const inputStr = typeof item.input === 'string' ? item.input : JSON.stringify(item.input);\n        const outputStr = item.groundTruth\n          ? typeof item.groundTruth === 'string'\n            ? item.groundTruth\n            : JSON.stringify(item.groundTruth)\n          : '';\n        return inputStr.toLowerCase().includes(searchLower) || outputStr.toLowerCase().includes(searchLower);\n      });\n    }\n\n    // Sort by createdAt descending, then by id descending for stability\n    items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.id.localeCompare(a.id));\n\n    const { page, perPage: perPageInput } = args.pagination;\n    const perPage = normalizePerPage(perPageInput, 100);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? items.length : start + perPage;\n\n    return {\n      items: items.slice(start, end),\n      pagination: {\n        total: items.length,\n        page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : items.length > end,\n      },\n    };\n  }\n\n  // --- Dataset version methods ---\n\n  async createDatasetVersion(datasetId: string, version: number): Promise<DatasetVersion> {\n    const id = crypto.randomUUID();\n    const dsVersion: DatasetVersion = {\n      id,\n      datasetId,\n      version,\n      createdAt: new Date(),\n    };\n    this.db.datasetVersions.set(id, dsVersion);\n    return dsVersion;\n  }\n\n  async listDatasetVersions(input: ListDatasetVersionsInput): Promise<ListDatasetVersionsOutput> {\n    const versions: DatasetVersion[] = [];\n    for (const v of this.db.datasetVersions.values()) {\n      if (v.datasetId === input.datasetId) {\n        versions.push(v);\n      }\n    }\n    versions.sort((a, b) => b.version - a.version);\n\n    const { page, perPage: perPageInput } = input.pagination;\n    const perPage = normalizePerPage(perPageInput, 100);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? versions.length : start + perPage;\n\n    return {\n      versions: versions.slice(start, end),\n      pagination: {\n        total: versions.length,\n        page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : versions.length > end,\n      },\n    };\n  }\n\n  // --- Bulk operations (SCD-2 internally) ---\n\n  protected async _doBatchInsertItems(input: BatchInsertItemsInput): Promise<DatasetItem[]> {\n    const dataset = this.db.datasets.get(input.datasetId);\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${input.datasetId}`);\n    }\n    if (input.items.length === 0) return [];\n\n    const acceptedByExternalId = new Map<string, { first: DatasetItemRow; current: DatasetItemRow | null }>();\n    for (const rows of this.db.datasetItems.values()) {\n      const first = rows[0];\n      if (!first || first.datasetId !== input.datasetId || !first.externalId) continue;\n      const existing = acceptedByExternalId.get(first.externalId);\n      if (existing && existing.first.id !== first.id) {\n        throw new Error(`Dataset item identity history is corrupt for externalId: ${first.externalId}`);\n      }\n      acceptedByExternalId.set(first.externalId, {\n        first,\n        current: rows.find(row => row.validTo === null && !row.isDeleted) ?? null,\n      });\n    }\n\n    const conflicts = [];\n    const planned = new Map<string, { id: string; item: (typeof input.items)[number] }>();\n    const plannedByExternalId = new Map<string, { id: string; item: (typeof input.items)[number] }>();\n    const resolvedIds: string[] = [];\n\n    for (const [index, item] of input.items.entries()) {\n      if (!item.externalId) {\n        const id = crypto.randomUUID();\n        planned.set(id, { id, item });\n        resolvedIds.push(id);\n        continue;\n      }\n\n      const accepted = acceptedByExternalId.get(item.externalId);\n      if (accepted) {\n        if (!accepted.current) {\n          conflicts.push({\n            index,\n            externalId: item.externalId,\n            existingItemId: accepted.first.id,\n            reason: 'deleted' as const,\n          });\n        } else if (!datasetItemPayloadsEqual(item, accepted.first)) {\n          conflicts.push({\n            index,\n            externalId: item.externalId,\n            existingItemId: accepted.first.id,\n            reason: 'payload_mismatch' as const,\n          });\n        }\n        resolvedIds.push(accepted.first.id);\n        continue;\n      }\n\n      const requestLocal = plannedByExternalId.get(item.externalId);\n      if (requestLocal) {\n        if (\n          !datasetItemPayloadsEqual(item, {\n            ...requestLocal.item,\n            id: requestLocal.id,\n            datasetId: input.datasetId,\n            datasetVersion: 0,\n            validTo: null,\n            isDeleted: false,\n            createdAt: new Date(0),\n            updatedAt: new Date(0),\n          })\n        ) {\n          conflicts.push({\n            index,\n            externalId: item.externalId,\n            existingItemId: requestLocal.id,\n            reason: 'payload_mismatch' as const,\n          });\n        }\n        resolvedIds.push(requestLocal.id);\n        continue;\n      }\n\n      const id = crypto.randomUUID();\n      const plannedEntry = { id, item };\n      planned.set(id, plannedEntry);\n      plannedByExternalId.set(item.externalId, plannedEntry);\n      resolvedIds.push(id);\n    }\n\n    if (conflicts.length > 0) throw createDatasetItemIdentityConflictError(conflicts);\n    if (planned.size === 0) {\n      return resolvedIds.map(id => {\n        const rows = this.db.datasetItems.get(id)!;\n        return toDatasetItem(rows.find(row => row.validTo === null && !row.isDeleted)!);\n      });\n    }\n\n    const newVersion = dataset.version + 1;\n    this.db.datasets.set(input.datasetId, { ...dataset, version: newVersion });\n    const now = new Date();\n    const inserted = new Map<string, DatasetItem>();\n\n    for (const { id, item } of planned.values()) {\n      const row: DatasetItemRow = {\n        id,\n        datasetId: input.datasetId,\n        datasetVersion: newVersion,\n        externalId: item.externalId ?? null,\n        organizationId: dataset.organizationId ?? null,\n        projectId: dataset.projectId ?? null,\n        validTo: null,\n        isDeleted: false,\n        input: item.input,\n        groundTruth: item.groundTruth,\n        expectedTrajectory: item.expectedTrajectory,\n        toolMocks: item.toolMocks,\n        unmockedToolPolicy: item.unmockedToolPolicy,\n        scorerIds: item.scorerIds,\n        requestContext: item.requestContext,\n        metadata: item.metadata,\n        source: item.source,\n        createdAt: now,\n        updatedAt: now,\n      };\n      this.db.datasetItems.set(id, [row]);\n      inserted.set(id, toDatasetItem(row));\n    }\n\n    await this.createDatasetVersion(input.datasetId, newVersion);\n\n    return resolvedIds.map(id => {\n      const newItem = inserted.get(id);\n      if (newItem) return newItem;\n      const rows = this.db.datasetItems.get(id)!;\n      return toDatasetItem(rows.find(row => row.validTo === null && !row.isDeleted)!);\n    });\n  }\n\n  protected async _doBatchDeleteItems(input: BatchDeleteItemsInput): Promise<void> {\n    const dataset = this.db.datasets.get(input.datasetId);\n    if (!dataset) {\n      throw new Error(`Dataset not found: ${input.datasetId}`);\n    }\n\n    // T3.20 — single version increment\n    const newVersion = dataset.version + 1;\n    this.db.datasets.set(input.datasetId, { ...dataset, version: newVersion });\n\n    const now = new Date();\n\n    for (const itemId of input.itemIds) {\n      const rows = this.db.datasetItems.get(itemId);\n      if (!rows) continue;\n\n      const currentRow = rows.find(r => r.validTo === null && !r.isDeleted);\n      if (!currentRow || currentRow.datasetId !== input.datasetId) continue;\n\n      // Close old row\n      currentRow.validTo = newVersion;\n\n      // Insert tombstone. See _doDeleteItem above for why it's safe to read\n      // tenancy from the prior current row rather than re-fetching from the\n      // parent dataset (tenancy is immutable post-create on both sides).\n      rows.push({\n        id: itemId,\n        datasetId: input.datasetId,\n        datasetVersion: newVersion,\n        externalId: currentRow.externalId ?? null,\n        organizationId: currentRow.organizationId ?? null,\n        projectId: currentRow.projectId ?? null,\n        validTo: null,\n        isDeleted: true,\n        input: currentRow.input,\n        groundTruth: currentRow.groundTruth,\n        expectedTrajectory: currentRow.expectedTrajectory,\n        toolMocks: currentRow.toolMocks,\n        unmockedToolPolicy: currentRow.unmockedToolPolicy,\n        scorerIds: currentRow.scorerIds,\n        requestContext: currentRow.requestContext,\n        metadata: currentRow.metadata,\n        source: currentRow.source,\n        createdAt: currentRow.createdAt,\n        updatedAt: now,\n      });\n    }\n\n    // T3.11\n    await this.createDatasetVersion(input.datasetId, newVersion);\n  }\n}\n","import type {\n  Experiment,\n  ExperimentResult,\n  ExperimentReviewCounts,\n  ExperimentTenancyFilters,\n  CreateExperimentInput,\n  UpdateExperimentInput,\n  AddExperimentResultInput,\n  UpdateExperimentResultInput,\n  ListExperimentsInput,\n  ListExperimentsOutput,\n  ListExperimentResultsInput,\n  ListExperimentResultsOutput,\n} from '../../types';\nimport { StorageDomain } from '../base';\n\n/**\n * Abstract base class for dataset experiments storage domain.\n * Provides the contract for experiment lifecycle and result tracking.\n */\nexport abstract class ExperimentsStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'EXPERIMENTS',\n    });\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    // Default no-op - subclasses override\n  }\n\n  // Experiment lifecycle\n  abstract createExperiment(input: CreateExperimentInput): Promise<Experiment>;\n  abstract updateExperiment(input: UpdateExperimentInput): Promise<Experiment>;\n  /**\n   * When `filters` is set, returns `null` on tenancy mismatch (never throws,\n   * so existence does not leak via error timing/text). Implementers must fold\n   * the tenancy predicate into the SELECT, not filter in application code.\n   */\n  abstract getExperimentById(args: { id: string; filters?: ExperimentTenancyFilters }): Promise<Experiment | null>;\n  abstract listExperiments(args: ListExperimentsInput): Promise<ListExperimentsOutput>;\n  /**\n   * Deletes an experiment and cascades to its results.\n   *\n   * When `filters` is set, silent no-op on tenancy mismatch (never throws,\n   * so existence does not leak). A resolved Promise does not imply a row was\n   * deleted. Implementers must fold the tenancy predicate into the destructive\n   * DML itself — a pre-check followed by an unscoped DELETE is unsafe under\n   * concurrent id reuse across tenants.\n   *\n   * When `filters` is omitted, implementations MAY skip the tenancy predicate\n   * entirely (backward compat: callers explicitly opt out of scoping).\n   */\n  abstract deleteExperiment(args: { id: string; filters?: ExperimentTenancyFilters }): Promise<void>;\n\n  // Results (per-item)\n  abstract addExperimentResult(input: AddExperimentResultInput): Promise<ExperimentResult>;\n  abstract updateExperimentResult(input: UpdateExperimentResultInput): Promise<ExperimentResult>;\n  /**\n   * When `filters` is set, returns `null` on tenancy mismatch (never throws).\n   * Implementers must fold the tenancy predicate into the SELECT.\n   */\n  abstract getExperimentResultById(args: {\n    id: string;\n    filters?: ExperimentTenancyFilters;\n  }): Promise<ExperimentResult | null>;\n  abstract listExperimentResults(args: ListExperimentResultsInput): Promise<ListExperimentResultsOutput>;\n  /**\n   * Deletes all results for an experiment.\n   *\n   * When `filters` is set, silent no-op on tenancy mismatch (never throws).\n   * Result rows carry `organizationId`/`projectId` from their parent, so\n   * implementers must fold the tenancy predicate into the destructive DML —\n   * a parent pre-check followed by an unscoped `DELETE WHERE experimentId = ?`\n   * is unsafe under concurrent id reuse.\n   *\n   * When `filters` is omitted, implementations MAY skip the tenancy predicate\n   * entirely (backward compat: callers explicitly opt out of scoping). This is\n   * why pg/mysql/spanner take an unscoped fast path here while mongodb/libsql\n   * fold the (empty) filter unconditionally — both are correct.\n   */\n  abstract deleteExperimentResults(args: { experimentId: string; filters?: ExperimentTenancyFilters }): Promise<void>;\n\n  // Aggregation\n  abstract getReviewSummary(): Promise<ExperimentReviewCounts[]>;\n}\n","import { calculatePagination, normalizePerPage } from '../../base';\nimport type {\n  Experiment,\n  ExperimentResult,\n  ExperimentReviewCounts,\n  ExperimentTenancyFilters,\n  CreateExperimentInput,\n  UpdateExperimentInput,\n  AddExperimentResultInput,\n  UpdateExperimentResultInput,\n  ListExperimentsInput,\n  ListExperimentsOutput,\n  ListExperimentResultsInput,\n  ListExperimentResultsOutput,\n} from '../../types';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { ExperimentsStorage } from './base';\n\nexport class ExperimentsInMemory extends ExperimentsStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.experiments.clear();\n    this.db.experimentResults.clear();\n  }\n\n  // Experiment lifecycle\n  async createExperiment(input: CreateExperimentInput): Promise<Experiment> {\n    const now = new Date();\n    const experiment: Experiment = {\n      id: input.id ?? crypto.randomUUID(),\n      datasetId: input.datasetId,\n      datasetVersion: input.datasetVersion,\n      agentVersion: input.agentVersion ?? null,\n      targetType: input.targetType,\n      targetId: input.targetId,\n      name: input.name,\n      description: input.description,\n      metadata: input.metadata,\n      status: 'pending',\n      totalItems: input.totalItems,\n      succeededCount: 0,\n      failedCount: 0,\n      skippedCount: 0,\n      organizationId: input.organizationId ?? null,\n      projectId: input.projectId ?? null,\n      startedAt: null,\n      completedAt: null,\n      createdAt: now,\n      updatedAt: now,\n    };\n    this.db.experiments.set(experiment.id, experiment);\n    return experiment;\n  }\n\n  async updateExperiment(input: UpdateExperimentInput): Promise<Experiment> {\n    const existing = this.db.experiments.get(input.id);\n    if (!existing) {\n      throw new Error(`Experiment not found: ${input.id}`);\n    }\n    const updated: Experiment = {\n      ...existing,\n      status: input.status ?? existing.status,\n      totalItems: input.totalItems ?? existing.totalItems,\n      succeededCount: input.succeededCount ?? existing.succeededCount,\n      failedCount: input.failedCount ?? existing.failedCount,\n      skippedCount: input.skippedCount ?? existing.skippedCount,\n      startedAt: input.startedAt ?? existing.startedAt,\n      completedAt: input.completedAt ?? existing.completedAt,\n      name: input.name ?? existing.name,\n      description: input.description ?? existing.description,\n      metadata: input.metadata ?? existing.metadata,\n      updatedAt: new Date(),\n    };\n    this.db.experiments.set(input.id, updated);\n    return updated;\n  }\n\n  async getExperimentById(args: { id: string; filters?: ExperimentTenancyFilters }): Promise<Experiment | null> {\n    const row = this.db.experiments.get(args.id);\n    if (!row) return null;\n    if (args.filters?.organizationId !== undefined && (row.organizationId ?? null) !== args.filters.organizationId) {\n      return null;\n    }\n    if (args.filters?.projectId !== undefined && (row.projectId ?? null) !== args.filters.projectId) {\n      return null;\n    }\n    return row;\n  }\n\n  async listExperiments(args: ListExperimentsInput): Promise<ListExperimentsOutput> {\n    let experiments = Array.from(this.db.experiments.values());\n\n    // Apply filters\n    if (args.datasetId) {\n      experiments = experiments.filter(r => r.datasetId === args.datasetId);\n    }\n    if (args.targetType) {\n      experiments = experiments.filter(r => r.targetType === args.targetType);\n    }\n    if (args.targetId) {\n      experiments = experiments.filter(r => r.targetId === args.targetId);\n    }\n    if (args.agentVersion) {\n      experiments = experiments.filter(r => r.agentVersion === args.agentVersion);\n    }\n    if (args.status) {\n      experiments = experiments.filter(r => r.status === args.status);\n    }\n    if (args.filters?.organizationId !== undefined) {\n      experiments = experiments.filter(r => (r.organizationId ?? null) === args.filters!.organizationId);\n    }\n    if (args.filters?.projectId !== undefined) {\n      experiments = experiments.filter(r => (r.projectId ?? null) === args.filters!.projectId);\n    }\n\n    // Sort by createdAt descending (newest first)\n    experiments.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());\n\n    const { page, perPage: perPageInput } = args.pagination;\n    const perPage = normalizePerPage(perPageInput, 100);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? experiments.length : start + perPage;\n\n    return {\n      experiments: experiments.slice(start, end),\n      pagination: {\n        total: experiments.length,\n        page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : experiments.length > end,\n      },\n    };\n  }\n\n  async deleteExperiment(args: { id: string; filters?: ExperimentTenancyFilters }): Promise<void> {\n    const existing = this.db.experiments.get(args.id);\n    if (!existing) return;\n    if (\n      args.filters?.organizationId !== undefined &&\n      (existing.organizationId ?? null) !== args.filters.organizationId\n    ) {\n      return;\n    }\n    if (args.filters?.projectId !== undefined && (existing.projectId ?? null) !== args.filters.projectId) {\n      return;\n    }\n    this.db.experiments.delete(args.id);\n    // Also delete associated results\n    for (const [resultId, result] of this.db.experimentResults) {\n      if (result.experimentId === args.id) {\n        this.db.experimentResults.delete(resultId);\n      }\n    }\n  }\n\n  // Results (per-item)\n  async addExperimentResult(input: AddExperimentResultInput): Promise<ExperimentResult> {\n    const now = new Date();\n    const result: ExperimentResult = {\n      id: input.id ?? crypto.randomUUID(),\n      experimentId: input.experimentId,\n      itemId: input.itemId,\n      itemDatasetVersion: input.itemDatasetVersion,\n      input: input.input,\n      output: input.output,\n      groundTruth: input.groundTruth,\n      error: input.error,\n      startedAt: input.startedAt,\n      completedAt: input.completedAt,\n      retryCount: input.retryCount,\n      traceId: input.traceId ?? null,\n      status: input.status ?? null,\n      tags: input.tags ?? null,\n      comment: null,\n      toolMockReport: input.toolMockReport ?? null,\n      organizationId: input.organizationId ?? null,\n      projectId: input.projectId ?? null,\n      createdAt: now,\n    };\n    this.db.experimentResults.set(result.id, result);\n    return result;\n  }\n\n  async updateExperimentResult(input: UpdateExperimentResultInput): Promise<ExperimentResult> {\n    const existing = this.db.experimentResults.get(input.id);\n    if (!existing) {\n      throw new Error(`Experiment result not found: ${input.id}`);\n    }\n    if (input.experimentId && existing.experimentId !== input.experimentId) {\n      throw new Error(`Experiment result ${input.id} does not belong to experiment ${input.experimentId}`);\n    }\n    const updated: ExperimentResult = {\n      ...existing,\n      status: input.status !== undefined ? input.status : existing.status,\n      tags: input.tags !== undefined ? input.tags : existing.tags,\n      comment: input.comment !== undefined ? input.comment : existing.comment,\n    };\n    this.db.experimentResults.set(input.id, updated);\n    return updated;\n  }\n\n  async getExperimentResultById(args: {\n    id: string;\n    filters?: ExperimentTenancyFilters;\n  }): Promise<ExperimentResult | null> {\n    const row = this.db.experimentResults.get(args.id);\n    if (!row) return null;\n    if (args.filters?.organizationId !== undefined && (row.organizationId ?? null) !== args.filters.organizationId) {\n      return null;\n    }\n    if (args.filters?.projectId !== undefined && (row.projectId ?? null) !== args.filters.projectId) {\n      return null;\n    }\n    return row;\n  }\n\n  async listExperimentResults(args: ListExperimentResultsInput): Promise<ListExperimentResultsOutput> {\n    let results = Array.from(this.db.experimentResults.values()).filter(r => r.experimentId === args.experimentId);\n\n    // Apply filters\n    if (args.traceId) {\n      results = results.filter(r => r.traceId === args.traceId);\n    }\n    if (args.status) {\n      results = results.filter(r => r.status === args.status);\n    }\n    if (args.filters?.organizationId !== undefined) {\n      results = results.filter(r => (r.organizationId ?? null) === args.filters!.organizationId);\n    }\n    if (args.filters?.projectId !== undefined) {\n      results = results.filter(r => (r.projectId ?? null) === args.filters!.projectId);\n    }\n\n    // Sort by startedAt ascending (execution order)\n    results.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());\n\n    const { page, perPage: perPageInput } = args.pagination;\n    const perPage = normalizePerPage(perPageInput, 100);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? results.length : start + perPage;\n\n    return {\n      results: results.slice(start, end),\n      pagination: {\n        total: results.length,\n        page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : results.length > end,\n      },\n    };\n  }\n\n  async deleteExperimentResults(args: { experimentId: string; filters?: ExperimentTenancyFilters }): Promise<void> {\n    // Gate the cascade on the parent experiment's tenancy — if the experiment\n    // exists but belongs to a different tenant, silently no-op instead of\n    // wiping another tenant's results.\n    if (args.filters?.organizationId !== undefined || args.filters?.projectId !== undefined) {\n      const parent = this.db.experiments.get(args.experimentId);\n      if (!parent) return;\n      if (\n        args.filters?.organizationId !== undefined &&\n        (parent.organizationId ?? null) !== args.filters.organizationId\n      ) {\n        return;\n      }\n      if (args.filters?.projectId !== undefined && (parent.projectId ?? null) !== args.filters.projectId) {\n        return;\n      }\n    }\n    for (const [resultId, result] of this.db.experimentResults) {\n      if (result.experimentId === args.experimentId) {\n        this.db.experimentResults.delete(resultId);\n      }\n    }\n  }\n\n  async getReviewSummary(): Promise<ExperimentReviewCounts[]> {\n    const counts = new Map<string, ExperimentReviewCounts>();\n\n    for (const result of this.db.experimentResults.values()) {\n      let entry = counts.get(result.experimentId);\n      if (!entry) {\n        entry = { experimentId: result.experimentId, total: 0, needsReview: 0, reviewed: 0, complete: 0 };\n        counts.set(result.experimentId, entry);\n      }\n      entry.total++;\n      if (result.status === 'needs-review') entry.needsReview++;\n      else if (result.status === 'reviewed') entry.reviewed++;\n      else if (result.status === 'complete') entry.complete++;\n    }\n\n    return Array.from(counts.values());\n  }\n}\n","import { StorageDomain } from '../base';\nimport type { HarnessPendingItemRecord, SessionRecord, SessionRecordUpdate } from './types';\n\nexport abstract class HarnessStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'HARNESS',\n    });\n  }\n\n  abstract loadSession(sessionId: string): Promise<SessionRecord | null>;\n\n  abstract saveSession(record: SessionRecord): Promise<void>;\n\n  abstract listSessions(): Promise<SessionRecord[]>;\n\n  async updateSession(sessionId: string, updates: SessionRecordUpdate): Promise<SessionRecord> {\n    const record = await this.loadSession(sessionId);\n    if (!record) {\n      throw new Error(`Harness session \"${sessionId}\" was not found`);\n    }\n\n    const next: SessionRecord = {\n      ...record,\n      ...updates,\n      id: record.id,\n      createdAt: record.createdAt,\n      lastActivityAt: updates.lastActivityAt ?? new Date(),\n    };\n    await this.saveSession(next);\n    return next;\n  }\n\n  async appendPendingItem(sessionId: string, item: HarnessPendingItemRecord): Promise<SessionRecord> {\n    const record = await this.loadSession(sessionId);\n    if (!record) {\n      throw new Error(`Harness session \"${sessionId}\" was not found`);\n    }\n\n    if (record.pending?.some(existing => existing.id === item.id)) {\n      throw new Error(`Harness pending item \"${item.id}\" already exists on session \"${sessionId}\"`);\n    }\n\n    return this.updateSession(sessionId, {\n      pending: [...(record.pending ?? []), item],\n    });\n  }\n\n  async updatePendingItem(\n    sessionId: string,\n    pendingItemId: string,\n    updates: Partial<Omit<HarnessPendingItemRecord, 'id' | 'sessionId' | 'createdAt'>>,\n  ): Promise<SessionRecord> {\n    const record = await this.loadSession(sessionId);\n    if (!record) {\n      throw new Error(`Harness session \"${sessionId}\" was not found`);\n    }\n\n    let found = false;\n    const pending = (record.pending ?? []).map(item => {\n      if (item.id !== pendingItemId) return item;\n      found = true;\n      return {\n        ...item,\n        ...updates,\n        id: item.id,\n        sessionId: item.sessionId,\n        createdAt: item.createdAt,\n        updatedAt: new Date(),\n      };\n    });\n\n    if (!found) {\n      throw new Error(`Harness pending item \"${pendingItemId}\" was not found on session \"${sessionId}\"`);\n    }\n\n    return this.updateSession(sessionId, { pending });\n  }\n\n  async removePendingItem(sessionId: string, pendingItemId: string): Promise<SessionRecord> {\n    const record = await this.loadSession(sessionId);\n    if (!record) {\n      throw new Error(`Harness session \"${sessionId}\" was not found`);\n    }\n\n    return this.updateSession(sessionId, {\n      pending: (record.pending ?? []).filter(item => item.id !== pendingItemId),\n    });\n  }\n}\n","import { HarnessStorage } from './base';\nimport type { HarnessPendingItemRecord, SessionRecord, SessionRecordUpdate } from './types';\n\nfunction clonePendingItemRecord(item: HarnessPendingItemRecord): HarnessPendingItemRecord {\n  return {\n    ...item,\n    createdAt: new Date(item.createdAt),\n    updatedAt: new Date(item.updatedAt),\n    payload: item.payload ? structuredClone(item.payload) : undefined,\n    response: item.response ? structuredClone(item.response) : undefined,\n  };\n}\n\nfunction cloneSessionRecord(record: SessionRecord): SessionRecord {\n  return {\n    ...record,\n    source: record.source ? { ...record.source } : undefined,\n    metadata: record.metadata ? structuredClone(record.metadata) : undefined,\n    state: record.state ? structuredClone(record.state) : undefined,\n    pending: record.pending ? record.pending.map(clonePendingItemRecord) : undefined,\n    createdAt: new Date(record.createdAt),\n    lastActivityAt: new Date(record.lastActivityAt),\n    closingAt: record.closingAt ? new Date(record.closingAt) : record.closingAt,\n    closeDeadlineAt: record.closeDeadlineAt ? new Date(record.closeDeadlineAt) : record.closeDeadlineAt,\n    closedAt: record.closedAt ? new Date(record.closedAt) : record.closedAt,\n    deletedAt: record.deletedAt ? new Date(record.deletedAt) : record.deletedAt,\n  };\n}\n\nexport class InMemoryHarness extends HarnessStorage {\n  readonly #sessions = new Map<string, SessionRecord>();\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.#sessions.clear();\n  }\n\n  async loadSession(sessionId: string): Promise<SessionRecord | null> {\n    const record = this.#sessions.get(sessionId);\n    return record ? cloneSessionRecord(record) : null;\n  }\n\n  async saveSession(record: SessionRecord): Promise<void> {\n    this.#sessions.set(record.id, cloneSessionRecord(record));\n  }\n\n  async listSessions(): Promise<SessionRecord[]> {\n    return [...this.#sessions.values()].map(cloneSessionRecord);\n  }\n\n  override async updateSession(sessionId: string, updates: SessionRecordUpdate): Promise<SessionRecord> {\n    const record = this.#sessions.get(sessionId);\n    if (!record) {\n      throw new Error(`Harness session \"${sessionId}\" was not found`);\n    }\n\n    const next = cloneSessionRecord({\n      ...record,\n      ...updates,\n      id: record.id,\n      createdAt: record.createdAt,\n      lastActivityAt: updates.lastActivityAt ?? new Date(),\n    });\n    this.#sessions.set(sessionId, next);\n    return cloneSessionRecord(next);\n  }\n}\n","import type { MastraMessageContentV2 } from '../../../agent';\nimport type { MastraDBMessage, StorageThreadType } from '../../../memory/types';\nimport type {\n  StorageResourceType,\n  ThreadOrderBy,\n  ThreadSortDirection,\n  StorageListMessagesInput,\n  StorageListMessagesByResourceIdInput,\n  StorageListMessagesOutput,\n  StorageListThreadsInput,\n  StorageListThreadsOutput,\n  StorageOrderBy,\n  StorageCloneThreadInput,\n  StorageCloneThreadOutput,\n  ObservationalMemoryRecord,\n  ObservationalMemoryHistoryOptions,\n  CreateObservationalMemoryInput,\n  UpdateActiveObservationsInput,\n  UpdateBufferedObservationsInput,\n  UpdateBufferedReflectionInput,\n  SwapBufferedToActiveInput,\n  SwapBufferedToActiveResult,\n  SwapBufferedReflectionToActiveInput,\n  CreateReflectionGenerationInput,\n  UpdateObservationalMemoryConfigInput,\n} from '../../types';\nimport { StorageDomain } from '../base';\n\nfunction isPlainObj(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n// Constants for metadata key validation\nconst SAFE_METADATA_KEY_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\nconst MAX_METADATA_KEY_LENGTH = 128;\nconst DISALLOWED_METADATA_KEYS = new Set(['__proto__', 'prototype', 'constructor']);\n\nexport abstract class MemoryStorage extends StorageDomain {\n  /**\n   * Whether this storage adapter supports Observational Memory.\n   * Adapters that implement OM methods should set this to true.\n   * Defaults to false for backwards compatibility with custom adapters.\n   */\n  readonly supportsObservationalMemory?: boolean = false;\n\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'MEMORY',\n    });\n  }\n\n  abstract getThreadById({\n    threadId,\n    resourceId,\n  }: {\n    threadId: string;\n    resourceId?: string;\n  }): Promise<StorageThreadType | null>;\n\n  abstract saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType>;\n\n  abstract updateThread({\n    id,\n    title,\n    metadata,\n  }: {\n    id: string;\n    title: string;\n    metadata: Record<string, unknown>;\n  }): Promise<StorageThreadType>;\n\n  abstract deleteThread({ threadId }: { threadId: string }): Promise<void>;\n\n  abstract listMessages(args: StorageListMessagesInput): Promise<StorageListMessagesOutput>;\n\n  /**\n   * List messages by resource ID only (across all threads).\n   * Used by Observational Memory and LongMemEval for resource-scoped queries.\n   *\n   * @param args - Resource ID and pagination/filtering options\n   * @returns Paginated list of messages for the resource\n   */\n  async listMessagesByResourceId(_args: StorageListMessagesByResourceIdInput): Promise<StorageListMessagesOutput> {\n    throw new Error(\n      `Resource-scoped message listing is not implemented by this storage adapter (${this.constructor.name}). ` +\n        `Use an adapter that supports Observational Memory (pg, libsql, mongodb, convex) or disable observational memory.`,\n    );\n  }\n\n  abstract listMessagesById({ messageIds }: { messageIds: string[] }): Promise<{ messages: MastraDBMessage[] }>;\n\n  abstract saveMessages(args: { messages: MastraDBMessage[] }): Promise<{ messages: MastraDBMessage[] }>;\n\n  abstract updateMessages(args: {\n    messages: (Partial<Omit<MastraDBMessage, 'createdAt'>> & {\n      id: string;\n      content?: { metadata?: MastraMessageContentV2['metadata']; content?: MastraMessageContentV2['content'] };\n    })[];\n  }): Promise<MastraDBMessage[]>;\n\n  async deleteMessages(_messageIds: string[]): Promise<void> {\n    throw new Error(\n      `Message deletion is not supported by this storage adapter (${this.constructor.name}). ` +\n        `The deleteMessages method needs to be implemented in the storage adapter.`,\n    );\n  }\n\n  /**\n   * List threads with optional filtering by resourceId and metadata.\n   *\n   * @param args - Filter, pagination, and ordering options\n   * @param args.filter - Optional filters for resourceId and/or metadata\n   * @param args.filter.resourceId - Optional resource ID to filter by\n   * @param args.filter.metadata - Optional metadata key-value pairs to filter by (AND logic)\n   * @returns Paginated list of threads matching the filters\n   */\n  abstract listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput>;\n\n  /**\n   * Clone a thread and its messages to create a new independent thread.\n   * The cloned thread will have clone metadata stored in its metadata field.\n   *\n   * @param args - Clone configuration options\n   * @returns The newly created thread and the cloned messages\n   */\n  async cloneThread(_args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput> {\n    throw new Error(\n      `Thread cloning is not implemented by this storage adapter (${this.constructor.name}). ` +\n        `The cloneThread method needs to be implemented in the storage adapter.`,\n    );\n  }\n\n  async getResourceById(_: { resourceId: string }): Promise<StorageResourceType | null> {\n    throw new Error(\n      `Resource working memory is not implemented by this storage adapter (${this.constructor.name}). ` +\n        `This is likely a bug - all Mastra storage adapters should implement resource support. ` +\n        `Please report this issue at https://github.com/mastra-ai/mastra/issues`,\n    );\n  }\n\n  async saveResource(_: { resource: StorageResourceType }): Promise<StorageResourceType> {\n    throw new Error(\n      `Resource working memory is not implemented by this storage adapter (${this.constructor.name}). ` +\n        `This is likely a bug - all Mastra storage adapters should implement resource support. ` +\n        `Please report this issue at https://github.com/mastra-ai/mastra/issues`,\n    );\n  }\n\n  async updateResource(_: {\n    resourceId: string;\n    workingMemory?: string;\n    metadata?: Record<string, unknown>;\n  }): Promise<StorageResourceType> {\n    throw new Error(\n      `Resource working memory is not implemented by this storage adapter (${this.constructor.name}). ` +\n        `This is likely a bug - all Mastra storage adapters should implement resource support. ` +\n        `Please report this issue at https://github.com/mastra-ai/mastra/issues`,\n    );\n  }\n\n  protected parseOrderBy(\n    orderBy?: StorageOrderBy,\n    defaultDirection: ThreadSortDirection = 'DESC',\n  ): { field: ThreadOrderBy; direction: ThreadSortDirection } {\n    return {\n      field: orderBy?.field && orderBy.field in THREAD_ORDER_BY_SET ? orderBy.field : 'createdAt',\n      direction:\n        orderBy?.direction && orderBy.direction in THREAD_THREAD_SORT_DIRECTION_SET\n          ? orderBy.direction\n          : defaultDirection,\n    };\n  }\n\n  // ============================================\n  // Observational Memory Methods\n  // ============================================\n\n  /**\n   * Get the current observational memory record for a thread/resource.\n   * Returns the most recent active record.\n   */\n  async getObservationalMemory(\n    _threadId: string | null,\n    _resourceId: string,\n  ): Promise<ObservationalMemoryRecord | null> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Get observational memory history (previous generations).\n   * Returns records in reverse chronological order (newest first).\n   */\n  async getObservationalMemoryHistory(\n    _threadId: string | null,\n    _resourceId: string,\n    _limit?: number,\n    _options?: ObservationalMemoryHistoryOptions,\n  ): Promise<ObservationalMemoryRecord[]> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Create a new observational memory record.\n   * Called when starting observations for a new thread/resource.\n   */\n  async initializeObservationalMemory(_input: CreateObservationalMemoryInput): Promise<ObservationalMemoryRecord> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Update active observations.\n   * Called when observations are created and immediately activated (no buffering).\n   */\n  async updateActiveObservations(_input: UpdateActiveObservationsInput): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  // ============================================\n  // Buffering Methods (for async observation/reflection)\n  // These methods support async buffering when `bufferTokens` is configured.\n  // ============================================\n\n  /**\n   * Update buffered observations.\n   * Called when observations are created asynchronously via `bufferTokens`.\n   */\n  async updateBufferedObservations(_input: UpdateBufferedObservationsInput): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Swap buffered observations to active.\n   * Atomic operation that:\n   * 1. Appends bufferedObservations → activeObservations (based on activationRatio)\n   * 2. Moves activated bufferedMessageIds → observedMessageIds\n   * 3. Keeps remaining buffered content if activationRatio < 100\n   * 4. Updates lastObservedAt\n   *\n   * Returns info about what was activated for UI feedback.\n   */\n  async swapBufferedToActive(_input: SwapBufferedToActiveInput): Promise<SwapBufferedToActiveResult> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Create a new generation from a reflection.\n   * Creates a new record with:\n   * - originType: 'reflection'\n   * - activeObservations containing the reflection\n   * - generationCount incremented from the current record\n   */\n  async createReflectionGeneration(_input: CreateReflectionGenerationInput): Promise<ObservationalMemoryRecord> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Update buffered reflection (async reflection in progress).\n   * Called when reflection runs asynchronously via `bufferTokens`.\n   */\n  async updateBufferedReflection(_input: UpdateBufferedReflectionInput): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Swap buffered reflection to active observations.\n   * Creates a new generation where activeObservations = bufferedReflection + unreflected observations.\n   * The `tokenCount` in input is the processor-computed token count for the combined content.\n   */\n  async swapBufferedReflectionToActive(\n    _input: SwapBufferedReflectionToActiveInput,\n  ): Promise<ObservationalMemoryRecord> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Set the isReflecting flag.\n   */\n  async setReflectingFlag(_id: string, _isReflecting: boolean): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Set the isObserving flag.\n   */\n  async setObservingFlag(_id: string, _isObserving: boolean): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Set the isBufferingObservation flag and update lastBufferedAtTokens.\n   * Called when async observation buffering starts (true) or ends/fails (false).\n   * @param id - Record ID\n   * @param isBuffering - Whether buffering is in progress\n   * @param lastBufferedAtTokens - The pending token count at which this buffer was triggered (only set when isBuffering=true)\n   */\n  async setBufferingObservationFlag(_id: string, _isBuffering: boolean, _lastBufferedAtTokens?: number): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Set the isBufferingReflection flag.\n   * Called when async reflection buffering starts (true) or ends/fails (false).\n   */\n  async setBufferingReflectionFlag(_id: string, _isBuffering: boolean): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Insert a fully-formed observational memory record.\n   * Used by thread cloning to copy OM state with remapped IDs.\n   */\n  async insertObservationalMemoryRecord(_record: ObservationalMemoryRecord): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Clear all observational memory for a thread/resource.\n   * Removes all records and history.\n   */\n  async clearObservationalMemory(_threadId: string | null, _resourceId: string): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Set the pending message token count.\n   * Called at the end of each OM processing step to persist the current\n   * context window token count so the UI can display it on page load.\n   */\n  async setPendingMessageTokens(_id: string, _tokenCount: number): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Update the config of an existing observational memory record.\n   * The provided config is deep-merged into the record's existing config.\n   */\n  async updateObservationalMemoryConfig(_input: UpdateObservationalMemoryConfigInput): Promise<void> {\n    throw new Error(`Observational memory is not implemented by this storage adapter (${this.constructor.name}).`);\n  }\n\n  /**\n   * Deep-merge two plain objects. Available for subclasses to merge\n   * partial config overrides into existing record configs.\n   */\n  protected deepMergeConfig(target: Record<string, unknown>, source: Record<string, unknown>): Record<string, unknown> {\n    const output: Record<string, unknown> = { ...target };\n    for (const key of Object.keys(source)) {\n      const tVal = target[key];\n      const sVal = source[key];\n      if (isPlainObj(tVal) && isPlainObj(sVal)) {\n        output[key] = this.deepMergeConfig(tVal, sVal);\n      } else if (sVal !== undefined) {\n        output[key] = sVal;\n      }\n    }\n    return output;\n  }\n\n  /**\n   * Validates metadata keys to prevent SQL injection attacks and prototype pollution.\n   * Keys must start with a letter or underscore, followed by alphanumeric characters or underscores.\n   * @param metadata - The metadata object to validate\n   * @throws Error if any key contains invalid characters or is a disallowed key\n   */\n  protected validateMetadataKeys(metadata: Record<string, unknown> | undefined): void {\n    if (!metadata) return;\n\n    for (const key of Object.keys(metadata)) {\n      // First check for disallowed prototype pollution keys\n      if (DISALLOWED_METADATA_KEYS.has(key)) {\n        throw new Error(`Invalid metadata key: \"${key}\".`);\n      }\n\n      // Then check pattern\n      if (!SAFE_METADATA_KEY_PATTERN.test(key)) {\n        throw new Error(\n          `Invalid metadata key: \"${key}\". Keys must start with a letter or underscore and contain only alphanumeric characters and underscores.`,\n        );\n      }\n\n      // Also limit key length to prevent potential issues\n      if (key.length > MAX_METADATA_KEY_LENGTH) {\n        throw new Error(`Metadata key \"${key}\" exceeds maximum length of ${MAX_METADATA_KEY_LENGTH} characters.`);\n      }\n    }\n  }\n\n  /**\n   * Validates pagination parameters and returns safe offset.\n   * @param page - Page number (0-indexed)\n   * @param perPage - Items per page (0 is allowed and returns empty results)\n   * @throws Error if page is negative, perPage is negative/invalid, or offset would overflow\n   */\n  protected validatePagination(page: number, perPage: number): void {\n    if (!Number.isFinite(page) || !Number.isSafeInteger(page) || page < 0) {\n      throw new Error('page must be >= 0');\n    }\n\n    // perPage: 0 is allowed (returns empty results), negative values are rejected\n    if (!Number.isFinite(perPage) || !Number.isSafeInteger(perPage) || perPage < 0) {\n      throw new Error('perPage must be >= 0');\n    }\n\n    // Skip overflow check when perPage is 0 (no offset needed)\n    if (perPage === 0) {\n      return;\n    }\n\n    // Prevent overflow when calculating offset\n    const offset = page * perPage;\n    if (!Number.isSafeInteger(offset) || offset > Number.MAX_SAFE_INTEGER) {\n      throw new Error('page value too large');\n    }\n  }\n\n  /**\n   * Validates pagination input before normalization.\n   * Use this when accepting raw perPageInput (number | false) from callers.\n   *\n   * When perPage is false (fetch all), page must be 0 since pagination is disabled.\n   * When perPage is a number, delegates to validatePagination for full validation.\n   *\n   * @param page - Page number (0-indexed)\n   * @param perPageInput - Items per page as number, or false to fetch all results\n   * @throws Error if perPageInput is false and page !== 0\n   * @throws Error if perPageInput is invalid (not false or a non-negative safe integer)\n   * @throws Error if page is invalid or offset would overflow\n   */\n  protected validatePaginationInput(page: number, perPageInput: number | false): void {\n    // Validate perPageInput type first\n    if (perPageInput !== false) {\n      if (typeof perPageInput !== 'number' || !Number.isFinite(perPageInput) || !Number.isSafeInteger(perPageInput)) {\n        throw new Error('perPage must be false or a safe integer');\n      }\n      if (perPageInput < 0) {\n        throw new Error('perPage must be >= 0');\n      }\n    }\n\n    // When fetching all (perPage: false), only page 0 is valid\n    if (perPageInput === false) {\n      if (page !== 0) {\n        throw new Error('page must be 0 when perPage is false');\n      }\n      // Still validate page is a valid integer\n      if (!Number.isFinite(page) || !Number.isSafeInteger(page)) {\n        throw new Error('page must be >= 0');\n      }\n      return;\n    }\n\n    // For numeric perPage, delegate to existing validation\n    this.validatePagination(page, perPageInput);\n  }\n}\n\nconst THREAD_ORDER_BY_SET: Record<ThreadOrderBy, true> = {\n  createdAt: true,\n  updatedAt: true,\n};\n\nconst THREAD_THREAD_SORT_DIRECTION_SET: Record<ThreadSortDirection, true> = {\n  ASC: true,\n  DESC: true,\n};\n","import { MessageList } from '../../../agent/message-list';\nimport type { MastraDBMessage, StorageThreadType } from '../../../memory/types';\nimport { normalizePerPage, calculatePagination } from '../../base';\nimport type {\n  StorageMessageType,\n  StorageResourceType,\n  ThreadOrderBy,\n  ThreadSortDirection,\n  StorageListMessagesInput,\n  StorageListMessagesByResourceIdInput,\n  StorageListMessagesOutput,\n  StorageListThreadsInput,\n  StorageListThreadsOutput,\n  StorageCloneThreadInput,\n  StorageCloneThreadOutput,\n  ThreadCloneMetadata,\n  ObservationalMemoryRecord,\n  ObservationalMemoryHistoryOptions,\n  BufferedObservationChunk,\n  CreateObservationalMemoryInput,\n  UpdateActiveObservationsInput,\n  UpdateBufferedObservationsInput,\n  UpdateBufferedReflectionInput,\n  SwapBufferedToActiveInput,\n  SwapBufferedToActiveResult,\n  SwapBufferedReflectionToActiveInput,\n  CreateReflectionGenerationInput,\n  UpdateObservationalMemoryConfigInput,\n} from '../../types';\nimport {\n  filterByDateRange,\n  jsonValueEquals,\n  safelyParseJSON,\n  storageMessageMatchesMetadataFilter,\n  validateStorageMetadataFilter,\n} from '../../utils';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { MemoryStorage } from './base';\n\nexport class InMemoryMemory extends MemoryStorage {\n  readonly supportsObservationalMemory = true;\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.threads.clear();\n    this.db.messages.clear();\n    this.db.resources.clear();\n    this.db.observationalMemory.clear();\n  }\n\n  async getThreadById({\n    threadId,\n    resourceId,\n  }: {\n    threadId: string;\n    resourceId?: string;\n  }): Promise<StorageThreadType | null> {\n    const thread = this.db.threads.get(threadId);\n    if (!thread || (resourceId !== undefined && thread.resourceId !== resourceId)) return null;\n    return { ...thread, metadata: thread.metadata ? { ...thread.metadata } : thread.metadata };\n  }\n\n  async saveThread({ thread }: { thread: StorageThreadType }): Promise<StorageThreadType> {\n    const key = thread.id;\n    this.db.threads.set(key, thread);\n    return thread;\n  }\n\n  async updateThread({\n    id,\n    title,\n    metadata,\n  }: {\n    id: string;\n    title: string;\n    metadata: Record<string, unknown>;\n  }): Promise<StorageThreadType> {\n    const thread = this.db.threads.get(id);\n\n    if (!thread) {\n      throw new Error(`Thread with id ${id} not found`);\n    }\n\n    if (thread) {\n      thread.title = title;\n      thread.metadata = { ...thread.metadata, ...metadata };\n      thread.updatedAt = new Date();\n    }\n    return thread;\n  }\n\n  async deleteThread({ threadId }: { threadId: string }): Promise<void> {\n    this.db.threads.delete(threadId);\n\n    this.db.messages.forEach((msg, key) => {\n      if (msg.thread_id === threadId) {\n        this.db.messages.delete(key);\n      }\n    });\n  }\n\n  async listMessages({\n    threadId,\n    resourceId: optionalResourceId,\n    include,\n    filter,\n    perPage: perPageInput,\n    page = 0,\n    orderBy,\n  }: StorageListMessagesInput): Promise<StorageListMessagesOutput> {\n    const metadataFilter = validateStorageMetadataFilter(filter?.metadata);\n    // Normalize threadId to array\n    const threadIds = Array.isArray(threadId) ? threadId : [threadId];\n\n    if (threadIds.length === 0 || threadIds.some(id => !id.trim())) {\n      throw new Error('threadId must be a non-empty string or array of non-empty strings');\n    }\n\n    const threadIdSet = new Set(threadIds);\n\n    const { field, direction } = this.parseOrderBy(orderBy, 'ASC');\n\n    // Normalize perPage for query (false → MAX_SAFE_INTEGER, 0 → 0, undefined → 40)\n    const perPage = normalizePerPage(perPageInput, 40);\n\n    if (page < 0) {\n      throw new Error('page must be >= 0');\n    }\n\n    // Prevent unreasonably large page values that could cause performance issues\n    const maxOffset = Number.MAX_SAFE_INTEGER / 2;\n    if (page * perPage > maxOffset) {\n      throw new Error('page value too large');\n    }\n\n    // Calculate offset from page\n    const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n\n    // When perPage is 0 with no includes, there's nothing to return.\n    if (perPage === 0 && (!include || include.length === 0)) {\n      return { messages: [], total: 0, page, perPage: perPageForResponse, hasMore: false };\n    }\n\n    // Step 1: Get messages matching threadId(s) and optionally resourceId\n    let threadMessages = Array.from(this.db.messages.values()).filter((msg: any) => {\n      // Message must be in one of the specified threads\n      if (threadIdSet && !threadIdSet.has(msg.thread_id)) return false;\n      // If optionalResourceId provided, message must match it\n      if (optionalResourceId && msg.resourceId !== optionalResourceId) return false;\n      return true;\n    });\n\n    // Apply date filtering\n    threadMessages = filterByDateRange(threadMessages, (msg: any) => new Date(msg.createdAt), filter?.dateRange);\n    threadMessages = threadMessages.filter(message =>\n      storageMessageMatchesMetadataFilter(message.content, metadataFilter),\n    );\n\n    // Sort thread messages before pagination\n    threadMessages.sort((a: any, b: any) => {\n      const isDateField = field === 'createdAt' || field === 'updatedAt';\n      const aValue = isDateField ? new Date(a[field]).getTime() : a[field];\n      const bValue = isDateField ? new Date(b[field]).getTime() : b[field];\n\n      if (typeof aValue === 'number' && typeof bValue === 'number') {\n        return direction === 'ASC' ? aValue - bValue : bValue - aValue;\n      }\n      return direction === 'ASC'\n        ? String(aValue).localeCompare(String(bValue))\n        : String(bValue).localeCompare(String(aValue));\n    });\n\n    // Get total count of thread messages (for pagination metadata). When\n    // perPage is 0, the count query is skipped so the response total is 0.\n    const totalThreadMessages = perPage === 0 ? 0 : threadMessages.length;\n\n    // Apply pagination to thread messages. When perPage is 0, skip the main\n    // pagination entirely so only included messages are returned.\n    const paginatedThreadMessages = perPage === 0 ? [] : threadMessages.slice(offset, offset + perPage);\n\n    // Convert paginated thread messages to MastraDBMessage\n    const messages: MastraDBMessage[] = [];\n    const messageIds = new Set<string>();\n\n    for (const msg of paginatedThreadMessages) {\n      const convertedMessage = this.parseStoredMessage(msg);\n      messages.push(convertedMessage);\n      messageIds.add(msg.id);\n    }\n\n    // Step 2: Add included messages with context (if any), excluding duplicates\n    if (include && include.length > 0) {\n      for (const includeItem of include) {\n        const targetMessage = this.db.messages.get(includeItem.id);\n        if (targetMessage) {\n          // Convert StorageMessageType to MastraDBMessage\n          const convertedMessage = {\n            id: targetMessage.id,\n            threadId: targetMessage.thread_id,\n            content: safelyParseJSON(targetMessage.content),\n            role: targetMessage.role as 'user' | 'assistant' | 'system' | 'tool',\n            type: targetMessage.type,\n            createdAt: targetMessage.createdAt,\n            resourceId: targetMessage.resourceId,\n          } as MastraDBMessage;\n\n          // Only add if not already in messages array (deduplication)\n          if (!messageIds.has(convertedMessage.id)) {\n            messages.push(convertedMessage);\n            messageIds.add(convertedMessage.id);\n          }\n\n          // Add previous messages if requested\n          if (includeItem.withPreviousMessages) {\n            const allThreadMessages = Array.from(this.db.messages.values())\n              .filter((msg: any) => msg.thread_id === (includeItem.threadId || threadId))\n              .sort((a: any, b: any) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n\n            const targetIndex = allThreadMessages.findIndex(msg => msg.id === includeItem.id);\n            if (targetIndex !== -1) {\n              const startIndex = Math.max(0, targetIndex - (includeItem.withPreviousMessages || 0));\n              for (let i = startIndex; i < targetIndex; i++) {\n                const message = allThreadMessages[i];\n                if (message && !messageIds.has(message.id)) {\n                  const convertedPrevMessage = {\n                    id: message.id,\n                    threadId: message.thread_id,\n                    content: safelyParseJSON(message.content),\n                    role: message.role as 'user' | 'assistant' | 'system' | 'tool',\n                    type: message.type,\n                    createdAt: message.createdAt,\n                    resourceId: message.resourceId,\n                  } as MastraDBMessage;\n                  messages.push(convertedPrevMessage);\n                  messageIds.add(message.id);\n                }\n              }\n            }\n          }\n\n          // Add next messages if requested\n          if (includeItem.withNextMessages) {\n            const allThreadMessages = Array.from(this.db.messages.values())\n              .filter((msg: any) => msg.thread_id === (includeItem.threadId || threadId))\n              .sort((a: any, b: any) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n\n            const targetIndex = allThreadMessages.findIndex(msg => msg.id === includeItem.id);\n            if (targetIndex !== -1) {\n              const endIndex = Math.min(\n                allThreadMessages.length,\n                targetIndex + (includeItem.withNextMessages || 0) + 1,\n              );\n              for (let i = targetIndex + 1; i < endIndex; i++) {\n                const message = allThreadMessages[i];\n                if (message && !messageIds.has(message.id)) {\n                  const convertedNextMessage = {\n                    id: message.id,\n                    threadId: message.thread_id,\n                    content: safelyParseJSON(message.content),\n                    role: message.role as 'user' | 'assistant' | 'system' | 'tool',\n                    type: message.type,\n                    createdAt: message.createdAt,\n                    resourceId: message.resourceId,\n                  } as MastraDBMessage;\n                  messages.push(convertedNextMessage);\n                  messageIds.add(message.id);\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n\n    // Sort all messages (paginated + included) for final output\n    messages.sort((a: any, b: any) => {\n      const isDateField = field === 'createdAt' || field === 'updatedAt';\n      const aValue = isDateField ? new Date(a[field]).getTime() : a[field];\n      const bValue = isDateField ? new Date(b[field]).getTime() : b[field];\n\n      if (typeof aValue === 'number' && typeof bValue === 'number') {\n        return direction === 'ASC' ? aValue - bValue : bValue - aValue;\n      }\n      return direction === 'ASC'\n        ? String(aValue).localeCompare(String(bValue))\n        : String(bValue).localeCompare(String(aValue));\n    });\n\n    // Calculate hasMore\n    let hasMore;\n    if (perPage === 0) {\n      // perPage=0 fast path skips pagination entirely\n      hasMore = false;\n    } else if (metadataFilter) {\n      hasMore = offset + paginatedThreadMessages.length < totalThreadMessages;\n    } else if (include && include.length > 0) {\n      // When using include, check if we've returned all messages from the thread\n      // because include might bring in messages beyond the pagination window\n      const returnedThreadMessageIds = new Set(messages.filter(m => m.threadId === threadId).map(m => m.id));\n      hasMore = returnedThreadMessageIds.size < totalThreadMessages;\n    } else {\n      // Standard pagination: check if there are more pages\n      hasMore = offset + perPage < totalThreadMessages;\n    }\n\n    return {\n      messages,\n      total: totalThreadMessages,\n      page,\n      perPage: perPageForResponse,\n      hasMore,\n    };\n  }\n\n  async listMessagesByResourceId({\n    resourceId,\n    filter,\n    perPage: perPageInput,\n    page = 0,\n    orderBy,\n  }: StorageListMessagesByResourceIdInput): Promise<StorageListMessagesOutput> {\n    const metadataFilter = validateStorageMetadataFilter(filter?.metadata);\n    const { field, direction } = this.parseOrderBy(orderBy, 'ASC');\n\n    // Normalize perPage for query (false → MAX_SAFE_INTEGER, 0 → 0, undefined → 40)\n    const perPage = normalizePerPage(perPageInput, 40);\n\n    if (page < 0) {\n      throw new Error('page must be >= 0');\n    }\n\n    // Prevent unreasonably large page values that could cause performance issues\n    const maxOffset = Number.MAX_SAFE_INTEGER / 2;\n    if (page * perPage > maxOffset) {\n      throw new Error('page value too large');\n    }\n\n    const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n\n    // Get all messages matching the resourceId (across all threads)\n    let messages = Array.from(this.db.messages.values()).filter((msg: any) => msg.resourceId === resourceId);\n\n    // Apply date filtering\n    messages = filterByDateRange(messages, (msg: any) => new Date(msg.createdAt), filter?.dateRange);\n    messages = messages.filter(message => storageMessageMatchesMetadataFilter(message.content, metadataFilter));\n\n    // Sort messages\n    messages.sort((a: any, b: any) => {\n      const isDateField = field === 'createdAt' || field === 'updatedAt';\n      const aValue = isDateField ? new Date(a[field]).getTime() : a[field];\n      const bValue = isDateField ? new Date(b[field]).getTime() : b[field];\n\n      if (typeof aValue === 'number' && typeof bValue === 'number') {\n        return direction === 'ASC' ? aValue - bValue : bValue - aValue;\n      }\n      return direction === 'ASC'\n        ? String(aValue).localeCompare(String(bValue))\n        : String(bValue).localeCompare(String(aValue));\n    });\n\n    // Get total count for pagination\n    const total = messages.length;\n\n    // Apply pagination\n    const paginatedMessages = messages.slice(offset, offset + perPage);\n\n    const list = new MessageList().add(\n      paginatedMessages.map(m => this.parseStoredMessage(m)),\n      'memory',\n    );\n\n    const hasMore = offset + paginatedMessages.length < total;\n\n    return {\n      messages: list.get.all.db(),\n      total,\n      page,\n      perPage: perPageForResponse,\n      hasMore,\n    };\n  }\n\n  protected parseStoredMessage(message: StorageMessageType): MastraDBMessage {\n    const { resourceId, content, role, thread_id, ...rest } = message;\n\n    // Parse content using safelyParseJSON utility\n    let parsedContent = safelyParseJSON(content);\n\n    // If the result is a plain string (V1 format), wrap it in V2 structure\n    if (typeof parsedContent === 'string') {\n      parsedContent = {\n        format: 2,\n        content: parsedContent,\n        parts: [{ type: 'text', text: parsedContent }],\n      };\n    }\n\n    return {\n      ...rest,\n      threadId: thread_id,\n      ...(message.resourceId && { resourceId: message.resourceId }),\n      content: parsedContent,\n      role: role as MastraDBMessage['role'],\n    } satisfies MastraDBMessage;\n  }\n\n  async listMessagesById({ messageIds }: { messageIds: string[] }): Promise<{ messages: MastraDBMessage[] }> {\n    const rawMessages = messageIds.map(id => this.db.messages.get(id)).filter(message => !!message);\n\n    const list = new MessageList().add(\n      rawMessages.map(m => this.parseStoredMessage(m)),\n      'memory',\n    );\n    return { messages: list.get.all.db() };\n  }\n\n  async saveMessages(args: { messages: MastraDBMessage[] }): Promise<{ messages: MastraDBMessage[] }> {\n    const { messages } = args;\n    // Simulate error handling for testing - check before saving\n    if (messages.some(msg => msg.id === 'error-message' || msg.resourceId === null)) {\n      throw new Error('Simulated error for testing');\n    }\n\n    // Update thread timestamps for each unique threadId\n    const threadIds = new Set(messages.map(msg => msg.threadId).filter((id): id is string => Boolean(id)));\n    for (const threadId of threadIds) {\n      const thread = this.db.threads.get(threadId);\n      if (thread) {\n        thread.updatedAt = new Date();\n      }\n    }\n\n    for (const message of messages) {\n      const key = message.id;\n      // Convert MastraDBMessage to StorageMessageType\n      const storageMessage: StorageMessageType = {\n        id: message.id,\n        thread_id: message.threadId || '',\n        content: JSON.stringify(message.content),\n        role: message.role || 'user',\n        type: message.type || 'text',\n        createdAt: message.createdAt,\n        resourceId: message.resourceId || null,\n      };\n      this.db.messages.set(key, storageMessage);\n    }\n\n    const list = new MessageList().add(messages, 'memory');\n    return { messages: list.get.all.db() };\n  }\n\n  async updateMessages(args: { messages: (Partial<MastraDBMessage> & { id: string })[] }): Promise<MastraDBMessage[]> {\n    const updatedMessages: MastraDBMessage[] = [];\n    for (const update of args.messages) {\n      const storageMsg = this.db.messages.get(update.id);\n      if (!storageMsg) continue;\n\n      // Track old threadId for possible move\n      const oldThreadId = storageMsg.thread_id;\n      const newThreadId = update.threadId || oldThreadId;\n      let threadIdChanged = false;\n      if (update.threadId && update.threadId !== oldThreadId) {\n        threadIdChanged = true;\n      }\n\n      // Update fields\n      if (update.role !== undefined) storageMsg.role = update.role;\n      if (update.type !== undefined) storageMsg.type = update.type;\n      if (update.createdAt !== undefined) storageMsg.createdAt = update.createdAt;\n      if (update.resourceId !== undefined) storageMsg.resourceId = update.resourceId;\n      // Deep merge content if present\n      if (update.content !== undefined) {\n        let oldContent = safelyParseJSON(storageMsg.content);\n        let newContent = update.content;\n        if (typeof newContent === 'object' && typeof oldContent === 'object') {\n          // Deep merge for metadata/content fields\n          newContent = { ...oldContent, ...newContent };\n          if (oldContent.metadata && newContent.metadata) {\n            newContent.metadata = { ...oldContent.metadata, ...newContent.metadata };\n          }\n        }\n        storageMsg.content = JSON.stringify(newContent);\n      }\n      // Handle threadId change\n      if (threadIdChanged) {\n        storageMsg.thread_id = newThreadId;\n        // Update updatedAt for both threads, ensuring strictly greater and not equal\n        const base = Date.now();\n        let oldThreadNewTime: number | undefined;\n        const oldThread = this.db.threads.get(oldThreadId);\n        if (oldThread) {\n          const prev = new Date(oldThread.updatedAt).getTime();\n          oldThreadNewTime = Math.max(base, prev + 1);\n          oldThread.updatedAt = new Date(oldThreadNewTime);\n        }\n        const newThread = this.db.threads.get(newThreadId);\n        if (newThread) {\n          const prev = new Date(newThread.updatedAt).getTime();\n          let newThreadNewTime = Math.max(base + 1, prev + 1);\n          if (oldThreadNewTime !== undefined && newThreadNewTime <= oldThreadNewTime) {\n            newThreadNewTime = oldThreadNewTime + 1;\n          }\n          newThread.updatedAt = new Date(newThreadNewTime);\n        }\n      } else {\n        // Only update the thread's updatedAt if not a move\n        const thread = this.db.threads.get(oldThreadId);\n        if (thread) {\n          const prev = new Date(thread.updatedAt).getTime();\n          let newTime = Date.now();\n          if (newTime <= prev) newTime = prev + 1;\n          thread.updatedAt = new Date(newTime);\n        }\n      }\n      // Save the updated message\n      this.db.messages.set(update.id, storageMsg);\n      // Return as MastraDBMessage\n      updatedMessages.push({\n        id: storageMsg.id,\n        threadId: storageMsg.thread_id,\n        content: safelyParseJSON(storageMsg.content),\n        role: storageMsg.role === 'user' || storageMsg.role === 'assistant' ? storageMsg.role : 'user',\n        type: storageMsg.type,\n        createdAt: storageMsg.createdAt,\n        resourceId: storageMsg.resourceId === null ? undefined : storageMsg.resourceId,\n      });\n    }\n    return updatedMessages;\n  }\n\n  async deleteMessages(messageIds: string[]): Promise<void> {\n    if (!messageIds || messageIds.length === 0) {\n      return;\n    }\n\n    // Collect thread IDs to update\n    const threadIds = new Set<string>();\n\n    for (const messageId of messageIds) {\n      const message = this.db.messages.get(messageId);\n      if (message && message.thread_id) {\n        threadIds.add(message.thread_id);\n      }\n      // Delete the message\n      this.db.messages.delete(messageId);\n    }\n\n    // Update thread timestamps\n    const now = new Date();\n    for (const threadId of threadIds) {\n      const thread = this.db.threads.get(threadId);\n      if (thread) {\n        thread.updatedAt = now;\n      }\n    }\n  }\n\n  async listThreads(args: StorageListThreadsInput): Promise<StorageListThreadsOutput> {\n    const { page = 0, perPage: perPageInput, orderBy, filter } = args;\n    const { field, direction } = this.parseOrderBy(orderBy);\n\n    // Validate pagination input before normalization\n    // This ensures page === 0 when perPageInput === false\n    this.validatePaginationInput(page, perPageInput ?? 100);\n\n    const perPage = normalizePerPage(perPageInput, 100);\n\n    // Start with all threads\n    let threads = Array.from(this.db.threads.values());\n\n    // Apply resourceId filter if provided\n    if (filter?.resourceId) {\n      threads = threads.filter((t: any) => t.resourceId === filter.resourceId);\n    }\n\n    // Validate metadata keys before filtering\n    this.validateMetadataKeys(filter?.metadata);\n\n    // Apply metadata filter if provided (AND logic - all key-value pairs must match)\n    if (filter?.metadata && Object.keys(filter.metadata).length > 0) {\n      threads = threads.filter(thread => {\n        if (!thread.metadata) return false;\n        return Object.entries(filter.metadata!).every(([key, value]) => jsonValueEquals(thread.metadata![key], value));\n      });\n    }\n\n    const sortedThreads = this.sortThreads(threads, field, direction);\n    const clonedThreads = sortedThreads.map(thread => ({\n      ...thread,\n      metadata: thread.metadata ? { ...thread.metadata } : thread.metadata,\n    })) as StorageThreadType[];\n\n    const { offset, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n\n    return {\n      threads: clonedThreads.slice(offset, offset + perPage),\n      total: clonedThreads.length,\n      page,\n      perPage: perPageForResponse,\n      hasMore: offset + perPage < clonedThreads.length,\n    };\n  }\n\n  async getResourceById({ resourceId }: { resourceId: string }): Promise<StorageResourceType | null> {\n    const resource = this.db.resources.get(resourceId);\n    return resource\n      ? { ...resource, metadata: resource.metadata ? { ...resource.metadata } : resource.metadata }\n      : null;\n  }\n\n  async saveResource({ resource }: { resource: StorageResourceType }): Promise<StorageResourceType> {\n    this.db.resources.set(resource.id, resource);\n    return resource;\n  }\n\n  async updateResource({\n    resourceId,\n    workingMemory,\n    metadata,\n  }: {\n    resourceId: string;\n    workingMemory?: string;\n    metadata?: Record<string, unknown>;\n  }): Promise<StorageResourceType> {\n    let resource = this.db.resources.get(resourceId);\n\n    if (!resource) {\n      // Create new resource if it doesn't exist\n      resource = {\n        id: resourceId,\n        workingMemory,\n        metadata: metadata || {},\n        createdAt: new Date(),\n        updatedAt: new Date(),\n      };\n    } else {\n      resource = {\n        ...resource,\n        workingMemory: workingMemory !== undefined ? workingMemory : resource.workingMemory,\n        metadata: {\n          ...resource.metadata,\n          ...metadata,\n        },\n        updatedAt: new Date(),\n      };\n    }\n\n    this.db.resources.set(resourceId, resource);\n    return resource;\n  }\n\n  async cloneThread(args: StorageCloneThreadInput): Promise<StorageCloneThreadOutput> {\n    const { sourceThreadId, newThreadId: providedThreadId, resourceId, title, metadata, options } = args;\n\n    // Get the source thread\n    const sourceThread = this.db.threads.get(sourceThreadId);\n    if (!sourceThread) {\n      throw new Error(`Source thread with id ${sourceThreadId} not found`);\n    }\n\n    // Use provided ID or generate a new one\n    const newThreadId = providedThreadId || crypto.randomUUID();\n\n    // Check if the new thread ID already exists\n    if (this.db.threads.has(newThreadId)) {\n      throw new Error(`Thread with id ${newThreadId} already exists`);\n    }\n\n    // Get messages from the source thread\n    let sourceMessages = Array.from(this.db.messages.values())\n      .filter((msg: StorageMessageType) => msg.thread_id === sourceThreadId)\n      .sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n\n    // Apply message filters if provided\n    if (options?.messageFilter) {\n      const { startDate, endDate, messageIds } = options.messageFilter;\n\n      if (messageIds && messageIds.length > 0) {\n        const messageIdSet = new Set(messageIds);\n        sourceMessages = sourceMessages.filter(msg => messageIdSet.has(msg.id));\n      }\n\n      if (startDate) {\n        sourceMessages = sourceMessages.filter(msg => new Date(msg.createdAt) >= startDate);\n      }\n\n      if (endDate) {\n        sourceMessages = sourceMessages.filter(msg => new Date(msg.createdAt) <= endDate);\n      }\n    }\n\n    // Apply message limit (take from the end to get most recent)\n    if (options?.messageLimit && options.messageLimit > 0 && sourceMessages.length > options.messageLimit) {\n      sourceMessages = sourceMessages.slice(-options.messageLimit);\n    }\n\n    const now = new Date();\n\n    // Determine the last message ID for clone metadata\n    const lastMessageId = sourceMessages.length > 0 ? sourceMessages[sourceMessages.length - 1]!.id : undefined;\n\n    // Create clone metadata\n    const cloneMetadata: ThreadCloneMetadata = {\n      sourceThreadId,\n      clonedAt: now,\n      ...(lastMessageId && { lastMessageId }),\n    };\n\n    // Create the new thread\n    const newThread: StorageThreadType = {\n      id: newThreadId,\n      resourceId: resourceId || sourceThread.resourceId,\n      title: title || (sourceThread.title ? `Clone of ${sourceThread.title}` : undefined),\n      metadata: {\n        ...metadata,\n        clone: cloneMetadata,\n      },\n      createdAt: now,\n      updatedAt: now,\n    };\n\n    // Save the new thread\n    this.db.threads.set(newThreadId, newThread);\n\n    // Clone messages with new IDs\n    const clonedMessages: MastraDBMessage[] = [];\n    const messageIdMap: Record<string, string> = {};\n    for (const sourceMsg of sourceMessages) {\n      const newMessageId = crypto.randomUUID();\n      messageIdMap[sourceMsg.id] = newMessageId;\n      const parsedContent = safelyParseJSON(sourceMsg.content);\n\n      // Create storage message\n      const newStorageMessage: StorageMessageType = {\n        id: newMessageId,\n        thread_id: newThreadId,\n        content: sourceMsg.content,\n        role: sourceMsg.role,\n        type: sourceMsg.type,\n        createdAt: sourceMsg.createdAt,\n        resourceId: resourceId || sourceMsg.resourceId,\n      };\n\n      this.db.messages.set(newMessageId, newStorageMessage);\n\n      // Create MastraDBMessage for return\n      clonedMessages.push({\n        id: newMessageId,\n        threadId: newThreadId,\n        content: parsedContent,\n        role: sourceMsg.role as MastraDBMessage['role'],\n        type: sourceMsg.type,\n        createdAt: sourceMsg.createdAt,\n        resourceId: resourceId || sourceMsg.resourceId || undefined,\n      });\n    }\n\n    return {\n      thread: newThread,\n      clonedMessages,\n      messageIdMap,\n    };\n  }\n\n  private sortThreads(threads: any[], field: ThreadOrderBy, direction: ThreadSortDirection): any[] {\n    return threads.sort((a, b) => {\n      const isDateField = field === 'createdAt' || field === 'updatedAt';\n      const aValue = isDateField ? new Date(a[field]).getTime() : a[field];\n      const bValue = isDateField ? new Date(b[field]).getTime() : b[field];\n\n      if (typeof aValue === 'number' && typeof bValue === 'number') {\n        if (direction === 'ASC') {\n          return aValue - bValue;\n        } else {\n          return bValue - aValue;\n        }\n      }\n      return direction === 'ASC'\n        ? String(aValue).localeCompare(String(bValue))\n        : String(bValue).localeCompare(String(aValue));\n    });\n  }\n\n  // ============================================\n  // Observational Memory Implementation\n  // ============================================\n\n  private getObservationalMemoryKey(threadId: string | null, resourceId: string): string {\n    if (threadId) {\n      return `thread:${threadId}`;\n    }\n    return `resource:${resourceId}`;\n  }\n\n  async getObservationalMemory(threadId: string | null, resourceId: string): Promise<ObservationalMemoryRecord | null> {\n    const key = this.getObservationalMemoryKey(threadId, resourceId);\n    const records = this.db.observationalMemory.get(key);\n    return records?.[0] ?? null;\n  }\n\n  async getObservationalMemoryHistory(\n    threadId: string | null,\n    resourceId: string,\n    limit?: number,\n    options?: ObservationalMemoryHistoryOptions,\n  ): Promise<ObservationalMemoryRecord[]> {\n    const key = this.getObservationalMemoryKey(threadId, resourceId);\n    let records = this.db.observationalMemory.get(key) ?? [];\n\n    if (options?.from) {\n      records = records.filter(r => r.createdAt >= options.from!);\n    }\n    if (options?.to) {\n      records = records.filter(r => r.createdAt <= options.to!);\n    }\n    if (options?.offset != null) {\n      records = records.slice(options.offset);\n    }\n\n    return limit != null ? records.slice(0, limit) : records;\n  }\n\n  async initializeObservationalMemory(input: CreateObservationalMemoryInput): Promise<ObservationalMemoryRecord> {\n    const { threadId, resourceId, scope, config, observedTimezone } = input;\n    const key = this.getObservationalMemoryKey(threadId, resourceId);\n    const now = new Date();\n\n    const record: ObservationalMemoryRecord = {\n      id: crypto.randomUUID(),\n      scope,\n      threadId,\n      resourceId,\n      // Timestamps at top level\n      createdAt: now,\n      updatedAt: now,\n      // lastObservedAt starts undefined - all messages are \"unobserved\" initially\n      // This ensures historical data (like LongMemEval fixtures) works correctly\n      lastObservedAt: undefined,\n      originType: 'initial',\n      generationCount: 0,\n      activeObservations: '',\n      // Buffering (for async observation/reflection)\n      bufferedObservations: undefined,\n      bufferedReflection: undefined,\n      // Message tracking\n      // Note: Message ID tracking removed in favor of cursor-based lastObservedAt\n      // Token tracking\n      totalTokensObserved: 0,\n      observationTokenCount: 0,\n      pendingMessageTokens: 0,\n      // State flags\n      isReflecting: false,\n      isObserving: false,\n      isBufferingObservation: false,\n      isBufferingReflection: false,\n      lastBufferedAtTokens: 0,\n      lastBufferedAtTime: null,\n      // Configuration\n      config,\n      // Timezone used for observation date formatting\n      observedTimezone,\n      // Extensible metadata (optional)\n      metadata: {},\n    };\n\n    // Add as first record (most recent)\n    const existing = this.db.observationalMemory.get(key) ?? [];\n    this.db.observationalMemory.set(key, [record, ...existing]);\n\n    return record;\n  }\n\n  async insertObservationalMemoryRecord(record: ObservationalMemoryRecord): Promise<void> {\n    const key = this.getObservationalMemoryKey(record.threadId, record.resourceId);\n    const existing = this.db.observationalMemory.get(key) ?? [];\n    // Insert in order by generationCount descending (newest first)\n    let inserted = false;\n    for (let i = 0; i < existing.length; i++) {\n      if (record.generationCount >= existing[i]!.generationCount) {\n        existing.splice(i, 0, record);\n        inserted = true;\n        break;\n      }\n    }\n    if (!inserted) existing.push(record);\n    this.db.observationalMemory.set(key, existing);\n  }\n\n  async updateActiveObservations(input: UpdateActiveObservationsInput): Promise<void> {\n    const { id, observations, tokenCount, lastObservedAt, observedMessageIds } = input;\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    record.activeObservations = observations;\n    record.observationTokenCount = tokenCount;\n    record.totalTokensObserved += tokenCount;\n    // Reset pending tokens since we've now observed them\n    record.pendingMessageTokens = 0;\n\n    // Update timestamps (top-level, not in metadata)\n    record.lastObservedAt = lastObservedAt;\n    record.updatedAt = new Date();\n\n    // Store observed message IDs as safeguard against re-observation\n    if (observedMessageIds) {\n      record.observedMessageIds = observedMessageIds;\n    }\n  }\n\n  async updateBufferedObservations(input: UpdateBufferedObservationsInput): Promise<void> {\n    const { id, chunk } = input;\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    // Create a new chunk with generated id and timestamp\n    const newChunk: BufferedObservationChunk = {\n      id: `ombuf-${crypto.randomUUID()}`,\n      cycleId: chunk.cycleId,\n      observations: chunk.observations,\n      tokenCount: chunk.tokenCount,\n      messageIds: chunk.messageIds,\n      messageTokens: chunk.messageTokens,\n      lastObservedAt: chunk.lastObservedAt,\n      createdAt: new Date(),\n      suggestedContinuation: chunk.suggestedContinuation,\n      currentTask: chunk.currentTask,\n      threadTitle: chunk.threadTitle,\n      extractedValues: chunk.extractedValues,\n      extractionFailures: chunk.extractionFailures,\n    };\n\n    // Add chunk to the array\n    const existingChunks = Array.isArray(record.bufferedObservationChunks) ? record.bufferedObservationChunks : [];\n    record.bufferedObservationChunks = [...existingChunks, newChunk];\n\n    if (input.lastBufferedAtTime) {\n      record.lastBufferedAtTime = input.lastBufferedAtTime;\n    }\n\n    record.updatedAt = new Date();\n  }\n\n  async swapBufferedToActive(input: SwapBufferedToActiveInput): Promise<SwapBufferedToActiveResult> {\n    const { id, activationRatio, lastObservedAt } = input;\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    // Use caller-provided refreshed chunks (with up-to-date token weights) for\n    // activation math, falling back to persisted chunks otherwise.\n    // Keep refreshed chunks local — don't overwrite the stored buffer.\n    const persistedChunks = Array.isArray(record.bufferedObservationChunks) ? record.bufferedObservationChunks : [];\n    const chunks = Array.isArray(input.bufferedChunks) ? input.bufferedChunks : persistedChunks;\n    if (chunks.length === 0) {\n      return {\n        chunksActivated: 0,\n        messageTokensActivated: 0,\n        observationTokensActivated: 0,\n        messagesActivated: 0,\n        activatedCycleIds: [],\n        activatedMessageIds: [],\n      };\n    }\n\n    // Calculate target: how many message tokens to remove so that\n    // (1 - activationRatio) * threshold worth of raw messages remain.\n    // e.g., ratio=0.8, threshold=5000, pending=6000 → remove 6000 - 1000 = 5000\n    const retentionFloor = input.messageTokensThreshold * (1 - activationRatio);\n    const targetMessageTokens = Math.max(0, input.currentPendingTokens - retentionFloor);\n\n    // Find the closest chunk boundary to the target, biased over (prefer removing\n    // slightly more than the target so remaining context lands at or below retentionFloor).\n    // Track both best-over and best-under boundaries so we can fall back to under\n    // if the over boundary would overshoot by too much.\n    let cumulativeMessageTokens = 0;\n    let bestOverBoundary = 0;\n    let bestOverTokens = 0;\n    let bestUnderBoundary = 0;\n    let bestUnderTokens = 0;\n\n    for (let i = 0; i < chunks.length; i++) {\n      cumulativeMessageTokens += chunks[i]!.messageTokens ?? 0;\n      const boundary = i + 1;\n\n      if (cumulativeMessageTokens >= targetMessageTokens) {\n        // Over or equal — track the closest (lowest) over boundary\n        if (bestOverBoundary === 0 || cumulativeMessageTokens < bestOverTokens) {\n          bestOverBoundary = boundary;\n          bestOverTokens = cumulativeMessageTokens;\n        }\n      } else {\n        // Under — track the closest (highest) under boundary\n        if (cumulativeMessageTokens > bestUnderTokens) {\n          bestUnderBoundary = boundary;\n          bestUnderTokens = cumulativeMessageTokens;\n        }\n      }\n    }\n\n    // Safeguard: if the over boundary would eat into more than 95% of the\n    // retention floor, fall back to the best under boundary instead.\n    // This prevents edge cases where a large chunk overshoots dramatically.\n    // When forceMaxActivation is set (above blockAfter), still prefer the over\n    // boundary, but never if it would leave fewer than the smaller of 1000\n    // tokens or the retention floor remaining.\n    const maxOvershoot = retentionFloor * 0.95;\n    const overshoot = bestOverTokens - targetMessageTokens;\n    const remainingAfterOver = input.currentPendingTokens - bestOverTokens;\n    const remainingAfterUnder = input.currentPendingTokens - bestUnderTokens;\n    // When activationRatio ≈ 1.0, retentionFloor is 0 and minRemaining becomes 0 — intentional for \"activate everything\" configs.\n    const minRemaining = Math.min(1000, retentionFloor);\n\n    let chunksToActivate: number;\n    if (input.forceMaxActivation && bestOverBoundary > 0 && remainingAfterOver >= minRemaining) {\n      chunksToActivate = bestOverBoundary;\n    } else if (bestOverBoundary > 0 && overshoot <= maxOvershoot && remainingAfterOver >= minRemaining) {\n      chunksToActivate = bestOverBoundary;\n    } else if (bestUnderBoundary > 0 && remainingAfterUnder >= minRemaining) {\n      chunksToActivate = bestUnderBoundary;\n    } else if (bestOverBoundary > 0) {\n      // All boundaries are over and exceed the safeguard — still activate\n      // the closest over boundary (better than nothing)\n      chunksToActivate = bestOverBoundary;\n    } else {\n      chunksToActivate = 1;\n    }\n    const activatedChunks = chunks.slice(0, chunksToActivate);\n    const remainingChunks = chunks.slice(chunksToActivate);\n\n    // Combine activated chunks into content\n    const activatedContent = activatedChunks.map(c => c.observations).join('\\n\\n');\n    const activatedTokens = activatedChunks.reduce((sum, c) => sum + c.tokenCount, 0);\n    const activatedMessageTokens = activatedChunks.reduce((sum, c) => sum + (c.messageTokens ?? 0), 0);\n    const activatedMessageCount = activatedChunks.reduce((sum, c) => sum + c.messageIds.length, 0);\n    const activatedCycleIds = activatedChunks.map(c => c.cycleId).filter((id): id is string => !!id);\n    const activatedMessageIds = activatedChunks.flatMap(c => c.messageIds);\n\n    // Derive lastObservedAt from the latest activated chunk, or use provided value\n    const latestChunk = activatedChunks[activatedChunks.length - 1];\n    const derivedLastObservedAt =\n      lastObservedAt ?? (latestChunk?.lastObservedAt ? new Date(latestChunk.lastObservedAt) : new Date());\n\n    // Append activated content to active observations with message boundary for cache stability\n    if (record.activeObservations) {\n      const boundary = `\\n\\n--- message boundary (${derivedLastObservedAt.toISOString()}) ---\\n\\n`;\n      record.activeObservations = `${record.activeObservations}${boundary}${activatedContent}`;\n    } else {\n      record.activeObservations = activatedContent;\n    }\n\n    // Update observation token count\n    record.observationTokenCount = (record.observationTokenCount ?? 0) + activatedTokens;\n\n    // Decrement pending message tokens (clamped to zero)\n    record.pendingMessageTokens = Math.max(0, (record.pendingMessageTokens ?? 0) - activatedMessageTokens);\n\n    // NOTE: We intentionally do NOT add activatedMessageIds to record.observedMessageIds.\n    // observedMessageIds is used by getUnobservedMessages to filter future messages.\n    // Since AI SDK may reuse message IDs for new content, adding them here would\n    // permanently block new content from being observed. Instead, we return\n    // activatedMessageIds so the caller can remove them from messageList directly.\n\n    // Update buffered state with remaining chunks\n    record.bufferedObservationChunks = remainingChunks.length > 0 ? remainingChunks : undefined;\n\n    // Update timestamps\n    record.lastObservedAt = derivedLastObservedAt;\n    record.updatedAt = new Date();\n\n    // Use hints from the most recent activated chunk only — stale hints from older chunks are discarded\n    const latestChunkHints = activatedChunks[activatedChunks.length - 1];\n\n    return {\n      chunksActivated: activatedChunks.length,\n      messageTokensActivated: activatedMessageTokens,\n      observationTokensActivated: activatedTokens,\n      messagesActivated: activatedMessageCount,\n      activatedCycleIds,\n      activatedMessageIds,\n      observations: activatedContent,\n      perChunk: activatedChunks.map(c => ({\n        cycleId: c.cycleId ?? '',\n        messageTokens: c.messageTokens ?? 0,\n        observationTokens: c.tokenCount,\n        messageCount: c.messageIds.length,\n        observations: c.observations,\n      })),\n      suggestedContinuation: latestChunkHints?.suggestedContinuation ?? undefined,\n      currentTask: latestChunkHints?.currentTask ?? undefined,\n    };\n  }\n\n  async createReflectionGeneration(input: CreateReflectionGenerationInput): Promise<ObservationalMemoryRecord> {\n    const { currentRecord, reflection, tokenCount } = input;\n    const key = this.getObservationalMemoryKey(currentRecord.threadId, currentRecord.resourceId);\n    const now = new Date();\n\n    const newRecord: ObservationalMemoryRecord = {\n      id: crypto.randomUUID(),\n      scope: currentRecord.scope,\n      threadId: currentRecord.threadId,\n      resourceId: currentRecord.resourceId,\n      // Timestamps at top level\n      createdAt: now,\n      updatedAt: now,\n      lastObservedAt: currentRecord.lastObservedAt ?? now, // Carry over from observation (which always runs before reflection)\n      originType: 'reflection',\n      generationCount: currentRecord.generationCount + 1,\n      activeObservations: reflection,\n      config: currentRecord.config,\n      totalTokensObserved: currentRecord.totalTokensObserved,\n      observationTokenCount: tokenCount,\n      pendingMessageTokens: 0,\n      isReflecting: false,\n      isObserving: false,\n      isBufferingObservation: false,\n      isBufferingReflection: false,\n      lastBufferedAtTokens: 0,\n      lastBufferedAtTime: null,\n      // Timezone used for observation date formatting\n      observedTimezone: currentRecord.observedTimezone,\n      // Extensible metadata (optional)\n      metadata: {},\n    };\n\n    // Add as first record (most recent)\n    const existing = this.db.observationalMemory.get(key) ?? [];\n    this.db.observationalMemory.set(key, [newRecord, ...existing]);\n\n    return newRecord;\n  }\n\n  async updateBufferedReflection(input: UpdateBufferedReflectionInput): Promise<void> {\n    const { id, reflection, tokenCount, inputTokenCount, reflectedObservationLineCount } = input;\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    const existing = record.bufferedReflection || '';\n    record.bufferedReflection = existing ? `${existing}\\n\\n${reflection}` : reflection;\n    record.bufferedReflectionTokens = (record.bufferedReflectionTokens || 0) + tokenCount;\n    record.bufferedReflectionInputTokens = (record.bufferedReflectionInputTokens || 0) + inputTokenCount;\n    record.reflectedObservationLineCount = reflectedObservationLineCount;\n    record.updatedAt = new Date();\n  }\n\n  async swapBufferedReflectionToActive(input: SwapBufferedReflectionToActiveInput): Promise<ObservationalMemoryRecord> {\n    const { currentRecord } = input;\n    const record = this.findObservationalMemoryRecordById(currentRecord.id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${currentRecord.id}`);\n    }\n\n    if (!record.bufferedReflection) {\n      throw new Error('No buffered reflection to swap');\n    }\n\n    const bufferedReflection = record.bufferedReflection;\n    const reflectedLineCount = record.reflectedObservationLineCount ?? 0;\n\n    // Split current activeObservations by the boundary line count.\n    // Lines 0..reflectedLineCount were reflected on → replaced by bufferedReflection.\n    // Lines after reflectedLineCount were added after reflection started → kept as-is.\n    const currentObservations = record.activeObservations ?? '';\n    const allLines = currentObservations.split('\\n');\n    const unreflectedLines = allLines.slice(reflectedLineCount);\n    const unreflectedContent = unreflectedLines.join('\\n').trim();\n\n    // New activeObservations = bufferedReflection + unreflected observations\n    const newObservations = unreflectedContent ? `${bufferedReflection}\\n\\n${unreflectedContent}` : bufferedReflection;\n\n    // Create a new generation with the merged content.\n    // tokenCount is computed by the processor using its token counter on the combined content.\n    const newRecord = await this.createReflectionGeneration({\n      currentRecord: record,\n      reflection: newObservations,\n      tokenCount: input.tokenCount,\n    });\n\n    // Clear buffered state on old record\n    record.bufferedReflection = undefined;\n    record.bufferedReflectionTokens = undefined;\n    record.bufferedReflectionInputTokens = undefined;\n    record.reflectedObservationLineCount = undefined;\n\n    return newRecord;\n  }\n\n  async setReflectingFlag(id: string, isReflecting: boolean): Promise<void> {\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    record.isReflecting = isReflecting;\n    record.updatedAt = new Date();\n  }\n\n  async setObservingFlag(id: string, isObserving: boolean): Promise<void> {\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    record.isObserving = isObserving;\n    record.updatedAt = new Date();\n  }\n\n  async setBufferingObservationFlag(id: string, isBuffering: boolean, lastBufferedAtTokens?: number): Promise<void> {\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    record.isBufferingObservation = isBuffering;\n    if (lastBufferedAtTokens !== undefined) {\n      record.lastBufferedAtTokens = lastBufferedAtTokens;\n    }\n    record.updatedAt = new Date();\n  }\n\n  async setBufferingReflectionFlag(id: string, isBuffering: boolean): Promise<void> {\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    record.isBufferingReflection = isBuffering;\n    record.updatedAt = new Date();\n  }\n\n  async clearObservationalMemory(threadId: string | null, resourceId: string): Promise<void> {\n    const key = this.getObservationalMemoryKey(threadId, resourceId);\n    this.db.observationalMemory.delete(key);\n  }\n\n  async setPendingMessageTokens(id: string, tokenCount: number): Promise<void> {\n    const record = this.findObservationalMemoryRecordById(id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${id}`);\n    }\n\n    record.pendingMessageTokens = tokenCount;\n    record.updatedAt = new Date();\n  }\n\n  async updateObservationalMemoryConfig(input: UpdateObservationalMemoryConfigInput): Promise<void> {\n    const record = this.findObservationalMemoryRecordById(input.id);\n    if (!record) {\n      throw new Error(`Observational memory record not found: ${input.id}`);\n    }\n\n    record.config = this.deepMergeConfig(record.config as Record<string, unknown>, input.config);\n    record.updatedAt = new Date();\n  }\n\n  /**\n   * Helper to find an observational memory record by ID across all keys\n   */\n  private findObservationalMemoryRecordById(id: string): ObservationalMemoryRecord | null {\n    for (const records of this.db.observationalMemory.values()) {\n      const record = records.find(r => r.id === id);\n      if (record) return record;\n    }\n    return null;\n  }\n}\n","import type { AgentSignalAttributes, AgentSignalType } from '../../../agent/signals';\nimport type { ScheduleIfActive, ScheduleIfIdle } from '../../../schedules/types';\nimport { StorageDomain } from '../base';\n\n/**\n * Discriminated union describing what a schedule fires.\n *\n * `workflow` targets publish a `workflow.start` event on the `workflows`\n * pubsub topic and are processed by the orchestration worker. `agent`\n * targets publish an `agent-schedule.fire` event on the `agent-schedules`\n * pubsub topic and are processed by the {@link AgentScheduleWorker}, which\n * runs the referenced agent directly (no workflow indirection).\n */\nexport type ScheduleTarget = WorkflowScheduleTarget | AgentScheduleTarget;\n\nexport type WorkflowScheduleTarget = {\n  type: 'workflow';\n  workflowId: string;\n  inputData?: unknown;\n  initialState?: unknown;\n  requestContext?: Record<string, unknown>;\n};\n\n// Agent-schedule semantic types are owned by the schedules feature module\n// and re-exported here so callers describing schedule rows can reach them\n// through the storage barrel.\nexport type { ScheduleIfActive, ScheduleIfIdle } from '../../../schedules/types';\n\n/**\n * Schedule target that fires an agent run on a cron. The agent-schedule\n * worker reads these fields and runs the referenced agent directly —\n * either via `sendSignal` (when `threadId` is set) or `agent.generate`\n * (threadless). The agent's `runId` is recorded on the trigger row for\n * UI linkability into chat / observability traces.\n */\nexport type AgentScheduleTarget = {\n  type: 'agent';\n  agentId: string;\n  prompt: string;\n  /**\n   * Free-form label for distinguishing multiple schedules on the same\n   * agent/thread (e.g. `'morning-checkin'`). Optional; filterable via\n   * `mastra.schedules.list({ name })`.\n   */\n  name?: string;\n  /** Threaded agent schedules send a signal into this thread. */\n  threadId?: string;\n  /** Required when `threadId` is set. */\n  resourceId?: string;\n  /** Signal type used by threaded agent schedules. Defaults to `'notification'`. */\n  signalType?: AgentSignalType;\n  /** XML tag the signal renders as. Defaults to `'schedule'`. */\n  tagName?: string;\n  /** Signal attributes rendered onto the XML tag. */\n  attributes?: AgentSignalAttributes;\n  /** Provider options merged into the schedule signal payload on every fire. JSON-safe. */\n  providerOptions?: Record<string, unknown>;\n  /** Options applied when the target thread is actively streaming. Threaded only. */\n  ifActive?: ScheduleIfActive;\n  /** Options applied when the target thread is idle (incl. serializable streamOptions). Threaded only. */\n  ifIdle?: ScheduleIfIdle;\n  /** Arbitrary metadata stored alongside the schedule row. */\n  metadata?: Record<string, unknown>;\n  requestContext?: Record<string, unknown>;\n};\n\n/**\n * Read-shim for schedule rows persisted before the heartbeat → schedules\n * rename: maps a legacy `target.type: 'heartbeat'` discriminator to the\n * current `'agent'` value. Every {@link SchedulesStorage} implementation\n * MUST run row targets through this at deserialization time so legacy rows\n * keep dispatching. Never used on the write path — new rows always persist\n * `'agent'`.\n */\nexport function normalizeScheduleTarget(target: ScheduleTarget): ScheduleTarget {\n  if ((target as { type: string }).type === 'heartbeat') {\n    return { ...target, type: 'agent' } as AgentScheduleTarget;\n  }\n  return target;\n}\n\n/** Lifecycle status of a schedule row. */\nexport type ScheduleStatus = 'active' | 'paused';\n\n/**\n * Polymorphic owner of a schedule. Workflow schedules created via\n * `createWorkflow({ schedule })` leave both fields null. Agent\n * schedules created via `mastra.schedules.create(...)` set\n * `ownerType: 'agent'` and `ownerId` to the agent id. Future schedule\n * types (tenant-owned, workflow-owned, etc.) can use the same shape\n * without a migration.\n */\nexport type ScheduleOwnerType = 'agent' | (string & {});\n\n/**\n * A persisted schedule.\n *\n * `nextFireAt` is advanced atomically by the scheduler before publishing\n * a trigger event, providing CAS-style dedup across multiple instances\n * polling the same storage.\n */\nexport type Schedule = {\n  id: string;\n  target: ScheduleTarget;\n  cron: string;\n  timezone?: string;\n  status: ScheduleStatus;\n  nextFireAt: number;\n  lastFireAt?: number;\n  lastRunId?: string;\n  createdAt: number;\n  updatedAt: number;\n  metadata?: Record<string, unknown>;\n  /** Optional owner classification (e.g. 'agent' for agent schedules). */\n  ownerType?: ScheduleOwnerType;\n  /** Optional owner identifier paired with `ownerType`. */\n  ownerId?: string;\n};\n\n/**\n * Outcome of an individual schedule trigger attempt.\n *\n * Shared across all schedule target types (workflows, agents, …).\n *\n * Workflow outcomes:\n * - `published`  — workflow run was successfully dispatched to the workflow\n *                  engine. Write-once at dispatch time; the trigger row is\n *                  not updated when the run later completes.\n * - `failed`     — dispatch threw (workflow or agent schedule).\n *\n * Agent-schedule outcomes (terminal — written after the run/signal resolves):\n * - `succeeded`  — the scheduled agent run finished without error.\n * - `delivered`  — the schedule signal joined an active run on the target\n *                  thread instead of starting a new one (`ifActive: 'deliver'`).\n * - `persisted`  — the signal was saved to memory without triggering a run\n *                  (`ifActive: 'persist'` or `ifIdle: 'persist'`).\n * - `discarded`  — the signal was dropped without effect\n *                  (`ifActive: 'discard'` or `ifIdle: 'discard'`).\n * - `skipped`    — the user `prepare` hook returned `null`, asking the worker\n *                  to skip this fire entirely.\n * - `aborted`    — the agent run was aborted mid-stream.\n *\n * Legacy outcomes (no longer written, kept readable for rows persisted by\n * older builds so that listing/exhaustive handling does not break):\n * - `acked`, `alerted`, `deferred`, `appended-from-queue`, `dropped-stale`,\n *   `dropped-superseded`, `dropped-busy`.\n */\nexport type ScheduleTriggerOutcome =\n  | 'published'\n  | 'succeeded'\n  | 'delivered'\n  | 'persisted'\n  | 'discarded'\n  | 'skipped'\n  | 'aborted'\n  | 'failed'\n  // Legacy queue/notification outcomes — never written by current code, but\n  // older trigger rows may still carry them. Retained so reads stay typed.\n  | 'acked'\n  | 'alerted'\n  | 'deferred'\n  | 'appended-from-queue'\n  | 'dropped-stale'\n  | 'dropped-superseded'\n  | 'dropped-busy';\n\n/**\n * Distinguishes a tick-loop schedule fire from a deferred drain event or a\n * manual (\"fire now\") invocation. Drain rows reference the original fire\n * via `parentTriggerId`.\n */\nexport type ScheduleTriggerKind = 'schedule-fire' | 'queue-drain' | 'manual';\n\n/** Audit record produced for each trigger attempt. */\nexport type ScheduleTrigger = {\n  /** Stable trigger row id. Generated by storage when omitted on write. */\n  id?: string;\n  scheduleId: string;\n  /**\n   * Identifier of the downstream run produced by this fire.\n   *\n   * For workflow targets this is the workflow run id (`sched_<scheduleId>_<ts>`).\n   * For agent targets this is the agent run id recorded by the\n   * {@link AgentScheduleWorker} after the agent run starts. May be null for\n   * drain rows or fires that failed before producing a run id.\n   */\n  runId: string | null;\n  scheduledFireAt: number;\n  actualFireAt: number;\n  outcome: ScheduleTriggerOutcome;\n  error?: string;\n  /** Defaults to `'schedule-fire'` when omitted. */\n  triggerKind?: ScheduleTriggerKind;\n  /** Pointer back to the originating fire row when `triggerKind === 'queue-drain'`. */\n  parentTriggerId?: string;\n  /** Outcome-specific context (alert text, append message id, queue age, etc.). */\n  metadata?: Record<string, unknown>;\n};\n\n/** Filter options for listing schedules. */\nexport type ScheduleFilter = {\n  status?: ScheduleStatus;\n  workflowId?: string;\n  /** `null` matches schedules with no owner (e.g. workflow-only schedules). */\n  ownerType?: ScheduleOwnerType | null;\n  /** `null` matches schedules with no owner id. */\n  ownerId?: string | null;\n};\n\n/** Filter / pagination options for listing trigger history. */\nexport type ScheduleTriggerListOptions = {\n  limit?: number;\n  /** Inclusive lower bound on actualFireAt (ms epoch). */\n  fromActualFireAt?: number;\n  /** Exclusive upper bound on actualFireAt (ms epoch). */\n  toActualFireAt?: number;\n};\n\n/** Fields that can be patched via {@link SchedulesStorage.updateSchedule}. */\nexport type ScheduleUpdate = Partial<\n  Pick<Schedule, 'cron' | 'timezone' | 'status' | 'nextFireAt' | 'metadata' | 'target' | 'ownerType' | 'ownerId'>\n>;\n\n/**\n * Abstract storage domain for workflow schedules.\n *\n * Powers the {@link Scheduler}: the scheduler's tick loop polls\n * `listDueSchedules`, atomically advances `nextFireAt` via\n * `updateScheduleNextFire` (CAS), publishes a `workflow.start` event on\n * the `workflows` pubsub topic, and records the trigger via `recordTrigger`.\n */\nexport abstract class SchedulesStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'SCHEDULES',\n    });\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    // Default no-op — subclasses override\n  }\n\n  /** Insert a new schedule row. Throws if a row with the same id already exists. Returns the stored row. */\n  abstract createSchedule(schedule: Schedule): Promise<Schedule>;\n\n  /** Get a single schedule by id. Returns null if not found. */\n  abstract getSchedule(id: string): Promise<Schedule | null>;\n\n  /** List schedules matching the filter (no pagination — schedule counts are expected to stay small). */\n  abstract listSchedules(filter?: ScheduleFilter): Promise<Schedule[]>;\n\n  /**\n   * List schedules whose `nextFireAt <= now` and whose `status === 'active'`.\n   * Used by the scheduler tick loop.\n   */\n  abstract listDueSchedules(now: number, limit?: number): Promise<Schedule[]>;\n\n  /** Partial update of a schedule row. */\n  abstract updateSchedule(id: string, patch: ScheduleUpdate): Promise<Schedule>;\n\n  /**\n   * Compare-and-swap update of `nextFireAt`. Used by the scheduler to claim\n   * a fire before publishing — only one tick across many processes will succeed.\n   *\n   * Returns true if the row's `nextFireAt` matched `expectedNextFireAt` and\n   * was advanced to `newNextFireAt`. Returns false if another instance\n   * already advanced it (meaning the caller should skip publishing).\n   */\n  abstract updateScheduleNextFire(\n    id: string,\n    expectedNextFireAt: number,\n    newNextFireAt: number,\n    lastFireAt: number,\n    lastRunId: string,\n  ): Promise<boolean>;\n\n  /** Delete a schedule and its trigger history. */\n  abstract deleteSchedule(id: string): Promise<void>;\n\n  /** Append an entry to a schedule's trigger history. */\n  abstract recordTrigger(trigger: ScheduleTrigger): Promise<void>;\n\n  /** List trigger history for a schedule, newest first. */\n  abstract listTriggers(scheduleId: string, opts?: ScheduleTriggerListOptions): Promise<ScheduleTrigger[]>;\n}\n","import { randomUUID } from 'node:crypto';\nimport type { InMemoryDB } from '../inmemory-db';\nimport type { Schedule, ScheduleFilter, ScheduleTrigger, ScheduleTriggerListOptions, ScheduleUpdate } from './base';\nimport { normalizeScheduleTarget, SchedulesStorage } from './base';\n\nfunction clone<T>(value: T): T {\n  return value == null ? value : (JSON.parse(JSON.stringify(value)) as T);\n}\n\n/** Clone a stored row, normalizing legacy target discriminators on the way out. */\nfunction cloneRow(row: Schedule): Schedule {\n  const copy = clone(row);\n  copy.target = normalizeScheduleTarget(copy.target);\n  return copy;\n}\n\nexport class InMemorySchedulesStorage extends SchedulesStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.schedules.clear();\n    this.db.scheduleTriggers.length = 0;\n  }\n\n  async createSchedule(schedule: Schedule): Promise<Schedule> {\n    if (this.db.schedules.has(schedule.id)) {\n      throw new Error(`Schedule ${schedule.id} already exists`);\n    }\n    const stored = clone(schedule);\n    this.db.schedules.set(stored.id, stored);\n    return clone(stored);\n  }\n\n  async getSchedule(id: string): Promise<Schedule | null> {\n    const found = this.db.schedules.get(id);\n    return found ? cloneRow(found) : null;\n  }\n\n  async listSchedules(filter?: ScheduleFilter): Promise<Schedule[]> {\n    let rows = Array.from(this.db.schedules.values());\n    if (filter?.status) {\n      rows = rows.filter(r => r.status === filter.status);\n    }\n    if (filter?.workflowId) {\n      rows = rows.filter(r => r.target.type === 'workflow' && r.target.workflowId === filter.workflowId);\n    }\n    if (filter?.ownerType !== undefined) {\n      rows = rows.filter(r => (r.ownerType ?? null) === filter.ownerType);\n    }\n    if (filter?.ownerId !== undefined) {\n      rows = rows.filter(r => (r.ownerId ?? null) === filter.ownerId);\n    }\n    rows.sort((a, b) => a.createdAt - b.createdAt);\n    return rows.map(cloneRow);\n  }\n\n  async listDueSchedules(now: number, limit?: number): Promise<Schedule[]> {\n    const due: Schedule[] = [];\n    for (const row of this.db.schedules.values()) {\n      if (row.status === 'active' && row.nextFireAt <= now) {\n        due.push(row);\n      }\n    }\n    due.sort((a, b) => a.nextFireAt - b.nextFireAt);\n    const cap = limit ?? due.length;\n    return due.slice(0, cap).map(cloneRow);\n  }\n\n  async updateSchedule(id: string, patch: ScheduleUpdate): Promise<Schedule> {\n    const existing = this.db.schedules.get(id);\n    if (!existing) {\n      throw new Error(`Schedule ${id} not found`);\n    }\n    const updated: Schedule = {\n      ...existing,\n      ...patch,\n      target: patch.target !== undefined ? patch.target : existing.target,\n      metadata: patch.metadata !== undefined ? patch.metadata : existing.metadata,\n      updatedAt: Date.now(),\n    };\n    const stored = clone(updated);\n    this.db.schedules.set(id, stored);\n    return cloneRow(stored);\n  }\n\n  async updateScheduleNextFire(\n    id: string,\n    expectedNextFireAt: number,\n    newNextFireAt: number,\n    lastFireAt: number,\n    lastRunId: string,\n  ): Promise<boolean> {\n    const existing = this.db.schedules.get(id);\n    if (!existing) return false;\n    if (existing.nextFireAt !== expectedNextFireAt) return false;\n    if (existing.status !== 'active') return false;\n    const stored: Schedule = {\n      ...existing,\n      nextFireAt: newNextFireAt,\n      lastFireAt,\n      lastRunId,\n      updatedAt: Date.now(),\n    };\n    this.db.schedules.set(id, stored);\n    return true;\n  }\n\n  async deleteSchedule(id: string): Promise<void> {\n    this.db.schedules.delete(id);\n    for (let i = this.db.scheduleTriggers.length - 1; i >= 0; i--) {\n      if (this.db.scheduleTriggers[i]!.scheduleId === id) {\n        this.db.scheduleTriggers.splice(i, 1);\n      }\n    }\n  }\n\n  async recordTrigger(trigger: ScheduleTrigger): Promise<void> {\n    const stored: ScheduleTrigger = {\n      ...trigger,\n      id: trigger.id ?? randomUUID(),\n      triggerKind: trigger.triggerKind ?? 'schedule-fire',\n    };\n    this.db.scheduleTriggers.push(clone(stored));\n  }\n\n  async listTriggers(scheduleId: string, opts?: ScheduleTriggerListOptions): Promise<ScheduleTrigger[]> {\n    let rows = this.db.scheduleTriggers.filter(f => f.scheduleId === scheduleId);\n    if (opts?.fromActualFireAt != null) {\n      rows = rows.filter(f => f.actualFireAt >= opts.fromActualFireAt!);\n    }\n    if (opts?.toActualFireAt != null) {\n      rows = rows.filter(f => f.actualFireAt < opts.toActualFireAt!);\n    }\n    rows.sort((a, b) => b.actualFireAt - a.actualFireAt);\n    if (opts?.limit != null) {\n      rows = rows.slice(0, opts.limit);\n    }\n    return rows.map(clone);\n  }\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\nimport type { ListScoresResponse, SaveScorePayload, ScoreRowData } from '../../../evals/types';\nimport type {\n  ListScoresByEntityIdInput,\n  ListScoresByRunIdInput,\n  ListScoresByScorerIdInput,\n  ListScoresBySpanInput,\n  ScoreTenancyFilters,\n} from '../../types';\nimport { StorageDomain } from '../base';\n\nexport type { ScoreTenancyFilters };\n\nexport abstract class ScoresStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'SCORES',\n    });\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    // Default no-op - subclasses override\n  }\n\n  abstract getScoreById({ id }: { id: string }): Promise<ScoreRowData | null>;\n\n  abstract saveScore(score: SaveScorePayload): Promise<{ score: ScoreRowData }>;\n\n  abstract listScoresByScorerId(input: ListScoresByScorerIdInput): Promise<ListScoresResponse>;\n\n  abstract listScoresByRunId(input: ListScoresByRunIdInput): Promise<ListScoresResponse>;\n\n  abstract listScoresByEntityId(input: ListScoresByEntityIdInput): Promise<ListScoresResponse>;\n\n  async listScoresBySpan({ traceId, spanId }: ListScoresBySpanInput): Promise<ListScoresResponse> {\n    throw new MastraError({\n      id: 'SCORES_STORAGE_GET_SCORES_BY_SPAN_NOT_IMPLEMENTED',\n      domain: ErrorDomain.STORAGE,\n      category: ErrorCategory.SYSTEM,\n      details: { traceId, spanId },\n    });\n  }\n}\n","import type { ListScoresResponse, SaveScorePayload, ScoreRowData, ScoringSource } from '../../../evals/types';\nimport { calculatePagination, normalizePerPage } from '../../base';\nimport type { ScoreTenancyFilters, StoragePagination } from '../../types';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { ScoresStorage } from './base';\n\nfunction matchesTenancy(score: ScoreRowData, filters?: ScoreTenancyFilters): boolean {\n  if (!filters) return true;\n  if (filters.organizationId !== undefined && score.organizationId !== filters.organizationId) return false;\n  if (filters.projectId !== undefined && score.projectId !== filters.projectId) return false;\n  return true;\n}\n\nexport class ScoresInMemory extends ScoresStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.scores.clear();\n  }\n\n  async getScoreById({ id }: { id: string }): Promise<ScoreRowData | null> {\n    return this.db.scores.get(id) ?? null;\n  }\n\n  async saveScore(score: SaveScorePayload): Promise<{ score: ScoreRowData }> {\n    const newScore = { id: crypto.randomUUID(), createdAt: new Date(), updatedAt: new Date(), ...score };\n    this.db.scores.set(newScore.id, newScore);\n    return { score: newScore };\n  }\n\n  async listScoresByScorerId({\n    scorerId,\n    pagination,\n    entityId,\n    entityType,\n    source,\n    filters,\n  }: {\n    scorerId: string;\n    pagination: StoragePagination;\n    entityId?: string;\n    entityType?: string;\n    source?: ScoringSource;\n    filters?: ScoreTenancyFilters;\n  }): Promise<ListScoresResponse> {\n    const scores = Array.from(this.db.scores.values()).filter(score => {\n      let baseFilter = score.scorerId === scorerId;\n\n      if (entityId) {\n        baseFilter = baseFilter && score.entityId === entityId;\n      }\n\n      if (entityType) {\n        baseFilter = baseFilter && score.entityType === entityType;\n      }\n\n      if (source) {\n        baseFilter = baseFilter && score.source === source;\n      }\n\n      return baseFilter && matchesTenancy(score, filters);\n    });\n\n    // Match the pg/libsql adapters (and the sibling listScoresBySpan), which\n    // return scores newest-first.\n    scores.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n    const { page, perPage: perPageInput } = pagination;\n    const perPage = normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? scores.length : start + perPage;\n\n    return {\n      scores: scores.slice(start, end),\n      pagination: {\n        total: scores.length,\n        page: page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : scores.length > end,\n      },\n    };\n  }\n\n  async listScoresByRunId({\n    runId,\n    pagination,\n    filters,\n  }: {\n    runId: string;\n    pagination: StoragePagination;\n    filters?: ScoreTenancyFilters;\n  }): Promise<ListScoresResponse> {\n    const scores = Array.from(this.db.scores.values()).filter(\n      score => score.runId === runId && matchesTenancy(score, filters),\n    );\n\n    const { page, perPage: perPageInput } = pagination;\n    const perPage = normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER); // false → MAX_SAFE_INTEGER\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? scores.length : start + perPage;\n\n    return {\n      scores: scores.slice(start, end),\n      pagination: {\n        total: scores.length,\n        page: page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : scores.length > end,\n      },\n    };\n  }\n\n  async listScoresByEntityId({\n    entityId,\n    entityType,\n    pagination,\n    filters,\n  }: {\n    entityId: string;\n    entityType: string;\n    pagination: StoragePagination;\n    filters?: ScoreTenancyFilters;\n  }): Promise<ListScoresResponse> {\n    const scores = Array.from(this.db.scores.values()).filter(score => {\n      const baseFilter = score.entityId === entityId && score.entityType === entityType;\n\n      return baseFilter && matchesTenancy(score, filters);\n    });\n\n    const { page, perPage: perPageInput } = pagination;\n    const perPage = normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? scores.length : start + perPage;\n\n    return {\n      scores: scores.slice(start, end),\n      pagination: {\n        total: scores.length,\n        page: page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : scores.length > end,\n      },\n    };\n  }\n\n  async listScoresBySpan({\n    traceId,\n    spanId,\n    pagination,\n    filters,\n  }: {\n    traceId: string;\n    spanId: string;\n    pagination: StoragePagination;\n    filters?: ScoreTenancyFilters;\n  }): Promise<ListScoresResponse> {\n    const scores = Array.from(this.db.scores.values()).filter(\n      score => score.traceId === traceId && score.spanId === spanId && matchesTenancy(score, filters),\n    );\n    scores.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n    const { page, perPage: perPageInput } = pagination;\n    const perPage = normalizePerPage(perPageInput, Number.MAX_SAFE_INTEGER);\n    const { offset: start, perPage: perPageForResponse } = calculatePagination(page, perPageInput, perPage);\n    const end = perPageInput === false ? scores.length : start + perPage;\n\n    return {\n      scores: scores.slice(start, end),\n      pagination: {\n        total: scores.length,\n        page: page,\n        perPage: perPageForResponse,\n        hasMore: perPageInput === false ? false : scores.length > end,\n      },\n    };\n  }\n}\n","import { MastraBase } from '../../../base';\nimport type {\n  StorageDeleteToolProviderConnectionInput,\n  StorageListToolProviderConnectionsInput,\n  StorageToolProviderConnection,\n  StorageToolProviderConnectionKey,\n  StorageUpsertToolProviderConnectionInput,\n} from '../../types';\n\n/**\n * Abstract base class for the tool-provider-connections storage domain.\n *\n * Persists a per-author, provider-agnostic registry of authorized tool\n * provider connections so the UI can surface a stable, user-supplied label\n * (e.g. \"Work Gmail\") across agents. Rows are keyed by\n * `(authorId, providerId, connectionId)`. The label is the only mutable field.\n *\n * Adapter-native connection state (status, scopes, expiry) still lives with the\n * provider — this domain is purely a name lookup.\n */\nexport abstract class ToolProviderConnectionsStorage extends MastraBase {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'TOOL_PROVIDER_CONNECTIONS',\n    });\n  }\n\n  /** Initialize the store (create tables, indexes, etc). */\n  abstract init(): Promise<void>;\n\n  /**\n   * Fetch a single tool provider connection row. Returns `null` when no row\n   * exists for the given `(authorId, providerId, connectionId)`.\n   */\n  abstract getConnectionById(key: StorageToolProviderConnectionKey): Promise<StorageToolProviderConnection | null>;\n\n  /**\n   * Insert or update a tool provider connection row. Idempotent on\n   * `(authorId, providerId, connectionId)` — the existing label/toolkit are\n   * overwritten. `createdAt` is preserved on update.\n   */\n  abstract upsertConnection(input: StorageUpsertToolProviderConnectionInput): Promise<StorageToolProviderConnection>;\n\n  /**\n   * List tool provider connection rows for the given author. Optionally\n   * narrow by `providerId` and/or `toolkit`. Order is not guaranteed.\n   */\n  abstract listConnectionsByAuthor(\n    input: StorageListToolProviderConnectionsInput,\n  ): Promise<StorageToolProviderConnection[]>;\n\n  /**\n   * Remove a single tool provider connection row. Idempotent — returns\n   * silently when the row does not exist.\n   */\n  abstract deleteConnection(input: StorageDeleteToolProviderConnectionInput): Promise<void>;\n\n  /**\n   * Delete every tool provider connection row. Used by tests.\n   */\n  abstract dangerouslyClearAll(): Promise<void>;\n}\n","import type {\n  StorageDeleteToolProviderConnectionInput,\n  StorageListToolProviderConnectionsInput,\n  StorageToolProviderConnection,\n  StorageToolProviderConnectionKey,\n  StorageUpsertToolProviderConnectionInput,\n} from '../../types';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { ToolProviderConnectionsStorage } from './base';\n\n/** Build the composite key used by the in-memory tool-provider-connections Map. */\nfunction connKey(authorId: string, providerId: string, connectionId: string): string {\n  return `${authorId}\\u0000${providerId}\\u0000${connectionId}`;\n}\n\n/**\n * In-memory implementation of ToolProviderConnectionsStorage. Backed by the\n * shared InMemoryDB Map so tests can clear and inspect rows alongside other\n * domains.\n *\n * Atomicity is provided by the JavaScript single-threaded event loop.\n */\nexport class InMemoryToolProviderConnectionsStorage extends ToolProviderConnectionsStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async init(): Promise<void> {\n    // No-op for in-memory store.\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.toolProviderConnections.clear();\n  }\n\n  async getConnectionById({\n    authorId,\n    providerId,\n    connectionId,\n  }: StorageToolProviderConnectionKey): Promise<StorageToolProviderConnection | null> {\n    return this.db.toolProviderConnections.get(connKey(authorId, providerId, connectionId)) ?? null;\n  }\n\n  async upsertConnection(input: StorageUpsertToolProviderConnectionInput): Promise<StorageToolProviderConnection> {\n    const key = connKey(input.authorId, input.providerId, input.connectionId);\n    const existing = this.db.toolProviderConnections.get(key);\n    const now = new Date();\n    const row: StorageToolProviderConnection = {\n      authorId: input.authorId,\n      providerId: input.providerId,\n      toolkit: input.toolkit,\n      connectionId: input.connectionId,\n      label: input.label,\n      scope: input.scope ?? existing?.scope ?? 'per-author',\n      createdAt: existing?.createdAt ?? now,\n      updatedAt: now,\n    };\n    this.db.toolProviderConnections.set(key, row);\n    return row;\n  }\n\n  async listConnectionsByAuthor({\n    authorId,\n    providerId,\n    toolkit,\n    scope,\n  }: StorageListToolProviderConnectionsInput): Promise<StorageToolProviderConnection[]> {\n    const rows: StorageToolProviderConnection[] = [];\n    for (const row of this.db.toolProviderConnections.values()) {\n      if (authorId !== undefined && row.authorId !== authorId) continue;\n      if (providerId && row.providerId !== providerId) continue;\n      if (toolkit && row.toolkit !== toolkit) continue;\n      if (scope && row.scope !== scope) continue;\n      rows.push(row);\n    }\n    return rows;\n  }\n\n  async deleteConnection({\n    authorId,\n    providerId,\n    connectionId,\n  }: StorageDeleteToolProviderConnectionInput): Promise<void> {\n    this.db.toolProviderConnections.delete(connKey(authorId, providerId, connectionId));\n  }\n}\n","import type { SerializedStepFlowEntry } from '../../../workflows/types';\nimport { StorageDomain } from '../base';\n\n/**\n * On-disk shape for a statically-defined, JSON-round-trippable workflow.\n *\n * Created by tools that produce workflows declaratively (the workflow-builder\n * CLI / studio) and rehydrated at load time into a runnable\n * `Workflow` instance. Anything carrying a closure is intentionally absent\n * from this shape: conditional/loop conditions, mapping `fn` sources, and\n * dynamic sleep durations are out of scope for the static subset.\n */\nexport interface WorkflowDefinition {\n  id: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n\n  /** JSON Schema (Draft 2020-12) — rehydrated to Zod via `json-schema-to-zod`. */\n  inputSchema: unknown;\n  outputSchema: unknown;\n  stateSchema?: unknown;\n  requestContextSchema?: unknown;\n\n  /**\n   * The workflow graph in its JSON-safe form. Same shape the engine already\n   * emits via `serializedStepGraph` — but with full mapping configs preserved\n   * (no truncation) and all step/agent/tool references stored as ids.\n   */\n  graph: SerializedStepFlowEntry[];\n\n  /** Lifecycle status. Only 'active' definitions are loaded at startWorkers(). */\n  status: 'active' | 'archived';\n\n  /** Provenance — distinguishes user-stored from code-registered workflows. */\n  source: 'storage';\n  authorId?: string;\n\n  createdAt: Date;\n  updatedAt: Date;\n}\n\n/** Input for creating a new workflow definition. */\nexport interface CreateWorkflowDefinitionInput {\n  id: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  inputSchema: unknown;\n  outputSchema: unknown;\n  stateSchema?: unknown;\n  requestContextSchema?: unknown;\n  graph: SerializedStepFlowEntry[];\n  authorId?: string;\n}\n\n/** Input for updating an existing workflow definition. */\nexport interface UpdateWorkflowDefinitionInput {\n  id: string;\n  description?: string;\n  metadata?: Record<string, unknown>;\n  inputSchema?: unknown;\n  outputSchema?: unknown;\n  stateSchema?: unknown;\n  requestContextSchema?: unknown;\n  graph?: SerializedStepFlowEntry[];\n  status?: 'active' | 'archived';\n  authorId?: string;\n}\n\nexport interface ListWorkflowDefinitionsInput {\n  status?: 'active' | 'archived';\n  authorId?: string;\n}\n\nexport interface ListWorkflowDefinitionsOutput {\n  definitions: WorkflowDefinition[];\n  total: number;\n}\n\n/**\n * Abstract storage domain for persisted workflow definitions.\n *\n * Versioning is intentionally out of scope for v1 — `upsert` overwrites in\n * place. A future revision can layer the {@link VersionedStorageDomain}\n * pattern on top without breaking the rehydration path.\n */\nexport abstract class WorkflowDefinitionsStorage extends StorageDomain {\n  constructor() {\n    super({ component: 'STORAGE', name: 'WORKFLOW_DEFINITIONS' });\n  }\n\n  abstract upsert(input: CreateWorkflowDefinitionInput | UpdateWorkflowDefinitionInput): Promise<WorkflowDefinition>;\n  abstract get(id: string): Promise<WorkflowDefinition | null>;\n  abstract list(args?: ListWorkflowDefinitionsInput): Promise<ListWorkflowDefinitionsOutput>;\n  abstract delete(id: string): Promise<void>;\n}\n","import type { InMemoryDB } from '../inmemory-db';\nimport type {\n  CreateWorkflowDefinitionInput,\n  ListWorkflowDefinitionsInput,\n  ListWorkflowDefinitionsOutput,\n  UpdateWorkflowDefinitionInput,\n  WorkflowDefinition,\n} from './base';\nimport { WorkflowDefinitionsStorage } from './base';\n\nexport class InMemoryWorkflowDefinitionsStorage extends WorkflowDefinitionsStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.workflowDefinitions.clear();\n  }\n\n  async upsert(input: CreateWorkflowDefinitionInput | UpdateWorkflowDefinitionInput): Promise<WorkflowDefinition> {\n    const now = new Date();\n    const existing = this.db.workflowDefinitions.get(input.id);\n\n    if (existing) {\n      const merged: WorkflowDefinition = {\n        ...existing,\n        ...('description' in input && input.description !== undefined && { description: input.description }),\n        ...('metadata' in input && input.metadata !== undefined && { metadata: input.metadata }),\n        ...('inputSchema' in input && input.inputSchema !== undefined && { inputSchema: input.inputSchema }),\n        ...('outputSchema' in input && input.outputSchema !== undefined && { outputSchema: input.outputSchema }),\n        ...('stateSchema' in input && input.stateSchema !== undefined && { stateSchema: input.stateSchema }),\n        ...('requestContextSchema' in input &&\n          input.requestContextSchema !== undefined && { requestContextSchema: input.requestContextSchema }),\n        ...('graph' in input && input.graph !== undefined && { graph: input.graph }),\n        ...('status' in input && input.status !== undefined && { status: input.status }),\n        ...('authorId' in input && input.authorId !== undefined && { authorId: input.authorId }),\n        updatedAt: now,\n      };\n      this.db.workflowDefinitions.set(input.id, merged);\n      return this.deepCopy(merged);\n    }\n\n    // Creation requires the full schema set + graph. Check values, not key\n    // presence — `{ graph: undefined }` must not slip through.\n    if (\n      !('inputSchema' in input) ||\n      input.inputSchema === undefined ||\n      !('outputSchema' in input) ||\n      input.outputSchema === undefined ||\n      !('graph' in input) ||\n      input.graph === undefined\n    ) {\n      throw new Error(\n        `Cannot create workflow definition \"${input.id}\": inputSchema, outputSchema, and graph are required.`,\n      );\n    }\n\n    const def: WorkflowDefinition = {\n      id: input.id,\n      description: input.description,\n      metadata: input.metadata,\n      inputSchema: input.inputSchema,\n      outputSchema: input.outputSchema,\n      stateSchema: input.stateSchema,\n      requestContextSchema: input.requestContextSchema,\n      graph: input.graph,\n      status: 'active',\n      source: 'storage',\n      authorId: 'authorId' in input ? input.authorId : undefined,\n      createdAt: now,\n      updatedAt: now,\n    };\n    this.db.workflowDefinitions.set(input.id, def);\n    return this.deepCopy(def);\n  }\n\n  async get(id: string): Promise<WorkflowDefinition | null> {\n    const def = this.db.workflowDefinitions.get(id);\n    return def ? this.deepCopy(def) : null;\n  }\n\n  async list(args?: ListWorkflowDefinitionsInput): Promise<ListWorkflowDefinitionsOutput> {\n    let defs = Array.from(this.db.workflowDefinitions.values());\n    if (args?.status) defs = defs.filter(d => d.status === args.status);\n    if (args?.authorId !== undefined) defs = defs.filter(d => d.authorId === args.authorId);\n    const cloned = defs.map(d => this.deepCopy(d));\n    return { definitions: cloned, total: cloned.length };\n  }\n\n  async delete(id: string): Promise<void> {\n    this.db.workflowDefinitions.delete(id);\n  }\n\n  private deepCopy(def: WorkflowDefinition): WorkflowDefinition {\n    return structuredClone(def);\n  }\n}\n","import type { StepResult, WorkflowRunState } from '../workflows';\n\n// NOTE: This merge logic is duplicated in stores/convex/src/server/workflow-snapshot.ts\n// for the Convex server runtime. Keep both copies in sync.\nconst PENDING_MARKER_KEY = '__mastra_pending__';\n\nfunction isPendingMarker(val: unknown): boolean {\n  return (\n    val !== null &&\n    typeof val === 'object' &&\n    Object.prototype.hasOwnProperty.call(val, PENDING_MARKER_KEY) &&\n    (val as Record<string, unknown>)[PENDING_MARKER_KEY] === true &&\n    Object.keys(val).length === 1\n  );\n}\n\n// Suspended forEach iteration results may come from multiple engines. Treat\n// StepResult-shaped suspended entries as resettable without relying only on\n// evented __workflow_meta, but avoid matching plain user outputs with only\n// status/payload fields.\nfunction isSuspendedStepResult(val: unknown): boolean {\n  const result = val as Record<string, unknown> | null;\n\n  return (\n    val !== null &&\n    typeof val === 'object' &&\n    'status' in val &&\n    result?.status === 'suspended' &&\n    ('suspendPayload' in val || 'suspendedAt' in val)\n  );\n}\n\nfunction canResetWithPendingMarker(val: unknown): boolean {\n  if (val == null || isPendingMarker(val)) {\n    return true;\n  }\n\n  return isSuspendedStepResult(val);\n}\n\nexport function createEmptyWorkflowSnapshot(runId: string): WorkflowRunState {\n  return {\n    context: {},\n    activePaths: [],\n    activeStepsPath: {},\n    timestamp: Date.now(),\n    suspendedPaths: {},\n    resumeLabels: {},\n    serializedStepGraph: [],\n    value: {},\n    waitingPaths: {},\n    status: 'pending',\n    runId,\n  } as WorkflowRunState;\n}\n\nexport function mergeWorkflowStepResult({\n  snapshot,\n  stepId,\n  result,\n  requestContext,\n}: {\n  snapshot: WorkflowRunState;\n  stepId: string;\n  result: StepResult<any, any, any, any>;\n  requestContext: Record<string, any>;\n}): Record<string, StepResult<any, any, any, any>> {\n  if (!snapshot?.context) {\n    throw new Error(`Snapshot context not found for runId ${snapshot?.runId}`);\n  }\n\n  const existingResult = snapshot.context[stepId];\n  if (\n    existingResult &&\n    'output' in existingResult &&\n    Array.isArray(existingResult.output) &&\n    result &&\n    typeof result === 'object' &&\n    'output' in result &&\n    Array.isArray(result.output)\n  ) {\n    const existingOutput = existingResult.output as unknown[];\n    const newOutput = result.output as unknown[];\n    const mergedOutput = [...existingOutput];\n    const hasPendingMarker = newOutput.some(isPendingMarker);\n    for (let i = 0; i < Math.max(existingOutput.length, newOutput.length); i++) {\n      if (i < newOutput.length) {\n        const newVal = newOutput[i];\n        if (isPendingMarker(newVal)) {\n          if (i >= existingOutput.length || canResetWithPendingMarker(existingOutput[i])) {\n            mergedOutput[i] = null;\n          }\n        } else if (newVal !== null && newVal !== undefined && !hasPendingMarker) {\n          mergedOutput[i] = newVal;\n        } else if (i >= existingOutput.length) {\n          mergedOutput[i] = null;\n        }\n      }\n    }\n    snapshot.context[stepId] = {\n      ...existingResult,\n      // Pending-marker writes are reset commands built from an earlier snapshot,\n      // so keep existing step-level fields and ignore sibling values they carry.\n      ...(hasPendingMarker ? {} : (result as any)),\n      output: mergedOutput,\n    };\n  } else {\n    snapshot.context[stepId] = result;\n  }\n\n  snapshot.requestContext = { ...snapshot.requestContext, ...requestContext };\n  try {\n    return JSON.parse(JSON.stringify(snapshot.context));\n  } catch {\n    // Step results may contain non-serializable values (circular refs, functions, etc.)\n    // when the workflow opts out of full persistence. Return a shallow copy so the\n    // caller still gets a usable context without crashing.\n    return { ...snapshot.context };\n  }\n}\n","import type { StepResult, WorkflowRunState } from '../../../workflows';\nimport type { UpdateWorkflowStateOptions, WorkflowRun, WorkflowRuns, StorageListWorkflowRunsInput } from '../../types';\nimport { StorageDomain } from '../base';\n\nexport abstract class WorkflowsStorage extends StorageDomain {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'WORKFLOWS',\n    });\n  }\n\n  abstract supportsConcurrentUpdates(): boolean;\n\n  abstract updateWorkflowResults({\n    workflowName,\n    runId,\n    stepId,\n    result,\n    requestContext,\n  }: {\n    workflowName: string;\n    runId: string;\n    stepId: string;\n    result: StepResult<any, any, any, any>;\n    requestContext: Record<string, any>;\n  }): Promise<Record<string, StepResult<any, any, any, any>>>;\n\n  abstract updateWorkflowState({\n    workflowName,\n    runId,\n    opts,\n  }: {\n    workflowName: string;\n    runId: string;\n    opts: UpdateWorkflowStateOptions;\n  }): Promise<WorkflowRunState | undefined>;\n\n  abstract persistWorkflowSnapshot(_: {\n    workflowName: string;\n    runId: string;\n    resourceId?: string;\n    snapshot: WorkflowRunState;\n    createdAt?: Date;\n    updatedAt?: Date;\n  }): Promise<void>;\n\n  abstract loadWorkflowSnapshot({\n    workflowName,\n    runId,\n  }: {\n    workflowName: string;\n    runId: string;\n  }): Promise<WorkflowRunState | null>;\n\n  abstract listWorkflowRuns(args?: StorageListWorkflowRunsInput): Promise<WorkflowRuns>;\n\n  abstract getWorkflowRunById(args: { runId: string; workflowName?: string }): Promise<WorkflowRun | null>;\n\n  abstract deleteWorkflowRunById(args: { runId: string; workflowName: string }): Promise<void>;\n}\n","import type { StepResult, WorkflowRunState } from '../../../workflows';\nimport { normalizePerPage } from '../../base';\nimport type {\n  StorageWorkflowRun,\n  WorkflowRun,\n  WorkflowRuns,\n  StorageListWorkflowRunsInput,\n  UpdateWorkflowStateOptions,\n} from '../../types';\nimport { createEmptyWorkflowSnapshot, mergeWorkflowStepResult } from '../../workflow-snapshot';\nimport type { InMemoryDB } from '../inmemory-db';\nimport { WorkflowsStorage } from './base';\n\n/**\n * Deep-clone in-memory workflow state.\n *\n * We previously used `JSON.parse(JSON.stringify(x))` here, but the agent loop\n * and workflow engine legitimately place values in step results that don't\n * survive JSON round-tripping:\n * - `Date` instances (e.g. `response.timestamp`) — JSON turns them into ISO\n *   strings, downstream consumers that do `.getTime()` then break.\n * - Explicitly-`undefined` properties (e.g. `headers`, `providerMetadata`,\n *   `usage.{cacheRead, cacheWrite, reasoning}`) — JSON drops keys with\n *   `undefined` values, breaking snapshot assertions that include them.\n * - `Error` instances (e.g. tool execution failures, AssertionErrors from\n *   inside `tool.execute`) — JSON strips `message`/`name`/`stack` (non-\n *   enumerable). `structuredClone` isn't enough either — it preserves the\n *   Error type but drops subclass-specific enumerable props (`actual`,\n *   `expected`, `operator`).\n *\n * The custom walk below preserves all of that. It also handles builtins with\n * internal slots explicitly — `Map`, `Set`, `RegExp`, `URL`, `ArrayBuffer`,\n * typed arrays, and `DataView` — because cloning them via `Object.create(proto)`\n * would produce a value that passes `instanceof` but whose methods throw (the\n * internal slots were never initialized). Null-prototype dictionaries keep\n * their null prototype.\n */\n/** @internal Exported for testing only. */\nexport function cloneRunData<T>(value: T): T {\n  return deepCloneForRun(value, new WeakMap()) as T;\n}\n\nfunction deepCloneForRun(value: unknown, seen: WeakMap<object, unknown>): unknown {\n  if (value === null || typeof value !== 'object') return value;\n  const cached = seen.get(value as object);\n  if (cached !== undefined) return cached;\n\n  if (value instanceof Date) {\n    return new Date(value.getTime());\n  }\n\n  if (value instanceof RegExp) {\n    return new RegExp(value.source, value.flags);\n  }\n\n  if (value instanceof URL) {\n    return new URL(value.href);\n  }\n\n  if (value instanceof Map) {\n    const out = new Map();\n    seen.set(value, out);\n    for (const [k, v] of value) {\n      out.set(deepCloneForRun(k, seen), deepCloneForRun(v, seen));\n    }\n    return out;\n  }\n\n  if (value instanceof Set) {\n    const out = new Set();\n    seen.set(value, out);\n    for (const v of value) {\n      out.add(deepCloneForRun(v, seen));\n    }\n    return out;\n  }\n\n  if (value instanceof ArrayBuffer) {\n    return value.slice(0);\n  }\n\n  // Typed arrays and DataView — `Object.create(proto)` would yield a shell with\n  // no backing buffer, so rebuild against a fresh copy of the underlying bytes.\n  if (ArrayBuffer.isView(value)) {\n    if (value instanceof DataView) {\n      return new DataView(value.buffer.slice(value.byteOffset, value.byteOffset + value.byteLength));\n    }\n    const typed = value as unknown as Uint8Array;\n    return new (typed.constructor as Uint8ArrayConstructor)(typed);\n  }\n\n  if (value instanceof Error) {\n    // Clone via Object.create(proto) so `instanceof Error` and subclass\n    // branches keep working (e.g. `expect.any(Error)`) without invoking\n    // subclass constructors that may have non-standard signatures\n    // (AssertionError expects an options object). Surface `message` as an\n    // enumerable own prop so Vitest's snapshot serializer renders it\n    // alongside subclass-specific fields.\n    const out = Object.create(Object.getPrototypeOf(value)) as Error;\n    Object.defineProperty(out, 'message', {\n      value: value.message,\n      writable: true,\n      configurable: true,\n      enumerable: true,\n    });\n    Object.defineProperty(out, 'name', { value: value.name, writable: true, configurable: true });\n    // For `stack`, defer to the Error's own `toJSON` if present — that's how\n    // producers signal whether they want stack persisted (e.g. step-executor\n    // wraps via `getErrorFromUnknown(err, { serializeStack: false })` so the\n    // attached toJSON omits stack from the JSON form). We only honour\n    // toJSON's stack signal here, not its other fields, to avoid pulling in\n    // subclass extras like Chai AssertionError.toJSON's name/ok/stack that\n    // the agent-loop snapshot tests don't expect.\n    const errRecord = value as unknown as Record<string, unknown>;\n    let includeStack = value.stack !== undefined;\n    if (includeStack && typeof errRecord.toJSON === 'function') {\n      try {\n        const serialized = (errRecord.toJSON as () => unknown)();\n        if (serialized && typeof serialized === 'object' && !('stack' in serialized)) {\n          includeStack = false;\n        }\n      } catch {\n        // Defensive: if toJSON throws, fall back to default behaviour.\n      }\n    }\n    if (includeStack) {\n      Object.defineProperty(out, 'stack', { value: value.stack, writable: true, configurable: true });\n    }\n    // Register in `seen` BEFORE recursing so cycles (incl. self-referential\n    // `cause`) terminate.\n    seen.set(value, out);\n    const outRecord = out as unknown as Record<string, unknown>;\n    if (value.cause !== undefined) outRecord.cause = deepCloneForRun(value.cause, seen);\n    for (const key of Object.keys(value)) {\n      outRecord[key] = deepCloneForRun(errRecord[key], seen);\n    }\n    return out;\n  }\n\n  if (Array.isArray(value)) {\n    const out: unknown[] = new Array(value.length);\n    seen.set(value, out);\n    for (let i = 0; i < value.length; i++) {\n      out[i] = deepCloneForRun(value[i], seen);\n    }\n    return out;\n  }\n\n  // Preserve the prototype so class instances stay recognizable to consumers\n  // (e.g. `DefaultStepResult` in the agent loop, anything that uses `instanceof`\n  // or Vitest's snapshot serializer which prints the class name) and so\n  // null-prototype dictionaries (`Object.create(null)`) keep their null proto\n  // rather than silently becoming plain `{}`. Builtins with internal slots\n  // (Map/Set/RegExp/typed arrays/Date/Error) are handled explicitly above, so\n  // the only objects reaching here are plain objects and plain data-holder\n  // class instances — `Object.create(proto)` + an own-property copy reproduces\n  // those faithfully.\n  const proto = Object.getPrototypeOf(value);\n  const out: Record<string, unknown> =\n    proto === Object.prototype ? {} : (Object.create(proto) as Record<string, unknown>);\n  seen.set(value, out);\n  // `Object.keys` includes keys whose value is `undefined`, so explicitly-undefined\n  // properties are preserved (unlike a JSON round-trip).\n  for (const key of Object.keys(value as object)) {\n    out[key] = deepCloneForRun((value as Record<string, unknown>)[key], seen);\n  }\n  return out;\n}\n\nexport class WorkflowsInMemory extends WorkflowsStorage {\n  private db: InMemoryDB;\n\n  constructor({ db }: { db: InMemoryDB }) {\n    super();\n    this.db = db;\n  }\n\n  supportsConcurrentUpdates(): boolean {\n    return true;\n  }\n\n  async dangerouslyClearAll(): Promise<void> {\n    this.db.workflows.clear();\n  }\n\n  private getWorkflowKey(workflowName: string, runId: string): string {\n    return `${workflowName}-${runId}`;\n  }\n\n  async updateWorkflowResults({\n    workflowName,\n    runId,\n    stepId,\n    result,\n    requestContext,\n  }: {\n    workflowName: string;\n    runId: string;\n    stepId: string;\n    result: StepResult<any, any, any, any>;\n    requestContext: Record<string, any>;\n  }): Promise<Record<string, StepResult<any, any, any, any>>> {\n    const key = this.getWorkflowKey(workflowName, runId);\n    const run = this.db.workflows.get(key);\n\n    if (!run) {\n      return {};\n    }\n\n    let snapshot: WorkflowRunState;\n    if (!run.snapshot) {\n      snapshot = createEmptyWorkflowSnapshot(run.run_id);\n\n      this.db.workflows.set(key, {\n        ...run,\n        snapshot,\n      });\n    } else {\n      snapshot = typeof run.snapshot === 'string' ? JSON.parse(run.snapshot) : run.snapshot;\n    }\n\n    if (!snapshot || !snapshot?.context) {\n      throw new Error(`Snapshot not found for runId ${runId}`);\n    }\n\n    const context = mergeWorkflowStepResult({ snapshot, stepId, result, requestContext });\n\n    this.db.workflows.set(key, {\n      ...run,\n      snapshot: snapshot,\n    });\n\n    return cloneRunData(context);\n  }\n\n  async updateWorkflowState({\n    workflowName,\n    runId,\n    opts,\n  }: {\n    workflowName: string;\n    runId: string;\n    opts: UpdateWorkflowStateOptions;\n  }): Promise<WorkflowRunState | undefined> {\n    const key = this.getWorkflowKey(workflowName, runId);\n    const run = this.db.workflows.get(key);\n\n    if (!run) {\n      return;\n    }\n\n    let snapshot: WorkflowRunState;\n    if (!run.snapshot) {\n      snapshot = createEmptyWorkflowSnapshot(run.run_id);\n\n      this.db.workflows.set(key, {\n        ...run,\n        snapshot,\n      });\n    } else {\n      snapshot = typeof run.snapshot === 'string' ? JSON.parse(run.snapshot) : run.snapshot;\n    }\n\n    if (!snapshot || !snapshot?.context) {\n      throw new Error(`Snapshot not found for runId ${runId}`);\n    }\n\n    snapshot = { ...snapshot, ...opts };\n    this.db.workflows.set(key, {\n      ...run,\n      snapshot: snapshot,\n    });\n\n    return snapshot;\n  }\n\n  async persistWorkflowSnapshot({\n    workflowName,\n    runId,\n    resourceId,\n    snapshot,\n    createdAt,\n    updatedAt,\n  }: {\n    workflowName: string;\n    runId: string;\n    resourceId?: string;\n    snapshot: WorkflowRunState;\n    createdAt?: Date;\n    updatedAt?: Date;\n  }): Promise<void> {\n    const key = this.getWorkflowKey(workflowName, runId);\n    const now = new Date();\n    const existing = this.db.workflows.get(key);\n    const data: StorageWorkflowRun = {\n      workflow_name: workflowName,\n      run_id: runId,\n      resourceId,\n      snapshot,\n      // Preserve the original creation time when re-persisting an existing run; only set it\n      // on first insert. Otherwise listWorkflowRuns ordering and date filters drift to the\n      // last activity time. Matches the persistent stores (pg/mysql/mongodb/libsql).\n      createdAt: createdAt ?? existing?.createdAt ?? now,\n      updatedAt: updatedAt ?? now,\n    };\n\n    this.db.workflows.set(key, data);\n  }\n\n  async loadWorkflowSnapshot({\n    workflowName,\n    runId,\n  }: {\n    workflowName: string;\n    runId: string;\n  }): Promise<WorkflowRunState | null> {\n    const key = this.getWorkflowKey(workflowName, runId);\n    const run = this.db.workflows.get(key);\n\n    if (!run) {\n      return null;\n    }\n\n    const snapshot = typeof run.snapshot === 'string' ? JSON.parse(run.snapshot) : run.snapshot;\n    // Return a deep copy to prevent mutation\n    return snapshot ? cloneRunData(snapshot) : null;\n  }\n\n  async listWorkflowRuns({\n    workflowName,\n    fromDate,\n    toDate,\n    perPage,\n    page,\n    resourceId,\n    status,\n  }: StorageListWorkflowRunsInput = {}): Promise<WorkflowRuns> {\n    if (page !== undefined && page < 0) {\n      throw new Error('page must be >= 0');\n    }\n\n    let runs = Array.from(this.db.workflows.values());\n\n    if (workflowName) runs = runs.filter((run: any) => run.workflow_name === workflowName);\n    if (status) {\n      runs = runs.filter((run: any) => {\n        let snapshot: WorkflowRunState | string = run?.snapshot!;\n\n        if (!snapshot) {\n          return false;\n        }\n\n        if (typeof snapshot === 'string') {\n          try {\n            snapshot = JSON.parse(snapshot) as WorkflowRunState;\n          } catch {\n            return false;\n          }\n        } else {\n          snapshot = cloneRunData(snapshot) as WorkflowRunState;\n        }\n\n        return snapshot.status === status;\n      });\n    }\n\n    if (fromDate && toDate) {\n      runs = runs.filter(\n        (run: any) =>\n          new Date(run.createdAt).getTime() >= fromDate.getTime() &&\n          new Date(run.createdAt).getTime() <= toDate.getTime(),\n      );\n    } else if (fromDate) {\n      runs = runs.filter((run: any) => new Date(run.createdAt).getTime() >= fromDate.getTime());\n    } else if (toDate) {\n      runs = runs.filter((run: any) => new Date(run.createdAt).getTime() <= toDate.getTime());\n    }\n    if (resourceId) runs = runs.filter((run: any) => run.resourceId === resourceId);\n\n    const total = runs.length;\n\n    // Sort by createdAt\n    runs.sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());\n\n    // Apply pagination\n    if (perPage !== undefined && page !== undefined) {\n      // Use MAX_SAFE_INTEGER as default to maintain \"no pagination\" behavior when undefined\n      const normalizedPerPage = normalizePerPage(perPage, Number.MAX_SAFE_INTEGER);\n      const offset = page * normalizedPerPage;\n      const start = offset;\n      const end = start + normalizedPerPage;\n      runs = runs.slice(start, end);\n    }\n\n    // Deserialize snapshot if it's a string\n    const parsedRuns = runs.map((run: any) => ({\n      ...run,\n      snapshot: typeof run.snapshot === 'string' ? JSON.parse(run.snapshot) : cloneRunData(run.snapshot),\n      createdAt: new Date(run.createdAt),\n      updatedAt: new Date(run.updatedAt),\n      runId: run.run_id,\n      workflowName: run.workflow_name,\n      resourceId: run.resourceId,\n    }));\n\n    return { runs: parsedRuns as WorkflowRun[], total };\n  }\n\n  async getWorkflowRunById({\n    runId,\n    workflowName,\n  }: {\n    runId: string;\n    workflowName?: string;\n  }): Promise<WorkflowRun | null> {\n    // `workflowName` is optional in the storage contract. The pg/libsql adapters\n    // match by `runId` alone when it is omitted and return the most recent run\n    // (ORDER BY createdAt DESC LIMIT 1), so mirror that here.\n    const run = Array.from(this.db.workflows.values())\n      .filter((r: any) => r.run_id === runId && (!workflowName || r.workflow_name === workflowName))\n      .sort((a: any, b: any) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())[0];\n\n    if (!run) return null;\n\n    // Return a deep copy to prevent mutation\n    const parsedRun = {\n      ...run,\n      snapshot: typeof run.snapshot === 'string' ? JSON.parse(run.snapshot) : cloneRunData(run.snapshot),\n      createdAt: new Date(run.createdAt),\n      updatedAt: new Date(run.updatedAt),\n      runId: run.run_id,\n      workflowName: run.workflow_name,\n      resourceId: run.resourceId,\n    };\n\n    return parsedRun as WorkflowRun;\n  }\n\n  async deleteWorkflowRunById({ runId, workflowName }: { runId: string; workflowName: string }): Promise<void> {\n    const key = this.getWorkflowKey(workflowName, runId);\n    this.db.workflows.delete(key);\n  }\n}\n","import { MastraCompositeStore } from './base';\nimport type { StorageDomains } from './base';\nimport { InMemoryAgentsStorage } from './domains/agents/inmemory';\nimport { BackgroundTasksInMemory } from './domains/background-tasks/inmemory';\nimport { InMemoryBlobStore } from './domains/blobs/inmemory';\nimport { InMemoryChannelsStorage } from './domains/channels/inmemory';\nimport { DatasetsInMemory } from './domains/datasets/inmemory';\nimport { ExperimentsInMemory } from './domains/experiments/inmemory';\nimport { InMemoryFavoritesStorage } from './domains/favorites/inmemory';\nimport { InMemoryHarness } from './domains/harness/inmemory';\nimport { InMemoryDB } from './domains/inmemory-db';\nimport { InMemoryMCPClientsStorage } from './domains/mcp-clients/inmemory';\nimport { InMemoryMCPServersStorage } from './domains/mcp-servers/inmemory';\nimport { InMemoryMemory } from './domains/memory/inmemory';\nimport { InMemoryNotificationsStorage } from './domains/notifications';\nimport { ObservabilityInMemory } from './domains/observability/inmemory';\nimport { InMemoryPromptBlocksStorage } from './domains/prompt-blocks/inmemory';\nimport { InMemorySchedulesStorage } from './domains/schedules/inmemory';\nimport { InMemoryScorerDefinitionsStorage } from './domains/scorer-definitions/inmemory';\nimport { ScoresInMemory } from './domains/scores/inmemory';\nimport { InMemorySkillsStorage } from './domains/skills/inmemory';\nimport { InMemoryThreadStateStorage } from './domains/thread-state/inmemory';\nimport { InMemoryToolProviderConnectionsStorage } from './domains/tool-provider-connections/inmemory';\nimport { InMemoryWorkflowDefinitionsStorage } from './domains/workflow-definitions/inmemory';\nimport { WorkflowsInMemory } from './domains/workflows/inmemory';\nimport { InMemoryWorkspacesStorage } from './domains/workspaces/inmemory';\n/**\n * In-memory storage implementation for testing and development.\n *\n * All data is stored in memory and will be lost when the process ends.\n * Access domain-specific storage via `getStore()`:\n *\n * @example\n * ```typescript\n * const storage = new InMemoryStore();\n *\n * // Access memory domain\n * const memory = await storage.getStore('memory');\n * await memory?.saveThread({ thread });\n *\n * // Access workflows domain\n * const workflows = await storage.getStore('workflows');\n * await workflows?.persistWorkflowSnapshot({ workflowName, runId, snapshot });\n * ```\n */\nexport class InMemoryStore extends MastraCompositeStore {\n  stores: StorageDomains;\n\n  /**\n   * Internal database layer shared across all domains.\n   * This is an implementation detail - domains interact with this\n   * rather than managing their own data structures.\n   */\n  #db: InMemoryDB;\n\n  constructor({ id = 'in-memory' }: { id?: string } = {}) {\n    super({ id, name: 'InMemoryStorage' });\n    // InMemoryStore doesn't need async initialization\n    this.hasInitialized = Promise.resolve(true);\n\n    // Create internal db layer - shared across all domains\n    this.#db = new InMemoryDB();\n\n    // Create all domain instances with the shared db\n    this.stores = {\n      memory: new InMemoryMemory({ db: this.#db }),\n      workflows: new WorkflowsInMemory({ db: this.#db }),\n      workflowDefinitions: new InMemoryWorkflowDefinitionsStorage({ db: this.#db }),\n      scores: new ScoresInMemory({ db: this.#db }),\n      observability: new ObservabilityInMemory({ db: this.#db }),\n      agents: new InMemoryAgentsStorage({ db: this.#db }),\n      channels: new InMemoryChannelsStorage(),\n      notifications: new InMemoryNotificationsStorage(),\n      datasets: new DatasetsInMemory({ db: this.#db }),\n      experiments: new ExperimentsInMemory({ db: this.#db }),\n      promptBlocks: new InMemoryPromptBlocksStorage({ db: this.#db }),\n      scorerDefinitions: new InMemoryScorerDefinitionsStorage({ db: this.#db }),\n      mcpClients: new InMemoryMCPClientsStorage({ db: this.#db }),\n      mcpServers: new InMemoryMCPServersStorage({ db: this.#db }),\n      workspaces: new InMemoryWorkspacesStorage({ db: this.#db }),\n      skills: new InMemorySkillsStorage({ db: this.#db }),\n      favorites: new InMemoryFavoritesStorage({ db: this.#db }),\n      blobs: new InMemoryBlobStore(),\n      backgroundTasks: new BackgroundTasksInMemory({ db: this.#db }),\n      schedules: new InMemorySchedulesStorage({ db: this.#db }),\n      harness: new InMemoryHarness(),\n      toolProviderConnections: new InMemoryToolProviderConnectionsStorage({ db: this.#db }),\n      threadState: new InMemoryThreadStateStorage(),\n    };\n  }\n\n  /**\n   * Clears all data from the in-memory database.\n   * Useful for testing.\n   * @deprecated Use dangerouslyClearAll() on individual domains instead.\n   */\n  clear(): void {\n    this.#db.clear();\n    // These domains don't share the InMemoryDB\n    void this.stores.channels?.dangerouslyClearAll?.();\n    void this.stores.harness?.dangerouslyClearAll?.();\n    void this.stores.notifications?.dangerouslyClearAll?.();\n  }\n}\n\nexport const MockStore = InMemoryStore;\n","import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, readdirSync, statSync, rmSync } from 'node:fs';\nimport { join, dirname, relative, resolve, sep, extname } from 'node:path';\n\n/**\n * FilesystemDB is a thin I/O layer for filesystem-based storage.\n * It manages reading/writing JSON files in a directory, similar to how\n * InMemoryDB holds Maps for in-memory storage.\n *\n * Each editor domain gets its own JSON file (e.g., `agents.json`, `prompt-blocks.json`).\n * Skills use a real file tree under `skills/` instead of JSON.\n */\nexport class FilesystemDB {\n  readonly dir: string;\n\n  /** In-memory cache of parsed domain data, keyed by filename */\n  private cache = new Map<string, Record<string, unknown>>();\n\n  private initialized = false;\n\n  constructor(dir: string) {\n    this.dir = dir;\n  }\n\n  /**\n   * Initialize the storage directory. Called once; subsequent calls are no-ops.\n   */\n  async init(): Promise<void> {\n    if (this.initialized) return;\n    this.ensureDir();\n    this.initialized = true;\n  }\n\n  /**\n   * Ensure the storage directory and skills subdirectory exist.\n   */\n  ensureDir(): void {\n    if (!existsSync(this.dir)) {\n      mkdirSync(this.dir, { recursive: true });\n    }\n    const skillsDir = join(this.dir, 'skills');\n    if (!existsSync(skillsDir)) {\n      mkdirSync(skillsDir, { recursive: true });\n    }\n  }\n\n  // ==========================================================================\n  // Domain-level JSON operations\n  // ==========================================================================\n\n  /**\n   * Read a domain JSON file and return its entity map.\n   * Uses in-memory cache; reads from disk on first access.\n   */\n  readDomain<T = Record<string, unknown>>(filename: string): Record<string, T> {\n    if (this.cache.has(filename)) {\n      return this.cache.get(filename) as Record<string, T>;\n    }\n\n    const filePath = join(this.dir, filename);\n    let data: Record<string, T> = {};\n\n    if (existsSync(filePath)) {\n      try {\n        const raw = readFileSync(filePath, 'utf-8');\n        data = JSON.parse(raw, dateReviver) as Record<string, T>;\n      } catch {\n        // If the file is corrupted, start fresh\n        data = {};\n      }\n    }\n\n    this.cache.set(filename, data as Record<string, unknown>);\n    return data;\n  }\n\n  /**\n   * Write a domain's full entity map to its JSON file.\n   * Uses atomic write (write to .tmp, then rename) to prevent corruption.\n   */\n  writeDomain<T = Record<string, unknown>>(filename: string, data: Record<string, T>): void {\n    this.cache.set(filename, data as Record<string, unknown>);\n\n    const filePath = join(this.dir, filename);\n    const tmpPath = filePath + '.tmp';\n\n    // Ensure parent directory exists\n    const parentDir = dirname(filePath);\n    if (!existsSync(parentDir)) {\n      mkdirSync(parentDir, { recursive: true });\n    }\n\n    writeFileSync(tmpPath, JSON.stringify(data, null, 2), 'utf-8');\n    renameSync(tmpPath, filePath);\n  }\n\n  /**\n   * Clear all data from a domain JSON file.\n   */\n  clearDomain(filename: string): void {\n    this.writeDomain(filename, {});\n  }\n\n  listDomainFiles(directory: string, extension = '.json'): string[] {\n    const baseDir = resolve(this.dir, directory);\n    const rootDir = resolve(this.dir);\n    if (!baseDir.startsWith(rootDir + sep) && baseDir !== rootDir) {\n      throw new Error(`Path traversal detected: directory \"${directory}\" escapes storage directory`);\n    }\n    if (!existsSync(baseDir)) return [];\n    if (!statSync(baseDir).isDirectory()) {\n      throw new Error(`Configured domain path \"${directory}\" is a file, expected a directory`);\n    }\n\n    return readdirSync(baseDir)\n      .filter(file => extname(file) === extension && statSync(join(baseDir, file)).isFile())\n      .map(file => `${directory}/${file}`);\n  }\n\n  /**\n   * Check whether a domain file currently exists on disk.\n   */\n  domainFileExists(filename: string): boolean {\n    const filePath = resolve(this.dir, filename);\n    const rootDir = resolve(this.dir);\n    if (!filePath.startsWith(rootDir + sep) && filePath !== rootDir) {\n      throw new Error(`Path traversal detected: file \"${filename}\" escapes storage directory`);\n    }\n    return existsSync(filePath);\n  }\n\n  removeDomainFile(filename: string): void {\n    this.cache.delete(filename);\n    const filePath = resolve(this.dir, filename);\n    const rootDir = resolve(this.dir);\n    if (!filePath.startsWith(rootDir + sep) && filePath !== rootDir) {\n      throw new Error(`Path traversal detected: file \"${filename}\" escapes storage directory`);\n    }\n    if (existsSync(filePath)) {\n      rmSync(filePath);\n    }\n  }\n\n  /**\n   * Invalidate the in-memory cache for a domain, forcing a re-read from disk on next access.\n   */\n  invalidateCache(filename?: string): void {\n    if (filename) {\n      this.cache.delete(filename);\n    } else {\n      this.cache.clear();\n    }\n  }\n\n  // ==========================================================================\n  // Entity-level convenience methods (used by FilesystemVersionedHelpers)\n  // ==========================================================================\n\n  /**\n   * Get a single entity by ID from a domain JSON file.\n   */\n  get<T>(filename: string, id: string): T | null {\n    const data = this.readDomain<T>(filename);\n    return data[id] ?? null;\n  }\n\n  /**\n   * Get all entities from a domain JSON file as an array.\n   */\n  getAll<T>(filename: string): T[] {\n    const data = this.readDomain<T>(filename);\n    return Object.values(data);\n  }\n\n  /**\n   * Set (create or update) an entity in a domain JSON file.\n   */\n  set<T>(filename: string, id: string, entity: T): void {\n    const data = this.readDomain<T>(filename);\n    data[id] = entity;\n    this.writeDomain(filename, data);\n  }\n\n  /**\n   * Remove an entity by ID from a domain JSON file. No-op if not found.\n   */\n  remove(filename: string, id: string): void {\n    const data = this.readDomain(filename);\n    if (id in data) {\n      delete data[id];\n      this.writeDomain(filename, data);\n    }\n  }\n\n  // =========================================================================\n  // Skills directory operations (real file tree, not JSON)\n  // =========================================================================\n\n  /**\n   * Get the path to a skill's directory.\n   */\n  skillDir(skillName: string): string {\n    const skillsBase = join(this.dir, 'skills');\n    const dir = resolve(skillsBase, skillName);\n    if (!dir.startsWith(skillsBase + sep) && dir !== skillsBase) {\n      throw new Error(`Path traversal detected: skill name \"${skillName}\" escapes skills directory`);\n    }\n    return dir;\n  }\n\n  /**\n   * Resolve a file path within a skill directory, throwing if it escapes.\n   */\n  private safeSkillPath(skillName: string, relativePath: string): string {\n    const base = this.skillDir(skillName);\n    const resolved = resolve(base, relativePath);\n    if (!resolved.startsWith(base + sep) && resolved !== base) {\n      throw new Error(`Path traversal detected: \"${relativePath}\" escapes skill directory`);\n    }\n    return resolved;\n  }\n\n  /**\n   * List all files in a skill's directory, returning relative paths.\n   */\n  listSkillFiles(skillName: string): string[] {\n    const dir = this.skillDir(skillName);\n    if (!existsSync(dir)) return [];\n    return walkDir(dir).map(abs => relative(dir, abs).split(sep).join('/'));\n  }\n\n  /**\n   * Read a file from a skill's directory.\n   */\n  readSkillFile(skillName: string, relativePath: string): Buffer | null {\n    const filePath = this.safeSkillPath(skillName, relativePath);\n    if (!existsSync(filePath)) return null;\n    try {\n      return readFileSync(filePath);\n    } catch {\n      return null;\n    }\n  }\n\n  /**\n   * Write a file to a skill's directory.\n   */\n  writeSkillFile(skillName: string, relativePath: string, content: Buffer | string): void {\n    const filePath = this.safeSkillPath(skillName, relativePath);\n    const parentDir = dirname(filePath);\n    if (!existsSync(parentDir)) {\n      mkdirSync(parentDir, { recursive: true });\n    }\n    writeFileSync(filePath, content);\n  }\n\n  /**\n   * Delete a skill's entire directory.\n   */\n  deleteSkillDir(skillName: string): void {\n    const dir = this.skillDir(skillName);\n    if (existsSync(dir)) {\n      rmSync(dir, { recursive: true, force: true });\n    }\n  }\n}\n\n/**\n * JSON reviver that converts ISO date strings back to Date objects.\n */\nfunction dateReviver(_key: string, value: unknown): unknown {\n  if (typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(value)) {\n    const d = new Date(value);\n    if (!isNaN(d.getTime())) return d;\n  }\n  return value;\n}\n\n/**\n * Recursively walk a directory and return all file paths.\n */\nfunction walkDir(dir: string): string[] {\n  const results: string[] = [];\n  for (const entry of readdirSync(dir)) {\n    const fullPath = join(dir, entry);\n    const stat = statSync(fullPath);\n    if (stat.isDirectory()) {\n      results.push(...walkDir(fullPath));\n    } else {\n      results.push(fullPath);\n    }\n  }\n  return results;\n}\n","import { resolve } from 'node:path';\n\nimport { MastraCompositeStore } from './base';\nimport type { StorageDomains } from './base';\nimport { FilesystemAgentsStorage } from './domains/agents/filesystem';\nimport { FilesystemMCPClientsStorage } from './domains/mcp-clients/filesystem';\nimport { FilesystemMCPServersStorage } from './domains/mcp-servers/filesystem';\nimport { FilesystemPromptBlocksStorage } from './domains/prompt-blocks/filesystem';\nimport { FilesystemScorerDefinitionsStorage } from './domains/scorer-definitions/filesystem';\nimport { FilesystemSkillsStorage } from './domains/skills/filesystem';\nimport { FilesystemWorkspacesStorage } from './domains/workspaces/filesystem';\nimport { FilesystemDB } from './filesystem-db';\n\nexport interface FilesystemStoreConfig {\n  /**\n   * Directory to store JSON files in.\n   * Defaults to `.mastra-storage/` relative to `process.cwd()`.\n   */\n  dir?: string;\n}\n\n/**\n * Filesystem-based storage adapter for the Mastra Editor.\n *\n * Stores editor primitives (agents, prompt blocks, scorer definitions,\n * MCP clients, MCP servers, workspaces, skills) as JSON files on disk.\n * This enables Git-based version tracking instead of database-based versioning.\n *\n * Only implements the 7 editor domains — other domains (memory, workflows, scores,\n * observability, datasets, experiments, blobs) are left undefined and should be\n * provided by a separate store via the `editor` shorthand on `MastraCompositeStore`.\n *\n * @example\n * ```typescript\n * import { FilesystemStore, MastraCompositeStore } from '@mastra/core/storage';\n *\n * const storage = new MastraCompositeStore({\n *   id: 'my-storage',\n *   default: postgresStore,\n *   editor: new FilesystemStore({ dir: '.mastra-storage' }),\n * });\n * ```\n */\nexport class FilesystemStore extends MastraCompositeStore {\n  #db: FilesystemDB;\n  #dir: string;\n\n  constructor(config: FilesystemStoreConfig = {}) {\n    const dir = resolve(config.dir ?? '.mastra-storage');\n\n    super({ id: 'filesystem', name: 'FilesystemStore' });\n\n    this.#dir = dir;\n    this.#db = new FilesystemDB(dir);\n\n    // Only editor domains are provided; other domains (workflows, scores, memory, etc.)\n    // should come from a default store when using the `editor` shorthand on MastraCompositeStore.\n    this.stores = {\n      agents: new FilesystemAgentsStorage({ db: this.#db }),\n      promptBlocks: new FilesystemPromptBlocksStorage({ db: this.#db }),\n      scorerDefinitions: new FilesystemScorerDefinitionsStorage({ db: this.#db }),\n      mcpClients: new FilesystemMCPClientsStorage({ db: this.#db }),\n      mcpServers: new FilesystemMCPServersStorage({ db: this.#db }),\n      workspaces: new FilesystemWorkspacesStorage({ db: this.#db }),\n      skills: new FilesystemSkillsStorage({ db: this.#db }),\n    } as unknown as StorageDomains;\n  }\n\n  /**\n   * The absolute path to the storage directory.\n   */\n  get dir(): string {\n    return this.#dir;\n  }\n}\n","import type {\n  SourceChangeRequestInput,\n  SourceChangeRequestResult,\n  SourceFile,\n  SourceFileHistoryEntry,\n  SourceFileHistoryInput,\n  SourceFileListEntry,\n  SourceFileListInput,\n  SourceFileRef,\n  SourceControlCapabilities,\n  SourceControlProvider,\n  SourceWriteFileInput,\n  SourceWriteResult,\n} from '../source-control';\n\nexport type GitHubSourceControlProviderConfig = {\n  endpoint: string;\n  token: string;\n  pathPrefix?: string;\n  fetch?: typeof fetch;\n};\n\ntype BrokerErrorResponse = {\n  type?: string;\n  detail?: string;\n};\n\nexport class GitHubSourceControlProvider implements SourceControlProvider {\n  readonly id = 'github';\n  readonly displayName = 'GitHub';\n\n  private readonly endpoint: string;\n  private readonly token: string;\n  private readonly pathPrefix: string;\n  private readonly fetch: typeof fetch;\n\n  constructor(config: GitHubSourceControlProviderConfig) {\n    this.endpoint = normalizeApiEndpoint(config.endpoint);\n    this.token = config.token;\n    this.pathPrefix = normalizePathPrefix(config.pathPrefix ?? 'mastra/editor');\n    this.fetch = config.fetch ?? fetch;\n  }\n\n  async getCapabilities(): Promise<SourceControlCapabilities> {\n    return this.request<SourceControlCapabilities>('/capabilities');\n  }\n\n  async readFile(input: SourceFileRef): Promise<SourceFile | null> {\n    const path = this.sourcePath(input.path);\n    const query = new URLSearchParams({ path });\n    if (input.ref) query.set('ref', input.ref);\n\n    const result = await this.request<SourceFile | null>(`/files?${query.toString()}`);\n    return result ? { ...result, path: input.path } : null;\n  }\n\n  async writeFile(input: SourceWriteFileInput): Promise<SourceWriteResult> {\n    const result = await this.request<SourceWriteResult>('/files', {\n      method: 'POST',\n      body: JSON.stringify({ ...input, path: this.sourcePath(input.path) }),\n    });\n\n    return { ...result, path: input.path };\n  }\n\n  async listFileHistory(input: SourceFileHistoryInput): Promise<SourceFileHistoryEntry[]> {\n    const query = new URLSearchParams({ path: this.sourcePath(input.path) });\n    if (input.ref) query.set('ref', input.ref);\n    if (input.limit) query.set('limit', String(input.limit));\n\n    return this.request<SourceFileHistoryEntry[]>(`/files/history?${query.toString()}`);\n  }\n\n  async listFiles(input: SourceFileListInput): Promise<SourceFileListEntry[]> {\n    const query = new URLSearchParams({ path: this.sourcePath(input.path) });\n    if (input.ref) query.set('ref', input.ref);\n\n    const files = await this.request<SourceFileListEntry[]>(`/files/list?${query.toString()}`);\n    return files.map(file => ({ ...file, path: this.unsourcePath(file.path) }));\n  }\n\n  async openChangeRequest(input: SourceChangeRequestInput): Promise<SourceChangeRequestResult> {\n    return this.request<SourceChangeRequestResult>('/change-requests', {\n      method: 'POST',\n      body: JSON.stringify({\n        ...input,\n        files: input.files.map(file => ({ ...file, path: this.sourcePath(file.path) })),\n      }),\n    });\n  }\n\n  private sourcePath(path: string): string {\n    const normalizedPath = stripLeadingSlashes(path);\n    return this.pathPrefix ? `${this.pathPrefix}/${normalizedPath}` : normalizedPath;\n  }\n\n  private unsourcePath(path: string): string {\n    const normalizedPath = stripLeadingSlashes(path);\n    const prefix = this.pathPrefix ? `${this.pathPrefix}/` : '';\n    return prefix && normalizedPath.startsWith(prefix) ? normalizedPath.slice(prefix.length) : normalizedPath;\n  }\n\n  private async request<T>(path: string, init?: RequestInit): Promise<T> {\n    const res = await this.fetch(`${this.endpoint}/v1/server/source-storage/github${path}`, {\n      ...init,\n      headers: {\n        Authorization: `Bearer ${this.token}`,\n        Accept: 'application/json',\n        'Content-Type': 'application/json',\n        ...init?.headers,\n      },\n    });\n\n    if (!res.ok) {\n      let detail = `GitHub source control request failed: ${res.status}`;\n      try {\n        const body = (await res.json()) as BrokerErrorResponse;\n        detail = body.detail ?? detail;\n      } catch {\n        // Ignore non-JSON error bodies.\n      }\n      throw new Error(detail);\n    }\n\n    return (await res.json()) as T;\n  }\n}\n\nexport function createGitHubSourceControlProviderFromEnv(\n  env: Record<string, string | undefined> = process.env,\n  defaults?: { pathPrefix?: string },\n): GitHubSourceControlProvider | undefined {\n  if (env.MASTRA_SOURCE_PROVIDER !== 'github') return undefined;\n\n  const endpoint = env.MASTRA_SOURCE_PROVIDER_ENDPOINT ?? env.MASTRA_SHARED_API_URL ?? env.MASTRA_CLOUD_API_ENDPOINT;\n  const token = env.MASTRA_PLATFORM_ACCESS_TOKEN ?? env.MASTRA_CLOUD_ACCESS_TOKEN;\n\n  if (!endpoint || !token) return undefined;\n\n  return new GitHubSourceControlProvider({\n    endpoint: normalizeApiEndpoint(endpoint),\n    token,\n    pathPrefix: env.MASTRA_SOURCE_STORAGE_PATH_PREFIX ?? defaults?.pathPrefix,\n  });\n}\n\nfunction normalizeApiEndpoint(endpoint: string): string {\n  const trimmed = stripTrailingSlashes(endpoint);\n  const withoutV1 = trimmed.endsWith('/v1') ? trimmed.slice(0, -3) : trimmed;\n  return stripTrailingSlashes(withoutV1);\n}\n\nfunction normalizePathPrefix(pathPrefix: string): string {\n  return stripTrailingSlashes(stripLeadingSlashes(pathPrefix));\n}\n\nfunction stripLeadingSlashes(value: string): string {\n  let start = 0;\n  while (start < value.length && value[start] === '/') start += 1;\n  return value.slice(start);\n}\n\nfunction stripTrailingSlashes(value: string): string {\n  let end = value.length;\n  while (end > 0 && value[end - 1] === '/') end -= 1;\n  return value.slice(0, end);\n}\n","import { MastraBase } from '../../../base';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\nimport type { TABLE_NAMES } from '../../constants';\nimport type { StorageColumn, CreateIndexOptions, IndexInfo, StorageIndexStats } from '../../types';\n\nexport abstract class StoreOperations extends MastraBase {\n  constructor() {\n    super({\n      component: 'STORAGE',\n      name: 'OPERATIONS',\n    });\n  }\n\n  abstract hasColumn(table: string, column: string): Promise<boolean>;\n\n  protected getSqlType(type: StorageColumn['type']): string {\n    switch (type) {\n      case 'text':\n        return 'TEXT';\n      case 'timestamp':\n        return 'TIMESTAMP';\n      case 'float':\n        return 'FLOAT';\n      case 'integer':\n        return 'INTEGER';\n      case 'bigint':\n        return 'BIGINT';\n      case 'jsonb':\n        return 'JSONB';\n      default:\n        return 'TEXT';\n    }\n  }\n\n  protected getDefaultValue(type: StorageColumn['type']): string {\n    switch (type) {\n      case 'text':\n      case 'uuid':\n        return \"DEFAULT ''\";\n      case 'timestamp':\n        return \"DEFAULT '1970-01-01 00:00:00'\";\n      case 'integer':\n      case 'bigint':\n      case 'float':\n        return 'DEFAULT 0';\n      case 'jsonb':\n        return \"DEFAULT '{}'\";\n      default:\n        return \"DEFAULT ''\";\n    }\n  }\n\n  abstract createTable({ tableName }: { tableName: TABLE_NAMES; schema: Record<string, StorageColumn> }): Promise<void>;\n\n  abstract clearTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void>;\n\n  abstract dropTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void>;\n\n  abstract alterTable(args: {\n    tableName: TABLE_NAMES;\n    schema: Record<string, StorageColumn>;\n    ifNotExists: string[];\n  }): Promise<void>;\n\n  abstract insert({ tableName, record }: { tableName: TABLE_NAMES; record: Record<string, any> }): Promise<void>;\n\n  abstract batchInsert({\n    tableName,\n    records,\n  }: {\n    tableName: TABLE_NAMES;\n    records: Record<string, any>[];\n  }): Promise<void>;\n\n  abstract load<R>({ tableName, keys }: { tableName: TABLE_NAMES; keys: Record<string, any> }): Promise<R | null>;\n\n  /**\n   * DATABASE INDEX MANAGEMENT\n   * Optional methods for database index management.\n   * Storage adapters can override these to provide index management capabilities.\n   */\n\n  /**\n   * Creates a database index on specified columns\n   * @throws {MastraError} if not supported by the storage adapter\n   */\n  async createIndex(_options: CreateIndexOptions): Promise<void> {\n    throw new MastraError({\n      id: 'MASTRA_STORAGE_CREATE_INDEX_NOT_SUPPORTED',\n      domain: ErrorDomain.STORAGE,\n      category: ErrorCategory.SYSTEM,\n      text: `Index management is not supported by this storage adapter`,\n    });\n  }\n\n  /**\n   * Drops a database index by name\n   * @throws {MastraError} if not supported by the storage adapter\n   */\n  async dropIndex(_indexName: string): Promise<void> {\n    throw new MastraError({\n      id: 'MASTRA_STORAGE_DROP_INDEX_NOT_SUPPORTED',\n      domain: ErrorDomain.STORAGE,\n      category: ErrorCategory.SYSTEM,\n      text: `Index management is not supported by this storage adapter`,\n    });\n  }\n\n  /**\n   * Lists database indexes for a table or all tables\n   * @throws {MastraError} if not supported by the storage adapter\n   */\n  async listIndexes(_tableName?: string): Promise<IndexInfo[]> {\n    throw new MastraError({\n      id: 'MASTRA_STORAGE_LIST_INDEXES_NOT_SUPPORTED',\n      domain: ErrorDomain.STORAGE,\n      category: ErrorCategory.SYSTEM,\n      text: `Index management is not supported by this storage adapter`,\n    });\n  }\n\n  /**\n   * Gets detailed statistics for a specific index\n   * @throws {MastraError} if not supported by the storage adapter\n   */\n  async describeIndex(_indexName: string): Promise<StorageIndexStats> {\n    throw new MastraError({\n      id: 'MASTRA_STORAGE_DESCRIBE_INDEX_NOT_SUPPORTED',\n      domain: ErrorDomain.STORAGE,\n      category: ErrorCategory.SYSTEM,\n      text: `Index management is not supported by this storage adapter`,\n    });\n  }\n\n  /**\n   * Returns definitions for automatic performance indexes\n   * Storage adapters can override this to define indexes that should be created during initialization\n   * @returns Array of index definitions to create automatically\n   */\n  protected getAutomaticIndexDefinitions(): CreateIndexOptions[] {\n    return [];\n  }\n}\n","import { TABLE_NOTIFICATIONS, TABLE_WORKFLOW_SNAPSHOT } from '../../constants';\nimport type { TABLE_NAMES, TABLE_OBSERVATIONAL_MEMORY } from '../../constants';\nimport type { StorageColumn } from '../../types';\nimport { StoreOperations } from './base';\n\n// InMemory storage supports all tables including observational memory\ntype InMemoryTableNames = TABLE_NAMES | typeof TABLE_OBSERVATIONAL_MEMORY;\n\nexport class StoreOperationsInMemory extends StoreOperations {\n  data: Record<InMemoryTableNames, Map<string, Record<string, any>>>;\n\n  constructor() {\n    super();\n    this.data = {\n      mastra_workflow_snapshot: new Map(),\n      mastra_messages: new Map(),\n      mastra_threads: new Map(),\n      mastra_traces: new Map(),\n      mastra_resources: new Map(),\n      mastra_scorers: new Map(),\n      mastra_ai_spans: new Map(),\n      mastra_agents: new Map(),\n      mastra_agent_versions: new Map(),\n      mastra_observational_memory: new Map(),\n      mastra_prompt_blocks: new Map(),\n      mastra_prompt_block_versions: new Map(),\n      mastra_scorer_definitions: new Map(),\n      mastra_scorer_definition_versions: new Map(),\n      mastra_mcp_clients: new Map(),\n      mastra_mcp_client_versions: new Map(),\n      mastra_mcp_servers: new Map(),\n      mastra_mcp_server_versions: new Map(),\n      mastra_workspaces: new Map(),\n      mastra_workspace_versions: new Map(),\n      mastra_skills: new Map(),\n      mastra_skill_versions: new Map(),\n      mastra_skill_blobs: new Map(),\n      mastra_datasets: new Map(),\n      mastra_dataset_items: new Map(),\n      mastra_dataset_versions: new Map(),\n      mastra_experiments: new Map(),\n      mastra_experiment_results: new Map(),\n      mastra_background_tasks: new Map(),\n      mastra_favorites: new Map(),\n      mastra_schedules: new Map(),\n      mastra_schedule_triggers: new Map(),\n      mastra_channel_installations: new Map(),\n      mastra_channel_config: new Map(),\n      mastra_tool_provider_connections: new Map(),\n      mastra_notifications: new Map(),\n      mastra_harness_sessions: new Map(),\n      mastra_thread_state: new Map(),\n      mastra_workflow_definitions: new Map(),\n    };\n  }\n\n  getDatabase() {\n    return this.data;\n  }\n\n  async insert({ tableName, record }: { tableName: TABLE_NAMES; record: Record<string, any> }): Promise<void> {\n    const table = this.data[tableName];\n    let key = record.id;\n    if (tableName === TABLE_NOTIFICATIONS && record.threadId && record.id) {\n      key = `${record.threadId}\\0${record.id}`;\n    } else if ([TABLE_WORKFLOW_SNAPSHOT].includes(tableName) && !record.id && record.run_id) {\n      key = record.workflow_name ? `${record.workflow_name}-${record.run_id}` : record.run_id;\n      record.id = key;\n    } else if (!record.id) {\n      key = `auto-${Date.now()}-${Math.random()}`;\n      record.id = key;\n    }\n    table.set(key, record);\n  }\n\n  async batchInsert({ tableName, records }: { tableName: TABLE_NAMES; records: Record<string, any>[] }): Promise<void> {\n    const table = this.data[tableName];\n    for (const record of records) {\n      let key = record.id;\n      if (tableName === TABLE_NOTIFICATIONS && record.threadId && record.id) {\n        key = `${record.threadId}\\0${record.id}`;\n      } else if ([TABLE_WORKFLOW_SNAPSHOT].includes(tableName) && !record.id && record.run_id) {\n        key = record.run_id;\n        record.id = key;\n      } else if (!record.id) {\n        key = `auto-${Date.now()}-${Math.random()}`;\n        record.id = key;\n      }\n      table.set(key, record);\n    }\n  }\n\n  async load<R>({ tableName, keys }: { tableName: TABLE_NAMES; keys: Record<string, string> }): Promise<R | null> {\n    const table = this.data[tableName];\n\n    const records = Array.from(table.values());\n\n    return records.filter(record => Object.keys(keys).every(key => record[key] === keys[key]))?.[0] as R | null;\n  }\n\n  async createTable({\n    tableName,\n    schema: _schema,\n  }: {\n    tableName: TABLE_NAMES;\n    schema: Record<string, StorageColumn>;\n  }): Promise<void> {\n    this.data[tableName] = new Map();\n  }\n\n  async clearTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {\n    this.data[tableName].clear();\n  }\n\n  async dropTable({ tableName }: { tableName: TABLE_NAMES }): Promise<void> {\n    this.data[tableName].clear();\n  }\n\n  async alterTable({\n    tableName: _tableName,\n    schema: _schema,\n  }: {\n    tableName: TABLE_NAMES;\n    schema: Record<string, StorageColumn>;\n    ifNotExists: string[];\n  }): Promise<void> {}\n\n  async hasColumn(_table: string, _column: string): Promise<boolean> {\n    return true;\n  }\n}\n"],"x_google_ignoreList":[13],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJA,IAAa,uBAAb,cAA0C,MAAM;CAC9C;CAEA,YAAY,YAAoB,SAA+B;EAC7D,MAAM,8CAA8C,WAAW,IAAI,OAAO;EAC1E,KAAK,OAAO;EACZ,KAAK,aAAa;CACpB;AACF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