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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/README.md +210 -42
  2. package/dist/boards/board-events.d.ts +34 -0
  3. package/dist/boards/board-events.d.ts.map +1 -0
  4. package/dist/boards/board-events.js +50 -0
  5. package/dist/boards/board-events.js.map +1 -0
  6. package/dist/boards/board-writes.d.ts +86 -0
  7. package/dist/boards/board-writes.d.ts.map +1 -0
  8. package/dist/boards/board-writes.js +252 -0
  9. package/dist/boards/board-writes.js.map +1 -0
  10. package/dist/boards/define-board.d.ts +16 -5
  11. package/dist/boards/define-board.d.ts.map +1 -1
  12. package/dist/boards/define-board.js +30 -8
  13. package/dist/boards/define-board.js.map +1 -1
  14. package/dist/boards/intake-routing.d.ts +30 -6
  15. package/dist/boards/intake-routing.d.ts.map +1 -1
  16. package/dist/boards/intake-routing.js +43 -5
  17. package/dist/boards/intake-routing.js.map +1 -1
  18. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  19. package/dist/boards/legacy-plan-role.js +8 -4
  20. package/dist/boards/legacy-plan-role.js.map +1 -1
  21. package/dist/boards/phase-automation.d.ts.map +1 -1
  22. package/dist/boards/phase-automation.js +7 -2
  23. package/dist/boards/phase-automation.js.map +1 -1
  24. package/dist/boards/project-boards.d.ts +18 -7
  25. package/dist/boards/project-boards.d.ts.map +1 -1
  26. package/dist/boards/project-boards.js +78 -14
  27. package/dist/boards/project-boards.js.map +1 -1
  28. package/dist/boards/stored-board.d.ts +59 -1
  29. package/dist/boards/stored-board.d.ts.map +1 -1
  30. package/dist/boards/stored-board.js +219 -7
  31. package/dist/boards/stored-board.js.map +1 -1
  32. package/dist/factory.d.ts +63 -9
  33. package/dist/factory.d.ts.map +1 -1
  34. package/dist/factory.js +187 -22
  35. package/dist/factory.js.map +1 -1
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -3
  39. package/dist/integrations/base.d.ts +6 -0
  40. package/dist/integrations/base.d.ts.map +1 -1
  41. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  42. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  43. package/dist/integrations/github/acceptance-labels.js +1 -1
  44. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  45. package/dist/integrations/github/default-rules.d.ts +2 -9
  46. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  47. package/dist/integrations/github/default-rules.js +7 -6
  48. package/dist/integrations/github/default-rules.js.map +1 -1
  49. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  50. package/dist/integrations/github/issue-reconciler.js +17 -1
  51. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  52. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  53. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  54. package/dist/integrations/github/review-status-comment.js +217 -0
  55. package/dist/integrations/github/review-status-comment.js.map +1 -0
  56. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  57. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  58. package/dist/integrations/github/review-status-reporter.js +100 -0
  59. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  60. package/dist/integrations/github/review-status.d.ts +28 -0
  61. package/dist/integrations/github/review-status.d.ts.map +1 -0
  62. package/dist/integrations/github/review-status.js +95 -0
  63. package/dist/integrations/github/review-status.js.map +1 -0
  64. package/dist/integrations/github/routes.d.ts.map +1 -1
  65. package/dist/integrations/github/routes.js +2 -5
  66. package/dist/integrations/github/routes.js.map +1 -1
  67. package/dist/integrations/github/rules.d.ts +13 -1
  68. package/dist/integrations/github/rules.d.ts.map +1 -1
  69. package/dist/integrations/github/rules.js +77 -6
  70. package/dist/integrations/github/rules.js.map +1 -1
  71. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  72. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  73. package/dist/integrations/gitlab/default-rules.js +4 -4
  74. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  75. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  76. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  77. package/dist/integrations/gitlab/routes.js +1 -3
  78. package/dist/integrations/gitlab/routes.js.map +1 -1
  79. package/dist/integrations/gitlab/rules.d.ts +16 -0
  80. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  81. package/dist/integrations/gitlab/rules.js +69 -4
  82. package/dist/integrations/gitlab/rules.js.map +1 -1
  83. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  84. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  85. package/dist/integrations/incidentio/default-rules.js +3 -4
  86. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  87. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/routes.js +1 -4
  89. package/dist/integrations/incidentio/routes.js.map +1 -1
  90. package/dist/integrations/incidentio/rules.d.ts +7 -0
  91. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  92. package/dist/integrations/incidentio/rules.js +35 -3
  93. package/dist/integrations/incidentio/rules.js.map +1 -1
  94. package/dist/integrations/jira/default-rules.d.ts +1 -9
  95. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  96. package/dist/integrations/jira/default-rules.js +3 -4
  97. package/dist/integrations/jira/default-rules.js.map +1 -1
  98. package/dist/integrations/jira/routes.d.ts.map +1 -1
  99. package/dist/integrations/jira/routes.js +1 -4
  100. package/dist/integrations/jira/routes.js.map +1 -1
  101. package/dist/integrations/jira/rules.d.ts +7 -0
  102. package/dist/integrations/jira/rules.d.ts.map +1 -1
  103. package/dist/integrations/jira/rules.js +35 -3
  104. package/dist/integrations/jira/rules.js.map +1 -1
  105. package/dist/integrations/linear/default-rules.d.ts +1 -9
  106. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/default-rules.js +3 -4
  108. package/dist/integrations/linear/default-rules.js.map +1 -1
  109. package/dist/integrations/linear/routes.d.ts.map +1 -1
  110. package/dist/integrations/linear/routes.js +1 -4
  111. package/dist/integrations/linear/routes.js.map +1 -1
  112. package/dist/integrations/linear/rules.d.ts +7 -0
  113. package/dist/integrations/linear/rules.d.ts.map +1 -1
  114. package/dist/integrations/linear/rules.js +35 -3
  115. package/dist/integrations/linear/rules.js.map +1 -1
  116. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  117. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  118. package/dist/integrations/platform/connect/routes.js +42 -5
  119. package/dist/integrations/platform/connect/routes.js.map +1 -1
  120. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  121. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  122. package/dist/integrations/platform/connect/session-tools.js +30 -0
  123. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  124. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  125. package/dist/integrations/platform/github/integration.js +1 -3
  126. package/dist/integrations/platform/github/integration.js.map +1 -1
  127. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  128. package/dist/integrations/platform/jira/routes.js +1 -4
  129. package/dist/integrations/platform/jira/routes.js.map +1 -1
  130. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  131. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  132. package/dist/integrations/platform/linear/event-worker.js +9 -0
  133. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  134. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  135. package/dist/integrations/platform/linear/integration.js +1 -3
  136. package/dist/integrations/platform/linear/integration.js.map +1 -1
  137. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  138. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  139. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  140. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  141. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  142. package/dist/integrations/slack/connect-route.js +1 -1
  143. package/dist/integrations/slack/connect-route.js.map +1 -1
  144. package/dist/integrations/slack/integration.d.ts.map +1 -1
  145. package/dist/integrations/slack/integration.js +2 -0
  146. package/dist/integrations/slack/integration.js.map +1 -1
  147. package/dist/integrations/slack/slack.d.ts +12 -10
  148. package/dist/integrations/slack/slack.d.ts.map +1 -1
  149. package/dist/integrations/slack/slack.js +110 -43
  150. package/dist/integrations/slack/slack.js.map +1 -1
  151. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  152. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  153. package/dist/integrations/slack/voice-clips.js +201 -0
  154. package/dist/integrations/slack/voice-clips.js.map +1 -0
  155. package/dist/integrations/workos/integration.d.ts.map +1 -1
  156. package/dist/integrations/workos/integration.js +1 -3
  157. package/dist/integrations/workos/integration.js.map +1 -1
  158. package/dist/mcp/routes.js +1 -1
  159. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  160. package/dist/routes/attention-activity.js +1 -1
  161. package/dist/routes/attention-providers.js +1 -1
  162. package/dist/routes/automation-runs.d.ts.map +1 -1
  163. package/dist/routes/automation-runs.js +1 -4
  164. package/dist/routes/automation-runs.js.map +1 -1
  165. package/dist/routes/boards.d.ts +8 -6
  166. package/dist/routes/boards.d.ts.map +1 -1
  167. package/dist/routes/boards.js +73 -143
  168. package/dist/routes/boards.js.map +1 -1
  169. package/dist/routes/config.d.ts.map +1 -1
  170. package/dist/routes/config.js +3 -8
  171. package/dist/routes/config.js.map +1 -1
  172. package/dist/routes/contracts.d.ts +132 -0
  173. package/dist/routes/contracts.d.ts.map +1 -1
  174. package/dist/routes/contracts.js +77 -29
  175. package/dist/routes/contracts.js.map +1 -1
  176. package/dist/routes/fs.d.ts.map +1 -1
  177. package/dist/routes/fs.js +1 -4
  178. package/dist/routes/fs.js.map +1 -1
  179. package/dist/routes/intake-routes.d.ts.map +1 -1
  180. package/dist/routes/intake-routes.js +19 -12
  181. package/dist/routes/intake-routes.js.map +1 -1
  182. package/dist/routes/intake.d.ts.map +1 -1
  183. package/dist/routes/intake.js +3 -5
  184. package/dist/routes/intake.js.map +1 -1
  185. package/dist/routes/knowledge.d.ts.map +1 -1
  186. package/dist/routes/knowledge.js +1 -4
  187. package/dist/routes/knowledge.js.map +1 -1
  188. package/dist/routes/oauth.d.ts.map +1 -1
  189. package/dist/routes/oauth.js +1 -4
  190. package/dist/routes/oauth.js.map +1 -1
  191. package/dist/routes/projects.d.ts +3 -0
  192. package/dist/routes/projects.d.ts.map +1 -1
  193. package/dist/routes/projects.js +7 -4
  194. package/dist/routes/projects.js.map +1 -1
  195. package/dist/routes/provider-credentials.d.ts.map +1 -1
  196. package/dist/routes/provider-credentials.js +6 -0
  197. package/dist/routes/provider-credentials.js.map +1 -1
  198. package/dist/routes/route.d.ts +2 -0
  199. package/dist/routes/route.d.ts.map +1 -1
  200. package/dist/routes/route.js +5 -1
  201. package/dist/routes/route.js.map +1 -1
  202. package/dist/routes/skills.d.ts.map +1 -1
  203. package/dist/routes/skills.js +1 -4
  204. package/dist/routes/skills.js.map +1 -1
  205. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  206. package/dist/routes/source-control-sessions.js +1 -3
  207. package/dist/routes/source-control-sessions.js.map +1 -1
  208. package/dist/routes/source-control-settings.d.ts.map +1 -1
  209. package/dist/routes/source-control-settings.js +3 -2
  210. package/dist/routes/source-control-settings.js.map +1 -1
  211. package/dist/routes/surface.d.ts +3 -1
  212. package/dist/routes/surface.d.ts.map +1 -1
  213. package/dist/routes/surface.js +11 -1
  214. package/dist/routes/surface.js.map +1 -1
  215. package/dist/routes/voice.d.ts +48 -0
  216. package/dist/routes/voice.d.ts.map +1 -0
  217. package/dist/routes/voice.js +248 -0
  218. package/dist/routes/voice.js.map +1 -0
  219. package/dist/routes/work-items.d.ts.map +1 -1
  220. package/dist/routes/work-items.js +1 -4
  221. package/dist/routes/work-items.js.map +1 -1
  222. package/dist/rules/decision-applicability.js +1 -1
  223. package/dist/rules/dispatcher.d.ts +28 -0
  224. package/dist/rules/dispatcher.d.ts.map +1 -1
  225. package/dist/rules/dispatcher.js +391 -93
  226. package/dist/rules/dispatcher.js.map +1 -1
  227. package/dist/rules/event-rules.d.ts +40 -1
  228. package/dist/rules/event-rules.d.ts.map +1 -1
  229. package/dist/rules/event-rules.js +59 -1
  230. package/dist/rules/event-rules.js.map +1 -1
  231. package/dist/rules/processor.js +1 -1
  232. package/dist/rules/processor.js.map +1 -1
  233. package/dist/rules/transition-service.d.ts +9 -0
  234. package/dist/rules/transition-service.d.ts.map +1 -1
  235. package/dist/rules/transition-service.js +4 -2
  236. package/dist/rules/transition-service.js.map +1 -1
  237. package/dist/rules/types.d.ts +54 -3
  238. package/dist/rules/types.d.ts.map +1 -1
  239. package/dist/rules/types.js +2 -0
  240. package/dist/rules/types.js.map +1 -1
  241. package/dist/rules/validation.d.ts.map +1 -1
  242. package/dist/rules/validation.js +57 -2
  243. package/dist/rules/validation.js.map +1 -1
  244. package/dist/session/credential-policy.d.ts +2 -2
  245. package/dist/session/credential-policy.d.ts.map +1 -1
  246. package/dist/session/credential-policy.js +3 -3
  247. package/dist/session/credential-policy.js.map +1 -1
  248. package/dist/session/default-model-hydration.d.ts +2 -2
  249. package/dist/session/default-model-hydration.d.ts.map +1 -1
  250. package/dist/session/default-model-hydration.js +4 -4
  251. package/dist/session/default-model-hydration.js.map +1 -1
  252. package/dist/session/session-threads.d.ts +8 -0
  253. package/dist/session/session-threads.d.ts.map +1 -1
  254. package/dist/session/session-threads.js +11 -1
  255. package/dist/session/session-threads.js.map +1 -1
  256. package/dist/skills/catalog.js +1 -1
  257. package/dist/storage/domains/audit/actions.d.ts +1 -1
  258. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  259. package/dist/storage/domains/audit/actions.js +2 -1
  260. package/dist/storage/domains/audit/actions.js.map +1 -1
  261. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  262. package/dist/storage/domains/audit/domain.js +1 -3
  263. package/dist/storage/domains/audit/domain.js.map +1 -1
  264. package/dist/storage/domains/boards/base.d.ts +32 -1
  265. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  266. package/dist/storage/domains/boards/base.js +155 -8
  267. package/dist/storage/domains/boards/base.js.map +1 -1
  268. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  269. package/dist/storage/domains/boards/schemas.js +13 -1
  270. package/dist/storage/domains/boards/schemas.js.map +1 -1
  271. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  272. package/dist/storage/domains/comments/routes.js +1 -3
  273. package/dist/storage/domains/comments/routes.js.map +1 -1
  274. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  275. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  276. package/dist/storage/domains/memory-settings/base.js +1 -11
  277. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  278. package/dist/storage/domains/projects/base.d.ts +6 -0
  279. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  280. package/dist/storage/domains/projects/base.js +9 -1
  281. package/dist/storage/domains/projects/base.js.map +1 -1
  282. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  283. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  284. package/dist/storage/domains/voice-settings/base.js +81 -0
  285. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  286. package/dist/storage/domains/work-items/base.d.ts +31 -2
  287. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  288. package/dist/storage/domains/work-items/base.js +197 -44
  289. package/dist/storage/domains/work-items/base.js.map +1 -1
  290. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  291. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  292. package/dist/storage/domains/work-items/cards.js +54 -4
  293. package/dist/storage/domains/work-items/cards.js.map +1 -1
  294. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  295. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  296. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  297. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  298. package/dist/timing.d.ts +1 -0
  299. package/dist/timing.d.ts.map +1 -1
  300. package/dist/timing.js +1 -1
  301. package/dist/timing.js.map +1 -1
  302. package/dist/tools/read-tools.d.ts +2 -2
  303. package/dist/tools/read-tools.d.ts.map +1 -1
  304. package/dist/tools/read-tools.js +7 -6
  305. package/dist/tools/read-tools.js.map +1 -1
  306. package/dist/tools/session-tools.d.ts +1 -1
  307. package/dist/tools/session-tools.d.ts.map +1 -1
  308. package/dist/tools/session-tools.js.map +1 -1
  309. package/dist/tools/sessions-state-processor.d.ts +1 -1
  310. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  311. package/dist/tools/sessions-state-processor.js +9 -2
  312. package/dist/tools/sessions-state-processor.js.map +1 -1
  313. package/dist/tools/work-item-tools.js +2 -2
  314. package/dist/voice/rate-limit.d.ts +13 -0
  315. package/dist/voice/rate-limit.d.ts.map +1 -0
  316. package/dist/voice/rate-limit.js +36 -0
  317. package/dist/voice/rate-limit.js.map +1 -0
  318. package/dist/voice/realtime.d.ts +13 -0
  319. package/dist/voice/realtime.d.ts.map +1 -0
  320. package/dist/voice/realtime.js +56 -0
  321. package/dist/voice/realtime.js.map +1 -0
  322. package/dist/voice/transcription.d.ts +51 -0
  323. package/dist/voice/transcription.d.ts.map +1 -0
  324. package/dist/voice/transcription.js +112 -0
  325. package/dist/voice/transcription.js.map +1 -0
  326. package/dist/work-items/split-backfill.d.ts +13 -0
  327. package/dist/work-items/split-backfill.d.ts.map +1 -0
  328. package/dist/work-items/split-backfill.js +32 -0
  329. package/dist/work-items/split-backfill.js.map +1 -0
  330. package/dist/work-items/split-migration.d.ts +39 -2
  331. package/dist/work-items/split-migration.d.ts.map +1 -1
  332. package/dist/work-items/split-migration.js +170 -62
  333. package/dist/work-items/split-migration.js.map +1 -1
  334. package/dist/workspace.js +2 -2
  335. package/package.json +9 -8
@@ -1,6 +1,6 @@
1
1
  import { isPullRequestCard, pullRequestReviewPhase, reviewsPullRequest } from "../../boards/semantics.js";
2
2
  import "../../boards/index.js";
3
- import { recordExplicitRuleOverrides } from "../../rules/event-rules.js";
3
+ import { closedByRoutes, recordExplicitRuleOverrides } from "../../rules/event-rules.js";
4
4
  // src/integrations/gitlab/default-rules.ts
5
5
  function actorUsername(context) {
6
6
  return context.actor.type === "gitlab" ? context.actor.username : void 0;
@@ -55,13 +55,12 @@ function issueClosed(context) {
55
55
  if (!context.item || context.item.source !== "gitlab-issue") return;
56
56
  const closure = context.boardClosure;
57
57
  if (!context.board || !closure || closure.itemTerminal) return;
58
- return {
59
- type: "transition",
58
+ return closedByRoutes(false, {
60
59
  idempotencyKey: `${context.ingress.id}:issue-closed`,
61
60
  board: context.board,
62
61
  stage: closure.completed.phase,
63
62
  message: { text: `GitLab issue #${context.issue?.number ?? ""} was closed; this ${closure.boardTitle} card was moved to ${closure.completed.title}.` }
64
- };
63
+ });
65
64
  }
66
65
  function materializeMergeRequest(context) {
67
66
  if (!context.mergeRequest) return;
@@ -153,6 +152,7 @@ const defaultGitLabRules = Object.freeze({
153
152
  issueOpened,
154
153
  issueUpdated: null,
155
154
  issueClosed,
155
+ issueReopened: (context) => context.item ? void 0 : issueOpened(context),
156
156
  issueCommented: null,
157
157
  mergeRequestOpened: materializeMergeRequest,
158
158
  mergeRequestUpdated,
@@ -1 +1 @@
1
- {"version":3,"file":"default-rules.js","names":[],"sources":["../../../src/integrations/gitlab/default-rules.ts"],"sourcesContent":["import { isPullRequestCard, pullRequestReviewPhase, reviewsPullRequest } from '../../boards/index.js';\nimport { recordExplicitRuleOverrides } from '../../rules/event-rules.js';\nimport type { FactoryGitLabEventName, FactoryGitLabRuleContext, FactoryRuleHandler } from '../../rules/types.js';\n\nexport type GitLabRuleOverrides = Partial<\n Record<FactoryGitLabEventName, FactoryRuleHandler<FactoryGitLabRuleContext> | null | undefined>\n>;\nexport type GitLabEventRules = Readonly<\n Record<FactoryGitLabEventName, FactoryRuleHandler<FactoryGitLabRuleContext> | null>\n>;\n\nfunction actorUsername(context: Pick<FactoryGitLabRuleContext, 'actor'>): string | undefined {\n return context.actor.type === 'gitlab' ? context.actor.username : undefined;\n}\n\nfunction trustedGitLabActor(context: Pick<FactoryGitLabRuleContext, 'actor'>): boolean {\n return context.actor.type === 'gitlab' && context.actor.trusted;\n}\n\nfunction createdAfterFactory(createdAt: string | undefined, factoryCreatedAt: string): boolean {\n if (!createdAt) return false;\n const sourceCreatedAt = Date.parse(createdAt);\n const projectCreatedAt = Date.parse(factoryCreatedAt);\n return Number.isFinite(sourceCreatedAt) && Number.isFinite(projectCreatedAt) && sourceCreatedAt > projectCreatedAt;\n}\n\n/** The Work card whose session authored the merge request, as opposed to the merge request's own card. */\nfunction authoringCard(context: FactoryGitLabRuleContext): boolean {\n return context.board === 'work' && context.item !== undefined && !isPullRequestCard(context.item);\n}\n\n/** The board holding the merge request's own card: Work for new cards, Review for cards filed before. */\nfunction mergeRequestCardBoard(context: FactoryGitLabRuleContext): 'work' | 'review' {\n return context.board === 'review' ? 'review' : 'work';\n}\n\nfunction mergeRequestCardNoun(context: FactoryGitLabRuleContext): string {\n return context.board === 'review' ? 'Review card' : 'merge request card';\n}\n\nfunction issueOpened(context: FactoryGitLabRuleContext) {\n if (!context.issue) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:issue-intake`,\n board: context.intake?.board ?? 'work',\n source: 'gitlab-issue',\n sourceKey: context.issue.sourceKey,\n title: context.issue.title,\n url: context.issue.url,\n stage: context.intake?.initialPhase ?? 'intake',\n metadata: {\n gitlabHost: context.repository.host,\n gitlabProjectId: context.repository.id,\n gitlabIssueIid: context.issue.number,\n identifier: `${context.repository.fullName}#${context.issue.number}`,\n ...(context.issue.createdAt ? { sourceCreatedAt: context.issue.createdAt } : {}),\n ...((context.issue.author ?? actorUsername(context))\n ? { author: context.issue.author ?? actorUsername(context) }\n : {}),\n authorTrusted: context.issue.authorTrusted,\n autoStartCandidate:\n trustedGitLabActor(context) &&\n context.issue.authorTrusted &&\n createdAfterFactory(context.issue.createdAt, context.factory.createdAt),\n assignees: context.issue.assignees ?? [],\n labels: context.issue.labels ?? [],\n labelColors: context.issue.labelColors ?? {},\n },\n } as const;\n}\n\nfunction issueClosed(context: FactoryGitLabRuleContext) {\n if (!context.item || context.item.source !== 'gitlab-issue') return;\n // The card's board decides where a closed source sends it; boards that declare no\n // `sourceClosed` mapping keep the card where it is, as do cards already finished.\n const closure = context.boardClosure;\n if (!context.board || !closure || closure.itemTerminal) return;\n // GitLab reports no close reason, so every closure counts as completed.\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:issue-closed`,\n board: context.board,\n stage: closure.completed.phase,\n message: {\n text: `GitLab issue #${context.issue?.number ?? ''} was closed; this ${closure.boardTitle} card was moved to ${closure.completed.title}.`,\n },\n } as const;\n}\n\nfunction materializeMergeRequest(context: FactoryGitLabRuleContext) {\n if (!context.mergeRequest) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:merge-request-intake`,\n board: 'work',\n source: 'gitlab-pr',\n sourceKey: context.mergeRequest.sourceKey,\n title: context.mergeRequest.title,\n url: context.mergeRequest.url,\n stage: 'intake',\n metadata: {\n gitlabHost: context.repository.host,\n gitlabProjectId: context.repository.id,\n gitlabMergeRequestIid: context.mergeRequest.number,\n ...(context.mergeRequest.createdAt ? { sourceCreatedAt: context.mergeRequest.createdAt } : {}),\n factoryAuthored: context.mergeRequest.factoryAuthored,\n authorTrusted: context.mergeRequest.authorTrusted,\n autoStartCandidate:\n ((trustedGitLabActor(context) && context.mergeRequest.authorTrusted) || context.mergeRequest.factoryAuthored) &&\n createdAfterFactory(context.mergeRequest.createdAt, context.factory.createdAt),\n state: context.mergeRequest.state,\n draft: context.mergeRequest.draft,\n merged: context.mergeRequest.merged,\n assignees: context.mergeRequest.assignees ?? [],\n requestedReviewers: context.mergeRequest.reviewers ?? [],\n labels: context.mergeRequest.labels ?? [],\n labelColors: context.mergeRequest.labelColors ?? {},\n headBranch: context.mergeRequest.headBranch,\n baseBranch: context.mergeRequest.baseBranch,\n ...(context.mergeRequest.author ? { author: context.mergeRequest.author } : {}),\n },\n } as const;\n}\n\nfunction mergeRequestUpdated(context: FactoryGitLabRuleContext) {\n if (!context.item || context.item.source !== 'gitlab-pr' || !reviewsPullRequest(context)) return;\n if (!context.mergeRequest || context.mergeRequest.state !== 'open' || context.mergeRequest.merged) return;\n if (context.item.stages.some(stage => stage === 'intake')) return;\n // An untrusted push must not start review passes on demand.\n if (!trustedGitLabActor(context) && !context.mergeRequest.factoryAuthored) return;\n const stage = pullRequestReviewPhase(context.board);\n const alreadyReviewing = context.item.stages.some(current => current === stage);\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:re-review-updated`,\n board: mergeRequestCardBoard(context),\n stage,\n ...(alreadyReviewing ? { reenter: true } : {}),\n } as const;\n}\n\nfunction mergeRequestCommented(context: FactoryGitLabRuleContext) {\n if (!context.item || !context.mergeRequest || !context.note || !authoringCard(context)) return;\n if (context.mergeRequest.state !== 'open' || context.mergeRequest.merged) return;\n if (context.actor.type === 'gitlab' && context.actor.factoryAuthored) return;\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:address-merge-request-comment`,\n role: 'work',\n priority: 'high',\n message:\n `${context.note.author ?? 'Someone'} commented on GitLab merge request !${context.mergeRequest.number} ` +\n `(${context.note.url ?? context.mergeRequest.url}). Read the comment, address it if you agree, and push ` +\n 'the fixes to the merge-request branch. Reply in GitLab to anything you are deliberately not changing.',\n } as const;\n}\n\nfunction mergeRequestMerged(context: FactoryGitLabRuleContext) {\n if (!context.item || !context.mergeRequest?.merged) return;\n if (reviewsPullRequest(context)) {\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:merge-request-merged`,\n board: mergeRequestCardBoard(context),\n stage: 'done',\n message: {\n text: `GitLab merge request !${context.mergeRequest.number} merged; this ${mergeRequestCardNoun(context)} was moved to Done.`,\n },\n } as const;\n }\n if (!authoringCard(context)) return;\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:assess-work-completion`,\n role: 'work',\n message:\n `GitLab merge request !${context.mergeRequest.number} merged. Assess whether the linked Work item is complete. ` +\n 'Do not mark it Done solely because this merge request merged.',\n } as const;\n}\n\nfunction mergeRequestClosed(context: FactoryGitLabRuleContext) {\n if (!context.item || !context.mergeRequest || context.mergeRequest.merged || !reviewsPullRequest(context)) return;\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:merge-request-closed`,\n board: mergeRequestCardBoard(context),\n stage: 'canceled',\n message: {\n text:\n `GitLab merge request !${context.mergeRequest.number} was closed without merging; ` +\n `this ${mergeRequestCardNoun(context)} was moved to Canceled.`,\n },\n } as const;\n}\n\nexport const defaultGitLabRules = Object.freeze({\n issueOpened,\n // Triage runs once, when a person moves the card into Triage or starts the run; later edits and\n // comments on the issue don't run it again.\n issueUpdated: null,\n issueClosed,\n issueCommented: null,\n mergeRequestOpened: materializeMergeRequest,\n mergeRequestUpdated,\n mergeRequestCommented,\n mergeRequestMerged,\n mergeRequestClosed,\n} satisfies GitLabEventRules);\n\nexport function resolveGitLabRules(overrides?: GitLabRuleOverrides): GitLabEventRules {\n if (overrides !== undefined && (overrides === null || typeof overrides !== 'object' || Array.isArray(overrides))) {\n throw new Error('GitLab rules must be an object.');\n }\n const rules: Record<string, FactoryRuleHandler<FactoryGitLabRuleContext> | null> = { ...defaultGitLabRules };\n for (const key of Reflect.ownKeys(overrides ?? {})) {\n if (typeof key !== 'string' || !Object.hasOwn(defaultGitLabRules, key)) {\n throw new Error(`Unknown GitLab rule event: ${String(key)}.`);\n }\n const handler = overrides?.[key as FactoryGitLabEventName];\n if (handler !== undefined && handler !== null && typeof handler !== 'function') {\n throw new Error(`GitLab rule ${key} must be a function, null, or undefined.`);\n }\n if (handler !== undefined) rules[key] = handler;\n }\n return recordExplicitRuleOverrides(Object.freeze(rules) as GitLabEventR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AAA,MAAc,cAAc,QAAQ,OAAO,cAAc,YAAY,MAAM,QAAQ,SAAS,IAC5G,MAAM,IAAI,MAAM,iCAAiC;CAEnD,MAAM,QAA6E,EAAE,GAAG,mBAAmB;CAC3G,KAAK,MAAM,OAAO,QAAQ,QAAQ,aAAa,CAAC,CAAC,GAAG;EAClD,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,OAAO,oBAAoB,GAAG,GACnE,MAAM,IAAI,MAAM,8BAA8B,OAAO,GAAG,EAAE,EAAE;EAE9D,MAAM,UAAU,YAAY;EAC5B,IAAI,YAAY,KAAA,KAAa,YAAY,QAAQ,OAAO,YAAY,YAClE,MAAM,IAAI,MAAM,eAAe,IAAI,yCAAyC;EAE9E,IAAI,YAAY,KAAA,GAAW,MAAM,OAAO;CAC1C;CACA,OAAO,4BAA4B,OAAO,OAAO,KAAK,GAAuB,SAAS;AACxF"}
1
+ {"version":3,"file":"default-rules.js","names":[],"sources":["../../../src/integrations/gitlab/default-rules.ts"],"sourcesContent":["import { isPullRequestCard, pullRequestReviewPhase, reviewsPullRequest } from '../../boards/index.js';\nimport { closedByRoutes, recordExplicitRuleOverrides } from '../../rules/event-rules.js';\nimport type { FactoryGitLabEventName, FactoryGitLabRuleContext, FactoryRuleHandler } from '../../rules/types.js';\n\nexport type GitLabRuleOverrides = Partial<\n Record<FactoryGitLabEventName, FactoryRuleHandler<FactoryGitLabRuleContext> | null | undefined>\n>;\nexport type GitLabEventRules = Readonly<\n Record<FactoryGitLabEventName, FactoryRuleHandler<FactoryGitLabRuleContext> | null>\n>;\n\nfunction actorUsername(context: Pick<FactoryGitLabRuleContext, 'actor'>): string | undefined {\n return context.actor.type === 'gitlab' ? context.actor.username : undefined;\n}\n\nfunction trustedGitLabActor(context: Pick<FactoryGitLabRuleContext, 'actor'>): boolean {\n return context.actor.type === 'gitlab' && context.actor.trusted;\n}\n\nfunction createdAfterFactory(createdAt: string | undefined, factoryCreatedAt: string): boolean {\n if (!createdAt) return false;\n const sourceCreatedAt = Date.parse(createdAt);\n const projectCreatedAt = Date.parse(factoryCreatedAt);\n return Number.isFinite(sourceCreatedAt) && Number.isFinite(projectCreatedAt) && sourceCreatedAt > projectCreatedAt;\n}\n\n/** The Work card whose session authored the merge request, as opposed to the merge request's own card. */\nfunction authoringCard(context: FactoryGitLabRuleContext): boolean {\n return context.board === 'work' && context.item !== undefined && !isPullRequestCard(context.item);\n}\n\n/** The board holding the merge request's own card: Work for new cards, Review for cards filed before. */\nfunction mergeRequestCardBoard(context: FactoryGitLabRuleContext): 'work' | 'review' {\n return context.board === 'review' ? 'review' : 'work';\n}\n\nfunction mergeRequestCardNoun(context: FactoryGitLabRuleContext): string {\n return context.board === 'review' ? 'Review card' : 'merge request card';\n}\n\nfunction issueOpened(context: FactoryGitLabRuleContext) {\n if (!context.issue) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:issue-intake`,\n board: context.intake?.board ?? 'work',\n source: 'gitlab-issue',\n sourceKey: context.issue.sourceKey,\n title: context.issue.title,\n url: context.issue.url,\n stage: context.intake?.initialPhase ?? 'intake',\n metadata: {\n gitlabHost: context.repository.host,\n gitlabProjectId: context.repository.id,\n gitlabIssueIid: context.issue.number,\n identifier: `${context.repository.fullName}#${context.issue.number}`,\n ...(context.issue.createdAt ? { sourceCreatedAt: context.issue.createdAt } : {}),\n ...((context.issue.author ?? actorUsername(context))\n ? { author: context.issue.author ?? actorUsername(context) }\n : {}),\n authorTrusted: context.issue.authorTrusted,\n autoStartCandidate:\n trustedGitLabActor(context) &&\n context.issue.authorTrusted &&\n createdAfterFactory(context.issue.createdAt, context.factory.createdAt),\n assignees: context.issue.assignees ?? [],\n labels: context.issue.labels ?? [],\n labelColors: context.issue.labelColors ?? {},\n },\n } as const;\n}\n\nfunction issueClosed(context: FactoryGitLabRuleContext) {\n if (!context.item || context.item.source !== 'gitlab-issue') return;\n // The project's intake routes decide where a closed source sends the card. The board's\n // `sourceClosed` mapping applies only when no route on the board handles closes; without\n // one the close goes to the routes alone (see `routeEventDecision`).\n const closure = context.boardClosure;\n if (!context.board || !closure || closure.itemTerminal) return;\n // GitLab reports no close reason, so every closure counts as completed.\n return closedByRoutes(false, {\n idempotencyKey: `${context.ingress.id}:issue-closed`,\n board: context.board,\n stage: closure.completed.phase,\n message: {\n text: `GitLab issue #${context.issue?.number ?? ''} was closed; this ${closure.boardTitle} card was moved to ${closure.completed.title}.`,\n },\n });\n}\n\nfunction materializeMergeRequest(context: FactoryGitLabRuleContext) {\n if (!context.mergeRequest) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:merge-request-intake`,\n board: 'work',\n source: 'gitlab-pr',\n sourceKey: context.mergeRequest.sourceKey,\n title: context.mergeRequest.title,\n url: context.mergeRequest.url,\n stage: 'intake',\n metadata: {\n gitlabHost: context.repository.host,\n gitlabProjectId: context.repository.id,\n gitlabMergeRequestIid: context.mergeRequest.number,\n ...(context.mergeRequest.createdAt ? { sourceCreatedAt: context.mergeRequest.createdAt } : {}),\n factoryAuthored: context.mergeRequest.factoryAuthored,\n authorTrusted: context.mergeRequest.authorTrusted,\n autoStartCandidate:\n ((trustedGitLabActor(context) && context.mergeRequest.authorTrusted) || context.mergeRequest.factoryAuthored) &&\n createdAfterFactory(context.mergeRequest.createdAt, context.factory.createdAt),\n state: context.mergeRequest.state,\n draft: context.mergeRequest.draft,\n merged: context.mergeRequest.merged,\n assignees: context.mergeRequest.assignees ?? [],\n requestedReviewers: context.mergeRequest.reviewers ?? [],\n labels: context.mergeRequest.labels ?? [],\n labelColors: context.mergeRequest.labelColors ?? {},\n headBranch: context.mergeRequest.headBranch,\n baseBranch: context.mergeRequest.baseBranch,\n ...(context.mergeRequest.author ? { author: context.mergeRequest.author } : {}),\n },\n } as const;\n}\n\nfunction mergeRequestUpdated(context: FactoryGitLabRuleContext) {\n if (!context.item || context.item.source !== 'gitlab-pr' || !reviewsPullRequest(context)) return;\n if (!context.mergeRequest || context.mergeRequest.state !== 'open' || context.mergeRequest.merged) return;\n if (context.item.stages.some(stage => stage === 'intake')) return;\n // An untrusted push must not start review passes on demand.\n if (!trustedGitLabActor(context) && !context.mergeRequest.factoryAuthored) return;\n const stage = pullRequestReviewPhase(context.board);\n const alreadyReviewing = context.item.stages.some(current => current === stage);\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:re-review-updated`,\n board: mergeRequestCardBoard(context),\n stage,\n ...(alreadyReviewing ? { reenter: true } : {}),\n } as const;\n}\n\nfunction mergeRequestCommented(context: FactoryGitLabRuleContext) {\n if (!context.item || !context.mergeRequest || !context.note || !authoringCard(context)) return;\n if (context.mergeRequest.state !== 'open' || context.mergeRequest.merged) return;\n if (context.actor.type === 'gitlab' && context.actor.factoryAuthored) return;\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:address-merge-request-comment`,\n role: 'work',\n priority: 'high',\n message:\n `${context.note.author ?? 'Someone'} commented on GitLab merge request !${context.mergeRequest.number} ` +\n `(${context.note.url ?? context.mergeRequest.url}). Read the comment, address it if you agree, and push ` +\n 'the fixes to the merge-request branch. Reply in GitLab to anything you are deliberately not changing.',\n } as const;\n}\n\nfunction mergeRequestMerged(context: FactoryGitLabRuleContext) {\n if (!context.item || !context.mergeRequest?.merged) return;\n if (reviewsPullRequest(context)) {\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:merge-request-merged`,\n board: mergeRequestCardBoard(context),\n stage: 'done',\n message: {\n text: `GitLab merge request !${context.mergeRequest.number} merged; this ${mergeRequestCardNoun(context)} was moved to Done.`,\n },\n } as const;\n }\n if (!authoringCard(context)) return;\n return {\n type: 'sendMessage',\n idempotencyKey: `${context.ingress.id}:assess-work-completion`,\n role: 'work',\n message:\n `GitLab merge request !${context.mergeRequest.number} merged. Assess whether the linked Work item is complete. ` +\n 'Do not mark it Done solely because this merge request merged.',\n } as const;\n}\n\nfunction mergeRequestClosed(context: FactoryGitLabRuleContext) {\n if (!context.item || !context.mergeRequest || context.mergeRequest.merged || !reviewsPullRequest(context)) return;\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:merge-request-closed`,\n board: mergeRequestCardBoard(context),\n stage: 'canceled',\n message: {\n text:\n `GitLab merge request !${context.mergeRequest.number} was closed without merging; ` +\n `this ${mergeRequestCardNoun(context)} was moved to Canceled.`,\n },\n } as const;\n}\n\nexport const defaultGitLabRules = Object.freeze({\n issueOpened,\n // Triage runs once, when a person moves the card into Triage or starts the run; later edits and\n // comments on the issue don't run it again.\n issueUpdated: null,\n issueClosed,\n // A reopen files a card when the issue has none, as an open does. A card the issue already has\n // is left to the project's intake routes.\n issueReopened: context => (context.item ? undefined : issueOpened(context)),\n issueCommented: null,\n mergeRequestOpened: materializeMergeRequest,\n mergeRequestUpdated,\n mergeRequestCommented,\n mergeRequestMerged,\n mergeRequestClosed,\n} satisfies GitLabEventRules);\n\nexport function resolveGitLabRules(overrides?: GitLabRuleOverrides): GitLabEventRules {\n if (overrides !== undefined && (overrides === null || typeof overrides !== 'object' || Array.isArray(overrides))) {\n throw new Error('GitLab rules must be an object.');\n }\n const rules: Record<string, FactoryRuleHandler<FactoryGitLabRuleContext> | null> = { ...defaultGitLabRules };\n for (const key of Reflect.ownKeys(overrides ?? {})) {\n if (typeof key !== 'string' || !Object.hasOwn(defaultGitLabRules, key)) {\n throw new Error(`Unknown GitLab rule event: ${String(key)}.`);\n }\n const handler = overrides?.[key as FactoryGitLabEventName];\n if (handler !== undefined && handler !== null && typeof handler !== 'function') {\n throw new Error(`GitLab rule ${key} must be a function, null, or undefined.`);\n }\n if (handler !== undefined) rules[key] = handler;\n }\n return recordExplicitRuleOverrides(Object.freeze(rules) as GitLabEventRules, overrides);\n}\n"],"mappings":";;;;AAWA,SAAS,cAAc,SAAsE;CAC3F,OAAO,QAAQ,MAAM,SAAS,WAAW,QAAQ,MAAM,WAAW,KAAA;AACpE;AAEA,SAAS,mBAAmB,SAA2D;CACrF,OAAO,QAAQ,MAAM,SAAS,YAAY,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E,GAAG,mBAAmB;CAC3G,KAAK,MAAM,OAAO,QAAQ,QAAQ,aAAa,CAAC,CAAC,GAAG;EAClD,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,OAAO,oBAAoB,GAAG,GACnE,MAAM,IAAI,MAAM,8BAA8B,OAAO,GAAG,EAAE,EAAE;EAE9D,MAAM,UAAU,YAAY;EAC5B,IAAI,YAAY,KAAA,KAAa,YAAY,QAAQ,OAAO,YAAY,YAClE,MAAM,IAAI,MAAM,eAAe,IAAI,yCAAyC;EAE9E,IAAI,YAAY,KAAA,GAAW,MAAM,OAAO;CAC1C;CACA,OAAO,4BAA4B,OAAO,OAAO,KAAK,GAAuB,SAAS;AACxF"}
@@ -1,5 +1,5 @@
1
- import "../../boards/index.js";
2
1
  import { workItemPhaseSemantics } from "../../boards/semantics.js";
2
+ import "../../boards/index.js";
3
3
  import { FACTORY_PULL_REQUEST_RECONCILIATION_KEY } from "../../storage/domains/work-items/base.js";
4
4
  import { decodeMergeRequestReference, gitlabConnection } from "./integration.js";
5
5
  import { attachGitLabRules } from "./rules.js";
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/integrations/gitlab/routes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAI7D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uCAAuC,CAAC;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAS1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kBAAkB,CAAC;AAG9D,OAAO,KAAK,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAQrF,MAAM,WAAW,wBAAwB;IACvC,MAAM,CAAC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,wBAAwB;IACvC,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAC/B,IAAI,CAAC,EAAE,SAAS,CAAC;IACjB,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,SAAS,CAAC,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;IACjC,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACtE,iFAAiF;IACjF,UAAU,CAAC,EAAE,2BAA2B,CAAC,YAAY,CAAC,CAAC;CACxD;AA8JD,wBAAsB,mCAAmC,CAAC,IAAI,EAAE;IAC9D,MAAM,EAAE,qBAAqB,CAAC;IAC9B,KAAK,EAAE,MAAM,CAAC;IACd,mBAAmB,EAAE,MAAM,CAAC;IAC5B,kBAAkB,CAAC,EAAE,wBAAwB,CAAC,oBAAoB,CAAC,CAAC;CACrE,GAAG,OAAO,CAAC,IAAI,CAAC,CAiChB;AAwCD,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CAqa/E"}
@@ -1,3 +1,4 @@
1
+ import { loose } from "../../routes/route.js";
1
2
  import { sanitizeSegment } from "../../sandbox/workdir.js";
2
3
  import { GitLabApiError } from "./api.js";
3
4
  import { decodeIssueReference, decodeSourceId, encodeIssueReference, encodeSourceId, gitlabConnection } from "./integration.js";
@@ -5,9 +6,6 @@ import { listMergeRequestSubscriptionsForThread, mergeRequestUrl } from "./subsc
5
6
  import { handleGitLabWebhook } from "./webhook.js";
6
7
  import { registerApiRoute } from "@mastra/core/server";
7
8
  // src/integrations/gitlab/routes.ts
8
- function loose(c) {
9
- return c;
10
- }
11
9
  async function resolveOrgTenant(c, auth) {
12
10
  await auth.ensureUser(c);
13
11
  const tenant = auth.tenant(c);
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/gitlab/routes.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactorySandbox } from '@mastra/core/workspace';\nimport type { Context } from 'hono';\nimport type { IntakeIssue } from '../../capabilities/intake.js';\nimport type { PullRequest } from '../../capabilities/version-control.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport { sanitizeSegment } from '../../sandbox/workdir.js';\nimport type { AuditEmitter } from '../../storage/domains/audit/domain.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport { GitLabApiError } from './api.js';\nimport {\n decodeIssueReference,\n decodeSourceId,\n encodeIssueReference,\n encodeSourceId,\n gitlabConnection,\n} from './integration.js';\nimport type { GitLabIntegrationBase } from './integration.js';\nimport { listMergeRequestSubscriptionsForThread, mergeRequestUrl } from './subscriptions.js';\nimport { handleGitLabWebhook } from './webhook.js';\nimport type { GitLabWebhookHandlerOptions, ParsedGitLabWebhook } from './webhook.js';\n\ntype RouteContext = Context;\n\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\nexport interface BuildGitLabRoutesOptions {\n gitlab?: GitLabIntegrationBase;\n auth?: RouteAuth;\n intake?: IntakeStorage;\n sandbox?: FactorySandbox;\n emitAudit?: AuditEmitter['emit'];\n webhookSecret?: string;\n ingestFactoryEvent?: (event: ParsedGitLabWebhook) => Promise<unknown>;\n /** Mounted agent controller; enables webhook delivery to subscribed sessions. */\n controller?: GitLabWebhookHandlerOptions['controller'];\n}\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', reason: 'auth_required' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'GitLab intake requires an organization. Personal accounts cannot use GitLab intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction gitlabFetchError(c: RouteContext, error: unknown) {\n if (error instanceof GitLabApiError && error.code === 'gitlab_auth_failed') {\n return c.json({ error: 'gitlab_auth_failed', message: error.message }, 409);\n }\n return c.json({ error: 'gitlab_fetch_failed', message: error instanceof Error ? error.message : String(error) }, 502);\n}\n\ntype GitLabSourceIdentityMigration = { from: string; to: string };\n\nfunction gitlabProjectPayload(source: { id: string; name: string; metadata?: Record<string, unknown> }) {\n const connectionId = typeof source.metadata?.connectionId === 'string' ? source.metadata.connectionId : null;\n const projectId = typeof source.metadata?.projectId === 'string' ? source.metadata.projectId : null;\n const projectPath = typeof source.metadata?.projectPath === 'string' ? source.metadata.projectPath : source.name;\n if (!connectionId || !projectId) return null;\n const repositoryName = projectPath.split('/').filter(Boolean).at(-1) ?? 'repo';\n return {\n id: source.id,\n name: source.name,\n projectId,\n projectPath,\n connectionId,\n accountLabel: typeof source.metadata?.accountLabel === 'string' ? source.metadata.accountLabel : null,\n defaultBranch: typeof source.metadata?.defaultBranch === 'string' ? source.metadata.defaultBranch : 'main',\n sandboxProvider: 'none',\n sandboxWorkdir: `~/${sanitizeSegment(repositoryName)}`,\n };\n}\n\nfunction positiveId(value: string | undefined): number | null {\n const number = Number(value);\n return value && /^[1-9]\\d*$/.test(value) && Number.isSafeInteger(number) ? number : null;\n}\n\nfunction mergeRequestSourceKey(host: string, projectId: number, mergeRequestIid: number): string {\n return `gitlab-pr:${Buffer.from(JSON.stringify({ version: 1, host, projectId, mergeRequestIid }), 'utf8').toString('base64url')}`;\n}\n\nconst LINKED_BACKLOG_MAX_PAGES = 5;\nconst POLLED_ACTOR = '__factory_poll__';\n\nfunction listedMergeRequestEvent(\n project: { host: string; projectId: number; projectPath: string },\n pr: PullRequest,\n): ParsedGitLabWebhook {\n const iid = Number(pr.id);\n return {\n event: 'Merge Request Hook',\n deliveryId: `poll:merge-request:${project.host}:${project.projectId}:${iid}:${pr.createdAt}`,\n instanceHost: project.host,\n payload: {\n user_username: POLLED_ACTOR,\n project: { id: project.projectId, path_with_namespace: project.projectPath, web_url: `https://${project.host}/${project.projectPath}` },\n object_attributes: {\n iid,\n action: 'open',\n state: 'opened',\n title: pr.title,\n url: pr.url,\n created_at: pr.createdAt,\n updated_at: pr.updatedAt,\n source_branch: pr.headBranch,\n target_branch: pr.baseBranch,\n draft: pr.draft,\n author: pr.author ? { username: pr.author } : undefined,\n assignees: (pr.assignees ?? []).map(username => ({ username })),\n reviewers: (pr.requestedReviewers ?? []).map(username => ({ username })),\n labels: pr.labels ?? [],\n },\n },\n };\n}\n\nfunction listedMergeRequestEvents(\n project: { host: string; projectId: number; projectPath: string },\n pr: PullRequest,\n): ParsedGitLabWebhook[] {\n const opened = listedMergeRequestEvent(project, pr);\n if (!pr.headSha || pr.updatedAt === pr.createdAt) return [opened];\n return [\n opened,\n {\n ...opened,\n deliveryId: `poll:merge-request-head:${project.host}:${project.projectId}:${pr.id}:${pr.updatedAt}:${pr.headSha}`,\n payload: {\n ...opened.payload,\n object_attributes: {\n ...(opened.payload.object_attributes as Record<string, unknown>),\n action: 'update',\n last_commit: { id: pr.headSha },\n },\n },\n },\n ];\n}\n\nfunction listedIssueEvent(issue: IntakeIssue): ParsedGitLabWebhook | null {\n const source = decodeSourceId(issue.sourceId ?? '');\n const projectId = source && positiveId(source.projectId);\n const iid = positiveId(issue.id);\n const projectPath = issue.source || source?.projectPath;\n if (!source?.host || !projectId || !iid || !projectPath) return null;\n return {\n event: 'Issue Hook',\n deliveryId: `poll:issue:${source.host}:${projectId}:${iid}:${issue.createdAt}`,\n instanceHost: source.host,\n payload: {\n user_username: POLLED_ACTOR,\n project: { id: projectId, path_with_namespace: projectPath, web_url: `https://${source.host}/${projectPath}` },\n object_attributes: {\n iid,\n action: 'open',\n state: 'opened',\n title: issue.title,\n url: issue.url,\n created_at: issue.createdAt,\n updated_at: issue.updatedAt,\n author: issue.authorUsername ? { username: issue.authorUsername } : undefined,\n labels: issue.labels ?? [],\n },\n },\n };\n}\n\nasync function ingestListedEvents(events: Array<ParsedGitLabWebhook | null>, ingest?: BuildGitLabRoutesOptions['ingestFactoryEvent']) {\n if (!ingest) return;\n const listed = events.filter((event): event is ParsedGitLabWebhook => event !== null);\n const openings = listed.filter(event => !event.deliveryId.startsWith('poll:merge-request-head:'));\n const headUpdates = listed.filter(event => event.deliveryId.startsWith('poll:merge-request-head:'));\n for (const batch of [openings, headUpdates]) {\n const results = await Promise.allSettled(batch.map(event => ingest(event)));\n const rejected = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');\n if (rejected) console.warn('[Mastra Factory] Failed to ingest listed GitLab events', { error: rejected.reason });\n }\n}\n\nexport async function ingestLinkedGitLabRepositoryBacklog(args: {\n gitlab: GitLabIntegrationBase;\n orgId: string;\n projectRepositoryId: string;\n ingestFactoryEvent?: BuildGitLabRoutesOptions['ingestFactoryEvent'];\n}): Promise<void> {\n if (!args.ingestFactoryEvent) return;\n const storage = args.gitlab.sourceControlStorage;\n const link = await storage?.projectRepositories.get({ orgId: args.orgId, id: args.projectRepositoryId });\n if (!link) return;\n const connection = await storage!.connections.get({ orgId: args.orgId, id: link.connectionId });\n if (!connection || connection.integrationId !== 'gitlab') return;\n const linked = await args.gitlab.getLinkedRepository({\n orgId: args.orgId,\n factoryProjectId: connection.factoryProjectId,\n projectRepositoryId: link.id,\n });\n if (!linked) return;\n const projectId = positiveId(linked.repository.externalId);\n if (!projectId) return;\n const project = { host: linked.host, projectId, projectPath: linked.repository.slug };\n const target = await args.gitlab.versionControl.getRepositoryTarget({\n orgId: args.orgId,\n repositoryId: linked.repository.id,\n });\n for (let page = 1; page <= LINKED_BACKLOG_MAX_PAGES; page += 1) {\n const result = await args.gitlab.versionControl.listPullRequests({ ...target, includeDrafts: false, cursor: String(page) });\n await ingestListedEvents(result.pullRequests.flatMap(pr => listedMergeRequestEvents(project, pr)), args.ingestFactoryEvent);\n if (result.nextCursor === null) break;\n }\n const sourceId = encodeSourceId({ host: linked.host, projectId: String(projectId) });\n let cursor: string | undefined;\n for (let page = 1; page <= LINKED_BACKLOG_MAX_PAGES; page += 1) {\n const result = await args.gitlab.intake.listIssues({ connection: target.connection, sourceIds: [sourceId], cursor });\n await ingestListedEvents(result.issues.map(listedIssueEvent), args.ingestFactoryEvent);\n if (result.nextCursor === null) break;\n cursor = result.nextCursor;\n }\n}\n\nasync function reconcileGitLabSourceIdentity({\n intake,\n orgId,\n sources,\n}: {\n intake: IntakeStorage;\n orgId: string;\n sources: Array<{ id: string; metadata?: Record<string, unknown> }>;\n}): Promise<{ migrations: GitLabSourceIdentityMigration[]; conflicts: GitLabSourceIdentityMigration[] }> {\n await intake.ensureReady();\n const [config, bindings] = await Promise.all([\n intake.getConfig({ orgId }),\n intake.listBindings({ orgId, integrationId: 'gitlab' }),\n ]);\n const selected = config.gitlab?.sourceIds ?? [];\n const canonicalByProject = new Map<string, string[]>();\n for (const source of sources) {\n const reference = decodeSourceId(source.id);\n if (!reference?.host) continue;\n const ids = canonicalByProject.get(reference.projectId) ?? [];\n ids.push(source.id);\n canonicalByProject.set(reference.projectId, ids);\n }\n\n const migrations = new Map<string, string>();\n for (const sourceId of new Set([...selected, ...bindings.map(binding => binding.sourceId)])) {\n const reference = decodeSourceId(sourceId);\n if (!reference || reference.host) continue;\n const candidates = canonicalByProject.get(reference.projectId) ?? [];\n if (candidates.length === 1) migrations.set(sourceId, candidates[0]!);\n }\n return intake.migrateSourceIds({\n orgId,\n integrationId: 'gitlab',\n migrations: [...migrations].map(([from, to]) => ({ from, to })),\n });\n}\n\nexport function buildGitLabRoutes(options: BuildGitLabRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { gitlab, auth, intake, emitAudit } = options;\n const enabled = Boolean(gitlab && auth?.enabled());\n\n if (gitlab && auth) {\n routes.push(\n registerApiRoute('/web/gitlab/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const diagnostics = gitlab.diagnostics();\n if (!enabled) {\n return c.json({ enabled: false, configured: true, reauthRequired: false, reason: 'missing_config' });\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 if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: false,\n organizationRequired: true,\n connections: [],\n accounts: [],\n reauthRequired: false,\n reason: 'organization_required',\n });\n }\n\n try {\n await gitlab.verifyStatus();\n const connections = await gitlab.statusConnections();\n const active = connections?.filter(connection => connection.status === 'active');\n const direct = connections === undefined;\n const endpointHost = typeof diagnostics.endpointHost === 'string' ? diagnostics.endpointHost : null;\n const accounts = direct\n ? endpointHost\n ? [endpointHost]\n : []\n : (active ?? []).flatMap(connection => (connection.accountLabel ? [connection.accountLabel] : []));\n const configured = direct || (active?.length ?? 0) > 0;\n return c.json({\n enabled: true,\n configured,\n mode: direct ? 'direct' : 'platform',\n ...(connections ? { connections } : {}),\n accounts,\n reauthRequired: connections?.some(connection => connection.status === 'needs_reauth') ?? false,\n reason: configured ? 'ready' : 'not_connected',\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/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 try {\n const sources = await gitlab.intake.listSources(resolved.tenant);\n if (intake) {\n const identity = await reconcileGitLabSourceIdentity({\n intake,\n orgId: resolved.tenant.orgId,\n sources,\n });\n if (identity.conflicts.length > 0) {\n return c.json(\n {\n error: 'gitlab_source_identity_conflict',\n message: 'Conflicting routes exist for the same GitLab project. Resolve the duplicate bindings.',\n conflicts: identity.conflicts,\n },\n 409,\n );\n }\n if (identity.migrations.length > 0) {\n await emitAudit?.({\n context: loose(c),\n input: {\n action: 'factory.intake.config_updated',\n targets: identity.migrations.map(migration => ({ type: 'intake_source', id: migration.to })),\n metadata: { provider: 'gitlab', migrated: identity.migrations.length },\n },\n });\n }\n }\n return c.json({\n projects: sources.flatMap(source => {\n const project = gitlabProjectPayload(source);\n return project ? [{ ...project, sandboxProvider: options.sandbox ? 'custom' : 'none' }] : [];\n }),\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/projects/registration', {\n method: 'POST',\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 input = (await c.req.json().catch(() => null)) as { sourceId?: unknown } | null;\n const sourceId = typeof input?.sourceId === 'string' ? input.sourceId.trim() : '';\n if (!sourceId) return c.json({ error: 'invalid_gitlab_source' }, 400);\n try {\n const source = (await gitlab.intake.listSources(resolved.tenant)).find(\n candidate => candidate.id === sourceId,\n );\n const project = source ? gitlabProjectPayload(source) : null;\n if (!project) return c.json({ error: 'gitlab_project_not_found' }, 404);\n const installation = await gitlab.versionControl.registerInstallation({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n installation: {\n externalId: project.connectionId,\n accountName: project.accountLabel ?? 'GitLab',\n accountType: 'GitLab',\n metadata: { connection: gitlabConnection(project.connectionId) },\n },\n });\n return c.json({\n project: {\n ...project,\n installationStorageId: installation.id,\n sandboxProvider: options.sandbox ? 'custom' : 'none',\n },\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/projects/:id/prs', {\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 factoryProjectId = c.req.query('factoryProjectId')?.trim();\n const page = positiveId(c.req.query('page') ?? '1');\n if (!factoryProjectId || !page) return c.json({ error: 'invalid_request' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId)\n return c.json({ error: 'factory_project_not_found' }, 404);\n const linked = await gitlab.getLinkedRepository({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n projectRepositoryId: c.req.param('id'),\n });\n if (!linked) return c.json({ error: 'project_repository_not_found' }, 404);\n const projectId = positiveId(linked.repository.externalId);\n if (!projectId) return c.json({ error: 'invalid_gitlab_project' }, 502);\n try {\n const target = await gitlab.versionControl.getRepositoryTarget({\n orgId: resolved.tenant.orgId,\n repositoryId: linked.repository.id,\n });\n const result = await gitlab.versionControl.listPullRequests({\n ...target,\n includeDrafts: false,\n cursor: String(page),\n });\n await ingestListedEvents(\n result.pullRequests.flatMap(pr =>\n listedMergeRequestEvents({ host: linked.host, projectId, projectPath: linked.repository.slug }, pr),\n ),\n options.ingestFactoryEvent,\n );\n return c.json({\n pullRequests: result.pullRequests.map(pr => ({\n number: Number(pr.id),\n externalId: mergeRequestSourceKey(linked.host, projectId, Number(pr.id)),\n title: pr.title,\n url: pr.url,\n author: pr.author,\n assignees: pr.assignees ?? [],\n requestedReviewers: pr.requestedReviewers ?? [],\n labels: pr.labels ?? [],\n baseBranch: pr.baseBranch,\n headBranch: pr.headBranch,\n createdAt: pr.createdAt,\n updatedAt: pr.updatedAt,\n })),\n nextPage: result.nextCursor === null ? null : Number(result.nextCursor),\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/projects/:id/prs/:number', {\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 factoryProjectId = c.req.query('factoryProjectId')?.trim();\n const number = positiveId(c.req.param('number'));\n if (!factoryProjectId || !number) return c.json({ error: 'invalid_request' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId)\n return c.json({ error: 'factory_project_not_found' }, 404);\n const linked = await gitlab.getLinkedRepository({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n projectRepositoryId: c.req.param('id'),\n });\n if (!linked) return c.json({ error: 'project_repository_not_found' }, 404);\n try {\n const target = await gitlab.versionControl.getRepositoryTarget({\n orgId: resolved.tenant.orgId,\n repositoryId: linked.repository.id,\n });\n const pr = await gitlab.versionControl.getPullRequest({ ...target, pullRequestId: String(number) });\n if (!pr) return c.json({ error: 'merge_request_not_found' }, 404);\n return c.json({\n number,\n title: pr.title,\n url: pr.url,\n author: pr.author,\n assignees: pr.assignees ?? [],\n requestedReviewers: pr.requestedReviewers ?? [],\n baseBranch: pr.baseBranch,\n headBranch: pr.headBranch,\n createdAt: pr.createdAt,\n updatedAt: pr.updatedAt,\n description: pr.body,\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n );\n }\n\n if (gitlab && auth && intake) {\n routes.push(\n registerApiRoute('/web/gitlab/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 const factoryProjectId = c.req.query('factoryProjectId')?.trim();\n if (!factoryProjectId) return c.json({ error: 'invalid_factory_project_id' }, 400);\n const board = c.req.query('board')?.trim();\n if (!board) return c.json({ error: 'invalid_board' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['gitlab'] });\n const selection = config.gitlab!;\n if (!selection.enabled) {\n return c.json(\n { error: 'gitlab_intake_disabled', message: 'GitLab intake is turned off in Settings.' },\n 404,\n );\n }\n const selected = new Set(selection.sourceIds ?? []);\n const sourceIds = [\n ...new Set(\n (await intake.listBindings({ orgId: resolved.tenant.orgId, integrationId: 'gitlab' }))\n .filter(\n binding =>\n binding.factoryProjectId === factoryProjectId &&\n binding.board === board &&\n selected.has(binding.sourceId),\n )\n .map(binding => binding.sourceId),\n ),\n ];\n if (sourceIds.length === 0) return c.json({ issues: [], nextCursor: null });\n\n try {\n const result = await gitlab.intake.listIssues({\n connection: { type: 'oauth', accessToken: 'gitlab-route' },\n sourceIds,\n cursor: c.req.query('after')?.trim() || undefined,\n });\n await ingestListedEvents(result.issues.map(listedIssueEvent), options.ingestFactoryEvent);\n return c.json({\n ...result,\n issues: result.issues.map(issue => {\n const source = decodeSourceId(issue.sourceId ?? '');\n const issueIid = Number(issue.id);\n if (!source || !Number.isSafeInteger(issueIid) || issueIid <= 0) {\n throw new Error('GitLab returned an invalid routed issue reference.');\n }\n return { ...issue, externalId: encodeIssueReference({ ...source, issueIid }) };\n }),\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/gitlab/issues/:issueId', {\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 factoryProjectId = c.req.query('factoryProjectId')?.trim();\n if (!factoryProjectId) return c.json({ error: 'invalid_factory_project_id' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n const issueId = c.req.param('issueId')?.trim();\n const issueReference = issueId ? decodeIssueReference(issueId) : null;\n if (!issueReference) return c.json({ error: 'invalid_gitlab_issue_id' }, 400);\n\n const { host, connectionId, projectId, projectPath } = issueReference;\n const sourceId = host\n ? encodeSourceId({ host, projectId })\n : encodeSourceId({ connectionId, projectId, projectPath });\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['gitlab'] });\n const selection = config.gitlab!;\n const selected = new Set(selection.sourceIds ?? []);\n const routed =\n selection.enabled &&\n selected.has(sourceId) &&\n (await intake.listBindings({ orgId: resolved.tenant.orgId, integrationId: 'gitlab' })).some(\n binding => binding.factoryProjectId === factoryProjectId && binding.sourceId === sourceId,\n );\n if (!routed) return c.json({ error: 'gitlab_issue_not_routed' }, 404);\n\n try {\n const issue = await gitlab.intake.getIssue({\n connection: { type: 'oauth', accessToken: 'gitlab-route' },\n issueId,\n });\n if (!issue) return c.json({ error: 'gitlab_issue_not_found' }, 404);\n return c.json(issue);\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n );\n }\n\n if (gitlab && auth) {\n routes.push(\n registerApiRoute('/web/gitlab/subscriptions', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n // Sessions read by session id; resourceId is the older address.\n const sessionId = c.req.query('sessionId');\n const resourceId = c.req.query('resourceId');\n const threadId = c.req.query('threadId');\n const target = !threadId\n ? null\n : sessionId\n ? { orgId: tenant.orgId, sessionId, threadId }\n : resourceId\n ? { orgId: tenant.orgId, resourceId, threadId }\n : null;\n if (!target) return c.json({ error: 'sessionId (or resourceId) and threadId are required' }, 400);\n\n const subscriptions = await listMergeRequestSubscriptionsForThread(target, gitlab.integrationStorage);\n return c.json({\n subscriptions: subscriptions.map(subscription => ({\n id: subscription.id,\n repoFullName: subscription.data.projectPath,\n pullRequestNumber: Number(subscription.data.changeRequestId),\n status: subscription.status,\n url: mergeRequestUrl(\n subscription.data.host,\n subscription.data.projectPath,\n subscription.data.changeRequestId,\n ),\n })),\n });\n },\n }),\n );\n }\n\n routes.push(\n registerApiRoute('/web/gitlab/webhook', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const result = await handleGitLabWebhook(loose(c), {\n webhookSecret: options.webhookSecret,\n ingestFactoryEvent: options.ingestFactoryEvent,\n ...(options.controller && gitlab\n ? {\n controller: options.controller,\n gitlab,\n onTargetError: (subscription, error) => {\n console.warn(\n `[GitLab Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`,\n error,\n );\n },\n }\n : {}),\n });\n return c.json(result.body, result.status);\n },\n }),\n );\n return routes;\n}\n"],"mappings":";;;;;;;AAyBA,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;AAcA,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAA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,GAAG;IACjD,eAAe,QAAQ;IACvB,oBAAoB,QAAQ;IAC5B,GAAI,QAAQ,cAAc,SACtB;KACE,YAAY,QAAQ;KACpB;KACA,gBAAgB,cAAc,UAAU;MACtC,QAAQ,KACN,qDAAqD,aAAa,GAAG,IAAI,aAAa,WAAW,GAAG,aAAa,SAAS,KAC1H,KACF;KACF;IACF,IACA,CAAC;GACP,CAAC;GACD,OAAO,EAAE,KAAK,OAAO,MAAM,OAAO,MAAM;EAC1C;CACF,CAAC,CACH;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/gitlab/routes.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { FactorySandbox } from '@mastra/core/workspace';\nimport type { Context } from 'hono';\nimport type { IntakeIssue } from '../../capabilities/intake.js';\nimport type { PullRequest } from '../../capabilities/version-control.js';\nimport { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport { sanitizeSegment } from '../../sandbox/workdir.js';\nimport type { AuditEmitter } from '../../storage/domains/audit/domain.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport { GitLabApiError } from './api.js';\nimport {\n decodeIssueReference,\n decodeSourceId,\n encodeIssueReference,\n encodeSourceId,\n gitlabConnection,\n} from './integration.js';\nimport type { GitLabIntegrationBase } from './integration.js';\nimport { listMergeRequestSubscriptionsForThread, mergeRequestUrl } from './subscriptions.js';\nimport { handleGitLabWebhook } from './webhook.js';\nimport type { GitLabWebhookHandlerOptions, ParsedGitLabWebhook } from './webhook.js';\n\ntype RouteContext = Context;\n\nexport interface BuildGitLabRoutesOptions {\n gitlab?: GitLabIntegrationBase;\n auth?: RouteAuth;\n intake?: IntakeStorage;\n sandbox?: FactorySandbox;\n emitAudit?: AuditEmitter['emit'];\n webhookSecret?: string;\n ingestFactoryEvent?: (event: ParsedGitLabWebhook) => Promise<unknown>;\n /** Mounted agent controller; enables webhook delivery to subscribed sessions. */\n controller?: GitLabWebhookHandlerOptions['controller'];\n}\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', reason: 'auth_required' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'GitLab intake requires an organization. Personal accounts cannot use GitLab intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\nfunction gitlabFetchError(c: RouteContext, error: unknown) {\n if (error instanceof GitLabApiError && error.code === 'gitlab_auth_failed') {\n return c.json({ error: 'gitlab_auth_failed', message: error.message }, 409);\n }\n return c.json({ error: 'gitlab_fetch_failed', message: error instanceof Error ? error.message : String(error) }, 502);\n}\n\ntype GitLabSourceIdentityMigration = { from: string; to: string };\n\nfunction gitlabProjectPayload(source: { id: string; name: string; metadata?: Record<string, unknown> }) {\n const connectionId = typeof source.metadata?.connectionId === 'string' ? source.metadata.connectionId : null;\n const projectId = typeof source.metadata?.projectId === 'string' ? source.metadata.projectId : null;\n const projectPath = typeof source.metadata?.projectPath === 'string' ? source.metadata.projectPath : source.name;\n if (!connectionId || !projectId) return null;\n const repositoryName = projectPath.split('/').filter(Boolean).at(-1) ?? 'repo';\n return {\n id: source.id,\n name: source.name,\n projectId,\n projectPath,\n connectionId,\n accountLabel: typeof source.metadata?.accountLabel === 'string' ? source.metadata.accountLabel : null,\n defaultBranch: typeof source.metadata?.defaultBranch === 'string' ? source.metadata.defaultBranch : 'main',\n sandboxProvider: 'none',\n sandboxWorkdir: `~/${sanitizeSegment(repositoryName)}`,\n };\n}\n\nfunction positiveId(value: string | undefined): number | null {\n const number = Number(value);\n return value && /^[1-9]\\d*$/.test(value) && Number.isSafeInteger(number) ? number : null;\n}\n\nfunction mergeRequestSourceKey(host: string, projectId: number, mergeRequestIid: number): string {\n return `gitlab-pr:${Buffer.from(JSON.stringify({ version: 1, host, projectId, mergeRequestIid }), 'utf8').toString('base64url')}`;\n}\n\nconst LINKED_BACKLOG_MAX_PAGES = 5;\nconst POLLED_ACTOR = '__factory_poll__';\n\nfunction listedMergeRequestEvent(\n project: { host: string; projectId: number; projectPath: string },\n pr: PullRequest,\n): ParsedGitLabWebhook {\n const iid = Number(pr.id);\n return {\n event: 'Merge Request Hook',\n deliveryId: `poll:merge-request:${project.host}:${project.projectId}:${iid}:${pr.createdAt}`,\n instanceHost: project.host,\n payload: {\n user_username: POLLED_ACTOR,\n project: { id: project.projectId, path_with_namespace: project.projectPath, web_url: `https://${project.host}/${project.projectPath}` },\n object_attributes: {\n iid,\n action: 'open',\n state: 'opened',\n title: pr.title,\n url: pr.url,\n created_at: pr.createdAt,\n updated_at: pr.updatedAt,\n source_branch: pr.headBranch,\n target_branch: pr.baseBranch,\n draft: pr.draft,\n author: pr.author ? { username: pr.author } : undefined,\n assignees: (pr.assignees ?? []).map(username => ({ username })),\n reviewers: (pr.requestedReviewers ?? []).map(username => ({ username })),\n labels: pr.labels ?? [],\n },\n },\n };\n}\n\nfunction listedMergeRequestEvents(\n project: { host: string; projectId: number; projectPath: string },\n pr: PullRequest,\n): ParsedGitLabWebhook[] {\n const opened = listedMergeRequestEvent(project, pr);\n if (!pr.headSha || pr.updatedAt === pr.createdAt) return [opened];\n return [\n opened,\n {\n ...opened,\n deliveryId: `poll:merge-request-head:${project.host}:${project.projectId}:${pr.id}:${pr.updatedAt}:${pr.headSha}`,\n payload: {\n ...opened.payload,\n object_attributes: {\n ...(opened.payload.object_attributes as Record<string, unknown>),\n action: 'update',\n last_commit: { id: pr.headSha },\n },\n },\n },\n ];\n}\n\nfunction listedIssueEvent(issue: IntakeIssue): ParsedGitLabWebhook | null {\n const source = decodeSourceId(issue.sourceId ?? '');\n const projectId = source && positiveId(source.projectId);\n const iid = positiveId(issue.id);\n const projectPath = issue.source || source?.projectPath;\n if (!source?.host || !projectId || !iid || !projectPath) return null;\n return {\n event: 'Issue Hook',\n deliveryId: `poll:issue:${source.host}:${projectId}:${iid}:${issue.createdAt}`,\n instanceHost: source.host,\n payload: {\n user_username: POLLED_ACTOR,\n project: { id: projectId, path_with_namespace: projectPath, web_url: `https://${source.host}/${projectPath}` },\n object_attributes: {\n iid,\n action: 'open',\n state: 'opened',\n title: issue.title,\n url: issue.url,\n created_at: issue.createdAt,\n updated_at: issue.updatedAt,\n author: issue.authorUsername ? { username: issue.authorUsername } : undefined,\n labels: issue.labels ?? [],\n },\n },\n };\n}\n\nasync function ingestListedEvents(events: Array<ParsedGitLabWebhook | null>, ingest?: BuildGitLabRoutesOptions['ingestFactoryEvent']) {\n if (!ingest) return;\n const listed = events.filter((event): event is ParsedGitLabWebhook => event !== null);\n const openings = listed.filter(event => !event.deliveryId.startsWith('poll:merge-request-head:'));\n const headUpdates = listed.filter(event => event.deliveryId.startsWith('poll:merge-request-head:'));\n for (const batch of [openings, headUpdates]) {\n const results = await Promise.allSettled(batch.map(event => ingest(event)));\n const rejected = results.find((result): result is PromiseRejectedResult => result.status === 'rejected');\n if (rejected) console.warn('[Mastra Factory] Failed to ingest listed GitLab events', { error: rejected.reason });\n }\n}\n\nexport async function ingestLinkedGitLabRepositoryBacklog(args: {\n gitlab: GitLabIntegrationBase;\n orgId: string;\n projectRepositoryId: string;\n ingestFactoryEvent?: BuildGitLabRoutesOptions['ingestFactoryEvent'];\n}): Promise<void> {\n if (!args.ingestFactoryEvent) return;\n const storage = args.gitlab.sourceControlStorage;\n const link = await storage?.projectRepositories.get({ orgId: args.orgId, id: args.projectRepositoryId });\n if (!link) return;\n const connection = await storage!.connections.get({ orgId: args.orgId, id: link.connectionId });\n if (!connection || connection.integrationId !== 'gitlab') return;\n const linked = await args.gitlab.getLinkedRepository({\n orgId: args.orgId,\n factoryProjectId: connection.factoryProjectId,\n projectRepositoryId: link.id,\n });\n if (!linked) return;\n const projectId = positiveId(linked.repository.externalId);\n if (!projectId) return;\n const project = { host: linked.host, projectId, projectPath: linked.repository.slug };\n const target = await args.gitlab.versionControl.getRepositoryTarget({\n orgId: args.orgId,\n repositoryId: linked.repository.id,\n });\n for (let page = 1; page <= LINKED_BACKLOG_MAX_PAGES; page += 1) {\n const result = await args.gitlab.versionControl.listPullRequests({ ...target, includeDrafts: false, cursor: String(page) });\n await ingestListedEvents(result.pullRequests.flatMap(pr => listedMergeRequestEvents(project, pr)), args.ingestFactoryEvent);\n if (result.nextCursor === null) break;\n }\n const sourceId = encodeSourceId({ host: linked.host, projectId: String(projectId) });\n let cursor: string | undefined;\n for (let page = 1; page <= LINKED_BACKLOG_MAX_PAGES; page += 1) {\n const result = await args.gitlab.intake.listIssues({ connection: target.connection, sourceIds: [sourceId], cursor });\n await ingestListedEvents(result.issues.map(listedIssueEvent), args.ingestFactoryEvent);\n if (result.nextCursor === null) break;\n cursor = result.nextCursor;\n }\n}\n\nasync function reconcileGitLabSourceIdentity({\n intake,\n orgId,\n sources,\n}: {\n intake: IntakeStorage;\n orgId: string;\n sources: Array<{ id: string; metadata?: Record<string, unknown> }>;\n}): Promise<{ migrations: GitLabSourceIdentityMigration[]; conflicts: GitLabSourceIdentityMigration[] }> {\n await intake.ensureReady();\n const [config, bindings] = await Promise.all([\n intake.getConfig({ orgId }),\n intake.listBindings({ orgId, integrationId: 'gitlab' }),\n ]);\n const selected = config.gitlab?.sourceIds ?? [];\n const canonicalByProject = new Map<string, string[]>();\n for (const source of sources) {\n const reference = decodeSourceId(source.id);\n if (!reference?.host) continue;\n const ids = canonicalByProject.get(reference.projectId) ?? [];\n ids.push(source.id);\n canonicalByProject.set(reference.projectId, ids);\n }\n\n const migrations = new Map<string, string>();\n for (const sourceId of new Set([...selected, ...bindings.map(binding => binding.sourceId)])) {\n const reference = decodeSourceId(sourceId);\n if (!reference || reference.host) continue;\n const candidates = canonicalByProject.get(reference.projectId) ?? [];\n if (candidates.length === 1) migrations.set(sourceId, candidates[0]!);\n }\n return intake.migrateSourceIds({\n orgId,\n integrationId: 'gitlab',\n migrations: [...migrations].map(([from, to]) => ({ from, to })),\n });\n}\n\nexport function buildGitLabRoutes(options: BuildGitLabRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { gitlab, auth, intake, emitAudit } = options;\n const enabled = Boolean(gitlab && auth?.enabled());\n\n if (gitlab && auth) {\n routes.push(\n registerApiRoute('/web/gitlab/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const diagnostics = gitlab.diagnostics();\n if (!enabled) {\n return c.json({ enabled: false, configured: true, reauthRequired: false, reason: 'missing_config' });\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 if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: false,\n organizationRequired: true,\n connections: [],\n accounts: [],\n reauthRequired: false,\n reason: 'organization_required',\n });\n }\n\n try {\n await gitlab.verifyStatus();\n const connections = await gitlab.statusConnections();\n const active = connections?.filter(connection => connection.status === 'active');\n const direct = connections === undefined;\n const endpointHost = typeof diagnostics.endpointHost === 'string' ? diagnostics.endpointHost : null;\n const accounts = direct\n ? endpointHost\n ? [endpointHost]\n : []\n : (active ?? []).flatMap(connection => (connection.accountLabel ? [connection.accountLabel] : []));\n const configured = direct || (active?.length ?? 0) > 0;\n return c.json({\n enabled: true,\n configured,\n mode: direct ? 'direct' : 'platform',\n ...(connections ? { connections } : {}),\n accounts,\n reauthRequired: connections?.some(connection => connection.status === 'needs_reauth') ?? false,\n reason: configured ? 'ready' : 'not_connected',\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/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 try {\n const sources = await gitlab.intake.listSources(resolved.tenant);\n if (intake) {\n const identity = await reconcileGitLabSourceIdentity({\n intake,\n orgId: resolved.tenant.orgId,\n sources,\n });\n if (identity.conflicts.length > 0) {\n return c.json(\n {\n error: 'gitlab_source_identity_conflict',\n message: 'Conflicting routes exist for the same GitLab project. Resolve the duplicate bindings.',\n conflicts: identity.conflicts,\n },\n 409,\n );\n }\n if (identity.migrations.length > 0) {\n await emitAudit?.({\n context: loose(c),\n input: {\n action: 'factory.intake.config_updated',\n targets: identity.migrations.map(migration => ({ type: 'intake_source', id: migration.to })),\n metadata: { provider: 'gitlab', migrated: identity.migrations.length },\n },\n });\n }\n }\n return c.json({\n projects: sources.flatMap(source => {\n const project = gitlabProjectPayload(source);\n return project ? [{ ...project, sandboxProvider: options.sandbox ? 'custom' : 'none' }] : [];\n }),\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/projects/registration', {\n method: 'POST',\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 input = (await c.req.json().catch(() => null)) as { sourceId?: unknown } | null;\n const sourceId = typeof input?.sourceId === 'string' ? input.sourceId.trim() : '';\n if (!sourceId) return c.json({ error: 'invalid_gitlab_source' }, 400);\n try {\n const source = (await gitlab.intake.listSources(resolved.tenant)).find(\n candidate => candidate.id === sourceId,\n );\n const project = source ? gitlabProjectPayload(source) : null;\n if (!project) return c.json({ error: 'gitlab_project_not_found' }, 404);\n const installation = await gitlab.versionControl.registerInstallation({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n installation: {\n externalId: project.connectionId,\n accountName: project.accountLabel ?? 'GitLab',\n accountType: 'GitLab',\n metadata: { connection: gitlabConnection(project.connectionId) },\n },\n });\n return c.json({\n project: {\n ...project,\n installationStorageId: installation.id,\n sandboxProvider: options.sandbox ? 'custom' : 'none',\n },\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/projects/:id/prs', {\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 factoryProjectId = c.req.query('factoryProjectId')?.trim();\n const page = positiveId(c.req.query('page') ?? '1');\n if (!factoryProjectId || !page) return c.json({ error: 'invalid_request' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId)\n return c.json({ error: 'factory_project_not_found' }, 404);\n const linked = await gitlab.getLinkedRepository({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n projectRepositoryId: c.req.param('id'),\n });\n if (!linked) return c.json({ error: 'project_repository_not_found' }, 404);\n const projectId = positiveId(linked.repository.externalId);\n if (!projectId) return c.json({ error: 'invalid_gitlab_project' }, 502);\n try {\n const target = await gitlab.versionControl.getRepositoryTarget({\n orgId: resolved.tenant.orgId,\n repositoryId: linked.repository.id,\n });\n const result = await gitlab.versionControl.listPullRequests({\n ...target,\n includeDrafts: false,\n cursor: String(page),\n });\n await ingestListedEvents(\n result.pullRequests.flatMap(pr =>\n listedMergeRequestEvents({ host: linked.host, projectId, projectPath: linked.repository.slug }, pr),\n ),\n options.ingestFactoryEvent,\n );\n return c.json({\n pullRequests: result.pullRequests.map(pr => ({\n number: Number(pr.id),\n externalId: mergeRequestSourceKey(linked.host, projectId, Number(pr.id)),\n title: pr.title,\n url: pr.url,\n author: pr.author,\n assignees: pr.assignees ?? [],\n requestedReviewers: pr.requestedReviewers ?? [],\n labels: pr.labels ?? [],\n baseBranch: pr.baseBranch,\n headBranch: pr.headBranch,\n createdAt: pr.createdAt,\n updatedAt: pr.updatedAt,\n })),\n nextPage: result.nextCursor === null ? null : Number(result.nextCursor),\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n registerApiRoute('/web/gitlab/projects/:id/prs/:number', {\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 factoryProjectId = c.req.query('factoryProjectId')?.trim();\n const number = positiveId(c.req.param('number'));\n if (!factoryProjectId || !number) return c.json({ error: 'invalid_request' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId)\n return c.json({ error: 'factory_project_not_found' }, 404);\n const linked = await gitlab.getLinkedRepository({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n projectRepositoryId: c.req.param('id'),\n });\n if (!linked) return c.json({ error: 'project_repository_not_found' }, 404);\n try {\n const target = await gitlab.versionControl.getRepositoryTarget({\n orgId: resolved.tenant.orgId,\n repositoryId: linked.repository.id,\n });\n const pr = await gitlab.versionControl.getPullRequest({ ...target, pullRequestId: String(number) });\n if (!pr) return c.json({ error: 'merge_request_not_found' }, 404);\n return c.json({\n number,\n title: pr.title,\n url: pr.url,\n author: pr.author,\n assignees: pr.assignees ?? [],\n requestedReviewers: pr.requestedReviewers ?? [],\n baseBranch: pr.baseBranch,\n headBranch: pr.headBranch,\n createdAt: pr.createdAt,\n updatedAt: pr.updatedAt,\n description: pr.body,\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n );\n }\n\n if (gitlab && auth && intake) {\n routes.push(\n registerApiRoute('/web/gitlab/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 const factoryProjectId = c.req.query('factoryProjectId')?.trim();\n if (!factoryProjectId) return c.json({ error: 'invalid_factory_project_id' }, 400);\n const board = c.req.query('board')?.trim();\n if (!board) return c.json({ error: 'invalid_board' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['gitlab'] });\n const selection = config.gitlab!;\n if (!selection.enabled) {\n return c.json(\n { error: 'gitlab_intake_disabled', message: 'GitLab intake is turned off in Settings.' },\n 404,\n );\n }\n const selected = new Set(selection.sourceIds ?? []);\n const sourceIds = [\n ...new Set(\n (await intake.listBindings({ orgId: resolved.tenant.orgId, integrationId: 'gitlab' }))\n .filter(\n binding =>\n binding.factoryProjectId === factoryProjectId &&\n binding.board === board &&\n selected.has(binding.sourceId),\n )\n .map(binding => binding.sourceId),\n ),\n ];\n if (sourceIds.length === 0) return c.json({ issues: [], nextCursor: null });\n\n try {\n const result = await gitlab.intake.listIssues({\n connection: { type: 'oauth', accessToken: 'gitlab-route' },\n sourceIds,\n cursor: c.req.query('after')?.trim() || undefined,\n });\n await ingestListedEvents(result.issues.map(listedIssueEvent), options.ingestFactoryEvent);\n return c.json({\n ...result,\n issues: result.issues.map(issue => {\n const source = decodeSourceId(issue.sourceId ?? '');\n const issueIid = Number(issue.id);\n if (!source || !Number.isSafeInteger(issueIid) || issueIid <= 0) {\n throw new Error('GitLab returned an invalid routed issue reference.');\n }\n return { ...issue, externalId: encodeIssueReference({ ...source, issueIid }) };\n }),\n });\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/gitlab/issues/:issueId', {\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 factoryProjectId = c.req.query('factoryProjectId')?.trim();\n if (!factoryProjectId) return c.json({ error: 'invalid_factory_project_id' }, 400);\n if ((await gitlab.resolveOrgId(factoryProjectId)) !== resolved.tenant.orgId) {\n return c.json({ error: 'factory_project_not_found' }, 404);\n }\n const issueId = c.req.param('issueId')?.trim();\n const issueReference = issueId ? decodeIssueReference(issueId) : null;\n if (!issueReference) return c.json({ error: 'invalid_gitlab_issue_id' }, 400);\n\n const { host, connectionId, projectId, projectPath } = issueReference;\n const sourceId = host\n ? encodeSourceId({ host, projectId })\n : encodeSourceId({ connectionId, projectId, projectPath });\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['gitlab'] });\n const selection = config.gitlab!;\n const selected = new Set(selection.sourceIds ?? []);\n const routed =\n selection.enabled &&\n selected.has(sourceId) &&\n (await intake.listBindings({ orgId: resolved.tenant.orgId, integrationId: 'gitlab' })).some(\n binding => binding.factoryProjectId === factoryProjectId && binding.sourceId === sourceId,\n );\n if (!routed) return c.json({ error: 'gitlab_issue_not_routed' }, 404);\n\n try {\n const issue = await gitlab.intake.getIssue({\n connection: { type: 'oauth', accessToken: 'gitlab-route' },\n issueId,\n });\n if (!issue) return c.json({ error: 'gitlab_issue_not_found' }, 404);\n return c.json(issue);\n } catch (error) {\n return gitlabFetchError(loose(c), error);\n }\n },\n }),\n );\n }\n\n if (gitlab && auth) {\n routes.push(\n registerApiRoute('/web/gitlab/subscriptions', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant?.orgId) return c.json({ error: 'unauthorized' }, 401);\n\n // Sessions read by session id; resourceId is the older address.\n const sessionId = c.req.query('sessionId');\n const resourceId = c.req.query('resourceId');\n const threadId = c.req.query('threadId');\n const target = !threadId\n ? null\n : sessionId\n ? { orgId: tenant.orgId, sessionId, threadId }\n : resourceId\n ? { orgId: tenant.orgId, resourceId, threadId }\n : null;\n if (!target) return c.json({ error: 'sessionId (or resourceId) and threadId are required' }, 400);\n\n const subscriptions = await listMergeRequestSubscriptionsForThread(target, gitlab.integrationStorage);\n return c.json({\n subscriptions: subscriptions.map(subscription => ({\n id: subscription.id,\n repoFullName: subscription.data.projectPath,\n pullRequestNumber: Number(subscription.data.changeRequestId),\n status: subscription.status,\n url: mergeRequestUrl(\n subscription.data.host,\n subscription.data.projectPath,\n subscription.data.changeRequestId,\n ),\n })),\n });\n },\n }),\n );\n }\n\n routes.push(\n registerApiRoute('/web/gitlab/webhook', {\n method: 'POST',\n requiresAuth: false,\n handler: async c => {\n const result = await handleGitLabWebhook(loose(c), {\n webhookSecret: options.webhookSecret,\n ingestFactoryEvent: options.ingestFactoryEvent,\n ...(options.controller && gitlab\n ? {\n controller: options.controller,\n gitlab,\n onTargetError: (subscription, error) => {\n console.warn(\n `[GitLab Webhook] Delivery failed for subscription ${subscription.id} (${subscription.resourceId}/${subscription.threadId}).`,\n error,\n );\n },\n }\n : {}),\n });\n return c.json(result.body, result.status);\n },\n }),\n );\n return routes;\n}\n"],"mappings":";;;;;;;;AAsCA,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;EAAgB,QAAQ;CAAgB,GAAG,GAAG,EAAE;CAChG,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,iBAAiB,GAAiB,OAAgB;CACzD,IAAI,iBAAiB,kBAAkB,MAAM,SAAS,sBACpD,OAAO,EAAE,KAAK;EAAE,OAAO;EAAsB,SAAS,MAAM;CAAQ,GAAG,GAAG;CAE5E,OAAO,EAAE,KAAK;EAAE,OAAO;EAAuB,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;CAAE,GAAG,GAAG;AACtH;AAIA,SAAS,qBAAqB,QAA0E;CACtG,MAAM,eAAe,OAAO,OAAO,UAAU,iBAAiB,WAAW,OAAO,SAAS,eAAe;CACxG,MAAM,YAAY,OAAO,OAAO,UAAU,cAAc,WAAW,OAAO,SAAS,YAAY;CAC/F,MAAM,cAAc,OAAO,OAAO,UAAU,gBAAgB,WAAW,OAAO,SAAS,cAAc,OAAO;CAC5G,IAAI,CAAC,gBAAgB,CAAC,WAAW,OAAO;CACxC,MAAM,iBAAiB,YAAY,MAAM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Ac,aAAa,KAAK;IAChC,mBAAmB,OAAO,aAAa,KAAK,eAAe;IAC3D,QAAQ,aAAa;IACrB,KAAK,gBACH,aAAa,KAAK,MAClB,aAAa,KAAK,aAClB,aAAa,KAAK,eACpB;GACF,EAAE,EACJ,CAAC;EACH;CACF,CAAC,CACH;CAGF,OAAO,KACL,iBAAiB,uBAAuB;EACtC,QAAQ;EACR,cAAc;EACd,SAAS,OAAM,MAAK;GAClB,MAAM,SAAS,MAAM,oBAAoB,MAAM,CAAC,GAAG;IACjD,eAAe,QAAQ;IACvB,oBAAoB,QAAQ;IAC5B,GAAI,QAAQ,cAAc,SACtB;KACE,YAAY,QAAQ;KACpB;KACA,gBAAgB,cAAc,UAAU;MACtC,QAAQ,KACN,qDAAqD,aAAa,GAAG,IAAI,aAAa,WAAW,GAAG,aAAa,SAAS,KAC1H,KACF;KACF;IACF,IACA,CAAC;GACP,CAAC;GACD,OAAO,EAAE,KAAK,OAAO,MAAM,OAAO,MAAM;EAC1C;CACF,CAAC,CACH;CACA,OAAO;AACT"}
@@ -1,4 +1,6 @@
1
+ import type { BoardEventFacts } from '../../boards/board-events.js';
1
2
  import type { BoardRegistry } from '../../boards/index.js';
3
+ import type { FactoryGitLabRuleContext, FactorySignalActivityDecision } from '../../rules/types.js';
2
4
  import type { IntakeStorage } from '../../storage/domains/intake/base.js';
3
5
  import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
4
6
  import type { SourceControlStorageHandle } from '../../storage/domains/source-control/base.js';
@@ -7,6 +9,20 @@ import type { IntegrationContext } from '../base.js';
7
9
  import type { GitLabEventRules } from './default-rules.js';
8
10
  import type { ParsedGitLabWebhook } from './webhook.js';
9
11
  type IngressStatus = 'ignored' | 'committed' | 'replayed' | 'missing';
12
+ /**
13
+ * Points the card's session at a new comment on its issue, or at an edit to
14
+ * the issue's title or description. Only pointers travel (who, where, a link).
15
+ * An edited comment (a Note Hook with action `update`, GitLab 16.11+) is no new comment.
16
+ * GitLab deliveries don't say whether Factory wrote the comment, so the
17
+ * message waits in the session's notifications instead of waking it: a session
18
+ * that comments must not wake itself.
19
+ */
20
+ export declare function activitySignalFor(context: Pick<FactoryGitLabRuleContext, 'event' | 'item' | 'actor' | 'ingress' | 'repository' | 'issue' | 'note'>, delivery: {
21
+ edited: boolean;
22
+ noteEdited: boolean;
23
+ }): FactorySignalActivityDecision | undefined;
24
+ /** The status change a GitLab delivery reports. GitLab gives no close reason, so every close is completed. */
25
+ export declare function boardEventFor(context: Pick<FactoryGitLabRuleContext, 'event'>): BoardEventFacts | undefined;
10
26
  export interface GitLabRulesIntegration {
11
27
  readonly rules: GitLabEventRules;
12
28
  resolveActiveConnectionForHost?(storedConnectionId: string, host: string): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/gitlab/rules.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAS3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAEV,0BAA0B,EAC3B,MAAM,8CAA8C,CAAC;AAEtD,OAAO,KAAK,EAAQ,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE3D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAIxD,KAAK,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,UAAU,GAAG,SAAS,CAAC;AAoHtE,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,KAAK,EAAE,gBAAgB,CAAC;IACjC,8BAA8B,CAAC,CAAC,kBAAkB,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,G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S,CAAC,CAAC;IACpH,yBAAyB,CACvB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,OAAO,GAAG,eAAe,EAC/B,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CAChC;AAED,UAAU,kBAAkB;IAC1B,MAAM,EAAE,sBAAsB,CAAC;IAC/B,aAAa,EAAE,0BAA0B,CAAC;IAC1C,QAAQ,EAAE,sBAAsB,CAAC;IACjC,OAAO,EAAE,gBAAgB,CAAC;IAC1B,MAAM,EAAE,aAAa,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,aAAa,CAAC;CACvB;AAOD,qBAAa,WAAW;;IACV,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,kBAAkB,EAAI;IAEtD,MAAM,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAA;KAAE,CAAC,CAkB5E;CAsjBF;AAED,wBAAgB,iBAAiB,CAC/B,MAAM,EAAE,sBAAsB,EAC9B,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAYhE"}
@@ -1,6 +1,7 @@
1
+ import { closeReason } from "../../boards/board-events.js";
1
2
  import "../../boards/index.js";
2
- import { hasExplicitRuleOverride, selectEventRule } from "../../rules/event-rules.js";
3
3
  import { boardEventHandlers, boardForWorkItem, eventBoardId, rulePhaseField, withBoardClosure } from "../../boards/semantics.js";
4
+ import { deploymentOwnsEvent, hasExplicitRuleOverride, routeEventDecision, selectEventRule, withoutRouteEvent } from "../../rules/event-rules.js";
4
5
  import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "../../rules/validation.js";
5
6
  import { WorkItemUpdateConflictError } from "../../storage/domains/work-items/base.js";
6
7
  import { recordPullRequestHead } from "../pull-request-head.js";
@@ -51,11 +52,47 @@ function labelColors(value) {
51
52
  return name && color ? [[name, color]] : [];
52
53
  }));
53
54
  }
55
+ /**
56
+ * Points the card's session at a new comment on its issue, or at an edit to
57
+ * the issue's title or description. Only pointers travel (who, where, a link).
58
+ * An edited comment (a Note Hook with action `update`, GitLab 16.11+) is no new comment.
59
+ * GitLab deliveries don't say whether Factory wrote the comment, so the
60
+ * message waits in the session's notifications instead of waking it: a session
61
+ * that comments must not wake itself.
62
+ */
63
+ function activitySignalFor(context, delivery) {
64
+ const event = context.event === "issueCommented" && !delivery.noteEdited ? "work_item.commented" : context.event === "issueUpdated" && delivery.edited ? "work_item.edited" : void 0;
65
+ if (!event || !context.item || !context.issue) return void 0;
66
+ if (context.actor.type !== "gitlab" || context.actor.factoryAuthored) return void 0;
67
+ return {
68
+ type: "signalActivity",
69
+ idempotencyKey: `${context.ingress.id}:activity`,
70
+ event,
71
+ reference: `${context.repository.fullName}#${context.issue.number}`,
72
+ url: (event === "work_item.commented" ? context.note?.url : void 0) ?? context.issue.url,
73
+ ...context.actor.username ? { author: context.actor.username } : {},
74
+ authorTrusted: context.actor.trusted,
75
+ idleBehavior: "persist"
76
+ };
77
+ }
78
+ /** The status change a GitLab delivery reports. GitLab gives no close reason, so every close is completed. */
79
+ function boardEventFor(context) {
80
+ switch (context.event) {
81
+ case "issueOpened": return { type: "work_item.created" };
82
+ case "issueReopened": return { type: "work_item.reopened" };
83
+ case "issueClosed": return {
84
+ type: "work_item.closed",
85
+ reason: closeReason(false)
86
+ };
87
+ default: return;
88
+ }
89
+ }
54
90
  function eventName(parsed) {
55
91
  const attributes = object(parsed.payload.object_attributes);
56
92
  const action = string(attributes?.action)?.toLowerCase();
57
93
  if (parsed.event === "Issue Hook") {
58
- if (action === "open" || action === "reopen") return "issueOpened";
94
+ if (action === "open") return "issueOpened";
95
+ if (action === "reopen") return "issueReopened";
59
96
  if (action === "close") return "issueClosed";
60
97
  return "issueUpdated";
61
98
  }
@@ -186,6 +223,19 @@ var GitLabRules = class {
186
223
  issueIid
187
224
  }) : void 0;
188
225
  const mergeRequestKey = mergeRequestIid ? mergeRequestSourceKey(host, projectId, mergeRequestIid) : void 0;
226
+ await this.options.storage.copyLegacyCards({
227
+ orgId: target.target.orgId,
228
+ factoryProjectId: target.target.factoryProjectId,
229
+ sources: [...issueSourceKey ? [{
230
+ integrationId: "gitlab",
231
+ type: "issue",
232
+ externalId: issueSourceKey
233
+ }] : [], ...mergeRequestKey ? [{
234
+ integrationId: "gitlab",
235
+ type: "pull-request",
236
+ externalId: mergeRequestKey
237
+ }] : []]
238
+ });
189
239
  const items = await this.options.storage.list({
190
240
  orgId: target.target.orgId,
191
241
  factoryProjectId: target.target.factoryProjectId
@@ -438,10 +488,13 @@ var GitLabRules = class {
438
488
  baseBranch: string(input.mergeRequest?.target_branch) ?? ""
439
489
  } } : {}
440
490
  };
491
+ const boardEvent = boardEventFor(context);
492
+ if (boardEvent) context.boardEvent = boardEvent;
441
493
  const boardRules = boardEventHandlers(this.options.boards, input.mergeRequestOpenedScope === "intake" ? void 0 : eventBoardId(context), "gitlab");
442
494
  const rule = input.mergeRequestOpenedScope === "board" ? hasExplicitRuleOverride(this.options.gitlab.rules, input.event) ? void 0 : boardRules?.mergeRequestOpened : selectEventRule(this.options.gitlab.rules, boardRules, input.event);
443
495
  if (input.mergeRequestOpenedScope === "board" && !rule) return { status: "ignored" };
444
- let decision;
496
+ const ownedByDeployment = deploymentOwnsEvent(this.options.gitlab.rules, boardRules, input.event);
497
+ let decision = void 0;
445
498
  let decisions = [];
446
499
  let outcome = { status: "accepted" };
447
500
  try {
@@ -463,6 +516,18 @@ var GitLabRules = class {
463
516
  reason: timedOut ? "Factory rule evaluation timed out." : error instanceof Error ? error.message.slice(0, 2e3) : "Factory GitLab rule failed."
464
517
  };
465
518
  }
519
+ if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);
520
+ if (!decision && !ownedByDeployment && outcome.status === "accepted") {
521
+ const changes = object(input.parsed.payload.changes);
522
+ const routed = await routeEventDecision(context, this.options.storage, {
523
+ orgId: input.orgId,
524
+ factoryProjectId: input.factoryProjectId
525
+ }) ?? activitySignalFor(context, {
526
+ edited: Boolean(object(changes?.title) || object(changes?.description)),
527
+ noteEdited: string(object(input.parsed.payload.object_attributes)?.action)?.toLowerCase() === "update"
528
+ });
529
+ if (routed) decisions = [{ ...routed }];
530
+ }
466
531
  const committed = await this.options.storage.commitRuleEvaluation({
467
532
  orgId: input.orgId,
468
533
  factoryProjectId: input.factoryProjectId,
@@ -507,6 +572,6 @@ function attachGitLabRules(gitlab, context) {
507
572
  });
508
573
  return (event) => rules.ingest(event);
509
574
  }
510
- export { GitLabRules, attachGitLabRules };
575
+ export { GitLabRules, activitySignalFor, attachGitLabRules, boardEventFor };
511
576
 
512
577
  //# sourceMappingURL=rules.js.map