@mastra/factory 0.29.0-alpha.0 → 0.29.0-alpha.1

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 (237) hide show
  1. package/README.md +20 -4
  2. package/dist/board-changes.d.ts +16 -0
  3. package/dist/board-changes.d.ts.map +1 -0
  4. package/dist/board-changes.js +40 -0
  5. package/dist/board-changes.js.map +1 -0
  6. package/dist/boards/index.js +2 -1
  7. package/dist/boards/semantics.d.ts +1 -3
  8. package/dist/boards/semantics.d.ts.map +1 -1
  9. package/dist/boards/semantics.js +1 -5
  10. package/dist/boards/semantics.js.map +1 -1
  11. package/dist/factory.d.ts +4 -0
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +51 -3
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/base.d.ts +9 -0
  16. package/dist/integrations/base.d.ts.map +1 -1
  17. package/dist/integrations/github/pull-request-source.js +2 -1
  18. package/dist/integrations/github/pull-request-source.js.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +1 -1
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/rules.d.ts +5 -2
  22. package/dist/integrations/github/rules.d.ts.map +1 -1
  23. package/dist/integrations/github/rules.js +16 -13
  24. package/dist/integrations/github/rules.js.map +1 -1
  25. package/dist/integrations/github/sandbox.js +2 -2
  26. package/dist/integrations/github/sandbox.js.map +1 -1
  27. package/dist/integrations/gitlab/default-rules.js +2 -1
  28. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  29. package/dist/integrations/gitlab/discovery.d.ts +16 -0
  30. package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
  31. package/dist/integrations/gitlab/discovery.js +107 -0
  32. package/dist/integrations/gitlab/discovery.js.map +1 -0
  33. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/integration.js +1 -2
  35. package/dist/integrations/gitlab/integration.js.map +1 -1
  36. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/issue-reconciler.js +1 -0
  38. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  39. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  40. package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
  41. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  42. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/reconciler.js +4 -2
  44. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  45. package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
  46. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  47. package/dist/integrations/gitlab/reconciliation-config.js +2 -8
  48. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  49. package/dist/integrations/gitlab/routes.d.ts +17 -0
  50. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  51. package/dist/integrations/gitlab/routes.js +28 -22
  52. package/dist/integrations/gitlab/routes.js.map +1 -1
  53. package/dist/integrations/gitlab/rules.d.ts +10 -4
  54. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  55. package/dist/integrations/gitlab/rules.js +32 -8
  56. package/dist/integrations/gitlab/rules.js.map +1 -1
  57. package/dist/integrations/incidentio/integration.d.ts +2 -1
  58. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  59. package/dist/integrations/incidentio/integration.js +7 -7
  60. package/dist/integrations/incidentio/integration.js.map +1 -1
  61. package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
  62. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  63. package/dist/integrations/incidentio/issue-reconciler.js +36 -1
  64. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  65. package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
  66. package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
  67. package/dist/integrations/incidentio/reconciliation-config.js +2 -5
  68. package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
  69. package/dist/integrations/incidentio/routes.d.ts +24 -8
  70. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  71. package/dist/integrations/incidentio/routes.js +33 -35
  72. package/dist/integrations/incidentio/routes.js.map +1 -1
  73. package/dist/integrations/incidentio/rules.d.ts +0 -4
  74. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  75. package/dist/integrations/incidentio/rules.js +17 -14
  76. package/dist/integrations/incidentio/rules.js.map +1 -1
  77. package/dist/integrations/intake-discovery.d.ts +44 -0
  78. package/dist/integrations/intake-discovery.d.ts.map +1 -0
  79. package/dist/integrations/intake-discovery.js +60 -0
  80. package/dist/integrations/intake-discovery.js.map +1 -0
  81. package/dist/integrations/issue-reconcile-worker.js +1 -1
  82. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  83. package/dist/integrations/issue-reconciler.d.ts +7 -0
  84. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  85. package/dist/integrations/issue-reconciler.js +47 -12
  86. package/dist/integrations/issue-reconciler.js.map +1 -1
  87. package/dist/integrations/jira/integration.d.ts +3 -2
  88. package/dist/integrations/jira/integration.d.ts.map +1 -1
  89. package/dist/integrations/jira/integration.js +5 -7
  90. package/dist/integrations/jira/integration.js.map +1 -1
  91. package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
  92. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/jira/issue-reconciler.js +34 -1
  94. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
  96. package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
  97. package/dist/integrations/jira/reconciliation-config.js +2 -5
  98. package/dist/integrations/jira/reconciliation-config.js.map +1 -1
  99. package/dist/integrations/jira/routes.d.ts +0 -7
  100. package/dist/integrations/jira/routes.d.ts.map +1 -1
  101. package/dist/integrations/jira/routes.js +2 -12
  102. package/dist/integrations/jira/routes.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts +0 -4
  104. package/dist/integrations/jira/rules.d.ts.map +1 -1
  105. package/dist/integrations/jira/rules.js +3 -13
  106. package/dist/integrations/jira/rules.js.map +1 -1
  107. package/dist/integrations/kept-cards.d.ts +49 -0
  108. package/dist/integrations/kept-cards.d.ts.map +1 -0
  109. package/dist/integrations/kept-cards.js +97 -0
  110. package/dist/integrations/kept-cards.js.map +1 -0
  111. package/dist/integrations/linear/intake-discovery.d.ts +34 -0
  112. package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
  113. package/dist/integrations/linear/intake-discovery.js +112 -0
  114. package/dist/integrations/linear/intake-discovery.js.map +1 -0
  115. package/dist/integrations/linear/integration.d.ts.map +1 -1
  116. package/dist/integrations/linear/integration.js +1 -4
  117. package/dist/integrations/linear/integration.js.map +1 -1
  118. package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
  119. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  120. package/dist/integrations/linear/issue-reconciler.js +24 -20
  121. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  122. package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
  123. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  124. package/dist/integrations/linear/reconciliation-config.js +2 -8
  125. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  126. package/dist/integrations/linear/routes.d.ts +0 -2
  127. package/dist/integrations/linear/routes.d.ts.map +1 -1
  128. package/dist/integrations/linear/routes.js +3 -9
  129. package/dist/integrations/linear/routes.js.map +1 -1
  130. package/dist/integrations/platform/api-client.d.ts +2 -0
  131. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  132. package/dist/integrations/platform/api-client.js +6 -1
  133. package/dist/integrations/platform/api-client.js.map +1 -1
  134. package/dist/integrations/platform/connect/routes.js +4 -1
  135. package/dist/integrations/platform/connect/routes.js.map +1 -1
  136. package/dist/integrations/platform/github/event-worker.d.ts +12 -0
  137. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  138. package/dist/integrations/platform/github/event-worker.js +56 -5
  139. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  140. package/dist/integrations/platform/github/integration.d.ts +1 -0
  141. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  142. package/dist/integrations/platform/github/integration.js +8 -3
  143. package/dist/integrations/platform/github/integration.js.map +1 -1
  144. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  145. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  146. package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
  147. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  148. package/dist/integrations/platform/incidentio/integration.js +7 -7
  149. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  150. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  151. package/dist/integrations/platform/jira/integration.js +4 -7
  152. package/dist/integrations/platform/jira/integration.js.map +1 -1
  153. package/dist/integrations/platform/jira/routes.d.ts +0 -7
  154. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  155. package/dist/integrations/platform/jira/routes.js +2 -12
  156. package/dist/integrations/platform/jira/routes.js.map +1 -1
  157. package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
  158. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  159. package/dist/integrations/platform/linear/event-worker.js +1 -1
  160. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  161. package/dist/integrations/platform/linear/integration.d.ts +1 -0
  162. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  163. package/dist/integrations/platform/linear/integration.js +7 -7
  164. package/dist/integrations/platform/linear/integration.js.map +1 -1
  165. package/dist/integrations/platform/vanta/integration.d.ts +7 -2
  166. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  167. package/dist/integrations/platform/vanta/integration.js +22 -6
  168. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  169. package/dist/integrations/reconciliation-config.d.ts +0 -1
  170. package/dist/integrations/reconciliation-config.d.ts.map +1 -1
  171. package/dist/integrations/reconciliation-config.js +1 -8
  172. package/dist/integrations/reconciliation-config.js.map +1 -1
  173. package/dist/integrations/slack/channel-reply-processor.js +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  175. package/dist/integrations/startup-summary.d.ts +8 -0
  176. package/dist/integrations/startup-summary.d.ts.map +1 -0
  177. package/dist/integrations/startup-summary.js +36 -0
  178. package/dist/integrations/startup-summary.js.map +1 -0
  179. package/dist/integrations/vanta/sync.d.ts +9 -5
  180. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  181. package/dist/integrations/vanta/sync.js +16 -8
  182. package/dist/integrations/vanta/sync.js.map +1 -1
  183. package/dist/linked-repositories-changed.d.ts +14 -0
  184. package/dist/linked-repositories-changed.d.ts.map +1 -0
  185. package/dist/linked-repositories-changed.js +48 -0
  186. package/dist/linked-repositories-changed.js.map +1 -0
  187. package/dist/routes/contracts.d.ts +117 -0
  188. package/dist/routes/contracts.d.ts.map +1 -1
  189. package/dist/routes/contracts.js +44 -1
  190. package/dist/routes/contracts.js.map +1 -1
  191. package/dist/routes/run-queue.d.ts +17 -0
  192. package/dist/routes/run-queue.d.ts.map +1 -0
  193. package/dist/routes/run-queue.js +69 -0
  194. package/dist/routes/run-queue.js.map +1 -0
  195. package/dist/routes/surface.d.ts +8 -0
  196. package/dist/routes/surface.d.ts.map +1 -1
  197. package/dist/routes/surface.js +4 -2
  198. package/dist/routes/surface.js.map +1 -1
  199. package/dist/routes/work-item-selection.d.ts +4 -1
  200. package/dist/routes/work-item-selection.d.ts.map +1 -1
  201. package/dist/routes/work-item-selection.js +7 -2
  202. package/dist/routes/work-item-selection.js.map +1 -1
  203. package/dist/routes/work-items.d.ts +5 -0
  204. package/dist/routes/work-items.d.ts.map +1 -1
  205. package/dist/routes/work-items.js +17 -0
  206. package/dist/routes/work-items.js.map +1 -1
  207. package/dist/rules/dispatcher.d.ts +13 -1
  208. package/dist/rules/dispatcher.d.ts.map +1 -1
  209. package/dist/rules/dispatcher.js +9 -2
  210. package/dist/rules/dispatcher.js.map +1 -1
  211. package/dist/rules/review-source-tool.js +2 -1
  212. package/dist/rules/review-source-tool.js.map +1 -1
  213. package/dist/storage/domains/projects/base.d.ts +2 -0
  214. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  215. package/dist/storage/domains/projects/base.js +13 -1
  216. package/dist/storage/domains/projects/base.js.map +1 -1
  217. package/dist/storage/domains/source-control/base.d.ts +32 -0
  218. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  219. package/dist/storage/domains/source-control/base.js +54 -4
  220. package/dist/storage/domains/source-control/base.js.map +1 -1
  221. package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
  222. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  223. package/dist/storage/domains/source-control/inmemory.js +17 -0
  224. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  225. package/dist/storage/domains/work-items/base.d.ts +1 -0
  226. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  227. package/dist/storage/domains/work-items/base.js +9 -0
  228. package/dist/storage/domains/work-items/base.js.map +1 -1
  229. package/dist/timing.d.ts +8 -1
  230. package/dist/timing.d.ts.map +1 -1
  231. package/dist/timing.js +10 -2
  232. package/dist/timing.js.map +1 -1
  233. package/dist/work-items/source-external-id.d.ts +4 -0
  234. package/dist/work-items/source-external-id.d.ts.map +1 -0
  235. package/dist/work-items/source-external-id.js +9 -0
  236. package/dist/work-items/source-external-id.js.map +1 -0
  237. package/package.json +8 -8
@@ -2,27 +2,14 @@ import { workItemPhaseSemantics } from "../../boards/semantics.js";
2
2
  import "../../boards/index.js";
3
3
  import { toBoardSource } from "../../boards/project-boards.js";
4
4
  import { createIssueReconciler } from "../issue-reconciler.js";
5
+ import { createLinearIntakeDiscovery, issueToIngress } from "./intake-discovery.js";
5
6
  import { LinearRules } from "./rules.js";
6
7
  // src/integrations/linear/issue-reconciler.ts
7
- function issueToIngress(issue) {
8
- return {
9
- id: issue.id,
10
- identifier: issue.identifier,
11
- title: issue.title,
12
- url: issue.url,
13
- state: issue.state ?? "",
14
- stateType: issue.stateType ?? "",
15
- priorityLabel: issue.priority ?? "",
16
- assignee: issue.assignee ?? null,
17
- creator: issue.author ?? null,
18
- team: issue.source ?? null,
19
- labels: [...issue.labels ?? []],
20
- sourceId: issue.sourceId,
21
- projectId: issue.projectId,
22
- createdAt: issue.createdAt,
23
- updatedAt: issue.updatedAt
24
- };
25
- }
8
+ /**
9
+ * One Linear sweep: refresh carded issues (metadata, closes), then list every
10
+ * project's bound sources so issues nobody has carded yet get their card.
11
+ * Linear sends Factory no webhooks, so this is the only first-sight path.
12
+ */
26
13
  function attachLinearIssueReconciler(linear, context) {
27
14
  if (!context.runtime || !linear.intake.resolveIntakeDispatch) return void 0;
28
15
  const boards = context.runtime.boards;
@@ -33,11 +20,12 @@ function attachLinearIssueReconciler(linear, context) {
33
20
  boards,
34
21
  linearRules: linear.rules
35
22
  });
36
- return createIssueReconciler({
23
+ const reconcile = createIssueReconciler({
37
24
  integrationId: "linear",
38
25
  intake: linear.intake,
39
26
  projects: context.storage.projects,
40
27
  storage: context.runtime.workItems,
28
+ ...context.runtime.keptCards ? { cards: context.runtime.keptCards } : {},
41
29
  isTerminal: (item) => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === "terminal",
42
30
  issueId: (item) => {
43
31
  const issueId = item.workItem.metadata?.linearIssueId;
@@ -67,6 +55,22 @@ function attachLinearIssueReconciler(linear, context) {
67
55
  });
68
56
  }
69
57
  });
58
+ const discover = createLinearIntakeDiscovery({
59
+ linear,
60
+ intake: context.storage.intake,
61
+ projects: context.storage.projects,
62
+ rules
63
+ });
64
+ return async () => {
65
+ const reconciled = await reconcile();
66
+ const discovered = await discover();
67
+ return {
68
+ ...reconciled,
69
+ observed: discovered.observed,
70
+ failed: reconciled.failed + discovered.failed,
71
+ errors: [...reconciled.errors, ...discovered.errors]
72
+ };
73
+ };
70
74
  }
71
75
  export { attachLinearIssueReconciler };
72
76
 
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/linear/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearRules } from './rules.js';\nimport type { LinearIssueIngress } from './rules.js';\n\nexport type LinearIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(issue: import('../../capabilities/intake.js').IntakeIssue): LinearIssueIngress {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n creator: issue.author ?? null,\n team: issue.source ?? null,\n labels: [...(issue.labels ?? [])],\n sourceId: issue.sourceId,\n projectId: issue.projectId,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nexport function attachLinearIssueReconciler(\n linear: Pick<LinearIntegration, 'intake' | 'rules'>,\n context: Pick<IntegrationContext, 'runtime'> & {\n storage: Pick<IntegrationContext['storage'], 'projects'>;\n },\n): LinearIssueReconciler | undefined {\n if (!context.runtime || !linear.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n linearRules: linear.rules,\n });\n\n return createIssueReconciler({\n integrationId: 'linear',\n intake: linear.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => {\n const issueId = item.workItem.metadata?.linearIssueId;\n return typeof issueId === 'string' && issueId.length > 0 ? issueId : undefined;\n },\n metadata: (_item, issue) => ({\n linearIssueId: issue.id,\n // Persist explicit removal too; omitting the key would retain stale membership.\n linearProjectId: issue.projectId ?? null,\n identifier: issue.identifier,\n linearState: issue.state,\n linearStateType: issue.stateType,\n linearPriority: issue.priority,\n linearAssignee: issue.assignee,\n linearCreator: issue.author,\n linearTeam: issue.source,\n assignee: issue.assignee,\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(issue)],\n });\n },\n });\n}\n"],"mappings":";;;;;;AAWA,SAAS,eAAe,OAA+E;CACrG,OAAO;EACL,IAAI,MAAM;EACV,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW,MAAM,aAAa;EAC9B,eAAe,MAAM,YAAY;EACjC,UAAU,MAAM,YAAY;EAC5B,SAAS,MAAM,UAAU;EACzB,MAAM,MAAM,UAAU;EACtB,QAAQ,CAAC,GAAI,MAAM,UAAU,CAAC,CAAE;EAChC,UAAU,MAAM;EAChB,WAAW,MAAM;EACjB,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF;AAEA,SAAgB,4BACd,QACA,SAGmC;CACnC,IAAI,CAAC,QAAQ,WAAW,CAAC,OAAO,OAAO,uBAAuB,OAAO,KAAA;CACrE,MAAM,SAAS,QAAQ,QAAQ;CAE/B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B;EACA,aAAa,OAAO;CACtB,CAAC;CAED,OAAO,sBAAsB;EAC3B,eAAe;EACf,QAAQ,OAAO;EACf,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,aAAY,SAAQ,uBAAuB,cAAc,MAAM,CAAC,CAAC,WAAW,IAAI,GAAG,IAAI,CAAC,EAAE,SAAS;EACnG,UAAS,SAAQ;GACf,MAAM,UAAU,KAAK,SAAS,UAAU;GACxC,OAAO,OAAO,YAAY,YAAY,QAAQ,SAAS,IAAI,UAAU,KAAA;EACvE;EACA,WAAW,OAAO,WAAW;GAC3B,eAAe,MAAM;GAErB,iBAAiB,MAAM,aAAa;GACpC,YAAY,MAAM;GAClB,aAAa,MAAM;GACnB,iBAAiB,MAAM;GACvB,gBAAgB,MAAM;GACtB,gBAAgB,MAAM;GACtB,eAAe,MAAM;GACrB,YAAY,MAAM;GAClB,UAAU,MAAM;GAChB,SAAS,MAAM;GACf,QAAQ,MAAM;GACd,QAAQ,MAAM,UAAU,CAAC;EAC3B;EACA,UAAU,OAAO,MAAM,OAAO,YAAY;GACxC,MAAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,CAAC;GAChC,CAAC;EACH;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/linear/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconcileSummary } from '../issue-reconciler.js';\nimport { createLinearIntakeDiscovery, issueToIngress } from './intake-discovery.js';\nimport type { LinearIntegration } from './integration.js';\nimport { LinearRules } from './rules.js';\n\nexport type LinearIssueReconcileSummary = IssueReconcileSummary & {\n /** Active issues on bound sources replayed through the Linear rules (first sight creates the card). */\n observed: number;\n};\n\nexport type LinearIssueReconciler = () => Promise<LinearIssueReconcileSummary>;\n\n/**\n * One Linear sweep: refresh carded issues (metadata, closes), then list every\n * project's bound sources so issues nobody has carded yet get their card.\n * Linear sends Factory no webhooks, so this is the only first-sight path.\n */\nexport function attachLinearIssueReconciler(\n linear: Pick<LinearIntegration, 'intake' | 'rules' | 'loadConnection' | 'getFreshAccessToken'>,\n context: Pick<IntegrationContext, 'runtime'> & {\n storage: Pick<IntegrationContext['storage'], 'projects' | 'intake'>;\n },\n): LinearIssueReconciler | undefined {\n if (!context.runtime || !linear.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n linearRules: linear.rules,\n });\n\n const reconcile = createIssueReconciler({\n integrationId: 'linear',\n intake: linear.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n ...(context.runtime.keptCards ? { cards: context.runtime.keptCards } : {}),\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => {\n const issueId = item.workItem.metadata?.linearIssueId;\n return typeof issueId === 'string' && issueId.length > 0 ? issueId : undefined;\n },\n metadata: (_item, issue) => ({\n linearIssueId: issue.id,\n // Persist explicit removal too; omitting the key would retain stale membership.\n linearProjectId: issue.projectId ?? null,\n identifier: issue.identifier,\n linearState: issue.state,\n linearStateType: issue.stateType,\n linearPriority: issue.priority,\n linearAssignee: issue.assignee,\n linearCreator: issue.author,\n linearTeam: issue.source,\n assignee: issue.assignee,\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(issue)],\n });\n },\n });\n\n const discover = createLinearIntakeDiscovery({\n linear,\n intake: context.storage.intake,\n projects: context.storage.projects,\n rules,\n });\n\n return async () => {\n const reconciled = await reconcile();\n const discovered = await discover();\n return {\n ...reconciled,\n observed: discovered.observed,\n failed: reconciled.failed + discovered.failed,\n errors: [...reconciled.errors, ...discovered.errors],\n };\n };\n}\n"],"mapp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EACxB,UAAU,QAAQ,QAAQ;EAC1B;CACF,CAAC;CAED,OAAO,YAAY;EACjB,MAAM,aAAa,MAAM,UAAU;EACnC,MAAM,aAAa,MAAM,SAAS;EAClC,OAAO;GACL,GAAG;GACH,UAAU,WAAW;GACrB,QAAQ,WAAW,SAAS,WAAW;GACvC,QAAQ,CAAC,GAAG,WAAW,QAAQ,GAAG,WAAW,MAAM;EACrD;CACF;AACF"}
@@ -1,3 +1,2 @@
1
- export declare function linearIssueReconciliationEnabled(): boolean;
2
1
  export declare function linearIssueReconciliationInterval(): number | undefined;
3
2
  //# sourceMappingURL=reconciliation-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/reconciliation-config.ts"],"names":[],"mappings":"AAyBA,wBAAgB,gCAAgC,IAAI,OAAO,CAO1D;AAED,wBAAgB,iCAAiC,IAAI,MAAM,GAAG,SAAS,CAWtE"}
1
+ {"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/reconciliation-config.ts"],"names":[],"mappings":"AAYA,wBAAgB,iCAAiC,IAAI,MAAM,GAAG,SAAS,CAWtE"}
@@ -1,20 +1,14 @@
1
- import { optionalBoolean, optionalPositiveInteger } from "../reconciliation-config.js";
1
+ import { optionalPositiveInteger } from "../reconciliation-config.js";
2
2
  // src/integrations/linear/reconciliation-config.ts
3
3
  const RECONCILIATION_LABEL = "Linear reconciliation";
4
- function reconciliationEnabled(childName, childValue, legacyName, legacyValue) {
5
- return optionalBoolean(childName, childValue, RECONCILIATION_LABEL) ?? optionalBoolean(legacyName, legacyValue, RECONCILIATION_LABEL) ?? true;
6
- }
7
4
  function optionalPositiveInterval(name, value) {
8
5
  const interval = optionalPositiveInteger(value);
9
6
  if (value?.trim() && interval === void 0) console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);
10
7
  return interval;
11
8
  }
12
- function linearIssueReconciliationEnabled() {
13
- return reconciliationEnabled("MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED", process.env.MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED, "MASTRACODE_LINEAR_RECONCILE_ENABLED", process.env.MASTRACODE_LINEAR_RECONCILE_ENABLED);
14
- }
15
9
  function linearIssueReconciliationInterval() {
16
10
  return optionalPositiveInterval("MASTRACODE_LINEAR_ISSUE_RECONCILE_INTERVAL_MS", process.env.MASTRACODE_LINEAR_ISSUE_RECONCILE_INTERVAL_MS) ?? optionalPositiveInterval("MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS", process.env.MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS);
17
11
  }
18
- export { linearIssueReconciliationEnabled, linearIssueReconciliationInterval };
12
+ export { linearIssueReconciliationInterval };
19
13
 
20
14
  //# sourceMappingURL=reconciliation-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconciliation-config.js","names":[],"sources":["../../../src/integrations/linear/reconciliation-config.ts"],"sourcesContent":["import { optionalBoolean, optionalPositiveInteger } from '../reconciliation-config.js';\n\nconst RECONCILIATION_LABEL = 'Linear reconciliation';\n\nfunction reconciliationEnabled(\n childName: string,\n childValue: string | undefined,\n legacyName: string,\n legacyValue: string | undefined,\n): boolean {\n return (\n optionalBoolean(childName, childValue, RECONCILIATION_LABEL) ??\n optionalBoolean(legacyName, legacyValue, RECONCILIATION_LABEL) ??\n true\n );\n}\n\nfunction optionalPositiveInterval(name: string, value: string | undefined): number | undefined {\n const interval = optionalPositiveInteger(value);\n if (value?.trim() && interval === undefined) {\n console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);\n }\n return interval;\n}\n\nexport function linearIssueReconciliationEnabled(): boolean {\n return reconciliationEnabled(\n 'MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED',\n process.env.MASTRACODE_LINEAR_ISSUE_RECONCILE_ENABLED,\n 'MASTRACODE_LINEAR_RECONCILE_ENABLED',\n process.env.MASTRACODE_LINEAR_RECONCILE_ENABLED,\n );\n}\n\nexport function linearIssueReconciliationInterval(): number | undefined {\n return (\n optionalPositiveInterval(\n 'MASTRACODE_LINEAR_ISSUE_RECONCILE_INTERVAL_MS',\n process.env.MASTRACODE_LINEAR_ISSUE_RECONCILE_INTERVAL_MS,\n ) ??\n optionalPositiveInterval(\n 'MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS',\n process.env.MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS,\n )\n );\n}\n"],"mappings":";;AAEA,MAAM,uBAAuB;AAE7B,SAAS,sBACP,WACA,YACA,YACA,aACS;CACT,OACE,gBAAgB,WAAW,YAAY,oBAAoB,KAC3D,gBAAgB,YAAY,aAAa,oBAAoB,KAC7D;AAEJ;AAEA,SAAS,yBAAyB,MAAc,OAA+C;CAC7F,MAAM,WAAW,wBAAwB,KAAK;CAC9C,IAAI,OAAO,KAAK,KAAK,aAAa,KAAA,GAChC,QAAQ,KAAK,IAAI,qBAAqB,IAAI,KAAK,wCAAwC,KAAK,UAAU,KAAK,EAAE,EAAE;CAEjH,OAAO;AACT;AAEA,SAAgB,mCAA4C;CAC1D,OAAO,sBACL,6CACA,QAAQ,IAAI,2CACZ,uCACA,QAAQ,IAAI,mCACd;AACF;AAEA,SAAgB,oCAAwD;CACtE,OACE,yBACE,iDACA,QAAQ,IAAI,6CACd,KACA,yBACE,2CACA,QAAQ,IAAI,uCACd;AAEJ"}
1
+ {"version":3,"file":"reconciliation-config.js","names":[],"sources":["../../../src/integrations/linear/reconciliation-config.ts"],"sourcesContent":["import { optionalPositiveInteger } from '../reconciliation-config.js';\n\nconst RECONCILIATION_LABEL = 'Linear reconciliation';\n\nfunction optionalPositiveInterval(name: string, value: string | undefined): number | undefined {\n const interval = optionalPositiveInteger(value);\n if (value?.trim() && interval === undefined) {\n console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);\n }\n return interval;\n}\n\nexport function linearIssueReconciliationInterval(): number | undefined {\n return (\n optionalPositiveInterval(\n 'MASTRACODE_LINEAR_ISSUE_RECONCILE_INTERVAL_MS',\n process.env.MASTRACODE_LINEAR_ISSUE_RECONCILE_INTERVAL_MS,\n ) ??\n optionalPositiveInterval(\n 'MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS',\n process.env.MASTRACODE_LINEAR_RECONCILE_INTERVAL_MS,\n )\n );\n}\n"],"mappings":";;AAEA,MAAM,uBAAuB;AAE7B,SAAS,yBAAyB,MAAc,OAA+C;CAC7F,MAAM,WAAW,wBAAwB,KAAK;CAC9C,IAAI,OAAO,KAAK,KAAK,aAAa,KAAA,GAChC,QAAQ,KAAK,IAAI,qBAAqB,IAAI,KAAK,wCAAwC,KAAK,UAAU,KAAK,EAAE,EAAE;CAEjH,OAAO;AACT;AAEA,SAAgB,oCAAwD;CACtE,OACE,yBACE,iDACA,QAAQ,IAAI,6CACd,KACA,yBACE,2CACA,QAAQ,IAAI,uCACd;AAEJ"}
@@ -18,7 +18,6 @@ import type { StateSigner } from '../../state-signing.js';
18
18
  import type { IntakeStorage } from '../../storage/domains/intake/base.js';
19
19
  import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
20
20
  import type { LinearIntegration, LinearProject, LinearTeam } from './integration.js';
21
- import type { LinearRulesIngress } from './rules.js';
22
21
  /**
23
22
  * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the
24
23
  * GitHub diagnostics shape. Only booleans — never values.
@@ -84,7 +83,6 @@ export interface MountLinearRoutesOptions {
84
83
  orgId: string;
85
84
  }): Promise<unknown[]>;
86
85
  };
87
- ingestFactoryIssues?: (input: LinearRulesIngress) => Promise<unknown>;
88
86
  /**
89
87
  * Work-item lookup so the detail route can keep serving a card this Factory
90
88
  * already holds after the issue's winning source was routed elsewhere. When
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/routes.ts"],"names":[],"mappings":"AAAA;;;;;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AAiF;IACjF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B;;;OAGG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB;;;;OAIG;IACH,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,KAAK,EAAE;YAAE,KAAK,EAAE,MAAM,CAAA;SAAE,GAAG,OAAO,CAAC,OAAO,EAAE,CAAC,CAAA;KAAE,CAAC;IAClE;;;;OAIG;IACH,SAAS,CAAC,EAAE,IAAI,CAAC,gBAAgB,EAAE,oBAAoB,GAAG,YAAY,CAAC,CAAC;IACxE,gFAAgF;IAChF,MAAM,CAAC,EAAE,aAAa,GAAG,kBAAkB,CAAC;CAC7C;AAkHD;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CA8V/E"}
@@ -11,10 +11,10 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
11
11
  * Factory project.
12
12
  *
13
13
  * A Linear issue carries no Factory project of its own, so without a binding
14
- * every board view would ingest every selected source's issues into whichever
14
+ * every board view would show every selected source's issues in whichever
15
15
  * project happened to be on screen. Routing is explicit: a source feeds this
16
- * project only when it is bound to the project. The project's intake routes
17
- * then decide where each card lands.
16
+ * project only when it is bound to the project. The intake discovery sweep
17
+ * uses the same binding rule when it creates cards.
18
18
  */
19
19
  async function scopeSourceIdsToProject({ intake, orgId, factoryProjectId, selectedIds }) {
20
20
  const selected = new Set(selectedIds);
@@ -313,12 +313,6 @@ function buildLinearRoutes(options) {
313
313
  sourceId: issue.sourceId ?? null,
314
314
  projectId: issue.projectId ?? null
315
315
  }));
316
- if (factoryProjectId && boundSourceIds && options.ingestFactoryIssues) await options.ingestFactoryIssues({
317
- orgId: resolved.tenant.orgId,
318
- userId: resolved.tenant.userId,
319
- factoryProjectId,
320
- issues: issuePayload
321
- });
322
316
  return c.json({
323
317
  issues: issuePayload,
324
318
  nextCursor
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/linear/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Linear intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the WorkOS auth gate.\n * Mirrors the GitHub module: every route re-resolves the authenticated user\n * from the request cookie and scopes all rows by the caller's WorkOS org, so an\n * org can only ever see its own Linear connection and issues.\n *\n * When the feature is disabled (`isLinearFeatureEnabled()` false),\n * `buildLinearRoutes` returns only `GET /web/linear/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Linear UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { isTerminalWorkItem } 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 { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { LinearIntegration, LinearProject, LinearTeam } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\nimport type { LinearRulesIngress } from './rules.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;\n\n/**\n * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the\n * GitHub diagnostics shape. Only booleans — never values.\n */\nexport interface LinearFeatureDiagnostics {\n linearAppConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface LinearWorkspaceListingError {\n workspaceId: string;\n name: string;\n}\n\n/** Platform connection inventory entry, including disconnected workspaces. Never contains tokens. */\nexport interface LinearConnectionWorkspace {\n id: string;\n name: string;\n urlKey: string | null;\n connected: boolean;\n}\n\nexport interface MountLinearRoutesOptions {\n listProjectsWithStatus?: () => Promise<{ projects: LinearProject[]; workspaceErrors: LinearWorkspaceListingError[] }>;\n listTeamsWithStatus?: () => Promise<{ teams: LinearTeam[]; workspaceErrors: LinearWorkspaceListingError[] }>;\n listConnectionWorkspaces?: () => Promise<LinearConnectionWorkspace[]>;\n /**\n * The integration instance providing OAuth + GraphQL access. Required for\n * everything beyond the disabled `status` route.\n */\n linear?: LinearIntegration;\n /** Host auth seam. Linear connections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Absolute base URL of the web server (e.g. `http://localhost:4111`), used to\n * build the OAuth redirect URI when one isn't explicitly configured.\n */\n baseUrl?: string;\n /** Explicit OAuth callback URI; defaults to `<baseUrl>/auth/linear/callback`. */\n redirectUri?: string;\n /**\n * Shared OAuth `state` signer (created once per boot by the factory).\n * Required for the connect/callback flow; when absent, only the disabled\n * `status` route is served.\n */\n stateSigner?: StateSigner;\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 /**\n * Factory project domain, used to keep single-project installs working\n * without any source binding. When absent, unbound sources are treated as\n * belonging to no project.\n */\n projects?: { list(input: { orgId: string }): Promise<unknown[]> };\n ingestFactoryIssues?: (input: LinearRulesIngress) => Promise<unknown>;\n /**\n * Work-item lookup so the detail route can keep serving a card this Factory\n * already holds after the issue's winning source was routed elsewhere. When\n * absent, details resolve only through sources routed to the Factory.\n */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource' | 'listShared'>;\n /** Installed boards, so a held card's terminal status follows its own board. */\n boards?: BoardRegistry | ProjectBoardSource;\n}\n\n/**\n * Narrow the caller's selected Linear sources to the ones that feed this\n * Factory project.\n *\n * A Linear issue carries no Factory project of its own, so without a binding\n * every board view would ingest every selected source's issues into whichever\n * project happened to be on screen. Routing is explicit: a source feeds this\n * project only when it is bound to the project. The project's intake routes\n * then decide where each card lands.\n */\nasync function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<string[]> {\n const selected = new Set(selectedIds);\n return (await intake.listBindings({ orgId, integrationId: 'linear' }))\n .filter(binding => binding.factoryProjectId === factoryProjectId && selected.has(binding.sourceId))\n .map(binding => binding.sourceId);\n}\n\n/**\n * Resolve the org-scoped tenant for a Linear request. The connection is\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the GitHub 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: 'Linear intake requires an organization. Personal accounts cannot connect Linear.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Linear pagination cursor from the query string. Cursors\n * are server-issued (`pageInfo.endCursor`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Linear.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 8192 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Human issue key as it appears on a card (`ENG-123`). */\nconst ISSUE_IDENTIFIER_RE = /^[A-Za-z][A-Za-z0-9]{0,9}-\\d{1,7}$/;\n/** Project sources are more specific than their team and win every routed read. */\nfunction winningLinearSourceId(\n linear: LinearIntegration,\n sourceIds: string[],\n issue: Parameters<LinearIntegration['sourceMatchesIssue']>[1],\n): string | null {\n const matching = sourceIds.filter(sourceId => linear.sourceMatchesIssue(sourceId, issue));\n return matching.find(sourceId => !sourceId.startsWith('linear-team:')) ?? matching[0] ?? null;\n}\n\n/**\n * Whether this Factory holds a live card for an issue: under the identifier it\n * was filed with, or by the stable issue id when the SPA sent one.\n */\nasync function holdsLiveCardFor(\n options: MountLinearRoutesOptions,\n orgId: string,\n factoryProjectId: string,\n identifier: string,\n issueId: string | undefined,\n) {\n if (!options.workItems) return false;\n const boards = toBoardSource(options.boards);\n const isLive = (item: Card) => !isTerminalWorkItem(boards.forProject(item), item);\n const byIdentifier = await options.workItems.getByProjectSource({\n orgId,\n factoryProjectId,\n source: { integrationId: 'linear', type: 'issue', externalId: `linear:${identifier}` },\n });\n if (byIdentifier && isLive(byIdentifier)) return true;\n if (!issueId) return false;\n const items = await options.workItems.listShared({ orgId, factoryProjectId });\n return items.some(item => item.workItem.metadata?.linearIssueId === issueId && isLive(item));\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\n if ((err as { code?: unknown }).code === 'invalid_cursor') {\n return c.json({ error: 'invalid_cursor' }, 400);\n }\n if (err instanceof LinearReauthRequiredError || (err as { status?: number }).status === 401) {\n return c.json({ error: 'linear_reauth_required', message: new LinearReauthRequiredError().message }, 409);\n }\n return c.json({ error: 'linear_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Linear 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 buildLinearRoutes(options: MountLinearRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { linear, auth, stateSigner, intake } = options;\n const enabled = Boolean(linear) && auth.enabled();\n const diagnostics = (): LinearFeatureDiagnostics => ({\n linearAppConfigured: Boolean(linear),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: true,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !linear || !stateSigner) {\n return c.json({\n enabled: false,\n connected: false,\n workspace: 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 organizationRequired: true,\n connected: false,\n workspace: null,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n if (options.listConnectionWorkspaces) {\n const workspaces = await options.listConnectionWorkspaces();\n const active = workspaces.find(workspace => workspace.connected);\n return c.json({\n enabled: true,\n connected: Boolean(active),\n mode: 'platform',\n workspace: active ? { name: active.name, urlKey: active.urlKey } : null,\n workspaces,\n reason: active ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n }\n const connection = await linear.loadConnection(tenant.orgId);\n return c.json({\n enabled: true,\n connected: Boolean(connection),\n workspace: connection ? { name: connection.workspaceName, urlKey: connection.workspaceUrlKey } : null,\n reason: connection ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or a state signer the connect/callback\n // flow cannot talk to Linear or bind the OAuth round-trip to a tenant —\n // serve only the disabled `status` route (mirrors the feature gate).\n if (!enabled || !linear || !stateSigner || !intake) {\n return routes;\n }\n\n const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? '').replace(/\\/$/, '')}/auth/linear/callback`;\n\n // ── Connect: send the user to Linear's OAuth consent screen ─────────────\n routes.push(\n registerApiRoute('/auth/linear/connect', {\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 const state = stateSigner.sign(resolved.tenant.orgId, resolved.tenant.userId);\n return c.redirect(linear.buildAuthorizeUrl(state, redirectUri));\n },\n }),\n );\n\n // ── Callback: exchange the code, persist the connection for the org ─────\n routes.push(\n registerApiRoute('/auth/linear/callback', {\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 const { orgId, userId } = resolved.tenant;\n\n // CSRF / cross-tenant linking protection: the signed state must belong\n // to the same logged-in user *and* their current org.\n const stateTenant = stateSigner.verify(c.req.query('state'));\n if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {\n console.warn('[Linear] OAuth callback rejected: state/tenant mismatch.');\n return c.redirect('/?linear=error');\n }\n\n const code = c.req.query('code');\n if (!code) {\n // User denied consent (or Linear returned an error).\n return c.redirect('/?linear=error');\n }\n\n try {\n const tokens = await linear.exchangeOAuthCode(code, redirectUri);\n const workspace = await linear.fetchWorkspace(tokens.accessToken);\n await linear.upsertConnection({\n orgId,\n userId,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n workspaceName: workspace.name,\n workspaceUrlKey: workspace.urlKey,\n });\n } catch (error) {\n console.warn(`[Linear] OAuth callback failed to persist connection for org ${orgId}.`, error);\n return c.redirect('/?linear=error');\n }\n\n return c.redirect('/?linear=connected');\n },\n }),\n );\n\n // ── List the workspace's projects (Settings intake-source picker) ───────\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear projects.' }, 409);\n }\n\n try {\n if (options.listProjectsWithStatus) return c.json(await options.listProjectsWithStatus());\n const accessToken = await linear.getFreshAccessToken(connection);\n const projects = await linear.listProjects(accessToken);\n return c.json({ projects });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's teams (Settings intake-source picker) ──────────\n routes.push(\n registerApiRoute('/web/linear/teams', {\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 connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear teams.' }, 409);\n }\n\n try {\n if (options.listTeamsWithStatus) return c.json(await options.listTeamsWithStatus());\n const accessToken = await linear.getFreshAccessToken(connection);\n const teams = await linear.listTeams(accessToken);\n return c.json({ teams });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's active issues (cursor-paged) ───────────────────\n // Respects the org's intake config: disabled Linear intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n\n // No sources selected means nothing is synced — don't fan out to Linear.\n const selectedIds = selection.sourceIds ?? [];\n // A board request is also an ingest, so it only ever sees the sources\n // bound to that Factory project. Sources may be projects or whole\n // teams; both are keyed by their opaque source id.\n const boundSourceIds = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const routedSourceIds = boundSourceIds ?? selectedIds;\n if (routedSourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const { issues, nextCursor } = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: routedSourceIds,\n attributionSourceIds: selectedIds,\n cursor: after,\n });\n // Source precedence must be resolved against the complete selection,\n // then the winning issues can be narrowed to this Factory project.\n const routedIssues = boundSourceIds\n ? issues.filter(issue => issue.sourceId != null && routedSourceIds.includes(issue.sourceId))\n : issues;\n const issuePayload = routedIssues.map(issue => ({\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n creator: issue.author,\n team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId ?? null,\n projectId: issue.projectId ?? null,\n }));\n if (factoryProjectId && boundSourceIds && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/linear/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 if (!ISSUE_IDENTIFIER_RE.test(identifier)) return c.json({ error: 'invalid_identifier' }, 400);\n const issueId = c.req.query('issueId');\n if (issueId !== undefined && (issueId.length === 0 || issueId.length > 512)) {\n return c.json({ error: 'invalid_issue_id' }, 400);\n }\n const issueReference = issueId ?? identifier;\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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n const selectedIds = selection.sourceIds ?? [];\n const routedSourceIds = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n });\n // A card this Factory already ingested stays readable after its issue's\n // winning source moved to a source routed elsewhere: the fetch widens to\n // every selected source (never beyond the selection), and the routing\n // check is waived for that card alone. Without a live card, the strict\n // routed-source rule applies.\n const holdsLiveCard = await holdsLiveCardFor(\n options,\n resolved.tenant.orgId,\n factoryProjectId,\n identifier,\n issueId,\n );\n if (routedSourceIds.length === 0 && !holdsLiveCard) return c.json({ error: 'issue_not_found' }, 404);\n const fetchSourceIds = holdsLiveCard ? selectedIds : routedSourceIds;\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const issue = await linear.fetchIssueDetail(accessToken, issueReference, selectedIds, fetchSourceIds);\n const matchesReference = issueId !== undefined ? issue?.id === issueId : issue?.identifier === identifier;\n const winningSourceId = issue ? winningLinearSourceId(linear, selectedIds, issue) : null;\n const isRouted = winningSourceId != null && (holdsLiveCard || routedSourceIds.includes(winningSourceId));\n // Reads exactly like an issue that doesn't exist.\n if (!issue || !matchesReference || !isRouted) {\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 linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;;AAgCA,MAAM,UAAU;;;;;;;;;;;A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S,KAAK;IACZ,OAAO,iBAAiB,MAAM,CAAC,GAAG,GAAG;GACvC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/linear/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Linear intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the WorkOS auth gate.\n * Mirrors the GitHub module: every route re-resolves the authenticated user\n * from the request cookie and scopes all rows by the caller's WorkOS org, so an\n * org can only ever see its own Linear connection and issues.\n *\n * When the feature is disabled (`isLinearFeatureEnabled()` false),\n * `buildLinearRoutes` returns only `GET /web/linear/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Linear UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { isTerminalWorkItem } 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 { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { StateSigner } from '../../state-signing.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { LinearIntegration, LinearProject, LinearTeam } from './integration.js';\nimport { LinearReauthRequiredError } 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;\n\n/**\n * Non-secret diagnostic snapshot of every Linear feature gate, mirroring the\n * GitHub diagnostics shape. Only booleans — never values.\n */\nexport interface LinearFeatureDiagnostics {\n linearAppConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface LinearWorkspaceListingError {\n workspaceId: string;\n name: string;\n}\n\n/** Platform connection inventory entry, including disconnected workspaces. Never contains tokens. */\nexport interface LinearConnectionWorkspace {\n id: string;\n name: string;\n urlKey: string | null;\n connected: boolean;\n}\n\nexport interface MountLinearRoutesOptions {\n listProjectsWithStatus?: () => Promise<{ projects: LinearProject[]; workspaceErrors: LinearWorkspaceListingError[] }>;\n listTeamsWithStatus?: () => Promise<{ teams: LinearTeam[]; workspaceErrors: LinearWorkspaceListingError[] }>;\n listConnectionWorkspaces?: () => Promise<LinearConnectionWorkspace[]>;\n /**\n * The integration instance providing OAuth + GraphQL access. Required for\n * everything beyond the disabled `status` route.\n */\n linear?: LinearIntegration;\n /** Host auth seam. Linear connections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Absolute base URL of the web server (e.g. `http://localhost:4111`), used to\n * build the OAuth redirect URI when one isn't explicitly configured.\n */\n baseUrl?: string;\n /** Explicit OAuth callback URI; defaults to `<baseUrl>/auth/linear/callback`. */\n redirectUri?: string;\n /**\n * Shared OAuth `state` signer (created once per boot by the factory).\n * Required for the connect/callback flow; when absent, only the disabled\n * `status` route is served.\n */\n stateSigner?: StateSigner;\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 /**\n * Factory project domain, used to keep single-project installs working\n * without any source binding. When absent, unbound sources are treated as\n * belonging to no project.\n */\n projects?: { list(input: { orgId: string }): Promise<unknown[]> };\n /**\n * Work-item lookup so the detail route can keep serving a card this Factory\n * already holds after the issue's winning source was routed elsewhere. When\n * absent, details resolve only through sources routed to the Factory.\n */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource' | 'listShared'>;\n /** Installed boards, so a held card's terminal status follows its own board. */\n boards?: BoardRegistry | ProjectBoardSource;\n}\n\n/**\n * Narrow the caller's selected Linear sources to the ones that feed this\n * Factory project.\n *\n * A Linear issue carries no Factory project of its own, so without a binding\n * every board view would show every selected source's issues in whichever\n * project happened to be on screen. Routing is explicit: a source feeds this\n * project only when it is bound to the project. The intake discovery sweep\n * uses the same binding rule when it creates cards.\n */\nasync function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<string[]> {\n const selected = new Set(selectedIds);\n return (await intake.listBindings({ orgId, integrationId: 'linear' }))\n .filter(binding => binding.factoryProjectId === factoryProjectId && selected.has(binding.sourceId))\n .map(binding => binding.sourceId);\n}\n\n/**\n * Resolve the org-scoped tenant for a Linear request. The connection is\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the GitHub 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: 'Linear intake requires an organization. Personal accounts cannot connect Linear.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Linear pagination cursor from the query string. Cursors\n * are server-issued (`pageInfo.endCursor`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Linear.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 8192 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Human issue key as it appears on a card (`ENG-123`). */\nconst ISSUE_IDENTIFIER_RE = /^[A-Za-z][A-Za-z0-9]{0,9}-\\d{1,7}$/;\n/** Project sources are more specific than their team and win every routed read. */\nfunction winningLinearSourceId(\n linear: LinearIntegration,\n sourceIds: string[],\n issue: Parameters<LinearIntegration['sourceMatchesIssue']>[1],\n): string | null {\n const matching = sourceIds.filter(sourceId => linear.sourceMatchesIssue(sourceId, issue));\n return matching.find(sourceId => !sourceId.startsWith('linear-team:')) ?? matching[0] ?? null;\n}\n\n/**\n * Whether this Factory holds a live card for an issue: under the identifier it\n * was filed with, or by the stable issue id when the SPA sent one.\n */\nasync function holdsLiveCardFor(\n options: MountLinearRoutesOptions,\n orgId: string,\n factoryProjectId: string,\n identifier: string,\n issueId: string | undefined,\n) {\n if (!options.workItems) return false;\n const boards = toBoardSource(options.boards);\n const isLive = (item: Card) => !isTerminalWorkItem(boards.forProject(item), item);\n const byIdentifier = await options.workItems.getByProjectSource({\n orgId,\n factoryProjectId,\n source: { integrationId: 'linear', type: 'issue', externalId: `linear:${identifier}` },\n });\n if (byIdentifier && isLive(byIdentifier)) return true;\n if (!issueId) return false;\n const items = await options.workItems.listShared({ orgId, factoryProjectId });\n return items.some(item => item.workItem.metadata?.linearIssueId === issueId && isLive(item));\n}\n\n/** Map a Linear read failure to the API response for the SPA. */\nfunction linearFetchError(c: RouteContext, err: unknown) {\n if ((err as { code?: unknown }).code === 'invalid_cursor') {\n return c.json({ error: 'invalid_cursor' }, 400);\n }\n if (err instanceof LinearReauthRequiredError || (err as { status?: number }).status === 401) {\n return c.json({ error: 'linear_reauth_required', message: new LinearReauthRequiredError().message }, 409);\n }\n return c.json({ error: 'linear_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Linear 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 buildLinearRoutes(options: MountLinearRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { linear, auth, stateSigner, intake } = options;\n const enabled = Boolean(linear) && auth.enabled();\n const diagnostics = (): LinearFeatureDiagnostics => ({\n linearAppConfigured: Boolean(linear),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: true,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !linear || !stateSigner) {\n return c.json({\n enabled: false,\n connected: false,\n workspace: 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 organizationRequired: true,\n connected: false,\n workspace: null,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n if (options.listConnectionWorkspaces) {\n const workspaces = await options.listConnectionWorkspaces();\n const active = workspaces.find(workspace => workspace.connected);\n return c.json({\n enabled: true,\n connected: Boolean(active),\n mode: 'platform',\n workspace: active ? { name: active.name, urlKey: active.urlKey } : null,\n workspaces,\n reason: active ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n }\n const connection = await linear.loadConnection(tenant.orgId);\n return c.json({\n enabled: true,\n connected: Boolean(connection),\n workspace: connection ? { name: connection.workspaceName, urlKey: connection.workspaceUrlKey } : null,\n reason: connection ? 'ready' : 'not_connected',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or a state signer the connect/callback\n // flow cannot talk to Linear or bind the OAuth round-trip to a tenant —\n // serve only the disabled `status` route (mirrors the feature gate).\n if (!enabled || !linear || !stateSigner || !intake) {\n return routes;\n }\n\n const redirectUri = options.redirectUri ?? `${(options.baseUrl ?? '').replace(/\\/$/, '')}/auth/linear/callback`;\n\n // ── Connect: send the user to Linear's OAuth consent screen ─────────────\n routes.push(\n registerApiRoute('/auth/linear/connect', {\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 const state = stateSigner.sign(resolved.tenant.orgId, resolved.tenant.userId);\n return c.redirect(linear.buildAuthorizeUrl(state, redirectUri));\n },\n }),\n );\n\n // ── Callback: exchange the code, persist the connection for the org ─────\n routes.push(\n registerApiRoute('/auth/linear/callback', {\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 const { orgId, userId } = resolved.tenant;\n\n // CSRF / cross-tenant linking protection: the signed state must belong\n // to the same logged-in user *and* their current org.\n const stateTenant = stateSigner.verify(c.req.query('state'));\n if (!stateTenant || stateTenant.userId !== userId || stateTenant.orgId !== orgId) {\n console.warn('[Linear] OAuth callback rejected: state/tenant mismatch.');\n return c.redirect('/?linear=error');\n }\n\n const code = c.req.query('code');\n if (!code) {\n // User denied consent (or Linear returned an error).\n return c.redirect('/?linear=error');\n }\n\n try {\n const tokens = await linear.exchangeOAuthCode(code, redirectUri);\n const workspace = await linear.fetchWorkspace(tokens.accessToken);\n await linear.upsertConnection({\n orgId,\n userId,\n accessToken: tokens.accessToken,\n refreshToken: tokens.refreshToken,\n expiresAt: tokens.expiresAt,\n scope: tokens.scope,\n workspaceName: workspace.name,\n workspaceUrlKey: workspace.urlKey,\n });\n } catch (error) {\n console.warn(`[Linear] OAuth callback failed to persist connection for org ${orgId}.`, error);\n return c.redirect('/?linear=error');\n }\n\n return c.redirect('/?linear=connected');\n },\n }),\n );\n\n // ── List the workspace's projects (Settings intake-source picker) ───────\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear projects.' }, 409);\n }\n\n try {\n if (options.listProjectsWithStatus) return c.json(await options.listProjectsWithStatus());\n const accessToken = await linear.getFreshAccessToken(connection);\n const projects = await linear.listProjects(accessToken);\n return c.json({ projects });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's teams (Settings intake-source picker) ──────────\n routes.push(\n registerApiRoute('/web/linear/teams', {\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 connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to list Linear teams.' }, 409);\n }\n\n try {\n if (options.listTeamsWithStatus) return c.json(await options.listTeamsWithStatus());\n const accessToken = await linear.getFreshAccessToken(connection);\n const teams = await linear.listTeams(accessToken);\n return c.json({ teams });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the workspace's active issues (cursor-paged) ───────────────────\n // Respects the org's intake config: disabled Linear intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/linear/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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n\n // No sources selected means nothing is synced — don't fan out to Linear.\n const selectedIds = selection.sourceIds ?? [];\n // A board request only ever sees the sources bound to that Factory\n // project. Sources may be projects or whole teams; both are keyed by\n // their opaque source id.\n const boundSourceIds = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const routedSourceIds = boundSourceIds ?? selectedIds;\n if (routedSourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const { issues, nextCursor } = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: routedSourceIds,\n attributionSourceIds: selectedIds,\n cursor: after,\n });\n // Source precedence must be resolved against the complete selection,\n // then the winning issues can be narrowed to this Factory project.\n const routedIssues = boundSourceIds\n ? issues.filter(issue => issue.sourceId != null && routedSourceIds.includes(issue.sourceId))\n : issues;\n const issuePayload = routedIssues.map(issue => ({\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n creator: issue.author,\n team: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId ?? null,\n projectId: issue.projectId ?? null,\n }));\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/linear/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 if (!ISSUE_IDENTIFIER_RE.test(identifier)) return c.json({ error: 'invalid_identifier' }, 400);\n const issueId = c.req.query('issueId');\n if (issueId !== undefined && (issueId.length === 0 || issueId.length > 512)) {\n return c.json({ error: 'invalid_issue_id' }, 400);\n }\n const issueReference = issueId ?? identifier;\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 const connection = await linear.loadConnection(resolved.tenant.orgId);\n if (!connection) {\n return c.json({ error: 'linear_not_connected', message: 'Connect Linear to see intake issues.' }, 409);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['linear'] });\n const selection = config.linear!;\n if (!selection.enabled) {\n return c.json({ error: 'linear_intake_disabled', message: 'Linear intake is turned off in Settings.' }, 404);\n }\n const selectedIds = selection.sourceIds ?? [];\n const routedSourceIds = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n });\n // A card this Factory already ingested stays readable after its issue's\n // winning source moved to a source routed elsewhere: the fetch widens to\n // every selected source (never beyond the selection), and the routing\n // check is waived for that card alone. Without a live card, the strict\n // routed-source rule applies.\n const holdsLiveCard = await holdsLiveCardFor(\n options,\n resolved.tenant.orgId,\n factoryProjectId,\n identifier,\n issueId,\n );\n if (routedSourceIds.length === 0 && !holdsLiveCard) return c.json({ error: 'issue_not_found' }, 404);\n const fetchSourceIds = holdsLiveCard ? selectedIds : routedSourceIds;\n\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const issue = await linear.fetchIssueDetail(accessToken, issueReference, selectedIds, fetchSourceIds);\n const matchesReference = issueId !== undefined ? issue?.id === issueId : issue?.identifier === identifier;\n const winningSourceId = issue ? winningLinearSourceId(linear, selectedIds, issue) : null;\n const isRouted = winningSourceId != null && (holdsLiveCard || routedSourceIds.includes(winningSourceId));\n // Reads exactly like an issue that doesn't exist.\n if (!issue || !matchesReference || !isRouted) {\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 linearFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;;AA+BA,MAAM,UAAU;;;;;;;;;;;AAgFhB,eAAe,wBAAwB,EACrC,QACA,OACA,kBACA,eAMoB;CACpB,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,QAAQ,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAS,CAAC,EAAA,CACjE,QAAO,YAAW,QAAQ,qBA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K;IAAE,OAAO;IAA0B,SAAS;GAA2C,GAAG,GAAG;GAE7G,MAAM,cAAc,UAAU,aAAa,CAAC;GAC5C,MAAM,kBAAkB,MAAM,wBAAwB;IACpD;IACA,OAAO,SAAS,OAAO;IACvB;IACA;GACF,CAAC;GAMD,MAAM,gBAAgB,MAAM,iBAC1B,SACA,SAAS,OAAO,OAChB,kBACA,YACA,OACF;GACA,IAAI,gBAAgB,WAAW,KAAK,CAAC,eAAe,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;GACnG,MAAM,iBAAiB,gBAAgB,cAAc;GAErD,IAAI;IACF,MAAM,cAAc,MAAM,OAAO,oBAAoB,UAAU;IAC/D,MAAM,QAAQ,MAAM,OAAO,iBAAiB,aAAa,gBAAgB,aAAa,cAAc;IACpG,MAAM,mBAAmB,YAAY,KAAA,IAAY,OAAO,OAAO,UAAU,OAAO,eAAe;IAC/F,MAAM,kBAAkB,QAAQ,sBAAsB,QAAQ,aAAa,KAAK,IAAI;IACpF,MAAM,WAAW,mBAAmB,SAAS,iBAAiB,gBAAgB,SAAS,eAAe;IAEtG,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC,UAClC,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,iBAAiB,MAAM,CAAC,GAAG,GAAG;GACvC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
@@ -27,6 +27,8 @@ export declare class PlatformApiClient {
27
27
  }): Promise<string>;
28
28
  }
29
29
  export declare function logPlatformInfo(message: string, fields?: Record<string, unknown>): void;
30
+ /** Startup detail that `mastra factory dev` hides unless run with `--debug`. */
31
+ export declare function logPlatformBootInfo(message: string, fields?: Record<string, unknown>): void;
30
32
  export declare function logPlatformWarn(message: string, fields?: Record<string, unknown>): void;
31
33
  export declare function logPlatformError(message: string, fields?: Record<string, unknown>): void;
32
34
  //# sourceMappingURL=api-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.d.ts","sourceRoot":"","sources":["../../../src/integrations/platform/api-client.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,uBAAuB;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;CAC1B;AAQD,wBAAgB,8BAA8B,IAAI,uBAAuB,CAsBxE;AAuBD,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,iBAAiB,EAAE,MAAM,GAAG,IAAI,CAAC;IAE1C,YAAY,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,iBAAiB,GAAE,MAAM,GAAG,IAAW,EAKnF;CACF;AAED,qBAAa,iBAAiB;;IAM5B,YAAY,MAAM,EAAE,uBAAuB,EAS1C;IAEK,OAAO,CAAC,CAAC,EACb,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,IAAI,CAAC,EAAE,OAAO,EACd,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,GACxD,OAAO,CAAC,CAAC,CAAC,CAgBZ;IAEK,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAoBvG;CA4DF;AAkBD,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE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AM,CAAC,EAAE,WAAW,CAAA;KAAE,GAAG,OAAO,CAAC,MAAM,CAAC,CAoBvG;CA4DF;AAkBD,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAEvF;AAED,gFAAgF;AAChF,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAE3F;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAEvF;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAExF"}
@@ -1,3 +1,4 @@
1
+ import { bootDiagnosticsEnabled } from "../../timing.js";
1
2
  // src/integrations/platform/api-client.ts
2
3
  const DEFAULT_INTEGRATIONS_URL = "https://integrations.mastra.ai";
3
4
  const REGIONAL_INTEGRATIONS_URLS = {
@@ -158,6 +159,10 @@ function redact(message, accessToken) {
158
159
  function logPlatformInfo(message, fields) {
159
160
  writePlatformLog("info", message, fields);
160
161
  }
162
+ /** Startup detail that `mastra factory dev` hides unless run with `--debug`. */
163
+ function logPlatformBootInfo(message, fields) {
164
+ if (bootDiagnosticsEnabled) writePlatformLog("info", message, fields);
165
+ }
161
166
  function logPlatformWarn(message, fields) {
162
167
  writePlatformLog("warn", message, fields);
163
168
  }
@@ -176,6 +181,6 @@ function parseRetryAfter(value) {
176
181
  const seconds = Number.parseInt(value, 10);
177
182
  return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;
178
183
  }
179
- export { PlatformApiClient, PlatformApiError, logPlatformError, logPlatformInfo, logPlatformWarn, platformApiClientConfigFromEnv };
184
+ export { PlatformApiClient, PlatformApiError, logPlatformBootInfo, logPlatformError, logPlatformInfo, logPlatformWarn, platformApiClientConfigFromEnv };
180
185
 
181
186
  //# sourceMappingURL=api-client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"api-client.js","names":[],"sources":["../../../src/integrations/platform/api-client.ts"],"sourcesContent":["export interface PlatformApiClientConfig {\n baseUrl: string;\n accessToken: string;\n /**\n * Mastra project this deployment belongs to. Sent as `x-mastra-project-id`\n * so the platform can attribute proxied provider activity to the project;\n * the platform strips the header before forwarding anything upstream.\n */\n projectId?: string;\n fetchImpl?: typeof fetch;\n}\n\nconst DEFAULT_INTEGRATIONS_URL = 'https://integrations.mastra.ai';\nconst REGIONAL_INTEGRATIONS_URLS: Record<'us' | 'eu', string> = {\n us: 'https://integrations.us.mastra.ai',\n eu: 'https://integrations.eu.mastra.ai',\n};\n\nexport function platformApiClientConfigFromEnv(): PlatformApiClientConfig {\n // MASTRA_INTEGRATIONS_API_URL is the dedicated override for the\n // integrations service and takes precedence over MASTRA_PLATFORM_REGION.\n // MASTRA_SHARED_API_URL is deliberately not consulted: it configures the\n // shared platform API, and integrations routing is independent of it.\n const integrationsApiUrl = process.env.MASTRA_INTEGRATIONS_API_URL?.trim() || resolveIntegrationsUrl();\n // MASTRA_PLATFORM_ACCESS_TOKEN is the credential Mastra Platform injects\n // into deployed projects; MASTRA_PLATFORM_SECRET_KEY is the org secret key\n // written by project scaffolding. The platform API accepts both forms.\n const accessToken =\n process.env.MASTRA_PLATFORM_ACCESS_TOKEN?.trim() || process.env.MASTRA_PLATFORM_SECRET_KEY?.trim();\n if (!accessToken) {\n throw new Error(\n 'Platform integration: missing required environment variable MASTRA_PLATFORM_ACCESS_TOKEN (or MASTRA_PLATFORM_SECRET_KEY).',\n );\n }\n const projectId = process.env.MASTRA_PROJECT_ID?.trim();\n return {\n baseUrl: normalizeIntegrationsApiUrl(integrationsApiUrl),\n accessToken,\n ...(projectId ? { projectId } : {}),\n };\n}\n\n/**\n * Resolves the integrations API base URL from `MASTRA_PLATFORM_REGION`\n * (case-insensitive `us` or `eu`), falling back to the global default.\n * Unknown region values fall through to the global default.\n */\nfunction resolveIntegrationsUrl(): string {\n const region = process.env.MASTRA_PLATFORM_REGION?.trim().toLowerCase();\n if (region === 'us' || region === 'eu') return REGIONAL_INTEGRATIONS_URLS[region];\n return DEFAULT_INTEGRATIONS_URL;\n}\n\n/**\n * Normalizes an integrations API URL to a bare origin. Callers pass fully\n * versioned paths (`/v1/server/...`, `/v2/...`), so a trailing `/v1` — as in\n * legacy platform API URLs like `https://platform.mastra.ai/v1` — is stripped\n * to avoid duplicated version segments.\n */\nfunction normalizeIntegrationsApiUrl(integrationsApiUrl: string): string {\n return integrationsApiUrl.replace(/\\/+$/, '').replace(/\\/v1$/, '');\n}\n\nexport class PlatformApiError extends Error {\n readonly status: number;\n readonly retryAfterSeconds: number | null;\n\n constructor(message: string, status: number, retryAfterSeconds: number | null = null) {\n super(message);\n this.name = 'PlatformApiError';\n this.status = status;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nexport class PlatformApiClient {\n readonly #baseUrl: string;\n readonly #accessToken: string;\n readonly #projectId: string | null;\n readonly #fetch: typeof fetch;\n\n constructor(config: PlatformApiClientConfig) {\n const missing = ['baseUrl', 'accessToken'].filter(field => !config[field as keyof PlatformApiClientConfig]);\n if (missing.length > 0) {\n throw new Error(`Platform integration: missing required config field(s): ${missing.join(', ')}.`);\n }\n this.#baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.#accessToken = config.accessToken;\n this.#projectId = config.projectId?.trim() || null;\n this.#fetch = config.fetchImpl ?? globalThis.fetch;\n }\n\n async request<T>(\n method: string,\n path: string,\n body?: unknown,\n options?: { signal?: AbortSignal; actingUserId?: string },\n ): Promise<T> {\n const response = await this.#send(method, path, body, options);\n if (!response.ok) {\n const message = redact(await extractError(response), this.#accessToken);\n const retryAfterSeconds = parseRetryAfter(response.headers.get('retry-after'));\n logPlatformError('Platform API request failed', {\n method,\n path,\n status: response.status,\n retryAfterSeconds,\n message,\n });\n throw new PlatformApiError(message, response.status, retryAfterSeconds);\n }\n if (response.status === 204) return undefined as T;\n return (await response.json()) as T;\n }\n\n async requestRedirect(method: string, path: string, options?: { signal?: AbortSignal }): Promise<string> {\n const response = await this.#send(method, path, undefined, options, 'manual');\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (location) return location;\n }\n if (!response.ok) {\n const message = redact(await extractError(response), this.#accessToken);\n const retryAfterSeconds = parseRetryAfter(response.headers.get('retry-after'));\n logPlatformError('Platform API redirect request failed', {\n method,\n path,\n status: response.status,\n retryAfterSeconds,\n message,\n });\n throw new PlatformApiError(message, response.status, retryAfterSeconds);\n }\n logPlatformError('Platform API request did not return a redirect', { method, path, status: response.status });\n throw new PlatformApiError('Platform API request did not return a redirect.', response.status);\n }\n\n async #send(\n method: string,\n path: string,\n body?: unknown,\n options?: { signal?: AbortSignal; actingUserId?: string },\n redirect?: RequestInit['redirect'],\n ): Promise<Response> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n authorization: `Bearer ${this.#accessToken}`,\n };\n // Project attribution for proxied provider calls. Org-scoped machine\n // tokens carry no project claim, so without this header the platform\n // records proxy activity with no project.\n if (this.#projectId) {\n headers['x-mastra-project-id'] = this.#projectId;\n }\n // Acting end-user for platform GitHub writes: the platform resolves this\n // user's GitHub OAuth connection (org-scoped) so issues/PRs are authored\n // by the human instead of the App bot. Ignored by older platforms.\n if (options?.actingUserId) {\n headers['x-acting-user-id'] = options.actingUserId;\n }\n const timeoutSignal = AbortSignal.timeout(15_000);\n const init: RequestInit = {\n method,\n headers,\n redirect,\n signal: options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal,\n };\n if (body !== undefined) {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(body);\n }\n\n try {\n return await this.#fetch(`${this.#baseUrl}${path}`, init);\n } catch (error) {\n if (error instanceof Error && error.message.includes(this.#accessToken)) {\n const redacted = new Error(redact(error.message, this.#accessToken));\n redacted.name = error.name;\n logPlatformError('Platform API transport error', {\n method,\n path,\n name: redacted.name,\n message: redacted.message,\n });\n throw redacted;\n }\n logPlatformError('Platform API transport error', {\n method,\n path,\n name: error instanceof Error ? error.name : undefined,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n}\n\nasync function extractError(response: Response): Promise<string> {\n try {\n const data = (await response.clone().json()) as Record<string, unknown>;\n for (const field of ['detail', 'error', 'title']) {\n if (typeof data[field] === 'string' && data[field]) return data[field];\n }\n } catch {\n // Fall through to the status-based message.\n }\n return `Platform API request failed (${response.status})`;\n}\n\nfunction redact(message: string, accessToken: string): string {\n return message.split(accessToken).join('[REDACTED]');\n}\n\nexport function logPlatformInfo(message: string, fields?: Record<string, unknown>): void {\n writePlatformLog('info', message, fields);\n}\n\nexport function logPlatformWarn(message: string, fields?: Record<string, unknown>): void {\n writePlatformLog('warn', message, fields);\n}\n\nexport function logPlatformError(message: string, fields?: Record<string, unknown>): void {\n writePlatformLog('error', message, fields);\n}\n\nfunction writePlatformLog(level: 'info' | 'warn' | 'error', message: string, fields?: Record<string, unknown>): void {\n const metadata = fields ? ` ${JSON.stringify(stripUndefined(fields))}` : '';\n process.stderr.write(`[Mastra Factory] ${level.toUpperCase()} ${message}${metadata}\\n`);\n}\n\nfunction stripUndefined(fields: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));\n}\n\nfunction parseRetryAfter(value: string | null): number | null {\n if (!value) return null;\n const seconds = Number.parseInt(value, 10);\n return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;\n}\n"],"mappings":";AAYA,MAAM,2BAA2B;AACjC,MAAM,6BAA0D;CAC9D,IAAI;CACJ,IAAI;AACN;AAEA,SAAgB,iCAA0D;CAKxE,MAAM,qBAAqB,QAAQ,IAAI,6BAA6B,KAAK,KAAK,uBAAuB;CAIrG,MAAM,cACJ,QAAQ,IAA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CACxF,iBAAiB,SAAS,SAAS,MAAM;AAC3C;AAEA,SAAS,iBAAiB,OAAkC,SAAiB,QAAwC;CACnH,MAAM,WAAW,SAAS,IAAI,KAAK,UAAU,eAAe,MAAM,CAAC,MAAM;CACzE,QAAQ,OAAO,MAAM,oBAAoB,MAAM,YAAY,EAAE,GAAG,UAAU,SAAS,GAAG;AACxF;AAEA,SAAS,eAAe,QAA0D;CAChF,OAAO,OAAO,YAAY,OAAO,QAAQ,MAAM,CAAC,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CAAC;AAC7F;AAEA,SAAS,gBAAgB,OAAqC;CAC5D,IAAI,CAAC,OAAO,OAAO;CACnB,MAAM,UAAU,OAAO,SAAS,OAAO,EAAE;CACzC,OAAO,OAAO,cAAc,OAAO,KAAK,WAAW,IAAI,UAAU;AACnE"}
1
+ {"version":3,"file":"api-client.js","names":[],"sources":["../../../src/integrations/platform/api-client.ts"],"sourcesContent":["import { bootDiagnosticsEnabled } from '../../timing.js';\n\nexport interface PlatformApiClientConfig {\n baseUrl: string;\n accessToken: string;\n /**\n * Mastra project this deployment belongs to. Sent as `x-mastra-project-id`\n * so the platform can attribute proxied provider activity to the project;\n * the platform strips the header before forwarding anything upstream.\n */\n projectId?: string;\n fetchImpl?: typeof fetch;\n}\n\nconst DEFAULT_INTEGRATIONS_URL = 'https://integrations.mastra.ai';\nconst REGIONAL_INTEGRATIONS_URLS: Record<'us' | 'eu', string> = {\n us: 'https://integrations.us.mastra.ai',\n eu: 'https://integrations.eu.mastra.ai',\n};\n\nexport function platformApiClientConfigFromEnv(): PlatformApiClientConfig {\n // MASTRA_INTEGRATIONS_API_URL is the dedicated override for the\n // integrations service and takes precedence over MASTRA_PLATFORM_REGION.\n // MASTRA_SHARED_API_URL is deliberately not consulted: it configures the\n // shared platform API, and integrations routing is independent of it.\n const integrationsApiUrl = process.env.MASTRA_INTEGRATIONS_API_URL?.trim() || resolveIntegrationsUrl();\n // MASTRA_PLATFORM_ACCESS_TOKEN is the credential Mastra Platform injects\n // into deployed projects; MASTRA_PLATFORM_SECRET_KEY is the org secret key\n // written by project scaffolding. The platform API accepts both forms.\n const accessToken =\n process.env.MASTRA_PLATFORM_ACCESS_TOKEN?.trim() || process.env.MASTRA_PLATFORM_SECRET_KEY?.trim();\n if (!accessToken) {\n throw new Error(\n 'Platform integration: missing required environment variable MASTRA_PLATFORM_ACCESS_TOKEN (or MASTRA_PLATFORM_SECRET_KEY).',\n );\n }\n const projectId = process.env.MASTRA_PROJECT_ID?.trim();\n return {\n baseUrl: normalizeIntegrationsApiUrl(integrationsApiUrl),\n accessToken,\n ...(projectId ? { projectId } : {}),\n };\n}\n\n/**\n * Resolves the integrations API base URL from `MASTRA_PLATFORM_REGION`\n * (case-insensitive `us` or `eu`), falling back to the global default.\n * Unknown region values fall through to the global default.\n */\nfunction resolveIntegrationsUrl(): string {\n const region = process.env.MASTRA_PLATFORM_REGION?.trim().toLowerCase();\n if (region === 'us' || region === 'eu') return REGIONAL_INTEGRATIONS_URLS[region];\n return DEFAULT_INTEGRATIONS_URL;\n}\n\n/**\n * Normalizes an integrations API URL to a bare origin. Callers pass fully\n * versioned paths (`/v1/server/...`, `/v2/...`), so a trailing `/v1` — as in\n * legacy platform API URLs like `https://platform.mastra.ai/v1` — is stripped\n * to avoid duplicated version segments.\n */\nfunction normalizeIntegrationsApiUrl(integrationsApiUrl: string): string {\n return integrationsApiUrl.replace(/\\/+$/, '').replace(/\\/v1$/, '');\n}\n\nexport class PlatformApiError extends Error {\n readonly status: number;\n readonly retryAfterSeconds: number | null;\n\n constructor(message: string, status: number, retryAfterSeconds: number | null = null) {\n super(message);\n this.name = 'PlatformApiError';\n this.status = status;\n this.retryAfterSeconds = retryAfterSeconds;\n }\n}\n\nexport class PlatformApiClient {\n readonly #baseUrl: string;\n readonly #accessToken: string;\n readonly #projectId: string | null;\n readonly #fetch: typeof fetch;\n\n constructor(config: PlatformApiClientConfig) {\n const missing = ['baseUrl', 'accessToken'].filter(field => !config[field as keyof PlatformApiClientConfig]);\n if (missing.length > 0) {\n throw new Error(`Platform integration: missing required config field(s): ${missing.join(', ')}.`);\n }\n this.#baseUrl = config.baseUrl.replace(/\\/+$/, '');\n this.#accessToken = config.accessToken;\n this.#projectId = config.projectId?.trim() || null;\n this.#fetch = config.fetchImpl ?? globalThis.fetch;\n }\n\n async request<T>(\n method: string,\n path: string,\n body?: unknown,\n options?: { signal?: AbortSignal; actingUserId?: string },\n ): Promise<T> {\n const response = await this.#send(method, path, body, options);\n if (!response.ok) {\n const message = redact(await extractError(response), this.#accessToken);\n const retryAfterSeconds = parseRetryAfter(response.headers.get('retry-after'));\n logPlatformError('Platform API request failed', {\n method,\n path,\n status: response.status,\n retryAfterSeconds,\n message,\n });\n throw new PlatformApiError(message, response.status, retryAfterSeconds);\n }\n if (response.status === 204) return undefined as T;\n return (await response.json()) as T;\n }\n\n async requestRedirect(method: string, path: string, options?: { signal?: AbortSignal }): Promise<string> {\n const response = await this.#send(method, path, undefined, options, 'manual');\n if (response.status >= 300 && response.status < 400) {\n const location = response.headers.get('location');\n if (location) return location;\n }\n if (!response.ok) {\n const message = redact(await extractError(response), this.#accessToken);\n const retryAfterSeconds = parseRetryAfter(response.headers.get('retry-after'));\n logPlatformError('Platform API redirect request failed', {\n method,\n path,\n status: response.status,\n retryAfterSeconds,\n message,\n });\n throw new PlatformApiError(message, response.status, retryAfterSeconds);\n }\n logPlatformError('Platform API request did not return a redirect', { method, path, status: response.status });\n throw new PlatformApiError('Platform API request did not return a redirect.', response.status);\n }\n\n async #send(\n method: string,\n path: string,\n body?: unknown,\n options?: { signal?: AbortSignal; actingUserId?: string },\n redirect?: RequestInit['redirect'],\n ): Promise<Response> {\n const headers: Record<string, string> = {\n accept: 'application/json',\n authorization: `Bearer ${this.#accessToken}`,\n };\n // Project attribution for proxied provider calls. Org-scoped machine\n // tokens carry no project claim, so without this header the platform\n // records proxy activity with no project.\n if (this.#projectId) {\n headers['x-mastra-project-id'] = this.#projectId;\n }\n // Acting end-user for platform GitHub writes: the platform resolves this\n // user's GitHub OAuth connection (org-scoped) so issues/PRs are authored\n // by the human instead of the App bot. Ignored by older platforms.\n if (options?.actingUserId) {\n headers['x-acting-user-id'] = options.actingUserId;\n }\n const timeoutSignal = AbortSignal.timeout(15_000);\n const init: RequestInit = {\n method,\n headers,\n redirect,\n signal: options?.signal ? AbortSignal.any([options.signal, timeoutSignal]) : timeoutSignal,\n };\n if (body !== undefined) {\n headers['content-type'] = 'application/json';\n init.body = JSON.stringify(body);\n }\n\n try {\n return await this.#fetch(`${this.#baseUrl}${path}`, init);\n } catch (error) {\n if (error instanceof Error && error.message.includes(this.#accessToken)) {\n const redacted = new Error(redact(error.message, this.#accessToken));\n redacted.name = error.name;\n logPlatformError('Platform API transport error', {\n method,\n path,\n name: redacted.name,\n message: redacted.message,\n });\n throw redacted;\n }\n logPlatformError('Platform API transport error', {\n method,\n path,\n name: error instanceof Error ? error.name : undefined,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n}\n\nasync function extractError(response: Response): Promise<string> {\n try {\n const data = (await response.clone().json()) as Record<string, unknown>;\n for (const field of ['detail', 'error', 'title']) {\n if (typeof data[field] === 'string' && data[field]) return data[field];\n }\n } catch {\n // Fall through to the status-based message.\n }\n return `Platform API request failed (${response.status})`;\n}\n\nfunction redact(message: string, accessToken: string): string {\n return message.split(accessToken).join('[REDACTED]');\n}\n\nexport function logPlatformInfo(message: string, fields?: Record<string, unknown>): void {\n writePlatformLog('info', message, fields);\n}\n\n/** Startup detail that `mastra factory dev` hides unless run with `--debug`. */\nexport function logPlatformBootInfo(message: string, fields?: Record<string, unknown>): void {\n if (bootDiagnosticsEnabled) writePlatformLog('info', message, fields);\n}\n\nexport function logPlatformWarn(message: string, fields?: Record<string, unknown>): void {\n writePlatformLog('warn', message, fields);\n}\n\nexport function logPlatformError(message: string, fields?: Record<string, unknown>): void {\n writePlatformLog('error', message, fields);\n}\n\nfunction writePlatformLog(level: 'info' | 'warn' | 'error', message: string, fields?: Record<string, unknown>): void {\n const metadata = fields ? ` ${JSON.stringify(stripUndefined(fields))}` : '';\n process.stderr.write(`[Mastra Factory] ${level.toUpperCase()} ${message}${metadata}\\n`);\n}\n\nfunction stripUndefined(fields: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));\n}\n\nfunction parseRetryAfter(value: string | null): number | null {\n if (!value) return null;\n const seconds = Number.parseInt(value, 10);\n return Number.isSafeInteger(seconds) && seconds >= 0 ? seconds : null;\n}\n"],"mappings":";;AAcA,MAAM,2BAA2B;AACjC,MAAM,6BAA0D;CAC9D,IAAI;CACJ,IAAI;AACN;AAEA,SAAgB,iCAA0D;CAKxE,MAAM,qBAAqB,QAAQ,IAAI,6BAA6B,KAAK,KAAK,uBAAuB;CAIrG,MAAM,cACJ,QAAQ,IAAI,8BAA8B,KAAK,KAAK,QAAQ,IAAI,4BAA4B,KAAK;CACnG,IAAI,CAAC,aACH,MAAM,IAAI,MACR,2HACF;CAEF,MAAM,YAAY,QAAQ,IAAI,mBAAmB,KAAK;CACtD,OAAO;EACL,SAAS,4BAA4B,kBAAkB;EACvD;EACA,GAAI,YAAY,EAAE,UAAU,IAAI,CAAC;CACnC;AACF;;;;;;AAOA,SAAS,yBAAiC;CACxC,MAAM,SAAS,QAAQ,IAAI,wBAAwB,KAAK,CAAC,CAAC,YAAY;CACtE,IAAI,WAAW,QAAQ,WAAW,MAAM,OAAO,2BAA2B;CAC1E,OAAO;AACT;;;;;;;AAQA,SAAS,4BAA4B,oBAAoC;CACvE,OAAO,mBAAmB,QAAQ,QAAQ,EAAE,CAAC,CAAC,QAAQ,SAAS,EAAE;AACnE;AAEA,IAAa,mBAAb,cAAsC,MAAM;CAC1C;CACA;CAEA,YAAY,SAAiB,QAAgB,oBAAmC,MAAM;EACpF,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,oBAAoB;CAC3B;AACF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
98
98
  }).sort((a, b) => a.providerName.localeCompare(b.providerName));
99
- return c.json({ connections });
99
+ return c.json({
100
+ projectId,
101
+ connections
102
+ });
100
103
  } catch (err) {
101
104
  return platformError(c, err);
102
105
  }
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory, and list the\n * Platform project connections whose Mastra Connect tools sessions get.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\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 { PlatformApiClient} from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\nimport { offersSessionTools } from './session-tools.js';\n\ntype RouteContext = Context;\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n gitlab: { integrationId: 'gitlab', connectionIntegrationIds: ['gitlab'] },\n vanta: { integrationId: 'vanta', connectionIntegrationIds: ['vanta'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\ninterface ProjectConnectionRow {\n id: string;\n integrationId: string;\n status: string;\n accountLabel?: string | null;\n}\n\ninterface CatalogEntry {\n id: string;\n displayName?: string | null;\n logoUrl?: string | null;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nexport interface ConnectToolsSource {\n client: PlatformApiClient;\n projectId: string;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\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: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\nexport function buildConnectToolsRoute(auth: RouteAuth, source: ConnectToolsSource | undefined): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (!source) {\n return c.json(\n { error: 'connect_tools_off', message: \"This Factory's sessions don't get Mastra Connect tools.\" },\n 404,\n );\n }\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n const { client, projectId } = source;\n try {\n const [listed, catalog] = await Promise.all([\n client.request<{ connections: ProjectConnectionRow[] }>(\n 'GET',\n `/v2/projects/${encodeURIComponent(projectId)}/connections`,\n ),\n client.request<{ integrations: CatalogEntry[] }>('GET', '/v2/integrations').catch((error: unknown) => {\n console.warn(\n `MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { integrations: [] };\n }),\n ]);\n const entries = new Map(catalog.integrations.map(entry => [entry.id, entry]));\n const connections = listed.connections\n .filter(connection => offersSessionTools(connection.integrationId))\n .map(connection => {\n const entry = entries.get(connection.integrationId);\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n providerName: entry?.displayName ?? connection.integrationId,\n logoUrl: entry?.logoUrl ?? null,\n accountLabel: connection.accountLabel ?? null,\n status: connection.status,\n };\n })\n .sort((a, b) => a.providerName.localeCompare(b.providerName));\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n });\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":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EACF,CAAC;EACD,iBAAiB,oFAAoF;GACnG,QAAQ;GACR,cAAc;GACd,SAAS,OAAM,eAAc;IAC3B,MAAM,IAAI,MAAM,UAAU;IAC1B,MAAM,WAAW,kBAAkB,CAAC;IACpC,IAAI,CAAC,UAAU,OAAO,EAAE,KAAK,EAAE,OAAO,mBAAmB,GAAG,GAAG;IAC/D,MAAM,WAAW,MAAM,iBAAiB,GAAG,IAAI;IAC/C,IAAI,cAAc,UAAU,OAAO,SAAS;IAC5C,MAAM,eAAe,EAAE,IAAI,MAAM,cAAc;IAC/C,IAAI,CAAC,cAAc,OAAO,EAAE,KAAK,EAAE,OAAO,sBAAsB,GAAG,GAAG;IACtE,IAAI;KASF,IAAI,EAJe,MADE,OAAO,QAAkD,OAAO,iBAAiB,EAAA,CAC5E,YAAY,MACpC,cACE,UAAU,OAAO,gBAAgB,SAAS,yBAAyB,SAAS,UAAU,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/integrations/platform/connect/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` that let the Factory SPA connect and reconnect\n * Platform-managed provider accounts without leaving Factory, and list the\n * Platform project connections whose Mastra Connect tools sessions get.\n *\n * The browser cannot talk to the integrations service itself — it has no\n * Platform session — so these routes mint Nango connect/reconnect sessions\n * server-side with the deploy's machine credentials\n * (`MASTRA_PLATFORM_ACCESS_TOKEN`/`MASTRA_PLATFORM_SECRET_KEY`) and hand the\n * short-lived session token back to the SPA, which drives the provider's\n * OAuth popup headlessly via `@nangohq/frontend`. Gating mirrors the\n * Platform's own rule for these providers: a signed-in organization member\n * (org:write parity with Linear), not an organization admin.\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 { PlatformApiClient} from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\nimport { offersSessionTools } from './session-tools.js';\n\ntype RouteContext = Context;\n\nexport interface PlatformConnectProvider {\n /** Platform integration id used to mint connect sessions. */\n integrationId: string;\n /** Connection `integrationId` variants that belong to this provider. */\n connectionIntegrationIds: readonly string[];\n}\n\n/**\n * Providers the Factory SPA may connect through these routes. Keys are the\n * SPA-facing provider slugs; `integrationId` is the Platform catalog id used\n * for new connect sessions. Provider-specific PRs extend this registry when\n * their Factory integrations are available.\n */\nexport const PLATFORM_CONNECT_PROVIDERS: Record<string, PlatformConnectProvider> = {\n jira: { integrationId: 'jira', connectionIntegrationIds: ['jira'] },\n 'incident-io': { integrationId: 'incident-io', connectionIntegrationIds: ['incident-io'] },\n gitlab: { integrationId: 'gitlab', connectionIntegrationIds: ['gitlab'] },\n vanta: { integrationId: 'vanta', connectionIntegrationIds: ['vanta'] },\n};\n\ninterface PlatformConnectionRow {\n id: string;\n integrationId: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n displayName?: string | null;\n connectedAt?: string;\n}\n\ninterface PlatformSessionResponse {\n connectionId: string;\n integrationId: string;\n connectUrl: string;\n sessionToken: string;\n expiresAt: string;\n}\n\ninterface ProjectConnectionRow {\n id: string;\n integrationId: string;\n status: string;\n accountLabel?: string | null;\n}\n\ninterface CatalogEntry {\n id: string;\n displayName?: string | null;\n logoUrl?: string | null;\n}\n\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\n}\n\nexport interface ConnectToolsSource {\n client: PlatformApiClient;\n projectId: string;\n}\n\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n if (!auth.enabled()) {\n return { response: c.json({ error: 'auth_disabled', message: 'Factory auth is not enabled.' }, 403) };\n }\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: 'Provider connections require an organization. Personal accounts cannot connect providers.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction providerFromParam(c: RouteContext): PlatformConnectProvider | null {\n const provider = c.req.param('provider');\n return provider ? (PLATFORM_CONNECT_PROVIDERS[provider] ?? null) : null;\n}\n\nfunction platformError(c: RouteContext, err: unknown) {\n if (err instanceof PlatformApiError) {\n if (err.status === 409) {\n return c.json({ error: 'session_pending', message: err.message }, 409);\n }\n if (err.status === 403) {\n return c.json({ error: 'platform_forbidden', message: err.message }, 403);\n }\n }\n return c.json({ error: 'platform_request_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\nexport function buildConnectToolsRoute(auth: RouteAuth, source: ConnectToolsSource | undefined): ApiRoute {\n return registerApiRoute('/web/integrations/platform/connect-tools', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n if (!source) {\n return c.json(\n { error: 'connect_tools_off', message: \"This Factory's sessions don't get Mastra Connect tools.\" },\n 404,\n );\n }\n if (auth.enabled()) {\n await auth.ensureUser(c);\n if (!auth.tenant(c)) return c.json({ error: 'unauthorized' }, 401);\n }\n const { client, projectId } = source;\n try {\n const [listed, catalog] = await Promise.all([\n client.request<{ connections: ProjectConnectionRow[] }>(\n 'GET',\n `/v2/projects/${encodeURIComponent(projectId)}/connections`,\n ),\n client.request<{ integrations: CatalogEntry[] }>('GET', '/v2/integrations').catch((error: unknown) => {\n console.warn(\n `MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`,\n );\n return { integrations: [] };\n }),\n ]);\n const entries = new Map(catalog.integrations.map(entry => [entry.id, entry]));\n const connections = listed.connections\n .filter(connection => offersSessionTools(connection.integrationId))\n .map(connection => {\n const entry = entries.get(connection.integrationId);\n return {\n id: connection.id,\n integrationId: connection.integrationId,\n providerName: entry?.displayName ?? connection.integrationId,\n logoUrl: entry?.logoUrl ?? null,\n accountLabel: connection.accountLabel ?? null,\n status: connection.status,\n };\n })\n .sort((a, b) => a.providerName.localeCompare(b.providerName));\n return c.json({ projectId, connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n });\n}\n\n/**\n * Build the `/web/integrations/platform/*` routes. Callers only mount these\n * when Platform machine credentials are configured.\n */\nexport function buildPlatformConnectRoutes(options: BuildPlatformConnectRoutesOptions): ApiRoute[] {\n const { auth, client } = options;\n\n return [\n registerApiRoute('/web/integrations/platform/:provider/connections', {\n method: 'GET',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const result = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connections = result.connections.filter(connection =>\n provider.connectionIntegrationIds.includes(connection.integrationId),\n );\n return c.json({ connections });\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n try {\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/integrations/${encodeURIComponent(provider.integrationId)}/connect-sessions`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n registerApiRoute('/web/integrations/platform/:provider/connections/:connectionId/reconnect-session', {\n method: 'POST',\n requiresAuth: false,\n handler: async rawContext => {\n const c = loose(rawContext);\n const provider = providerFromParam(c);\n if (!provider) return c.json({ error: 'unknown_provider' }, 404);\n const resolved = await resolveOrgTenant(c, auth);\n if ('response' in resolved) return resolved.response;\n const connectionId = c.req.param('connectionId');\n if (!connectionId) return c.json({ error: 'connection_required' }, 400);\n try {\n // Confirm the connection belongs to this provider before minting so\n // one provider's page cannot reconnect a different provider's\n // connection through this route family.\n const listed = await client.request<{ connections: PlatformConnectionRow[] }>('GET', '/v2/connections');\n const connection = listed.connections.find(\n candidate =>\n candidate.id === connectionId && provider.connectionIntegrationIds.includes(candidate.integrationId),\n );\n if (!connection) return c.json({ error: 'connection_not_found' }, 404);\n const session = await client.request<PlatformSessionResponse>(\n 'POST',\n `/v2/connections/${encodeURIComponent(connectionId)}/reconnect-session`,\n {},\n );\n c.header('Cache-Control', 'no-store');\n return c.json(session, 201);\n } catch (err) {\n return platformError(c, err);\n }\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;AAwCA,MAAa,6BAAsE;CACjF,MAAM;EAAE,eAAe;EAAQ,0BAA0B,CAAC,MAAM;CAAE;CAClE,eAAe;EAAE,eAAe;EAAe,0BAA0B,CAAC,aAAa;CAAE;CACzF,QAAQ;EAAE,eAAe;EAAU,0BAA0B,CAAC,QAAQ;CAAE;CACxE,OAAO;EAAE,eAAe;EAAS,0BAA0B,CAAC,OAAO;CAAE;AACvE;AA0CA,eAAe,iBACb,GACA,MACiF;CACjF,IAAI,CAAC,KAAK,QAAQ,GAChB,OAAO,EAAE,UAAU,EAAE,KAAK;EAAE,OAAO;EAAiB,SAAS;CAA+B,GAAG,GAAG,EAAE;CAEtG,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAA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ACpC,cACE,UAAU,OAAO,gBAAgB,SAAS,yBAAyB,SAAS,UAAU,aAAa,CAEzF,GAAG,OAAO,EAAE,KAAK,EAAE,OAAO,uBAAuB,GAAG,GAAG;KACrE,MAAM,UAAU,MAAM,OAAO,QAC3B,QACA,mBAAmB,mBAAmB,YAAY,EAAE,qBACpD,CAAC,CACH;KACA,EAAE,OAAO,iBAAiB,UAAU;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;EACF,CAAC;CACH;AACF"}
@@ -33,6 +33,18 @@ export interface PlatformGithubEventWorkerConfig {
33
33
  * GitHub org.
34
34
  */
35
35
  sourceControl: GithubReconcileRepositorySource;
36
+ /**
37
+ * Subscribes to changes of the linked repository set and returns the
38
+ * unsubscribe. With it the worker reads the set from storage once, and again
39
+ * only after a change, so a poll that finds no events costs no storage reads.
40
+ * Without it every poll re-reads the set.
41
+ */
42
+ onRepositoriesChanged?: (listener: () => void) => () => void;
43
+ /**
44
+ * False while changes made on other replicas cannot reach this one; the
45
+ * worker then re-reads the set on every poll. Defaults to true.
46
+ */
47
+ repositoryChangesShared?: () => boolean;
36
48
  ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;
37
49
  reconcileFactoryState?: GithubPullRequestReconciler;
38
50
  reconcileIssuesFactoryState?: GithubIssueReconciler;
@@ -1 +1 @@
1
- {"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/event-worker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAE9F,OAAO,KAAK,EAAE,cAAc,EA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