@mastra/factory 0.28.0-alpha.0 → 0.28.0-alpha.10

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 (746) hide show
  1. package/README.md +528 -161
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +12 -6
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/board-events.d.ts +54 -0
  6. package/dist/boards/board-events.d.ts.map +1 -0
  7. package/dist/boards/board-events.js +87 -0
  8. package/dist/boards/board-events.js.map +1 -0
  9. package/dist/boards/board-writes.d.ts +86 -0
  10. package/dist/boards/board-writes.d.ts.map +1 -0
  11. package/dist/boards/board-writes.js +266 -0
  12. package/dist/boards/board-writes.js.map +1 -0
  13. package/dist/boards/card-facts.d.ts +3 -1
  14. package/dist/boards/card-facts.d.ts.map +1 -1
  15. package/dist/boards/card-facts.js +30 -4
  16. package/dist/boards/card-facts.js.map +1 -1
  17. package/dist/boards/default-board.d.ts +7 -0
  18. package/dist/boards/default-board.d.ts.map +1 -0
  19. package/dist/boards/default-board.js +10 -0
  20. package/dist/boards/default-board.js.map +1 -0
  21. package/dist/boards/define-board.d.ts +56 -23
  22. package/dist/boards/define-board.d.ts.map +1 -1
  23. package/dist/boards/define-board.js +89 -45
  24. package/dist/boards/define-board.js.map +1 -1
  25. package/dist/boards/index.d.ts +6 -9
  26. package/dist/boards/index.d.ts.map +1 -1
  27. package/dist/boards/index.js +6 -20
  28. package/dist/boards/intake-routing.d.ts +55 -11
  29. package/dist/boards/intake-routing.d.ts.map +1 -1
  30. package/dist/boards/intake-routing.js +109 -19
  31. package/dist/boards/intake-routing.js.map +1 -1
  32. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  33. package/dist/boards/legacy-plan-role.js +14 -5
  34. package/dist/boards/legacy-plan-role.js.map +1 -1
  35. package/dist/boards/phase-automation.d.ts +7 -0
  36. package/dist/boards/phase-automation.d.ts.map +1 -1
  37. package/dist/boards/phase-automation.js +19 -3
  38. package/dist/boards/phase-automation.js.map +1 -1
  39. package/dist/boards/phase-runner.d.ts +18 -10
  40. package/dist/boards/phase-runner.d.ts.map +1 -1
  41. package/dist/boards/phase-runner.js +39 -34
  42. package/dist/boards/phase-runner.js.map +1 -1
  43. package/dist/boards/project-boards.d.ts +65 -8
  44. package/dist/boards/project-boards.d.ts.map +1 -1
  45. package/dist/boards/project-boards.js +217 -26
  46. package/dist/boards/project-boards.js.map +1 -1
  47. package/dist/boards/registry.d.ts +7 -1
  48. package/dist/boards/registry.d.ts.map +1 -1
  49. package/dist/boards/registry.js +19 -4
  50. package/dist/boards/registry.js.map +1 -1
  51. package/dist/boards/relocate.d.ts +1 -1
  52. package/dist/boards/relocate.d.ts.map +1 -1
  53. package/dist/boards/relocate.js +3 -2
  54. package/dist/boards/relocate.js.map +1 -1
  55. package/dist/boards/review.d.ts +5 -2
  56. package/dist/boards/review.d.ts.map +1 -1
  57. package/dist/boards/review.js +12 -11
  58. package/dist/boards/review.js.map +1 -1
  59. package/dist/boards/semantics.d.ts +160 -20
  60. package/dist/boards/semantics.d.ts.map +1 -1
  61. package/dist/boards/semantics.js +255 -23
  62. package/dist/boards/semantics.js.map +1 -1
  63. package/dist/boards/stored-board.d.ts +73 -1
  64. package/dist/boards/stored-board.d.ts.map +1 -1
  65. package/dist/boards/stored-board.js +157 -11
  66. package/dist/boards/stored-board.js.map +1 -1
  67. package/dist/boards/work-migrations.d.ts +43 -0
  68. package/dist/boards/work-migrations.d.ts.map +1 -0
  69. package/dist/boards/work-migrations.js +353 -0
  70. package/dist/boards/work-migrations.js.map +1 -0
  71. package/dist/boards/work-routes.d.ts +58 -0
  72. package/dist/boards/work-routes.d.ts.map +1 -0
  73. package/dist/boards/work-routes.js +270 -0
  74. package/dist/boards/work-routes.js.map +1 -0
  75. package/dist/boards/work-seeds.d.ts +9 -0
  76. package/dist/boards/work-seeds.d.ts.map +1 -0
  77. package/dist/boards/work-seeds.js +56 -0
  78. package/dist/boards/work-seeds.js.map +1 -0
  79. package/dist/boards/work.d.ts +8 -19
  80. package/dist/boards/work.d.ts.map +1 -1
  81. package/dist/boards/work.js +33 -281
  82. package/dist/boards/work.js.map +1 -1
  83. package/dist/environment/build-runner.d.ts.map +1 -1
  84. package/dist/environment/build-runner.js +2 -2
  85. package/dist/environment/build-runner.js.map +1 -1
  86. package/dist/environment/build-workflow.d.ts.map +1 -1
  87. package/dist/environment/build-workflow.js +6 -5
  88. package/dist/environment/build-workflow.js.map +1 -1
  89. package/dist/environment/build.d.ts +15 -2
  90. package/dist/environment/build.d.ts.map +1 -1
  91. package/dist/environment/build.js +32 -9
  92. package/dist/environment/build.js.map +1 -1
  93. package/dist/factory.d.ts +90 -9
  94. package/dist/factory.d.ts.map +1 -1
  95. package/dist/factory.js +334 -141
  96. package/dist/factory.js.map +1 -1
  97. package/dist/feed-events.d.ts +4 -4
  98. package/dist/feed-events.d.ts.map +1 -1
  99. package/dist/feed-events.js +6 -6
  100. package/dist/feed-events.js.map +1 -1
  101. package/dist/index.d.ts +10 -3
  102. package/dist/index.d.ts.map +1 -1
  103. package/dist/index.js +7 -4
  104. package/dist/integrations/base.d.ts +12 -13
  105. package/dist/integrations/base.d.ts.map +1 -1
  106. package/dist/integrations/closing-references.d.ts +15 -0
  107. package/dist/integrations/closing-references.d.ts.map +1 -0
  108. package/dist/integrations/closing-references.js +69 -0
  109. package/dist/integrations/closing-references.js.map +1 -0
  110. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  111. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  112. package/dist/integrations/github/acceptance-labels.js +1 -1
  113. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  114. package/dist/integrations/github/default-rules.d.ts +17 -75
  115. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  116. package/dist/integrations/github/default-rules.js +134 -77
  117. package/dist/integrations/github/default-rules.js.map +1 -1
  118. package/dist/integrations/github/integration.d.ts.map +1 -1
  119. package/dist/integrations/github/integration.js +7 -3
  120. package/dist/integrations/github/integration.js.map +1 -1
  121. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  122. package/dist/integrations/github/issue-reconciler.js +21 -3
  123. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  124. package/dist/integrations/github/provenance.js +1 -1
  125. package/dist/integrations/github/provenance.js.map +1 -1
  126. package/dist/integrations/github/pull-request-source.d.ts +8 -0
  127. package/dist/integrations/github/pull-request-source.d.ts.map +1 -0
  128. package/dist/integrations/github/pull-request-source.js +17 -0
  129. package/dist/integrations/github/pull-request-source.js.map +1 -0
  130. package/dist/integrations/github/reconcile-worker.d.ts +5 -1
  131. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  132. package/dist/integrations/github/reconcile-worker.js +39 -6
  133. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  134. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  135. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  136. package/dist/integrations/github/review-status-comment.js +217 -0
  137. package/dist/integrations/github/review-status-comment.js.map +1 -0
  138. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  139. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  140. package/dist/integrations/github/review-status-reporter.js +104 -0
  141. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  142. package/dist/integrations/github/review-status.d.ts +28 -0
  143. package/dist/integrations/github/review-status.d.ts.map +1 -0
  144. package/dist/integrations/github/review-status.js +95 -0
  145. package/dist/integrations/github/review-status.js.map +1 -0
  146. package/dist/integrations/github/routes.d.ts +4 -3
  147. package/dist/integrations/github/routes.d.ts.map +1 -1
  148. package/dist/integrations/github/routes.js +11 -91
  149. package/dist/integrations/github/routes.js.map +1 -1
  150. package/dist/integrations/github/rules.d.ts +92 -8
  151. package/dist/integrations/github/rules.d.ts.map +1 -1
  152. package/dist/integrations/github/rules.js +498 -103
  153. package/dist/integrations/github/rules.js.map +1 -1
  154. package/dist/integrations/github/sandbox.d.ts +10 -2
  155. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  156. package/dist/integrations/github/sandbox.js +20 -4
  157. package/dist/integrations/github/sandbox.js.map +1 -1
  158. package/dist/integrations/github/session-subscriptions.js +2 -2
  159. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  160. package/dist/integrations/github/token-refresh.d.ts +2 -1
  161. package/dist/integrations/github/token-refresh.d.ts.map +1 -1
  162. package/dist/integrations/github/token-refresh.js.map +1 -1
  163. package/dist/integrations/gitlab/agent-tools.js +1 -1
  164. package/dist/integrations/gitlab/default-rules.d.ts +96 -39
  165. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  166. package/dist/integrations/gitlab/default-rules.js +109 -46
  167. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  168. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  169. package/dist/integrations/gitlab/issue-reconciler.js +2 -1
  170. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  171. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  172. package/dist/integrations/gitlab/merge-request-reconciler.js +12 -5
  173. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  174. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  175. package/dist/integrations/gitlab/routes.js +2 -6
  176. package/dist/integrations/gitlab/routes.js.map +1 -1
  177. package/dist/integrations/gitlab/rules.d.ts +22 -1
  178. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  179. package/dist/integrations/gitlab/rules.js +188 -34
  180. package/dist/integrations/gitlab/rules.js.map +1 -1
  181. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  182. package/dist/integrations/incidentio/agent-tools.js +6 -6
  183. package/dist/integrations/incidentio/agent-tools.js.map +1 -1
  184. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  185. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  186. package/dist/integrations/incidentio/default-rules.js +6 -7
  187. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  188. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  189. package/dist/integrations/incidentio/issue-reconciler.js +2 -1
  190. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  191. package/dist/integrations/incidentio/routes.d.ts +2 -2
  192. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  193. package/dist/integrations/incidentio/routes.js +11 -17
  194. package/dist/integrations/incidentio/routes.js.map +1 -1
  195. package/dist/integrations/incidentio/rules.d.ts +11 -4
  196. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  197. package/dist/integrations/incidentio/rules.js +52 -16
  198. package/dist/integrations/incidentio/rules.js.map +1 -1
  199. package/dist/integrations/issue-reconciler.js +1 -1
  200. package/dist/integrations/issue-reconciler.js.map +1 -1
  201. package/dist/integrations/jira/agent-tools.js +1 -1
  202. package/dist/integrations/jira/binding-scope.d.ts +5 -6
  203. package/dist/integrations/jira/binding-scope.d.ts.map +1 -1
  204. package/dist/integrations/jira/binding-scope.js +9 -11
  205. package/dist/integrations/jira/binding-scope.js.map +1 -1
  206. package/dist/integrations/jira/default-rules.d.ts +1 -9
  207. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  208. package/dist/integrations/jira/default-rules.js +6 -7
  209. package/dist/integrations/jira/default-rules.js.map +1 -1
  210. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  211. package/dist/integrations/jira/issue-reconciler.js +2 -1
  212. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  213. package/dist/integrations/jira/routes.d.ts.map +1 -1
  214. package/dist/integrations/jira/routes.js +4 -9
  215. package/dist/integrations/jira/routes.js.map +1 -1
  216. package/dist/integrations/jira/rules.d.ts +11 -4
  217. package/dist/integrations/jira/rules.d.ts.map +1 -1
  218. package/dist/integrations/jira/rules.js +52 -16
  219. package/dist/integrations/jira/rules.js.map +1 -1
  220. package/dist/integrations/linear/agent-tools.d.ts +9 -1
  221. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  222. package/dist/integrations/linear/agent-tools.js +81 -3
  223. package/dist/integrations/linear/agent-tools.js.map +1 -1
  224. package/dist/integrations/linear/default-rules.d.ts +1 -9
  225. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  226. package/dist/integrations/linear/default-rules.js +6 -7
  227. package/dist/integrations/linear/default-rules.js.map +1 -1
  228. package/dist/integrations/linear/integration.d.ts +4 -1
  229. package/dist/integrations/linear/integration.d.ts.map +1 -1
  230. package/dist/integrations/linear/integration.js +21 -1
  231. package/dist/integrations/linear/integration.js.map +1 -1
  232. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  233. package/dist/integrations/linear/issue-reconciler.js +2 -1
  234. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  235. package/dist/integrations/linear/routes.d.ts +2 -1
  236. package/dist/integrations/linear/routes.d.ts.map +1 -1
  237. package/dist/integrations/linear/routes.js +16 -21
  238. package/dist/integrations/linear/routes.js.map +1 -1
  239. package/dist/integrations/linear/rules.d.ts +11 -4
  240. package/dist/integrations/linear/rules.d.ts.map +1 -1
  241. package/dist/integrations/linear/rules.js +50 -17
  242. package/dist/integrations/linear/rules.js.map +1 -1
  243. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  244. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  245. package/dist/integrations/platform/connect/routes.js +42 -5
  246. package/dist/integrations/platform/connect/routes.js.map +1 -1
  247. package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
  248. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  249. package/dist/integrations/platform/connect/session-tools.js +35 -0
  250. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  251. package/dist/integrations/platform/github/event-worker.d.ts +4 -1
  252. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  253. package/dist/integrations/platform/github/event-worker.js +39 -3
  254. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  255. package/dist/integrations/platform/github/integration.d.ts +8 -0
  256. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  257. package/dist/integrations/platform/github/integration.js +132 -90
  258. package/dist/integrations/platform/github/integration.js.map +1 -1
  259. package/dist/integrations/platform/jira/agent-tools.js +1 -1
  260. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  261. package/dist/integrations/platform/jira/routes.js +4 -9
  262. package/dist/integrations/platform/jira/routes.js.map +1 -1
  263. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  264. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  265. package/dist/integrations/platform/linear/event-worker.js +10 -1
  266. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  267. package/dist/integrations/platform/linear/integration.d.ts +1 -1
  268. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  269. package/dist/integrations/platform/linear/integration.js +7 -8
  270. package/dist/integrations/platform/linear/integration.js.map +1 -1
  271. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  272. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  273. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  274. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  275. package/dist/integrations/slack/chat-tools.js +1 -1
  276. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  277. package/dist/integrations/slack/connect-route.js +1 -1
  278. package/dist/integrations/slack/connect-route.js.map +1 -1
  279. package/dist/integrations/slack/integration.d.ts +0 -2
  280. package/dist/integrations/slack/integration.d.ts.map +1 -1
  281. package/dist/integrations/slack/integration.js +2 -5
  282. package/dist/integrations/slack/integration.js.map +1 -1
  283. package/dist/integrations/slack/reply-tool.js +1 -1
  284. package/dist/integrations/slack/run-error-card.js +1 -0
  285. package/dist/integrations/slack/run-error-card.js.map +1 -1
  286. package/dist/integrations/slack/share-file-tool.js +1 -1
  287. package/dist/integrations/slack/slack.d.ts +23 -30
  288. package/dist/integrations/slack/slack.d.ts.map +1 -1
  289. package/dist/integrations/slack/slack.js +131 -125
  290. package/dist/integrations/slack/slack.js.map +1 -1
  291. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  292. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  293. package/dist/integrations/slack/voice-clips.js +201 -0
  294. package/dist/integrations/slack/voice-clips.js.map +1 -0
  295. package/dist/integrations/workos/integration.d.ts.map +1 -1
  296. package/dist/integrations/workos/integration.js +1 -3
  297. package/dist/integrations/workos/integration.js.map +1 -1
  298. package/dist/links.d.ts +1 -2
  299. package/dist/links.d.ts.map +1 -1
  300. package/dist/links.js +4 -4
  301. package/dist/links.js.map +1 -1
  302. package/dist/mcp/routes.js +2 -2
  303. package/dist/mcp/routes.js.map +1 -1
  304. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  305. package/dist/provider-display-name.d.ts.map +1 -1
  306. package/dist/provider-display-name.js +1 -0
  307. package/dist/provider-display-name.js.map +1 -1
  308. package/dist/routes/attention-parked.d.ts +1 -0
  309. package/dist/routes/attention-parked.d.ts.map +1 -1
  310. package/dist/routes/attention-parked.js +2 -2
  311. package/dist/routes/attention-parked.js.map +1 -1
  312. package/dist/routes/attention-providers.d.ts +0 -25
  313. package/dist/routes/attention-providers.d.ts.map +1 -1
  314. package/dist/routes/attention-providers.js +3 -151
  315. package/dist/routes/attention-providers.js.map +1 -1
  316. package/dist/routes/attention.d.ts +0 -2
  317. package/dist/routes/attention.d.ts.map +1 -1
  318. package/dist/routes/attention.js +2 -13
  319. package/dist/routes/attention.js.map +1 -1
  320. package/dist/routes/automation-runs.d.ts +5 -1
  321. package/dist/routes/automation-runs.d.ts.map +1 -1
  322. package/dist/routes/automation-runs.js +16 -4
  323. package/dist/routes/automation-runs.js.map +1 -1
  324. package/dist/routes/board-snapshot.d.ts +15 -0
  325. package/dist/routes/board-snapshot.d.ts.map +1 -0
  326. package/dist/routes/board-snapshot.js +41 -0
  327. package/dist/routes/board-snapshot.js.map +1 -0
  328. package/dist/routes/boards.d.ts +9 -7
  329. package/dist/routes/boards.d.ts.map +1 -1
  330. package/dist/routes/boards.js +59 -145
  331. package/dist/routes/boards.js.map +1 -1
  332. package/dist/routes/config.d.ts +11 -1
  333. package/dist/routes/config.d.ts.map +1 -1
  334. package/dist/routes/config.js +122 -29
  335. package/dist/routes/config.js.map +1 -1
  336. package/dist/routes/contracts.d.ts +366 -34
  337. package/dist/routes/contracts.d.ts.map +1 -1
  338. package/dist/routes/contracts.js +179 -51
  339. package/dist/routes/contracts.js.map +1 -1
  340. package/dist/routes/feed-events.d.ts +15 -0
  341. package/dist/routes/feed-events.d.ts.map +1 -0
  342. package/dist/routes/feed-events.js +68 -0
  343. package/dist/routes/feed-events.js.map +1 -0
  344. package/dist/routes/fs.d.ts +4 -0
  345. package/dist/routes/fs.d.ts.map +1 -1
  346. package/dist/routes/fs.js +9 -8
  347. package/dist/routes/fs.js.map +1 -1
  348. package/dist/routes/intake-routes.d.ts.map +1 -1
  349. package/dist/routes/intake-routes.js +25 -13
  350. package/dist/routes/intake-routes.js.map +1 -1
  351. package/dist/routes/intake.d.ts +0 -23
  352. package/dist/routes/intake.d.ts.map +1 -1
  353. package/dist/routes/intake.js +16 -314
  354. package/dist/routes/intake.js.map +1 -1
  355. package/dist/routes/knowledge.d.ts.map +1 -1
  356. package/dist/routes/knowledge.js +2 -5
  357. package/dist/routes/knowledge.js.map +1 -1
  358. package/dist/routes/mastra-gateway.d.ts +19 -0
  359. package/dist/routes/mastra-gateway.d.ts.map +1 -0
  360. package/dist/routes/mastra-gateway.js +120 -0
  361. package/dist/routes/mastra-gateway.js.map +1 -0
  362. package/dist/routes/oauth.d.ts.map +1 -1
  363. package/dist/routes/oauth.js +1 -4
  364. package/dist/routes/oauth.js.map +1 -1
  365. package/dist/routes/projects.d.ts +3 -0
  366. package/dist/routes/projects.d.ts.map +1 -1
  367. package/dist/routes/projects.js +80 -61
  368. package/dist/routes/projects.js.map +1 -1
  369. package/dist/routes/provider-credentials.d.ts +6 -1
  370. package/dist/routes/provider-credentials.d.ts.map +1 -1
  371. package/dist/routes/provider-credentials.js +44 -3
  372. package/dist/routes/provider-credentials.js.map +1 -1
  373. package/dist/routes/route.d.ts +8 -0
  374. package/dist/routes/route.d.ts.map +1 -1
  375. package/dist/routes/route.js +5 -1
  376. package/dist/routes/route.js.map +1 -1
  377. package/dist/routes/running-packages.d.ts +13 -0
  378. package/dist/routes/running-packages.d.ts.map +1 -0
  379. package/dist/routes/running-packages.js +45 -0
  380. package/dist/routes/running-packages.js.map +1 -0
  381. package/dist/routes/sandbox-envs.d.ts +26 -0
  382. package/dist/routes/sandbox-envs.d.ts.map +1 -0
  383. package/dist/routes/sandbox-envs.js +180 -0
  384. package/dist/routes/sandbox-envs.js.map +1 -0
  385. package/dist/routes/session-access.d.ts.map +1 -1
  386. package/dist/routes/session-access.js +12 -3
  387. package/dist/routes/session-access.js.map +1 -1
  388. package/dist/routes/skills.d.ts.map +1 -1
  389. package/dist/routes/skills.js +1 -4
  390. package/dist/routes/skills.js.map +1 -1
  391. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  392. package/dist/routes/source-control-sessions.js +1 -3
  393. package/dist/routes/source-control-sessions.js.map +1 -1
  394. package/dist/routes/source-control-settings.d.ts.map +1 -1
  395. package/dist/routes/source-control-settings.js +3 -2
  396. package/dist/routes/source-control-settings.js.map +1 -1
  397. package/dist/routes/surface.d.ts +13 -9
  398. package/dist/routes/surface.d.ts.map +1 -1
  399. package/dist/routes/surface.js +116 -43
  400. package/dist/routes/surface.js.map +1 -1
  401. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  402. package/dist/routes/tenant-credentials.js +5 -1
  403. package/dist/routes/tenant-credentials.js.map +1 -1
  404. package/dist/routes/voice.d.ts +48 -0
  405. package/dist/routes/voice.d.ts.map +1 -0
  406. package/dist/routes/voice.js +248 -0
  407. package/dist/routes/voice.js.map +1 -0
  408. package/dist/routes/work-items.d.ts +0 -3
  409. package/dist/routes/work-items.d.ts.map +1 -1
  410. package/dist/routes/work-items.js +39 -14
  411. package/dist/routes/work-items.js.map +1 -1
  412. package/dist/rules/binding-context.d.ts.map +1 -1
  413. package/dist/rules/binding-context.js +1 -0
  414. package/dist/rules/binding-context.js.map +1 -1
  415. package/dist/rules/decision-applicability.js +1 -1
  416. package/dist/rules/dispatcher.d.ts +28 -9
  417. package/dist/rules/dispatcher.d.ts.map +1 -1
  418. package/dist/rules/dispatcher.js +734 -143
  419. package/dist/rules/dispatcher.js.map +1 -1
  420. package/dist/rules/event-rules.d.ts +71 -1
  421. package/dist/rules/event-rules.d.ts.map +1 -1
  422. package/dist/rules/event-rules.js +94 -1
  423. package/dist/rules/event-rules.js.map +1 -1
  424. package/dist/rules/index.d.ts +2 -4
  425. package/dist/rules/index.d.ts.map +1 -1
  426. package/dist/rules/index.js +2 -3
  427. package/dist/rules/phase-goal.d.ts +54 -0
  428. package/dist/rules/phase-goal.d.ts.map +1 -0
  429. package/dist/rules/phase-goal.js +70 -0
  430. package/dist/rules/phase-goal.js.map +1 -0
  431. package/dist/rules/phase-tools.d.ts +11 -0
  432. package/dist/rules/phase-tools.d.ts.map +1 -0
  433. package/dist/rules/phase-tools.js +19 -0
  434. package/dist/rules/phase-tools.js.map +1 -0
  435. package/dist/rules/processor.d.ts.map +1 -1
  436. package/dist/rules/processor.js +116 -15
  437. package/dist/rules/processor.js.map +1 -1
  438. package/dist/rules/review-source-tool.d.ts +4 -1
  439. package/dist/rules/review-source-tool.d.ts.map +1 -1
  440. package/dist/rules/review-source-tool.js +24 -4
  441. package/dist/rules/review-source-tool.js.map +1 -1
  442. package/dist/rules/rule-group.d.ts +1 -1
  443. package/dist/rules/rule-group.d.ts.map +1 -1
  444. package/dist/rules/rule-group.js +15 -6
  445. package/dist/rules/rule-group.js.map +1 -1
  446. package/dist/rules/start-coordinator.d.ts +5 -1
  447. package/dist/rules/start-coordinator.d.ts.map +1 -1
  448. package/dist/rules/start-coordinator.js +9 -3
  449. package/dist/rules/start-coordinator.js.map +1 -1
  450. package/dist/rules/tools.d.ts.map +1 -1
  451. package/dist/rules/tools.js +39 -28
  452. package/dist/rules/tools.js.map +1 -1
  453. package/dist/rules/transition-service.d.ts +10 -7
  454. package/dist/rules/transition-service.d.ts.map +1 -1
  455. package/dist/rules/transition-service.js +63 -55
  456. package/dist/rules/transition-service.js.map +1 -1
  457. package/dist/rules/types.d.ts +140 -39
  458. package/dist/rules/types.d.ts.map +1 -1
  459. package/dist/rules/types.js +7 -41
  460. package/dist/rules/types.js.map +1 -1
  461. package/dist/rules/validation.d.ts.map +1 -1
  462. package/dist/rules/validation.js +89 -4
  463. package/dist/rules/validation.js.map +1 -1
  464. package/dist/run-error.d.ts +1 -1
  465. package/dist/run-error.d.ts.map +1 -1
  466. package/dist/run-error.js +38 -5
  467. package/dist/run-error.js.map +1 -1
  468. package/dist/sandbox/sandbox-env-cache.d.ts +33 -0
  469. package/dist/sandbox/sandbox-env-cache.d.ts.map +1 -0
  470. package/dist/sandbox/sandbox-env-cache.js +140 -0
  471. package/dist/sandbox/sandbox-env-cache.js.map +1 -0
  472. package/dist/sandbox/sandbox-env.d.ts +77 -0
  473. package/dist/sandbox/sandbox-env.d.ts.map +1 -0
  474. package/dist/sandbox/sandbox-env.js +130 -0
  475. package/dist/sandbox/sandbox-env.js.map +1 -0
  476. package/dist/secret-encryption.d.ts +21 -0
  477. package/dist/secret-encryption.d.ts.map +1 -1
  478. package/dist/secret-encryption.js +31 -4
  479. package/dist/secret-encryption.js.map +1 -1
  480. package/dist/session/credential-policy.d.ts +2 -2
  481. package/dist/session/credential-policy.d.ts.map +1 -1
  482. package/dist/session/credential-policy.js +3 -3
  483. package/dist/session/credential-policy.js.map +1 -1
  484. package/dist/session/default-model-hydration.d.ts +2 -2
  485. package/dist/session/default-model-hydration.d.ts.map +1 -1
  486. package/dist/session/default-model-hydration.js +4 -4
  487. package/dist/session/default-model-hydration.js.map +1 -1
  488. package/dist/session/live-sessions.d.ts +11 -4
  489. package/dist/session/live-sessions.d.ts.map +1 -1
  490. package/dist/session/live-sessions.js +31 -10
  491. package/dist/session/live-sessions.js.map +1 -1
  492. package/dist/session/self-review-gate.d.ts +6 -4
  493. package/dist/session/self-review-gate.d.ts.map +1 -1
  494. package/dist/session/self-review-gate.js +9 -12
  495. package/dist/session/self-review-gate.js.map +1 -1
  496. package/dist/session/session-threads.d.ts +10 -3
  497. package/dist/session/session-threads.d.ts.map +1 -1
  498. package/dist/session/session-threads.js +11 -1
  499. package/dist/session/session-threads.js.map +1 -1
  500. package/dist/session/source-control-tools.d.ts +39 -13
  501. package/dist/session/source-control-tools.d.ts.map +1 -1
  502. package/dist/session/source-control-tools.js +55 -61
  503. package/dist/session/source-control-tools.js.map +1 -1
  504. package/dist/session/work-item-state-processor.d.ts +24 -0
  505. package/dist/session/work-item-state-processor.d.ts.map +1 -0
  506. package/dist/session/work-item-state-processor.js +275 -0
  507. package/dist/session/work-item-state-processor.js.map +1 -0
  508. package/dist/skills/catalog.js +1 -1
  509. package/dist/storage/domains/audit/actions.d.ts +3 -2
  510. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  511. package/dist/storage/domains/audit/actions.js +7 -5
  512. package/dist/storage/domains/audit/actions.js.map +1 -1
  513. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  514. package/dist/storage/domains/audit/domain.js +1 -3
  515. package/dist/storage/domains/audit/domain.js.map +1 -1
  516. package/dist/storage/domains/boards/base.d.ts +107 -23
  517. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  518. package/dist/storage/domains/boards/base.js +201 -65
  519. package/dist/storage/domains/boards/base.js.map +1 -1
  520. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  521. package/dist/storage/domains/boards/schemas.js +25 -1
  522. package/dist/storage/domains/boards/schemas.js.map +1 -1
  523. package/dist/storage/domains/channel-identity/base.d.ts +0 -4
  524. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
  525. package/dist/storage/domains/channel-identity/base.js +0 -7
  526. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  527. package/dist/storage/domains/intake/base.d.ts +5 -45
  528. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  529. package/dist/storage/domains/intake/base.js +11 -89
  530. package/dist/storage/domains/intake/base.js.map +1 -1
  531. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  532. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  533. package/dist/storage/domains/memory-settings/base.js +1 -11
  534. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  535. package/dist/storage/domains/projects/base.d.ts +23 -9
  536. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  537. package/dist/storage/domains/projects/base.js +24 -8
  538. package/dist/storage/domains/projects/base.js.map +1 -1
  539. package/dist/storage/domains/sandbox-envs/base.d.ts +70 -0
  540. package/dist/storage/domains/sandbox-envs/base.d.ts.map +1 -0
  541. package/dist/storage/domains/sandbox-envs/base.js +227 -0
  542. package/dist/storage/domains/sandbox-envs/base.js.map +1 -0
  543. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  544. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  545. package/dist/storage/domains/voice-settings/base.js +81 -0
  546. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  547. package/dist/storage/domains/work-items/base.d.ts +93 -24
  548. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  549. package/dist/storage/domains/work-items/base.js +413 -188
  550. package/dist/storage/domains/work-items/base.js.map +1 -1
  551. package/dist/storage/domains/work-items/board-version.d.ts +6 -2
  552. package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
  553. package/dist/storage/domains/work-items/board-version.js +20 -9
  554. package/dist/storage/domains/work-items/board-version.js.map +1 -1
  555. package/dist/storage/domains/work-items/cards.d.ts +33 -5
  556. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  557. package/dist/storage/domains/work-items/cards.js +208 -25
  558. package/dist/storage/domains/work-items/cards.js.map +1 -1
  559. package/dist/storage/domains/work-items/legacy-review.d.ts +63 -0
  560. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -0
  561. package/dist/storage/domains/work-items/legacy-review.js +109 -0
  562. package/dist/storage/domains/work-items/legacy-review.js.map +1 -0
  563. package/dist/storage/domains/work-items/metrics.d.ts +12 -4
  564. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
  565. package/dist/storage/domains/work-items/metrics.js +14 -32
  566. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  567. package/dist/storage/domains/work-items/work-item-schema.d.ts +6 -2
  568. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  569. package/dist/storage/domains/work-items/work-item-schema.js +83 -27
  570. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  571. package/dist/timing.d.ts +1 -0
  572. package/dist/timing.d.ts.map +1 -1
  573. package/dist/timing.js +1 -1
  574. package/dist/timing.js.map +1 -1
  575. package/dist/tools/approval-tools.d.ts.map +1 -1
  576. package/dist/tools/approval-tools.js +28 -9
  577. package/dist/tools/approval-tools.js.map +1 -1
  578. package/dist/tools/index.d.ts +1 -1
  579. package/dist/tools/index.js +1 -1
  580. package/dist/tools/index.js.map +1 -1
  581. package/dist/tools/messaging-tools.d.ts +3 -0
  582. package/dist/tools/messaging-tools.d.ts.map +1 -1
  583. package/dist/tools/messaging-tools.js +2 -1
  584. package/dist/tools/messaging-tools.js.map +1 -1
  585. package/dist/tools/read-tools.d.ts +10 -6
  586. package/dist/tools/read-tools.d.ts.map +1 -1
  587. package/dist/tools/read-tools.js +89 -39
  588. package/dist/tools/read-tools.js.map +1 -1
  589. package/dist/tools/reports.d.ts +1 -0
  590. package/dist/tools/reports.d.ts.map +1 -1
  591. package/dist/tools/reports.js +2 -1
  592. package/dist/tools/reports.js.map +1 -1
  593. package/dist/tools/run-watch.d.ts +1 -1
  594. package/dist/tools/run-watch.d.ts.map +1 -1
  595. package/dist/tools/run-watch.js +1 -0
  596. package/dist/tools/run-watch.js.map +1 -1
  597. package/dist/tools/sandbox-tools.js +1 -1
  598. package/dist/tools/session-tools.d.ts +1 -1
  599. package/dist/tools/session-tools.d.ts.map +1 -1
  600. package/dist/tools/session-tools.js +1 -1
  601. package/dist/tools/session-tools.js.map +1 -1
  602. package/dist/tools/sessions-state-processor.d.ts +3 -1
  603. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  604. package/dist/tools/sessions-state-processor.js +13 -4
  605. package/dist/tools/sessions-state-processor.js.map +1 -1
  606. package/dist/tools/side-sessions.d.ts +2 -0
  607. package/dist/tools/side-sessions.d.ts.map +1 -1
  608. package/dist/tools/side-sessions.js +2 -1
  609. package/dist/tools/side-sessions.js.map +1 -1
  610. package/dist/tools/work-item-tools.d.ts +0 -3
  611. package/dist/tools/work-item-tools.d.ts.map +1 -1
  612. package/dist/tools/work-item-tools.js +10 -20
  613. package/dist/tools/work-item-tools.js.map +1 -1
  614. package/dist/voice/rate-limit.d.ts +13 -0
  615. package/dist/voice/rate-limit.d.ts.map +1 -0
  616. package/dist/voice/rate-limit.js +36 -0
  617. package/dist/voice/rate-limit.js.map +1 -0
  618. package/dist/voice/realtime.d.ts +13 -0
  619. package/dist/voice/realtime.d.ts.map +1 -0
  620. package/dist/voice/realtime.js +56 -0
  621. package/dist/voice/realtime.js.map +1 -0
  622. package/dist/voice/transcription.d.ts +51 -0
  623. package/dist/voice/transcription.d.ts.map +1 -0
  624. package/dist/voice/transcription.js +112 -0
  625. package/dist/voice/transcription.js.map +1 -0
  626. package/dist/work-item-branch.d.ts +13 -0
  627. package/dist/work-item-branch.d.ts.map +1 -1
  628. package/dist/work-item-branch.js +16 -1
  629. package/dist/work-item-branch.js.map +1 -1
  630. package/dist/work-items/create-work-item.d.ts +6 -0
  631. package/dist/work-items/create-work-item.d.ts.map +1 -1
  632. package/dist/work-items/create-work-item.js +28 -3
  633. package/dist/work-items/create-work-item.js.map +1 -1
  634. package/dist/work-items/description-context.d.ts +5 -0
  635. package/dist/work-items/description-context.d.ts.map +1 -0
  636. package/dist/work-items/description-context.js +17 -0
  637. package/dist/work-items/description-context.js.map +1 -0
  638. package/dist/work-items/providers/base.d.ts +4 -1
  639. package/dist/work-items/providers/base.d.ts.map +1 -1
  640. package/dist/work-items/providers/base.js +6 -1
  641. package/dist/work-items/providers/base.js.map +1 -1
  642. package/dist/work-items/providers/github.d.ts.map +1 -1
  643. package/dist/work-items/providers/github.js +2 -1
  644. package/dist/work-items/providers/github.js.map +1 -1
  645. package/dist/work-items/providers/gitlab.d.ts.map +1 -1
  646. package/dist/work-items/providers/gitlab.js +2 -1
  647. package/dist/work-items/providers/gitlab.js.map +1 -1
  648. package/dist/work-items/providers/jira.d.ts.map +1 -1
  649. package/dist/work-items/providers/jira.js +3 -2
  650. package/dist/work-items/providers/jira.js.map +1 -1
  651. package/dist/work-items/providers/linear.d.ts.map +1 -1
  652. package/dist/work-items/providers/linear.js +3 -2
  653. package/dist/work-items/providers/linear.js.map +1 -1
  654. package/dist/work-items/providers/types.d.ts +6 -0
  655. package/dist/work-items/providers/types.d.ts.map +1 -1
  656. package/dist/work-items/split-backfill.d.ts +13 -0
  657. package/dist/work-items/split-backfill.d.ts.map +1 -0
  658. package/dist/work-items/split-backfill.js +32 -0
  659. package/dist/work-items/split-backfill.js.map +1 -0
  660. package/dist/work-items/split-migration.d.ts +39 -2
  661. package/dist/work-items/split-migration.d.ts.map +1 -1
  662. package/dist/work-items/split-migration.js +178 -70
  663. package/dist/work-items/split-migration.js.map +1 -1
  664. package/dist/workspace.d.ts +3 -1
  665. package/dist/workspace.d.ts.map +1 -1
  666. package/dist/workspace.js +118 -34
  667. package/dist/workspace.js.map +1 -1
  668. package/factory-skills/configure-factory-rules/SKILL.md +13 -11
  669. package/factory-skills/factory-build/SKILL.md +64 -0
  670. package/factory-skills/factory-gitlab-rereview/SKILL.md +4 -4
  671. package/factory-skills/factory-gitlab-review/SKILL.md +6 -6
  672. package/factory-skills/factory-plan/SKILL.md +8 -10
  673. package/factory-skills/factory-rereview/SKILL.md +74 -28
  674. package/factory-skills/factory-review/SKILL.md +85 -29
  675. package/factory-skills/factory-self-review/SKILL.md +32 -13
  676. package/factory-skills/factory-triage/SKILL.md +36 -32
  677. package/package.json +12 -11
  678. package/dist/boards/index.js.map +0 -1
  679. package/dist/boards/pull-request-review.d.ts +0 -14
  680. package/dist/boards/pull-request-review.d.ts.map +0 -1
  681. package/dist/boards/pull-request-review.js +0 -81
  682. package/dist/boards/pull-request-review.js.map +0 -1
  683. package/dist/boards/work-tool-rules.d.ts +0 -8
  684. package/dist/boards/work-tool-rules.d.ts.map +0 -1
  685. package/dist/boards/work-tool-rules.js +0 -19
  686. package/dist/boards/work-tool-rules.js.map +0 -1
  687. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
  688. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
  689. package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
  690. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
  691. package/dist/integrations/slack/emoji.d.ts +0 -3
  692. package/dist/integrations/slack/emoji.d.ts.map +0 -1
  693. package/dist/integrations/slack/emoji.js +0 -11
  694. package/dist/integrations/slack/emoji.js.map +0 -1
  695. package/dist/integrations/slack/feed-publisher.d.ts +0 -26
  696. package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
  697. package/dist/integrations/slack/feed-publisher.js +0 -43
  698. package/dist/integrations/slack/feed-publisher.js.map +0 -1
  699. package/dist/routes/attention-activity.d.ts +0 -23
  700. package/dist/routes/attention-activity.d.ts.map +0 -1
  701. package/dist/routes/attention-activity.js +0 -154
  702. package/dist/routes/attention-activity.js.map +0 -1
  703. package/dist/rules/resolve.d.ts +0 -15
  704. package/dist/rules/resolve.d.ts.map +0 -1
  705. package/dist/rules/resolve.js +0 -22
  706. package/dist/rules/resolve.js.map +0 -1
  707. package/dist/storage/domains/comments/activity.d.ts +0 -40
  708. package/dist/storage/domains/comments/activity.d.ts.map +0 -1
  709. package/dist/storage/domains/comments/activity.js +0 -93
  710. package/dist/storage/domains/comments/activity.js.map +0 -1
  711. package/dist/storage/domains/comments/actor.d.ts +0 -51
  712. package/dist/storage/domains/comments/actor.d.ts.map +0 -1
  713. package/dist/storage/domains/comments/actor.js +0 -37
  714. package/dist/storage/domains/comments/actor.js.map +0 -1
  715. package/dist/storage/domains/comments/base.d.ts +0 -245
  716. package/dist/storage/domains/comments/base.d.ts.map +0 -1
  717. package/dist/storage/domains/comments/base.js +0 -539
  718. package/dist/storage/domains/comments/base.js.map +0 -1
  719. package/dist/storage/domains/comments/domain.d.ts +0 -135
  720. package/dist/storage/domains/comments/domain.d.ts.map +0 -1
  721. package/dist/storage/domains/comments/domain.js +0 -284
  722. package/dist/storage/domains/comments/domain.js.map +0 -1
  723. package/dist/storage/domains/comments/feed-context.d.ts +0 -22
  724. package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
  725. package/dist/storage/domains/comments/feed-context.js +0 -88
  726. package/dist/storage/domains/comments/feed-context.js.map +0 -1
  727. package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
  728. package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
  729. package/dist/storage/domains/comments/feed-sync.js +0 -1
  730. package/dist/storage/domains/comments/parse.d.ts +0 -23
  731. package/dist/storage/domains/comments/parse.d.ts.map +0 -1
  732. package/dist/storage/domains/comments/parse.js +0 -89
  733. package/dist/storage/domains/comments/parse.js.map +0 -1
  734. package/dist/storage/domains/comments/routes.d.ts +0 -24
  735. package/dist/storage/domains/comments/routes.d.ts.map +0 -1
  736. package/dist/storage/domains/comments/routes.js +0 -301
  737. package/dist/storage/domains/comments/routes.js.map +0 -1
  738. package/dist/storage/domains/comments/schema.d.ts +0 -5
  739. package/dist/storage/domains/comments/schema.d.ts.map +0 -1
  740. package/dist/storage/domains/comments/schema.js +0 -178
  741. package/dist/storage/domains/comments/schema.js.map +0 -1
  742. package/dist/storage/domains/comments/wire.d.ts +0 -40
  743. package/dist/storage/domains/comments/wire.d.ts.map +0 -1
  744. package/dist/storage/domains/comments/wire.js +0 -36
  745. package/dist/storage/domains/comments/wire.js.map +0 -1
  746. package/factory-skills/factory-complete-issue/SKILL.md +0 -24
@@ -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 type { RouteAuth } from '../../routes/route.js';\nimport { isTerminalFactoryRuleStage } from '../../rules/types.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/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\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;\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 its binding names both the project and a board. Returns\n * the bound board per source so the ingest lands cards where the user asked.\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<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'linear' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\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 isLive = (item: Card) =>\n !(options.boards ? isTerminalWorkItem(options.boards, item) : isTerminalFactoryRuleStage(item.stages));\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 // routed to a board of that Factory project. Sources may be projects or\n // whole teams; both are keyed by their opaque source id.\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const routedSourceIds = intakeBoards ? Object.keys(intakeBoards) : 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 = intakeBoards\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 && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\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 = Object.keys(\n await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n }),\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 });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,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"}
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;;;;;;;;;;;AAiFhB,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,qBAAqB,oBAAoB,SAAS,IAAI,QAAQ,QAAQ,CAAC,CAAC,CAClG,KAAI,YAAW,QAAQ,QAAQ;AACpC;;;;;;AAOA,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;;;;;;AAOA,SAAS,iBAAiB,KAAoD;CAC5E,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAAI,OAAO,KAAA;CAC5C,IAAI,IAAI,SAAS,QAAQ,CAAC,gBAAgB,KAAK,GAAG,GAAG,OAAO;CAC5D,OAAO;AACT;;AAGA,MAAM,sBAAsB;;AAE5B,SAAS,sBACP,QACA,WACA,OACe;CACf,MAAM,WAAW,UAAU,QAAO,aAAY,OAAO,mBAAmB,UAAU,KAAK,CAAC;CACxF,OAAO,SAAS,MAAK,aAAY,C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AAS,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"}
@@ -1,4 +1,7 @@
1
+ import type { BoardEventFacts } from '../../boards/board-events.js';
1
2
  import type { BoardRegistry } from '../../boards/index.js';
3
+ import type { ProjectBoardSource } from '../../boards/project-boards.js';
4
+ import type { FactoryLinearRuleContext } from '../../rules/types.js';
2
5
  import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
3
6
  import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
4
7
  import type { IntegrationContext } from '../base.js';
@@ -18,7 +21,7 @@ export interface LinearIssueIngress {
18
21
  labels: string[];
19
22
  createdAt: string;
20
23
  updatedAt: string;
21
- /** Linear source the issue was read from (project or team); resolves the bound board via `intakeBoards`. */
24
+ /** Linear source the issue was read from (project or team). */
22
25
  sourceId?: string | null;
23
26
  projectId?: string | null;
24
27
  }
@@ -26,7 +29,8 @@ export interface LinearRulesOptions {
26
29
  projects: Pick<FactoryProjectsStorage, 'get'>;
27
30
  storage: WorkItemsStorage;
28
31
  configVersion: string;
29
- boards: BoardRegistry;
32
+ /** The code boards, or the per-project source so a project's stored boards run its cards. */
33
+ boards: BoardRegistry | ProjectBoardSource;
30
34
  linearRules: LinearEventRules;
31
35
  }
32
36
  export interface LinearRulesIngress {
@@ -34,10 +38,13 @@ export interface LinearRulesIngress {
34
38
  userId: string;
35
39
  factoryProjectId: string;
36
40
  issues: LinearIssueIngress[];
37
- /** Board id per bound Linear source id, from the project's intake bindings. */
38
- intakeBoards?: Readonly<Record<string, string>>;
39
41
  }
40
42
  type IngressStatus = 'committed' | 'replayed' | 'missing';
43
+ /**
44
+ * The status change a Linear sync reports: a issue seen for the first time is created, and a
45
+ * completed or canceled one is closed for that reason. Later sightings of an open issue report none.
46
+ */
47
+ export declare function boardEventFor(context: Pick<FactoryLinearRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined;
41
48
  export declare class LinearRules {
42
49
  #private;
43
50
  private readonly options;
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/rules.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAI3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAQ,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAoB3D,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,6EAA6E;IAC7E,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,4GAA4G;IAC5G,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,CAAC,EAAE,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ACjC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,kBAAkB,EAAE,CAAC;CAC9B;AAED,KAAK,aAAa,GAAG,WAAW,GAAG,UAAU,GAAG,SAAS,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,wBAAwB,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC,GAAG,eAAe,GAAG,SAAS,CAK9H;AAED,qBAAa,WAAW;;IACV,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,kBAAkB,EAAI;IAOtD,MAAM,CAAC,KAAK,EAAE,kBAAkB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CA8B5F;CA4HF;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAA;CAAE,EAC5C,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAU/D"}
@@ -1,6 +1,8 @@
1
+ import { closeReason } from "../../boards/board-events.js";
1
2
  import "../../boards/index.js";
2
- import { boardEventHandlers, boardForWorkItem, eventBoardId, isTerminalWorkItem, rulePhaseField, withBoardClosure } from "../../boards/semantics.js";
3
- import { selectEventRule } from "../../rules/event-rules.js";
3
+ import { boardEventHandlers, boardForWorkItem, eventBoardId, isTerminalWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from "../../boards/semantics.js";
4
+ import { toBoardSource } from "../../boards/project-boards.js";
5
+ import { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from "../../rules/event-rules.js";
4
6
  import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "../../rules/validation.js";
5
7
  // src/integrations/linear/rules.ts
6
8
  const RULE_TIMEOUT_MS = 5e3;
@@ -15,11 +17,26 @@ async function withRuleTimeout(promise) {
15
17
  }
16
18
  }
17
19
  const MAX_STALE_RULE_ATTEMPTS = 3;
20
+ /**
21
+ * The status change a Linear sync reports: a issue seen for the first time is created, and a
22
+ * completed or canceled one is closed for that reason. Later sightings of an open issue report none.
23
+ */
24
+ function boardEventFor(context) {
25
+ if (context.event === "issueClosed") return {
26
+ type: "work_item.closed",
27
+ reason: closeReason(context.issue.stateType === "canceled")
28
+ };
29
+ return context.item ? void 0 : { type: "work_item.created" };
30
+ }
18
31
  var LinearRules = class {
19
32
  options;
20
33
  constructor(options) {
21
34
  this.options = options;
22
35
  }
36
+ /** The project's boards, loaded at the start of {@link ingest}. */
37
+ #boards(scope) {
38
+ return toBoardSource(this.options.boards).forProject(scope);
39
+ }
23
40
  async ingest(input) {
24
41
  if (!await this.options.projects.get({
25
42
  orgId: input.orgId,
@@ -28,7 +45,17 @@ var LinearRules = class {
28
45
  status: "missing",
29
46
  ingested: 0
30
47
  };
31
- const items = await this.options.storage.list({
48
+ await toBoardSource(this.options.boards).load(input);
49
+ await this.options.storage.copyLegacyCards({
50
+ orgId: input.orgId,
51
+ factoryProjectId: input.factoryProjectId,
52
+ sources: input.issues.map((issue) => ({
53
+ integrationId: "linear",
54
+ type: "issue",
55
+ externalId: `linear:${issue.identifier}`
56
+ }))
57
+ });
58
+ const items = await this.options.storage.listShared({
32
59
  orgId: input.orgId,
33
60
  factoryProjectId: input.factoryProjectId
34
61
  });
@@ -36,8 +63,8 @@ var LinearRules = class {
36
63
  const statuses = [];
37
64
  for (const issue of input.issues) {
38
65
  const byIssueId = items.filter((item) => item.workItem.metadata?.linearIssueId === issue.id);
39
- const relatedItem = itemsBySourceKey.get(`linear:${issue.identifier}`) ?? byIssueId.find((item) => !isTerminalWorkItem(this.options.boards, item)) ?? byIssueId[0];
40
- statuses.push(await this.#ingestIssue(input, issue, relatedItem));
66
+ const relatedItem = itemsBySourceKey.get(`linear:${issue.identifier}`) ?? byIssueId.find((item) => !isTerminalWorkItem(this.#boards(input), item)) ?? byIssueId[0];
67
+ statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));
41
68
  }
42
69
  if (statuses.some((status) => status === "committed")) return {
43
70
  status: "committed",
@@ -61,8 +88,6 @@ var LinearRules = class {
61
88
  const isClosed = issue.stateType === "completed" || issue.stateType === "canceled";
62
89
  if (isClosed && !relatedItem) return "missing";
63
90
  const event = isClosed ? "issueClosed" : "issueObserved";
64
- const boundBoardId = issue.sourceId ? input.intakeBoards?.[issue.sourceId] : void 0;
65
- const boundBoard = boundBoardId ? this.options.boards.get(boundBoardId) : void 0;
66
91
  const context = {
67
92
  tenant: {
68
93
  orgId: input.orgId,
@@ -91,18 +116,18 @@ var LinearRules = class {
91
116
  },
92
117
  board: boardForWorkItem(relatedItem),
93
118
  itemRevision: relatedItem.revision,
94
- ...withBoardClosure(this.options.boards, relatedItem),
95
- ...rulePhaseField(this.options.boards, relatedItem)
119
+ ...withBoardClosure(this.#boards(input), relatedItem),
120
+ ...rulePhaseField(this.#boards(input), relatedItem)
96
121
  } : {},
97
- ...boundBoard ? { intake: {
98
- board: boundBoard.id,
99
- initialPhase: boundBoard.initialPhase
100
- } } : {},
122
+ ...withIntakeTarget(this.#boards(input)),
101
123
  event,
102
124
  issue
103
125
  };
104
- const rule = selectEventRule(this.options.linearRules, boardEventHandlers(this.options.boards, eventBoardId(context), "linear"), context.event);
105
- let decision;
126
+ const boardEvent = boardEventFor(context);
127
+ if (boardEvent) context.boardEvent = boardEvent;
128
+ const ownedByDeployment = deploymentOwnsEvent(this.options.linearRules, boardEventHandlers(this.#boards(input), eventBoardId(context), "linear"), context.event);
129
+ const rule = selectEventRule(this.options.linearRules, boardEventHandlers(this.#boards(input), eventBoardId(context), "linear"), context.event);
130
+ let decision = void 0;
106
131
  let decisions = [];
107
132
  let outcome = { status: "accepted" };
108
133
  try {
@@ -113,7 +138,7 @@ var LinearRules = class {
113
138
  reason: decision.reason
114
139
  };
115
140
  else if (decision) decisions = validateFactoryRuleDecisions([decision]).map((entry) => {
116
- assertFactoryDecisionTarget(entry, this.options.boards, relatedItem ? boardForWorkItem(relatedItem) : void 0);
141
+ assertFactoryDecisionTarget(entry, this.#boards(input), relatedItem ? boardForWorkItem(relatedItem) : void 0);
117
142
  return { ...entry };
118
143
  });
119
144
  } catch (error) {
@@ -124,6 +149,14 @@ var LinearRules = class {
124
149
  reason: timedOut ? "Factory rule evaluation timed out." : error instanceof Error ? error.message.slice(0, 2e3) : "Factory Linear rule failed."
125
150
  };
126
151
  }
152
+ if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);
153
+ if (!decision && !ownedByDeployment && outcome.status === "accepted") {
154
+ const routed = await routeEventDecision(context, this.options.storage, {
155
+ orgId: input.orgId,
156
+ factoryProjectId: input.factoryProjectId
157
+ });
158
+ if (routed) decisions = [{ ...routed }];
159
+ }
127
160
  const committed = await this.options.storage.commitRuleEvaluation({
128
161
  orgId: input.orgId,
129
162
  factoryProjectId: input.factoryProjectId,
@@ -163,6 +196,6 @@ function attachLinearRules(linear, context) {
163
196
  });
164
197
  return (input) => rules.ingest(input);
165
198
  }
166
- export { LinearRules, attachLinearRules };
199
+ export { LinearRules, attachLinearRules, boardEventFor };
167
200
 
168
201
  //# sourceMappingURL=rules.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/linear/rules.ts"],"sourcesContent":["import {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n isTerminalWorkItem,\n rulePhaseField,\n withBoardClosure,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { selectEventRule } from '../../rules/event-rules.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { LinearEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface LinearIssueIngress {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team); resolves the bound board via `intakeBoards`. */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry;\n linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n /** Board id per bound Linear source id, from the project's intake bindings. */\n intakeBoards?: Readonly<Record<string, string>>;\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n async ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n\n const items = await this.options.storage.list({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Linear issue per project; other projects may file their own.\n // The identifier finds the card filed under it; after Linear renamed the\n // identifier, the stable issue id finds it, preferring a live card over\n // finished ones, as the issue detail route does.\n const byIssueId = items.filter(item => item.workItem.metadata?.linearIssueId === issue.id);\n const relatedItem =\n itemsBySourceKey.get(`linear:${issue.identifier}`) ??\n byIssueId.find(item => !isTerminalWorkItem(this.options.boards, item)) ??\n byIssueId[0];\n statuses.push(await this.#ingestIssue(input, issue, relatedItem));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const boundBoardId = issue.sourceId ? input.intakeBoards?.[issue.sourceId] : undefined;\n const boundBoard = boundBoardId ? this.options.boards.get(boundBoardId) : undefined;\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.options.boards, relatedItem),\n ...rulePhaseField(this.options.boards, relatedItem),\n }\n : {}),\n ...(boundBoard ? { intake: { board: boundBoard.id, initialPhase: boundBoard.initialPhase } } : {}),\n event,\n issue,\n };\n\n const rule = selectEventRule(\n this.options.linearRules,\n boardEventHandlers(this.options.boards, eventBoardId(context), 'linear'),\n context.event,\n );\n let decision: FactoryRuleDecision | void;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.options.boards,\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Linear rule failed.',\n };\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: 'linear.issueObserved' },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Linear rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;AAiBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;AAyChC,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,SAA8C;EAA7B,KAAA,UAAA;CAA8B;CAE3D,MAAM,OAAO,OAAiF;EAE5F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EAEtD,MAAM,QAAQ,MAAM,KAAK,QAAQ,QAAQ,KAAK;GAAE,OAAO,MAAM;GAAO,kBAAkB,MAAM;EAAiB,CAAC;EAC9G,MAAM,mBAAmB,IAAI,IAAI,MAAM,KAAI,SAAQ,CAAC,KAAK,gBAAgB,YAAY,IAAI,CAAC,CAAC;EAC3F,MAAM,WAA4B,CAAC;EACnC,KAAK,MAAM,SAAS,MAAM,QAAQ;GAKhC,MAAM,YA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Y,aAAa,MAAM;GAC/B,SAAS;IAAE,UAAU;IAAW,aAAa;GAAuB;GACpE,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,sCAAsC,UAAU,6BAA6B;GAE/F,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF;AAEA,SAAgB,kBACd,QACA,SAC+D;CAC/D,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/linear/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n isTerminalWorkItem,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} 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 { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryLinearRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { LinearEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface LinearIssueIngress {\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team). */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Linear sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryLinearRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: LinearRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Linear issue per project; other projects may file their own.\n // The identifier finds the card filed under it; after Linear renamed the\n // identifier, the stable issue id finds it, preferring a live card over\n // finished ones, as the issue detail route does.\n const byIssueId = items.filter(item => item.workItem.metadata?.linearIssueId === issue.id);\n const relatedItem =\n itemsBySourceKey.get(`linear:${issue.identifier}`) ??\n byIssueId.find(item => !isTerminalWorkItem(this.#boards(input), item)) ??\n byIssueId[0];\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Linear rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: 'linear.issueObserved' },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Linear rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.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AAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Mastra `apiRoutes` that let the Factory SPA connect and reconnect
3
- * Platform-managed provider accounts without leaving Factory.
3
+ * Platform-managed provider accounts without leaving Factory, and list the
4
+ * Platform project connections whose Mastra Connect tools sessions get.
4
5
  *
5
6
  * The browser cannot talk to the integrations service itself — it has no
6
7
  * Platform session — so these routes mint Nango connect/reconnect sessions
@@ -31,6 +32,11 @@ export interface BuildPlatformConnectRoutesOptions {
31
32
  auth: RouteAuth;
32
33
  client: PlatformApiClient;
33
34
  }
35
+ export interface ConnectToolsSource {
36
+ client: PlatformApiClient;
37
+ projectId: string;
38
+ }
39
+ export declare function buildConnectToolsRoute(auth: RouteAuth, source: ConnectToolsSource | undefined): ApiRoute;
34
40
  /**
35
41
  * Build the `/web/integrations/platform/*` routes. Callers only mount these
36
42
  * when Platform machine credentials are configured.
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AAUzD,MAAM,WAAW,uBAAuB;IACtC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,wBAAwB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAI9E,CAAC;AAmBF,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,iBAAiB,CAAC;CAC3B;AA2CD;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iCAAiC,GAAG,QAAQ,EAAE,CAgFjG"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,iBAAiB,EAAC,MAAM,kBAAkB,CAAC;AAMzD,MAAM,WAAW,uBAAuB;IACtC,6DAA6D;IAC7D,aAAa,EAAE,MAAM,CAAC;IACtB,wEAAwE;IACxE,wBAAwB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,0BAA0B,EAAE,MAAM,CAAC,MAAM,EAAE,uBAAuB,CAI9E,CAAC;AAgCF,MAAM,WAAW,iCAAiC;IAChD,IAAI,EAAE,SAAS,CAAC;IAChB,MAAM,EAAE,iBAAiB,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,iBAAiB,CAAC;IAC1B,SAAS,EAAE,MAAM,CAAC;CACnB;AA2CD,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,kBAAkB,GAAG,SAAS,GAAG,QAAQ,CAmDxG;AAED;;;GAGG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,iCAAiC,GAAG,QAAQ,EAAE,CAgFjG"}
@@ -1,10 +1,8 @@
1
+ import { loose } from "../../../routes/route.js";
1
2
  import { PlatformApiError } from "../api-client.js";
3
+ import { offersSessionTools } from "./session-tools.js";
2
4
  import { registerApiRoute } from "@mastra/core/server";
3
5
  // src/integrations/platform/connect/routes.ts
4
- /** Erase a route handler's path-parameterized context to a plain `Context`. */
5
- function loose(c) {
6
- return c;
7
- }
8
6
  /**
9
7
  * Providers the Factory SPA may connect through these routes. Keys are the
10
8
  * SPA-facing provider slugs; `integrationId` is the Platform catalog id used
@@ -62,6 +60,45 @@ function platformError(c, err) {
62
60
  message: err instanceof Error ? err.message : String(err)
63
61
  }, 502);
64
62
  }
63
+ function buildConnectToolsRoute(auth, source) {
64
+ return registerApiRoute("/web/integrations/platform/connect-tools", {
65
+ method: "GET",
66
+ requiresAuth: false,
67
+ handler: async (rawContext) => {
68
+ const c = loose(rawContext);
69
+ if (!source) return c.json({
70
+ error: "connect_tools_off",
71
+ message: "This Factory's sessions don't get Mastra Connect tools."
72
+ }, 404);
73
+ if (auth.enabled()) {
74
+ await auth.ensureUser(c);
75
+ if (!auth.tenant(c)) return c.json({ error: "unauthorized" }, 401);
76
+ }
77
+ const { client, projectId } = source;
78
+ try {
79
+ const [listed, catalog] = await Promise.all([client.request("GET", `/v2/projects/${encodeURIComponent(projectId)}/connections`), client.request("GET", "/v2/integrations").catch((error) => {
80
+ console.warn(`MastraFactory: listing connections without provider names; the Platform catalog failed: ${error instanceof Error ? error.message : String(error)}`);
81
+ return { integrations: [] };
82
+ })]);
83
+ const entries = new Map(catalog.integrations.map((entry) => [entry.id, entry]));
84
+ const connections = listed.connections.filter((connection) => offersSessionTools(connection.integrationId)).map((connection) => {
85
+ const entry = entries.get(connection.integrationId);
86
+ return {
87
+ id: connection.id,
88
+ integrationId: connection.integrationId,
89
+ providerName: entry?.displayName ?? connection.integrationId,
90
+ logoUrl: entry?.logoUrl ?? null,
91
+ accountLabel: connection.accountLabel ?? null,
92
+ status: connection.status
93
+ };
94
+ }).sort((a, b) => a.providerName.localeCompare(b.providerName));
95
+ return c.json({ connections });
96
+ } catch (err) {
97
+ return platformError(c, err);
98
+ }
99
+ }
100
+ });
101
+ }
65
102
  /**
66
103
  * Build the `/web/integrations/platform/*` routes. Callers only mount these
67
104
  * when Platform machine credentials are configured.
@@ -127,6 +164,6 @@ function buildPlatformConnectRoutes(options) {
127
164
  })
128
165
  ];
129
166
  }
130
- export { PLATFORM_CONNECT_PROVIDERS, buildPlatformConnectRoutes };
167
+ export { PLATFORM_CONNECT_PROVIDERS, buildConnectToolsRoute, buildPlatformConnectRoutes };
131
168
 
132
169
  //# sourceMappingURL=routes.js.map
@@ -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.\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 type { RouteAuth } from '../../../routes/route.js';\nimport type { PlatformApiClient} from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\ntype RouteContext = Context;\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\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};\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\nexport interface BuildPlatformConnectRoutesOptions {\n auth: RouteAuth;\n client: PlatformApiClient;\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\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":";;;;AAyBA,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;AAeA,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;AAC1E;AAwBA,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,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;AAEA,SAAS,kBAAkB,GAAiD;CAC1E,MAAM,WAAW,EAAE,IAAI,MAAM,UAAU;CACvC,OAAO,WAAY,2BAA2B,aAAa,OAAQ;AACrE;AAEA,SAAS,cAAc,GAAiB,KAAc;CACpD,IAAI,eAAe,kBAAkB;EACnC,IAAI,IAAI,WAAW,KACjB,OAAO,EAAE,KAAK;GAAE,OAAO;GAAmB,SAAS,IAAI;EAAQ,GAAG,GAAG;EAEvE,IAAI,IAAI,WAAW,KACjB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;KACpC,OAAO,EAAE,KAAK,SAAS,GAAG;IAC5B,SAAS,KAAK;KACZ,OAAO,cAAc,GAAG,GAAG;IAC7B;GACF;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};\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":";;;;;;;;;;;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;AAC1E;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,QAAQ,OA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AU,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"}
@@ -0,0 +1,12 @@
1
+ import type { RequestContext } from '@mastra/core/request-context';
2
+ import type { IntegrationTools } from '../../base.js';
3
+ export declare function offersSessionTools(integrationId: string): boolean;
4
+ /**
5
+ * The Mastra Connect tools Factory gives sessions by default, without delete,
6
+ * archive, and GitHub/GitLab tools. Passing `tools` replaces that default; call
7
+ * this to keep it alongside your own.
8
+ */
9
+ export declare function platformConnectTools(projectId: string): (args: {
10
+ requestContext: RequestContext;
11
+ }) => Promise<IntegrationTools>;
12
+ //# sourceMappingURL=session-tools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-tools.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/connect/session-tools.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAEnE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAQtD,wBAAgB,kBAAkB,CAAC,aAAa,EAAE,MAAM,GAAG,OAAO,CAEjE;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,SAAS,EAAE,MAAM,GAChB,CAAC,IAAI,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAwBzE"}