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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (335) hide show
  1. package/README.md +210 -42
  2. package/dist/boards/board-events.d.ts +34 -0
  3. package/dist/boards/board-events.d.ts.map +1 -0
  4. package/dist/boards/board-events.js +50 -0
  5. package/dist/boards/board-events.js.map +1 -0
  6. package/dist/boards/board-writes.d.ts +86 -0
  7. package/dist/boards/board-writes.d.ts.map +1 -0
  8. package/dist/boards/board-writes.js +252 -0
  9. package/dist/boards/board-writes.js.map +1 -0
  10. package/dist/boards/define-board.d.ts +16 -5
  11. package/dist/boards/define-board.d.ts.map +1 -1
  12. package/dist/boards/define-board.js +30 -8
  13. package/dist/boards/define-board.js.map +1 -1
  14. package/dist/boards/intake-routing.d.ts +30 -6
  15. package/dist/boards/intake-routing.d.ts.map +1 -1
  16. package/dist/boards/intake-routing.js +43 -5
  17. package/dist/boards/intake-routing.js.map +1 -1
  18. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  19. package/dist/boards/legacy-plan-role.js +8 -4
  20. package/dist/boards/legacy-plan-role.js.map +1 -1
  21. package/dist/boards/phase-automation.d.ts.map +1 -1
  22. package/dist/boards/phase-automation.js +7 -2
  23. package/dist/boards/phase-automation.js.map +1 -1
  24. package/dist/boards/project-boards.d.ts +18 -7
  25. package/dist/boards/project-boards.d.ts.map +1 -1
  26. package/dist/boards/project-boards.js +78 -14
  27. package/dist/boards/project-boards.js.map +1 -1
  28. package/dist/boards/stored-board.d.ts +59 -1
  29. package/dist/boards/stored-board.d.ts.map +1 -1
  30. package/dist/boards/stored-board.js +219 -7
  31. package/dist/boards/stored-board.js.map +1 -1
  32. package/dist/factory.d.ts +63 -9
  33. package/dist/factory.d.ts.map +1 -1
  34. package/dist/factory.js +187 -22
  35. package/dist/factory.js.map +1 -1
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -3
  39. package/dist/integrations/base.d.ts +6 -0
  40. package/dist/integrations/base.d.ts.map +1 -1
  41. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  42. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  43. package/dist/integrations/github/acceptance-labels.js +1 -1
  44. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  45. package/dist/integrations/github/default-rules.d.ts +2 -9
  46. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  47. package/dist/integrations/github/default-rules.js +7 -6
  48. package/dist/integrations/github/default-rules.js.map +1 -1
  49. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  50. package/dist/integrations/github/issue-reconciler.js +17 -1
  51. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  52. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  53. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  54. package/dist/integrations/github/review-status-comment.js +217 -0
  55. package/dist/integrations/github/review-status-comment.js.map +1 -0
  56. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  57. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  58. package/dist/integrations/github/review-status-reporter.js +100 -0
  59. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  60. package/dist/integrations/github/review-status.d.ts +28 -0
  61. package/dist/integrations/github/review-status.d.ts.map +1 -0
  62. package/dist/integrations/github/review-status.js +95 -0
  63. package/dist/integrations/github/review-status.js.map +1 -0
  64. package/dist/integrations/github/routes.d.ts.map +1 -1
  65. package/dist/integrations/github/routes.js +2 -5
  66. package/dist/integrations/github/routes.js.map +1 -1
  67. package/dist/integrations/github/rules.d.ts +13 -1
  68. package/dist/integrations/github/rules.d.ts.map +1 -1
  69. package/dist/integrations/github/rules.js +77 -6
  70. package/dist/integrations/github/rules.js.map +1 -1
  71. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  72. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  73. package/dist/integrations/gitlab/default-rules.js +4 -4
  74. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  75. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  76. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  77. package/dist/integrations/gitlab/routes.js +1 -3
  78. package/dist/integrations/gitlab/routes.js.map +1 -1
  79. package/dist/integrations/gitlab/rules.d.ts +16 -0
  80. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  81. package/dist/integrations/gitlab/rules.js +69 -4
  82. package/dist/integrations/gitlab/rules.js.map +1 -1
  83. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  84. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  85. package/dist/integrations/incidentio/default-rules.js +3 -4
  86. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  87. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/routes.js +1 -4
  89. package/dist/integrations/incidentio/routes.js.map +1 -1
  90. package/dist/integrations/incidentio/rules.d.ts +7 -0
  91. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  92. package/dist/integrations/incidentio/rules.js +35 -3
  93. package/dist/integrations/incidentio/rules.js.map +1 -1
  94. package/dist/integrations/jira/default-rules.d.ts +1 -9
  95. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  96. package/dist/integrations/jira/default-rules.js +3 -4
  97. package/dist/integrations/jira/default-rules.js.map +1 -1
  98. package/dist/integrations/jira/routes.d.ts.map +1 -1
  99. package/dist/integrations/jira/routes.js +1 -4
  100. package/dist/integrations/jira/routes.js.map +1 -1
  101. package/dist/integrations/jira/rules.d.ts +7 -0
  102. package/dist/integrations/jira/rules.d.ts.map +1 -1
  103. package/dist/integrations/jira/rules.js +35 -3
  104. package/dist/integrations/jira/rules.js.map +1 -1
  105. package/dist/integrations/linear/default-rules.d.ts +1 -9
  106. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/default-rules.js +3 -4
  108. package/dist/integrations/linear/default-rules.js.map +1 -1
  109. package/dist/integrations/linear/routes.d.ts.map +1 -1
  110. package/dist/integrations/linear/routes.js +1 -4
  111. package/dist/integrations/linear/routes.js.map +1 -1
  112. package/dist/integrations/linear/rules.d.ts +7 -0
  113. package/dist/integrations/linear/rules.d.ts.map +1 -1
  114. package/dist/integrations/linear/rules.js +35 -3
  115. package/dist/integrations/linear/rules.js.map +1 -1
  116. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  117. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  118. package/dist/integrations/platform/connect/routes.js +42 -5
  119. package/dist/integrations/platform/connect/routes.js.map +1 -1
  120. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  121. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  122. package/dist/integrations/platform/connect/session-tools.js +30 -0
  123. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  124. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  125. package/dist/integrations/platform/github/integration.js +1 -3
  126. package/dist/integrations/platform/github/integration.js.map +1 -1
  127. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  128. package/dist/integrations/platform/jira/routes.js +1 -4
  129. package/dist/integrations/platform/jira/routes.js.map +1 -1
  130. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  131. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  132. package/dist/integrations/platform/linear/event-worker.js +9 -0
  133. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  134. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  135. package/dist/integrations/platform/linear/integration.js +1 -3
  136. package/dist/integrations/platform/linear/integration.js.map +1 -1
  137. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  138. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  139. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  140. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  141. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  142. package/dist/integrations/slack/connect-route.js +1 -1
  143. package/dist/integrations/slack/connect-route.js.map +1 -1
  144. package/dist/integrations/slack/integration.d.ts.map +1 -1
  145. package/dist/integrations/slack/integration.js +2 -0
  146. package/dist/integrations/slack/integration.js.map +1 -1
  147. package/dist/integrations/slack/slack.d.ts +12 -10
  148. package/dist/integrations/slack/slack.d.ts.map +1 -1
  149. package/dist/integrations/slack/slack.js +110 -43
  150. package/dist/integrations/slack/slack.js.map +1 -1
  151. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  152. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  153. package/dist/integrations/slack/voice-clips.js +201 -0
  154. package/dist/integrations/slack/voice-clips.js.map +1 -0
  155. package/dist/integrations/workos/integration.d.ts.map +1 -1
  156. package/dist/integrations/workos/integration.js +1 -3
  157. package/dist/integrations/workos/integration.js.map +1 -1
  158. package/dist/mcp/routes.js +1 -1
  159. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  160. package/dist/routes/attention-activity.js +1 -1
  161. package/dist/routes/attention-providers.js +1 -1
  162. package/dist/routes/automation-runs.d.ts.map +1 -1
  163. package/dist/routes/automation-runs.js +1 -4
  164. package/dist/routes/automation-runs.js.map +1 -1
  165. package/dist/routes/boards.d.ts +8 -6
  166. package/dist/routes/boards.d.ts.map +1 -1
  167. package/dist/routes/boards.js +73 -143
  168. package/dist/routes/boards.js.map +1 -1
  169. package/dist/routes/config.d.ts.map +1 -1
  170. package/dist/routes/config.js +3 -8
  171. package/dist/routes/config.js.map +1 -1
  172. package/dist/routes/contracts.d.ts +132 -0
  173. package/dist/routes/contracts.d.ts.map +1 -1
  174. package/dist/routes/contracts.js +77 -29
  175. package/dist/routes/contracts.js.map +1 -1
  176. package/dist/routes/fs.d.ts.map +1 -1
  177. package/dist/routes/fs.js +1 -4
  178. package/dist/routes/fs.js.map +1 -1
  179. package/dist/routes/intake-routes.d.ts.map +1 -1
  180. package/dist/routes/intake-routes.js +19 -12
  181. package/dist/routes/intake-routes.js.map +1 -1
  182. package/dist/routes/intake.d.ts.map +1 -1
  183. package/dist/routes/intake.js +3 -5
  184. package/dist/routes/intake.js.map +1 -1
  185. package/dist/routes/knowledge.d.ts.map +1 -1
  186. package/dist/routes/knowledge.js +1 -4
  187. package/dist/routes/knowledge.js.map +1 -1
  188. package/dist/routes/oauth.d.ts.map +1 -1
  189. package/dist/routes/oauth.js +1 -4
  190. package/dist/routes/oauth.js.map +1 -1
  191. package/dist/routes/projects.d.ts +3 -0
  192. package/dist/routes/projects.d.ts.map +1 -1
  193. package/dist/routes/projects.js +7 -4
  194. package/dist/routes/projects.js.map +1 -1
  195. package/dist/routes/provider-credentials.d.ts.map +1 -1
  196. package/dist/routes/provider-credentials.js +6 -0
  197. package/dist/routes/provider-credentials.js.map +1 -1
  198. package/dist/routes/route.d.ts +2 -0
  199. package/dist/routes/route.d.ts.map +1 -1
  200. package/dist/routes/route.js +5 -1
  201. package/dist/routes/route.js.map +1 -1
  202. package/dist/routes/skills.d.ts.map +1 -1
  203. package/dist/routes/skills.js +1 -4
  204. package/dist/routes/skills.js.map +1 -1
  205. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  206. package/dist/routes/source-control-sessions.js +1 -3
  207. package/dist/routes/source-control-sessions.js.map +1 -1
  208. package/dist/routes/source-control-settings.d.ts.map +1 -1
  209. package/dist/routes/source-control-settings.js +3 -2
  210. package/dist/routes/source-control-settings.js.map +1 -1
  211. package/dist/routes/surface.d.ts +3 -1
  212. package/dist/routes/surface.d.ts.map +1 -1
  213. package/dist/routes/surface.js +11 -1
  214. package/dist/routes/surface.js.map +1 -1
  215. package/dist/routes/voice.d.ts +48 -0
  216. package/dist/routes/voice.d.ts.map +1 -0
  217. package/dist/routes/voice.js +248 -0
  218. package/dist/routes/voice.js.map +1 -0
  219. package/dist/routes/work-items.d.ts.map +1 -1
  220. package/dist/routes/work-items.js +1 -4
  221. package/dist/routes/work-items.js.map +1 -1
  222. package/dist/rules/decision-applicability.js +1 -1
  223. package/dist/rules/dispatcher.d.ts +28 -0
  224. package/dist/rules/dispatcher.d.ts.map +1 -1
  225. package/dist/rules/dispatcher.js +391 -93
  226. package/dist/rules/dispatcher.js.map +1 -1
  227. package/dist/rules/event-rules.d.ts +40 -1
  228. package/dist/rules/event-rules.d.ts.map +1 -1
  229. package/dist/rules/event-rules.js +59 -1
  230. package/dist/rules/event-rules.js.map +1 -1
  231. package/dist/rules/processor.js +1 -1
  232. package/dist/rules/processor.js.map +1 -1
  233. package/dist/rules/transition-service.d.ts +9 -0
  234. package/dist/rules/transition-service.d.ts.map +1 -1
  235. package/dist/rules/transition-service.js +4 -2
  236. package/dist/rules/transition-service.js.map +1 -1
  237. package/dist/rules/types.d.ts +54 -3
  238. package/dist/rules/types.d.ts.map +1 -1
  239. package/dist/rules/types.js +2 -0
  240. package/dist/rules/types.js.map +1 -1
  241. package/dist/rules/validation.d.ts.map +1 -1
  242. package/dist/rules/validation.js +57 -2
  243. package/dist/rules/validation.js.map +1 -1
  244. package/dist/session/credential-policy.d.ts +2 -2
  245. package/dist/session/credential-policy.d.ts.map +1 -1
  246. package/dist/session/credential-policy.js +3 -3
  247. package/dist/session/credential-policy.js.map +1 -1
  248. package/dist/session/default-model-hydration.d.ts +2 -2
  249. package/dist/session/default-model-hydration.d.ts.map +1 -1
  250. package/dist/session/default-model-hydration.js +4 -4
  251. package/dist/session/default-model-hydration.js.map +1 -1
  252. package/dist/session/session-threads.d.ts +8 -0
  253. package/dist/session/session-threads.d.ts.map +1 -1
  254. package/dist/session/session-threads.js +11 -1
  255. package/dist/session/session-threads.js.map +1 -1
  256. package/dist/skills/catalog.js +1 -1
  257. package/dist/storage/domains/audit/actions.d.ts +1 -1
  258. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  259. package/dist/storage/domains/audit/actions.js +2 -1
  260. package/dist/storage/domains/audit/actions.js.map +1 -1
  261. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  262. package/dist/storage/domains/audit/domain.js +1 -3
  263. package/dist/storage/domains/audit/domain.js.map +1 -1
  264. package/dist/storage/domains/boards/base.d.ts +32 -1
  265. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  266. package/dist/storage/domains/boards/base.js +155 -8
  267. package/dist/storage/domains/boards/base.js.map +1 -1
  268. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  269. package/dist/storage/domains/boards/schemas.js +13 -1
  270. package/dist/storage/domains/boards/schemas.js.map +1 -1
  271. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  272. package/dist/storage/domains/comments/routes.js +1 -3
  273. package/dist/storage/domains/comments/routes.js.map +1 -1
  274. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  275. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  276. package/dist/storage/domains/memory-settings/base.js +1 -11
  277. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  278. package/dist/storage/domains/projects/base.d.ts +6 -0
  279. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  280. package/dist/storage/domains/projects/base.js +9 -1
  281. package/dist/storage/domains/projects/base.js.map +1 -1
  282. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  283. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  284. package/dist/storage/domains/voice-settings/base.js +81 -0
  285. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  286. package/dist/storage/domains/work-items/base.d.ts +31 -2
  287. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  288. package/dist/storage/domains/work-items/base.js +197 -44
  289. package/dist/storage/domains/work-items/base.js.map +1 -1
  290. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  291. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  292. package/dist/storage/domains/work-items/cards.js +54 -4
  293. package/dist/storage/domains/work-items/cards.js.map +1 -1
  294. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  295. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  296. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  297. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  298. package/dist/timing.d.ts +1 -0
  299. package/dist/timing.d.ts.map +1 -1
  300. package/dist/timing.js +1 -1
  301. package/dist/timing.js.map +1 -1
  302. package/dist/tools/read-tools.d.ts +2 -2
  303. package/dist/tools/read-tools.d.ts.map +1 -1
  304. package/dist/tools/read-tools.js +7 -6
  305. package/dist/tools/read-tools.js.map +1 -1
  306. package/dist/tools/session-tools.d.ts +1 -1
  307. package/dist/tools/session-tools.d.ts.map +1 -1
  308. package/dist/tools/session-tools.js.map +1 -1
  309. package/dist/tools/sessions-state-processor.d.ts +1 -1
  310. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  311. package/dist/tools/sessions-state-processor.js +9 -2
  312. package/dist/tools/sessions-state-processor.js.map +1 -1
  313. package/dist/tools/work-item-tools.js +2 -2
  314. package/dist/voice/rate-limit.d.ts +13 -0
  315. package/dist/voice/rate-limit.d.ts.map +1 -0
  316. package/dist/voice/rate-limit.js +36 -0
  317. package/dist/voice/rate-limit.js.map +1 -0
  318. package/dist/voice/realtime.d.ts +13 -0
  319. package/dist/voice/realtime.d.ts.map +1 -0
  320. package/dist/voice/realtime.js +56 -0
  321. package/dist/voice/realtime.js.map +1 -0
  322. package/dist/voice/transcription.d.ts +51 -0
  323. package/dist/voice/transcription.d.ts.map +1 -0
  324. package/dist/voice/transcription.js +112 -0
  325. package/dist/voice/transcription.js.map +1 -0
  326. package/dist/work-items/split-backfill.d.ts +13 -0
  327. package/dist/work-items/split-backfill.d.ts.map +1 -0
  328. package/dist/work-items/split-backfill.js +32 -0
  329. package/dist/work-items/split-backfill.js.map +1 -0
  330. package/dist/work-items/split-migration.d.ts +39 -2
  331. package/dist/work-items/split-migration.d.ts.map +1 -1
  332. package/dist/work-items/split-migration.js +170 -62
  333. package/dist/work-items/split-migration.js.map +1 -1
  334. package/dist/workspace.js +2 -2
  335. package/package.json +12 -11
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/gitlab/rules.ts"],"sourcesContent":["import {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { hasExplicitRuleOverride, selectEventRule } from '../../rules/event-rules.js';\nimport type {\n FactoryGitLabEventName,\n FactoryGitLabRuleContext,\n FactoryRuleActor,\n FactoryRuleDecision,\n} from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.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 { recordPullRequestHead } from '../pull-request-head.js';\nimport type { GitLabEventRules } from './default-rules.js';\nimport { 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\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' || action === 'reopen') return 'issueOpened';\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\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\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 boards: BoardRegistry;\n}\n\ninterface ProjectTarget {\n target: ExternalRepositoryProjectTarget;\n connectionIds: string[];\n}\n\nexport class GitLabRules {\n constructor(private readonly options: GitLabRulesOptions) {}\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 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 const board = this.options.boards.get(binding.board ?? 'work');\n if (!board) 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 const items = await this.options.storage.list({\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n });\n const issueItem = issueSourceKey\n ? items.find(\n item => item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === issueSourceKey,\n )\n : undefined;\n const reviewItem = mergeRequestKey\n ? items.find(\n item => item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === mergeRequestKey,\n )\n : undefined;\n const headBranch = string(mergeRequest?.source_branch) ?? '';\n const authoringItem = headBranch\n ? items.find(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n Object.values(item.sessions).some(session => session.branch === headBranch),\n )\n : 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\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 && 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 candidates: Array<Card | undefined> =\n event === 'mergeRequestMerged'\n ? [...new Map([reviewItem, authoringItem].filter(Boolean).map(item => [item!.id, item!])).values()]\n : event === 'mergeRequestCommented'\n ? [authoringItem ?? reviewItem]\n : event === 'mergeRequestOpened'\n ? [authoringItem, ...(authoringItem ? [authoringItem] : [])]\n : event.startsWith('mergeRequest')\n ? [pushedReviewItem ?? 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: { board: board.id, initialPhase: board.initialPhase },\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 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\n ? items.filter(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n Object.values(item.sessions).some(session => session.branch === headBranch),\n )\n : [];\n if (authoringItem && mergeRequestIid && branchOwners.length === 1) {\n await this.#trackOpenMergeRequest({\n orgId: authoringItem.orgId,\n id: authoringItem.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 });\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 }): 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) {\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 (recorded === input.mergeRequestIid) {\n patch.openPullRequestNumber = null;\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: { board: string; initialPhase: string };\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 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.options.boards, input.item),\n ...rulePhaseField(this.options.boards, input.item),\n }\n : {}),\n intake: input.board,\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 boardRules = boardEventHandlers(\n this.options.boards,\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 let decision: FactoryRuleDecision | void;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.options.boards,\n 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\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 configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return event => rules.ingest(event);\n}\n"],"mappings":";;;;;;;;AA8BA,MAAM,kBAAkB;AAIxB,SAAS,OAAO,OAAqD;CACnE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IAAK,QAAoC,KAAA;AAC5G;AAEA,SAAS,OAAO,OAAoC;CAClD,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ,KAAA;AACjE;AAEA,SAAS,OAAO,OAAoC;CAClD,OAAO,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,IAAI,QAAQ,KAAA;AACvE;;AAGA,SAAS,UAAU,OAAoC;CACrD,MAAM,OAAO,OAAO,KAAK;CACzB,IAAI,CAAC,MAAM,OAAO,KAAA;CAClB,MAAM,SAAS,mFAAmF,KAAK,IAAI;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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 eventBoardId,\n rulePhaseField,\n withBoardClosure,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { deploymentOwnsEvent, hasExplicitRuleOverride, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type {\n FactoryGitLabEventName,\n FactoryGitLabRuleContext,\n FactoryRuleActor,\n FactoryRuleDecision,\n FactorySignalActivityDecision,\n} from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.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 { recordPullRequestHead } from '../pull-request-head.js';\nimport type { GitLabEventRules } from './default-rules.js';\nimport { 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\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\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 boards: BoardRegistry;\n}\n\ninterface ProjectTarget {\n target: ExternalRepositoryProjectTarget;\n connectionIds: string[];\n}\n\nexport class GitLabRules {\n constructor(private readonly options: GitLabRulesOptions) {}\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 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 const board = this.options.boards.get(binding.board ?? 'work');\n if (!board) 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 const items = await this.options.storage.list({\n orgId: target.target.orgId,\n factoryProjectId: target.target.factoryProjectId,\n });\n const issueItem = issueSourceKey\n ? items.find(\n item => item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === issueSourceKey,\n )\n : undefined;\n const reviewItem = mergeRequestKey\n ? items.find(\n item => item.externalSource?.integrationId === 'gitlab' && item.externalSource.externalId === mergeRequestKey,\n )\n : undefined;\n const headBranch = string(mergeRequest?.source_branch) ?? '';\n const authoringItem = headBranch\n ? items.find(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n Object.values(item.sessions).some(session => session.branch === headBranch),\n )\n : 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\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 && 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 candidates: Array<Card | undefined> =\n event === 'mergeRequestMerged'\n ? [...new Map([reviewItem, authoringItem].filter(Boolean).map(item => [item!.id, item!])).values()]\n : event === 'mergeRequestCommented'\n ? [authoringItem ?? reviewItem]\n : event === 'mergeRequestOpened'\n ? [authoringItem, ...(authoringItem ? [authoringItem] : [])]\n : event.startsWith('mergeRequest')\n ? [pushedReviewItem ?? 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: { board: board.id, initialPhase: board.initialPhase },\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 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\n ? items.filter(\n item =>\n item.externalSource?.type !== 'pull-request' &&\n Object.values(item.sessions).some(session => session.branch === headBranch),\n )\n : [];\n if (authoringItem && mergeRequestIid && branchOwners.length === 1) {\n await this.#trackOpenMergeRequest({\n orgId: authoringItem.orgId,\n id: authoringItem.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 });\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 }): 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) {\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 (recorded === input.mergeRequestIid) {\n patch.openPullRequestNumber = null;\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: { board: string; initialPhase: string };\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 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.options.boards, input.item),\n ...rulePhaseField(this.options.boards, input.item),\n }\n : {}),\n intake: input.board,\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.options.boards,\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.options.boards,\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 configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return event => rules.ingest(event);\n}\n"],"mappings":";;;;;;;;;AAiCA,MAAM,kBAAkB;AAIxB,SAAS,OAAO,OAAqD;CACnE,OAAO,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,I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AAS;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"}
@@ -27,15 +27,7 @@ declare function incidentioFollowUpObserved(context: FactoryIncidentioRuleContex
27
27
  readonly updatedAt: string;
28
28
  };
29
29
  } | undefined;
30
- declare function incidentioFollowUpClosed(context: FactoryIncidentioRuleContext): {
31
- readonly type: 'transition';
32
- readonly idempotencyKey: `${string}:follow-up-closed`;
33
- readonly board: import("../../rules/types.js").FactoryRuleBoard;
34
- readonly stage: string;
35
- readonly message: {
36
- readonly text: `incident.io follow-up ${string} was canceled; this ${string} card was moved to ${string}.` | `incident.io follow-up ${string} was completed; this ${string} card was moved to ${string}.`;
37
- };
38
- } | undefined;
30
+ declare function incidentioFollowUpClosed(context: FactoryIncidentioRuleContext): import("../../rules/types.js").FactoryTransitionDecision | undefined;
39
31
  export declare const defaultIncidentioRules: Readonly<{
40
32
  followUpObserved: typeof incidentioFollowUpObserved;
41
33
  followUpClosed: typeof incidentioFollowUpClosed;
@@ -1 +1 @@
1
- {"version":3,"file":"default-rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/default-rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EACnB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,MAAM,uBAAuB,GAAG,OAAO,CAC3C,MAAM,CAAC,0BAA0B,EAAE,kBAAkB,CAAC,4BAA4B,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC,CACxG,CAAC;AACF,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CACzC,MAAM,CAAC,0BAA0B,EAAE,kBAAkB,CAAC,4BAA4B,CAAC,GAAG,IAAI,CAAC,CAC5F,CAAC;AAEF,iBAAS,0BAA0B,CAAC,OAAO,EAAE,4BAA4B;mBAG/D,sBAAsB;;;qBAKpB,sBAAsB;;;;;;iBAM5B,UAAU;iBACV,QAAQ;iBACR,eAAe;iBACf,KAAK;iBACL,SAAS;iBACT,QAAQ;iBACR,QAAQ;iBACR,QAAQ;iBACR,SAAS,EAA8D,MAAM,EAAE;iBAC/E,OAAO;iBACP,MAAM;iBACN,MAAM,EAA+B,MAAM,EAAE;iBAC7C,SAAS;iBACT,SAAS;;cAGd;AAED,iBAAS,wBAAwB,CAAC,OAAO,EAAE,4BAA4B;mBAY7D,YAAY;;;;;iBAKhB,IAAI;;cAGT;AAED,eAAO,MAAM,sBAAsB;;;EAGF,CAAC;AAElC,wBAAgB,sBAAsB,CAAC,SAAS,CAAC,EAAE,uBAAuB,GAAG,oBAAoB,CAwBhG"}
1
+ {"version":3,"file":"default-rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/default-rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,0BAA0B,EAC1B,4BAA4B,EAC5B,kBAAkB,EACnB,MAAM,sBAAsB,CAAC;AAE9B,MAAM,MAAM,uBAAuB,GAAG,OAAO,CAC3C,MAAM,CAAC,0BAA0B,EAAE,kBAAkB,CAAC,4BAA4B,CAAC,GAAG,IAAI,GAAG,SAAS,CAAC,CACxG,CAAC;AACF,MAAM,MAAM,oBAAoB,GAAG,QAAQ,CACzC,MAAM,CAAC,0BAA0B,EAAE,kBAAkB,CAAC,4BAA4B,CAAC,GAAG,IAAI,CAAC,CAC5F,CAAC;AAEF,iBAAS,0BAA0B,CAAC,OAAO,EAAE,4BAA4B;mBAG/D,sBAAsB;;;qBAKpB,sBAAsB;;;;;;iBAM5B,UAAU;iBACV,QAAQ;iBACR,eAAe;iBACf,KAAK;iBACL,SAAS;iBACT,QAAQ;iBACR,QAAQ;iBACR,QAAQ;iBACR,SAAS,EAA8D,MAAM,EAAE;iBAC/E,OAAO;iBACP,MAAM;iBACN,MAAM,EAA+B,MAAM,EAAE;iBAC7C,SAAS;iBACT,SAAS;;cAGd;AAED,iBAAS,wBAAwB,CAAC,OAAO,EAAE,4BAA4B,wEAoBtE;AAED,eAAO,MAAM,sBAAsB;;;EAGF,CAAC;AAElC,wBAAgB,sBAAsB,CAAC,SAAS,CAAC,EAAE,uBAAuB,GAAG,oBAAoB,CAwBhG"}
@@ -1,4 +1,4 @@
1
- import { recordExplicitRuleOverrides } from "../../rules/event-rules.js";
1
+ import { closedByRoutes, recordExplicitRuleOverrides } from "../../rules/event-rules.js";
2
2
  // src/integrations/incidentio/default-rules.ts
3
3
  function incidentioFollowUpObserved(context) {
4
4
  if (context.item) return;
@@ -37,13 +37,12 @@ function incidentioFollowUpClosed(context) {
37
37
  if (stateType !== "completed" && stateType !== "canceled") return;
38
38
  const canceled = stateType === "canceled";
39
39
  const target = canceled ? closure.canceled : closure.completed;
40
- return {
41
- type: "transition",
40
+ return closedByRoutes(canceled, {
42
41
  idempotencyKey: `${context.ingress.id}:follow-up-closed`,
43
42
  board: context.board,
44
43
  stage: target.phase,
45
44
  message: { text: `incident.io follow-up ${context.issue.identifier} was ${canceled ? "canceled" : "completed"}; this ${closure.boardTitle} card was moved to ${target.title}.` }
46
- };
45
+ });
47
46
  }
48
47
  const defaultIncidentioRules = Object.freeze({
49
48
  followUpObserved: incidentioFollowUpObserved,
@@ -1 +1 @@
1
- {"version":3,"file":"default-rules.js","names":[],"sources":["../../../src/integrations/incidentio/default-rules.ts"],"sourcesContent":["import { recordExplicitRuleOverrides } from '../../rules/event-rules.js';\nimport type {\n FactoryIncidentioEventName,\n FactoryIncidentioRuleContext,\n FactoryRuleHandler,\n} from '../../rules/types.js';\n\nexport type IncidentioRuleOverrides = Partial<\n Record<FactoryIncidentioEventName, FactoryRuleHandler<FactoryIncidentioRuleContext> | null | undefined>\n>;\nexport type IncidentioEventRules = Readonly<\n Record<FactoryIncidentioEventName, FactoryRuleHandler<FactoryIncidentioRuleContext> | null>\n>;\n\nfunction incidentioFollowUpObserved(context: FactoryIncidentioRuleContext) {\n if (context.item) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:follow-up-triage`,\n // A source bound to a custom board lands on that board's initial phase;\n // otherwise the follow-up waits in Work Intake.\n board: context.intake?.board ?? 'work',\n source: 'incidentio-follow-up',\n sourceKey: context.issue.id,\n title: context.issue.title,\n url: context.issue.url,\n stage: context.intake?.initialPhase ?? 'intake',\n metadata: {\n identifier: context.issue.identifier,\n issueRef: context.issue.id,\n sourceCreatedAt: context.issue.createdAt,\n state: context.issue.state,\n stateType: context.issue.stateType,\n priority: context.issue.priorityLabel,\n incident: context.issue.incident,\n assignee: context.issue.assignee,\n assignees: (context.issue.assignee ? [context.issue.assignee] : []) as string[],\n creator: context.issue.author,\n author: context.issue.author,\n labels: [...context.issue.labels] as string[],\n createdAt: context.issue.createdAt,\n updatedAt: context.issue.updatedAt,\n },\n } as const;\n}\n\nfunction incidentioFollowUpClosed(context: FactoryIncidentioRuleContext) {\n if (!context.item || context.item.source !== 'incidentio-follow-up') return;\n // The card's board decides where a closed source sends it; boards that declare no\n // `sourceClosed` mapping keep the card where it is, as do cards already finished.\n const closure = context.boardClosure;\n if (!context.board || !closure || closure.itemTerminal) return;\n // Only terminal state types trigger close.\n const stateType = context.issue.stateType;\n if (stateType !== 'completed' && stateType !== 'canceled') return;\n const canceled = stateType === 'canceled';\n const target = canceled ? closure.canceled : closure.completed;\n return {\n type: 'transition',\n idempotencyKey: `${context.ingress.id}:follow-up-closed`,\n board: context.board,\n stage: target.phase,\n message: {\n text: `incident.io follow-up ${context.issue.identifier} was ${canceled ? 'canceled' : 'completed'}; this ${closure.boardTitle} card was moved to ${target.title}.`,\n },\n } as const;\n}\n\nexport const defaultIncidentioRules = Object.freeze({\n followUpObserved: incidentioFollowUpObserved,\n followUpClosed: incidentioFollowUpClosed,\n} satisfies IncidentioEventRules);\n\nexport function resolveIncidentioRules(overrides?: IncidentioRuleOverrides): IncidentioEventRules {\n if (\n overrides !== undefined &&\n (overrides === null ||\n typeof overrides !== 'object' ||\n Array.isArray(overrides) ||\n ![Object.prototype, null].includes(Object.getPrototypeOf(overrides)))\n ) {\n throw new Error('incident.io rules must be a plain object.');\n }\n const rules: Record<string, FactoryRuleHandler<FactoryIncidentioRuleContext> | null> = {\n ...defaultIncidentioRules,\n };\n for (const key of Reflect.ownKeys(overrides ?? {})) {\n if (typeof key !== 'string' || !Object.hasOwn(defaultIncidentioRules, key)) {\n throw new Error(`Unknown incident.io rule event: ${String(key)}.`);\n }\n const handler = overrides?.[key as FactoryIncidentioEventName];\n if (handler !== undefined && handler !== null && typeof handler !== 'function') {\n throw new Error(`incident.io rule ${key} must be a function, null, or undefined.`);\n }\n if (handler !== undefined) rules[key] = handler;\n }\n return recordExplicitRuleOverrides(Object.freeze(rules) as IncidentioEventRules, overrides);\n}\n"],"mappings":";;AAcA,SAAS,2BAA2B,SAAuC;CACzE,IAAI,QAAQ,MAAM;CAClB,OAAO;EACL,MAAM;EACN,gBAAgB,GAAG,QAAQ,QAAQ,GAAG;EAGtC,OAAO,QAAQ,QAAQ,SAAS;EA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AA,MACb,cAAc,QACb,OAAO,cAAc,YACrB,MAAM,QAAQ,SAAS,KACvB,CAAC,CAAC,OAAO,WAAW,IAAI,CAAC,CAAC,SAAS,OAAO,eAAe,SAAS,CAAC,IAErE,MAAM,IAAI,MAAM,2CAA2C;CAE7D,MAAM,QAAiF,EACrF,GAAG,uBACL;CACA,KAAK,MAAM,OAAO,QAAQ,QAAQ,aAAa,CAAC,CAAC,GAAG;EAClD,IAAI,OAAO,QAAQ,YAAY,CAAC,OAAO,OAAO,wBAAwB,GAAG,GACvE,MAAM,IAAI,MAAM,mCAAmC,OAAO,GAAG,EAAE,EAAE;EAEnE,MAAM,UAAU,YAAY;EAC5B,IAAI,YAAY,KAAA,KAAa,YAAY,QAAQ,OAAO,YAAY,YAClE,MAAM,IAAI,MAAM,oBAAoB,IAAI,yCAAyC;EAEnF,IAAI,YAAY,KAAA,GAAW,MAAM,OAAO;CAC1C;CACA,OAAO,4BAA4B,OAAO,OAAO,KAAK,GAA2B,SAAS;AAC5F"}
1
+ {"version":3,"file":"default-rules.js","names":[],"sources":["../../../src/integrations/incidentio/default-rules.ts"],"sourcesContent":["import { closedByRoutes, recordExplicitRuleOverrides } from '../../rules/event-rules.js';\nimport type {\n FactoryIncidentioEventName,\n FactoryIncidentioRuleContext,\n FactoryRuleHandler,\n} from '../../rules/types.js';\n\nexport type IncidentioRuleOverrides = Partial<\n Record<FactoryIncidentioEventName, FactoryRuleHandler<FactoryIncidentioRuleContext> | null | undefined>\n>;\nexport type IncidentioEventRules = Readonly<\n Record<FactoryIncidentioEventName, FactoryRuleHandler<FactoryIncidentioRuleContext> | null>\n>;\n\nfunction incidentioFollowUpObserved(context: FactoryIncidentioRuleContext) {\n if (context.item) return;\n return {\n type: 'upsertLinkedWorkItem',\n idempotencyKey: `${context.ingress.id}:follow-up-triage`,\n // A source bound to a custom board lands on that board's initial phase;\n // otherwise the follow-up waits in Work Intake.\n board: context.intake?.board ?? 'work',\n source: 'incidentio-follow-up',\n sourceKey: context.issue.id,\n title: context.issue.title,\n url: context.issue.url,\n stage: context.intake?.initialPhase ?? 'intake',\n metadata: {\n identifier: context.issue.identifier,\n issueRef: context.issue.id,\n sourceCreatedAt: context.issue.createdAt,\n state: context.issue.state,\n stateType: context.issue.stateType,\n priority: context.issue.priorityLabel,\n incident: context.issue.incident,\n assignee: context.issue.assignee,\n assignees: (context.issue.assignee ? [context.issue.assignee] : []) as string[],\n creator: context.issue.author,\n author: context.issue.author,\n labels: [...context.issue.labels] as string[],\n createdAt: context.issue.createdAt,\n updatedAt: context.issue.updatedAt,\n },\n } as const;\n}\n\nfunction incidentioFollowUpClosed(context: FactoryIncidentioRuleContext) {\n if (!context.item || context.item.source !== 'incidentio-follow-up') return;\n // The project's intake routes decide where a closed source sends the card. The board's\n // `sourceClosed` mapping applies only when no route on the board handles closes; without\n // one the close goes to the routes alone (see `routeEventDecision`).\n const closure = context.boardClosure;\n if (!context.board || !closure || closure.itemTerminal) return;\n // Only terminal state types trigger close.\n const stateType = context.issue.stateType;\n if (stateType !== 'completed' && stateType !== 'canceled') return;\n const canceled = stateType === 'canceled';\n const target = canceled ? closure.canceled : closure.completed;\n return closedByRoutes(canceled, {\n idempotencyKey: `${context.ingress.id}:follow-up-closed`,\n board: context.board,\n stage: target.phase,\n message: {\n text: `incident.io follow-up ${context.issue.identifier} was ${canceled ? 'canceled' : 'completed'}; this ${closure.boardTitle} card was moved to ${target.title}.`,\n },\n });\n}\n\nexport const defaultIncidentioRules = Object.freeze({\n followUpObserved: incidentioFollowUpObserved,\n followUpClosed: incidentioFollowUpClosed,\n} satisfies IncidentioEventRules);\n\nexport function resolveIncidentioRules(overrides?: IncidentioRuleOverrides): IncidentioEventRules {\n if (\n overrides !== undefined &&\n (overrides === null ||\n typeof overrides !== 'object' ||\n Array.isArray(overrides) ||\n ![Object.prototype, null].includes(Object.getPrototypeOf(overrides)))\n ) {\n throw new Error('incident.io rules must be a plain object.');\n }\n const rules: Record<string, FactoryRuleHandler<FactoryIncidentioRuleContext> | null> = {\n ...defaultIncidentioRules,\n };\n for (const key of Reflect.ownKeys(overrides ?? {})) {\n if (typeof key !== 'string' || !Object.hasOwn(defaultIncidentioRules, key)) {\n throw new Error(`Unknown incident.io rule event: ${String(key)}.`);\n }\n const handler = overrides?.[key as FactoryIncidentioEventName];\n if (handler !== undefined && handler !== null && typeof handler !== 'function') {\n throw new Error(`incident.io rule ${key} must be a function, null, or undefined.`);\n }\n if (handler !== undefined) rules[key] = handler;\n }\n return recordExplicitRuleOverrides(Object.freeze(rules) as IncidentioEventRules, overrides);\n}\n"],"mappings":";;AAcA,SAAS,2BAA2B,SAAuC;CACzE,IAAI,QAAQ,MAAM;CAClB,OAAO;EACL,MAAM;EACN,gBAAgB,GAAG,QAAQ,QAAQ,GAAG;EAGtC,OAAO,QAAQ,QAAQ,SAAS;EAChC,QAAQ;EACR,WAAW,QAAQ,MAAM;EACzB,OAAO,QAAQ,MAAM;EACrB,KAAK,QAAQ,MAAM;EACnB,OAAO,QAAQ,QAAQ,gBAAgB;EACvC,UAAU;GACR,YAAY,QAAQ,MAAM;GAC1B,UAAU,QAAQ,MAAM;GACxB,iBAAiB,QAAQ,MAAM;GAC/B,OAAO,QAAQ,MAAM;GACrB,WAAW,QAAQ,MAAM;GACzB,UAAU,QAAQ,MAAM;GACxB,UAAU,QAAQ,MAAM;GACxB,UAAU,QAAQ,MAAM;GACxB,WAAY,QAAQ,MAAM,WAAW,CAAC,QAAQ,MAAM,QAAQ,IAAI,CAAC;GACjE,SAAS,QAAQ,MAAM;GACvB,QAAQ,QAAQ,MAAM;GACtB,QAAQ,CAAC,GAAG,QAAQ,MAAM,MAAM;GAChC,WAAW,QAAQ,MAAM;GACzB,WAAW,QAAQ,MAAM;EAC3B;CACF;AACF;AAEA,SAAS,yBAAyB,SAAuC;CACvE,IAAI,CAAC,QAAQ,QAAQ,QAAQ,KAAK,WAAW,wBAAwB;CAIrE,MAAM,UAAU,QAAQ;CACxB,IAAI,CAAC,QAAQ,SAA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CASlC;AAqED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,QAAQ,EAAE,CAiNvF"}
@@ -1,13 +1,10 @@
1
+ import { loose } from "../../routes/route.js";
1
2
  import { IncidentioApiError } from "./api.js";
2
3
  import { registerApiRoute } from "@mastra/core/server";
3
4
  // src/integrations/incidentio/routes.ts
4
5
  const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
5
6
  const ITEM_REF_RE = /^incidentio:(?:follow-up|incident):[\w-]+$/;
6
7
  const FOLLOW_UP_PREFIX = "incidentio:follow-up:";
7
- /** Erase a route handler's path-parameterized context to a plain `Context`. */
8
- function loose(c) {
9
- return c;
10
- }
11
8
  /**
12
9
  * Narrow the caller's selected incident.io sources to the ones that feed this
13
10
  * Factory project. Routing is explicit: a source feeds this Factory only when
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/incidentio/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the incident.io intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Mirrors the Jira module: no connect/callback flow here — credentials are\n * either deployment-global constructor config (direct) or Platform-managed\n * connections discovered at runtime. Every route re-resolves the\n * authenticated user from the request and scopes intake selections by the\n * caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildIncidentioRoutes` returns only `GET /web/incidentio/status`, which\n * reports `enabled:false` so the SPA can cleanly hide all incident.io UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { Intake } from '../../capabilities/intake.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport { IncidentioApiError } from './api.js';\nimport type { IncidentioRulesIngress } from './rules.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ITEM_REF_RE = /^incidentio:(?:follow-up|incident):[\\w-]+$/;\nconst FOLLOW_UP_PREFIX = 'incidentio:follow-up:';\n\n/** Erase a route handler's path-parameterized context to a plain `Context`. */\nfunction loose(c: unknown): RouteContext {\n return c as RouteContext;\n}\n\n/**\n * Non-secret diagnostic snapshot of every incident.io feature gate, mirroring\n * the Jira diagnostics shape. Only booleans — never values.\n */\nexport interface IncidentioFeatureDiagnostics {\n incidentioConfigured: boolean;\n factoryAuthEnabled: boolean;\n}\n\nexport interface MountIncidentioRoutesOptions {\n /**\n * The integration's intake capability providing incident.io access. Required\n * for everything beyond the disabled `status` route.\n */\n incidentio?: { intake: Intake; id: string };\n /**\n * Credential mode reported on the status route so the SPA can tell a\n * deployment-configured API key apart from Platform-managed connections.\n */\n mode?: 'api-key' | 'platform';\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /**\n * Factory rules ingress for observed follow-ups. When present, a\n * board-scoped listing also materializes new cards through the incident.io\n * event rules — the same automatic intake Linear and Jira have.\n */\n ingestFactoryIssues?: (input: IncidentioRulesIngress) => Promise<unknown>;\n}\n\n/**\n * Narrow the caller's selected incident.io sources to the ones that feed this\n * Factory project. Routing is explicit: a source feeds this Factory only when\n * its binding names both the Factory project and a board. Mirrors the Jira\n * routes' scoping semantics — the generic binding storage is provider-neutral.\n * Shared with the agent tools, which enforce the same source-level\n * authorization before fetching item details.\n */\nexport async function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'incidentio' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\n}\n\n/**\n * Resolve the org-scoped tenant for an incident.io request. Intake selections\n * are org-owned, so it requires both a signed-in user and an organization.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'incident.io intake requires an organization. Personal accounts cannot use incident.io intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque pagination cursor from the query string. Cursors are\n * server-issued base64url blobs, so anything outside a conservative\n * charset/length is rejected rather than decoded.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 2_048 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map an incident.io read failure to the API response for the SPA. */\nfunction incidentioFetchError(c: RouteContext, err: unknown) {\n if (err instanceof IncidentioApiError && (err.status === 401 || err.status === 403)) {\n return c.json(\n {\n error: 'incidentio_auth_failed',\n message: 'incident.io rejected the configured credentials. Reconnect the incident.io account.',\n },\n 409,\n );\n }\n return c.json({ error: 'incidentio_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\ninterface IncidentioIssuePayload {\n id: string;\n identifier: string;\n title: string;\n url: string;\n author: string | null;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n sourceId: string | null;\n}\n\n/**\n * Build the incident.io routes as Mastra `apiRoutes`. When the feature is\n * disabled, returns only the `status` route so the SPA can detect the\n * disabled state.\n */\nexport function buildIncidentioRoutes(options: MountIncidentioRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { incidentio, auth, intake, mode } = options;\n const enabled = Boolean(incidentio) && auth.enabled();\n const modeField = mode ? { mode } : {};\n const diagnostics = (): IncidentioFeatureDiagnostics => ({\n incidentioConfigured: Boolean(incidentio),\n factoryAuthEnabled: auth.enabled(),\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/incidentio/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !incidentio || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(incidentio),\n ...modeField,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n ...modeField,\n organizationRequired: true,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n return c.json({ enabled: true, configured: true, ...modeField, reason: 'ready', diagnostics: diagnostics() });\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !incidentio || !intake) {\n return routes;\n }\n\n // ── List bound follow-ups (cursor-paged) ────────────────────────────────\n // Respects the caller's intake config: disabled incident.io intake 404s,\n // and only sources routed to the requested Factory project are listed.\n // Incidents never appear here — only follow-ups feed intake.\n routes.push(\n registerApiRoute('/web/incidentio/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n\n const selectedIds = selection.sourceIds ?? [];\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const sourceIds = intakeBoards ? Object.keys(intakeBoards) : selectedIds;\n if (sourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const page = await incidentio.intake.listItems({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n sourceIds,\n ...(after ? { cursor: after } : {}),\n });\n const issuePayload: IncidentioIssuePayload[] = [];\n for (const item of page.items) {\n const externalId = item.source.externalId;\n // Incidents stay out of intake even when a stale binding selects\n // the incidents source — only follow-ups are served.\n if (!externalId.startsWith(FOLLOW_UP_PREFIX)) continue;\n const metadata = item.metadata ?? {};\n const identifier = typeof metadata.identifier === 'string' ? metadata.identifier : externalId;\n const titlePrefix = `${identifier}: `;\n issuePayload.push({\n id: externalId,\n identifier,\n title: item.title.startsWith(titlePrefix) ? item.title.slice(titlePrefix.length) : item.title,\n url: item.source.url ?? '',\n author: typeof metadata.author === 'string' ? metadata.author : null,\n state: item.status ?? '',\n stateType: typeof metadata.stateType === 'string' ? metadata.stateType : '',\n priorityLabel: typeof metadata.priority === 'string' ? metadata.priority : '',\n assignee: item.assignee ?? null,\n incident: typeof metadata.incidentioIncidentId === 'string' ? metadata.incidentioIncidentId : null,\n labels: item.labels ?? [],\n createdAt: item.createdAt ?? '',\n updatedAt: item.updatedAt ?? '',\n sourceId: item.sourceId || null,\n });\n }\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor: page.nextCursor });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── Follow-up detail (description for the card panel) ───────────────────\n routes.push(\n registerApiRoute('/web/incidentio/issues/detail', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048 || !ITEM_REF_RE.test(issueRef)) {\n return c.json({ error: 'invalid_issue_ref' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n const intakeBoards = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (Object.keys(intakeBoards).length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n // The item must resolve through a source routed to this Factory —\n // an item from an unbound source reads exactly like one that\n // doesn't exist (same stance as the Jira detail route).\n const dispatch = await incidentio.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n if (!dispatch || !dispatch.sourceId || !(dispatch.sourceId in intakeBoards)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n const issue = await incidentio.intake.getIssue({\n connection: dispatch.connection,\n issueId: dispatch.issueId,\n });\n if (!issue) return c.json({ error: 'issue_not_found' }, 404);\n return c.json({\n issue: {\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description ?? null,\n },\n });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;AA2BA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,mBAAmB;;AAGzB,SAAS,MAAM,GAA0B;CACvC,OAAO;AACT;;;;;;;;;AA6CA,eAAsB,wBAAwB,EAC5C,QACA,OACA,kBACA,eAMkC;CAClC,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,MAAM,eAAuC,CAAC;CAC9C,KAAK,MAAM,WAAW,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAa,CAAC,GACpF,IAAI,QAAQ,qBAAqB,oBAAoB,QAAQ,SAAS,SAAS,IAAI,QAAQ,QAAQ,GACjG,aAAa,QAAQ,YAAY,QAAQ;CAG7C,OAAO;AACT;;;;;AAMA,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;;;;;;AAOA,SAAS,iBAAiB,KAAoD;CAC5E,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAAI,OAAO,KAAA;CAC5C,IAAI,IAAI,SAAS,QAAS,CAAC,gBAAgB,KAAK,GAAG,GAAG,OAAO;CAC7D,OAAO;AACT;;AAGA,SAAS,qBAAqB,GAAiB,KAAc;CAC3D,IAAI,eAAe,uBAAuB,IAAI,WAAW,OAAO,IAAI,WAAW,MAC7E,OAAO,EAAE,KACP;EACE,O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AAG,GAAG;GAC3C;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/incidentio/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the incident.io intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Mirrors the Jira module: no connect/callback flow here — credentials are\n * either deployment-global constructor config (direct) or Platform-managed\n * connections discovered at runtime. Every route re-resolves the\n * authenticated user from the request and scopes intake selections by the\n * caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildIncidentioRoutes` returns only `GET /web/incidentio/status`, which\n * reports `enabled:false` so the SPA can cleanly hide all incident.io UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport type { Intake } from '../../capabilities/intake.js';\nimport { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport { IncidentioApiError } from './api.js';\nimport type { IncidentioRulesIngress } from './rules.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ITEM_REF_RE = /^incidentio:(?:follow-up|incident):[\\w-]+$/;\nconst FOLLOW_UP_PREFIX = 'incidentio:follow-up:';\n\n/**\n * Non-secret diagnostic snapshot of every incident.io feature gate, mirroring\n * the Jira diagnostics shape. Only booleans — never values.\n */\nexport interface IncidentioFeatureDiagnostics {\n incidentioConfigured: boolean;\n factoryAuthEnabled: boolean;\n}\n\nexport interface MountIncidentioRoutesOptions {\n /**\n * The integration's intake capability providing incident.io access. Required\n * for everything beyond the disabled `status` route.\n */\n incidentio?: { intake: Intake; id: string };\n /**\n * Credential mode reported on the status route so the SPA can tell a\n * deployment-configured API key apart from Platform-managed connections.\n */\n mode?: 'api-key' | 'platform';\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /**\n * Factory rules ingress for observed follow-ups. When present, a\n * board-scoped listing also materializes new cards through the incident.io\n * event rules — the same automatic intake Linear and Jira have.\n */\n ingestFactoryIssues?: (input: IncidentioRulesIngress) => Promise<unknown>;\n}\n\n/**\n * Narrow the caller's selected incident.io sources to the ones that feed this\n * Factory project. Routing is explicit: a source feeds this Factory only when\n * its binding names both the Factory project and a board. Mirrors the Jira\n * routes' scoping semantics — the generic binding storage is provider-neutral.\n * Shared with the agent tools, which enforce the same source-level\n * authorization before fetching item details.\n */\nexport async function scopeSourceIdsToProject({\n intake,\n orgId,\n factoryProjectId,\n selectedIds,\n}: {\n intake: IntakeStorage;\n orgId: string;\n factoryProjectId: string;\n selectedIds: string[];\n}): Promise<Record<string, string>> {\n const selected = new Set(selectedIds);\n const intakeBoards: Record<string, string> = {};\n for (const binding of await intake.listBindings({ orgId, integrationId: 'incidentio' })) {\n if (binding.factoryProjectId === factoryProjectId && binding.board && selected.has(binding.sourceId)) {\n intakeBoards[binding.sourceId] = binding.board;\n }\n }\n return intakeBoards;\n}\n\n/**\n * Resolve the org-scoped tenant for an incident.io request. Intake selections\n * are org-owned, so it requires both a signed-in user and an organization.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'incident.io intake requires an organization. Personal accounts cannot use incident.io intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque pagination cursor from the query string. Cursors are\n * server-issued base64url blobs, so anything outside a conservative\n * charset/length is rejected rather than decoded.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 2_048 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map an incident.io read failure to the API response for the SPA. */\nfunction incidentioFetchError(c: RouteContext, err: unknown) {\n if (err instanceof IncidentioApiError && (err.status === 401 || err.status === 403)) {\n return c.json(\n {\n error: 'incidentio_auth_failed',\n message: 'incident.io rejected the configured credentials. Reconnect the incident.io account.',\n },\n 409,\n );\n }\n return c.json({ error: 'incidentio_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\ninterface IncidentioIssuePayload {\n id: string;\n identifier: string;\n title: string;\n url: string;\n author: string | null;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n sourceId: string | null;\n}\n\n/**\n * Build the incident.io routes as Mastra `apiRoutes`. When the feature is\n * disabled, returns only the `status` route so the SPA can detect the\n * disabled state.\n */\nexport function buildIncidentioRoutes(options: MountIncidentioRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { incidentio, auth, intake, mode } = options;\n const enabled = Boolean(incidentio) && auth.enabled();\n const modeField = mode ? { mode } : {};\n const diagnostics = (): IncidentioFeatureDiagnostics => ({\n incidentioConfigured: Boolean(incidentio),\n factoryAuthEnabled: auth.enabled(),\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/incidentio/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !incidentio || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(incidentio),\n ...modeField,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n ...modeField,\n organizationRequired: true,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n return c.json({ enabled: true, configured: true, ...modeField, reason: 'ready', diagnostics: diagnostics() });\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !incidentio || !intake) {\n return routes;\n }\n\n // ── List bound follow-ups (cursor-paged) ────────────────────────────────\n // Respects the caller's intake config: disabled incident.io intake 404s,\n // and only sources routed to the requested Factory project are listed.\n // Incidents never appear here — only follow-ups feed intake.\n routes.push(\n registerApiRoute('/web/incidentio/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n\n const selectedIds = selection.sourceIds ?? [];\n const intakeBoards = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const sourceIds = intakeBoards ? Object.keys(intakeBoards) : selectedIds;\n if (sourceIds.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const page = await incidentio.intake.listItems({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n sourceIds,\n ...(after ? { cursor: after } : {}),\n });\n const issuePayload: IncidentioIssuePayload[] = [];\n for (const item of page.items) {\n const externalId = item.source.externalId;\n // Incidents stay out of intake even when a stale binding selects\n // the incidents source — only follow-ups are served.\n if (!externalId.startsWith(FOLLOW_UP_PREFIX)) continue;\n const metadata = item.metadata ?? {};\n const identifier = typeof metadata.identifier === 'string' ? metadata.identifier : externalId;\n const titlePrefix = `${identifier}: `;\n issuePayload.push({\n id: externalId,\n identifier,\n title: item.title.startsWith(titlePrefix) ? item.title.slice(titlePrefix.length) : item.title,\n url: item.source.url ?? '',\n author: typeof metadata.author === 'string' ? metadata.author : null,\n state: item.status ?? '',\n stateType: typeof metadata.stateType === 'string' ? metadata.stateType : '',\n priorityLabel: typeof metadata.priority === 'string' ? metadata.priority : '',\n assignee: item.assignee ?? null,\n incident: typeof metadata.incidentioIncidentId === 'string' ? metadata.incidentioIncidentId : null,\n labels: item.labels ?? [],\n createdAt: item.createdAt ?? '',\n updatedAt: item.updatedAt ?? '',\n sourceId: item.sourceId || null,\n });\n }\n if (factoryProjectId && intakeBoards && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n intakeBoards,\n });\n }\n return c.json({ issues: issuePayload, nextCursor: page.nextCursor });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── Follow-up detail (description for the card panel) ───────────────────\n routes.push(\n registerApiRoute('/web/incidentio/issues/detail', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048 || !ITEM_REF_RE.test(issueRef)) {\n return c.json({ error: 'invalid_issue_ref' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['incidentio'] });\n const selection = config.incidentio!;\n if (!selection.enabled) {\n return c.json(\n { error: 'incidentio_intake_disabled', message: 'incident.io intake is turned off in Settings.' },\n 404,\n );\n }\n const intakeBoards = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (Object.keys(intakeBoards).length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n // The item must resolve through a source routed to this Factory —\n // an item from an unbound source reads exactly like one that\n // doesn't exist (same stance as the Jira detail route).\n const dispatch = await incidentio.intake.resolveIntakeDispatch?.({\n orgId: resolved.tenant.orgId,\n externalSource: { type: 'issue', externalId: issueRef },\n });\n if (!dispatch || !dispatch.sourceId || !(dispatch.sourceId in intakeBoards)) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n const issue = await incidentio.intake.getIssue({\n connection: dispatch.connection,\n issueId: dispatch.issueId,\n });\n if (!issue) return c.json({ error: 'issue_not_found' }, 404);\n return c.json({\n issue: {\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description ?? null,\n },\n });\n } catch (err) {\n return incidentioFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;AA4BA,MAAM,UAAU;AAChB,MAAM,cAAc;AACpB,MAAM,mBAAmB;;;;;;;;;AA6CzB,eAAsB,wBAAwB,EAC5C,QACA,OACA,kBACA,eAMkC;CAClC,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,MAAM,eAAuC,CAAC;CAC9C,KAAK,MAAM,WAAW,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAa,CAAC,GACpF,IAAI,QAAQ,qBAAqB,oBAAoB,QAAQ,SAAS,SAAS,IAAI,QAAQ,QAAQ,GACjG,aAAa,QAAQ,YAAY,QAAQ;CAG7C,OAAO;AACT;;;;;AAMA,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACv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G;GAE3F,IAAI;IAIF,MAAM,WAAW,MAAM,WAAW,OAAO,wBAAwB;KAC/D,OAAO,SAAS,OAAO;KACvB,gBAAgB;MAAE,MAAM;MAAS,YAAY;KAAS;IACxD,CAAC;IACD,IAAI,CAAC,YAAY,CAAC,SAAS,YAAY,EAAE,SAAS,YAAY,eAC5D,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAEjD,MAAM,QAAQ,MAAM,WAAW,OAAO,SAAS;KAC7C,YAAY,SAAS;KACrB,SAAS,SAAS;IACpB,CAAC;IACD,IAAI,CAAC,OAAO,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAC3D,OAAO,EAAE,KAAK,EACZ,OAAO;KACL,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM,eAAe;IACpC,EACF,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,qBAAqB,MAAM,CAAC,GAAG,GAAG;GAC3C;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
@@ -1,4 +1,6 @@
1
+ import type { BoardEventFacts } from '../../boards/board-events.js';
1
2
  import type { BoardRegistry } from '../../boards/index.js';
3
+ import type { FactoryIncidentioRuleContext } from '../../rules/types.js';
2
4
  import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
3
5
  import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
4
6
  import type { IntegrationContext } from '../base.js';
@@ -39,6 +41,11 @@ export interface IncidentioRulesIngress {
39
41
  intakeBoards?: Readonly<Record<string, string>>;
40
42
  }
41
43
  type IngressStatus = 'committed' | 'replayed' | 'missing';
44
+ /**
45
+ * The status change a incident.io sync reports: a follow-up seen for the first time is created, and a
46
+ * completed or canceled one is closed for that reason. Later sightings of an open follow-up report none.
47
+ */
48
+ export declare function boardEventFor(context: Pick<FactoryIncidentioRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined;
42
49
  export declare class IncidentioRules {
43
50
  #private;
44
51
  private readonly options;
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/rules.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAI3D,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAQ,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AACrD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAoB/D,MAAM,WAAW,sBAAsB;IACrC,qGAAqG;IACrG,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,6DAA6D;IAC7D,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,2EAA2E;IAC3E,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,mGAAmG;IACnG,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC1B;AAED,MAAM,WAAW,sBAAsB;IACrC,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,KAAK,CAAC,CAAC;IAC9C,OAAO,EAAE,gBAAgB,CAAC;IAC1B,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,aAAa,CAAC;IACtB,eAAe,EAAE,oBAAoB,CAAC;CACvC;AAED,MAAM,WAAW,s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,GAAG,MAAM,CAAC,GAAG,eAAe,GAAG,SAAS,CAKlI;AAED,qBAAa,eAAe;;IACd,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,sBAAsB,EAAI;IAE1D,MAAM,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAoBhG;CA8HF;AAED,wBAAgB,qBAAqB,CACnC,UAAU,EAAE;IAAE,QAAQ,CAAC,KAAK,EAAE,oBAAoB,CAAA;CAAE,EACpD,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,sBAAsB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAUnE"}
@@ -1,6 +1,7 @@
1
+ import { closeReason } from "../../boards/board-events.js";
1
2
  import "../../boards/index.js";
2
3
  import { boardEventHandlers, boardForWorkItem, eventBoardId, rulePhaseField, withBoardClosure } from "../../boards/semantics.js";
3
- import { selectEventRule } from "../../rules/event-rules.js";
4
+ import { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from "../../rules/event-rules.js";
4
5
  import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "../../rules/validation.js";
5
6
  // src/integrations/incidentio/rules.ts
6
7
  const RULE_TIMEOUT_MS = 5e3;
@@ -15,6 +16,17 @@ async function withRuleTimeout(promise) {
15
16
  }
16
17
  }
17
18
  const MAX_STALE_RULE_ATTEMPTS = 3;
19
+ /**
20
+ * The status change a incident.io sync reports: a follow-up seen for the first time is created, and a
21
+ * completed or canceled one is closed for that reason. Later sightings of an open follow-up report none.
22
+ */
23
+ function boardEventFor(context) {
24
+ if (context.event === "followUpClosed") return {
25
+ type: "work_item.closed",
26
+ reason: closeReason(context.issue.stateType === "canceled")
27
+ };
28
+ return context.item ? void 0 : { type: "work_item.created" };
29
+ }
18
30
  var IncidentioRules = class {
19
31
  options;
20
32
  constructor(options) {
@@ -28,6 +40,15 @@ var IncidentioRules = class {
28
40
  status: "missing",
29
41
  ingested: 0
30
42
  };
43
+ await this.options.storage.copyLegacyCards({
44
+ orgId: input.orgId,
45
+ factoryProjectId: input.factoryProjectId,
46
+ sources: input.issues.map((issue) => ({
47
+ integrationId: "incidentio",
48
+ type: "issue",
49
+ externalId: issue.id
50
+ }))
51
+ });
31
52
  const items = await this.options.storage.list({
32
53
  orgId: input.orgId,
33
54
  factoryProjectId: input.factoryProjectId
@@ -97,8 +118,11 @@ var IncidentioRules = class {
97
118
  event,
98
119
  issue
99
120
  };
121
+ const boardEvent = boardEventFor(context);
122
+ if (boardEvent) context.boardEvent = boardEvent;
123
+ const ownedByDeployment = deploymentOwnsEvent(this.options.incidentioRules, boardEventHandlers(this.options.boards, eventBoardId(context), "incidentio"), context.event);
100
124
  const rule = selectEventRule(this.options.incidentioRules, boardEventHandlers(this.options.boards, eventBoardId(context), "incidentio"), context.event);
101
- let decision;
125
+ let decision = void 0;
102
126
  let decisions = [];
103
127
  let outcome = { status: "accepted" };
104
128
  try {
@@ -120,6 +144,14 @@ var IncidentioRules = class {
120
144
  reason: timedOut ? "Factory rule evaluation timed out." : error instanceof Error ? error.message.slice(0, 2e3) : "Factory incident.io rule failed."
121
145
  };
122
146
  }
147
+ if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);
148
+ if (!decision && !ownedByDeployment && outcome.status === "accepted") {
149
+ const routed = await routeEventDecision(context, this.options.storage, {
150
+ orgId: input.orgId,
151
+ factoryProjectId: input.factoryProjectId
152
+ });
153
+ if (routed) decisions = [{ ...routed }];
154
+ }
123
155
  const committed = await this.options.storage.commitRuleEvaluation({
124
156
  orgId: input.orgId,
125
157
  factoryProjectId: input.factoryProjectId,
@@ -159,6 +191,6 @@ function attachIncidentioRules(incidentio, context) {
159
191
  });
160
192
  return (input) => rules.ingest(input);
161
193
  }
162
- export { IncidentioRules, attachIncidentioRules };
194
+ export { IncidentioRules, attachIncidentioRules, boardEventFor };
163
195
 
164
196
  //# sourceMappingURL=rules.js.map