@mastra/factory 0.29.0-alpha.2 → 0.29.0-alpha.4

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.
Files changed (211) hide show
  1. package/README.md +44 -5
  2. package/dist/factory.d.ts +8 -0
  3. package/dist/factory.d.ts.map +1 -1
  4. package/dist/factory.js +26 -10
  5. package/dist/factory.js.map +1 -1
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -2
  9. package/dist/integrations/dependabot/rules.d.ts.map +1 -1
  10. package/dist/integrations/dependabot/rules.js +1 -5
  11. package/dist/integrations/dependabot/rules.js.map +1 -1
  12. package/dist/integrations/github/commits.d.ts +0 -21
  13. package/dist/integrations/github/commits.d.ts.map +1 -1
  14. package/dist/integrations/github/commits.js +1 -24
  15. package/dist/integrations/github/commits.js.map +1 -1
  16. package/dist/integrations/github/integration.d.ts +1 -1
  17. package/dist/integrations/github/integration.d.ts.map +1 -1
  18. package/dist/integrations/github/integration.js +2 -6
  19. package/dist/integrations/github/integration.js.map +1 -1
  20. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  21. package/dist/integrations/github/reconcile-worker.js +30 -1
  22. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  23. package/dist/integrations/github/routes.d.ts +1 -11
  24. package/dist/integrations/github/routes.d.ts.map +1 -1
  25. package/dist/integrations/github/routes.js +6 -515
  26. package/dist/integrations/github/routes.js.map +1 -1
  27. package/dist/integrations/github/rules.d.ts.map +1 -1
  28. package/dist/integrations/github/rules.js +76 -13
  29. package/dist/integrations/github/rules.js.map +1 -1
  30. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  31. package/dist/integrations/github/sandbox.js +11 -2
  32. package/dist/integrations/github/sandbox.js.map +1 -1
  33. package/dist/integrations/gitlab/discovery.d.ts +1 -1
  34. package/dist/integrations/gitlab/discovery.js +1 -1
  35. package/dist/integrations/gitlab/discovery.js.map +1 -1
  36. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/integration.js +0 -1
  38. package/dist/integrations/gitlab/integration.js.map +1 -1
  39. package/dist/integrations/gitlab/routes.d.ts +0 -2
  40. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  41. package/dist/integrations/gitlab/routes.js +49 -165
  42. package/dist/integrations/gitlab/routes.js.map +1 -1
  43. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  44. package/dist/integrations/gitlab/rules.js +20 -7
  45. package/dist/integrations/gitlab/rules.js.map +1 -1
  46. package/dist/integrations/incidentio/routes.d.ts +5 -5
  47. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  48. package/dist/integrations/incidentio/routes.js +3 -59
  49. package/dist/integrations/incidentio/routes.js.map +1 -1
  50. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  51. package/dist/integrations/incidentio/rules.js +1 -5
  52. package/dist/integrations/incidentio/rules.js.map +1 -1
  53. package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
  54. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  55. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  56. package/dist/integrations/jira/routes.d.ts +2 -2
  57. package/dist/integrations/jira/routes.d.ts.map +1 -1
  58. package/dist/integrations/jira/routes.js +0 -68
  59. package/dist/integrations/jira/routes.js.map +1 -1
  60. package/dist/integrations/jira/rules.d.ts.map +1 -1
  61. package/dist/integrations/jira/rules.js +1 -5
  62. package/dist/integrations/jira/rules.js.map +1 -1
  63. package/dist/integrations/linear/routes.d.ts +2 -2
  64. package/dist/integrations/linear/routes.d.ts.map +1 -1
  65. package/dist/integrations/linear/routes.js +0 -83
  66. package/dist/integrations/linear/routes.js.map +1 -1
  67. package/dist/integrations/linear/rules.d.ts.map +1 -1
  68. package/dist/integrations/linear/rules.js +12 -5
  69. package/dist/integrations/linear/rules.js.map +1 -1
  70. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  71. package/dist/integrations/platform/github/integration.js +1 -3
  72. package/dist/integrations/platform/github/integration.js.map +1 -1
  73. package/dist/integrations/platform/jira/routes.d.ts +2 -2
  74. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  75. package/dist/integrations/platform/jira/routes.js +0 -69
  76. package/dist/integrations/platform/jira/routes.js.map +1 -1
  77. package/dist/integrations/vanta/rules.d.ts.map +1 -1
  78. package/dist/integrations/vanta/rules.js +1 -5
  79. package/dist/integrations/vanta/rules.js.map +1 -1
  80. package/dist/metrics/collectors/postgres.d.ts +29 -0
  81. package/dist/metrics/collectors/postgres.d.ts.map +1 -0
  82. package/dist/metrics/collectors/postgres.js +121 -0
  83. package/dist/metrics/collectors/postgres.js.map +1 -0
  84. package/dist/metrics/collectors/probe.d.ts +22 -0
  85. package/dist/metrics/collectors/probe.d.ts.map +1 -0
  86. package/dist/metrics/collectors/probe.js +69 -0
  87. package/dist/metrics/collectors/probe.js.map +1 -0
  88. package/dist/metrics/collectors/process.d.ts +13 -0
  89. package/dist/metrics/collectors/process.d.ts.map +1 -0
  90. package/dist/metrics/collectors/process.js +85 -0
  91. package/dist/metrics/collectors/process.js.map +1 -0
  92. package/dist/metrics/collectors/redis.d.ts +29 -0
  93. package/dist/metrics/collectors/redis.d.ts.map +1 -0
  94. package/dist/metrics/collectors/redis.js +97 -0
  95. package/dist/metrics/collectors/redis.js.map +1 -0
  96. package/dist/metrics/config.d.ts +33 -0
  97. package/dist/metrics/config.d.ts.map +1 -0
  98. package/dist/metrics/config.js +65 -0
  99. package/dist/metrics/config.js.map +1 -0
  100. package/dist/metrics/index.d.ts +20 -0
  101. package/dist/metrics/index.d.ts.map +1 -0
  102. package/dist/metrics/index.js +65 -0
  103. package/dist/metrics/index.js.map +1 -0
  104. package/dist/metrics/intake.d.ts +28 -0
  105. package/dist/metrics/intake.d.ts.map +1 -0
  106. package/dist/metrics/intake.js +76 -0
  107. package/dist/metrics/intake.js.map +1 -0
  108. package/dist/metrics/metrics.d.ts +60 -0
  109. package/dist/metrics/metrics.d.ts.map +1 -0
  110. package/dist/metrics/metrics.js +182 -0
  111. package/dist/metrics/metrics.js.map +1 -0
  112. package/dist/metrics/sandbox.d.ts +35 -0
  113. package/dist/metrics/sandbox.d.ts.map +1 -0
  114. package/dist/metrics/sandbox.js +156 -0
  115. package/dist/metrics/sandbox.js.map +1 -0
  116. package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
  117. package/dist/routes/automation-runs.d.ts +0 -2
  118. package/dist/routes/automation-runs.d.ts.map +1 -1
  119. package/dist/routes/automation-runs.js +2 -6
  120. package/dist/routes/automation-runs.js.map +1 -1
  121. package/dist/routes/contracts.d.ts +0 -5
  122. package/dist/routes/contracts.d.ts.map +1 -1
  123. package/dist/routes/contracts.js +2 -4
  124. package/dist/routes/contracts.js.map +1 -1
  125. package/dist/routes/fs.d.ts +10 -0
  126. package/dist/routes/fs.d.ts.map +1 -1
  127. package/dist/routes/fs.js +184 -11
  128. package/dist/routes/fs.js.map +1 -1
  129. package/dist/routes/projects.d.ts.map +1 -1
  130. package/dist/routes/projects.js +4 -17
  131. package/dist/routes/projects.js.map +1 -1
  132. package/dist/routes/source-control-sessions.d.ts +0 -3
  133. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  134. package/dist/routes/source-control-sessions.js +0 -19
  135. package/dist/routes/source-control-sessions.js.map +1 -1
  136. package/dist/routes/surface.d.ts +0 -2
  137. package/dist/routes/surface.d.ts.map +1 -1
  138. package/dist/routes/surface.js +2 -12
  139. package/dist/routes/surface.js.map +1 -1
  140. package/dist/rules/dispatcher.d.ts +1 -0
  141. package/dist/rules/dispatcher.d.ts.map +1 -1
  142. package/dist/rules/dispatcher.js +27 -13
  143. package/dist/rules/dispatcher.js.map +1 -1
  144. package/dist/rules/processor.d.ts.map +1 -1
  145. package/dist/rules/processor.js +1 -6
  146. package/dist/rules/processor.js.map +1 -1
  147. package/dist/rules/start-coordinator.d.ts +1 -0
  148. package/dist/rules/start-coordinator.d.ts.map +1 -1
  149. package/dist/rules/start-coordinator.js +2 -1
  150. package/dist/rules/start-coordinator.js.map +1 -1
  151. package/dist/rules/transition-service.d.ts.map +1 -1
  152. package/dist/rules/transition-service.js +0 -2
  153. package/dist/rules/transition-service.js.map +1 -1
  154. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  155. package/dist/sandbox/session-retirement.js +22 -14
  156. package/dist/sandbox/session-retirement.js.map +1 -1
  157. package/dist/sandbox/session-sandbox.d.ts +2 -0
  158. package/dist/sandbox/session-sandbox.d.ts.map +1 -1
  159. package/dist/sandbox/session-sandbox.js +7 -1
  160. package/dist/sandbox/session-sandbox.js.map +1 -1
  161. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  162. package/dist/storage/domains/boards/schemas.js +0 -4
  163. package/dist/storage/domains/boards/schemas.js.map +1 -1
  164. package/dist/storage/domains/intake/base.d.ts +11 -10
  165. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  166. package/dist/storage/domains/intake/base.js +30 -65
  167. package/dist/storage/domains/intake/base.js.map +1 -1
  168. package/dist/storage/domains/integrations/base.d.ts +0 -2
  169. package/dist/storage/domains/integrations/base.d.ts.map +1 -1
  170. package/dist/storage/domains/integrations/base.js +0 -6
  171. package/dist/storage/domains/integrations/base.js.map +1 -1
  172. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  173. package/dist/storage/domains/projects/base.js +0 -12
  174. package/dist/storage/domains/projects/base.js.map +1 -1
  175. package/dist/storage/domains/source-control/base.d.ts +0 -10
  176. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  177. package/dist/storage/domains/source-control/base.js +1 -19
  178. package/dist/storage/domains/source-control/base.js.map +1 -1
  179. package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
  180. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  181. package/dist/storage/domains/source-control/inmemory.js +1 -6
  182. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  183. package/dist/storage/domains/work-items/base.d.ts +6 -36
  184. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  185. package/dist/storage/domains/work-items/base.js +42 -82
  186. package/dist/storage/domains/work-items/base.js.map +1 -1
  187. package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
  188. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  189. package/dist/storage/domains/work-items/work-item-schema.js +12 -3
  190. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  191. package/dist/storage/legacy-collections.d.ts +9 -0
  192. package/dist/storage/legacy-collections.d.ts.map +1 -0
  193. package/dist/storage/legacy-collections.js +17 -0
  194. package/dist/storage/legacy-collections.js.map +1 -0
  195. package/dist/timing.d.ts +4 -1
  196. package/dist/timing.d.ts.map +1 -1
  197. package/dist/timing.js +12 -4
  198. package/dist/timing.js.map +1 -1
  199. package/dist/workspace.d.ts.map +1 -1
  200. package/dist/workspace.js +8 -4
  201. package/dist/workspace.js.map +1 -1
  202. package/factory-skills/configure-factory-rules/SKILL.md +2 -2
  203. package/package.json +10 -10
  204. package/dist/session/filesystem-capture.d.ts +0 -50
  205. package/dist/session/filesystem-capture.d.ts.map +0 -1
  206. package/dist/session/filesystem-capture.js +0 -229
  207. package/dist/session/filesystem-capture.js.map +0 -1
  208. package/dist/storage/domains/filesystem/base.d.ts +0 -30
  209. package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
  210. package/dist/storage/domains/filesystem/base.js +0 -78
  211. package/dist/storage/domains/filesystem/base.js.map +0 -1
@@ -1,7 +1,6 @@
1
1
  import { loose } from "../../../routes/route.js";
2
2
  import { JiraApiError } from "../../jira/api.js";
3
3
  import { scopeJiraSourcesToProject } from "../../jira/binding-scope.js";
4
- import { unfilteredJiraScopes } from "../../jira/intake-jql.js";
5
4
  import { registerApiRoute } from "@mastra/core/server";
6
5
  // src/integrations/platform/jira/routes.ts
7
6
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -24,16 +23,6 @@ async function resolveOrgTenant(c, auth) {
24
23
  userId: tenant.userId
25
24
  } };
26
25
  }
27
- /**
28
- * Validate an opaque Jira pagination cursor from the query string. Cursors are
29
- * server-issued (`nextPageToken`), so anything outside a conservative
30
- * charset/length is rejected rather than forwarded to Jira.
31
- */
32
- function parseAfterCursor(raw) {
33
- if (raw === void 0 || raw === "") return void 0;
34
- if (raw.length > 512 || !/^[\w+/=.:-]+$/.test(raw)) return null;
35
- return raw;
36
- }
37
26
  /** Map a Jira read failure to the API response for the SPA. */
38
27
  function jiraFetchError(c, err) {
39
28
  if (err instanceof JiraApiError && err.code === "jira_auth_failed") return c.json({
@@ -127,64 +116,6 @@ function buildPlatformJiraRoutes(options) {
127
116
  }
128
117
  }
129
118
  }));
130
- routes.push(registerApiRoute("/web/jira/issues", {
131
- method: "GET",
132
- requiresAuth: false,
133
- handler: async (c) => {
134
- const resolved = await resolveOrgTenant(loose(c), auth);
135
- if ("response" in resolved) return resolved.response;
136
- const after = parseAfterCursor(c.req.query("after"));
137
- if (after === null) return c.json({ error: "invalid_cursor" }, 400);
138
- const factoryProjectId = c.req.query("factoryProjectId");
139
- if (factoryProjectId && !UUID_RE.test(factoryProjectId)) return c.json({ error: "invalid_factory_project_id" }, 400);
140
- await intake.ensureReady();
141
- const selection = (await intake.getConfig({
142
- orgId: resolved.tenant.orgId,
143
- integrationIds: ["jira"]
144
- })).jira;
145
- if (!selection.enabled) return c.json({
146
- error: "jira_intake_disabled",
147
- message: "Jira intake is turned off in Settings."
148
- }, 404);
149
- const selectedIds = selection.sourceIds ?? [];
150
- const scopes = (factoryProjectId ? await scopeJiraSourcesToProject({
151
- intake,
152
- orgId: resolved.tenant.orgId,
153
- factoryProjectId,
154
- selectedIds
155
- }) : null)?.scopes ?? unfilteredJiraScopes(selectedIds);
156
- if (scopes.length === 0) return c.json({
157
- issues: [],
158
- nextCursor: null
159
- });
160
- try {
161
- const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);
162
- const issuePayload = issues.map((issue) => ({
163
- id: issue.externalId,
164
- identifier: issue.identifier,
165
- title: issue.title,
166
- url: issue.url,
167
- author: issue.author,
168
- state: issue.state ?? "",
169
- stateType: issue.stateType ?? "",
170
- priorityLabel: issue.priority ?? "",
171
- assignee: issue.assignee,
172
- project: issue.source,
173
- site: issue.site,
174
- labels: issue.labels,
175
- createdAt: issue.createdAt,
176
- updatedAt: issue.updatedAt,
177
- sourceId: issue.sourceId || null
178
- }));
179
- return c.json({
180
- issues: issuePayload,
181
- nextCursor
182
- });
183
- } catch (err) {
184
- return jiraFetchError(loose(c), err);
185
- }
186
- }
187
- }));
188
119
  routes.push(registerApiRoute("/web/jira/issues/:identifier", {
189
120
  method: "GET",
190
121
  requiresAuth: false,
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/jira/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Jira intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Jira connections are owned by the caller's Mastra Platform organization;\n * provider requests stay server-side and flow through the integrations v2\n * proxy. Every route re-resolves the authenticated user and scopes intake\n * selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildPlatformJiraRoutes` returns only `GET /web/jira/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Jira UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { IntakeStorage } from '../../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport { JiraApiError } from '../../jira/api.js';\nimport { scopeJiraSourcesToProject } from '../../jira/binding-scope.js';\nimport { unfilteredJiraScopes } from '../../jira/intake-jql.js';\nimport type { PlatformJiraIntegration } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\n/**\n * Non-secret diagnostic snapshot of every Jira feature gate, mirroring the\n * Linear diagnostics shape. Only booleans — never values.\n */\nexport interface JiraFeatureDiagnostics {\n jiraConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountJiraRoutesOptions {\n /**\n * The integration instance providing REST access. Required for everything\n * beyond the disabled `status` route.\n */\n jira?: PlatformJiraIntegration;\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /** Whether the host configured the application database backing intake state. */\n appDbConfigured: boolean;\n /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource'>;\n}\n\n/**\n * Resolve the org-scoped tenant for a Jira request. Intake selections are\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the Linear routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Jira intake requires an organization. Personal accounts cannot use Jira intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Jira pagination cursor from the query string. Cursors are\n * server-issued (`nextPageToken`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Jira.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Jira read failure to the API response for the SPA. */\nfunction jiraFetchError(c: RouteContext, err: unknown) {\n if (err instanceof JiraApiError && err.code === 'jira_auth_failed') {\n return c.json(\n {\n error: 'jira_auth_failed',\n message: 'Jira rejected the connected account. Reconnect it in Mastra Platform.',\n },\n 409,\n );\n }\n return c.json({ error: 'jira_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Jira routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildPlatformJiraRoutes(options: MountJiraRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { jira, auth, intake, workItems } = options;\n const enabled = Boolean(jira) && auth.enabled();\n const diagnostics = (): JiraFeatureDiagnostics => ({\n jiraConfigured: Boolean(jira),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: options.appDbConfigured,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !jira || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(jira),\n mode: 'platform',\n site: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: false,\n mode: 'platform',\n organizationRequired: true,\n site: null,\n sites: [],\n connections: [],\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n try {\n const connections = await jira.listConnections();\n const active = connections.filter(connection => connection.status === 'active');\n const sites = active.flatMap(connection => (connection.accountLabel ? [connection.accountLabel] : []));\n return c.json({\n enabled: true,\n configured: active.length > 0,\n mode: 'platform',\n site: sites.length === 1 ? sites[0] : null,\n sites,\n connections,\n reason: active.length > 0 ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !jira || !intake) {\n return routes;\n }\n\n // ── List the site's projects (Settings intake-source picker) ────────────\n routes.push(\n registerApiRoute('/web/jira/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n try {\n const sources = await jira.intake.listSources(resolved.tenant);\n return c.json({\n projects: sources.map(source => ({\n id: source.id,\n name: source.name,\n key: typeof source.metadata?.key === 'string' ? source.metadata.key : null,\n connectionId: typeof source.metadata?.connectionId === 'string' ? source.metadata.connectionId : null,\n site: typeof source.metadata?.site === 'string' ? source.metadata.site : null,\n })),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the site's active issues (cursor-paged) ────────────────────────\n // Respects the caller's intake config: disabled Jira intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/jira/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Jira.\n const selectedIds = selection.sourceIds ?? [];\n // A board request only ever sees the projects routed to a board of\n // that Factory project; unscoped listing stays available to callers\n // that don't view a specific board.\n const projectScope = factoryProjectId\n ? await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const scopes = projectScope?.scopes ?? unfilteredJiraScopes(selectedIds);\n if (scopes.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);\n const issuePayload = issues.map(issue => ({\n id: issue.externalId,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n project: issue.source,\n site: issue.site,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId || null,\n }));\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/jira/issues/:identifier', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const identifier = c.req.param('identifier');\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!ISSUE_KEY_RE.test(identifier)) return c.json({ error: 'invalid_issue_identifier' }, 400);\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048) return c.json({ error: 'invalid_issue_ref' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n const dispatch = await jira.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n const sourceId = dispatch?.sourceId;\n if (!dispatch || !sourceId || !projectScope.sourceIds.includes(sourceId)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n\n try {\n const issue = await jira.intake.getIssue(dispatch);\n // An issue in another Factory's slice that this Factory never filed reads like one that doesn't exist.\n if (\n !issue ||\n issue.identifier.toUpperCase() !== identifier.toUpperCase() ||\n !(\n projectScope.takes(sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issueRef },\n }))\n )\n ) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n return c.json({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description,\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;AA6BA,MAAM,UAAU;AAChB,MAAM,eAAe;;;;;;AAoCrB,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;;;;;;AAOA,SAAS,iBAAiB,KAAoD;CAC5E,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAAI,OAAO,KAAA;CAC5C,IAAI,IAAI,SAAS,OAAO,CAAC,gBAAgB,KAA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C,YAAY,CAAC,aAAa,UAAU,SAAS,QAAQ,GACrE,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;GAGjD,IAAI;IACF,MAAM,QAAQ,MAAM,KAAK,OAAO,SAAS,QAAQ;IAEjD,IACE,CAAC,SACD,MAAM,WAAW,YAAY,MAAM,WAAW,YAAY,KAC1D,EACE,aAAa,MAAM,UAAU,MAAM,MAAM,KACzC,CAAC,CAAE,MAAM,WAAW,mBAAmB;KACrC,OAAO,SAAS,OAAO;KACvB;KACA,QAAQ;MAAE,eAAe;MAAQ,MAAM;MAAS,YAAY;KAAS;IACvE,CAAC,IAGH,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAEjD,OAAO,EAAE,KAAK;KACZ,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM;IACrB,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,eAAe,MAAM,CAAC,GAAG,GAAG;GACrC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/jira/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Jira intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Jira connections are owned by the caller's Mastra Platform organization;\n * provider requests stay server-side and flow through the integrations v2\n * proxy. Every route re-resolves the authenticated user and scopes intake\n * selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildPlatformJiraRoutes` returns only `GET /web/jira/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Jira UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { IntakeStorage } from '../../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../../storage/domains/work-items/base.js';\nimport { JiraApiError } from '../../jira/api.js';\nimport { scopeJiraSourcesToProject } from '../../jira/binding-scope.js';\nimport type { PlatformJiraIntegration } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\n/**\n * Non-secret diagnostic snapshot of every Jira feature gate, mirroring the\n * Linear diagnostics shape. Only booleans — never values.\n */\nexport interface JiraFeatureDiagnostics {\n jiraConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountJiraRoutesOptions {\n /**\n * The integration instance providing REST access. Required for everything\n * beyond the disabled `status` route.\n */\n jira?: PlatformJiraIntegration;\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issue detail\n * route's project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /** Whether the host configured the application database backing intake state. */\n appDbConfigured: boolean;\n /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource'>;\n}\n\n/**\n * Resolve the org-scoped tenant for a Jira request. Intake selections are\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the Linear routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Jira intake requires an organization. Personal accounts cannot use Jira intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/** Map a Jira read failure to the API response for the SPA. */\nfunction jiraFetchError(c: RouteContext, err: unknown) {\n if (err instanceof JiraApiError && err.code === 'jira_auth_failed') {\n return c.json(\n {\n error: 'jira_auth_failed',\n message: 'Jira rejected the connected account. Reconnect it in Mastra Platform.',\n },\n 409,\n );\n }\n return c.json({ error: 'jira_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Jira routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildPlatformJiraRoutes(options: MountJiraRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { jira, auth, intake, workItems } = options;\n const enabled = Boolean(jira) && auth.enabled();\n const diagnostics = (): JiraFeatureDiagnostics => ({\n jiraConfigured: Boolean(jira),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: options.appDbConfigured,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !jira || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(jira),\n mode: 'platform',\n site: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: false,\n mode: 'platform',\n organizationRequired: true,\n site: null,\n sites: [],\n connections: [],\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n try {\n const connections = await jira.listConnections();\n const active = connections.filter(connection => connection.status === 'active');\n const sites = active.flatMap(connection => (connection.accountLabel ? [connection.accountLabel] : []));\n return c.json({\n enabled: true,\n configured: active.length > 0,\n mode: 'platform',\n site: sites.length === 1 ? sites[0] : null,\n sites,\n connections,\n reason: active.length > 0 ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !jira || !intake) {\n return routes;\n }\n\n // ── List the site's projects (Settings intake-source picker) ────────────\n routes.push(\n registerApiRoute('/web/jira/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n try {\n const sources = await jira.intake.listSources(resolved.tenant);\n return c.json({\n projects: sources.map(source => ({\n id: source.id,\n name: source.name,\n key: typeof source.metadata?.key === 'string' ? source.metadata.key : null,\n connectionId: typeof source.metadata?.connectionId === 'string' ? source.metadata.connectionId : null,\n site: typeof source.metadata?.site === 'string' ? source.metadata.site : null,\n })),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/jira/issues/:identifier', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const identifier = c.req.param('identifier');\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!ISSUE_KEY_RE.test(identifier)) return c.json({ error: 'invalid_issue_identifier' }, 400);\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048) return c.json({ error: 'invalid_issue_ref' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n const dispatch = await jira.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n const sourceId = dispatch?.sourceId;\n if (!dispatch || !sourceId || !projectScope.sourceIds.includes(sourceId)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n\n try {\n const issue = await jira.intake.getIssue(dispatch);\n // An issue in another Factory's slice that this Factory never filed reads like one that doesn't exist.\n if (\n !issue ||\n issue.identifier.toUpperCase() !== identifier.toUpperCase() ||\n !(\n projectScope.takes(sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issueRef },\n }))\n )\n ) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n return c.json({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description,\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;AA4BA,MAAM,UAAU;AAChB,MAAM,eAAe;;;;;;AAoCrB,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;;AAGA,SAAS,eAAe,GAAiB,KAAc;CACrD,IAAI,eAAe,gBAAgB,IAAI,SAAS,oBAC9C,OAAO,EAAE,KACP;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF;CAEF,OAAO,EAAE,KAAK;EAAE,OAAO;EAAqB,SAAS,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;CA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ingress: {
173
- identity: ingressId,
174
- triggerType: `vanta.${event}`
175
- },
176
- configVersion: this.options.configVersion,
172
+ ingress: { identity: ingressId },
177
173
  expectedRevision: relatedItem?.revision ?? null,
178
174
  actor,
179
175
  outcome,
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/vanta/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport { boardForWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { routeEventDecision } from '../../rules/event-rules.js';\nimport type { FactoryVantaRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { defaultVantaRules } from './default-rules.js';\nimport type { VantaEventRules } from './default-rules.js';\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\n/** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */\nexport function vantaLabels(severity: string | null): string[] {\n return ['security', 'vanta', ...(severity ? [`severity:${severity.toLowerCase()}`] : [])];\n}\n\nexport type VantaVulnerabilityIngress = FactoryVantaRuleContext['vulnerability'];\n\nexport interface VantaRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry | ProjectBoardSource;\n rules?: VantaEventRules;\n}\n\nexport interface VantaRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /** Every vulnerability Vanta currently lists as active. Open cards missing from it are closed. */\n vulnerabilities: VantaVulnerabilityIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */\nexport function boardEventFor(context: Pick<FactoryVantaRuleContext, 'event' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'vulnerabilityClosed') {\n return { type: 'work_item.closed', reason: closeReason(false) };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\n/** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */\nfunction resolvedFromCard(sourceKey: string, item: Card): VantaVulnerabilityIngress {\n const metadata = item.metadata ?? {};\n const text = (key: string) => (typeof metadata[key] === 'string' ? (metadata[key] as string) : null);\n return {\n id: sourceKey,\n name: text('identifier') ?? sourceKey,\n title: item.title,\n description: null,\n url: item.externalSource?.url ?? null,\n state: 'resolved',\n severity: text('severity'),\n packageIdentifier: text('packageIdentifier'),\n fixable: null,\n remediateBy: text('remediateBy'),\n labels: [],\n createdAt: text('sourceCreatedAt') ?? new Date(0).toISOString(),\n };\n}\n\nexport class VantaRules {\n readonly #rules: VantaEventRules;\n\n constructor(private readonly options: VantaRulesOptions) {\n this.#rules = options.rules ?? defaultVantaRules;\n }\n\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: VantaRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(\n items\n .filter(item => item.externalSource?.integrationId === 'vanta' && item.externalSource.type === 'vulnerability')\n .map(item => [item.externalSource?.externalId, item]),\n );\n const statuses: IngressStatus[] = [];\n const active = new Set(input.vulnerabilities.map(vulnerability => vulnerability.id));\n for (const vulnerability of input.vulnerabilities) {\n const relatedItem = itemsBySourceKey.get(vulnerability.id);\n statuses.push(await this.#ingestAlert(input, vulnerability, relatedItem && structuredClone(relatedItem)));\n }\n for (const [sourceKey, item] of itemsBySourceKey) {\n if (!sourceKey || active.has(sourceKey) || item.metadata?.state === 'resolved') continue;\n statuses.push(await this.#ingestAlert(input, resolvedFromCard(sourceKey, item), structuredClone(item)));\n }\n if (statuses.includes('committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.includes('replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestAlert(\n input: VantaRulesIngress,\n alert: VantaVulnerabilityIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const closed = alert.state === 'resolved';\n // A resolved vulnerability Factory never filed stays off the board.\n if (closed && !relatedItem) return 'missing';\n\n const ingressId = `vanta:${alert.id}:${alert.state}`;\n const actor = { type: 'human' as const, id: input.userId };\n const event = closed ? 'vulnerabilityClosed' : 'vulnerabilityObserved';\n const boards = this.#boards(input);\n const context: FactoryVantaRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'vanta', id: ingressId },\n cause: `vanta.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'vanta-vulnerability',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(boards, relatedItem),\n ...rulePhaseField(boards, relatedItem),\n }\n : {}),\n ...withIntakeTarget(boards),\n event,\n vulnerability: alert,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const rule = this.#rules[event];\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await rule(Object.freeze(context)) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(entry, boards, relatedItem ? boardForWorkItem(relatedItem) : undefined);\n return { ...entry };\n });\n }\n } catch (error) {\n outcome = {\n status: 'rejected',\n code: 'rule_error',\n reason: error instanceof Error ? error.message.slice(0, 2_000) : 'Factory Vanta rule failed.',\n };\n }\n if (!decision && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: `vanta.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Vanta rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestAlert(input, alert, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachVantaRules(\n context: IntegrationContext,\n): ((input: VantaRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new VantaRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.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version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/vanta/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport { boardForWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { routeEventDecision } from '../../rules/event-rules.js';\nimport type { FactoryVantaRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { defaultVantaRules } from './default-rules.js';\nimport type { VantaEventRules } from './default-rules.js';\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\n/** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */\nexport function vantaLabels(severity: string | null): string[] {\n return ['security', 'vanta', ...(severity ? [`severity:${severity.toLowerCase()}`] : [])];\n}\n\nexport type VantaVulnerabilityIngress = FactoryVantaRuleContext['vulnerability'];\n\nexport interface VantaRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry | ProjectBoardSource;\n rules?: VantaEventRules;\n}\n\nexport interface VantaRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /** Every vulnerability Vanta currently lists as active. Open cards missing from it are closed. */\n vulnerabilities: VantaVulnerabilityIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */\nexport function boardEventFor(context: Pick<FactoryVantaRuleContext, 'event' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'vulnerabilityClosed') {\n return { type: 'work_item.closed', reason: closeReason(false) };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\n/** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */\nfunction resolvedFromCard(sourceKey: string, item: Card): VantaVulnerabilityIngress {\n const metadata = item.metadata ?? {};\n const text = (key: string) => (typeof metadata[key] === 'string' ? (metadata[key] as string) : null);\n return {\n id: sourceKey,\n name: text('identifier') ?? sourceKey,\n title: item.title,\n description: null,\n url: item.externalSource?.url ?? null,\n state: 'resolved',\n severity: text('severity'),\n packageIdentifier: text('packageIdentifier'),\n fixable: null,\n remediateBy: text('remediateBy'),\n labels: [],\n createdAt: text('sourceCreatedAt') ?? new Date(0).toISOString(),\n };\n}\n\nexport class VantaRules {\n readonly #rules: VantaEventRules;\n\n constructor(private readonly options: VantaRulesOptions) {\n this.#rules = options.rules ?? defaultVantaRules;\n }\n\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: VantaRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(\n items\n .filter(item => item.externalSource?.integrationId === 'vanta' && item.externalSource.type === 'vulnerability')\n .map(item => [item.externalSource?.externalId, item]),\n );\n const statuses: IngressStatus[] = [];\n const active = new Set(input.vulnerabilities.map(vulnerability => vulnerability.id));\n for (const vulnerability of input.vulnerabilities) {\n const relatedItem = itemsBySourceKey.get(vulnerability.id);\n statuses.push(await this.#ingestAlert(input, vulnerability, relatedItem && structuredClone(relatedItem)));\n }\n for (const [sourceKey, item] of itemsBySourceKey) {\n if (!sourceKey || active.has(sourceKey) || item.metadata?.state === 'resolved') continue;\n statuses.push(await this.#ingestAlert(input, resolvedFromCard(sourceKey, item), structuredClone(item)));\n }\n if (statuses.includes('committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.includes('replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestAlert(\n input: VantaRulesIngress,\n alert: VantaVulnerabilityIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const closed = alert.state === 'resolved';\n // A resolved vulnerability Factory never filed stays off the board.\n if (closed && !relatedItem) return 'missing';\n\n const ingressId = `vanta:${alert.id}:${alert.state}`;\n const actor = { type: 'human' as const, id: input.userId };\n const event = closed ? 'vulnerabilityClosed' : 'vulnerabilityObserved';\n const boards = this.#boards(input);\n const context: FactoryVantaRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'vanta', id: ingressId },\n cause: `vanta.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'vanta-vulnerability',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(boards, relatedItem),\n ...rulePhaseField(boards, relatedItem),\n }\n : {}),\n ...withIntakeTarget(boards),\n event,\n vulnerability: alert,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const rule = this.#rules[event];\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await rule(Object.freeze(context)) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(entry, boards, relatedItem ? boardForWorkItem(relatedItem) : undefined);\n return { ...entry };\n });\n }\n } catch (error) {\n outcome = {\n status: 'rejected',\n code: 'rule_error',\n reason: error instanceof Error ? error.message.slice(0, 2_000) : 'Factory Vanta rule failed.',\n };\n }\n if (!decision && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Vanta rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestAlert(input, alert, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachVantaRules(\n context: IntegrationContext,\n): ((input: VantaRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new VantaRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,0BAA0B;;AAGhC,SAAgB,YAAY,UAAmC;CAC7D,OAAO;EAAC;EAAY;EAAS,GAAI,WAAW,CAAC,YAAY,SAAS,YAAY,GAAG,IAAI,CAAC;CAAE;AAC1F;;A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,SAAS;IACrE,OAAO,MAAM;IACb,kBAAkB,MAAM;GAC1B,CAAC;GACD,IAAI,QAAQ,YAAY,CAAC,EAAE,GAAG,OAAO,CAAC;EACxC;EAEA,MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS,EAAE,UAAU,UAAU;GAC/B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAChC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,qCAAqC,UAAU,6BAA6B;GAE9F,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF;AAEA,SAAgB,iBACd,SAC8D;CAC9D,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,WAAW;EAC3B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;CAC1B,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -0,0 +1,29 @@
1
+ import type { MetricsCollector, MetricsLogger } from '../metrics.js';
2
+ /** The subset of `pg.Pool` the collectors read. */
3
+ export interface PoolLike {
4
+ totalCount: number;
5
+ idleCount: number;
6
+ waitingCount: number;
7
+ query(sql: string): Promise<{
8
+ rows: Array<Record<string, unknown>>;
9
+ }>;
10
+ }
11
+ /** `value` when it looks like a `pg.Pool` (e.g. `PostgresStore.pool`, `PgVector.pool`). */
12
+ export declare function asPool(value: unknown): PoolLike | undefined;
13
+ /**
14
+ * Pool usage plus a `SELECT 1` round trip for each Postgres pool. `waiting` above 0 means queries
15
+ * are queued for a connection: the pool is too small or queries hold connections too long.
16
+ * The gauges are read after the probe, so a pool that had closed its idle connections shows the
17
+ * connection the probe just opened; the probe's duration then includes connecting.
18
+ */
19
+ export declare function postgresPoolCollector(pools: Record<string, PoolLike>, timeoutMs: number): MetricsCollector;
20
+ /**
21
+ * Server-wide Postgres stats, collected by one process per deployment. Every tick:
22
+ * `pg_stat_activity` session counts and the age of the longest running query and longest idle
23
+ * transaction. Every `statementsEveryTicks` ticks: the statements that used the most time since the
24
+ * previous sample, from `pg_stat_statements`, written as one log line with their query IDs and
25
+ * timings. Statement text is left out: pg_stat_statements can keep literal values in it, which
26
+ * mustn't reach application logs. Skipped when the extension isn't installed.
27
+ */
28
+ export declare function postgresStatsCollector(pool: PoolLike, timeoutMs: number, statementsEveryTicks: number, getLogger: () => MetricsLogger | undefined): MetricsCollector;
29
+ //# sourceMappingURL=postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../../../src/metrics/collectors/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAGrE,mDAAmD;AACnD,MAAM,WAAW,QAAQ;IACvB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,KAAK,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAA;KAAE,CAAC,CAAC;CACvE;AAED,2FAA2F;AAC3F,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,GAAG,QAAQ,GAAG,SAAS,CAS3D;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,EAAE,MAAM,GAAG,gBAAgB,CAc1G;AA2BD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,QAAQ,EACd,SAAS,EAAE,MAAM,EACjB,oBAAoB,EAAE,MAAM,EAC5B,SAAS,EAAE,MAAM,aAAa,GAAG,SAAS,GACzC,gBAAgB,CAyElB"}
@@ -0,0 +1,121 @@
1
+ import { createProbe, errorText } from "./probe.js";
2
+ // src/metrics/collectors/postgres.ts
3
+ /** `value` when it looks like a `pg.Pool` (e.g. `PostgresStore.pool`, `PgVector.pool`). */
4
+ function asPool(value) {
5
+ if (!value || typeof value !== "object") return void 0;
6
+ const pool = value;
7
+ return typeof pool.totalCount === "number" && typeof pool.idleCount === "number" && typeof pool.waitingCount === "number" && typeof pool.query === "function" ? pool : void 0;
8
+ }
9
+ /**
10
+ * Pool usage plus a `SELECT 1` round trip for each Postgres pool. `waiting` above 0 means queries
11
+ * are queued for a connection: the pool is too small or queries hold connections too long.
12
+ * The gauges are read after the probe, so a pool that had closed its idle connections shows the
13
+ * connection the probe just opened; the probe's duration then includes connecting.
14
+ */
15
+ function postgresPoolCollector(pools, timeoutMs) {
16
+ const probe = createProbe();
17
+ return { async collect(sink) {
18
+ await Promise.all(Object.entries(pools).map(async ([name, pool]) => {
19
+ await probe(sink, `db_${name}`, timeoutMs, () => pool.query("SELECT 1"));
20
+ sink.emit("mastra_factory_db_pool", pool.totalCount, {
21
+ pool: name,
22
+ state: "total"
23
+ });
24
+ sink.emit("mastra_factory_db_pool", pool.idleCount, {
25
+ pool: name,
26
+ state: "idle"
27
+ });
28
+ sink.emit("mastra_factory_db_pool", pool.waitingCount, {
29
+ pool: name,
30
+ state: "waiting"
31
+ });
32
+ }));
33
+ } };
34
+ }
35
+ const ACTIVITY_SQL = `
36
+ SELECT
37
+ count(*) FILTER (WHERE state = 'active') AS active,
38
+ count(*) FILTER (WHERE state = 'idle in transaction') AS idle_in_transaction,
39
+ count(*) FILTER (WHERE wait_event_type = 'Lock') AS waiting_on_lock,
40
+ coalesce(max(extract(epoch FROM now() - query_start)) FILTER (WHERE state = 'active'), 0) AS longest_query_s,
41
+ coalesce(max(extract(epoch FROM now() - xact_start)) FILTER (WHERE state = 'idle in transaction'), 0) AS longest_idle_transaction_s
42
+ FROM pg_stat_activity
43
+ WHERE datname = current_database() AND backend_type = 'client backend' AND pid <> pg_backend_pid()`;
44
+ const STATEMENTS_SQL = `
45
+ SELECT queryid::text AS id, sum(calls) AS calls, sum(total_exec_time) AS total_exec_time
46
+ FROM pg_stat_statements
47
+ WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND queryid IS NOT NULL
48
+ GROUP BY queryid`;
49
+ const SLOW_STATEMENTS_LOGGED = 5;
50
+ /**
51
+ * Server-wide Postgres stats, collected by one process per deployment. Every tick:
52
+ * `pg_stat_activity` session counts and the age of the longest running query and longest idle
53
+ * transaction. Every `statementsEveryTicks` ticks: the statements that used the most time since the
54
+ * previous sample, from `pg_stat_statements`, written as one log line with their query IDs and
55
+ * timings. Statement text is left out: pg_stat_statements can keep literal values in it, which
56
+ * mustn't reach application logs. Skipped when the extension isn't installed.
57
+ */
58
+ function postgresStatsCollector(pool, timeoutMs, statementsEveryTicks, getLogger) {
59
+ const probe = createProbe();
60
+ let tick = 0;
61
+ let previous;
62
+ let failing = false;
63
+ const number = (value) => Number(value ?? 0);
64
+ async function logSlowStatements() {
65
+ const { rows: installed } = await pool.query(`SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements'`);
66
+ if (installed.length === 0) return;
67
+ const { rows } = await pool.query(STATEMENTS_SQL);
68
+ const current = new Map(rows.map((row) => [String(row.id), {
69
+ calls: number(row.calls),
70
+ time: number(row.total_exec_time)
71
+ }]));
72
+ if (previous) {
73
+ const before = previous;
74
+ const slowest = [...current].map(([id, now]) => {
75
+ const then = before.get(id);
76
+ if (!then) return {
77
+ id,
78
+ calls: 0,
79
+ time: 0
80
+ };
81
+ const reset = then.calls > now.calls;
82
+ return {
83
+ id,
84
+ calls: reset ? now.calls : now.calls - then.calls,
85
+ time: reset ? now.time : now.time - then.time
86
+ };
87
+ }).filter((statement) => statement.calls > 0).sort((a, b) => b.time - a.time).slice(0, SLOW_STATEMENTS_LOGGED).map((statement) => ({
88
+ queryId: statement.id,
89
+ calls: statement.calls,
90
+ totalMs: Math.round(statement.time),
91
+ meanMs: Math.round(statement.time / statement.calls * 10) / 10
92
+ }));
93
+ if (slowest.length > 0) getLogger()?.info("[factory:metrics] Slowest Postgres statements since last sample.", { statements: slowest });
94
+ }
95
+ previous = current;
96
+ }
97
+ return { async collect(sink) {
98
+ const sampleStatements = tick % statementsEveryTicks === 0;
99
+ tick++;
100
+ let row;
101
+ const result = await probe(sink, "db_stats", timeoutMs, async () => {
102
+ row = (await pool.query(ACTIVITY_SQL)).rows[0] ?? {};
103
+ });
104
+ if (result.ok && row) {
105
+ sink.emit("mastra_factory_db_sessions", number(row.active), { state: "active" });
106
+ sink.emit("mastra_factory_db_sessions", number(row.idle_in_transaction), { state: "idle_in_transaction" });
107
+ sink.emit("mastra_factory_db_sessions", number(row.waiting_on_lock), { state: "waiting_on_lock" });
108
+ sink.emit("mastra_factory_db_longest_ms", number(row.longest_query_s) * 1e3, { kind: "query" });
109
+ sink.emit("mastra_factory_db_longest_ms", number(row.longest_idle_transaction_s) * 1e3, { kind: "idle_transaction" });
110
+ if (failing) getLogger()?.info("[factory:metrics] Postgres stats sampling recovered.");
111
+ failing = false;
112
+ } else if (!result.ok) {
113
+ if (!failing) getLogger()?.warn("[factory:metrics] Postgres stats sampling failed.", { error: errorText(result.error) });
114
+ failing = true;
115
+ }
116
+ if (sampleStatements) await probe(sink, "db_statements", timeoutMs, logSlowStatements);
117
+ } };
118
+ }
119
+ export { asPool, postgresPoolCollector, postgresStatsCollector };
120
+
121
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.js","names":[],"sources":["../../../src/metrics/collectors/postgres.ts"],"sourcesContent":["import type { MetricsCollector, MetricsLogger } from '../metrics.js';\nimport { createProbe, errorText } from './probe.js';\n\n/** The subset of `pg.Pool` the collectors read. */\nexport interface PoolLike {\n totalCount: number;\n idleCount: number;\n waitingCount: number;\n query(sql: string): Promise<{ rows: Array<Record<string, unknown>> }>;\n}\n\n/** `value` when it looks like a `pg.Pool` (e.g. `PostgresStore.pool`, `PgVector.pool`). */\nexport function asPool(value: unknown): PoolLike | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const pool = value as Partial<PoolLike>;\n return typeof pool.totalCount === 'number' &&\n typeof pool.idleCount === 'number' &&\n typeof pool.waitingCount === 'number' &&\n typeof pool.query === 'function'\n ? (pool as PoolLike)\n : undefined;\n}\n\n/**\n * Pool usage plus a `SELECT 1` round trip for each Postgres pool. `waiting` above 0 means queries\n * are queued for a connection: the pool is too small or queries hold connections too long.\n * The gauges are read after the probe, so a pool that had closed its idle connections shows the\n * connection the probe just opened; the probe's duration then includes connecting.\n */\nexport function postgresPoolCollector(pools: Record<string, PoolLike>, timeoutMs: number): MetricsCollector {\n const probe = createProbe();\n return {\n async collect(sink) {\n await Promise.all(\n Object.entries(pools).map(async ([name, pool]) => {\n await probe(sink, `db_${name}`, timeoutMs, () => pool.query('SELECT 1'));\n sink.emit('mastra_factory_db_pool', pool.totalCount, { pool: name, state: 'total' });\n sink.emit('mastra_factory_db_pool', pool.idleCount, { pool: name, state: 'idle' });\n sink.emit('mastra_factory_db_pool', pool.waitingCount, { pool: name, state: 'waiting' });\n }),\n );\n },\n };\n}\n\n// Sessions of this database, from the server's point of view. Locks and long-open transactions\n// slow every query, and the pool stats can't see them.\nconst ACTIVITY_SQL = `\nSELECT\n count(*) FILTER (WHERE state = 'active') AS active,\n count(*) FILTER (WHERE state = 'idle in transaction') AS idle_in_transaction,\n count(*) FILTER (WHERE wait_event_type = 'Lock') AS waiting_on_lock,\n coalesce(max(extract(epoch FROM now() - query_start)) FILTER (WHERE state = 'active'), 0) AS longest_query_s,\n coalesce(max(extract(epoch FROM now() - xact_start)) FILTER (WHERE state = 'idle in transaction'), 0) AS longest_idle_transaction_s\nFROM pg_stat_activity\nWHERE datname = current_database() AND backend_type = 'client backend' AND pid <> pg_backend_pid()`;\n\n// Lifetime totals of every statement of this database, one row per query ID. pg_stat_statements\n// keeps a row per user (and top-level flag) for the same query ID, so they are summed. Without\n// `pg_read_all_stats`, other users' query IDs read as null; those rows are skipped rather than lumped together. No limit:\n// the slowest are picked from the change since the previous sample, which a statement with a small\n// lifetime total can still lead. The extension caps its rows (`pg_stat_statements.max`, 5000 by default).\nconst STATEMENTS_SQL = `\nSELECT queryid::text AS id, sum(calls) AS calls, sum(total_exec_time) AS total_exec_time\nFROM pg_stat_statements\nWHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database()) AND queryid IS NOT NULL\nGROUP BY queryid`;\n\nconst SLOW_STATEMENTS_LOGGED = 5;\n\n/**\n * Server-wide Postgres stats, collected by one process per deployment. Every tick:\n * `pg_stat_activity` session counts and the age of the longest running query and longest idle\n * transaction. Every `statementsEveryTicks` ticks: the statements that used the most time since the\n * previous sample, from `pg_stat_statements`, written as one log line with their query IDs and\n * timings. Statement text is left out: pg_stat_statements can keep literal values in it, which\n * mustn't reach application logs. Skipped when the extension isn't installed.\n */\nexport function postgresStatsCollector(\n pool: PoolLike,\n timeoutMs: number,\n statementsEveryTicks: number,\n getLogger: () => MetricsLogger | undefined,\n): MetricsCollector {\n const probe = createProbe();\n let tick = 0;\n let previous: Map<string, { calls: number; time: number }> | undefined;\n let failing = false;\n const number = (value: unknown) => Number(value ?? 0);\n\n async function logSlowStatements(): Promise<void> {\n const { rows: installed } = await pool.query(`SELECT 1 FROM pg_extension WHERE extname = 'pg_stat_statements'`);\n if (installed.length === 0) return;\n const { rows } = await pool.query(STATEMENTS_SQL);\n const current = new Map(\n rows.map(row => [String(row.id), { calls: number(row.calls), time: number(row.total_exec_time) }]),\n );\n if (previous) {\n const before = previous;\n const slowest = [...current]\n .map(([id, now]) => {\n const then = before.get(id);\n // Not in the previous sample: no baseline yet (the totals are lifetime), so skip it.\n if (!then) return { id, calls: 0, time: 0 };\n // Fewer calls than before means the stats were reset: everything counted is new.\n const reset = then.calls > now.calls;\n return {\n id,\n calls: reset ? now.calls : now.calls - then.calls,\n time: reset ? now.time : now.time - then.time,\n };\n })\n .filter(statement => statement.calls > 0)\n .sort((a, b) => b.time - a.time)\n .slice(0, SLOW_STATEMENTS_LOGGED)\n .map(statement => ({\n queryId: statement.id,\n calls: statement.calls,\n totalMs: Math.round(statement.time),\n meanMs: Math.round((statement.time / statement.calls) * 10) / 10,\n }));\n if (slowest.length > 0) {\n getLogger()?.info('[factory:metrics] Slowest Postgres statements since last sample.', { statements: slowest });\n }\n }\n previous = current;\n }\n\n return {\n async collect(sink) {\n const sampleStatements = tick % statementsEveryTicks === 0;\n tick++;\n let row: Record<string, unknown> | undefined;\n const result = await probe(sink, 'db_stats', timeoutMs, async () => {\n row = (await pool.query(ACTIVITY_SQL)).rows[0] ?? {};\n });\n if (result.ok && row) {\n sink.emit('mastra_factory_db_sessions', number(row.active), { state: 'active' });\n sink.emit('mastra_factory_db_sessions', number(row.idle_in_transaction), { state: 'idle_in_transaction' });\n sink.emit('mastra_factory_db_sessions', number(row.waiting_on_lock), { state: 'waiting_on_lock' });\n sink.emit('mastra_factory_db_longest_ms', number(row.longest_query_s) * 1000, { kind: 'query' });\n sink.emit('mastra_factory_db_longest_ms', number(row.longest_idle_transaction_s) * 1000, {\n kind: 'idle_transaction',\n });\n if (failing) getLogger()?.info('[factory:metrics] Postgres stats sampling recovered.');\n failing = false;\n } else if (!result.ok) {\n // Log on the transition only; the probe failure counter counts each failure.\n if (!failing)\n getLogger()?.warn('[factory:metrics] Postgres stats sampling failed.', { error: errorText(result.error) });\n failing = true;\n }\n // Its own probe, so a slow pg_stat_statements read never cost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,OAAO,IAAI,MAAM,GAAG,EAAE,OAAO,SAAS,CAAC;GAC/E,KAAK,KAAK,8BAA8B,OAAO,IAAI,mBAAmB,GAAG,EAAE,OAAO,sBAAsB,CAAC;GACzG,KAAK,KAAK,8BAA8B,OAAO,IAAI,eAAe,GAAG,EAAE,OAAO,kBAAkB,CAAC;GACjG,KAAK,KAAK,gCAAgC,OAAO,IAAI,eAAe,IAAI,KAAM,EAAE,MAAM,QAAQ,CAAC;GAC/F,KAAK,KAAK,gCAAgC,OAAO,IAAI,0BAA0B,IAAI,KAAM,EACvF,MAAM,mBACR,CAAC;GACD,IAAI,SAAS,UAAU,CAAC,EAAE,KAAK,sDAAsD;GACrF,UAAU;EACZ,OAAO,IAAI,CAAC,OAAO,IAAI;GAErB,IAAI,CAAC,SACH,UAAU,CAAC,EAAE,KAAK,qDAAqD,EAAE,OAAO,UAAU,OAAO,KAAK,EAAE,CAAC;GAC3G,UAAU;EACZ;EAEA,IAAI,kBAAkB,MAAM,MAAM,MAAM,iBAAiB,WAAW,iBAAiB;CACvF,EACF;AACF"}
@@ -0,0 +1,22 @@
1
+ import type { MetricSink } from '../metrics.js';
2
+ export declare class ProbeTimeout extends Error {
3
+ }
4
+ export declare function withTimeout<T>(timeoutMs: number, run: () => Promise<T>): Promise<T>;
5
+ export type ProbeResult = {
6
+ ok: true;
7
+ } | {
8
+ ok: false;
9
+ error: unknown;
10
+ };
11
+ export type Probe = (sink: MetricSink, component: string, timeoutMs: number, run: () => Promise<unknown>) => Promise<ProbeResult>;
12
+ /**
13
+ * A probe for one collector. It times `run` and emits `mastra_factory_probe_duration_ms{component}`
14
+ * on success (only for the components in {@link TIMED_COMPONENTS}), or
15
+ * `mastra_factory_probe_failures_total{component,reason}` when it throws or exceeds
16
+ * `timeoutMs`. The timeout only stops waiting, it can't cancel the call, so a component whose call
17
+ * hasn't settled isn't checked again until it returns: a hung dependency holds at most one call
18
+ * (and one pooled connection) per component. Each collector has its own guard.
19
+ */
20
+ export declare function createProbe(): Probe;
21
+ export declare function errorText(error: unknown): string;
22
+ //# sourceMappingURL=probe.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"probe.d.ts","sourceRoot":"","sources":["../../../src/metrics/collectors/probe.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAEhD,qBAAa,YAAa,SAAQ,KAAK;CAAG;AAE1C,wBAAsB,WAAW,CAAC,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAYzF;AAED,MAAM,MAAM,WAAW,GAAG;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,OAAO,CAAA;CAAE,CAAC;AAQvE,MAAM,MAAM,KAAK,GAAG,CAClB,IAAI,EAAE,UAAU,EAChB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,GAAG,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,KACxB,OAAO,CAAC,WAAW,CAAC,CAAC;AAE1B;;;;;;;GAOG;AACH,wBAAgB,WAAW,IAAI,KAAK,CA0BnC;AAED,wBAAgB,SAAS,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAGhD"}
@@ -0,0 +1,69 @@
1
+ // src/metrics/collectors/probe.ts
2
+ var ProbeTimeout = class extends Error {};
3
+ async function withTimeout(timeoutMs, run) {
4
+ let timer;
5
+ try {
6
+ return await Promise.race([run(), new Promise((_, reject) => {
7
+ timer = setTimeout(() => reject(new ProbeTimeout()), timeoutMs);
8
+ })]);
9
+ } finally {
10
+ clearTimeout(timer);
11
+ }
12
+ }
13
+ /**
14
+ * Components whose round trip is its own signal. The stats probes run over the same pool or
15
+ * Redis client, so their durations would repeat these; only their failures are sent.
16
+ */
17
+ const TIMED_COMPONENTS = /* @__PURE__ */ new Set([
18
+ "db_store",
19
+ "db_vector",
20
+ "redis"
21
+ ]);
22
+ /**
23
+ * A probe for one collector. It times `run` and emits `mastra_factory_probe_duration_ms{component}`
24
+ * on success (only for the components in {@link TIMED_COMPONENTS}), or
25
+ * `mastra_factory_probe_failures_total{component,reason}` when it throws or exceeds
26
+ * `timeoutMs`. The timeout only stops waiting, it can't cancel the call, so a component whose call
27
+ * hasn't settled isn't checked again until it returns: a hung dependency holds at most one call
28
+ * (and one pooled connection) per component. Each collector has its own guard.
29
+ */
30
+ function createProbe() {
31
+ const stillRunning = /* @__PURE__ */ new Set();
32
+ return async (sink, component, timeoutMs, run) => {
33
+ const timed = TIMED_COMPONENTS.has(component);
34
+ if (stillRunning.has(component)) {
35
+ sink.emit("mastra_factory_probe_failures_total", 1, {
36
+ component,
37
+ reason: "timeout"
38
+ });
39
+ return {
40
+ ok: false,
41
+ error: new ProbeTimeout()
42
+ };
43
+ }
44
+ const start = performance.now();
45
+ stillRunning.add(component);
46
+ const call = Promise.resolve().then(run).finally(() => stillRunning.delete(component));
47
+ try {
48
+ await withTimeout(timeoutMs, () => call);
49
+ if (timed) sink.emit("mastra_factory_probe_duration_ms", performance.now() - start, { component });
50
+ return { ok: true };
51
+ } catch (error) {
52
+ sink.emit("mastra_factory_probe_failures_total", 1, {
53
+ component,
54
+ reason: error instanceof ProbeTimeout ? "timeout" : "error"
55
+ });
56
+ return {
57
+ ok: false,
58
+ error
59
+ };
60
+ }
61
+ };
62
+ }
63
+ function errorText(error) {
64
+ if (error instanceof ProbeTimeout) return "timeout";
65
+ return error instanceof Error ? error.message : String(error);
66
+ }
67
+ export { ProbeTimeout, createProbe, errorText, withTimeout };
68
+
69
+ //# sourceMappingURL=probe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"probe.js","names":[],"sources":["../../../src/metrics/collectors/probe.ts"],"sourcesContent":["import type { MetricSink } from '../metrics.js';\n\nexport class ProbeTimeout extends Error {}\n\nexport async function withTimeout<T>(timeoutMs: number, run: () => Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n run(),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new ProbeTimeout()), timeoutMs);\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport type ProbeResult = { ok: true } | { ok: false; error: unknown };\n\n/**\n * Components whose round trip is its own signal. The stats probes run over the same pool or\n * Redis client, so their durations would repeat these; only their failures are sent.\n */\nconst TIMED_COMPONENTS = new Set(['db_store', 'db_vector', 'redis']);\n\nexport type Probe = (\n sink: MetricSink,\n component: string,\n timeoutMs: number,\n run: () => Promise<unknown>,\n) => Promise<ProbeResult>;\n\n/**\n * A probe for one collector. It times `run` and emits `mastra_factory_probe_duration_ms{component}`\n * on success (only for the components in {@link TIMED_COMPONENTS}), or\n * `mastra_factory_probe_failures_total{component,reason}` when it throws or exceeds\n * `timeoutMs`. The timeout only stops waiting, it can't cancel the call, so a component whose call\n * hasn't settled isn't checked again until it returns: a hung dependency holds at most one call\n * (and one pooled connection) per component. Each collector has its own guard.\n */\nexport function createProbe(): Probe {\n const stillRunning = new Set<string>();\n return async (sink, component, timeoutMs, run) => {\n const timed = TIMED_COMPONENTS.has(component);\n if (stillRunning.has(component)) {\n sink.emit('mastra_factory_probe_failures_total', 1, { component, reason: 'timeout' });\n return { ok: false, error: new ProbeTimeout() };\n }\n const start = performance.now();\n stillRunning.add(component);\n // A synchronous throw becomes a rejection, so the component is always released.\n const call = Promise.resolve()\n .then(run)\n .finally(() => stillRunning.delete(component));\n try {\n await withTimeout(timeoutMs, () => call);\n if (timed) sink.emit('mastra_factory_probe_duration_ms', performance.now() - start, { component });\n return { ok: true };\n } catch (error) {\n sink.emit('mastra_factory_probe_failures_total', 1, {\n component,\n reason: error instanceof ProbeTimeout ? 'timeout' : 'error',\n });\n return { ok: false, error };\n }\n };\n}\n\nexport function errorText(error: unknown): string {\n if (error instanceof ProbeTimeout) return 'timeout';\n return error instanceof Error ? error.message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AQ,MAAM,UAAU,OAAO,KAAK;AAC9D"}
@@ -0,0 +1,13 @@
1
+ import type { MetricsCollector } from '../metrics.js';
2
+ /**
3
+ * Cores this process can use: the container's CPU limit when one is set (cgroup v2 `cpu.max`, or
4
+ * v1 `cpu.cfs_quota_us` / `cpu.cfs_period_us`), otherwise the cores the machine reports.
5
+ */
6
+ export declare function cpuLimitCores(): number;
7
+ /**
8
+ * Event-loop delay and utilization, memory against the heap limit, CPU against the CPU limit, and
9
+ * uptime of this Node process. Each major or incremental GC pause is passed to `onGcPause` as it
10
+ * happens, to be aggregated per interval.
11
+ */
12
+ export declare function processCollector(onGcPause?: (kind: string, ms: number) => void): MetricsCollector;
13
+ //# sourceMappingURL=process.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"process.d.ts","sourceRoot":"","sources":["../../../src/metrics/collectors/process.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAYtD;;;GAGG;AACH,wBAAgB,aAAa,IAAI,MAAM,CAOtC;AASD;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,KAAK,IAAI,GAAG,gBAAgB,CA0DjG"}