@mastra/factory 0.28.0 → 0.29.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (407) hide show
  1. package/README.md +26 -8
  2. package/dist/board-changes.d.ts +16 -0
  3. package/dist/board-changes.d.ts.map +1 -0
  4. package/dist/board-changes.js +40 -0
  5. package/dist/board-changes.js.map +1 -0
  6. package/dist/boards/index.js +2 -1
  7. package/dist/boards/reroute.d.ts +31 -0
  8. package/dist/boards/reroute.d.ts.map +1 -0
  9. package/dist/boards/reroute.js +71 -0
  10. package/dist/boards/reroute.js.map +1 -0
  11. package/dist/boards/semantics.d.ts +1 -3
  12. package/dist/boards/semantics.d.ts.map +1 -1
  13. package/dist/boards/semantics.js +1 -5
  14. package/dist/boards/semantics.js.map +1 -1
  15. package/dist/environment/repository-access.d.ts +2 -0
  16. package/dist/environment/repository-access.d.ts.map +1 -1
  17. package/dist/environment/repository-access.js +9 -4
  18. package/dist/environment/repository-access.js.map +1 -1
  19. package/dist/factory.d.ts +4 -0
  20. package/dist/factory.d.ts.map +1 -1
  21. package/dist/factory.js +60 -9
  22. package/dist/factory.js.map +1 -1
  23. package/dist/integrations/base.d.ts +17 -0
  24. package/dist/integrations/base.d.ts.map +1 -1
  25. package/dist/integrations/dependabot/default-rules.d.ts +38 -0
  26. package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
  27. package/dist/integrations/dependabot/default-rules.js +63 -0
  28. package/dist/integrations/dependabot/default-rules.js.map +1 -0
  29. package/dist/integrations/dependabot/rules.d.ts +42 -0
  30. package/dist/integrations/dependabot/rules.d.ts.map +1 -0
  31. package/dist/integrations/dependabot/rules.js +187 -0
  32. package/dist/integrations/dependabot/rules.js.map +1 -0
  33. package/dist/integrations/dependabot/sync.d.ts +76 -0
  34. package/dist/integrations/dependabot/sync.d.ts.map +1 -0
  35. package/dist/integrations/dependabot/sync.js +111 -0
  36. package/dist/integrations/dependabot/sync.js.map +1 -0
  37. package/dist/integrations/github/pull-request-source.js +2 -1
  38. package/dist/integrations/github/pull-request-source.js.map +1 -1
  39. package/dist/integrations/github/reconcile-worker.js +1 -1
  40. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  41. package/dist/integrations/github/routes.d.ts.map +1 -1
  42. package/dist/integrations/github/routes.js +7 -2
  43. package/dist/integrations/github/routes.js.map +1 -1
  44. package/dist/integrations/github/rules.d.ts +5 -2
  45. package/dist/integrations/github/rules.d.ts.map +1 -1
  46. package/dist/integrations/github/rules.js +16 -13
  47. package/dist/integrations/github/rules.js.map +1 -1
  48. package/dist/integrations/github/sandbox.d.ts +12 -0
  49. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  50. package/dist/integrations/github/sandbox.js +24 -3
  51. package/dist/integrations/github/sandbox.js.map +1 -1
  52. package/dist/integrations/gitlab/default-rules.js +2 -1
  53. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  54. package/dist/integrations/gitlab/discovery.d.ts +16 -0
  55. package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
  56. package/dist/integrations/gitlab/discovery.js +107 -0
  57. package/dist/integrations/gitlab/discovery.js.map +1 -0
  58. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  59. package/dist/integrations/gitlab/integration.js +1 -2
  60. package/dist/integrations/gitlab/integration.js.map +1 -1
  61. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  62. package/dist/integrations/gitlab/issue-reconciler.js +1 -0
  63. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  64. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  65. package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
  66. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  67. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  68. package/dist/integrations/gitlab/reconciler.js +4 -2
  69. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  70. package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
  71. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  72. package/dist/integrations/gitlab/reconciliation-config.js +2 -8
  73. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  74. package/dist/integrations/gitlab/routes.d.ts +17 -0
  75. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  76. package/dist/integrations/gitlab/routes.js +28 -22
  77. package/dist/integrations/gitlab/routes.js.map +1 -1
  78. package/dist/integrations/gitlab/rules.d.ts +10 -4
  79. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  80. package/dist/integrations/gitlab/rules.js +32 -8
  81. package/dist/integrations/gitlab/rules.js.map +1 -1
  82. package/dist/integrations/incidentio/integration.d.ts +2 -1
  83. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  84. package/dist/integrations/incidentio/integration.js +7 -7
  85. package/dist/integrations/incidentio/integration.js.map +1 -1
  86. package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
  87. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/issue-reconciler.js +36 -1
  89. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  90. package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
  91. package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
  92. package/dist/integrations/incidentio/reconciliation-config.js +2 -5
  93. package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
  94. package/dist/integrations/incidentio/routes.d.ts +24 -8
  95. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  96. package/dist/integrations/incidentio/routes.js +33 -35
  97. package/dist/integrations/incidentio/routes.js.map +1 -1
  98. package/dist/integrations/incidentio/rules.d.ts +0 -4
  99. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  100. package/dist/integrations/incidentio/rules.js +17 -14
  101. package/dist/integrations/incidentio/rules.js.map +1 -1
  102. package/dist/integrations/intake-discovery.d.ts +44 -0
  103. package/dist/integrations/intake-discovery.d.ts.map +1 -0
  104. package/dist/integrations/intake-discovery.js +60 -0
  105. package/dist/integrations/intake-discovery.js.map +1 -0
  106. package/dist/integrations/issue-reconcile-worker.js +1 -1
  107. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  108. package/dist/integrations/issue-reconciler.d.ts +7 -0
  109. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  110. package/dist/integrations/issue-reconciler.js +47 -12
  111. package/dist/integrations/issue-reconciler.js.map +1 -1
  112. package/dist/integrations/jira/integration.d.ts +3 -2
  113. package/dist/integrations/jira/integration.d.ts.map +1 -1
  114. package/dist/integrations/jira/integration.js +5 -7
  115. package/dist/integrations/jira/integration.js.map +1 -1
  116. package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
  117. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  118. package/dist/integrations/jira/issue-reconciler.js +34 -1
  119. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  120. package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
  121. package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
  122. package/dist/integrations/jira/reconciliation-config.js +2 -5
  123. package/dist/integrations/jira/reconciliation-config.js.map +1 -1
  124. package/dist/integrations/jira/routes.d.ts +0 -7
  125. package/dist/integrations/jira/routes.d.ts.map +1 -1
  126. package/dist/integrations/jira/routes.js +2 -12
  127. package/dist/integrations/jira/routes.js.map +1 -1
  128. package/dist/integrations/jira/rules.d.ts +0 -4
  129. package/dist/integrations/jira/rules.d.ts.map +1 -1
  130. package/dist/integrations/jira/rules.js +3 -13
  131. package/dist/integrations/jira/rules.js.map +1 -1
  132. package/dist/integrations/kept-cards.d.ts +49 -0
  133. package/dist/integrations/kept-cards.d.ts.map +1 -0
  134. package/dist/integrations/kept-cards.js +97 -0
  135. package/dist/integrations/kept-cards.js.map +1 -0
  136. package/dist/integrations/linear/intake-discovery.d.ts +34 -0
  137. package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
  138. package/dist/integrations/linear/intake-discovery.js +112 -0
  139. package/dist/integrations/linear/intake-discovery.js.map +1 -0
  140. package/dist/integrations/linear/integration.d.ts.map +1 -1
  141. package/dist/integrations/linear/integration.js +1 -4
  142. package/dist/integrations/linear/integration.js.map +1 -1
  143. package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
  144. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  145. package/dist/integrations/linear/issue-reconciler.js +24 -20
  146. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  147. package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
  148. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  149. package/dist/integrations/linear/reconciliation-config.js +2 -8
  150. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  151. package/dist/integrations/linear/routes.d.ts +0 -2
  152. package/dist/integrations/linear/routes.d.ts.map +1 -1
  153. package/dist/integrations/linear/routes.js +3 -9
  154. package/dist/integrations/linear/routes.js.map +1 -1
  155. package/dist/integrations/platform/api-client.d.ts +2 -0
  156. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  157. package/dist/integrations/platform/api-client.js +6 -1
  158. package/dist/integrations/platform/api-client.js.map +1 -1
  159. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  160. package/dist/integrations/platform/connect/routes.js +8 -1
  161. package/dist/integrations/platform/connect/routes.js.map +1 -1
  162. package/dist/integrations/platform/github/event-worker.d.ts +17 -0
  163. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  164. package/dist/integrations/platform/github/event-worker.js +89 -7
  165. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  166. package/dist/integrations/platform/github/integration.d.ts +20 -1
  167. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  168. package/dist/integrations/platform/github/integration.js +54 -3
  169. package/dist/integrations/platform/github/integration.js.map +1 -1
  170. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  171. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  172. package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
  173. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  174. package/dist/integrations/platform/incidentio/integration.js +7 -7
  175. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  176. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  177. package/dist/integrations/platform/jira/integration.js +4 -7
  178. package/dist/integrations/platform/jira/integration.js.map +1 -1
  179. package/dist/integrations/platform/jira/routes.d.ts +0 -7
  180. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  181. package/dist/integrations/platform/jira/routes.js +2 -12
  182. package/dist/integrations/platform/jira/routes.js.map +1 -1
  183. package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
  184. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  185. package/dist/integrations/platform/linear/event-worker.js +1 -1
  186. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  187. package/dist/integrations/platform/linear/integration.d.ts +1 -0
  188. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  189. package/dist/integrations/platform/linear/integration.js +7 -7
  190. package/dist/integrations/platform/linear/integration.js.map +1 -1
  191. package/dist/integrations/platform/vanta/integration.d.ts +38 -0
  192. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
  193. package/dist/integrations/platform/vanta/integration.js +149 -0
  194. package/dist/integrations/platform/vanta/integration.js.map +1 -0
  195. package/dist/integrations/reconciliation-config.d.ts +0 -1
  196. package/dist/integrations/reconciliation-config.d.ts.map +1 -1
  197. package/dist/integrations/reconciliation-config.js +1 -8
  198. package/dist/integrations/reconciliation-config.js.map +1 -1
  199. package/dist/integrations/slack/channel-reply-processor.js +1 -1
  200. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  201. package/dist/integrations/startup-summary.d.ts +8 -0
  202. package/dist/integrations/startup-summary.d.ts.map +1 -0
  203. package/dist/integrations/startup-summary.js +36 -0
  204. package/dist/integrations/startup-summary.js.map +1 -0
  205. package/dist/integrations/vanta/default-rules.d.ts +34 -0
  206. package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
  207. package/dist/integrations/vanta/default-rules.js +61 -0
  208. package/dist/integrations/vanta/default-rules.js.map +1 -0
  209. package/dist/integrations/vanta/rules.d.ts +40 -0
  210. package/dist/integrations/vanta/rules.d.ts.map +1 -0
  211. package/dist/integrations/vanta/rules.js +208 -0
  212. package/dist/integrations/vanta/rules.js.map +1 -0
  213. package/dist/integrations/vanta/sync.d.ts +40 -0
  214. package/dist/integrations/vanta/sync.d.ts.map +1 -0
  215. package/dist/integrations/vanta/sync.js +81 -0
  216. package/dist/integrations/vanta/sync.js.map +1 -0
  217. package/dist/linked-repositories-changed.d.ts +14 -0
  218. package/dist/linked-repositories-changed.d.ts.map +1 -0
  219. package/dist/linked-repositories-changed.js +48 -0
  220. package/dist/linked-repositories-changed.js.map +1 -0
  221. package/dist/mcp/routes.d.ts.map +1 -1
  222. package/dist/mcp/routes.js +1 -1
  223. package/dist/mcp/routes.js.map +1 -1
  224. package/dist/routes/board-snapshot.d.ts +8 -1
  225. package/dist/routes/board-snapshot.d.ts.map +1 -1
  226. package/dist/routes/board-snapshot.js +23 -2
  227. package/dist/routes/board-snapshot.js.map +1 -1
  228. package/dist/routes/contracts.d.ts +322 -0
  229. package/dist/routes/contracts.d.ts.map +1 -1
  230. package/dist/routes/contracts.js +202 -5
  231. package/dist/routes/contracts.js.map +1 -1
  232. package/dist/routes/intake-routes.d.ts +3 -0
  233. package/dist/routes/intake-routes.d.ts.map +1 -1
  234. package/dist/routes/intake-routes.js +44 -0
  235. package/dist/routes/intake-routes.js.map +1 -1
  236. package/dist/routes/knowledge.d.ts.map +1 -1
  237. package/dist/routes/knowledge.js +3 -2
  238. package/dist/routes/knowledge.js.map +1 -1
  239. package/dist/routes/run-queue.d.ts +17 -0
  240. package/dist/routes/run-queue.d.ts.map +1 -0
  241. package/dist/routes/run-queue.js +69 -0
  242. package/dist/routes/run-queue.js.map +1 -0
  243. package/dist/routes/source-control-sessions.d.ts +1 -1
  244. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  245. package/dist/routes/source-control-sessions.js +109 -3
  246. package/dist/routes/source-control-sessions.js.map +1 -1
  247. package/dist/routes/surface.d.ts +14 -1
  248. package/dist/routes/surface.d.ts.map +1 -1
  249. package/dist/routes/surface.js +76 -11
  250. package/dist/routes/surface.js.map +1 -1
  251. package/dist/routes/work-item-selection.d.ts +4 -5
  252. package/dist/routes/work-item-selection.d.ts.map +1 -1
  253. package/dist/routes/work-item-selection.js +11 -23
  254. package/dist/routes/work-item-selection.js.map +1 -1
  255. package/dist/routes/work-item-starters.d.ts.map +1 -1
  256. package/dist/routes/work-item-starters.js +4 -21
  257. package/dist/routes/work-item-starters.js.map +1 -1
  258. package/dist/routes/work-items.d.ts +5 -0
  259. package/dist/routes/work-items.d.ts.map +1 -1
  260. package/dist/routes/work-items.js +129 -36
  261. package/dist/routes/work-items.js.map +1 -1
  262. package/dist/rules/dispatch-errors.d.ts +3 -0
  263. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  264. package/dist/rules/dispatch-errors.js +5 -0
  265. package/dist/rules/dispatch-errors.js.map +1 -1
  266. package/dist/rules/dispatcher.d.ts +15 -1
  267. package/dist/rules/dispatcher.d.ts.map +1 -1
  268. package/dist/rules/dispatcher.js +48 -20
  269. package/dist/rules/dispatcher.js.map +1 -1
  270. package/dist/rules/index.d.ts +2 -2
  271. package/dist/rules/index.d.ts.map +1 -1
  272. package/dist/rules/index.js +2 -2
  273. package/dist/rules/review-source-tool.js +2 -1
  274. package/dist/rules/review-source-tool.js.map +1 -1
  275. package/dist/rules/start-coordinator.d.ts +6 -1
  276. package/dist/rules/start-coordinator.d.ts.map +1 -1
  277. package/dist/rules/start-coordinator.js +6 -2
  278. package/dist/rules/start-coordinator.js.map +1 -1
  279. package/dist/rules/transition-service.d.ts.map +1 -1
  280. package/dist/rules/transition-service.js +3 -2
  281. package/dist/rules/transition-service.js.map +1 -1
  282. package/dist/rules/types.d.ts +71 -3
  283. package/dist/rules/types.d.ts.map +1 -1
  284. package/dist/rules/types.js +10 -2
  285. package/dist/rules/types.js.map +1 -1
  286. package/dist/rules/validation.d.ts.map +1 -1
  287. package/dist/rules/validation.js +5 -0
  288. package/dist/rules/validation.js.map +1 -1
  289. package/dist/session/factory-session.d.ts +20 -5
  290. package/dist/session/factory-session.d.ts.map +1 -1
  291. package/dist/session/factory-session.js +20 -6
  292. package/dist/session/factory-session.js.map +1 -1
  293. package/dist/storage/domains/audit/actions.d.ts +1 -1
  294. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  295. package/dist/storage/domains/audit/actions.js +2 -1
  296. package/dist/storage/domains/audit/actions.js.map +1 -1
  297. package/dist/storage/domains/audit/actors.d.ts.map +1 -1
  298. package/dist/storage/domains/audit/actors.js +1 -1
  299. package/dist/storage/domains/audit/actors.js.map +1 -1
  300. package/dist/storage/domains/intake/base.d.ts +1 -1
  301. package/dist/storage/domains/intake/base.js +2 -2
  302. package/dist/storage/domains/intake/base.js.map +1 -1
  303. package/dist/storage/domains/projects/base.d.ts +10 -0
  304. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  305. package/dist/storage/domains/projects/base.js +24 -2
  306. package/dist/storage/domains/projects/base.js.map +1 -1
  307. package/dist/storage/domains/source-control/base.d.ts +32 -0
  308. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  309. package/dist/storage/domains/source-control/base.js +54 -4
  310. package/dist/storage/domains/source-control/base.js.map +1 -1
  311. package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
  312. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  313. package/dist/storage/domains/source-control/inmemory.js +17 -0
  314. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  315. package/dist/storage/domains/work-items/base.d.ts +16 -4
  316. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  317. package/dist/storage/domains/work-items/base.js +28 -1
  318. package/dist/storage/domains/work-items/base.js.map +1 -1
  319. package/dist/timing.d.ts +8 -1
  320. package/dist/timing.d.ts.map +1 -1
  321. package/dist/timing.js +10 -2
  322. package/dist/timing.js.map +1 -1
  323. package/dist/tools/approval-tools.d.ts +20 -0
  324. package/dist/tools/approval-tools.d.ts.map +1 -1
  325. package/dist/tools/approval-tools.js +79 -30
  326. package/dist/tools/approval-tools.js.map +1 -1
  327. package/dist/tools/audit-events-tool.d.ts +1 -1
  328. package/dist/tools/messaging-tools.d.ts.map +1 -1
  329. package/dist/tools/messaging-tools.js +1 -1
  330. package/dist/tools/messaging-tools.js.map +1 -1
  331. package/dist/tools/read-tools.d.ts +0 -2
  332. package/dist/tools/read-tools.d.ts.map +1 -1
  333. package/dist/tools/read-tools.js +2 -7
  334. package/dist/tools/read-tools.js.map +1 -1
  335. package/dist/tools/reports.d.ts +3 -0
  336. package/dist/tools/reports.d.ts.map +1 -1
  337. package/dist/tools/reports.js +3 -3
  338. package/dist/tools/reports.js.map +1 -1
  339. package/dist/tools/run-watch.d.ts +14 -2
  340. package/dist/tools/run-watch.d.ts.map +1 -1
  341. package/dist/tools/run-watch.js +24 -4
  342. package/dist/tools/run-watch.js.map +1 -1
  343. package/dist/tools/session-tools.d.ts.map +1 -1
  344. package/dist/tools/session-tools.js +17 -6
  345. package/dist/tools/session-tools.js.map +1 -1
  346. package/dist/tools/side-sessions.d.ts.map +1 -1
  347. package/dist/tools/side-sessions.js +1 -1
  348. package/dist/tools/side-sessions.js.map +1 -1
  349. package/dist/tools/work-item-tools.d.ts.map +1 -1
  350. package/dist/tools/work-item-tools.js +12 -2
  351. package/dist/tools/work-item-tools.js.map +1 -1
  352. package/dist/work-item-branch.d.ts +1 -1
  353. package/dist/work-item-branch.d.ts.map +1 -1
  354. package/dist/work-item-branch.js +2 -0
  355. package/dist/work-item-branch.js.map +1 -1
  356. package/dist/work-items/board-filter-options.d.ts +5 -0
  357. package/dist/work-items/board-filter-options.d.ts.map +1 -0
  358. package/dist/work-items/board-filter-options.js +27 -0
  359. package/dist/work-items/board-filter-options.js.map +1 -0
  360. package/dist/work-items/board-phases.d.ts +28 -0
  361. package/dist/work-items/board-phases.d.ts.map +1 -0
  362. package/dist/work-items/board-phases.js +165 -0
  363. package/dist/work-items/board-phases.js.map +1 -0
  364. package/dist/work-items/card-facts.d.ts +24 -0
  365. package/dist/work-items/card-facts.d.ts.map +1 -0
  366. package/dist/work-items/card-facts.js +75 -0
  367. package/dist/work-items/card-facts.js.map +1 -0
  368. package/dist/work-items/card-labels.d.ts +5 -0
  369. package/dist/work-items/card-labels.d.ts.map +1 -0
  370. package/dist/work-items/card-labels.js +13 -0
  371. package/dist/work-items/card-labels.js.map +1 -0
  372. package/dist/work-items/card-number.d.ts +10 -0
  373. package/dist/work-items/card-number.d.ts.map +1 -0
  374. package/dist/work-items/card-number.js +15 -0
  375. package/dist/work-items/card-number.js.map +1 -0
  376. package/dist/work-items/card-people.d.ts +25 -0
  377. package/dist/work-items/card-people.d.ts.map +1 -0
  378. package/dist/work-items/card-people.js +100 -0
  379. package/dist/work-items/card-people.js.map +1 -0
  380. package/dist/work-items/card-search-text.d.ts +4 -0
  381. package/dist/work-items/card-search-text.d.ts.map +1 -0
  382. package/dist/work-items/card-search-text.js +15 -0
  383. package/dist/work-items/card-search-text.js.map +1 -0
  384. package/dist/work-items/card-source-filters.d.ts +23 -0
  385. package/dist/work-items/card-source-filters.d.ts.map +1 -0
  386. package/dist/work-items/card-source-filters.js +25 -0
  387. package/dist/work-items/card-source-filters.js.map +1 -0
  388. package/dist/work-items/create-work-item.d.ts +0 -6
  389. package/dist/work-items/create-work-item.d.ts.map +1 -1
  390. package/dist/work-items/create-work-item.js +2 -7
  391. package/dist/work-items/create-work-item.js.map +1 -1
  392. package/dist/work-items/list-related-cards.d.ts +4 -0
  393. package/dist/work-items/list-related-cards.d.ts.map +1 -0
  394. package/dist/work-items/list-related-cards.js +24 -0
  395. package/dist/work-items/list-related-cards.js.map +1 -0
  396. package/dist/work-items/search-words.d.ts +5 -0
  397. package/dist/work-items/search-words.d.ts.map +1 -0
  398. package/dist/work-items/search-words.js +12 -0
  399. package/dist/work-items/search-words.js.map +1 -0
  400. package/dist/work-items/source-external-id.d.ts +4 -0
  401. package/dist/work-items/source-external-id.d.ts.map +1 -0
  402. package/dist/work-items/source-external-id.js +9 -0
  403. package/dist/work-items/source-external-id.js.map +1 -0
  404. package/dist/workspace.d.ts.map +1 -1
  405. package/dist/workspace.js +92 -47
  406. package/dist/workspace.js.map +1 -1
  407. package/package.json +9 -8
@@ -1,3 +1,4 @@
1
+ import "../../dependabot/sync.js";
1
2
  import "../../github/reconcile-worker.js";
2
3
  import { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from "../../github/subscriptions.js";
3
4
  import { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from "../../github/webhook.js";
@@ -44,6 +45,9 @@ var PlatformGithubEventWorker = class extends MastraWorker {
44
45
  #reconcileFactoryState;
45
46
  #reconcileIssuesFactoryState;
46
47
  #discoverPullRequests;
48
+ #syncDependabotAlerts;
49
+ #dependabotSyncIntervalMs;
50
+ #lastDependabotSyncAt = Number.NEGATIVE_INFINITY;
47
51
  #pollEventsEnabled;
48
52
  #pullRequestReconcileIntervalMs;
49
53
  #issueReconcileIntervalMs;
@@ -52,6 +56,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
52
56
  #now;
53
57
  #dispatch;
54
58
  #sourceControl;
59
+ #onRepositoriesChanged;
60
+ #repositoryChangesShared;
55
61
  #leaseOwner = globalThis.crypto.randomUUID();
56
62
  #running = false;
57
63
  #timer;
@@ -68,6 +74,9 @@ var PlatformGithubEventWorker = class extends MastraWorker {
68
74
  version: 1,
69
75
  repositories: {}
70
76
  };
77
+ #unsubscribeRepositoryChanges;
78
+ #repositories;
79
+ #repositoryChanges = 0;
71
80
  constructor(config) {
72
81
  super();
73
82
  this.#client = config.client;
@@ -78,6 +87,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
78
87
  this.#reconcileFactoryState = config.reconcileFactoryState;
79
88
  this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;
80
89
  this.#discoverPullRequests = config.discoverPullRequests;
90
+ this.#syncDependabotAlerts = config.syncDependabotAlerts;
91
+ this.#dependabotSyncIntervalMs = config.dependabotSyncIntervalMs ?? 9e5;
81
92
  this.#pollEventsEnabled = config.pollEventsEnabled ?? true;
82
93
  const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;
83
94
  this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;
@@ -92,6 +103,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
92
103
  this.#now = config.now ?? Date.now;
93
104
  this.#dispatch = config.dispatch ?? dispatchGithubWebhook;
94
105
  this.#sourceControl = config.sourceControl;
106
+ this.#onRepositoriesChanged = config.onRepositoriesChanged;
107
+ this.#repositoryChangesShared = config.repositoryChangesShared ?? (() => true);
95
108
  }
96
109
  async init(deps) {
97
110
  await super.init(deps);
@@ -102,8 +115,14 @@ var PlatformGithubEventWorker = class extends MastraWorker {
102
115
  if (!this.deps) throw new Error("PlatformGithubEventWorker: call init() before start()");
103
116
  this.#startedAt = this.#now() - 1;
104
117
  this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));
118
+ this.#repositoryChanges += 1;
119
+ this.#repositories = void 0;
120
+ this.#unsubscribeRepositoryChanges = this.#onRepositoriesChanged?.(() => {
121
+ this.#repositoryChanges += 1;
122
+ this.#repositories = void 0;
123
+ });
105
124
  this.#running = true;
106
- this.deps.logger.info("Platform GitHub event polling started", {
125
+ this.deps.logger.debug("Platform GitHub event polling started", {
107
126
  intervalMs: this.#intervalMs,
108
127
  leaseTtlMs: this.#leaseTtlMs
109
128
  });
@@ -115,6 +134,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
115
134
  if (this.#timer) clearTimeout(this.#timer);
116
135
  this.#timer = void 0;
117
136
  this.#stopLeaseRenewal();
137
+ this.#unsubscribeRepositoryChanges?.();
138
+ this.#unsubscribeRepositoryChanges = void 0;
118
139
  await this.#inFlight;
119
140
  if (this.#hasLease) {
120
141
  await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => void 0);
@@ -179,7 +200,7 @@ var PlatformGithubEventWorker = class extends MastraWorker {
179
200
  this.#leaseRenewalTimer = void 0;
180
201
  }
181
202
  async #poll() {
182
- const repositories = await this.#discoverRepositories();
203
+ const repositories = await this.#linkedRepositories();
183
204
  let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();
184
205
  if (this.#pollEventsEnabled) for (const repository of repositories) {
185
206
  if (!this.#running || !this.#hasLease) break;
@@ -203,7 +224,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
203
224
  const cadences = [
204
225
  this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : void 0,
205
226
  this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : void 0,
206
- this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : void 0
227
+ this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : void 0,
228
+ this.#syncDependabotAlerts ? this.#dependabotSyncIntervalMs : void 0
207
229
  ].filter((interval) => interval !== void 0);
208
230
  return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;
209
231
  }
@@ -213,10 +235,13 @@ var PlatformGithubEventWorker = class extends MastraWorker {
213
235
  const reconcilePullRequests = Boolean(this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs);
214
236
  const reconcileIssues = Boolean(this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs);
215
237
  const discoverPullRequests = Boolean(this.#discoverPullRequests && now - this.#lastPullRequestDiscoveryAt >= this.#pullRequestDiscoveryIntervalMs);
216
- if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests) return;
238
+ const syncDependabot = Boolean(this.#syncDependabotAlerts && now - this.#lastDependabotSyncAt >= this.#dependabotSyncIntervalMs);
239
+ if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests && !syncDependabot) return;
240
+ if (syncDependabot) this.#lastDependabotSyncAt = now;
217
241
  if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;
218
242
  if (reconcileIssues) this.#lastIssueReconcileAt = now;
219
243
  if (discoverPullRequests) this.#lastPullRequestDiscoveryAt = now;
244
+ if (reconcilePullRequests || reconcileIssues) await this.#refreshRepositoryNames(repositories);
220
245
  const targets = repositories.flatMap((repository) => repository.fullName ? [{
221
246
  id: repository.id,
222
247
  fullName: repository.fullName,
@@ -226,6 +251,28 @@ var PlatformGithubEventWorker = class extends MastraWorker {
226
251
  this.deps?.logger.debug("Platform GitHub reconciliation skipped: no named repositories");
227
252
  return;
228
253
  }
254
+ if (syncDependabot && this.#syncDependabotAlerts && this.#hasLease) {
255
+ const startedAt = Date.now();
256
+ try {
257
+ const { errors, ...counts } = await this.#syncDependabotAlerts(targets);
258
+ const context = {
259
+ ...counts,
260
+ candidateRepositories: targets.length,
261
+ durationMs: Date.now() - startedAt
262
+ };
263
+ if (counts.failed > 0) this.deps?.logger.warn("Platform GitHub Dependabot sync completed with failures", {
264
+ ...context,
265
+ errors
266
+ });
267
+ else this.deps?.logger.info("Platform GitHub Dependabot sync completed", context);
268
+ } catch (error) {
269
+ this.deps?.logger.error("Platform GitHub Dependabot sync failed", {
270
+ repositories: targets.length,
271
+ durationMs: Date.now() - startedAt,
272
+ error: error instanceof Error ? error.message : String(error)
273
+ });
274
+ }
275
+ }
229
276
  if (reconcilePullRequests && this.#reconcileFactoryState) {
230
277
  const startedAt = Date.now();
231
278
  try {
@@ -252,7 +299,11 @@ var PlatformGithubEventWorker = class extends MastraWorker {
252
299
  if (discoverPullRequests && this.#discoverPullRequests && this.#hasLease) {
253
300
  const startedAt = Date.now();
254
301
  try {
255
- const { errors, ...counts } = await this.#discoverPullRequests(targets);
302
+ const linked = new Map(repositories.map((repository) => [repository.id, repository.projects]));
303
+ const { errors, ...counts } = await this.#discoverPullRequests(targets.map((target) => ({
304
+ ...target,
305
+ projects: linked.get(target.id) ?? []
306
+ })));
256
307
  const context = {
257
308
  ...counts,
258
309
  candidateRepositories: targets.length,
@@ -298,6 +349,35 @@ var PlatformGithubEventWorker = class extends MastraWorker {
298
349
  }
299
350
  }
300
351
  }
352
+ async #linkedRepositories() {
353
+ const cacheable = Boolean(this.#unsubscribeRepositoryChanges) && this.#repositoryChangesShared();
354
+ if (this.#repositories && cacheable) return this.#repositories;
355
+ const changes = this.#repositoryChanges;
356
+ const repositories = await this.#discoverRepositories();
357
+ this.#repositories = cacheable && changes === this.#repositoryChanges ? repositories : void 0;
358
+ return repositories;
359
+ }
360
+ /**
361
+ * Takes each repository's current name from the platform. A rename is not a
362
+ * Factory write, so nothing announces it; the stored slug only catches up
363
+ * when someone lists the installation's repositories again. Runs with the
364
+ * hourly sweeps, one platform call per installation and no storage reads.
365
+ */
366
+ async #refreshRepositoryNames(repositories) {
367
+ for (const installationId of new Set(repositories.map((repository) => repository.installationId))) try {
368
+ const { repositories: current } = await this.#client.request("GET", `${API_PREFIX}/installations/${installationId}/repositories`);
369
+ const names = new Map(current.map((repository) => [repository.id, repository.fullName]));
370
+ for (const repository of repositories) {
371
+ const name = repository.installationId === installationId ? names.get(repository.id) : void 0;
372
+ if (name) repository.fullName = name;
373
+ }
374
+ } catch (error) {
375
+ this.deps?.logger.warn("Platform GitHub repository name refresh failed", {
376
+ installationId,
377
+ error: error instanceof Error ? error.message : String(error)
378
+ });
379
+ }
380
+ }
301
381
  /**
302
382
  * Configured `(installation, repository)` pairs — the same set the
303
383
  * reconciler sweeps — resolved to the numeric ids and slug the poll
@@ -313,7 +393,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
313
393
  const repositoryId = Number(key.repositoryExternalId);
314
394
  if (!Number.isSafeInteger(installationId) || installationId <= 0 || !Number.isSafeInteger(repositoryId) || repositoryId <= 0) continue;
315
395
  if (repositories.has(repositoryId)) continue;
316
- const orgId = (await this.#sourceControl.projectRepositories.listByExternalRepository(key))[0]?.orgId;
396
+ const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);
397
+ const orgId = projects[0]?.orgId;
317
398
  const repository = orgId ? await this.#sourceControl.repositories.findByExternalId({
318
399
  orgId,
319
400
  externalId: key.repositoryExternalId
@@ -321,7 +402,8 @@ var PlatformGithubEventWorker = class extends MastraWorker {
321
402
  repositories.set(repositoryId, {
322
403
  id: repositoryId,
323
404
  installationId,
324
- fullName: repository?.slug
405
+ fullName: repository?.slug,
406
+ projects
325
407
  });
326
408
  }
327
409
  return [...repositories.values()];
@@ -1 +1 @@
1
- {"version":3,"file":"event-worker.js","names":[],"sources":["../../../../src/integrations/platform/github/event-worker.ts"],"sourcesContent":["import type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { GithubRepositoryPermission } from '../../github/integration.js';\nimport type { GithubIssueReconciler } from '../../github/issue-reconciler.js';\nimport { DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS } from '../../github/reconcile-worker.js';\nimport type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';\nimport type {\n GithubPullRequestDiscovery,\n GithubPullRequestReconciler,\n ReconcileRepository,\n} from '../../github/rules.js';\nimport { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from '../../github/subscriptions.js';\nimport { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from '../../github/webhook.js';\nimport type {\n GithubWebhookDispatchIntegration,\n GithubWebhookNotification,\n ParsedGithubWebhook,\n} from '../../github/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/github-app';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\n// Event polling is the primary sync; the sweeps only catch drift (missed\n// events, cards ingested before polling was linked), so they run hourly.\nconst DEFAULT_RECONCILE_INTERVAL_MS = 60 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_github_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst SUPPORTED_EVENTS = new Set([\n 'issues',\n 'issue_comment',\n 'pull_request',\n 'pull_request_review',\n 'pull_request_review_comment',\n // Pushes never reach the subscription dispatcher; they feed the factory\n // ingest path so environment templates rebuild on default-branch updates.\n 'push',\n]);\n// Kinds emitted by `classifyGithubWebhook` that carry untrusted sender-authored\n// content and must pass the sender authorization gate below.\nconst AUTHOR_GATED_KINDS = new Set([\n 'issue-comment-created',\n 'review-comment-created',\n 'review-approved',\n 'review-changes-requested',\n 'review-submitted',\n 'review-dismissed',\n]);\nconst AUTHORIZED_PERMISSIONS = new Set<GithubRepositoryPermission>(['admin', 'maintain', 'write']);\nconst PERMISSION_CHECK_TIMEOUT_MS = 5_000;\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformGithubEventWorkerSettings = {\n version: 1;\n repositories: Record<string, EventCursor>;\n};\n\nexport type PlatformGithubEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGithubEventWorkerSettings,\n Record<string, unknown>\n>;\n\ntype EventLogEntry = {\n id: string;\n deliveryId: string;\n event: string;\n payload: unknown;\n};\n\ntype Repository = { id: number; fullName?: string; installationId: number };\n\nexport type PlatformGithubEventDispatchIntegration = GithubWebhookDispatchIntegration;\n\nexport interface PlatformGithubEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n github: PlatformGithubEventDispatchIntegration;\n storage: PlatformGithubEventStorage;\n /**\n * Source-control storage used to resolve the set of repositories the worker\n * should poll. The worker restricts itself to `(installation, repository)`\n * pairs linked to a factory project — the same set the reconciler uses —\n * so polling scales with Factory usage, not with the size of the underlying\n * GitHub org.\n */\n sourceControl: GithubReconcileRepositorySource;\n ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;\n reconcileFactoryState?: GithubPullRequestReconciler;\n reconcileIssuesFactoryState?: GithubIssueReconciler;\n discoverPullRequests?: GithubPullRequestDiscovery;\n /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n /** Legacy shared reconciliation cadence. */\n reconcileIntervalMs?: number;\n pullRequestReconcileIntervalMs?: number;\n issueReconcileIntervalMs?: number;\n /** Defaults to five minutes, or the pull request interval when that is shorter. */\n pullRequestDiscoveryIntervalMs?: number;\n now?: () => number;\n dispatch?: typeof dispatchGithubWebhook;\n}\n\nexport class PlatformGithubEventWorker extends MastraWorker {\n readonly name = 'platform-github-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #github: PlatformGithubEventDispatchIntegration;\n readonly #storage: PlatformGithubEventStorage;\n readonly #ingestFactoryEvent: ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: GithubPullRequestReconciler | undefined;\n readonly #reconcileIssuesFactoryState: GithubIssueReconciler | undefined;\n readonly #discoverPullRequests: GithubPullRequestDiscovery | undefined;\n readonly #pollEventsEnabled: boolean;\n readonly #pullRequestReconcileIntervalMs: number;\n readonly #issueReconcileIntervalMs: number;\n readonly #pullRequestDiscoveryIntervalMs: number;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #dispatch: typeof dispatchGithubWebhook;\n readonly #sourceControl: GithubReconcileRepositorySource;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n // Negative infinity so the first tick always sweeps, whatever the clock reads.\n #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;\n #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;\n #lastPullRequestDiscoveryAt = Number.NEGATIVE_INFINITY;\n #settings: PlatformGithubEventWorkerSettings = { version: 1, repositories: {} };\n\n constructor(config: PlatformGithubEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#github = config.github;\n this.#storage = config.storage;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;\n this.#discoverPullRequests = config.discoverPullRequests;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#pullRequestDiscoveryIntervalMs =\n config.pullRequestDiscoveryIntervalMs ??\n Math.min(DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS, this.#pullRequestReconcileIntervalMs);\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitHub event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub issue reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestDiscoveryIntervalMs) || this.#pullRequestDiscoveryIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request discovery interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(\n MIN_LEASE_TTL_MS,\n Math.min(\n this.#intervalMs,\n this.#pullRequestReconcileIntervalMs,\n this.#issueReconcileIntervalMs,\n this.#pullRequestDiscoveryIntervalMs,\n ) * 3,\n );\n this.#now = config.now ?? Date.now;\n this.#dispatch = config.dispatch ?? dispatchGithubWebhook;\n this.#sourceControl = config.sourceControl;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGithubEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n this.#running = true;\n this.deps.logger.info('Platform GitHub event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitHub event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitHub event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const repositories = await this.#discoverRepositories();\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();\n\n if (this.#pollEventsEnabled) {\n for (const repository of repositories) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollRepository(repository.id);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitHub repository event polling failed', {\n repositoryId: repository.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile(repositories);\n return retryInMs;\n }\n\n #reconcileCadence(): number {\n const cadences = [\n this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : undefined,\n this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : undefined,\n this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : undefined,\n ].filter((interval): interval is number => interval !== undefined);\n return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;\n }\n\n async #maybeReconcile(repositories: Repository[]): Promise<void> {\n if (!this.#running || !this.#hasLease) return;\n const now = this.#now();\n const reconcilePullRequests = Boolean(\n this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs,\n );\n const reconcileIssues = Boolean(\n this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs,\n );\n const discoverPullRequests = Boolean(\n this.#discoverPullRequests &&\n now - this.#lastPullRequestDiscoveryAt >= this.#pullRequestDiscoveryIntervalMs,\n );\n if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests) return;\n if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;\n if (reconcileIssues) this.#lastIssueReconcileAt = now;\n if (discoverPullRequests) this.#lastPullRequestDiscoveryAt = now;\n\n const targets: ReconcileRepository[] = repositories.flatMap(repository =>\n repository.fullName\n ? [{ id: repository.id, fullName: repository.fullName, installationId: repository.installationId }]\n : [],\n );\n if (targets.length === 0) {\n this.deps?.logger.debug('Platform GitHub reconciliation skipped: no named repositories');\n return;\n }\n\n if (reconcilePullRequests && this.#reconcileFactoryState) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.merged > 0 || counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub pull request reconcile replayed missed merges/closes', context);\n } else {\n this.deps?.logger.info('Platform GitHub pull request reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (discoverPullRequests && this.#discoverPullRequests && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#discoverPullRequests(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request discovery completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0 || counts.repaired > 0) {\n this.deps?.logger.info('Platform GitHub pull request discovery replayed missed opens', context);\n } else {\n this.deps?.logger.debug('Platform GitHub pull request discovery completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request discovery failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileIssuesFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed missed opens', context);\n } else if (counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed closed work items', context);\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform GitHub issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub issue reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n /**\n * Configured `(installation, repository)` pairs — the same set the\n * reconciler sweeps — resolved to the numeric ids and slug the poll\n * addresses GitHub with. Repositories not linked to any factory project\n * cannot produce work for Factory, so polling and reconciling them is\n * wasted `/events` bandwidth and platform load.\n */\n async #discoverRepositories(): Promise<Repository[]> {\n const keys = await this.#sourceControl.projectRepositories.listConfiguredExternalKeys();\n const repositories = new Map<number, Repository>();\n for (const key of keys) {\n const installationId = Number(key.installationExternalId);\n const repositoryId = Number(key.repositoryExternalId);\n if (\n !Number.isSafeInteger(installationId) ||\n installationId <= 0 ||\n !Number.isSafeInteger(repositoryId) ||\n repositoryId <= 0\n ) {\n continue;\n }\n if (repositories.has(repositoryId)) continue;\n // A configured key exists per project link, so `listByExternalRepository`\n // always yields at least one row; the first row's orgId is enough to\n // look up the repository row for its slug.\n const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);\n const orgId = projects[0]?.orgId;\n const repository = orgId\n ? await this.#sourceControl.repositories.findByExternalId({ orgId, externalId: key.repositoryExternalId })\n : null;\n repositories.set(repositoryId, {\n id: repositoryId,\n installationId,\n fullName: repository?.slug,\n });\n }\n return [...repositories.values()];\n }\n\n async #pollRepository(repositoryId: number): Promise<void> {\n const key = String(repositoryId);\n if (!this.#settings.repositories[key]) {\n this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.repositories[key]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('afterTimestamp', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: EventLogEntry[]; nextCursor: string | null }>(\n 'GET',\n `${API_PREFIX}/repositories/${repositoryId}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitHub repository event poll completed', {\n repositoryId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n const parsed = parseEvent(event);\n if (!parsed) {\n this.deps?.logger.warn('Platform GitHub event log returned a malformed event', {\n repositoryId,\n eventId: event.id,\n });\n continue;\n }\n if (isFactoryIngestedEvent(parsed)) {\n await this.#ingestFactoryEvent?.(parsed);\n } else {\n this.deps?.logger.debug('Platform GitHub event not forwarded to Factory ingress', {\n repositoryId,\n deliveryId: parsed.deliveryId,\n event: parsed.event,\n action: parsed.payload.action,\n });\n }\n const result = await this.#dispatch(parsed, {\n controller: this.#controller,\n listSubscriptions: (target, options) =>\n listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),\n retireSubscription: (id, status) =>\n retirePullRequestSubscription(id, status, this.#github.integrationStorage),\n github: this.#github,\n isAuthorizedSender: notification => this.#isAuthorizedSender(notification),\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another\n // deployment, so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitHub event skipped: thread is not held here', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitHub event dropped: sender not authorized', {\n deliveryId: event.deliveryId,\n repository: notification.metadata.repository,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitHub event delivery failed for a subscription', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.failed > 0) {\n this.deps?.logger.warn('Platform GitHub event completed with failed subscription deliveries', {\n repositoryId,\n deliveryId: event.deliveryId,\n delivered: result.delivered,\n failed: result.failed,\n });\n }\n }\n\n if (page.nextCursor === ('afterEventId' in cursor ? cursor.afterEventId : undefined)) return;\n this.#settings.repositories[key] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #isAuthorizedSender(notification: GithubWebhookNotification): Promise<boolean> {\n if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;\n const sender = notification.metadata.sender;\n const repository = notification.metadata.repository;\n if (!sender || !repository) return false;\n // Factory's own app has to clear the gate before the bot rules below, which\n // fail closed for every bot that is not explicitly allowlisted. GitHub\n // forbids an app from reviewing its own pull request, so `factory-review`\n // posts its verdict as a comment under this login and that comment is the\n // handoff the authoring agent wakes on.\n if (this.#github.identity?.matches(sender)) return true;\n if (isFactoryAppSender(sender, this.#github.slug)) return true;\n const normalizedSender = sender.toLowerCase();\n const authorizedBots = resolveAuthorizedBots(this.#github.authorizedBots);\n if (authorizedBots.has(normalizedSender)) return true;\n // Any other bot is gated purely by the allowlist: a GitHub App never holds a\n // collaborator permission under its sender login, so falling through to the\n // permission lookup would only fail closed after a wasted API call.\n if (notification.metadata.senderType?.toLowerCase() === 'bot' || normalizedSender.endsWith('[bot]')) {\n return false;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS);\n try {\n const permission = await this.#github.getRepositoryCollaboratorPermission(\n notification.metadata.installationId,\n repository,\n sender,\n abortController.signal,\n );\n return permission !== undefined && AUTHORIZED_PERMISSIONS.has(permission);\n } catch {\n return false;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGithubEventWorkerSettings | null): PlatformGithubEventWorkerSettings {\n if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== 'object') {\n return { version: 1, repositories: {} };\n }\n return { version: 1, repositories: { ...value.repositories } };\n}\n\n// Events the polling worker forwards to the factory rules engine. Closures\n// let the reconciler finalize cards; `synchronize` and `review_requested` on a\n// pull request are the triggers the review board's re-review path listens for;\n// submitted reviews and pull request comments are how review feedback reaches\n// the agent that authored the branch. Direct-webhook consumers ingest every\n// parsed event; the platform path gates because the remaining events (issue\n// edits, comment edits and deletions) only interest the subscription\n// dispatcher, not the factory rules.\nconst ISSUE_INGESTED_ACTIONS = new Set(['opened', 'reopened', 'edited', 'labeled', 'unlabeled']);\n\nfunction isFactoryIngestedEvent(event: ParsedGithubWebhook): boolean {\n if ((event.event === 'issues' || event.event === 'pull_request') && event.payload.action === 'closed') {\n return true;\n }\n if (event.event === 'pull_request') {\n const action = event.payload.action;\n // `opened` is what mints the Review card for a pull request. Without it a\n // factory-authored PR never gets reviewed on the polling path, which is the\n // only path a local deployment has.\n if (action === 'opened' || action === 'synchronize' || action === 'review_requested') return true;\n }\n // Issue opens, reopens, edits and label changes mint and update Work cards.\n // Without them a new issue never becomes a card on the polling path (#24972).\n if (event.event === 'issues' && ISSUE_INGESTED_ACTIONS.has(String(event.payload.action))) return true;\n if (event.event === 'pull_request_review' && event.payload.action === 'submitted') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'created') return true;\n // `factory-review` edits its earlier verdict in place on a re-review. The rules\n // engine only acts on edits that leave a request-changes verdict behind.\n if (event.event === 'pull_request_review' && event.payload.action === 'edited') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'edited') {\n const issue = event.payload.issue;\n if (issue && typeof issue === 'object' && 'pull_request' in issue && issue.pull_request) return true;\n }\n // Default-branch pushes reach the environment build hand-off\n // (`GithubRules` calls the `onRepositoryPush` hook).\n if (event.event === 'push') return true;\n return false;\n}\n\nfunction parseEvent(event: EventLogEntry): ParsedGithubWebhook | null {\n if (\n !event.id ||\n !event.deliveryId ||\n !SUPPORTED_EVENTS.has(event.event) ||\n !event.payload ||\n typeof event.payload !== 'object' ||\n Array.isArray(event.payload)\n ) {\n return null;\n }\n return {\n event: event.event,\n deliveryId: event.deliveryId,\n payload: event.payload as Record<string, unknown>,\n };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,aAAa;AACnB,MAAM,2BAA2B;AAGjC,MAAM,gCAAgC;AACtC,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,mCAAmB,IAAI,IAAI;CAC/B;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC;AAGD,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,yCAAyB,IAAI,IAAgC;CAAC;CAAS;CAAY;AAAO,CAAC;AACjG,MAAM,8BAA8B;AAuDpC,IAAa,4BAAb,cAA+C,aAAa;CAC1D,OAAgB;CAEhB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,cAAuB,WAAW,OAAO,WAAW;CAEpD,WAAW;CACX;CACA;CACA;CACA,iBAAgC;CAChC;CACA,YAAY;CACZ,aAAa;CAEb,8BAA8B,OAAO;CACrC,wBAAwB,OAAO;CAC/B,8BAA8B,OAAO;CACrC,YAA+C;EAAE,SAAS;EAAG,cAAc,CAAC;CAAE;CAE9E,YAAY,QAAyC;EACnD,MAAM;EACN,KAAK,UAAU,OAAO;EACtB,KAAK,cAAc,OAAO;EAC1B,KAAK,UAAU,OAAO;EACtB,KAAK,WAAW,OAAO;EACvB,KAAK,sBAAsB,OAAO;EAClC,KAAK,yBAAyB,OAAO;EACrC,KAAK,+BAA+B,OAAO;EAC3C,KAAK,wBA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AK,MAAM,UAAU,YAAY,MAAM,UAAU,mBAAmB,MAAM,QAAQ,WAAW,UAC3F,OAAO;CAET,IAAI,MAAM,UAAU,gBAAgB;EAClC,MAAM,SAAS,MAAM,QAAQ;EAI7B,IAAI,WAAW,YAAY,WAAW,iBAAiB,WAAW,oBAAoB,OAAO;CAC/F;CAGA,IAAI,MAAM,UAAU,YAAY,uBAAuB,IAAI,OAAO,MAAM,QAAQ,MAAM,CAAC,GAAG,OAAO;CACjG,IAAI,MAAM,UAAU,yBAAyB,MAAM,QAAQ,WAAW,aAAa,OAAO;CAC1F,IAAI,MAAM,UAAU,mBAAmB,MAAM,QAAQ,WAAW,WAAW,OAAO;CAGlF,IAAI,MAAM,UAAU,yBAAyB,MAAM,QAAQ,WAAW,UAAU,OAAO;CACvF,IAAI,MAAM,UAAU,mBAAmB,MAAM,QAAQ,WAAW,UAAU;EACxE,MAAM,QAAQ,MAAM,QAAQ;EAC5B,IAAI,SAAS,OAAO,UAAU,YAAY,kBAAkB,SAAS,MAAM,cAAc,OAAO;CAClG;CAGA,IAAI,MAAM,UAAU,QAAQ,OAAO;CACnC,OAAO;AACT;AAEA,SAAS,WAAW,OAAkD;CACpE,IACE,CAAC,MAAM,MACP,CAAC,MAAM,cACP,CAAC,iBAAiB,IAAI,MAAM,KAAK,KACjC,CAAC,MAAM,WACP,OAAO,MAAM,YAAY,YACzB,MAAM,QAAQ,MAAM,OAAO,GAE3B,OAAO;CAET,OAAO;EACL,OAAO,MAAM;EACb,YAAY,MAAM;EAClB,SAAS,MAAM;CACjB;AACF;AAEA,SAAS,WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
1
+ {"version":3,"file":"event-worker.js","names":[],"sources":["../../../../src/integrations/platform/github/event-worker.ts"],"sourcesContent":["import type { MountedMastraCode } from '@mastra/code-sdk';\nimport { isLeaseProvider, NoopLeaseProvider } from '@mastra/core/events';\nimport type { LeaseProvider, PubSub } from '@mastra/core/events';\nimport { MastraWorker } from '@mastra/core/worker';\nimport type { WorkerDeps } from '@mastra/core/worker';\n\nimport type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';\nimport type { ExternalRepositoryProjectTarget } from '../../../storage/domains/source-control/base.js';\nimport { DEFAULT_DEPENDABOT_SYNC_INTERVAL_MS } from '../../dependabot/sync.js';\nimport type { DependabotSync } from '../../dependabot/sync.js';\nimport type { GithubRepositoryPermission } from '../../github/integration.js';\nimport type { GithubIssueReconciler } from '../../github/issue-reconciler.js';\nimport { DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS } from '../../github/reconcile-worker.js';\nimport type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';\nimport type {\n GithubPullRequestDiscovery,\n GithubPullRequestReconciler,\n ReconcileRepository,\n} from '../../github/rules.js';\nimport { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from '../../github/subscriptions.js';\nimport { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from '../../github/webhook.js';\nimport type {\n GithubWebhookDispatchIntegration,\n GithubWebhookNotification,\n ParsedGithubWebhook,\n} from '../../github/webhook.js';\nimport type { PlatformApiClient } from '../api-client.js';\nimport { PlatformApiError } from '../api-client.js';\n\nconst API_PREFIX = '/v1/server/github-app';\nconst DEFAULT_POLL_INTERVAL_MS = 20_000;\n// Event polling is the primary sync; the sweeps only catch drift (missed\n// events, cards ingested before polling was linked), so they run hourly.\nconst DEFAULT_RECONCILE_INTERVAL_MS = 60 * 60_000;\nconst EVENT_PAGE_SIZE = 500;\nconst MIN_LEASE_TTL_MS = 30_000;\nconst CURSOR_ORG_ID = '__platform_github_event_worker__';\nconst CURSOR_USER_ID = 'worker';\nconst SUPPORTED_EVENTS = new Set([\n 'issues',\n 'issue_comment',\n 'pull_request',\n 'pull_request_review',\n 'pull_request_review_comment',\n // Pushes never reach the subscription dispatcher; they feed the factory\n // ingest path so environment templates rebuild on default-branch updates.\n 'push',\n]);\n// Kinds emitted by `classifyGithubWebhook` that carry untrusted sender-authored\n// content and must pass the sender authorization gate below.\nconst AUTHOR_GATED_KINDS = new Set([\n 'issue-comment-created',\n 'review-comment-created',\n 'review-approved',\n 'review-changes-requested',\n 'review-submitted',\n 'review-dismissed',\n]);\nconst AUTHORIZED_PERMISSIONS = new Set<GithubRepositoryPermission>(['admin', 'maintain', 'write']);\nconst PERMISSION_CHECK_TIMEOUT_MS = 5_000;\n\ntype EventCursor = { afterEventId: string } | { afterTimestamp: number };\ntype PlatformGithubEventWorkerSettings = {\n version: 1;\n repositories: Record<string, EventCursor>;\n};\n\nexport type PlatformGithubEventStorage = IntegrationStorageHandle<\n Record<string, unknown>,\n PlatformGithubEventWorkerSettings,\n Record<string, unknown>\n>;\n\ntype EventLogEntry = {\n id: string;\n deliveryId: string;\n event: string;\n payload: unknown;\n};\n\ntype Repository = {\n id: number;\n fullName?: string;\n installationId: number;\n projects: ExternalRepositoryProjectTarget[];\n};\n\nexport type PlatformGithubEventDispatchIntegration = GithubWebhookDispatchIntegration;\n\nexport interface PlatformGithubEventWorkerConfig {\n client: PlatformApiClient;\n controller: MountedMastraCode['controller'];\n github: PlatformGithubEventDispatchIntegration;\n storage: PlatformGithubEventStorage;\n /**\n * Source-control storage used to resolve the set of repositories the worker\n * should poll. The worker restricts itself to `(installation, repository)`\n * pairs linked to a factory project — the same set the reconciler uses —\n * so polling scales with Factory usage, not with the size of the underlying\n * GitHub org.\n */\n sourceControl: GithubReconcileRepositorySource;\n /**\n * Subscribes to changes of the linked repository set and returns the\n * unsubscribe. With it the worker reads the set from storage once, and again\n * only after a change, so a poll that finds no events costs no storage reads.\n * Without it every poll re-reads the set.\n */\n onRepositoriesChanged?: (listener: () => void) => () => void;\n /**\n * False while changes made on other replicas cannot reach this one; the\n * worker then re-reads the set on every poll. Defaults to true.\n */\n repositoryChangesShared?: () => boolean;\n ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;\n reconcileFactoryState?: GithubPullRequestReconciler;\n reconcileIssuesFactoryState?: GithubIssueReconciler;\n discoverPullRequests?: GithubPullRequestDiscovery;\n /** Files Dependabot alerts on linked repositories as cards. */\n syncDependabotAlerts?: DependabotSync;\n /** Defaults to fifteen minutes. */\n dependabotSyncIntervalMs?: number;\n /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */\n pollEventsEnabled?: boolean;\n intervalMs?: number;\n /** Legacy shared reconciliation cadence. */\n reconcileIntervalMs?: number;\n pullRequestReconcileIntervalMs?: number;\n issueReconcileIntervalMs?: number;\n /** Defaults to five minutes, or the pull request interval when that is shorter. */\n pullRequestDiscoveryIntervalMs?: number;\n now?: () => number;\n dispatch?: typeof dispatchGithubWebhook;\n}\n\nexport class PlatformGithubEventWorker extends MastraWorker {\n readonly name = 'platform-github-events';\n\n readonly #client: PlatformApiClient;\n readonly #controller: MountedMastraCode['controller'];\n readonly #github: PlatformGithubEventDispatchIntegration;\n readonly #storage: PlatformGithubEventStorage;\n readonly #ingestFactoryEvent: ((event: ParsedGithubWebhook) => Promise<unknown>) | undefined;\n readonly #reconcileFactoryState: GithubPullRequestReconciler | undefined;\n readonly #reconcileIssuesFactoryState: GithubIssueReconciler | undefined;\n readonly #discoverPullRequests: GithubPullRequestDiscovery | undefined;\n readonly #syncDependabotAlerts: DependabotSync | undefined;\n readonly #dependabotSyncIntervalMs: number;\n #lastDependabotSyncAt = Number.NEGATIVE_INFINITY;\n readonly #pollEventsEnabled: boolean;\n readonly #pullRequestReconcileIntervalMs: number;\n readonly #issueReconcileIntervalMs: number;\n readonly #pullRequestDiscoveryIntervalMs: number;\n readonly #intervalMs: number;\n readonly #now: () => number;\n readonly #dispatch: typeof dispatchGithubWebhook;\n readonly #sourceControl: GithubReconcileRepositorySource;\n readonly #onRepositoriesChanged: ((listener: () => void) => () => void) | undefined;\n readonly #repositoryChangesShared: () => boolean;\n readonly #leaseOwner = globalThis.crypto.randomUUID();\n\n #running = false;\n #timer: ReturnType<typeof setTimeout> | undefined;\n #leaseRenewalTimer: ReturnType<typeof setInterval> | undefined;\n #inFlight: Promise<void> | undefined;\n #leaseProvider: LeaseProvider = NoopLeaseProvider;\n #leaseTtlMs: number;\n #hasLease = false;\n #startedAt = 0;\n // Negative infinity so the first tick always sweeps, whatever the clock reads.\n #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;\n #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;\n #lastPullRequestDiscoveryAt = Number.NEGATIVE_INFINITY;\n #settings: PlatformGithubEventWorkerSettings = { version: 1, repositories: {} };\n #unsubscribeRepositoryChanges: (() => void) | undefined;\n #repositories: Repository[] | undefined;\n #repositoryChanges = 0;\n\n constructor(config: PlatformGithubEventWorkerConfig) {\n super();\n this.#client = config.client;\n this.#controller = config.controller;\n this.#github = config.github;\n this.#storage = config.storage;\n this.#ingestFactoryEvent = config.ingestFactoryEvent;\n this.#reconcileFactoryState = config.reconcileFactoryState;\n this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;\n this.#discoverPullRequests = config.discoverPullRequests;\n this.#syncDependabotAlerts = config.syncDependabotAlerts;\n this.#dependabotSyncIntervalMs = config.dependabotSyncIntervalMs ?? DEFAULT_DEPENDABOT_SYNC_INTERVAL_MS;\n this.#pollEventsEnabled = config.pollEventsEnabled ?? true;\n const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;\n this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;\n this.#pullRequestDiscoveryIntervalMs =\n config.pullRequestDiscoveryIntervalMs ??\n Math.min(DEFAULT_GITHUB_PR_DISCOVERY_INTERVAL_MS, this.#pullRequestReconcileIntervalMs);\n this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;\n if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) {\n throw new Error('Platform GitHub event polling interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) {\n throw new Error('Platform GitHub issue reconcile interval must be a positive number.');\n }\n if (!Number.isFinite(this.#pullRequestDiscoveryIntervalMs) || this.#pullRequestDiscoveryIntervalMs <= 0) {\n throw new Error('Platform GitHub pull request discovery interval must be a positive number.');\n }\n this.#leaseTtlMs = Math.max(\n MIN_LEASE_TTL_MS,\n Math.min(\n this.#intervalMs,\n this.#pullRequestReconcileIntervalMs,\n this.#issueReconcileIntervalMs,\n this.#pullRequestDiscoveryIntervalMs,\n ) * 3,\n );\n this.#now = config.now ?? Date.now;\n this.#dispatch = config.dispatch ?? dispatchGithubWebhook;\n this.#sourceControl = config.sourceControl;\n this.#onRepositoriesChanged = config.onRepositoriesChanged;\n this.#repositoryChangesShared = config.repositoryChangesShared ?? (() => true);\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n this.#leaseProvider = getLeaseProvider(deps.pubsub);\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('PlatformGithubEventWorker: call init() before start()');\n\n this.#startedAt = this.#now() - 1;\n this.#settings = normalizeSettings(await this.#storage.settings.get(CURSOR_ORG_ID, CURSOR_USER_ID));\n // Nothing was listening while stopped, and a read that was in flight\n // during stop() may have cached its result after stop() returned.\n this.#repositoryChanges += 1;\n this.#repositories = undefined;\n this.#unsubscribeRepositoryChanges = this.#onRepositoriesChanged?.(() => {\n this.#repositoryChanges += 1;\n this.#repositories = undefined;\n });\n this.#running = true;\n this.deps.logger.debug('Platform GitHub event polling started', {\n intervalMs: this.#intervalMs,\n leaseTtlMs: this.#leaseTtlMs,\n });\n this.#schedule(0);\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n this.#running = false;\n if (this.#timer) clearTimeout(this.#timer);\n this.#timer = undefined;\n this.#stopLeaseRenewal();\n this.#unsubscribeRepositoryChanges?.();\n this.#unsubscribeRepositoryChanges = undefined;\n await this.#inFlight;\n if (this.#hasLease) {\n await this.#leaseProvider.releaseLease(this.#leaseKey(), this.#leaseOwner).catch(() => undefined);\n this.#hasLease = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n #schedule(delayMs: number): void {\n if (!this.#running) return;\n this.#timer = setTimeout(() => {\n this.#timer = undefined;\n const run = this.#tick();\n this.#inFlight = run;\n void run.finally(() => {\n if (this.#inFlight === run) this.#inFlight = undefined;\n });\n }, delayMs);\n this.#timer.unref?.();\n }\n\n async #tick(): Promise<void> {\n let nextDelay = this.#intervalMs;\n try {\n if (!(await this.#ensureLease())) return;\n nextDelay = await this.#poll();\n } catch (error) {\n nextDelay = retryDelay(error, this.#intervalMs);\n this.deps?.logger.error('Platform GitHub event polling cycle failed', {\n error: error instanceof Error ? error.message : String(error),\n retryInMs: nextDelay,\n });\n } finally {\n this.#schedule(nextDelay);\n }\n }\n\n async #ensureLease(): Promise<boolean> {\n if (this.#hasLease) return true;\n const result = await this.#leaseProvider.acquireLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs);\n this.#hasLease = result.acquired;\n if (this.#hasLease) this.#startLeaseRenewal();\n return this.#hasLease;\n }\n\n #startLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) return;\n this.#leaseRenewalTimer = setInterval(\n () => {\n void this.#leaseProvider\n .renewLease(this.#leaseKey(), this.#leaseOwner, this.#leaseTtlMs)\n .then(renewed => {\n if (!renewed) {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n }\n })\n .catch(error => {\n this.#hasLease = false;\n this.#stopLeaseRenewal();\n this.deps?.logger.warn('Platform GitHub event polling lease renewal failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n Math.floor(this.#leaseTtlMs / 3),\n );\n this.#leaseRenewalTimer.unref?.();\n }\n\n #stopLeaseRenewal(): void {\n if (this.#leaseRenewalTimer) clearInterval(this.#leaseRenewalTimer);\n this.#leaseRenewalTimer = undefined;\n }\n\n async #poll(): Promise<number> {\n const repositories = await this.#linkedRepositories();\n let retryInMs = this.#pollEventsEnabled ? this.#intervalMs : this.#reconcileCadence();\n\n if (this.#pollEventsEnabled) {\n for (const repository of repositories) {\n if (!this.#running || !this.#hasLease) break;\n try {\n await this.#pollRepository(repository.id);\n } catch (error) {\n const delay = retryDelay(error, this.#intervalMs);\n retryInMs = Math.max(retryInMs, delay);\n this.deps?.logger.error('Platform GitHub repository event polling failed', {\n repositoryId: repository.id,\n error: error instanceof Error ? error.message : String(error),\n retryInMs: delay,\n });\n if (error instanceof PlatformApiError && error.status === 429) break;\n }\n }\n }\n\n await this.#maybeReconcile(repositories);\n return retryInMs;\n }\n\n #reconcileCadence(): number {\n const cadences = [\n this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : undefined,\n this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : undefined,\n this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : undefined,\n this.#syncDependabotAlerts ? this.#dependabotSyncIntervalMs : undefined,\n ].filter((interval): interval is number => interval !== undefined);\n return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;\n }\n\n async #maybeReconcile(repositories: Repository[]): Promise<void> {\n if (!this.#running || !this.#hasLease) return;\n const now = this.#now();\n const reconcilePullRequests = Boolean(\n this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs,\n );\n const reconcileIssues = Boolean(\n this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs,\n );\n const discoverPullRequests = Boolean(\n this.#discoverPullRequests && now - this.#lastPullRequestDiscoveryAt >= this.#pullRequestDiscoveryIntervalMs,\n );\n const syncDependabot = Boolean(\n this.#syncDependabotAlerts && now - this.#lastDependabotSyncAt >= this.#dependabotSyncIntervalMs,\n );\n if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests && !syncDependabot) return;\n if (syncDependabot) this.#lastDependabotSyncAt = now;\n if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;\n if (reconcileIssues) this.#lastIssueReconcileAt = now;\n if (discoverPullRequests) this.#lastPullRequestDiscoveryAt = now;\n if (reconcilePullRequests || reconcileIssues) await this.#refreshRepositoryNames(repositories);\n\n const targets: ReconcileRepository[] = repositories.flatMap(repository =>\n repository.fullName\n ? [{ id: repository.id, fullName: repository.fullName, installationId: repository.installationId }]\n : [],\n );\n if (targets.length === 0) {\n this.deps?.logger.debug('Platform GitHub reconciliation skipped: no named repositories');\n return;\n }\n\n if (syncDependabot && this.#syncDependabotAlerts && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#syncDependabotAlerts(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub Dependabot sync completed with failures', { ...context, errors });\n } else {\n this.deps?.logger.info('Platform GitHub Dependabot sync completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub Dependabot sync failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcilePullRequests && this.#reconcileFactoryState) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.merged > 0 || counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub pull request reconcile replayed missed merges/closes', context);\n } else {\n this.deps?.logger.info('Platform GitHub pull request reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (discoverPullRequests && this.#discoverPullRequests && this.#hasLease) {\n const startedAt = Date.now();\n try {\n // With the projects it already read, so discovery doesn't read the links again.\n const linked = new Map(repositories.map(repository => [repository.id, repository.projects]));\n const { errors, ...counts } = await this.#discoverPullRequests(\n targets.map(target => ({ ...target, projects: linked.get(target.id) ?? [] })),\n );\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub pull request discovery completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0 || counts.repaired > 0) {\n this.deps?.logger.info('Platform GitHub pull request discovery replayed missed opens', context);\n } else {\n this.deps?.logger.debug('Platform GitHub pull request discovery completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub pull request discovery failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {\n const startedAt = Date.now();\n try {\n const { errors, ...counts } = await this.#reconcileIssuesFactoryState(targets);\n const context = { ...counts, candidateRepositories: targets.length, durationMs: Date.now() - startedAt };\n if (counts.failed > 0) {\n this.deps?.logger.warn('Platform GitHub issue reconcile sweep completed with failures', {\n ...context,\n errors,\n });\n } else if (counts.created > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed missed opens', context);\n } else if (counts.closed > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile replayed closed work items', context);\n } else if (counts.updated > 0) {\n this.deps?.logger.info('Platform GitHub issue reconcile patched stale metadata', context);\n } else {\n this.deps?.logger.debug('Platform GitHub issue reconcile sweep completed', context);\n }\n } catch (error) {\n this.deps?.logger.error('Platform GitHub issue reconcile failed', {\n repositories: targets.length,\n durationMs: Date.now() - startedAt,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async #linkedRepositories(): Promise<Repository[]> {\n const cacheable = Boolean(this.#unsubscribeRepositoryChanges) && this.#repositoryChangesShared();\n if (this.#repositories && cacheable) return this.#repositories;\n const changes = this.#repositoryChanges;\n const repositories = await this.#discoverRepositories();\n // A change announced during the read may be missing from it, so that read\n // is used for this poll only and the next poll reads again.\n this.#repositories = cacheable && changes === this.#repositoryChanges ? repositories : undefined;\n return repositories;\n }\n\n /**\n * Takes each repository's current name from the platform. A rename is not a\n * Factory write, so nothing announces it; the stored slug only catches up\n * when someone lists the installation's repositories again. Runs with the\n * hourly sweeps, one platform call per installation and no storage reads.\n */\n async #refreshRepositoryNames(repositories: Repository[]): Promise<void> {\n for (const installationId of new Set(repositories.map(repository => repository.installationId))) {\n try {\n const { repositories: current } = await this.#client.request<{\n repositories: Array<{ id: number; fullName: string }>;\n }>('GET', `${API_PREFIX}/installations/${installationId}/repositories`);\n const names = new Map(current.map(repository => [repository.id, repository.fullName]));\n for (const repository of repositories) {\n const name = repository.installationId === installationId ? names.get(repository.id) : undefined;\n if (name) repository.fullName = name;\n }\n } catch (error) {\n this.deps?.logger.warn('Platform GitHub repository name refresh failed', {\n installationId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n /**\n * Configured `(installation, repository)` pairs — the same set the\n * reconciler sweeps — resolved to the numeric ids and slug the poll\n * addresses GitHub with. Repositories not linked to any factory project\n * cannot produce work for Factory, so polling and reconciling them is\n * wasted `/events` bandwidth and platform load.\n */\n async #discoverRepositories(): Promise<Repository[]> {\n const keys = await this.#sourceControl.projectRepositories.listConfiguredExternalKeys();\n const repositories = new Map<number, Repository>();\n for (const key of keys) {\n const installationId = Number(key.installationExternalId);\n const repositoryId = Number(key.repositoryExternalId);\n if (\n !Number.isSafeInteger(installationId) ||\n installationId <= 0 ||\n !Number.isSafeInteger(repositoryId) ||\n repositoryId <= 0\n ) {\n continue;\n }\n if (repositories.has(repositoryId)) continue;\n // A configured key exists per project link, so `listByExternalRepository`\n // always yields at least one row; the first row's orgId is enough to\n // look up the repository row for its slug.\n const projects = await this.#sourceControl.projectRepositories.listByExternalRepository(key);\n const orgId = projects[0]?.orgId;\n const repository = orgId\n ? await this.#sourceControl.repositories.findByExternalId({ orgId, externalId: key.repositoryExternalId })\n : null;\n repositories.set(repositoryId, {\n id: repositoryId,\n installationId,\n fullName: repository?.slug,\n projects,\n });\n }\n return [...repositories.values()];\n }\n\n async #pollRepository(repositoryId: number): Promise<void> {\n const key = String(repositoryId);\n if (!this.#settings.repositories[key]) {\n this.#settings.repositories[key] = { afterTimestamp: this.#startedAt };\n await this.#saveSettings();\n }\n\n while (this.#running && this.#hasLease) {\n const cursor: EventCursor = this.#settings.repositories[key]!;\n const query = new URLSearchParams({ limit: String(EVENT_PAGE_SIZE) });\n if ('afterEventId' in cursor) query.set('afterEventId', cursor.afterEventId);\n else query.set('afterTimestamp', String(cursor.afterTimestamp));\n\n const pollStartedAt = performance.now();\n const page = await this.#client.request<{ events: EventLogEntry[]; nextCursor: string | null }>(\n 'GET',\n `${API_PREFIX}/repositories/${repositoryId}/events?${query}`,\n );\n this.deps?.logger.debug('Platform GitHub repository event poll completed', {\n repositoryId,\n eventCount: page.events.length,\n latencyMs: Math.round(performance.now() - pollStartedAt),\n });\n if (page.events.length === 0 || !page.nextCursor) return;\n\n for (const event of page.events) {\n if (!this.#running || !this.#hasLease) return;\n const parsed = parseEvent(event);\n if (!parsed) {\n this.deps?.logger.warn('Platform GitHub event log returned a malformed event', {\n repositoryId,\n eventId: event.id,\n });\n continue;\n }\n if (isFactoryIngestedEvent(parsed)) {\n await this.#ingestFactoryEvent?.(parsed);\n } else {\n this.deps?.logger.debug('Platform GitHub event not forwarded to Factory ingress', {\n repositoryId,\n deliveryId: parsed.deliveryId,\n event: parsed.event,\n action: parsed.payload.action,\n });\n }\n const result = await this.#dispatch(parsed, {\n controller: this.#controller,\n listSubscriptions: (target, options) =>\n listPullRequestSubscriptionsForWebhook(target, options, this.#github.integrationStorage),\n retireSubscription: (id, status) =>\n retirePullRequestSubscription(id, status, this.#github.integrationStorage),\n github: this.#github,\n isAuthorizedSender: notification => this.#isAuthorizedSender(notification),\n onTargetSkipped: subscription => {\n // Routine when a subscription's thread belongs to another\n // deployment, so this stays at debug rather than warning on a loop.\n this.deps?.logger.debug('Platform GitHub event skipped: thread is not held here', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n threadId: subscription.threadId,\n });\n },\n onSenderRejected: notification => {\n this.deps?.logger.debug('Platform GitHub event dropped: sender not authorized', {\n deliveryId: event.deliveryId,\n repository: notification.metadata.repository,\n sender: notification.metadata.sender,\n kind: notification.kind,\n });\n },\n onTargetError: (subscription, error) => {\n this.deps?.logger.error('Platform GitHub event delivery failed for a subscription', {\n deliveryId: event.deliveryId,\n subscriptionId: subscription.id,\n resourceId: subscription.resourceId,\n threadId: subscription.threadId,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n });\n if (result.failed > 0) {\n this.deps?.logger.warn('Platform GitHub event completed with failed subscription deliveries', {\n repositoryId,\n deliveryId: event.deliveryId,\n delivered: result.delivered,\n failed: result.failed,\n });\n }\n }\n\n if (page.nextCursor === ('afterEventId' in cursor ? cursor.afterEventId : undefined)) return;\n this.#settings.repositories[key] = { afterEventId: page.nextCursor };\n await this.#saveSettings();\n }\n }\n\n async #isAuthorizedSender(notification: GithubWebhookNotification): Promise<boolean> {\n if (!AUTHOR_GATED_KINDS.has(notification.kind)) return true;\n const sender = notification.metadata.sender;\n const repository = notification.metadata.repository;\n if (!sender || !repository) return false;\n // Factory's own app has to clear the gate before the bot rules below, which\n // fail closed for every bot that is not explicitly allowlisted. GitHub\n // forbids an app from reviewing its own pull request, so `factory-review`\n // posts its verdict as a comment under this login and that comment is the\n // handoff the authoring agent wakes on.\n if (this.#github.identity?.matches(sender)) return true;\n if (isFactoryAppSender(sender, this.#github.slug)) return true;\n const normalizedSender = sender.toLowerCase();\n const authorizedBots = resolveAuthorizedBots(this.#github.authorizedBots);\n if (authorizedBots.has(normalizedSender)) return true;\n // Any other bot is gated purely by the allowlist: a GitHub App never holds a\n // collaborator permission under its sender login, so falling through to the\n // permission lookup would only fail closed after a wasted API call.\n if (notification.metadata.senderType?.toLowerCase() === 'bot' || normalizedSender.endsWith('[bot]')) {\n return false;\n }\n\n const abortController = new AbortController();\n const timeout = setTimeout(() => abortController.abort(), PERMISSION_CHECK_TIMEOUT_MS);\n try {\n const permission = await this.#github.getRepositoryCollaboratorPermission(\n notification.metadata.installationId,\n repository,\n sender,\n abortController.signal,\n );\n return permission !== undefined && AUTHORIZED_PERMISSIONS.has(permission);\n } catch {\n return false;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n async #saveSettings(): Promise<void> {\n await this.#storage.settings.save(CURSOR_ORG_ID, CURSOR_USER_ID, this.#settings);\n }\n\n #leaseKey(): string {\n return `${this.name}:${this.#storage.integrationId}`;\n }\n}\n\nfunction getLeaseProvider(pubsub: PubSub): LeaseProvider {\n const getProvider = (pubsub as PubSub & { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider;\n if (typeof getProvider === 'function') return getProvider.call(pubsub) ?? NoopLeaseProvider;\n return isLeaseProvider(pubsub) ? pubsub : NoopLeaseProvider;\n}\n\nfunction normalizeSettings(value: PlatformGithubEventWorkerSettings | null): PlatformGithubEventWorkerSettings {\n if (!value || value.version !== 1 || !value.repositories || typeof value.repositories !== 'object') {\n return { version: 1, repositories: {} };\n }\n return { version: 1, repositories: { ...value.repositories } };\n}\n\n// Events the polling worker forwards to the factory rules engine. Closures\n// let the reconciler finalize cards; `synchronize` and `review_requested` on a\n// pull request are the triggers the review board's re-review path listens for;\n// submitted reviews and pull request comments are how review feedback reaches\n// the agent that authored the branch. Direct-webhook consumers ingest every\n// parsed event; the platform path gates because the remaining events (issue\n// edits, comment edits and deletions) only interest the subscription\n// dispatcher, not the factory rules.\nconst ISSUE_INGESTED_ACTIONS = new Set(['opened', 'reopened', 'edited', 'labeled', 'unlabeled']);\n\nfunction isFactoryIngestedEvent(event: ParsedGithubWebhook): boolean {\n if ((event.event === 'issues' || event.event === 'pull_request') && event.payload.action === 'closed') {\n return true;\n }\n if (event.event === 'pull_request') {\n const action = event.payload.action;\n // `opened` is what mints the Review card for a pull request. Without it a\n // factory-authored PR never gets reviewed on the polling path, which is the\n // only path a local deployment has.\n if (action === 'opened' || action === 'synchronize' || action === 'review_requested') return true;\n }\n // Issue opens, reopens, edits and label changes mint and update Work cards.\n // Without them a new issue never becomes a card on the polling path (#24972).\n if (event.event === 'issues' && ISSUE_INGESTED_ACTIONS.has(String(event.payload.action))) return true;\n if (event.event === 'pull_request_review' && event.payload.action === 'submitted') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'created') return true;\n // `factory-review` edits its earlier verdict in place on a re-review. The rules\n // engine only acts on edits that leave a request-changes verdict behind.\n if (event.event === 'pull_request_review' && event.payload.action === 'edited') return true;\n if (event.event === 'issue_comment' && event.payload.action === 'edited') {\n const issue = event.payload.issue;\n if (issue && typeof issue === 'object' && 'pull_request' in issue && issue.pull_request) return true;\n }\n // Default-branch pushes reach the environment build hand-off\n // (`GithubRules` calls the `onRepositoryPush` hook).\n if (event.event === 'push') return true;\n return false;\n}\n\nfunction parseEvent(event: EventLogEntry): ParsedGithubWebhook | null {\n if (\n !event.id ||\n !event.deliveryId ||\n !SUPPORTED_EVENTS.has(event.event) ||\n !event.payload ||\n typeof event.payload !== 'object' ||\n Array.isArray(event.payload)\n ) {\n return null;\n }\n return {\n event: event.event,\n deliveryId: event.deliveryId,\n payload: event.payload as Record<string, unknown>,\n };\n}\n\nfunction retryDelay(error: unknown, fallbackMs: number): number {\n if (error instanceof PlatformApiError && error.status === 429 && error.retryAfterSeconds !== null) {\n return Math.max(fallbackMs, error.retryAfterSeconds * 1_000);\n }\n return fallbackMs;\n}\n"],"mappings":";;;;;;;;AA6BA,MAAM,aAAa;AACnB,MAAM,2BAA2B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AQ;EAC5B,IAAI,SAAS,OAAO,UAAU,YAAY,kBAAkB,SAAS,MAAM,cAAc,OAAO;CAClG;CAGA,IAAI,MAAM,UAAU,QAAQ,OAAO;CACnC,OAAO;AACT;AAEA,SAAS,WAAW,OAAkD;CACpE,IACE,CAAC,MAAM,MACP,CAAC,MAAM,cACP,CAAC,iBAAiB,IAAI,MAAM,KAAK,KACjC,CAAC,MAAM,WACP,OAAO,MAAM,YAAY,YACzB,MAAM,QAAQ,MAAM,OAAO,GAE3B,OAAO;CAET,OAAO;EACL,OAAO,MAAM;EACb,YAAY,MAAM;EAClB,SAAS,MAAM;CACjB;AACF;AAEA,SAAS,WAAW,OAAgB,YAA4B;CAC9D,IAAI,iBAAiB,oBAAoB,MAAM,WAAW,OAAO,MAAM,sBAAsB,MAC3F,OAAO,KAAK,IAAI,YAAY,MAAM,oBAAoB,GAAK;CAE7D,OAAO;AACT"}
@@ -1,11 +1,12 @@
1
1
  import type { RequestContext } from '@mastra/core/request-context';
2
2
  import type { ApiRoute } from '@mastra/core/server';
3
3
  import type { MastraWorker } from '@mastra/core/worker';
4
- import type { Intake } from '../../../capabilities/intake.js';
4
+ import type { Intake, ListIntakeSourcesInput } from '../../../capabilities/intake.js';
5
5
  import type { VersionControl } from '../../../capabilities/version-control.js';
6
6
  import type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';
7
7
  import type { SourceControlStorageHandle } from '../../../storage/domains/source-control/base.js';
8
8
  import type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../../base.js';
9
+ import type { GithubDependabotAlert } from '../../dependabot/sync.js';
9
10
  import { GithubAppIdentity } from '../../github/app-identity.js';
10
11
  import type { GithubEventRules, GithubRuleOverrides } from '../../github/default-rules.js';
11
12
  import type { GithubIntegration, GithubRepositoryPermission, GithubTriageCommentUpsertInput, GithubTriageCommentUpsertResult, RepoSummary } from '../../github/integration.js';
@@ -27,6 +28,17 @@ export declare class PlatformGithubIntegration implements FactoryIntegration {
27
28
  * notifications, merged over the built-in defaults.
28
29
  */
29
30
  readonly authorizedBots: readonly string[];
31
+ /** Dependabot opt-in: its sources are the same repositories; cards arrive through the alert sync, not intake items. */
32
+ readonly additionalIntakes: readonly [{
33
+ readonly id: "dependabot";
34
+ readonly intake: {
35
+ readonly listSources: (input: ListIntakeSourcesInput) => Promise<import("../../../capabilities/intake.js").IntakeSource[]>;
36
+ readonly listItems: () => Promise<{
37
+ items: never[];
38
+ nextCursor: null;
39
+ }>;
40
+ };
41
+ }];
30
42
  readonly intake: Intake;
31
43
  readonly versionControl: VersionControl;
32
44
  constructor(options?: {
@@ -55,7 +67,14 @@ export declare class PlatformGithubIntegration implements FactoryIntegration {
55
67
  orgId: string;
56
68
  projectRepositoryId: string;
57
69
  }): Promise<void>;
70
+ hasActiveConnections(): Promise<boolean>;
58
71
  workers(ctx: IntegrationContext): MastraWorker[];
72
+ /** Lists a repository's Dependabot alerts in one state through the Platform GitHub proxy. */
73
+ listDependabotAlerts(input: {
74
+ installationId: number;
75
+ repository: string;
76
+ state: 'open' | 'closed';
77
+ }): Promise<GithubDependabotAlert[]>;
59
78
  /**
60
79
  * Reads live PR state through the Platform GitHub proxy for the merge
61
80
  * reconciler. Returns undefined when the PR cannot be resolved (missing,
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAIxD,OAAO,KAAK,EAEV,MAAM,EAIP,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EA2BV,cAAc,EACf,MAAM,0CAA0C,CAAC;AAElD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAC9F,OAAO,KAAK,EAEV,0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AAQ,EAAE,MAAM,EAChB,MAAM,CAAC,EAAE,WAAW,GACnB,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAoCjD;IAEK,qBAAqB,CAAC,cAAc,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAyBzG;IAED;;;OAGG;IACG,mBAAmB,CAAC,cAAc,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAGnG;IAEK,qBAAqB,CAAC,cAAc,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAWnE;IAEK,cAAc,CAClB,eAAe,EAAE,MAAM,EACvB,QAAQ,EAAE,MAAM,EAChB,WAAW,EAAE,MAAM,EACnB,MAAM,EAAE,MAAM,EAAE,GACf,OAAO,CAAC,MAAM,EAAE,CAAC,CAOnB;IAEK,gBAAgB,CAAC,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAOnH;IAED,sBAAsB,CAAC,eAAe,EAAE,MAAM,GAAG,UAAU,CAAC,iBAAiB,CAAC,wBAAwB,CAAC,CAAC,CAYvG;CAoaF"}
@@ -1,4 +1,6 @@
1
1
  import { loose } from "../../../routes/route.js";
2
+ import { attachDependabotRules } from "../../dependabot/rules.js";
3
+ import { createDependabotSync } from "../../dependabot/sync.js";
2
4
  import { GithubAppIdentity } from "../../github/app-identity.js";
3
5
  import { resolveGithubRules } from "../../github/default-rules.js";
4
6
  import { attachGithubIssueReconciler } from "../../github/issue-reconciler.js";
@@ -8,7 +10,7 @@ import { attachGithubPullRequestDiscovery, attachGithubReconciler, attachGithubR
8
10
  import { createGithubSubscriptionTools, parseCreatedPullRequest, subscribeCurrentSessionToPullRequest } from "../../github/session-subscriptions.js";
9
11
  import { settleOrAbort } from "../../github/settle-or-abort.js";
10
12
  import { parseAuthorizedBotsEnv } from "../../github/webhook.js";
11
- import { PlatformApiClient, PlatformApiError, logPlatformInfo, logPlatformWarn, platformApiClientConfigFromEnv } from "../api-client.js";
13
+ import { PlatformApiClient, PlatformApiError, logPlatformBootInfo, logPlatformInfo, logPlatformWarn, platformApiClientConfigFromEnv } from "../api-client.js";
12
14
  import { PlatformGithubEventWorker } from "./event-worker.js";
13
15
  import { registerApiRoute } from "@mastra/core/server";
14
16
  import { Octokit } from "@octokit/rest";
@@ -24,6 +26,8 @@ function githubStatusReason(hasUsableInstallation, hiddenPersonalInstallReason)
24
26
  const PAGE_SIZE = 30;
25
27
  const OPEN_ISSUE_DISCOVERY_MAX_PAGES = 5;
26
28
  const API_PREFIX = "/v1/server";
29
+ /** Intake config id that opts repositories into Dependabot alert sync. */
30
+ const DEPENDABOT_INTAKE_ID = "dependabot";
27
31
  const CHECK_TITLE_LIMIT = 255;
28
32
  const CHECK_TEXT_LIMIT = 65535;
29
33
  /**
@@ -138,6 +142,17 @@ var PlatformGithubIntegration = class {
138
142
  #collaboratorPermissionCache = /* @__PURE__ */ new Map();
139
143
  /** Same key → lookup already in flight, so overlapping callers share one request. */
140
144
  #collaboratorPermissionInFlight = /* @__PURE__ */ new Map();
145
+ /** Dependabot opt-in: its sources are the same repositories; cards arrive through the alert sync, not intake items. */
146
+ additionalIntakes = [{
147
+ id: DEPENDABOT_INTAKE_ID,
148
+ intake: {
149
+ listSources: (input) => this.intake.listSources(input),
150
+ listItems: async () => ({
151
+ items: [],
152
+ nextCursor: null
153
+ })
154
+ }
155
+ }];
141
156
  intake = {
142
157
  resolveIntakeDispatch: (input) => this.#resolveIntakeDispatch(input),
143
158
  listSources: async ({ orgId, userId }) => {
@@ -226,6 +241,7 @@ var PlatformGithubIntegration = class {
226
241
  sourceId,
227
242
  title: pullRequest.title,
228
243
  status: pullRequest.state,
244
+ labels: pullRequest.labels,
229
245
  createdAt: pullRequest.createdAt,
230
246
  updatedAt: pullRequest.updatedAt,
231
247
  metadata: {
@@ -502,7 +518,7 @@ var PlatformGithubIntegration = class {
502
518
  }
503
519
  initialize({ storage }) {
504
520
  this.#integrationStorage = storage;
505
- logPlatformInfo("Platform GitHub integration initialized", {
521
+ logPlatformBootInfo("Platform GitHub integration initialized", {
506
522
  endpointHost: this.#endpointHost,
507
523
  pollingEnabled: this.#pollingEnabled,
508
524
  pollingIntervalMs: this.#pollingIntervalMs,
@@ -653,6 +669,9 @@ var PlatformGithubIntegration = class {
653
669
  };
654
670
  }
655
671
  }
672
+ async hasActiveConnections() {
673
+ return (await this.#client.request("GET", `${API_PREFIX}/github-app/installations`)).installations.some((installation) => installation.usable && !installation.suspendedAt);
674
+ }
656
675
  async #syncInstallations(orgId, userId) {
657
676
  const result = await this.#client.request("GET", `${API_PREFIX}/github-app/installations`);
658
677
  const usableInstallations = result.installations.filter((installation) => installation.usable && !installation.suspendedAt);
@@ -680,6 +699,7 @@ var PlatformGithubIntegration = class {
680
699
  ingestFactoryEvent: attachGithubRules(this, ctx),
681
700
  reconcileFactoryState: this.#pullRequestReconcileEnabled ? attachGithubReconciler(this, ctx, (input) => this.fetchPullRequestState(input)) : void 0,
682
701
  discoverPullRequests: this.#pullRequestReconcileEnabled ? attachGithubPullRequestDiscovery(this, ctx, openPullRequestLister(this.versionControl)) : void 0,
702
+ syncDependabotAlerts: this.#issueReconcileEnabled ? this.#dependabotSync(ctx) : void 0,
683
703
  reconcileIssuesFactoryState: this.#issueReconcileEnabled ? attachGithubIssueReconciler(this, ctx, (input) => this.fetchIssueState(input), (input) => this.listOpenIssueStates(input)) : void 0,
684
704
  pollEventsEnabled: this.#pollingEnabled,
685
705
  intervalMs: this.#pollingIntervalMs,
@@ -692,9 +712,40 @@ var PlatformGithubIntegration = class {
692
712
  listByExternalRepository: (args) => this.storage.projectRepositories.listByExternalRepository(args)
693
713
  },
694
714
  repositories: { findByExternalId: (args) => this.storage.repositories.findByExternalId(args) }
695
- }
715
+ },
716
+ onRepositoriesChanged: (listener) => this.storage.onLinkedRepositoriesChanged(listener),
717
+ repositoryChangesShared: () => this.storage.linkedRepositoryChangesShared()
696
718
  })];
697
719
  }
720
+ #dependabotSync(ctx) {
721
+ const ingest = attachDependabotRules(ctx);
722
+ if (!ingest) return void 0;
723
+ return createDependabotSync({
724
+ listAlerts: (input) => this.listDependabotAlerts(input),
725
+ listProjects: (args) => this.storage.projectRepositories.listByExternalRepository(args),
726
+ repositoryEnabled: async ({ orgId, repository }) => {
727
+ const config = (await ctx.storage.intake.getConfig({
728
+ orgId,
729
+ integrationIds: [DEPENDABOT_INTAKE_ID]
730
+ }))[DEPENDABOT_INTAKE_ID];
731
+ return Boolean(config?.enabled && config.sourceIds?.includes(repository));
732
+ },
733
+ ingest,
734
+ userId: "factory-rule-dispatcher"
735
+ });
736
+ }
737
+ /** Lists a repository's Dependabot alerts in one state through the Platform GitHub proxy. */
738
+ async listDependabotAlerts(input) {
739
+ const { owner, repo } = splitRepository(input.repository);
740
+ const state = input.state === "open" ? "open" : "fixed,dismissed,auto_dismissed";
741
+ const query = new URLSearchParams({
742
+ state,
743
+ per_page: "100",
744
+ sort: "updated",
745
+ direction: "desc"
746
+ });
747
+ return (await this.#client.request("GET", `${API_PREFIX}/github/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/dependabot/alerts?${query}`)).alerts;
748
+ }
698
749
  /**
699
750
  * Reads live PR state through the Platform GitHub proxy for the merge
700
751
  * reconciler. Returns undefined when the PR cannot be resolved (missing,