@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 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/gitlab/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n cardBoardFlow,\n eventBoardId,\n isTerminalWorkItem,\n cardOwnsBranch,\n newestOwnedOpenPullRequestNumber,\n pullRequestSources,\n intakeTarget,\n rulePhaseField,\n withBoardClosure,\n withBoardFlow,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, hasExplicitRuleOverride, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type {\n FactoryGitLabEventName,\n FactoryGitLabRuleContext,\n FactoryPullRequestHome,\n FactoryRuleIntakeTarget,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactorySignalActivityDecision,\n} from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type {\n ExternalRepositoryProjectTarget,\n SourceControlStorageHandle,\n} from '../../storage/domains/source-control/base.js';\nimport { WorkItemUpdateConflictError } from '../../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { closingIssueNumbers } from '../closing-references.js';\nimport { recordPullRequestHead } from '../pull-request-head.js';\nimport type { GitLabEventRules } from './default-rules.js';\nimport { decodeIssueReference, encodeIssueReference, encodeSourceId, GITLAB_TRUSTED_ACCESS_LEVEL } from './integration.js';\nimport type { ParsedGitLabWebhook } from './webhook.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\ntype IngressStatus = 'ignored' | 'committed' | 'replayed' | 'missing';\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\n/** GitLab sends `2024-01-02T03:04:05Z`, `2024-01-02 03:04:05 UTC` or `2024-01-02 03:04:05 +0000`. */\nfunction timestamp(value: unknown): number | undefined {\n const text = string(value);\n if (!text) return undefined;\n const spaced = /^(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?) (?:UTC|([+-]\\d{2}):?(\\d{2}))$/.exec(text);\n const parsed = Date.parse(\n spaced ? `${spaced[1]}T${spaced[2]}${spaced[3] ? `${spaced[3]}:${spaced[4]}` : 'Z'}` : text,\n );\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\nfunction boolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction usernames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(entry => {\n const username = string(object(entry)?.username);\n return username ? [username] : [];\n });\n}\n\nfunction labelNames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(entry => {\n if (typeof entry === 'string') return entry ? [entry] : [];\n const title = string(object(entry)?.title) ?? string(object(entry)?.name);\n return title ? [title] : [];\n });\n}\n\nfunction labelColors(value: unknown): Record<string, string> {\n if (!Array.isArray(value)) return {};\n return Object.fromEntries(\n value.flatMap(entry => {\n const label = object(entry);\n const name = string(label?.title) ?? string(label?.name);\n const color = string(label?.color);\n return name && color ? [[name, color]] : [];\n }),\n );\n}\n\n/**\n * Points the card's session at a new comment on its issue, or at an edit to\n * the issue's title or description. Only pointers travel (who, where, a link).\n * An edited comment (a Note Hook with action `update`, GitLab 16.11+) is no new comment.\n * GitLab deliveries don't say whether Factory wrote the comment, so the\n * message waits in the session's notifications instead of waking it: a session\n * that comments must not wake itself.\n */\nexport function activitySignalFor(\n context: Pick<FactoryGitLabRuleContext, 'event' | 'item' | 'actor' | 'ingress' | 'repository' | 'issue' | 'note'>,\n delivery: { edited: boolean; noteEdited: boolean },\n): FactorySignalActivityDecision | undefined {\n const event =\n context.event === 'issueCommented' && !delivery.noteEdited\n ? ('work_item.commented' as const)\n : context.event === 'issueUpdated' && delivery.edited\n ? ('work_item.edited' as const)\n : undefined;\n if (!event || !context.item || !context.issue) return undefined;\n if (context.actor.type !== 'gitlab' || context.actor.factoryAuthored) return undefined;\n return {\n type: 'signalActivity',\n idempotencyKey: `${context.ingress.id}:activity`,\n event,\n reference: `${context.repository.fullName}#${context.issue.number}`,\n url: (event === 'work_item.commented' ? context.note?.url : undefined) ?? context.issue.url,\n ...(context.actor.username ? { author: context.actor.username } : {}),\n authorTrusted: context.actor.trusted,\n idleBehavior: 'persist',\n };\n}\n\n/** The status change a GitLab delivery reports. GitLab gives no close reason, so every close is completed. */\nexport function boardEventFor(context: Pick<FactoryGitLabRuleContext, 'event'>): BoardEventFacts | undefined {\n switch (context.event) {\n case 'issueOpened':\n return { type: 'work_item.created' };\n case 'issueReopened':\n return { type: 'work_item.reopened' };\n case 'issueClosed':\n return { type: 'work_item.closed', reason: closeReason(false) };\n default:\n return undefined;\n }\n}\n\nfunction eventName(parsed: ParsedGitLabWebhook): FactoryGitLabEventName | undefined {\n const attributes = object(parsed.payload.object_attributes);\n const action = string(attributes?.action)?.toLowerCase();\n if (parsed.event === 'Issue Hook') {\n if (action === 'open') return 'issueOpened';\n if (action === 'reopen') return 'issueReopened';\n if (action === 'close') return 'issueClosed';\n return 'issueUpdated';\n }\n if (parsed.event === 'Note Hook') {\n const noteableType = string(attributes?.noteable_type);\n if (noteableType === 'Issue') return 'issueCommented';\n if (noteableType === 'MergeRequest') return 'mergeRequestCommented';\n return;\n }\n if (parsed.event !== 'Merge Request Hook') return;\n if (action === 'open' || action === 'reopen') return 'mergeRequestOpened';\n if (action === 'merge') return 'mergeRequestMerged';\n if (action === 'close') return 'mergeRequestClosed';\n return 'mergeRequestUpdated';\n}\n\n/**\n * A card filed for an issue in a different GitLab project than `projectId` on `host`. Branch\n * names repeat across projects, so a card attributed elsewhere never owns this project's branch.\n * A card with no GitLab issue of its own can't be attributed, and isn't.\n */\nfunction cardInOtherGitLabProject(item: Card, host: string, projectId: number): boolean {\n if (item.externalSource?.integrationId !== 'gitlab' || item.externalSource.type !== 'issue') return false;\n const reference = decodeIssueReference(item.externalSource.externalId);\n if (!reference) return false;\n return (\n reference.projectId !== String(projectId) || (reference.host !== undefined && normalizeHost(reference.host) !== host)\n );\n}\n\nfunction normalizeHost(host: string): string {\n return host.trim().toLowerCase().replace(/\\.$/, '');\n}\n\nfunction hostFromPayload(parsed: ParsedGitLabWebhook): string | undefined {\n const declaredHost = parsed.instanceHost ? normalizeHost(parsed.instanceHost) : undefined;\n const projectUrl = string(object(parsed.payload.project)?.web_url);\n if (!projectUrl) return declaredHost;\n try {\n const payloadHost = normalizeHost(new URL(projectUrl).host);\n if (declaredHost && declaredHost !== payloadHost) return undefined;\n return payloadHost;\n } catch {\n return undefined;\n }\n}\n\n/** Whether a card carries the merge request as a source attached to its issue, rather than as its own card. */\nfunction carriesAttachedMergeRequest(item: Card, mergeRequestKey: string): boolean {\n return (\n item.externalSource?.type !== 'pull-request' &&\n pullRequestSources(item).some(source => source.integrationId === 'gitlab' && source.externalId === `pull-request:${mergeRequestKey}`)\n );\n}\n\nfunction mergeRequestSourceKey(host: string, projectId: number, mergeRequestIid: number): string {\n return `gitlab-pr:${Buffer.from(JSON.stringify({ version: 1, host, projectId, mergeRequestIid }), 'utf8').toString('base64url')}`;\n}\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface GitLabRulesIntegration {\n readonly rules: GitLabEventRules;\n resolveActiveConnectionForHost?(storedConnectionId: string, host: string): Promise<string>;\n getProjectMemberAccessLevel(connectionId: string, projectId: string, username: string): Promise<number | undefined>;\n getWorkItemAuthorUsername(\n connectionId: string,\n projectId: string,\n kind: 'issue' | 'merge_request',\n iid: number,\n ): Promise<string | undefined>;\n}\n\ninterface GitLabRulesOptions {\n gitlab: GitLabRulesIntegration;\n sourceControl: SourceControlStorageHandle;\n projects: FactoryProjectsStorage;\n storage: WorkItemsStorage;\n intake: IntakeStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n}\n\ninterface ProjectTarget {\n target: ExternalRepositoryProjectTarget;\n connectionIds: string[];\n}\n\nexport class GitLabRules {\n constructor(private readonly options: GitLabRulesOptions) {}\n\n /** Brings the project's boards up to date, so the sync reads below see its stored boards. */\n async loadBoards(scope: StoredBoardScope): Promise<void> {\n await toBoardSource(this.options.boards).load(scope);\n }\n\n /** The project's loaded boards; {@link loadBoards} runs before an event is handled. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(parsed: ParsedGitLabWebhook): Promise<{ status: IngressStatus }> {\n const event = eventName(parsed);\n const project = object(parsed.payload.project);\n const projectId = number(project?.id);\n const projectPath = string(project?.path_with_namespace);\n const host = hostFromPayload(parsed);\n const username = string(parsed.payload.user_username) ?? string(object(parsed.payload.user)?.username);\n if (!event || !projectId || !projectPath || !host || !username) return { status: 'ignored' };\n\n const targets = await this.#targets(String(projectId), host);\n if (targets.length === 0) return { status: 'ignored' };\n const results: Array<{ status: IngressStatus }> = [];\n for (const target of targets) {\n await this.loadBoards(target.target);\n results.push(await this.#ingestProject(parsed, event, projectId, projectPath, host, username, target));\n }\n if (results.some(result => result.status === 'committed')) return { status: 'committed' };\n if (results.some(result => result.status === 'replayed')) return { status: 'replayed' };\n return results[0] ?? { status: 'ignored' };\n }\n\n async #targets(repositoryExternalId: string, host: string): Promise<ProjectTarget[]> {\n const grouped = new Map<string, ProjectTarget>();\n const keys = (await this.options.sourceControl.projectRepositories.listConfiguredExternalKeys()).filter(\n key => key.repositoryExternalId === repositoryExternalId,\n );\n for (const key of keys) {\n const targets = await this.options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: key.installationExternalId,\n repositoryExternalId,\n });\n for (const target of targets) {\n const installation = await this.options.sourceControl.installations.findByExternalId({\n orgId: target.orgId,\n externalId: key.installationExternalId,\n });\n const installationHost = string(installation?.providerMetadata.host);\n if (!installationHost || normalizeHost(installationHost) !== normalizeHost(host)) continue;\n const id = `${target.orgId}:${target.factoryProjectId}`;\n const current = grouped.get(id);\n if (current) {\n if (!current.connectionIds.includes(key.installationExternalId)) {\n current.connectionIds.push(key.installationExternalId);\n }\n } else {\n grouped.set(id, { target, connectionIds: [key.installationExternalId] });\n }\n }\n }\n return [...grouped.values()];\n }\n\n async #ingestProject(\n parsed: ParsedGitLabWebhook,\n event: FactoryGitLabEventName,\n projectId: number,\n projectPath: string,\n host: string,\n username: string,\n target: ProjectTarget,\n ): Promise<{ status: IngressStatus }> {\n const factoryProject = await this.options.projects.get({\n orgId: target.target.orgId,\n id: target.target.factoryProjectId,\n });\n if (!factoryProject) return { status: 'missing' };\n\n const sourceId = encodeSourceId({ host, projectId: String(projectId) });\n const config = await this.options.intake.getConfig({\n orgId: target.target.orgId,\n integrationIds: ['gitlab'],\n });\n if (!config.gitlab?.enabled || !config.gitlab.sourceIds?.includes(sourceId)) return { status: 'ignored' };\n const binding = (\n await this.options.intake.listBindings({ orgId: target.target.orgId, integrationId: 'gitlab' })\n ).find(\n candidate => candidate.sourceId === sourceId && candidate.factoryProjectId === target.target.factoryProjectId,\n );\n if (!binding) return { status: 'ignored' };\n\n const connectionIds = [\n ...new Set(\n await Promise.all(\n target.connectionIds.map(\n connectionId => this.options.gitlab.resolveActiveConnectionForHost?.(connectionId, host) ?? connectionId,\n ),\n ),\n ),\n ];\n\n const attributes = object(parsed.payload.object_attributes);\n const issue = parsed.event === 'Note Hook' ? object(parsed.payload.issue) : attributes;\n const mergeRequest = parsed.event === 'Note Hook' ? object(parsed.payload.merge_request) : attributes;\n const issueIid = number(issue?.iid);\n const mergeRequestIid = number(mergeRequest?.iid);\n const issueSourceKey = issueIid\n ? encodeIssueReference({ host, projectId: String(projectId), issueIid })\n : undefined;\n const mergeRequestKey = mergeRequestIid ? mergeRequestSourceKey(host, projectId, mergeRequestIid) : undefined;\n // A finished card may still be only in the legacy table; copy it so the event finds it.\n await this.options.storage.copyLegacyCards({\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n sources: [\n ...(issueSourceKey ? [{ integrationId: 'gitlab', type: 'issue', externalId: issueSourceKey }] : []),\n ...(mergeRequestKey ? [{ integrationId: 'gitlab', type: 'pull-request', externalId: mergeRequestKey }] : []),\n ],\n });\n // The shared list is the cache itself: only the cards handed on to rules are cloned.\n const items = await this.options.storage.listShared({\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n });\n const own = (card: Card | undefined) => card && structuredClone(card);\n const issueItem = issueSourceKey\n ? own(\n items.find(\n item =>\n item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === issueSourceKey,\n ),\n )\n : undefined;\n const reviewItem = mergeRequestKey\n ? own(\n items.find(\n item =>\n item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === mergeRequestKey,\n ),\n )\n : undefined;\n // A merge request attached to its issue's card, instead of filed on a card of its own.\n const attachedItem =\n mergeRequestKey && !reviewItem\n ? own(items.find(item => carriesAttachedMergeRequest(item, mergeRequestKey)))\n : undefined;\n const headBranch = string(mergeRequest?.source_branch) ?? '';\n // A card whose session builds on the merge request's branch, in this project.\n const buildsOnBranch = (item: Card) =>\n item.externalSource?.type !== 'pull-request' &&\n !cardInOtherGitLabProject(item, host, projectId) &&\n Object.values(item.sessions).some(session => session.branch === headBranch);\n const authoringItem = headBranch ? own(items.find(buildsOnBranch)) : undefined;\n const actorTrusted = await this.#trusted(connectionIds, String(projectId), username);\n const eventUserId = number(object(parsed.payload.user)?.id) ?? number(parsed.payload.user_id);\n const resolveAuthor = async (\n item: Record<string, unknown> | undefined,\n kind: 'issue' | 'merge_request',\n iid: number | undefined,\n ): Promise<string | undefined> => {\n if (!item || !iid) return undefined;\n const embedded = string(object(item.author)?.username);\n if (embedded) return embedded;\n if (eventUserId && eventUserId === number(item.author_id)) return username;\n for (const connectionId of connectionIds) {\n try {\n const resolved = await this.options.gitlab.getWorkItemAuthorUsername(\n connectionId,\n String(projectId),\n kind,\n iid,\n );\n if (resolved) return resolved;\n } catch {\n // Another active credential may cover this project; otherwise leave author trust unset.\n }\n }\n return undefined;\n };\n const [issueAuthor, mergeRequestAuthor] = await Promise.all([\n resolveAuthor(issue, 'issue', issueIid),\n resolveAuthor(mergeRequest, 'merge_request', mergeRequestIid),\n ]);\n const authorTrusted = async (author: string | undefined): Promise<boolean> => {\n if (!author) return false;\n return author === username ? actorTrusted : this.#trusted(connectionIds, String(projectId), author);\n };\n const [issueAuthorTrusted, mergeRequestAuthorTrusted] = await Promise.all([\n authorTrusted(issueAuthor),\n authorTrusted(mergeRequestAuthor),\n ]);\n const actor: FactoryRuleActor = {\n type: 'gitlab',\n username,\n trusted: actorTrusted,\n factoryAuthored: false,\n };\n // A merge request seen for the first time is filed on the card whose branch it comes from,\n // when its board reviews merge requests. Otherwise a trusted author's merge request names the card of the issue\n // its description says it closes, and the project's intake routes decide, when it is filed,\n // whether it joins that card. An untrusted author's merge request never lands on another card.\n // A card with no source of its own (a manual card) never takes one: the merge request would\n // become its only source and turn it into a merge request card. A GitHub card keeps only\n // GitHub pull requests, so a merge request on its session's branch gets its own card.\n const eligibleHome = (card: Card) =>\n card.externalSource !== null &&\n card.externalSource.integrationId !== 'github' &&\n card.externalSource.type !== 'pull-request' &&\n !isTerminalWorkItem(this.#boards(card), card);\n let home: { card: Card; reason: FactoryPullRequestHome['reason'] } | undefined;\n if (event === 'mergeRequestOpened' && mergeRequestKey && !reviewItem && !attachedItem) {\n // A branch name alone is not proof: a fork can reuse it. The Factory's own merge requests come\n // from this project under a trusted account.\n const sourceProjectId = number(mergeRequest?.source_project_id);\n const fromThisProject = sourceProjectId === undefined || sourceProjectId === projectId;\n if (\n authoringItem &&\n fromThisProject &&\n (actorTrusted || mergeRequestAuthorTrusted) &&\n eligibleHome(authoringItem) &&\n cardBoardFlow(this.#boards(authoringItem), authoringItem).pullRequestReview !== undefined\n ) {\n home = { card: authoringItem, reason: 'authored' };\n } else if (mergeRequestAuthorTrusted) {\n for (const iid of closingIssueNumbers(string(mergeRequest?.description), {\n provider: 'gitlab',\n repository: projectPath,\n })) {\n const key = encodeIssueReference({ host, projectId: String(projectId), issueIid: iid });\n const card = items.find(\n item =>\n item.externalSource?.integrationId === 'gitlab' &&\n item.externalSource.externalId === key &&\n eligibleHome(item),\n );\n if (card) {\n home = { card, reason: 'closes' };\n break;\n }\n }\n }\n }\n const pullRequestHome: FactoryPullRequestHome | undefined = home\n ? { workItemId: home.card.id, reason: home.reason }\n : undefined;\n // An attached merge request's state lives on its own source, never the issue's.\n if ((event === 'mergeRequestMerged' || event === 'mergeRequestClosed') && attachedItem && mergeRequestKey) {\n const merged = event === 'mergeRequestMerged';\n await this.options.storage.syncWorkItemSource({\n orgId: attachedItem.orgId,\n factoryProjectId: attachedItem.factoryProjectId,\n provider: 'gitlab',\n externalId: `pull-request:${mergeRequestKey}`,\n patch: { state: merged ? 'merged' : 'closed', metadata: { state: 'closed', merged } },\n });\n }\n\n // A push moves the head a recorded review verdict was given on. Recording\n // the new head lets the verdict badge show that it is outdated, while the\n // verdict itself stays so the next pass still runs as a re-review. It is\n // recorded before the push is evaluated: the dispatcher can apply the\n // re-review transition as soon as it commits, and the pass it starts names\n // the head it covers, which must be the pushed one.\n const lastCommit = object(mergeRequest?.last_commit);\n const headSha = string(lastCommit?.id)?.toLowerCase();\n // Without an update time the commit time still orders the push; dropping\n // the write would leave the pass naming the head the last verdict covered.\n const headAt = timestamp(mergeRequest?.updated_at) ?? timestamp(lastCommit?.timestamp);\n const unchangedListedHead =\n parsed.deliveryId.startsWith('poll:merge-request-head:') &&\n headAt !== undefined &&\n reviewItem?.metadata?.pullRequestHeadSha === headSha &&\n (reviewItem?.metadata?.pullRequestHeadAt !== headAt ||\n reviewItem?.metadata?.pullRequestHeadDeliveryId !== parsed.deliveryId);\n let pushedReviewItem = reviewItem;\n if (event === 'mergeRequestUpdated' && headSha && attachedItem && mergeRequestIid) {\n await recordPullRequestHead(this.options.storage, {\n orgId: attachedItem.orgId,\n id: attachedItem.id,\n headSha,\n headAt,\n ownedPullRequestNumber: mergeRequestIid,\n });\n if (unchangedListedHead) return { status: 'ignored' };\n }\n if (event === 'mergeRequestUpdated' && headSha && reviewItem) {\n const parent = items.find(item => item.id === reviewItem.parentWorkItemId);\n // The authoring Work item mirrors the verdict of the merge request it has\n // out; a push to an older one must not mark its successor's verdict.\n await recordPullRequestHead(this.options.storage, {\n orgId: reviewItem.orgId,\n id: reviewItem.id,\n headSha,\n headAt,\n deliveryId: parsed.deliveryId.startsWith('poll:merge-request-head:') ? parsed.deliveryId : undefined,\n });\n if (parent) {\n await recordPullRequestHead(this.options.storage, {\n orgId: parent.orgId,\n id: parent.id,\n headSha,\n headAt,\n ownedPullRequestNumber: mergeRequestIid,\n });\n }\n pushedReviewItem = (await this.options.storage.get({ orgId: reviewItem.orgId, id: reviewItem.id })) ?? reviewItem;\n if (unchangedListedHead) return { status: 'ignored' };\n }\n const ownItem = reviewItem ?? attachedItem;\n const openedItem = (home?.reason === 'authored' ? home.card : undefined) ?? authoringItem;\n const candidates: Array<Card | undefined> =\n event === 'mergeRequestMerged'\n ? [...new Map([ownItem, authoringItem].filter(Boolean).map(item => [item!.id, item!])).values()]\n : event === 'mergeRequestCommented'\n ? [authoringItem ?? ownItem]\n : event === 'mergeRequestOpened'\n ? [openedItem, ...(openedItem ? [openedItem] : [])]\n : event.startsWith('mergeRequest')\n ? [pushedReviewItem ?? attachedItem ?? authoringItem]\n : [issueItem];\n const results = [];\n for (const [index, item] of candidates.entries()) {\n results.push(\n await this.#evaluate({\n parsed,\n event,\n projectId,\n projectPath,\n host,\n actor,\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n factoryProject,\n board: intakeTarget(this.#boards(target.target)),\n issue,\n issueAuthor,\n issueAuthorTrusted,\n issueIid,\n issueSourceKey,\n mergeRequest,\n mergeRequestAuthor,\n mergeRequestAuthorTrusted,\n mergeRequestIid,\n mergeRequestKey,\n factoryAuthored: Boolean(authoringItem),\n item,\n ...(pullRequestHome ? { pullRequestHome } : {}),\n ingressIdentity: `gitlab:${projectId}:${parsed.deliveryId}${index ? `:${item?.id ?? index}` : ''}`,\n // A merge request opening concerns two cards: its own card,\n // which the integration handler files against the authoring item,\n // and that authoring item, which its board may react to. The second\n // evaluation runs only the board handler, under an id-suffixed\n // identity so it is not dropped as a replay of the first.\n ...(event === 'mergeRequestOpened' ? { mergeRequestOpenedScope: index ? ('board' as const) : ('intake' as const) } : {}),\n }),\n );\n }\n // The authoring Work item records which merge request it has out, so the\n // Work transition policy keeps an agent from closing the work while it is\n // open. Sessions carry no repository, so a branch shared by two Work cards\n // is ambiguous and records nothing.\n const branchOwners = headBranch ? items.filter(buildsOnBranch) : [];\n // A merge request filed on its issue's card is tracked there the same way.\n const trackedItem = attachedItem ?? (branchOwners.length === 1 ? authoringItem : undefined);\n if (trackedItem && mergeRequestIid) {\n await this.#trackOpenMergeRequest({\n orgId: trackedItem.orgId,\n id: trackedItem.id,\n event,\n mergeRequestIid,\n eventAt: timestamp(mergeRequest?.updated_at),\n opened: string(mergeRequest?.state) === 'opened' && (actorTrusted || mergeRequestAuthorTrusted),\n headSha: string(object(mergeRequest?.last_commit)?.id)?.toLowerCase(),\n // Only a merge request the card wrote is the one it has out. One filed there because it\n // closes the issue is someone else's work: recording it would stop the builder's own\n // self-review and merge request.\n ownedByCard: trackedItem.id !== attachedItem?.id || cardOwnsBranch(trackedItem, headBranch),\n });\n }\n if (results.some(result => result.status === 'committed')) return { status: 'committed' };\n if (results.some(result => result.status === 'replayed')) return { status: 'replayed' };\n return results[0] ?? { status: 'ignored' };\n }\n\n /**\n * Records or clears the merge request a Work card has out. Each merge\n * request's last applied event time is kept on the card, so an opening that\n * is older than a close already applied (a replay, or a close delivered\n * first) is ignored, while a genuine reopen is newer and records it again.\n */\n async #trackOpenMergeRequest(input: {\n orgId: string;\n id: string;\n event: string;\n mergeRequestIid: number;\n eventAt: number | undefined;\n opened: boolean;\n headSha: string | undefined;\n ownedByCard: boolean;\n }): Promise<void> {\n const settling = input.event === 'mergeRequestMerged' || input.event === 'mergeRequestClosed';\n if (input.event !== 'mergeRequestOpened' && !settling) return;\n const key = String(input.mergeRequestIid);\n for (let attempt = 0; attempt < 3; attempt++) {\n const item = await this.options.storage.get({ orgId: input.orgId, id: input.id });\n if (!item) return;\n const events = object(item.metadata?.mergeRequestEvents) ?? {};\n const last = object(events[key]);\n const lastAt = number(last?.at);\n if (input.eventAt !== undefined && lastAt !== undefined && lastAt >= input.eventAt) return;\n // Without a timestamp, only an opening that no close has settled is trusted.\n if (input.eventAt === undefined && !settling && last?.open === false) return;\n if (!settling && !input.opened) return;\n const recorded = item.metadata?.openPullRequestNumber;\n const patch: Record<string, unknown> = {\n mergeRequestEvents: { ...events, [key]: { at: input.eventAt ?? lastAt ?? null, open: !settling } },\n };\n if (!settling && input.ownedByCard) {\n // A head recorded for an earlier merge request must not mark this one's\n // verdict outdated. A replayed opening of the merge request already\n // recorded keeps the head its pushes left.\n if (recorded !== input.mergeRequestIid) {\n patch.pullRequestHeadSha = input.headSha ?? null;\n patch.pullRequestHeadAt = input.eventAt ?? null;\n }\n patch.openPullRequestNumber = input.mergeRequestIid;\n } else if (settling && recorded === input.mergeRequestIid) {\n // With several merge requests on the card, the newest one its sessions opened is out next;\n // someone else's merge request never becomes the card's own.\n patch.openPullRequestNumber = newestOwnedOpenPullRequestNumber(item, input.mergeRequestIid);\n if (input.event === 'mergeRequestMerged' && typeof item.metadata?.reviewVerdict === 'string') {\n patch.reviewVerdict = null;\n }\n }\n try {\n await this.options.storage.update({\n orgId: item.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n expectedRevision: item.revision,\n patch: { metadata: patch },\n });\n return;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n }\n }\n }\n\n async #trusted(connectionIds: string[], projectId: string, username: string): Promise<boolean> {\n for (const connectionId of connectionIds) {\n try {\n const level = await this.options.gitlab.getProjectMemberAccessLevel(connectionId, projectId, username);\n if (level !== undefined) return level >= GITLAB_TRUSTED_ACCESS_LEVEL;\n } catch {\n // Try another active credential covering the same canonical project; otherwise fail closed.\n }\n }\n return false;\n }\n\n async #evaluate(\n input: {\n parsed: ParsedGitLabWebhook;\n event: FactoryGitLabEventName;\n projectId: number;\n projectPath: string;\n host: string;\n actor: FactoryRuleActor;\n orgId: string;\n factoryProjectId: string;\n factoryProject: { createdAt: Date };\n board: FactoryRuleIntakeTarget | undefined;\n issue: Record<string, unknown> | undefined;\n issueAuthor: string | undefined;\n issueAuthorTrusted: boolean;\n issueIid: number | undefined;\n issueSourceKey: string | undefined;\n mergeRequest: Record<string, unknown> | undefined;\n mergeRequestAuthor: string | undefined;\n mergeRequestAuthorTrusted: boolean;\n mergeRequestIid: number | undefined;\n mergeRequestKey: string | undefined;\n factoryAuthored: boolean;\n item: Card | undefined;\n pullRequestHome?: FactoryPullRequestHome;\n ingressIdentity: string;\n mergeRequestOpenedScope?: 'intake' | 'board';\n },\n attempt = 1,\n ): Promise<{ status: IngressStatus }> {\n const note = object(input.parsed.payload.object_attributes);\n const issueAuthor = input.issueAuthor;\n const mergeRequestAuthor = input.mergeRequestAuthor;\n const mergeRequestState = string(input.mergeRequest?.state);\n const context: FactoryGitLabRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor: input.actor,\n ingress: { type: 'gitlab', id: input.ingressIdentity },\n cause: `gitlab.${input.event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(input.item\n ? {\n item: {\n id: input.item.id,\n source:\n input.item.externalSource?.type === 'pull-request'\n ? ('gitlab-pr' as const)\n : input.item.externalSource?.integrationId === 'gitlab'\n ? ('gitlab-issue' as const)\n : ('manual' as const),\n sourceKey: input.item.externalSource?.externalId ?? null,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n url: input.item.externalSource?.url ?? null,\n stages: input.item.stages,\n workItem: input.item.workItem,\n acceptedAt: input.item.acceptedAt,\n metadata: input.item.metadata,\n },\n board: boardForWorkItem(input.item),\n itemRevision: input.item.revision,\n ...withBoardClosure(this.#boards(input), input.item),\n ...rulePhaseField(this.#boards(input), input.item),\n ...withBoardFlow(this.#boards(input), input.item),\n }\n : {}),\n ...(input.board ? { intake: input.board } : {}),\n ...(input.pullRequestHome ? { pullRequestHome: input.pullRequestHome } : {}),\n event: input.event,\n deliveryId: input.parsed.deliveryId,\n factory: { createdAt: input.factoryProject.createdAt.toISOString() },\n repository: { id: input.projectId, fullName: input.projectPath, host: input.host },\n ...(input.issueIid && input.issueSourceKey && string(input.issue?.title)\n ? {\n issue: {\n number: input.issueIid,\n sourceKey: input.issueSourceKey,\n title: string(input.issue?.title)!,\n url:\n string(input.issue?.url) ??\n string(input.issue?.web_url) ??\n `https://${input.host}/${input.projectPath}/-/issues/${input.issueIid}`,\n ...(string(input.issue?.created_at) ? { createdAt: string(input.issue?.created_at) } : {}),\n ...(string(input.issue?.updated_at) ? { updatedAt: string(input.issue?.updated_at) } : {}),\n assignees: usernames(input.parsed.payload.assignees ?? input.issue?.assignees),\n labels: labelNames(input.issue?.labels ?? input.parsed.payload.labels),\n labelColors: labelColors(input.issue?.labels ?? input.parsed.payload.labels),\n state: string(input.issue?.state) === 'closed' ? ('closed' as const) : ('open' as const),\n ...(issueAuthor ? { author: issueAuthor } : {}),\n authorTrusted: input.issueAuthorTrusted,\n },\n }\n : {}),\n ...(input.parsed.event === 'Note Hook' && number(note?.id)\n ? {\n note: {\n id: number(note?.id)!,\n ...(string(note?.note) ? { body: string(note?.note) } : {}),\n ...(string(note?.url) ? { url: string(note?.url) } : {}),\n ...(string(object(input.parsed.payload.user)?.username)\n ? { author: string(object(input.parsed.payload.user)?.username) }\n : {}),\n ...(string(note?.created_at) ? { createdAt: string(note?.created_at) } : {}),\n ...(string(note?.updated_at) ? { updatedAt: string(note?.updated_at) } : {}),\n },\n }\n : {}),\n ...(input.mergeRequestIid && input.mergeRequestKey && string(input.mergeRequest?.title)\n ? {\n mergeRequest: {\n number: input.mergeRequestIid,\n sourceKey: input.mergeRequestKey,\n title: string(input.mergeRequest?.title)!,\n url:\n string(input.mergeRequest?.url) ??\n string(input.mergeRequest?.web_url) ??\n `https://${input.host}/${input.projectPath}/-/merge_requests/${input.mergeRequestIid}`,\n ...(string(input.mergeRequest?.created_at) ? { createdAt: string(input.mergeRequest?.created_at) } : {}),\n state:\n mergeRequestState === 'closed' || mergeRequestState === 'merged'\n ? ('closed' as const)\n : ('open' as const),\n draft: boolean(input.mergeRequest?.draft) ?? boolean(input.mergeRequest?.work_in_progress) ?? false,\n merged: input.event === 'mergeRequestMerged' || mergeRequestState === 'merged',\n assignees: usernames(input.parsed.payload.assignees ?? input.mergeRequest?.assignees),\n reviewers: usernames(input.parsed.payload.reviewers ?? input.mergeRequest?.reviewers),\n labels: labelNames(input.mergeRequest?.labels ?? input.parsed.payload.labels),\n labelColors: labelColors(input.mergeRequest?.labels ?? input.parsed.payload.labels),\n ...(mergeRequestAuthor ? { author: mergeRequestAuthor } : {}),\n authorTrusted: input.mergeRequestAuthorTrusted,\n factoryAuthored: input.factoryAuthored,\n headBranch: string(input.mergeRequest?.source_branch) ?? '',\n baseBranch: string(input.mergeRequest?.target_branch) ?? '',\n },\n }\n : {}),\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n const boardRules = boardEventHandlers(\n this.#boards(input),\n input.mergeRequestOpenedScope === 'intake' ? undefined : eventBoardId(context),\n 'gitlab',\n );\n const rule =\n input.mergeRequestOpenedScope === 'board'\n ? hasExplicitRuleOverride(this.options.gitlab.rules, input.event)\n ? undefined\n : boardRules?.mergeRequestOpened\n : selectEventRule(this.options.gitlab.rules, boardRules, input.event);\n // Without a board handler the authoring card has nothing to answer; skip\n // recording an empty evaluation for it.\n if (input.mergeRequestOpenedScope === 'board' && !rule) return { status: 'ignored' };\n const ownedByDeployment = deploymentOwnsEvent(this.options.gitlab.rules, boardRules, input.event);\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n input.item ? boardForWorkItem(input.item) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory GitLab rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const changes = object(input.parsed.payload.changes);\n const routed =\n (await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n })) ??\n activitySignalFor(context, {\n edited: Boolean(object(changes?.title) || object(changes?.description)),\n noteEdited: string(object(input.parsed.payload.object_attributes)?.action)?.toLowerCase() === 'update',\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: input.item?.id ?? null,\n ingress: { identity: input.ingressIdentity, triggerType: `gitlab.${input.event}` },\n configVersion: this.options.configVersion,\n expectedRevision: input.item?.revision ?? null,\n actor: { ...input.actor },\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory GitLab rule evaluation for ${input.ingressIdentity} kept losing revision races.`);\n }\n const fresh = input.item ? await this.options.storage.get({ orgId: input.orgId, id: input.item.id }) : null;\n if (input.item && !fresh) return { status: 'missing' };\n return this.#evaluate({ ...input, item: fresh ?? undefined }, attempt + 1);\n }\n return { status: committed.status };\n }\n}\n\nexport function attachGitLabRules(\n gitlab: GitLabRulesIntegration,\n context: IntegrationContext,\n): ((event: ParsedGitLabWebhook) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new GitLabRules({\n gitlab,\n sourceControl: context.storage.sourceControl,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n intake: context.storage.intake,\n config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BAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,MAAM,MAAM,MAAM;GAC9B,SAAS;IAAE,UAAU,MAAM;IAAiB,aAAa,UAAU,MAAM;GAAQ;GACjF,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,MAAM,MAAM,YAAY;GAC1C,OAAO,EAAE,GAAG,MAAM,MAAM;GACxB;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,sCAAsC,MAAM,gBAAgB,6BAA6B;GAE3G,MAAM,QAAQ,MAAM,OAAO,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,MAAM,KAAK;GAAG,CAAC,IAAI;GACvG,IAAI,MAAM,QAAQ,CAAC,OAAO,OAAO,EAAE,QAAQ,UAAU;GACrD,OAAO,KAAK,UAAU;IAAE,GAAG;IAAO,MAAM,SAAS,KAAA;GAAU,GAAG,UAAU,CAAC;EAC3E;EACA,OAAO,EAAE,QAAQ,UAAU,OAAO;CACpC;AACF;AAEA,SAAgB,kBACd,QACA,SACgE;CAChE,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B;EACA,eAAe,QAAQ,QAAQ;EAC/B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,QAAQ,QAAQ,QAAQ;EACxB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;CAC1B,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/gitlab/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n cardBoardFlow,\n eventBoardId,\n isTerminalWorkItem,\n cardOwnsBranch,\n newestOwnedOpenPullRequestNumber,\n pullRequestSources,\n intakeTarget,\n rulePhaseField,\n withBoardClosure,\n withBoardFlow,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, hasExplicitRuleOverride, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type {\n FactoryGitLabEventName,\n FactoryGitLabRuleContext,\n FactoryPullRequestHome,\n FactoryRuleIntakeTarget,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactorySignalActivityDecision,\n} from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type {\n ExternalRepositoryProjectTarget,\n SourceControlStorageHandle,\n} from '../../storage/domains/source-control/base.js';\nimport { WorkItemUpdateConflictError } from '../../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { closingIssueNumbers } from '../closing-references.js';\nimport { recordPullRequestHead } from '../pull-request-head.js';\nimport type { GitLabEventRules } from './default-rules.js';\nimport { decodeIssueReference, encodeIssueReference, encodeSourceId, GITLAB_TRUSTED_ACCESS_LEVEL } from './integration.js';\nimport type { ParsedGitLabWebhook } from './webhook.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\ntype IngressStatus = 'ignored' | 'committed' | 'replayed' | 'missing';\n\nexport interface GitLabIngressResult {\n status: IngressStatus;\n /**\n * Every Factory this delivery reaches has handled it for good: ingesting the same\n * delivery again would only replay. Sweeps use it to skip what they already listed.\n */\n settled?: boolean;\n}\n\nfunction settled(result: GitLabIngressResult): boolean {\n return result.settled ?? (result.status === 'committed' || result.status === 'replayed');\n}\n\nfunction combined(results: GitLabIngressResult[]): GitLabIngressResult {\n const all = results.length > 0 && results.every(settled);\n if (results.some(result => result.status === 'committed')) return { status: 'committed', settled: all };\n if (results.some(result => result.status === 'replayed')) return { status: 'replayed', settled: all };\n return { status: results[0]?.status ?? 'ignored', settled: all };\n}\n\nfunction object(value: unknown): Record<string, unknown> | undefined {\n return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction number(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined;\n}\n\n/** GitLab sends `2024-01-02T03:04:05Z`, `2024-01-02 03:04:05 UTC` or `2024-01-02 03:04:05 +0000`. */\nfunction timestamp(value: unknown): number | undefined {\n const text = string(value);\n if (!text) return undefined;\n const spaced = /^(\\d{4}-\\d{2}-\\d{2}) (\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?) (?:UTC|([+-]\\d{2}):?(\\d{2}))$/.exec(text);\n const parsed = Date.parse(\n spaced ? `${spaced[1]}T${spaced[2]}${spaced[3] ? `${spaced[3]}:${spaced[4]}` : 'Z'}` : text,\n );\n return Number.isNaN(parsed) ? undefined : parsed;\n}\n\nfunction boolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction usernames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(entry => {\n const username = string(object(entry)?.username);\n return username ? [username] : [];\n });\n}\n\nfunction labelNames(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap(entry => {\n if (typeof entry === 'string') return entry ? [entry] : [];\n const title = string(object(entry)?.title) ?? string(object(entry)?.name);\n return title ? [title] : [];\n });\n}\n\nfunction labelColors(value: unknown): Record<string, string> {\n if (!Array.isArray(value)) return {};\n return Object.fromEntries(\n value.flatMap(entry => {\n const label = object(entry);\n const name = string(label?.title) ?? string(label?.name);\n const color = string(label?.color);\n return name && color ? [[name, color]] : [];\n }),\n );\n}\n\n/**\n * Points the card's session at a new comment on its issue, or at an edit to\n * the issue's title or description. Only pointers travel (who, where, a link).\n * An edited comment (a Note Hook with action `update`, GitLab 16.11+) is no new comment.\n * GitLab deliveries don't say whether Factory wrote the comment, so the\n * message waits in the session's notifications instead of waking it: a session\n * that comments must not wake itself.\n */\nexport function activitySignalFor(\n context: Pick<FactoryGitLabRuleContext, 'event' | 'item' | 'actor' | 'ingress' | 'repository' | 'issue' | 'note'>,\n delivery: { edited: boolean; noteEdited: boolean },\n): FactorySignalActivityDecision | undefined {\n const event =\n context.event === 'issueCommented' && !delivery.noteEdited\n ? ('work_item.commented' as const)\n : context.event === 'issueUpdated' && delivery.edited\n ? ('work_item.edited' as const)\n : undefined;\n if (!event || !context.item || !context.issue) return undefined;\n if (context.actor.type !== 'gitlab' || context.actor.factoryAuthored) return undefined;\n return {\n type: 'signalActivity',\n idempotencyKey: `${context.ingress.id}:activity`,\n event,\n reference: `${context.repository.fullName}#${context.issue.number}`,\n url: (event === 'work_item.commented' ? context.note?.url : undefined) ?? context.issue.url,\n ...(context.actor.username ? { author: context.actor.username } : {}),\n authorTrusted: context.actor.trusted,\n idleBehavior: 'persist',\n };\n}\n\n/** The status change a GitLab delivery reports. GitLab gives no close reason, so every close is completed. */\nexport function boardEventFor(context: Pick<FactoryGitLabRuleContext, 'event'>): BoardEventFacts | undefined {\n switch (context.event) {\n case 'issueOpened':\n return { type: 'work_item.created' };\n case 'issueReopened':\n return { type: 'work_item.reopened' };\n case 'issueClosed':\n return { type: 'work_item.closed', reason: closeReason(false) };\n default:\n return undefined;\n }\n}\n\nfunction eventName(parsed: ParsedGitLabWebhook): FactoryGitLabEventName | undefined {\n const attributes = object(parsed.payload.object_attributes);\n const action = string(attributes?.action)?.toLowerCase();\n if (parsed.event === 'Issue Hook') {\n if (action === 'open') return 'issueOpened';\n if (action === 'reopen') return 'issueReopened';\n if (action === 'close') return 'issueClosed';\n return 'issueUpdated';\n }\n if (parsed.event === 'Note Hook') {\n const noteableType = string(attributes?.noteable_type);\n if (noteableType === 'Issue') return 'issueCommented';\n if (noteableType === 'MergeRequest') return 'mergeRequestCommented';\n return;\n }\n if (parsed.event !== 'Merge Request Hook') return;\n if (action === 'open' || action === 'reopen') return 'mergeRequestOpened';\n if (action === 'merge') return 'mergeRequestMerged';\n if (action === 'close') return 'mergeRequestClosed';\n return 'mergeRequestUpdated';\n}\n\n/**\n * A card filed for an issue in a different GitLab project than `projectId` on `host`. Branch\n * names repeat across projects, so a card attributed elsewhere never owns this project's branch.\n * A card with no GitLab issue of its own can't be attributed, and isn't.\n */\nfunction cardInOtherGitLabProject(item: Card, host: string, projectId: number): boolean {\n if (item.externalSource?.integrationId !== 'gitlab' || item.externalSource.type !== 'issue') return false;\n const reference = decodeIssueReference(item.externalSource.externalId);\n if (!reference) return false;\n return (\n reference.projectId !== String(projectId) || (reference.host !== undefined && normalizeHost(reference.host) !== host)\n );\n}\n\nfunction normalizeHost(host: string): string {\n return host.trim().toLowerCase().replace(/\\.$/, '');\n}\n\nfunction hostFromPayload(parsed: ParsedGitLabWebhook): string | undefined {\n const declaredHost = parsed.instanceHost ? normalizeHost(parsed.instanceHost) : undefined;\n const projectUrl = string(object(parsed.payload.project)?.web_url);\n if (!projectUrl) return declaredHost;\n try {\n const payloadHost = normalizeHost(new URL(projectUrl).host);\n if (declaredHost && declaredHost !== payloadHost) return undefined;\n return payloadHost;\n } catch {\n return undefined;\n }\n}\n\n/** Whether a card carries the merge request as a source attached to its issue, rather than as its own card. */\nfunction carriesAttachedMergeRequest(item: Card, mergeRequestKey: string): boolean {\n return (\n item.externalSource?.type !== 'pull-request' &&\n pullRequestSources(item).some(source => source.integrationId === 'gitlab' && source.externalId === `pull-request:${mergeRequestKey}`)\n );\n}\n\nfunction mergeRequestSourceKey(host: string, projectId: number, mergeRequestIid: number): string {\n return `gitlab-pr:${Buffer.from(JSON.stringify({ version: 1, host, projectId, mergeRequestIid }), 'utf8').toString('base64url')}`;\n}\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface GitLabRulesIntegration {\n readonly rules: GitLabEventRules;\n resolveActiveConnectionForHost?(storedConnectionId: string, host: string): Promise<string>;\n getProjectMemberAccessLevel(connectionId: string, projectId: string, username: string): Promise<number | undefined>;\n getWorkItemAuthorUsername(\n connectionId: string,\n projectId: string,\n kind: 'issue' | 'merge_request',\n iid: number,\n ): Promise<string | undefined>;\n}\n\ninterface GitLabRulesOptions {\n gitlab: GitLabRulesIntegration;\n sourceControl: SourceControlStorageHandle;\n projects: FactoryProjectsStorage;\n storage: WorkItemsStorage;\n intake: IntakeStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n}\n\ninterface ProjectTarget {\n target: ExternalRepositoryProjectTarget;\n connectionIds: string[];\n}\n\nexport class GitLabRules {\n constructor(private readonly options: GitLabRulesOptions) {}\n\n /** Brings the project's boards up to date, so the sync reads below see its stored boards. */\n async loadBoards(scope: StoredBoardScope): Promise<void> {\n await toBoardSource(this.options.boards).load(scope);\n }\n\n /** The project's loaded boards; {@link loadBoards} runs before an event is handled. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(parsed: ParsedGitLabWebhook): Promise<GitLabIngressResult> {\n const event = eventName(parsed);\n const project = object(parsed.payload.project);\n const projectId = number(project?.id);\n const projectPath = string(project?.path_with_namespace);\n const host = hostFromPayload(parsed);\n const username = string(parsed.payload.user_username) ?? string(object(parsed.payload.user)?.username);\n if (!event || !projectId || !projectPath || !host || !username) return { status: 'ignored' };\n\n const targets = await this.#targets(String(projectId), host);\n if (targets.length === 0) return { status: 'ignored' };\n const results: GitLabIngressResult[] = [];\n for (const target of targets) {\n await this.loadBoards(target.target);\n results.push(await this.#ingestProject(parsed, event, projectId, projectPath, host, username, target));\n }\n return combined(results);\n }\n\n async #targets(repositoryExternalId: string, host: string): Promise<ProjectTarget[]> {\n const grouped = new Map<string, ProjectTarget>();\n const keys = (await this.options.sourceControl.projectRepositories.listConfiguredExternalKeys()).filter(\n key => key.repositoryExternalId === repositoryExternalId,\n );\n for (const key of keys) {\n const targets = await this.options.sourceControl.projectRepositories.listByExternalRepository({\n installationExternalId: key.installationExternalId,\n repositoryExternalId,\n });\n for (const target of targets) {\n const installation = await this.options.sourceControl.installations.findByExternalId({\n orgId: target.orgId,\n externalId: key.installationExternalId,\n });\n const installationHost = string(installation?.providerMetadata.host);\n if (!installationHost || normalizeHost(installationHost) !== normalizeHost(host)) continue;\n const id = `${target.orgId}:${target.factoryProjectId}`;\n const current = grouped.get(id);\n if (current) {\n if (!current.connectionIds.includes(key.installationExternalId)) {\n current.connectionIds.push(key.installationExternalId);\n }\n } else {\n grouped.set(id, { target, connectionIds: [key.installationExternalId] });\n }\n }\n }\n return [...grouped.values()];\n }\n\n async #ingestProject(\n parsed: ParsedGitLabWebhook,\n event: FactoryGitLabEventName,\n projectId: number,\n projectPath: string,\n host: string,\n username: string,\n target: ProjectTarget,\n ): Promise<GitLabIngressResult> {\n const factoryProject = await this.options.projects.get({\n orgId: target.target.orgId,\n id: target.target.factoryProjectId,\n });\n if (!factoryProject) return { status: 'missing' };\n\n const sourceId = encodeSourceId({ host, projectId: String(projectId) });\n const config = await this.options.intake.getConfig({\n orgId: target.target.orgId,\n integrationIds: ['gitlab'],\n });\n if (!config.gitlab?.enabled || !config.gitlab.sourceIds?.includes(sourceId)) return { status: 'ignored' };\n const binding = (\n await this.options.intake.listBindings({ orgId: target.target.orgId, integrationId: 'gitlab' })\n ).find(\n candidate => candidate.sourceId === sourceId && candidate.factoryProjectId === target.target.factoryProjectId,\n );\n if (!binding) return { status: 'ignored' };\n\n const connectionIds = [\n ...new Set(\n await Promise.all(\n target.connectionIds.map(\n connectionId => this.options.gitlab.resolveActiveConnectionForHost?.(connectionId, host) ?? connectionId,\n ),\n ),\n ),\n ];\n\n const attributes = object(parsed.payload.object_attributes);\n const issue = parsed.event === 'Note Hook' ? object(parsed.payload.issue) : attributes;\n const mergeRequest = parsed.event === 'Note Hook' ? object(parsed.payload.merge_request) : attributes;\n const issueIid = number(issue?.iid);\n const mergeRequestIid = number(mergeRequest?.iid);\n const issueSourceKey = issueIid\n ? encodeIssueReference({ host, projectId: String(projectId), issueIid })\n : undefined;\n const mergeRequestKey = mergeRequestIid ? mergeRequestSourceKey(host, projectId, mergeRequestIid) : undefined;\n // A finished card may still be only in the legacy table; copy it so the event finds it.\n await this.options.storage.copyLegacyCards({\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n sources: [\n ...(issueSourceKey ? [{ integrationId: 'gitlab', type: 'issue', externalId: issueSourceKey }] : []),\n ...(mergeRequestKey ? [{ integrationId: 'gitlab', type: 'pull-request', externalId: mergeRequestKey }] : []),\n ],\n });\n // The shared list is the cache itself: only the cards handed on to rules are cloned.\n const items = await this.options.storage.listShared({\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n });\n const own = (card: Card | undefined) => card && structuredClone(card);\n const issueItem = issueSourceKey\n ? own(\n items.find(\n item =>\n item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === issueSourceKey,\n ),\n )\n : undefined;\n const reviewItem = mergeRequestKey\n ? own(\n items.find(\n item =>\n item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === mergeRequestKey,\n ),\n )\n : undefined;\n // A merge request attached to its issue's card, instead of filed on a card of its own.\n const attachedItem =\n mergeRequestKey && !reviewItem\n ? own(items.find(item => carriesAttachedMergeRequest(item, mergeRequestKey)))\n : undefined;\n const headBranch = string(mergeRequest?.source_branch) ?? '';\n // A card whose session builds on the merge request's branch, in this project.\n const buildsOnBranch = (item: Card) =>\n item.externalSource?.type !== 'pull-request' &&\n !cardInOtherGitLabProject(item, host, projectId) &&\n Object.values(item.sessions).some(session => session.branch === headBranch);\n const authoringItem = headBranch ? own(items.find(buildsOnBranch)) : undefined;\n const actorTrusted = await this.#trusted(connectionIds, String(projectId), username);\n const eventUserId = number(object(parsed.payload.user)?.id) ?? number(parsed.payload.user_id);\n const resolveAuthor = async (\n item: Record<string, unknown> | undefined,\n kind: 'issue' | 'merge_request',\n iid: number | undefined,\n ): Promise<string | undefined> => {\n if (!item || !iid) return undefined;\n const embedded = string(object(item.author)?.username);\n if (embedded) return embedded;\n if (eventUserId && eventUserId === number(item.author_id)) return username;\n for (const connectionId of connectionIds) {\n try {\n const resolved = await this.options.gitlab.getWorkItemAuthorUsername(\n connectionId,\n String(projectId),\n kind,\n iid,\n );\n if (resolved) return resolved;\n } catch {\n // Another active credential may cover this project; otherwise leave author trust unset.\n }\n }\n return undefined;\n };\n const [issueAuthor, mergeRequestAuthor] = await Promise.all([\n resolveAuthor(issue, 'issue', issueIid),\n resolveAuthor(mergeRequest, 'merge_request', mergeRequestIid),\n ]);\n const authorTrusted = async (author: string | undefined): Promise<boolean> => {\n if (!author) return false;\n return author === username ? actorTrusted : this.#trusted(connectionIds, String(projectId), author);\n };\n const [issueAuthorTrusted, mergeRequestAuthorTrusted] = await Promise.all([\n authorTrusted(issueAuthor),\n authorTrusted(mergeRequestAuthor),\n ]);\n const actor: FactoryRuleActor = {\n type: 'gitlab',\n username,\n trusted: actorTrusted,\n factoryAuthored: false,\n };\n // A merge request seen for the first time is filed on the card whose branch it comes from,\n // when its board reviews merge requests. Otherwise a trusted author's merge request names the card of the issue\n // its description says it closes, and the project's intake routes decide, when it is filed,\n // whether it joins that card. An untrusted author's merge request never lands on another card.\n // A card with no source of its own (a manual card) never takes one: the merge request would\n // become its only source and turn it into a merge request card. A GitHub card keeps only\n // GitHub pull requests, so a merge request on its session's branch gets its own card.\n const eligibleHome = (card: Card) =>\n card.externalSource !== null &&\n card.externalSource.integrationId !== 'github' &&\n card.externalSource.type !== 'pull-request' &&\n !isTerminalWorkItem(this.#boards(card), card);\n let home: { card: Card; reason: FactoryPullRequestHome['reason'] } | undefined;\n if (event === 'mergeRequestOpened' && mergeRequestKey && !reviewItem && !attachedItem) {\n // A branch name alone is not proof: a fork can reuse it. The Factory's own merge requests come\n // from this project under a trusted account.\n const sourceProjectId = number(mergeRequest?.source_project_id);\n const fromThisProject = sourceProjectId === undefined || sourceProjectId === projectId;\n if (\n authoringItem &&\n fromThisProject &&\n (actorTrusted || mergeRequestAuthorTrusted) &&\n eligibleHome(authoringItem) &&\n cardBoardFlow(this.#boards(authoringItem), authoringItem).pullRequestReview !== undefined\n ) {\n home = { card: authoringItem, reason: 'authored' };\n } else if (mergeRequestAuthorTrusted) {\n for (const iid of closingIssueNumbers(string(mergeRequest?.description), {\n provider: 'gitlab',\n repository: projectPath,\n })) {\n const key = encodeIssueReference({ host, projectId: String(projectId), issueIid: iid });\n const card = items.find(\n item =>\n item.externalSource?.integrationId === 'gitlab' &&\n item.externalSource.externalId === key &&\n eligibleHome(item),\n );\n if (card) {\n home = { card, reason: 'closes' };\n break;\n }\n }\n }\n }\n const pullRequestHome: FactoryPullRequestHome | undefined = home\n ? { workItemId: home.card.id, reason: home.reason }\n : undefined;\n // An attached merge request's state lives on its own source, never the issue's.\n if ((event === 'mergeRequestMerged' || event === 'mergeRequestClosed') && attachedItem && mergeRequestKey) {\n const merged = event === 'mergeRequestMerged';\n await this.options.storage.syncWorkItemSource({\n orgId: attachedItem.orgId,\n factoryProjectId: attachedItem.factoryProjectId,\n provider: 'gitlab',\n externalId: `pull-request:${mergeRequestKey}`,\n patch: { state: merged ? 'merged' : 'closed', metadata: { state: 'closed', merged } },\n });\n }\n\n // A push moves the head a recorded review verdict was given on. Recording\n // the new head lets the verdict badge show that it is outdated, while the\n // verdict itself stays so the next pass still runs as a re-review. It is\n // recorded before the push is evaluated: the dispatcher can apply the\n // re-review transition as soon as it commits, and the pass it starts names\n // the head it covers, which must be the pushed one.\n const lastCommit = object(mergeRequest?.last_commit);\n const headSha = string(lastCommit?.id)?.toLowerCase();\n // Without an update time the commit time still orders the push; dropping\n // the write would leave the pass naming the head the last verdict covered.\n const headAt = timestamp(mergeRequest?.updated_at) ?? timestamp(lastCommit?.timestamp);\n const unchangedListedHead =\n parsed.deliveryId.startsWith('poll:merge-request-head:') &&\n headAt !== undefined &&\n reviewItem?.metadata?.pullRequestHeadSha === headSha &&\n (reviewItem?.metadata?.pullRequestHeadAt !== headAt ||\n reviewItem?.metadata?.pullRequestHeadDeliveryId !== parsed.deliveryId);\n let pushedReviewItem = reviewItem;\n if (event === 'mergeRequestUpdated' && headSha && attachedItem && mergeRequestIid) {\n await recordPullRequestHead(this.options.storage, {\n orgId: attachedItem.orgId,\n id: attachedItem.id,\n headSha,\n headAt,\n ownedPullRequestNumber: mergeRequestIid,\n });\n if (unchangedListedHead) return { status: 'ignored', settled: true };\n }\n if (event === 'mergeRequestUpdated' && headSha && reviewItem) {\n const parent = items.find(item => item.id === reviewItem.parentWorkItemId);\n // The authoring Work item mirrors the verdict of the merge request it has\n // out; a push to an older one must not mark its successor's verdict.\n await recordPullRequestHead(this.options.storage, {\n orgId: reviewItem.orgId,\n id: reviewItem.id,\n headSha,\n headAt,\n deliveryId: parsed.deliveryId.startsWith('poll:merge-request-head:') ? parsed.deliveryId : undefined,\n });\n if (parent) {\n await recordPullRequestHead(this.options.storage, {\n orgId: parent.orgId,\n id: parent.id,\n headSha,\n headAt,\n ownedPullRequestNumber: mergeRequestIid,\n });\n }\n pushedReviewItem = (await this.options.storage.get({ orgId: reviewItem.orgId, id: reviewItem.id })) ?? reviewItem;\n if (unchangedListedHead) return { status: 'ignored', settled: true };\n }\n const ownItem = reviewItem ?? attachedItem;\n const openedItem = (home?.reason === 'authored' ? home.card : undefined) ?? authoringItem;\n const candidates: Array<Card | undefined> =\n event === 'mergeRequestMerged'\n ? [...new Map([ownItem, authoringItem].filter(Boolean).map(item => [item!.id, item!])).values()]\n : event === 'mergeRequestCommented'\n ? [authoringItem ?? ownItem]\n : event === 'mergeRequestOpened'\n ? [openedItem, ...(openedItem ? [openedItem] : [])]\n : event.startsWith('mergeRequest')\n ? [pushedReviewItem ?? attachedItem ?? authoringItem]\n : [issueItem];\n const results = [];\n for (const [index, item] of candidates.entries()) {\n results.push(\n await this.#evaluate({\n parsed,\n event,\n projectId,\n projectPath,\n host,\n actor,\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n factoryProject,\n board: intakeTarget(this.#boards(target.target)),\n issue,\n issueAuthor,\n issueAuthorTrusted,\n issueIid,\n issueSourceKey,\n mergeRequest,\n mergeRequestAuthor,\n mergeRequestAuthorTrusted,\n mergeRequestIid,\n mergeRequestKey,\n factoryAuthored: Boolean(authoringItem),\n item,\n ...(pullRequestHome ? { pullRequestHome } : {}),\n ingressIdentity: `gitlab:${projectId}:${parsed.deliveryId}${index ? `:${item?.id ?? index}` : ''}`,\n // A merge request opening concerns two cards: its own card,\n // which the integration handler files against the authoring item,\n // and that authoring item, which its board may react to. The second\n // evaluation runs only the board handler, under an id-suffixed\n // identity so it is not dropped as a replay of the first.\n ...(event === 'mergeRequestOpened' ? { mergeRequestOpenedScope: index ? ('board' as const) : ('intake' as const) } : {}),\n }),\n );\n }\n // The authoring Work item records which merge request it has out, so the\n // Work transition policy keeps an agent from closing the work while it is\n // open. Sessions carry no repository, so a branch shared by two Work cards\n // is ambiguous and records nothing.\n const branchOwners = headBranch ? items.filter(buildsOnBranch) : [];\n // A merge request filed on its issue's card is tracked there the same way.\n const trackedItem = attachedItem ?? (branchOwners.length === 1 ? authoringItem : undefined);\n if (trackedItem && mergeRequestIid) {\n await this.#trackOpenMergeRequest({\n orgId: trackedItem.orgId,\n id: trackedItem.id,\n event,\n mergeRequestIid,\n eventAt: timestamp(mergeRequest?.updated_at),\n opened: string(mergeRequest?.state) === 'opened' && (actorTrusted || mergeRequestAuthorTrusted),\n headSha: string(object(mergeRequest?.last_commit)?.id)?.toLowerCase(),\n // Only a merge request the card wrote is the one it has out. One filed there because it\n // closes the issue is someone else's work: recording it would stop the builder's own\n // self-review and merge request.\n ownedByCard: trackedItem.id !== attachedItem?.id || cardOwnsBranch(trackedItem, headBranch),\n });\n }\n const result = combined(results);\n const headWithoutCard =\n parsed.deliveryId.startsWith('poll:merge-request-head:') && !reviewItem && !attachedItem;\n return headWithoutCard ? { ...result, settled: false } : result;\n }\n\n /**\n * Records or clears the merge request a Work card has out. Each merge\n * request's last applied event time is kept on the card, so an opening that\n * is older than a close already applied (a replay, or a close delivered\n * first) is ignored, while a genuine reopen is newer and records it again.\n */\n async #trackOpenMergeRequest(input: {\n orgId: string;\n id: string;\n event: string;\n mergeRequestIid: number;\n eventAt: number | undefined;\n opened: boolean;\n headSha: string | undefined;\n ownedByCard: boolean;\n }): Promise<void> {\n const settling = input.event === 'mergeRequestMerged' || input.event === 'mergeRequestClosed';\n if (input.event !== 'mergeRequestOpened' && !settling) return;\n const key = String(input.mergeRequestIid);\n for (let attempt = 0; attempt < 3; attempt++) {\n const item = await this.options.storage.get({ orgId: input.orgId, id: input.id });\n if (!item) return;\n const events = object(item.metadata?.mergeRequestEvents) ?? {};\n const last = object(events[key]);\n const lastAt = number(last?.at);\n if (input.eventAt !== undefined && lastAt !== undefined && lastAt >= input.eventAt) return;\n // Without a timestamp, only an opening that no close has settled is trusted.\n if (input.eventAt === undefined && !settling && last?.open === false) return;\n if (!settling && !input.opened) return;\n const recorded = item.metadata?.openPullRequestNumber;\n const patch: Record<string, unknown> = {\n mergeRequestEvents: { ...events, [key]: { at: input.eventAt ?? lastAt ?? null, open: !settling } },\n };\n if (!settling && input.ownedByCard) {\n // A head recorded for an earlier merge request must not mark this one's\n // verdict outdated. A replayed opening of the merge request already\n // recorded keeps the head its pushes left.\n if (recorded !== input.mergeRequestIid) {\n patch.pullRequestHeadSha = input.headSha ?? null;\n patch.pullRequestHeadAt = input.eventAt ?? null;\n }\n patch.openPullRequestNumber = input.mergeRequestIid;\n } else if (settling && recorded === input.mergeRequestIid) {\n // With several merge requests on the card, the newest one its sessions opened is out next;\n // someone else's merge request never becomes the card's own.\n patch.openPullRequestNumber = newestOwnedOpenPullRequestNumber(item, input.mergeRequestIid);\n if (input.event === 'mergeRequestMerged' && typeof item.metadata?.reviewVerdict === 'string') {\n patch.reviewVerdict = null;\n }\n }\n try {\n await this.options.storage.update({\n orgId: item.orgId,\n id: item.id,\n userId: 'factory-rule-dispatcher',\n expectedRevision: item.revision,\n patch: { metadata: patch },\n });\n return;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n }\n }\n }\n\n async #trusted(connectionIds: string[], projectId: string, username: string): Promise<boolean> {\n for (const connectionId of connectionIds) {\n try {\n const level = await this.options.gitlab.getProjectMemberAccessLevel(connectionId, projectId, username);\n if (level !== undefined) return level >= GITLAB_TRUSTED_ACCESS_LEVEL;\n } catch {\n // Try another active credential covering the same canonical project; otherwise fail closed.\n }\n }\n return false;\n }\n\n async #evaluate(\n input: {\n parsed: ParsedGitLabWebhook;\n event: FactoryGitLabEventName;\n projectId: number;\n projectPath: string;\n host: string;\n actor: FactoryRuleActor;\n orgId: string;\n factoryProjectId: string;\n factoryProject: { createdAt: Date };\n board: FactoryRuleIntakeTarget | undefined;\n issue: Record<string, unknown> | undefined;\n issueAuthor: string | undefined;\n issueAuthorTrusted: boolean;\n issueIid: number | undefined;\n issueSourceKey: string | undefined;\n mergeRequest: Record<string, unknown> | undefined;\n mergeRequestAuthor: string | undefined;\n mergeRequestAuthorTrusted: boolean;\n mergeRequestIid: number | undefined;\n mergeRequestKey: string | undefined;\n factoryAuthored: boolean;\n item: Card | undefined;\n pullRequestHome?: FactoryPullRequestHome;\n ingressIdentity: string;\n mergeRequestOpenedScope?: 'intake' | 'board';\n },\n attempt = 1,\n ): Promise<{ status: IngressStatus }> {\n const note = object(input.parsed.payload.object_attributes);\n const issueAuthor = input.issueAuthor;\n const mergeRequestAuthor = input.mergeRequestAuthor;\n const mergeRequestState = string(input.mergeRequest?.state);\n const context: FactoryGitLabRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor: input.actor,\n ingress: { type: 'gitlab', id: input.ingressIdentity },\n cause: `gitlab.${input.event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(input.item\n ? {\n item: {\n id: input.item.id,\n source:\n input.item.externalSource?.type === 'pull-request'\n ? ('gitlab-pr' as const)\n : input.item.externalSource?.integrationId === 'gitlab'\n ? ('gitlab-issue' as const)\n : ('manual' as const),\n sourceKey: input.item.externalSource?.externalId ?? null,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n url: input.item.externalSource?.url ?? null,\n stages: input.item.stages,\n workItem: input.item.workItem,\n acceptedAt: input.item.acceptedAt,\n metadata: input.item.metadata,\n },\n board: boardForWorkItem(input.item),\n itemRevision: input.item.revision,\n ...withBoardClosure(this.#boards(input), input.item),\n ...rulePhaseField(this.#boards(input), input.item),\n ...withBoardFlow(this.#boards(input), input.item),\n }\n : {}),\n ...(input.board ? { intake: input.board } : {}),\n ...(input.pullRequestHome ? { pullRequestHome: input.pullRequestHome } : {}),\n event: input.event,\n deliveryId: input.parsed.deliveryId,\n factory: { createdAt: input.factoryProject.createdAt.toISOString() },\n repository: { id: input.projectId, fullName: input.projectPath, host: input.host },\n ...(input.issueIid && input.issueSourceKey && string(input.issue?.title)\n ? {\n issue: {\n number: input.issueIid,\n sourceKey: input.issueSourceKey,\n title: string(input.issue?.title)!,\n url:\n string(input.issue?.url) ??\n string(input.issue?.web_url) ??\n `https://${input.host}/${input.projectPath}/-/issues/${input.issueIid}`,\n ...(string(input.issue?.created_at) ? { createdAt: string(input.issue?.created_at) } : {}),\n ...(string(input.issue?.updated_at) ? { updatedAt: string(input.issue?.updated_at) } : {}),\n assignees: usernames(input.parsed.payload.assignees ?? input.issue?.assignees),\n labels: labelNames(input.issue?.labels ?? input.parsed.payload.labels),\n labelColors: labelColors(input.issue?.labels ?? input.parsed.payload.labels),\n state: string(input.issue?.state) === 'closed' ? ('closed' as const) : ('open' as const),\n ...(issueAuthor ? { author: issueAuthor } : {}),\n authorTrusted: input.issueAuthorTrusted,\n },\n }\n : {}),\n ...(input.parsed.event === 'Note Hook' && number(note?.id)\n ? {\n note: {\n id: number(note?.id)!,\n ...(string(note?.note) ? { body: string(note?.note) } : {}),\n ...(string(note?.url) ? { url: string(note?.url) } : {}),\n ...(string(object(input.parsed.payload.user)?.username)\n ? { author: string(object(input.parsed.payload.user)?.username) }\n : {}),\n ...(string(note?.created_at) ? { createdAt: string(note?.created_at) } : {}),\n ...(string(note?.updated_at) ? { updatedAt: string(note?.updated_at) } : {}),\n },\n }\n : {}),\n ...(input.mergeRequestIid && input.mergeRequestKey && string(input.mergeRequest?.title)\n ? {\n mergeRequest: {\n number: input.mergeRequestIid,\n sourceKey: input.mergeRequestKey,\n title: string(input.mergeRequest?.title)!,\n url:\n string(input.mergeRequest?.url) ??\n string(input.mergeRequest?.web_url) ??\n `https://${input.host}/${input.projectPath}/-/merge_requests/${input.mergeRequestIid}`,\n ...(string(input.mergeRequest?.created_at) ? { createdAt: string(input.mergeRequest?.created_at) } : {}),\n state:\n mergeRequestState === 'closed' || mergeRequestState === 'merged'\n ? ('closed' as const)\n : ('open' as const),\n draft: boolean(input.mergeRequest?.draft) ?? boolean(input.mergeRequest?.work_in_progress) ?? false,\n merged: input.event === 'mergeRequestMerged' || mergeRequestState === 'merged',\n assignees: usernames(input.parsed.payload.assignees ?? input.mergeRequest?.assignees),\n reviewers: usernames(input.parsed.payload.reviewers ?? input.mergeRequest?.reviewers),\n labels: labelNames(input.mergeRequest?.labels ?? input.parsed.payload.labels),\n labelColors: labelColors(input.mergeRequest?.labels ?? input.parsed.payload.labels),\n ...(mergeRequestAuthor ? { author: mergeRequestAuthor } : {}),\n authorTrusted: input.mergeRequestAuthorTrusted,\n factoryAuthored: input.factoryAuthored,\n headBranch: string(input.mergeRequest?.source_branch) ?? '',\n baseBranch: string(input.mergeRequest?.target_branch) ?? '',\n },\n }\n : {}),\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n const boardRules = boardEventHandlers(\n this.#boards(input),\n input.mergeRequestOpenedScope === 'intake' ? undefined : eventBoardId(context),\n 'gitlab',\n );\n const rule =\n input.mergeRequestOpenedScope === 'board'\n ? hasExplicitRuleOverride(this.options.gitlab.rules, input.event)\n ? undefined\n : boardRules?.mergeRequestOpened\n : selectEventRule(this.options.gitlab.rules, boardRules, input.event);\n // Without a board handler the authoring card has nothing to answer; skip\n // recording an empty evaluation for it.\n if (input.mergeRequestOpenedScope === 'board' && !rule) return { status: 'ignored' };\n const ownedByDeployment = deploymentOwnsEvent(this.options.gitlab.rules, boardRules, input.event);\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n input.item ? boardForWorkItem(input.item) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory GitLab rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const changes = object(input.parsed.payload.changes);\n const routed =\n (await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n })) ??\n activitySignalFor(context, {\n edited: Boolean(object(changes?.title) || object(changes?.description)),\n noteEdited: string(object(input.parsed.payload.object_attributes)?.action)?.toLowerCase() === 'update',\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: input.item?.id ?? null,\n ingress: { identity: input.ingressIdentity, triggerType: `gitlab.${input.event}` },\n configVersion: this.options.configVersion,\n expectedRevision: input.item?.revision ?? null,\n actor: { ...input.actor },\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory GitLab rule evaluation for ${input.ingressIdentity} kept losing revision races.`);\n }\n const fresh = input.item ? await this.options.storage.get({ orgId: input.orgId, id: input.item.id }) : null;\n if (input.item && !fresh) return { status: 'missing' };\n return this.#evaluate({ ...input, item: fresh ?? undefined }, attempt + 1);\n }\n return { status: committed.status };\n }\n}\n\nexport function attachGitLabRules(\n gitlab: GitLabRulesIntegration,\n context: IntegrationContext,\n): ((event: ParsedGitLabWebhook) => Promise<GitLabIngressResult>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new GitLabRules({\n gitlab,\n sourceControl: context.storage.sourceControl,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n intake: context.storage.intake,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return event => rules.ingest(event);\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,kBAAkB;AAaxB,SAAS,QAAQ,QAAsC;CACrD,OAAO,OAAO,YAAY,OAAO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,MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,MAAM,MAAM,MAAM;GAC9B,SAAS;IAAE,UAAU,MAAM;IAAiB,aAAa,UAAU,MAAM;GAAQ;GACjF,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,MAAM,MAAM,YAAY;GAC1C,OAAO,EAAE,GAAG,MAAM,MAAM;GACxB;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,sCAAsC,MAAM,gBAAgB,6BAA6B;GAE3G,MAAM,QAAQ,MAAM,OAAO,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,MAAM,KAAK;GAAG,CAAC,IAAI;GACvG,IAAI,MAAM,QAAQ,CAAC,OAAO,OAAO,EAAE,QAAQ,UAAU;GACrD,OAAO,KAAK,UAAU;IAAE,GAAG;IAAO,MAAM,SAAS,KAAA;GAAU,GAAG,UAAU,CAAC;EAC3E;EACA,OAAO,EAAE,QAAQ,UAAU,OAAO;CACpC;AACF;AAEA,SAAgB,kBACd,QACA,SAC4E;CAC5E,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B;EACA,eAAe,QAAQ,QAAQ;EAC/B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,QAAQ,QAAQ,QAAQ;EACxB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;CAC1B,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -51,11 +51,12 @@ export declare class IncidentioIntegration implements FactoryIntegration {
51
51
  agentTools(args: {
52
52
  requestContext: RequestContext;
53
53
  }): Promise<IntegrationTools>;
54
+ isFollowUpSource(sourceId: string): boolean;
54
55
  workers(ctx: IntegrationContext): MastraWorker[];
55
56
  /**
56
57
  * The integration's HTTP surface: `/web/incidentio/*` Mastra `apiRoutes`
57
58
  * (status + follow-up listing/detail for Intake). Handlers operate on this
58
- * instance; a board-scoped listing also feeds the incident.io event rules.
59
+ * instance.
59
60
  */
60
61
  routes(ctx: IntegrationContext): ApiRoute[];
61
62
  diagnostics(): Record<string, unknown>;
@@ -1 +1 @@
1
- {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAK3F,OAAO,KAAK,EAAE,oBAAoB,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAOxF,MAAM,WAAW,2BAA2B;IAC1C,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,KAAK,CAAC;IACzB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,KAAK,CAAC,EAAE,uBAAuB,CAAC;CACjC;AAKD,qBAAa,qBAAsB,YAAW,kBAAkB;;IAC9D,QAAQ,CAAC,EAAE,gBAAgB;IAC3B,QAAQ,CAAC,MAAM,gDAAC;IAUhB,YAAY,MAAM,GAAE,2BAAgC,EAoBnD;IAED,kFAAkF;IAClF,IAAI,KAAK,IAAI,oBAAoB,CAEhC;IAED;;;;OAIG;IACH,UAAU,CAAC,EACT,QAAQ,EACR,IAAI,EACJ,MAAM,GACP,EAAE;QACD,QAAQ,EAAE,sBAAsB,CAAC;QACjC,IAAI,EAAE,SAAS,CAAC;QAChB,MAAM,EAAE,aAAa,CAAC;KACvB,GAAG,IAAI,CAIP;IAED,oFAAoF;IACpF,IAAI,aAAa,IAAI,aAAa,CAKjC;IAED,+EAA+E;IAC/E,IAAI,QAAQ,IAAI,sBAAsB,CAKrC;IAED,sFAAsF;IACtF,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED;;;;OAIG;IACG,YAAY,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAmB7D;IAED,oDAAoD;IACpD,WAAW,IAAI,IAAI,CAElB;IAED;;;OAGG;IACG,UAAU,CAAC,IAAI,EAAE;QAAE,cAAc,EAAE,cAAc,CAAA;KAAE,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEpF;IAED,OAAO,CAAC,GAAG,EAAE,kBAAkB,GAAG,YAAY,EAAE,CAY/C;IAED;;;;OAIG;IACH,MAAM,CAAC,GAAG,EAAE,kBAAkB,GAAG,QAAQ,EAAE,CAQ1C;IAED,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAErC;CACF"}
1
+ {"version":3,"file":"integration.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/integration.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AACnE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,KA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CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAE1C;IAED,OAAO,CAAC,GAAG,EAAE,kBAAkB,GAAG,YAAY,EAAE,CAW/C;IAED;;;;OAIG;IACH,MAAM,CAAC,GAAG,EAAE,kBAAkB,GAAG,QAAQ,EAAE,CAO1C;IAED,WAAW,IAAI,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAErC;CACF"}
@@ -2,11 +2,10 @@ import { IssueReconcileWorker } from "../issue-reconcile-worker.js";
2
2
  import { buildIncidentioAgentTools } from "./agent-tools.js";
3
3
  import { IncidentioApiClient } from "./api.js";
4
4
  import { resolveIncidentioRules } from "./default-rules.js";
5
- import { createIncidentioIntake } from "./intake.js";
5
+ import { INCIDENTIO_FOLLOW_UPS_SOURCE_ID, createIncidentioIntake } from "./intake.js";
6
6
  import { attachIncidentioIssueReconciler } from "./issue-reconciler.js";
7
- import { incidentioReconciliationEnabled, incidentioReconciliationInterval } from "./reconciliation-config.js";
7
+ import { incidentioReconciliationInterval } from "./reconciliation-config.js";
8
8
  import { buildIncidentioRoutes } from "./routes.js";
9
- import { attachIncidentioRules } from "./rules.js";
10
9
  // src/integrations/incidentio/integration.ts
11
10
  const DIRECT_CONNECTION_TOKEN = "incidentio-direct-api-key";
12
11
  const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -104,8 +103,10 @@ var IncidentioIntegration = class {
104
103
  incidentio: this
105
104
  });
106
105
  }
106
+ isFollowUpSource(sourceId) {
107
+ return sourceId === INCIDENTIO_FOLLOW_UPS_SOURCE_ID;
108
+ }
107
109
  workers(ctx) {
108
- if (!incidentioReconciliationEnabled()) return [];
109
110
  const reconcile = attachIncidentioIssueReconciler(this, ctx);
110
111
  if (!reconcile) return [];
111
112
  const intervalMs = incidentioReconciliationInterval();
@@ -118,15 +119,14 @@ var IncidentioIntegration = class {
118
119
  /**
119
120
  * The integration's HTTP surface: `/web/incidentio/*` Mastra `apiRoutes`
120
121
  * (status + follow-up listing/detail for Intake). Handlers operate on this
121
- * instance; a board-scoped listing also feeds the incident.io event rules.
122
+ * instance.
122
123
  */
123
124
  routes(ctx) {
124
125
  return buildIncidentioRoutes({
125
126
  incidentio: this,
126
127
  mode: "api-key",
127
128
  auth: ctx.auth,
128
- intake: ctx.storage.intake,
129
- ingestFactoryIssues: attachIncidentioRules(this, ctx)
129
+ intake: ctx.storage.intake
130
130
  });
131
131
  }
132
132
  diagnostics() {
@@ -1 +1 @@
1
- {"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/incidentio/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildIncidentioAgentTools } from './agent-tools.js';\nimport { IncidentioApiClient } from './api.js';\nimport { resolveIncidentioRules } from './default-rules.js';\nimport type { IncidentioEventRules, IncidentioRuleOverrides } from './default-rules.js';\nimport { createIncidentioIntake } from './intake.js';\nimport { attachIncidentioIssueReconciler } from './issue-reconciler.js';\nimport { incidentioReconciliationEnabled, incidentioReconciliationInterval } from './reconciliation-config.js';\nimport { buildIncidentioRoutes } from './routes.js';\nimport { attachIncidentioRules } from './rules.js';\n\nexport interface IncidentioIntegrationConfig {\n apiKey?: string;\n fetchImpl?: typeof fetch;\n baseUrl?: string;\n /** Per-event replacements for the default Factory incident.io rules. */\n rules?: IncidentioRuleOverrides;\n}\n\nconst DIRECT_CONNECTION_TOKEN = 'incidentio-direct-api-key';\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport class IncidentioIntegration implements FactoryIntegration {\n readonly id = 'incidentio';\n readonly intake;\n readonly #endpointHost: string;\n readonly #rules: IncidentioEventRules;\n\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n #intakeStorage: IntakeStorage | undefined;\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n constructor(config: IncidentioIntegrationConfig = {}) {\n this.#rules = resolveIncidentioRules(config.rules);\n const apiKey = config.apiKey?.trim() || process.env.INCIDENT_IO_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('IncidentioIntegration: missing required INCIDENT_IO_API_KEY.');\n }\n const baseUrl = config.baseUrl ?? 'https://api.incident.io';\n this.#endpointHost = new URL(baseUrl).host;\n const api = new IncidentioApiClient({\n baseUrl,\n accessToken: apiKey,\n // Direct incident.io access: never leak the Mastra project id header\n // to incident.io itself.\n projectId: null,\n ...(config.fetchImpl ? { fetchImpl: config.fetchImpl } : {}),\n });\n this.intake = createIncidentioIntake({\n api,\n connection: { type: 'oauth', accessToken: DIRECT_CONNECTION_TOKEN },\n });\n }\n\n /** Event rules driving automatic follow-up materialization and close handling. */\n get rules(): IncidentioEventRules {\n return this.#rules;\n }\n\n /**\n * Bind the projects domain and the host auth seam. incident.io has no\n * per-org connection rows here — credentials are deployment-global\n * constructor config.\n */\n initialize({\n projects,\n auth,\n intake,\n }: {\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n intake: IntakeStorage;\n }): void {\n this.#projects = projects;\n this.#auth = auth;\n this.#intakeStorage = intake;\n }\n\n /** Cross-integration intake selection/binding domain — agent-tool authorization. */\n get intakeStorage(): IntakeStorage {\n if (!this.#intakeStorage) {\n throw new Error('IncidentioIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#intakeStorage;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('IncidentioIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /** Whether the host runs with web auth enabled; every surface is inert without it. */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n /**\n * Map a session's resourceId (the factory project id) to its owning org.\n * Same caching semantics as the Jira integration: definitive misses are\n * cached, transient database failures are not.\n */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org cache between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n }\n\n /**\n * Org-scoped agent tools: the read-only follow-up detail tool for sessions\n * whose resource is a factory project, matching the Linear/Jira surface.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildIncidentioAgentTools({ requestContext: args.requestContext, incidentio: this });\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n if (!incidentioReconciliationEnabled()) return [];\n const reconcile = attachIncidentioIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = incidentioReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * The integration's HTTP surface: `/web/incidentio/*` Mastra `apiRoutes`\n * (status + follow-up listing/detail for Intake). Handlers operate on this\n * instance; a board-scoped listing also feeds the incident.io event rules.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildIncidentioRoutes({\n incidentio: this,\n mode: 'api-key',\n auth: ctx.auth,\n intake: ctx.storage.intake,\n ingestFactoryIssues: attachIncidentioRules(this, ctx),\n });\n }\n\n diagnostics(): Record<string, unknown> {\n return { mode: 'api-key', endpointHost: this.#endpointHost };\n }\n}\n"],"mappings":";;;;;;;;;;AA2BA,MAAM,0BAA0B;AAChC,MAAM,eAAe;AAErB,IAAa,wBAAb,MAAiE;CAC/D,KAAc;CACd;CACA;CACA;;CAGA;CACA;CACA;CACA,qCAA8B,IAAI,IAA2B;CAE7D,YAAY,SAAsC,CAAC,GAAG;EACpD,KAAK,SAAS,uBAAuB,OAAO,KAAK;EACjD,MAAM,SAAS,OAAO,QAAQ,KAAK,KAAK,QAAQ,IAAI,qBAAqB,KAAK;EAC9E,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,8DAA8D;EAEhF,MAAM,UAAU,OAAO,WAAW;EAClC,KAAK,gBAAgB,IAAI,IAAI,OAAO,CAAC,CAAC;EACtC,MAAM,MAAM,IAAI,oBAAoB;GAClC;GACA,aAAa;GAGb,WAAW;GACX,GAAI,OAAO,YAAY,EAAE,WAAW,OAAO,UAAU,IAAI,CAAC;EAC5D,CAAC;EACD,KAAK,SAAS,uBAAuB;GACnC;GACA,YAAY;IAAE,MAAM;IAAS,aAAa;GAAwB;EACpE,CAAC;CACH;;CAGA,IAAI,QAA8B;EAChC,OAAO,KAAK;CACd;;;;;;CAOA,WAAW,EACT,UACA,MACA,UAKO;EACP,KAAK,YAAY;EACjB,KAAK,QAAQ;EACb,KAAK,iBAAiB;CACxB;;CAGA,IAAI,gBAA+B;EACjC,IAAI,CAAC,KAAK,gBACR,MAAM,IAAI,MAAM,wFAAwF;EAE1G,OAAO,KAAK;CACd;;CAGA,IAAI,WAAmC;EACrC,IAAI,CAAC,KAAK,WACR,MAAM,IAAI,MAAM,wFAAwF;EAE1G,OAAO,KAAK;CACd;;CAGA,IAAI,cAAuB;EACzB,OAAO,KAAK,OAAO,QAAQ,KAAK;CAClC;;;;;;CAOA,MAAM,aAAa,YAA4C;EAC7D,MAAM,SAAS,KAAK,mBAAmB,IAAI,UAAU;EACrD,IAAI,WAAW,KAAA,GAAW,OAAO;EACjC,IAAI,CAAC,aAAa,KAAK,UAAU,GAAG;GAClC,KAAK,mBAAmB,IAAI,YAAY,IAAI;GAC5C,OAAO;EACT;EACA,IAAI;EACJ,IAAI;GACF,MAAM,KAAK,SAAS,YAAY;GAEhC,SAAQ,MADc,KAAK,SAAS,QAAQ,EAAE,IAAI,WAAW,CAAC,EAAA,EAC7C,SAAS;EAC5B,QAAQ;GAGN,OAAO;EACT;EACA,KAAK,mBAAmB,IAAI,YAAY,KAAK;EAC7C,OAAO;CACT;;CAGA,cAAoB;EAClB,KAAK,mBAAmB,MAAM;CAChC;;;;;CAMA,MAAM,WAAW,MAAqE;EACpF,OAAO,0BAA0B;GAAE,gBAAgB,KAAK;GAAgB,YAAY;EAAK,CAAC;CAC5F;CAEA,QAAQ,KAAyC;EAC/C,IAAI,CAAC,gCAAgC,GAAG,OAAO,CAAC;EAChD,MAAM,YAAY,gCAAgC,MAAM,GAAG;EAC3D,IAAI,CAAC,WAAW,OAAO,CAAC;EACxB,MAAM,aAAa,iCAAiC;EACpD,OAAO,CACL,IAAI,qBAAqB;GACvB,eAAe,KAAK;GACpB;GACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC,CAAC,CACH;CACF;;;;;;CAOA,OAAO,KAAqC;EAC1C,OAAO,sBAAsB;GAC3B,YAAY;GACZ,MAAM;GACN,MAAM,IAAI;GACV,QAAQ,IAAI,QAAQ;GACpB,qBAAqB,sBAAsB,MAAM,GAAG;EACtD,CAAC;CACH;CAEA,cAAuC;EACrC,OAAO;GAAE,MAAM;GAAW,cAAc,KAAK;EAAc;CAC7D;AACF"}
1
+ {"version":3,"file":"integration.js","names":[],"sources":["../../../src/integrations/incidentio/integration.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport type { ApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationTools } from '../base.js';\nimport { IssueReconcileWorker } from '../issue-reconcile-worker.js';\nimport { buildIncidentioAgentTools } from './agent-tools.js';\nimport { IncidentioApiClient } from './api.js';\nimport { resolveIncidentioRules } from './default-rules.js';\nimport type { IncidentioEventRules, IncidentioRuleOverrides } from './default-rules.js';\nimport { createIncidentioIntake, INCIDENTIO_FOLLOW_UPS_SOURCE_ID } from './intake.js';\nimport { attachIncidentioIssueReconciler } from './issue-reconciler.js';\nimport { incidentioReconciliationInterval } from './reconciliation-config.js';\nimport { buildIncidentioRoutes } from './routes.js';\n\nexport interface IncidentioIntegrationConfig {\n apiKey?: string;\n fetchImpl?: typeof fetch;\n baseUrl?: string;\n /** Per-event replacements for the default Factory incident.io rules. */\n rules?: IncidentioRuleOverrides;\n}\n\nconst DIRECT_CONNECTION_TOKEN = 'incidentio-direct-api-key';\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport class IncidentioIntegration implements FactoryIntegration {\n readonly id = 'incidentio';\n readonly intake;\n readonly #endpointHost: string;\n readonly #rules: IncidentioEventRules;\n\n /** Bound once by the factory via `initialize()` before any surface is used. */\n #projects: FactoryProjectsStorage | undefined;\n #auth: RouteAuth | undefined;\n #intakeStorage: IntakeStorage | undefined;\n readonly #orgIdByResourceId = new Map<string, string | null>();\n\n constructor(config: IncidentioIntegrationConfig = {}) {\n this.#rules = resolveIncidentioRules(config.rules);\n const apiKey = config.apiKey?.trim() || process.env.INCIDENT_IO_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('IncidentioIntegration: missing required INCIDENT_IO_API_KEY.');\n }\n const baseUrl = config.baseUrl ?? 'https://api.incident.io';\n this.#endpointHost = new URL(baseUrl).host;\n const api = new IncidentioApiClient({\n baseUrl,\n accessToken: apiKey,\n // Direct incident.io access: never leak the Mastra project id header\n // to incident.io itself.\n projectId: null,\n ...(config.fetchImpl ? { fetchImpl: config.fetchImpl } : {}),\n });\n this.intake = createIncidentioIntake({\n api,\n connection: { type: 'oauth', accessToken: DIRECT_CONNECTION_TOKEN },\n });\n }\n\n /** Event rules driving automatic follow-up materialization and close handling. */\n get rules(): IncidentioEventRules {\n return this.#rules;\n }\n\n /**\n * Bind the projects domain and the host auth seam. incident.io has no\n * per-org connection rows here — credentials are deployment-global\n * constructor config.\n */\n initialize({\n projects,\n auth,\n intake,\n }: {\n projects: FactoryProjectsStorage;\n auth: RouteAuth;\n intake: IntakeStorage;\n }): void {\n this.#projects = projects;\n this.#auth = auth;\n this.#intakeStorage = intake;\n }\n\n /** Cross-integration intake selection/binding domain — agent-tool authorization. */\n get intakeStorage(): IntakeStorage {\n if (!this.#intakeStorage) {\n throw new Error('IncidentioIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#intakeStorage;\n }\n\n /** Factory projects domain — maps a session's resourceId to its owning org. */\n get projects(): FactoryProjectsStorage {\n if (!this.#projects) {\n throw new Error('IncidentioIntegration is not initialized — the factory binds storage during prepare().');\n }\n return this.#projects;\n }\n\n /** Whether the host runs with web auth enabled; every surface is inert without it. */\n get authEnabled(): boolean {\n return this.#auth?.enabled() ?? false;\n }\n\n /**\n * Map a session's resourceId (the factory project id) to its owning org.\n * Same caching semantics as the Jira integration: definitive misses are\n * cached, transient database failures are not.\n */\n async resolveOrgId(resourceId: string): Promise<string | null> {\n const cached = this.#orgIdByResourceId.get(resourceId);\n if (cached !== undefined) return cached;\n if (!UUID_PATTERN.test(resourceId)) {\n this.#orgIdByResourceId.set(resourceId, null);\n return null;\n }\n let orgId: string | null;\n try {\n await this.projects.ensureReady();\n const project = await this.projects.getById({ id: resourceId });\n orgId = project?.orgId ?? null;\n } catch {\n // Transient database failure: skip the tools for this request but don't\n // cache the miss, so the next request retries the lookup.\n return null;\n }\n this.#orgIdByResourceId.set(resourceId, orgId);\n return orgId;\n }\n\n /** Test hook: clear the org cache between specs. */\n clearCaches(): void {\n this.#orgIdByResourceId.clear();\n }\n\n /**\n * Org-scoped agent tools: the read-only follow-up detail tool for sessions\n * whose resource is a factory project, matching the Linear/Jira surface.\n */\n async agentTools(args: { requestContext: RequestContext }): Promise<IntegrationTools> {\n return buildIncidentioAgentTools({ requestContext: args.requestContext, incidentio: this });\n }\n\n isFollowUpSource(sourceId: string): boolean {\n return sourceId === INCIDENTIO_FOLLOW_UPS_SOURCE_ID;\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n const reconcile = attachIncidentioIssueReconciler(this, ctx);\n if (!reconcile) return [];\n const intervalMs = incidentioReconciliationInterval();\n return [\n new IssueReconcileWorker({\n integrationId: this.id,\n reconcile,\n ...(intervalMs ? { intervalMs } : {}),\n }),\n ];\n }\n\n /**\n * The integration's HTTP surface: `/web/incidentio/*` Mastra `apiRoutes`\n * (status + follow-up listing/detail for Intake). Handlers operate on this\n * instance.\n */\n routes(ctx: IntegrationContext): ApiRoute[] {\n return buildIncidentioRoutes({\n incidentio: this,\n mode: 'api-key',\n auth: ctx.auth,\n intake: ctx.storage.intake,\n });\n }\n\n diagnostics(): Record<string, unknown> {\n return { mode: 'api-key', endpointHost: this.#endpointHost };\n }\n}\n"],"mappings":";;;;;;;;;AA0BA,MAAM,0BAA0B;AAChC,MAAM,eAAe;AAErB,IAAa,wBAAb,MAAiE;CAC/D,KAAc;CACd;CACA;CACA;;CAGA;CACA;CACA;CACA,qCAA8B,IAAI,IAA2B;CAE7D,YAAY,SAAsC,CAAC,GAAG;EACpD,KAAK,SAAS,uBAAuB,OAAO,KAAK;EACjD,MAAM,SAAS,OAAO,QAAQ,KAAK,KAAK,QAAQ,IAAI,qBAAqB,KAAK;EAC9E,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,8DAA8D;EAEhF,MAAM,UAAU,OAAO,W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KAAK;GAAgB,YAAY;EAAK,CAAC;CAC5F;CAEA,iBAAiB,UAA2B;EAC1C,OAAO,aAAa;CACtB;CAEA,QAAQ,KAAyC;EAC/C,MAAM,YAAY,gCAAgC,MAAM,GAAG;EAC3D,IAAI,CAAC,WAAW,OAAO,CAAC;EACxB,MAAM,aAAa,iCAAiC;EACpD,OAAO,CACL,IAAI,qBAAqB;GACvB,eAAe,KAAK;GACpB;GACA,GAAI,aAAa,EAAE,WAAW,IAAI,CAAC;EACrC,CAAC,CACH;CACF;;;;;;CAOA,OAAO,KAAqC;EAC1C,OAAO,sBAAsB;GAC3B,YAAY;GACZ,MAAM;GACN,MAAM,IAAI;GACV,QAAQ,IAAI,QAAQ;EACtB,CAAC;CACH;CAEA,cAAuC;EACrC,OAAO;GAAE,MAAM;GAAW,cAAc,KAAK;EAAc;CAC7D;AACF"}
@@ -3,8 +3,15 @@ import type { IntegrationContext } from '../base.js';
3
3
  import type { IssueReconciler } from '../issue-reconciler.js';
4
4
  import type { IncidentioEventRules } from './default-rules.js';
5
5
  export type IncidentioIssueReconciler = IssueReconciler;
6
+ /**
7
+ * One incident.io sweep: refresh carded items (metadata, closes), then list
8
+ * what every project's board shows so follow-ups nobody has carded yet get
9
+ * their card. incident.io sends Factory no events, so this is the only
10
+ * first-sight path.
11
+ */
6
12
  export declare function attachIncidentioIssueReconciler(incidentio: {
7
13
  intake: Intake;
8
14
  rules: IncidentioEventRules;
15
+ isFollowUpSource(sourceId: string): boolean;
9
16
  }, context: IntegrationContext): IncidentioIssueReconciler | undefined;
10
17
  //# sourceMappingURL=issue-reconciler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/issue-reconciler.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAErD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAI/D,MAAM,MAAM,yBAAyB,GAAG,eAAe,CAAC;AAoBxD,wBAAgB,+BAA+B,CAC7C,UAAU,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,oBAAoB,CAAA;CAAE,EAC3D,OAAO,EAAE,kBAAkB,GAC1B,yBAAyB,GAAG,SAAS,CAkDvC"}
1
+ {"version":3,"file":"issue-reconciler.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/issue-reconciler.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,MAAM,EAAe,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAGrD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAK/D,MAAM,MAAM,yBAAyB,GAAG,eAAe,CAAC;AAoBxD;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,UAAU,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,oBAAoB,CAAC;IAAC,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,EACxG,OAAO,EAAE,kBAAkB,GAC1B,yBAAyB,GAAG,SAAS,CAiFvC"}
@@ -1,7 +1,9 @@
1
1
  import { workItemPhaseSemantics } from "../../boards/semantics.js";
2
2
  import "../../boards/index.js";
3
3
  import { toBoardSource } from "../../boards/project-boards.js";
4
+ import { withIntakeDiscovery } from "../intake-discovery.js";
4
5
  import { createIssueReconciler } from "../issue-reconciler.js";
6
+ import { followUpIssues, scopeSourceIdsToProject } from "./routes.js";
5
7
  import { IncidentioRules } from "./rules.js";
6
8
  // src/integrations/incidentio/issue-reconciler.ts
7
9
  function issueToIngress(itemRef, issue) {
@@ -21,6 +23,12 @@ function issueToIngress(itemRef, issue) {
21
23
  updatedAt: issue.updatedAt
22
24
  };
23
25
  }
26
+ /**
27
+ * One incident.io sweep: refresh carded items (metadata, closes), then list
28
+ * what every project's board shows so follow-ups nobody has carded yet get
29
+ * their card. incident.io sends Factory no events, so this is the only
30
+ * first-sight path.
31
+ */
24
32
  function attachIncidentioIssueReconciler(incidentio, context) {
25
33
  if (!context.runtime || !incidentio.intake.resolveIntakeDispatch) return void 0;
26
34
  const boards = context.runtime.boards;
@@ -31,11 +39,12 @@ function attachIncidentioIssueReconciler(incidentio, context) {
31
39
  boards,
32
40
  incidentioRules: incidentio.rules
33
41
  });
34
- return createIssueReconciler({
42
+ const reconcile = createIssueReconciler({
35
43
  integrationId: "incidentio",
36
44
  intake: incidentio.intake,
37
45
  projects: context.storage.projects,
38
46
  storage: context.runtime.workItems,
47
+ ...context.runtime.keptCards ? { cards: context.runtime.keptCards } : {},
39
48
  isTerminal: (item) => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === "terminal",
40
49
  issueId: (item) => item.externalSource?.externalId,
41
50
  metadata: (item, issue) => ({
@@ -69,6 +78,32 @@ function attachIncidentioIssueReconciler(incidentio, context) {
69
78
  });
70
79
  }
71
80
  });
81
+ return withIntakeDiscovery(reconcile, {
82
+ integrationId: "incidentio",
83
+ intake: context.storage.intake,
84
+ projects: context.storage.projects,
85
+ open: async (project, selectedIds) => {
86
+ return (await scopeSourceIdsToProject({
87
+ intake: context.storage.intake,
88
+ orgId: project.orgId,
89
+ factoryProjectId: project.id,
90
+ selectedIds
91
+ })).filter((sourceId) => incidentio.isFollowUpSource(sourceId)).map((sourceId) => async (cursor) => {
92
+ const page = await incidentio.intake.listItems({
93
+ orgId: project.orgId,
94
+ userId: "factory-rule-dispatcher",
95
+ sourceIds: [sourceId],
96
+ ...cursor ? { cursor } : {}
97
+ });
98
+ return {
99
+ issues: followUpIssues(page.items),
100
+ nextCursor: page.nextCursor
101
+ };
102
+ });
103
+ },
104
+ maxPages: Number.POSITIVE_INFINITY,
105
+ ingest: (input) => rules.ingest(input)
106
+ });
72
107
  }
73
108
  export { attachIncidentioIssueReconciler };
74
109
 
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/incidentio/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { Intake, IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { IncidentioEventRules } from './default-rules.js';\nimport { IncidentioRules } from './rules.js';\nimport type { IncidentioIssueIngress } from './rules.js';\n\nexport type IncidentioIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(itemRef: string, issue: IntakeIssue): IncidentioIssueIngress {\n return {\n id: itemRef,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n author: issue.author ?? null,\n incident: null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nexport function attachIncidentioIssueReconciler(\n incidentio: { intake: Intake; rules: IncidentioEventRules },\n context: IntegrationContext,\n): IncidentioIssueReconciler | undefined {\n if (!context.runtime || !incidentio.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new IncidentioRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n incidentioRules: incidentio.rules,\n });\n\n return createIssueReconciler({\n integrationId: 'incidentio',\n intake: incidentio.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => item.externalSource?.externalId,\n metadata: (item, issue) => ({\n identifier: issue.identifier,\n issueRef: item.externalSource?.externalId ?? issue.id,\n autoStartCandidate: issue.stateType === 'unstarted' || issue.stateType === 'started',\n incidentioItemType: issue.source === 'Follow-up' ? 'follow-up' : 'incident',\n incidentioState: issue.state,\n incidentioStateType: issue.stateType,\n incidentioPriority: issue.priority,\n incidentioAssignee: issue.assignee,\n incidentioDescription: 'description' in issue && typeof issue.description === 'string' ? issue.description : null,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priority,\n source: issue.source,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)],\n });\n },\n });\n}\n"],"mappings":";;;;;;AAYA,SAAS,eAAe,SAAiB,OAA4C;CACnF,OAAO;EACL,IAAI;EACJ,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW,MAAM,aAAa;EAC9B,eAAe,MAAM,YAAY;EACjC,UAAU,MAAM,YAAY;EAC5B,QAAQ,MAAM,UAAU;EACxB,UAAU;EACV,QAAQ,CAAC,GAAI,MAAM,UAAU,CAAC,CAAE;EAChC,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF;AAEA,SAAgB,gCACd,YACA,SACuC;CACvC,IAAI,CAAC,QAAQ,WAAW,CAAC,WAAW,OAAO,uBAAuB,OAAO,KAAA;CACzE,MAAM,SAAS,QAAQ,QAAQ;CAE/B,MAAM,QAAQ,IAAI,gBAAgB;EAChC,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B;EACA,iBAAiB,WAAW;CAC9B,CAAC;CAED,OAAO,sBAAsB;EAC3B,eAAe;EACf,QAAQ,WAAW;EACnB,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,aAAY,SAAQ,uBAAuB,cAAc,MAAM,CAAC,CAAC,WAAW,IAAI,GAAG,IAAI,CAAC,EAAE,SAAS;EACnG,UAAS,SAAQ,KAAK,gBAAgB;EACtC,WAAW,MAAM,WAAW;GAC1B,YAAY,MAAM;GAClB,UAAU,KAAK,gBAAgB,cAAc,MAAM;GACnD,oBAAoB,MAAM,cAAc,eAAe,MAAM,cAAc;GAC3E,oBAAoB,MAAM,WAAW,cAAc,cAAc;GACjE,iBAAiB,MAAM;GACvB,qBAAqB,MAAM;GAC3B,oBAAoB,MAAM;GAC1B,oBAAoB,MAAM;GAC1B,uBAAuB,iBAAiB,SAAS,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc;GAC7G,OAAO,MAAM;GACb,WAAW,MAAM;GACjB,UAAU,MAAM;GAChB,QAAQ,MAAM;GACd,UAAU,MAAM;GAChB,WAAW,MAAM,aAAa,CAAC;GAC/B,SAAS,MAAM;GACf,QAAQ,MAAM;GACd,QAAQ,MAAM,UAAU,CAAC;GACzB,WAAW,MAAM;GACjB,WAAW,MAAM;EACnB;EACA,UAAU,OAAO,MAAM,OAAO,YAAY;GACxC,MAAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,gBAAgB,cAAc,MAAM,IAAI,KAAK,CAAC;GAC7E,CAAC;EACH;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/incidentio/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { Intake, IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntegrationContext } from '../base.js';\nimport { withIntakeDiscovery } from '../intake-discovery.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { IncidentioEventRules } from './default-rules.js';\nimport { followUpIssues, scopeSourceIdsToProject } from './routes.js';\nimport { IncidentioRules } from './rules.js';\nimport type { IncidentioIssueIngress } from './rules.js';\n\nexport type IncidentioIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(itemRef: string, issue: IntakeIssue): IncidentioIssueIngress {\n return {\n id: itemRef,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n author: issue.author ?? null,\n incident: null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\n/**\n * One incident.io sweep: refresh carded items (metadata, closes), then list\n * what every project's board shows so follow-ups nobody has carded yet get\n * their card. incident.io sends Factory no events, so this is the only\n * first-sight path.\n */\nexport function attachIncidentioIssueReconciler(\n incidentio: { intake: Intake; rules: IncidentioEventRules; isFollowUpSource(sourceId: string): boolean },\n context: IntegrationContext,\n): IncidentioIssueReconciler | undefined {\n if (!context.runtime || !incidentio.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new IncidentioRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n incidentioRules: incidentio.rules,\n });\n\n const reconcile = createIssueReconciler({\n integrationId: 'incidentio',\n intake: incidentio.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n ...(context.runtime.keptCards ? { cards: context.runtime.keptCards } : {}),\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => item.externalSource?.externalId,\n metadata: (item, issue) => ({\n identifier: issue.identifier,\n issueRef: item.externalSource?.externalId ?? issue.id,\n autoStartCandidate: issue.stateType === 'unstarted' || issue.stateType === 'started',\n incidentioItemType: issue.source === 'Follow-up' ? 'follow-up' : 'incident',\n incidentioState: issue.state,\n incidentioStateType: issue.stateType,\n incidentioPriority: issue.priority,\n incidentioAssignee: issue.assignee,\n incidentioDescription: 'description' in issue && typeof issue.description === 'string' ? issue.description : null,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priority,\n source: issue.source,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)],\n });\n },\n });\n\n return withIntakeDiscovery(reconcile, {\n integrationId: 'incidentio',\n intake: context.storage.intake,\n projects: context.storage.projects,\n open: async (project, selectedIds) => {\n const bound = await scopeSourceIdsToProject({\n intake: context.storage.intake,\n orgId: project.orgId,\n factoryProjectId: project.id,\n selectedIds,\n });\n // A board shows follow-ups only, so incidents are never listed.\n return bound\n .filter(sourceId => incidentio.isFollowUpSource(sourceId))\n .map(sourceId => async (cursor: string | undefined) => {\n const page = await incidentio.intake.listItems({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n sourceIds: [sourceId],\n ...(cursor ? { cursor } : {}),\n });\n return { issues: followUpIssues(page.items), nextCursor: page.nextCursor };\n });\n },\n // incident.io lists follow-ups oldest first and cannot sort or filter them by\n // status, so a page cap would never reach the newest ones.\n maxPages: Number.POSITIVE_INFINITY,\n ingest: input => rules.ingest(input),\n });\n}\n"],"mappings":";;;;;;;;AAcA,SAAS,eAAe,SAAiB,OAA4C;CACnF,OAAO;EACL,IAAI;EACJ,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW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aAAa,CAAC;GAC/B,SAAS,MAAM;GACf,QAAQ,MAAM;GACd,QAAQ,MAAM,UAAU,CAAC;GACzB,WAAW,MAAM;GACjB,WAAW,MAAM;EACnB;EACA,UAAU,OAAO,MAAM,OAAO,YAAY;GACxC,MAAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,gBAAgB,cAAc,MAAM,IAAI,KAAK,CAAC;GAC7E,CAAC;EACH;CACF,CAAC;CAED,OAAO,oBAAoB,WAAW;EACpC,eAAe;EACf,QAAQ,QAAQ,QAAQ;EACxB,UAAU,QAAQ,QAAQ;EAC1B,MAAM,OAAO,SAAS,gBAAgB;GAQpC,QAAO,MAPa,wBAAwB;IAC1C,QAAQ,QAAQ,QAAQ;IACxB,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B;GACF,CAAC,EAAA,CAGE,QAAO,aAAY,WAAW,iBAAiB,QAAQ,CAAC,CAAC,CACzD,KAAI,aAAY,OAAO,WAA+B;IACrD,MAAM,OAAO,MAAM,WAAW,OAAO,UAAU;KAC7C,OAAO,QAAQ;KACf,QAAQ;KACR,WAAW,CAAC,QAAQ;KACpB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAC7B,CAAC;IACD,OAAO;KAAE,QAAQ,eAAe,KAAK,KAAK;KAAG,YAAY,KAAK;IAAW;GAC3E,CAAC;EACL;EAGA,UAAU,OAAO;EACjB,SAAQ,UAAS,MAAM,OAAO,KAAK;CACrC,CAAC;AACH"}
@@ -1,3 +1,2 @@
1
- export declare function incidentioReconciliationEnabled(): boolean;
2
1
  export declare function incidentioReconciliationInterval(): number | undefined;
3
2
  //# sourceMappingURL=reconciliation-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"names":[],"mappings":"AAIA,wBAAgB,+BAA+B,IAAI,OAAO,CAQzD;AAED,wBAAgB,gCAAgC,IAAI,MAAM,GAAG,SAAS,CAQrE"}
1
+ {"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"names":[],"mappings":"AAIA,wBAAgB,gCAAgC,IAAI,MAAM,GAAG,SAAS,CAQrE"}
@@ -1,9 +1,6 @@
1
- import { optionalBoolean, optionalPositiveInteger } from "../reconciliation-config.js";
1
+ import { optionalPositiveInteger } from "../reconciliation-config.js";
2
2
  // src/integrations/incidentio/reconciliation-config.ts
3
3
  const RECONCILIATION_LABEL = "incident.io reconciliation";
4
- function incidentioReconciliationEnabled() {
5
- return optionalBoolean("MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED", process.env.MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED, RECONCILIATION_LABEL) ?? true;
6
- }
7
4
  function incidentioReconciliationInterval() {
8
5
  const name = "MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS";
9
6
  const value = process.env.MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS;
@@ -11,6 +8,6 @@ function incidentioReconciliationInterval() {
11
8
  if (value?.trim() && interval === void 0) console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);
12
9
  return interval;
13
10
  }
14
- export { incidentioReconciliationEnabled, incidentioReconciliationInterval };
11
+ export { incidentioReconciliationInterval };
15
12
 
16
13
  //# sourceMappingURL=reconciliation-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconciliation-config.js","names":[],"sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"sourcesContent":["import { optionalBoolean, optionalPositiveInteger } from '../reconciliation-config.js';\n\nconst RECONCILIATION_LABEL = 'incident.io reconciliation';\n\nexport function incidentioReconciliationEnabled(): boolean {\n return (\n optionalBoolean(\n 'MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED',\n process.env.MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED,\n RECONCILIATION_LABEL,\n ) ?? true\n );\n}\n\nexport function incidentioReconciliationInterval(): number | undefined {\n const name = 'MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS';\n const value = process.env.MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS;\n const interval = optionalPositiveInteger(value);\n if (value?.trim() && interval === undefined) {\n console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);\n }\n return interval;\n}\n"],"mappings":";;AAEA,MAAM,uBAAuB;AAE7B,SAAgB,kCAA2C;CACzD,OACE,gBACE,4CACA,QAAQ,IAAI,0CACZ,oBACF,KAAK;AAET;AAEA,SAAgB,mCAAuD;CACrE,MAAM,OAAO;CACb,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,WAAW,wBAAwB,KAAK;CAC9C,IAAI,OAAO,KAAK,KAAK,aAAa,KAAA,GAChC,QAAQ,KAAK,IAAI,qBAAqB,IAAI,KAAK,wCAAwC,KAAK,UAAU,KAAK,EAAE,EAAE;CAEjH,OAAO;AACT"}
1
+ {"version":3,"file":"reconciliation-config.js","names":[],"sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"sourcesContent":["import { optionalPositiveInteger } from '../reconciliation-config.js';\n\nconst RECONCILIATION_LABEL = 'incident.io reconciliation';\n\nexport function incidentioReconciliationInterval(): number | undefined {\n const name = 'MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS';\n const value = process.env.MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS;\n const interval = optionalPositiveInteger(value);\n if (value?.trim() && interval === undefined) {\n console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);\n }\n return interval;\n}\n"],"mappings":";;AAEA,MAAM,uBAAuB;AAE7B,SAAgB,mCAAuD;CACrE,MAAM,OAAO;CACb,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,WAAW,wBAAwB,KAAK;CAC9C,IAAI,OAAO,KAAK,KAAK,aAAa,KAAA,GAChC,QAAQ,KAAK,IAAI,qBAAqB,IAAI,KAAK,wCAAwC,KAAK,UAAU,KAAK,EAAE,EAAE;CAEjH,OAAO;AACT"}