@mastra/pg 1.19.0-alpha.1 → 1.19.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,88 @@
1
1
  # @mastra/pg
2
2
 
3
+ ## 1.19.0-alpha.3
4
+
5
+ ### Minor Changes
6
+
7
+ - Added batch trace ID filtering to observability metric queries. ([#20535](https://github.com/mastra-ai/mastra/pull/20535))
8
+
9
+ ```ts
10
+ const result = await observability.getMetricBreakdown({
11
+ name: ['mastra_model_total_input_tokens'],
12
+ aggregation: 'sum',
13
+ groupBy: ['traceId'],
14
+ filters: { traceIds: ['trace-1', 'trace-2'] },
15
+ });
16
+ ```
17
+
18
+ ### Patch Changes
19
+
20
+ - Dataset item scorer selections now persist across PostgreSQL writes and reads. Setting `scorerIds` to `null` clears an item override, while `[]` remains an explicit override with no scorers. ([#20191](https://github.com/mastra-ai/mastra/pull/20191))
21
+
22
+ ```typescript
23
+ await dataset.addItem({
24
+ input: 'Evaluate this response',
25
+ scorerIds: [],
26
+ });
27
+ ```
28
+
29
+ - Fixed nine storage adapters declaring a `@mastra/core` peer range that permitted core versions too old to load them. Each adapter imports `storageMessageMatchesMetadataFilter` from `@mastra/core/storage`, which core only exports from 1.53.0, but every one of them still advertised a floor below that — as low as `>=1.0.0-0`. Package managers accepted the incompatible pair without a warning and the install then failed at import time: ([#20591](https://github.com/mastra-ai/mastra/pull/20591))
30
+
31
+ ```
32
+ SyntaxError: The requested module '@mastra/core/storage' does not provide an export named 'storageMessageMatchesMetadataFilter'
33
+ ```
34
+
35
+ All nine now declare `>=1.53.0-0 <2.0.0-0`, so npm and pnpm surface a peer conflict at install time instead of letting the project break on first import.
36
+
37
+ Fixes [#20586](https://github.com/mastra-ai/mastra/issues/20586).
38
+
39
+ - Updated dependencies [[`82201f7`](https://github.com/mastra-ai/mastra/commit/82201f75fae8e050a8de2df08b74875ee74c6b83), [`fb18da5`](https://github.com/mastra-ai/mastra/commit/fb18da56fc35689ae370621a8f10b5b0d8606e20), [`fb18da5`](https://github.com/mastra-ai/mastra/commit/fb18da56fc35689ae370621a8f10b5b0d8606e20), [`0a6598b`](https://github.com/mastra-ai/mastra/commit/0a6598bde80bde008986ad6616bed9632b9294cb), [`9e1dad8`](https://github.com/mastra-ai/mastra/commit/9e1dad8f7b1cab2bb7ade90e5b7561f24577b88a), [`2f43145`](https://github.com/mastra-ai/mastra/commit/2f4314504c03cbba280414ac81ba3197448ee6b0), [`34d34d8`](https://github.com/mastra-ai/mastra/commit/34d34d8c811df512fef4dd5459f79b7821be1866)]:
40
+ - @mastra/core@1.56.0-alpha.6
41
+
42
+ ## 1.19.0-alpha.2
43
+
44
+ ### Minor Changes
45
+
46
+ - Stored workflow definitions now persist across restarts on every major database backend. ([#20471](https://github.com/mastra-ai/mastra/pull/20471))
47
+
48
+ Implement the `workflowDefinitions` storage domain for libsql, pg, mysql, mssql, mongodb, and spanner. Previously the stored-workflow persistence path (`POST /stored/workflows`, `Mastra.addStoredWorkflow`) only worked against `@mastra/core`'s in-memory store. Persistent adapters returned `undefined` from `storage.getStore('workflowDefinitions')` and threw when the HTTP handler tried to read/write a workflow.
49
+
50
+ ```ts
51
+ const workflowDefinitions = await storage.getStore('workflowDefinitions');
52
+ if (!workflowDefinitions) {
53
+ throw new Error('This storage adapter does not support the workflowDefinitions domain');
54
+ }
55
+
56
+ await workflowDefinitions.upsert({
57
+ id: 'greeting-workflow',
58
+ inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
59
+ outputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
60
+ graph: [{ type: 'agent', id: 'greet', agentId: 'greeter-agent' }],
61
+ });
62
+
63
+ const { definitions, total } = await workflowDefinitions.list({ status: 'active' });
64
+ const definition = await workflowDefinitions.get('greeting-workflow');
65
+ await workflowDefinitions.delete('greeting-workflow');
66
+ ```
67
+
68
+ Each adapter now ships a `WorkflowDefinitions*` domain that:
69
+
70
+ - Creates the shared `mastra_workflow_definitions` table (or Mongo collection) from `WORKFLOW_DEFINITIONS_SCHEMA` during `init()`, plus a default index on `status`.
71
+ - Implements `upsert` / `get` / `list` / `delete` matching `WorkflowDefinitionsStorage` semantics (`list` supports `status` and `authorId` filters and orders by `updatedAt` desc). Partial upserts preserve unspecified fields, including `authorId` updates and `createdAt` / `updatedAt` semantics.
72
+ - Handles concurrent first-writes race-safely: if two callers upsert the same new id simultaneously, the losing insert detects the duplicate key, re-reads the row, and applies the partial-update path instead of failing.
73
+ - Round-trips the JSON columns (`inputSchema`, `outputSchema`, `stateSchema`, `requestContextSchema`, `metadata`, `graph`) through each adapter's JSON handling, so declarative workflow graphs rehydrate identically no matter which backend they were stored in. Malformed persisted JSON surfaces as an actionable error naming the row and column instead of hydrating raw strings.
74
+
75
+ Exported class names by adapter: `WorkflowDefinitionsLibSQL`, `WorkflowDefinitionsPG`, `WorkflowDefinitionsMySQL`, `WorkflowDefinitionsMSSQL`, `MongoDBWorkflowDefinitionsStore`, `WorkflowDefinitionsSpanner`. The composite stores (`LibSQLStore`, `PostgresStore`, `MySQLStore`, `MSSQLStore`, `MongoDBStore`, `SpannerStore`) auto-wire the new domain, so callers do not need to construct it manually — `storage.getStore('workflowDefinitions')` now returns a live handle.
76
+
77
+ The pg adapter reads `createdAt` / `updatedAt` from the auto-added `createdAtZ` / `updatedAtZ` `timestamptz` companion columns to avoid the naive-timestamp / local-TZ drift that a plain `TIMESTAMP` read exhibits under node-pg.
78
+
79
+ `@mastra/clickhouse` and `@mastra/cloudflare` register the new `mastra_workflow_definitions` table in their table/type maps so shared table constants stay exhaustive (no workflow-definitions domain implementation yet).
80
+
81
+ ### Patch Changes
82
+
83
+ - Updated dependencies [[`4844167`](https://github.com/mastra-ai/mastra/commit/4844167cff2d5ec5004e94edd34970833040fa3f), [`5faf93f`](https://github.com/mastra-ai/mastra/commit/5faf93f03e19daea394b9e2a923f2e4f833407f2), [`80ad891`](https://github.com/mastra-ai/mastra/commit/80ad891f8cd10379aa5b5af7510c763783b2ab56), [`a1cb98d`](https://github.com/mastra-ai/mastra/commit/a1cb98d11990b560b98482292a1f34aa1a2d9092), [`598ad82`](https://github.com/mastra-ai/mastra/commit/598ad82d41c41389a686338a1d0e50b7400e1938), [`1fd6aad`](https://github.com/mastra-ai/mastra/commit/1fd6aad1ea4a9d32f65efa832307c35e981a4c0a)]:
84
+ - @mastra/core@1.56.0-alpha.4
85
+
3
86
  ## 1.19.0-alpha.1
4
87
 
5
88
  ### Patch Changes
@@ -3,7 +3,7 @@ name: mastra-pg
3
3
  description: Documentation for @mastra/pg. Use when working with @mastra/pg APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/pg"
6
- version: "1.19.0-alpha.1"
6
+ version: "1.19.0-alpha.3"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -19,11 +19,14 @@ Read the individual reference documents for detailed explanations and code examp
19
19
  - [Workers](references/docs-deployment-workers.md) - Separate background processing from the API layer by running workflow execution, cron schedules, and background tasks in dedicated worker processes.
20
20
  - [Semantic recall](references/docs-memory-semantic-recall.md) - Learn how to use semantic recall in Mastra to retrieve relevant messages from past conversations using vector search and embeddings.
21
21
  - [Working memory](references/docs-memory-working-memory.md) - Learn how to configure working memory in Mastra to store persistent user data, preferences.
22
- - [RAG (Retrieval-Augmented Generation) in Mastra](references/docs-rag-overview.md) - Overview of Retrieval-Augmented Generation (RAG) in Mastra, detailing its capabilities for enhancing LLM outputs with relevant context.
23
- - [Retrieval, semantic search, reranking](references/docs-rag-retrieval.md) - Guide on retrieval processes in Mastra's RAG systems, including semantic search, filtering, and re-ranking.
24
- - [Storing embeddings in a vector database](references/docs-rag-vector-databases.md) - Guide on vector storage options in Mastra, including embedded and dedicated vector databases for similarity search.
25
22
  - [Storage overview](references/docs-storage-overview.md) - Configure storage for Mastra to persist runtime state across agents, workflows, observability, evals, schedules, and memory.
26
23
 
24
+ ### Guides
25
+
26
+ - [RAG (Retrieval-Augmented Generation) in Mastra](references/guides-rag-overview.md) - Overview of Retrieval-Augmented Generation (RAG) in Mastra, detailing its capabilities for enhancing LLM outputs with relevant context.
27
+ - [Retrieval, semantic search, reranking](references/guides-rag-retrieval.md) - Guide on retrieval processes in Mastra's RAG systems, including semantic search, filtering, and re-ranking.
28
+ - [Storing embeddings in a vector database](references/guides-rag-vector-databases.md) - Guide on vector storage options in Mastra, including embedded and dedicated vector databases for similarity search.
29
+
27
30
  ### Reference
28
31
 
29
32
  - [Reference: Memory class](references/reference-memory-memory-class.md) - Documentation for the `Memory` class in Mastra, which provides a reliable system for managing conversation history and thread-based message storage.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.19.0-alpha.1",
2
+ "version": "1.19.0-alpha.3",
3
3
  "package": "@mastra/pg",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -17,7 +17,7 @@ Workers matter when any of these apply:
17
17
  - Different parts of the system need to scale independently (e.g., more orchestration capacity without more API instances)
18
18
  - Background tool calls should run on dedicated compute
19
19
 
20
- If your application handles light traffic and workflows complete quickly, the default in-process setup works fine. Skip the worker infrastructure until you need it.
20
+ If your application handles light traffic and workflows complete fast, the default in-process setup works fine. Skip the worker infrastructure until you need it.
21
21
 
22
22
  ## Worker types
23
23
 
@@ -33,11 +33,11 @@ The orchestration worker requires a PubSub backend that supports pull mode (e.g.
33
33
 
34
34
  ### Scheduler worker
35
35
 
36
- Polls storage for due cron schedules and publishes `workflow.start` events. It is a producer only, meaning it creates work for the orchestration worker to pick up.
36
+ Polls storage for due cron schedules and publishes `workflow.start` events. It's a producer only, meaning it creates work for the orchestration worker to pick up.
37
37
 
38
38
  The scheduler reads declarative `schedule` fields from your workflow definitions automatically. See [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows) for how to declare schedules.
39
39
 
40
- **Do not run more than one scheduler instance.** Multiple schedulers polling the same storage would fire duplicate events for the same schedule.
40
+ **Don't run more than one scheduler instance.** Multiple schedulers polling the same storage would fire duplicate events for the same schedule.
41
41
 
42
42
  ### Background task worker
43
43
 
@@ -47,7 +47,7 @@ The background task worker manages concurrency limits, task lifecycle, and resul
47
47
 
48
48
  ## How workers run
49
49
 
50
- ### In-process (default)
50
+ ### In-process mode (default)
51
51
 
52
52
  With no configuration, Mastra creates and starts workers inside the API process. Events flow through an in-memory PubSub, and everything shares a single Node.js runtime.
53
53
 
@@ -64,7 +64,7 @@ This setup needs no external infrastructure beyond your storage adapter. It does
64
64
 
65
65
  ### Split processes
66
66
 
67
- To run workers separately, configure a distributed [PubSub](https://mastra.ai/docs/server/pubsub) backend and use the `MASTRA_WORKERS` environment variable to control which workers start in each process.
67
+ To run workers in their own processes, configure a distributed [PubSub](https://mastra.ai/docs/server/pubsub) backend and use the `MASTRA_WORKERS` environment variable to control which workers start in each process.
68
68
 
69
69
  **Redis Streams + PostgreSQL**:
70
70
 
@@ -100,38 +100,38 @@ export const mastra = new Mastra({
100
100
  })
101
101
  ```
102
102
 
103
- Any [supported storage backend](https://mastra.ai/reference/workers/overview) works swap the storage adapter for your preferred database.
103
+ Any [supported storage backend](https://mastra.ai/reference/workers/overview) works. Swap the storage adapter for your preferred database.
104
104
 
105
105
  Run the same build artifact in multiple containers, each with a different [`MASTRA_WORKERS`](https://mastra.ai/reference/workers/overview) value to control which worker starts in each process.
106
106
 
107
107
  Split deployments require a distributed PubSub backend ([`RedisStreamsPubSub`](https://mastra.ai/reference/pubsub/redis-streams) or [`GoogleCloudPubSub`](https://mastra.ai/reference/pubsub/google-cloud-pubsub)), a shared [storage backend](https://mastra.ai/reference/workers/overview), and network connectivity between the orchestration worker and the API.
108
108
 
109
- The [worker deployment guide](https://mastra.ai/guides/deployment/mastra-workers) walks through this setup with a Docker Compose example.
109
+ The [worker deployment guide](https://mastra.ai/guides/deployment/mastra-workers) walks through this setup with Docker Compose and Kubernetes examples.
110
110
 
111
111
  ## Network architecture
112
112
 
113
- Workers are internal infrastructure. They are not exposed to end users and do not need their own subdomain, public URL, or inbound HTTP route.
113
+ Workers are internal infrastructure. They're not exposed to end users and don't need their own subdomain, public URL, or inbound HTTP route.
114
114
 
115
115
  In a split deployment:
116
116
 
117
- - **The API server is the only public-facing process.** It serves all client HTTP requests REST endpoints, agent interactions, workflow triggers, and any custom routes.
118
- - **Workers connect outbound only.** They pull events from the distributed PubSub backend and read/write to the shared storage database. They do not accept inbound traffic from clients.
119
- - **The orchestration worker calls the API internally.** It sends step execution requests to the API over the container network using `MASTRA_STEP_EXECUTION_URL`. This is internal service-to-service communication, not a public endpoint.
117
+ - **The API server is the only public-facing process**: It serves all client HTTP requests, including REST endpoints, agent interactions, workflow triggers, and any custom routes.
118
+ - **Workers connect outbound only**: They pull events from the distributed PubSub backend and read/write to the shared storage database. They don't accept inbound traffic from clients.
119
+ - **The orchestration worker calls the API internally**: It sends step execution requests to the API over the container network using `MASTRA_STEP_EXECUTION_URL`. This is internal service-to-service communication, not a public endpoint.
120
120
 
121
121
  All three worker types (orchestration, scheduler, background task) sit behind the API on a private network. They share access to the PubSub backend and storage database but never receive traffic directly from clients. If a worker-related feature needs an HTTP route (for example, token minting for a voice integration), that route runs on the API server, not on the worker process.
122
122
 
123
123
  ## Known limitations
124
124
 
125
- - **No dead-letter queue**: Failed events are nacked and retried, but there is no DLQ for events that repeatedly fail.
125
+ - **No dead-letter queue**: Failed events are nacked and retried, but there's no DLQ for events that fail after all retries.
126
126
  - **No built-in health endpoint**: Workers don't expose an HTTP health check. Use container-level liveness probes or process monitoring.
127
127
  - **Scheduler is single-instance**: Running multiple scheduler processes causes duplicate schedule fires.
128
128
  - **Runs stuck in "running" after API crash**: If the API process crashes while executing a workflow step, the run remains in `running` status with no automatic retry. For [durable agents](https://mastra.ai/docs/long-running-agents/durable-agents), set `recovery.durableAgents` to `'auto'` in the Mastra config to automatically re-drive orphaned runs on server restart. See [Crash recovery](https://mastra.ai/docs/long-running-agents/durable-agents) for details.
129
129
 
130
130
  ## Related
131
131
 
132
- - [Worker deployment guide](https://mastra.ai/guides/deployment/mastra-workers): Docker Compose example and topology options
132
+ - [Worker deployment guide](https://mastra.ai/guides/deployment/mastra-workers): Docker Compose and Kubernetes examples
133
133
  - [Worker authentication](https://mastra.ai/docs/server/auth/workers): Secure worker-to-API communication
134
- - [Workers reference](https://mastra.ai/reference/workers/overview): Environment variables, worker types, and storage backends
134
+ - [Workers reference](https://mastra.ai/reference/workers/overview): Details about worker environment variables and types, with a list of supported storage backends
135
135
  - [CLI reference](https://mastra.ai/reference/cli/mastra): `mastra worker build` and `mastra worker start`
136
136
  - [PubSub](https://mastra.ai/docs/server/pubsub): Event delivery backends
137
137
  - [Scheduled workflows](https://mastra.ai/docs/workflows/scheduled-workflows): Declare cron schedules on workflows
@@ -63,11 +63,11 @@ This example shows the essentials. Initialize a document and create chunks, then
63
63
 
64
64
  ## Document processing
65
65
 
66
- The basic building block of RAG is document processing. Documents can be chunked using strategies (recursive, sliding window, etc.) and enriched with metadata. See the [chunking and embedding doc](https://mastra.ai/docs/rag/chunking-and-embedding).
66
+ The basic building block of RAG is document processing. Documents can be chunked using strategies (recursive, sliding window, etc.) and enriched with metadata. See the [chunking and embedding doc](https://mastra.ai/guides/rag/chunking-and-embedding).
67
67
 
68
68
  ## Vector storage
69
69
 
70
- Mastra supports multiple vector stores for embedding persistence and similarity search, including pgvector, Pinecone, Qdrant, and MongoDB. See the [vector database doc](https://mastra.ai/docs/rag/vector-databases).
70
+ Mastra supports multiple vector stores for embedding persistence and similarity search, including pgvector, Pinecone, Qdrant, and MongoDB. See the [vector database doc](https://mastra.ai/guides/rag/vector-databases).
71
71
 
72
72
  ## More resources
73
73
 
@@ -517,4 +517,4 @@ The re-ranked results combine vector similarity with semantic understanding to i
517
517
 
518
518
  For more details about re-ranking, see the [rerank()](https://mastra.ai/reference/rag/rerankWithScorer) method.
519
519
 
520
- For graph-based retrieval that follows connections between chunks, see the [GraphRAG](https://mastra.ai/docs/rag/graph-rag) documentation.
520
+ For graph-based retrieval that follows connections between chunks, see the [GraphRAG](https://mastra.ai/guides/rag/graph-rag) documentation.
@@ -188,6 +188,8 @@ export const mastra = new Mastra({
188
188
 
189
189
  **default** (`MastraCompositeStore`): Default storage adapter. Domains not explicitly specified in domains will use this storage's domains as fallbacks.
190
190
 
191
+ **editor** (`MastraCompositeStore`): Storage adapter for Editor-owned domains, including agents, prompt blocks, scorers, MCP clients and servers, workspaces, and skills. Takes precedence over default storage but not explicit domain overrides.
192
+
191
193
  **disableInit** (`boolean`): When true, automatic initialization is disabled. You must call init() explicitly.
192
194
 
193
195
  **domains** (`object`): Individual domain overrides. Each domain can come from a different storage adapter. These take precedence over both editor and default storage. Set a domain to false to disable it entirely; a disabled domain does not fall back to editor or default.
package/dist/index.cjs CHANGED
@@ -5299,6 +5299,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5299
5299
  await this.#addColumnIfNotExists(_mastra_core_storage.TABLE_DATASET_ITEMS, "projectId", "TEXT");
5300
5300
  await this.#addColumnIfNotExists(_mastra_core_storage.TABLE_DATASET_ITEMS, "toolMocks", "JSONB");
5301
5301
  await this.#addColumnIfNotExists(_mastra_core_storage.TABLE_DATASET_ITEMS, "unmockedToolPolicy", "TEXT");
5302
+ await this.#addColumnIfNotExists(_mastra_core_storage.TABLE_DATASET_ITEMS, "scorerIds", "JSONB");
5302
5303
  await this.#addColumnIfNotExists(_mastra_core_storage.TABLE_DATASET_ITEMS, "externalId", "TEXT");
5303
5304
  await this.createDefaultIndexes();
5304
5305
  await this.createCustomIndexes();
@@ -5422,6 +5423,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5422
5423
  expectedTrajectory: row.expectedTrajectory ? (0, _mastra_core_storage.safelyParseJSON)(row.expectedTrajectory) : void 0,
5423
5424
  toolMocks: row.toolMocks ? (0, _mastra_core_storage.safelyParseJSON)(row.toolMocks) : void 0,
5424
5425
  unmockedToolPolicy: row.unmockedToolPolicy ?? void 0,
5426
+ scorerIds: row.scorerIds ? (0, _mastra_core_storage.safelyParseJSON)(row.scorerIds) : void 0,
5425
5427
  requestContext: row.requestContext ? (0, _mastra_core_storage.safelyParseJSON)(row.requestContext) : void 0,
5426
5428
  metadata: row.metadata ? (0, _mastra_core_storage.safelyParseJSON)(row.metadata) : void 0,
5427
5429
  source: row.source ? (0, _mastra_core_storage.safelyParseJSON)(row.source) : void 0,
@@ -5444,6 +5446,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5444
5446
  expectedTrajectory: row.expectedTrajectory ? (0, _mastra_core_storage.safelyParseJSON)(row.expectedTrajectory) : void 0,
5445
5447
  toolMocks: row.toolMocks ? (0, _mastra_core_storage.safelyParseJSON)(row.toolMocks) : void 0,
5446
5448
  unmockedToolPolicy: row.unmockedToolPolicy ?? void 0,
5449
+ scorerIds: row.scorerIds ? (0, _mastra_core_storage.safelyParseJSON)(row.scorerIds) : void 0,
5447
5450
  requestContext: row.requestContext ? (0, _mastra_core_storage.safelyParseJSON)(row.requestContext) : void 0,
5448
5451
  metadata: row.metadata ? (0, _mastra_core_storage.safelyParseJSON)(row.metadata) : void 0,
5449
5452
  source: row.source ? (0, _mastra_core_storage.safelyParseJSON)(row.source) : void 0,
@@ -5775,7 +5778,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5775
5778
  newVersion = row.version;
5776
5779
  parentOrganizationId = row.organizationId ?? null;
5777
5780
  parentProjectId = row.projectId ?? null;
5778
- await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,false,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`, [
5781
+ await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","scorerIds","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,false,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [
5779
5782
  id,
5780
5783
  args.datasetId,
5781
5784
  newVersion,
@@ -5787,6 +5790,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5787
5790
  jsonbArg(args.expectedTrajectory),
5788
5791
  jsonbArg(args.toolMocks),
5789
5792
  args.unmockedToolPolicy ?? null,
5793
+ jsonbArg(args.scorerIds),
5790
5794
  jsonbArg(args.requestContext),
5791
5795
  jsonbArg(args.metadata),
5792
5796
  jsonbArg(args.source),
@@ -5814,6 +5818,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5814
5818
  expectedTrajectory: args.expectedTrajectory,
5815
5819
  toolMocks: args.toolMocks,
5816
5820
  unmockedToolPolicy: args.unmockedToolPolicy,
5821
+ scorerIds: args.scorerIds,
5817
5822
  requestContext: args.requestContext,
5818
5823
  metadata: args.metadata,
5819
5824
  source: args.source,
@@ -5868,6 +5873,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5868
5873
  const mergedExpectedTrajectory = args.expectedTrajectory !== void 0 ? args.expectedTrajectory : existing.expectedTrajectory;
5869
5874
  const mergedToolMocks = args.toolMocks !== void 0 ? args.toolMocks : existing.toolMocks;
5870
5875
  const mergedUnmockedToolPolicy = args.unmockedToolPolicy !== void 0 ? args.unmockedToolPolicy : existing.unmockedToolPolicy;
5876
+ const mergedScorerIds = args.scorerIds !== void 0 ? args.scorerIds ?? void 0 : existing.scorerIds;
5871
5877
  const mergedRequestContext = args.requestContext !== void 0 ? args.requestContext : existing.requestContext;
5872
5878
  const mergedMetadata = args.metadata !== void 0 ? args.metadata : existing.metadata;
5873
5879
  const mergedSource = args.source !== void 0 ? args.source : existing.source;
@@ -5880,7 +5886,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5880
5886
  parentOrganizationId = row.organizationId ?? null;
5881
5887
  parentProjectId = row.projectId ?? null;
5882
5888
  await t.none(`UPDATE ${itemsTable} SET "validTo" = $1 WHERE "id" = $2 AND "validTo" IS NULL AND "isDeleted" = false`, [newVersion, args.id]);
5883
- await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,false,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`, [
5889
+ await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","scorerIds","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,false,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [
5884
5890
  args.id,
5885
5891
  args.datasetId,
5886
5892
  newVersion,
@@ -5892,6 +5898,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5892
5898
  jsonbArg(mergedExpectedTrajectory),
5893
5899
  jsonbArg(mergedToolMocks),
5894
5900
  mergedUnmockedToolPolicy ?? null,
5901
+ jsonbArg(mergedScorerIds),
5895
5902
  jsonbArg(mergedRequestContext),
5896
5903
  jsonbArg(mergedMetadata),
5897
5904
  jsonbArg(mergedSource),
@@ -5918,6 +5925,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5918
5925
  expectedTrajectory: mergedExpectedTrajectory,
5919
5926
  toolMocks: mergedToolMocks,
5920
5927
  unmockedToolPolicy: mergedUnmockedToolPolicy,
5928
+ scorerIds: mergedScorerIds,
5921
5929
  requestContext: mergedRequestContext,
5922
5930
  metadata: mergedMetadata,
5923
5931
  source: mergedSource,
@@ -5966,7 +5974,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5966
5974
  const parentOrganizationId = row.organizationId ?? null;
5967
5975
  const parentProjectId = row.projectId ?? null;
5968
5976
  await t.none(`UPDATE ${itemsTable} SET "validTo" = $1 WHERE "id" = $2 AND "validTo" IS NULL AND "isDeleted" = false`, [newVersion, id]);
5969
- await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,true,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`, [
5977
+ await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","scorerIds","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,true,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [
5970
5978
  id,
5971
5979
  datasetId,
5972
5980
  newVersion,
@@ -5978,6 +5986,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
5978
5986
  jsonbArg(existing.expectedTrajectory),
5979
5987
  jsonbArg(existing.toolMocks),
5980
5988
  existing.unmockedToolPolicy ?? null,
5989
+ jsonbArg(existing.scorerIds),
5981
5990
  jsonbArg(existing.requestContext),
5982
5991
  jsonbArg(existing.metadata),
5983
5992
  jsonbArg(existing.source),
@@ -6037,7 +6046,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6037
6046
  const nowIso = now.toISOString();
6038
6047
  await t.none(`UPDATE ${datasetsTable} SET "version" = $2 WHERE "id" = $1`, [input.datasetId, newVersion]);
6039
6048
  for (const { id, item } of plan.inserts) {
6040
- await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,false,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`, [
6049
+ await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","scorerIds","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,false,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [
6041
6050
  id,
6042
6051
  input.datasetId,
6043
6052
  newVersion,
@@ -6049,6 +6058,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6049
6058
  jsonbArg(item.expectedTrajectory),
6050
6059
  jsonbArg(item.toolMocks),
6051
6060
  item.unmockedToolPolicy ?? null,
6061
+ jsonbArg(item.scorerIds),
6052
6062
  jsonbArg(item.requestContext),
6053
6063
  jsonbArg(item.metadata),
6054
6064
  jsonbArg(item.source),
@@ -6069,6 +6079,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6069
6079
  expectedTrajectory: item.expectedTrajectory,
6070
6080
  toolMocks: item.toolMocks,
6071
6081
  unmockedToolPolicy: item.unmockedToolPolicy,
6082
+ scorerIds: item.scorerIds,
6072
6083
  requestContext: item.requestContext,
6073
6084
  metadata: item.metadata,
6074
6085
  source: item.source,
@@ -6131,7 +6142,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6131
6142
  const newVersion = (await t.one(`UPDATE ${datasetsTable} SET "version" = "version" + 1 WHERE "id" = $1 RETURNING "version"`, [input.datasetId])).version;
6132
6143
  for (const item of currentItems) {
6133
6144
  await t.none(`UPDATE ${itemsTable} SET "validTo" = $1 WHERE "id" = $2 AND "validTo" IS NULL AND "isDeleted" = false`, [newVersion, item.id]);
6134
- await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,true,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18)`, [
6145
+ await t.none(`INSERT INTO ${itemsTable} ("id","datasetId","datasetVersion","externalId","organizationId","projectId","validTo","isDeleted","input","groundTruth","expectedTrajectory","toolMocks","unmockedToolPolicy","scorerIds","requestContext","metadata","source","createdAt","createdAtZ","updatedAt","updatedAtZ") VALUES ($1,$2,$3,$4,$5,$6,NULL,true,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)`, [
6135
6146
  item.id,
6136
6147
  input.datasetId,
6137
6148
  newVersion,
@@ -6143,6 +6154,7 @@ var DatasetsPG = class DatasetsPG extends _mastra_core_storage.DatasetsStorage {
6143
6154
  jsonbArg(item.expectedTrajectory),
6144
6155
  jsonbArg(item.toolMocks),
6145
6156
  item.unmockedToolPolicy ?? null,
6157
+ jsonbArg(item.scorerIds),
6146
6158
  jsonbArg(item.requestContext),
6147
6159
  jsonbArg(item.metadata),
6148
6160
  jsonbArg(item.source),
@@ -14252,6 +14264,7 @@ async function listLogsDelta(client, table, filters, after, limit) {
14252
14264
  */
14253
14265
  function applyMetricFilters(acc, filters) {
14254
14266
  applyCommonFilters(acc, filters);
14267
+ applySingleOrArrayFilter(acc, "traceId", filters?.traceIds);
14255
14268
  applySingleOrArrayFilter(acc, "name", filters?.name);
14256
14269
  applySingleOrArrayFilter(acc, "provider", filters?.provider);
14257
14270
  applySingleOrArrayFilter(acc, "model", filters?.model);
@@ -18772,6 +18785,187 @@ var ToolProviderConnectionsPG = class ToolProviderConnectionsPG extends _mastra_
18772
18785
  }
18773
18786
  };
18774
18787
  //#endregion
18788
+ //#region src/storage/domains/workflow-definitions/index.ts
18789
+ function rowToDefinition(row) {
18790
+ const inputSchema = parseJsonResilient(row.inputSchema);
18791
+ const outputSchema = parseJsonResilient(row.outputSchema);
18792
+ const graph = parseJsonResilient(row.graph);
18793
+ if (inputSchema === void 0 || outputSchema === void 0 || graph === void 0) throw new Error(`Workflow definition row "${String(row.id)}" is missing required JSON columns.`);
18794
+ const def = {
18795
+ id: String(row.id),
18796
+ inputSchema,
18797
+ outputSchema,
18798
+ graph,
18799
+ status: String(row.status),
18800
+ source: String(row.source),
18801
+ createdAt: new Date(row.createdAtZ ?? row.createdAt),
18802
+ updatedAt: new Date(row.updatedAtZ ?? row.updatedAt)
18803
+ };
18804
+ if (row.description != null) def.description = String(row.description);
18805
+ const metadata = parseJsonResilient(row.metadata);
18806
+ if (metadata !== void 0 && metadata !== null) def.metadata = metadata;
18807
+ const stateSchema = parseJsonResilient(row.stateSchema);
18808
+ if (stateSchema !== void 0 && stateSchema !== null) def.stateSchema = stateSchema;
18809
+ const requestContextSchema = parseJsonResilient(row.requestContextSchema);
18810
+ if (requestContextSchema !== void 0 && requestContextSchema !== null) def.requestContextSchema = requestContextSchema;
18811
+ if (row.authorId != null) def.authorId = String(row.authorId);
18812
+ return def;
18813
+ }
18814
+ var WorkflowDefinitionsPG = class WorkflowDefinitionsPG extends _mastra_core_storage.WorkflowDefinitionsStorage {
18815
+ #db;
18816
+ #schema;
18817
+ #skipDefaultIndexes;
18818
+ #indexes;
18819
+ static MANAGED_TABLES = [_mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS];
18820
+ constructor(config) {
18821
+ super();
18822
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
18823
+ this.#db = new PgDB({
18824
+ client,
18825
+ schemaName,
18826
+ skipDefaultIndexes
18827
+ });
18828
+ this.#schema = schemaName || "public";
18829
+ this.#skipDefaultIndexes = skipDefaultIndexes;
18830
+ this.#indexes = indexes?.filter((idx) => WorkflowDefinitionsPG.MANAGED_TABLES.includes(idx.table));
18831
+ }
18832
+ static getExportDDL(schemaName) {
18833
+ return [generateTableSQL({
18834
+ tableName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18835
+ schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS],
18836
+ schemaName,
18837
+ includeAllConstraints: true
18838
+ })];
18839
+ }
18840
+ getDefaultIndexDefinitions() {
18841
+ return [{
18842
+ name: `${this.#schema !== "public" ? `${this.#schema}_` : ""}idx_workflow_definitions_status`,
18843
+ table: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18844
+ columns: ["status"]
18845
+ }];
18846
+ }
18847
+ async createDefaultIndexes() {
18848
+ if (this.#skipDefaultIndexes) return;
18849
+ for (const indexDef of this.getDefaultIndexDefinitions()) try {
18850
+ await this.#db.createIndex(indexDef);
18851
+ } catch (error) {
18852
+ this.logger?.warn?.(`Failed to create index ${indexDef.name}:`, error);
18853
+ }
18854
+ }
18855
+ async createCustomIndexes() {
18856
+ if (!this.#indexes || this.#indexes.length === 0) return;
18857
+ for (const indexDef of this.#indexes) try {
18858
+ await this.#db.createIndex(indexDef);
18859
+ } catch (error) {
18860
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
18861
+ }
18862
+ }
18863
+ async init() {
18864
+ await this.#db.createTable({
18865
+ tableName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18866
+ schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS]
18867
+ });
18868
+ await this.createDefaultIndexes();
18869
+ await this.createCustomIndexes();
18870
+ }
18871
+ async dangerouslyClearAll() {
18872
+ await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS });
18873
+ }
18874
+ async upsert(input) {
18875
+ const now = /* @__PURE__ */ new Date();
18876
+ if (!await this.get(input.id)) {
18877
+ if (!("inputSchema" in input) || !input.inputSchema) throw new Error(`Cannot create workflow definition "${input.id}": inputSchema is required.`);
18878
+ if (!("outputSchema" in input) || !input.outputSchema) throw new Error(`Cannot create workflow definition "${input.id}": outputSchema is required.`);
18879
+ if (!("graph" in input) || !input.graph) throw new Error(`Cannot create workflow definition "${input.id}": graph is required.`);
18880
+ const record = {
18881
+ id: input.id,
18882
+ description: input.description ?? null,
18883
+ metadata: input.metadata ?? null,
18884
+ inputSchema: input.inputSchema,
18885
+ outputSchema: input.outputSchema,
18886
+ stateSchema: input.stateSchema ?? null,
18887
+ requestContextSchema: input.requestContextSchema ?? null,
18888
+ graph: input.graph,
18889
+ status: "active",
18890
+ source: "storage",
18891
+ authorId: "authorId" in input ? input.authorId ?? null : null,
18892
+ createdAt: now,
18893
+ updatedAt: now
18894
+ };
18895
+ try {
18896
+ await this.#db.insert({
18897
+ tableName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18898
+ record
18899
+ });
18900
+ } catch (error) {
18901
+ if (!await this.get(input.id)) throw error;
18902
+ return this.applyUpdate(input, now);
18903
+ }
18904
+ const created = await this.get(input.id);
18905
+ if (!created) throw new Error(`Failed to persist workflow definition "${input.id}".`);
18906
+ return created;
18907
+ }
18908
+ return this.applyUpdate(input, now);
18909
+ }
18910
+ async applyUpdate(input, now) {
18911
+ const data = { updatedAt: now };
18912
+ if ("description" in input && input.description !== void 0) data.description = input.description;
18913
+ if ("metadata" in input && input.metadata !== void 0) data.metadata = input.metadata;
18914
+ if ("inputSchema" in input && input.inputSchema !== void 0) data.inputSchema = input.inputSchema;
18915
+ if ("outputSchema" in input && input.outputSchema !== void 0) data.outputSchema = input.outputSchema;
18916
+ if ("stateSchema" in input && input.stateSchema !== void 0) data.stateSchema = input.stateSchema;
18917
+ if ("requestContextSchema" in input && input.requestContextSchema !== void 0) data.requestContextSchema = input.requestContextSchema;
18918
+ if ("graph" in input && input.graph !== void 0) data.graph = input.graph;
18919
+ if ("status" in input && input.status !== void 0) data.status = input.status;
18920
+ if ("authorId" in input && input.authorId !== void 0) data.authorId = input.authorId;
18921
+ await this.#db.update({
18922
+ tableName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18923
+ keys: { id: input.id },
18924
+ data
18925
+ });
18926
+ const updated = await this.get(input.id);
18927
+ if (!updated) throw new Error(`Failed to update workflow definition "${input.id}".`);
18928
+ return updated;
18929
+ }
18930
+ async get(id) {
18931
+ const tableName = getTableName$5({
18932
+ indexName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18933
+ schemaName: getSchemaName$5(this.#schema)
18934
+ });
18935
+ const row = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE "id" = $1`, [id]);
18936
+ return row ? rowToDefinition(row) : null;
18937
+ }
18938
+ async list(args) {
18939
+ const tableName = getTableName$5({
18940
+ indexName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18941
+ schemaName: getSchemaName$5(this.#schema)
18942
+ });
18943
+ const conditions = [];
18944
+ const params = [];
18945
+ if (args?.status) {
18946
+ params.push(args.status);
18947
+ conditions.push(`"status" = $${params.length}`);
18948
+ }
18949
+ if (args?.authorId !== void 0) {
18950
+ params.push(args.authorId);
18951
+ conditions.push(`"authorId" = $${params.length}`);
18952
+ }
18953
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
18954
+ const definitions = (await this.#db.client.manyOrNone(`SELECT * FROM ${tableName} ${where} ORDER BY "updatedAt" DESC`, params)).map((row) => rowToDefinition(row));
18955
+ return {
18956
+ definitions,
18957
+ total: definitions.length
18958
+ };
18959
+ }
18960
+ async delete(id) {
18961
+ const tableName = getTableName$5({
18962
+ indexName: _mastra_core_storage.TABLE_WORKFLOW_DEFINITIONS,
18963
+ schemaName: getSchemaName$5(this.#schema)
18964
+ });
18965
+ await this.#db.client.none(`DELETE FROM ${tableName} WHERE "id" = $1`, [id]);
18966
+ }
18967
+ };
18968
+ //#endregion
18775
18969
  //#region src/storage/domains/workflows/index.ts
18776
18970
  function getSchemaName(schema) {
18777
18971
  return schema ? `"${schema}"` : "\"public\"";
@@ -20264,6 +20458,7 @@ const ALL_DOMAINS = [
20264
20458
  BlobsPG,
20265
20459
  ToolProviderConnectionsPG,
20266
20460
  WorkflowsPG,
20461
+ WorkflowDefinitionsPG,
20267
20462
  DatasetsPG,
20268
20463
  ExperimentsPG,
20269
20464
  BackgroundTasksPG,
@@ -20345,6 +20540,7 @@ var PostgresStore = class extends _mastra_core_storage.MastraCompositeStore {
20345
20540
  this.stores = {
20346
20541
  scores: new ScoresPG(domainConfig),
20347
20542
  workflows: new WorkflowsPG(domainConfig),
20543
+ workflowDefinitions: new WorkflowDefinitionsPG(domainConfig),
20348
20544
  memory: new MemoryPG(domainConfig),
20349
20545
  notifications: new NotificationsPG(domainConfig),
20350
20546
  observability: new ObservabilityPG(domainConfig),
@@ -20694,6 +20890,7 @@ exports.ScorerDefinitionsPG = ScorerDefinitionsPG;
20694
20890
  exports.ScoresPG = ScoresPG;
20695
20891
  exports.SkillsPG = SkillsPG;
20696
20892
  exports.ToolProviderConnectionsPG = ToolProviderConnectionsPG;
20893
+ exports.WorkflowDefinitionsPG = WorkflowDefinitionsPG;
20697
20894
  exports.WorkflowsPG = WorkflowsPG;
20698
20895
  exports.WorkspacesPG = WorkspacesPG;
20699
20896
  exports.exportSchemas = exportSchemas;