@mastra/factory 0.29.0-alpha.0 → 0.29.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 (248) hide show
  1. package/README.md +20 -4
  2. package/dist/board-changes.d.ts +16 -0
  3. package/dist/board-changes.d.ts.map +1 -0
  4. package/dist/board-changes.js +40 -0
  5. package/dist/board-changes.js.map +1 -0
  6. package/dist/boards/index.js +2 -1
  7. package/dist/boards/semantics.d.ts +1 -3
  8. package/dist/boards/semantics.d.ts.map +1 -1
  9. package/dist/boards/semantics.js +1 -5
  10. package/dist/boards/semantics.js.map +1 -1
  11. package/dist/factory.d.ts +4 -0
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +51 -3
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/base.d.ts +9 -0
  16. package/dist/integrations/base.d.ts.map +1 -1
  17. package/dist/integrations/github/pull-request-source.js +2 -1
  18. package/dist/integrations/github/pull-request-source.js.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +1 -1
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/rules.d.ts +5 -2
  22. package/dist/integrations/github/rules.d.ts.map +1 -1
  23. package/dist/integrations/github/rules.js +16 -13
  24. package/dist/integrations/github/rules.js.map +1 -1
  25. package/dist/integrations/github/sandbox.js +2 -2
  26. package/dist/integrations/github/sandbox.js.map +1 -1
  27. package/dist/integrations/gitlab/default-rules.js +2 -1
  28. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  29. package/dist/integrations/gitlab/discovery.d.ts +16 -0
  30. package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
  31. package/dist/integrations/gitlab/discovery.js +107 -0
  32. package/dist/integrations/gitlab/discovery.js.map +1 -0
  33. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/integration.js +1 -2
  35. package/dist/integrations/gitlab/integration.js.map +1 -1
  36. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/issue-reconciler.js +1 -0
  38. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  39. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  40. package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
  41. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  42. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/reconciler.js +4 -2
  44. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  45. package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
  46. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  47. package/dist/integrations/gitlab/reconciliation-config.js +2 -8
  48. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  49. package/dist/integrations/gitlab/routes.d.ts +17 -0
  50. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  51. package/dist/integrations/gitlab/routes.js +28 -22
  52. package/dist/integrations/gitlab/routes.js.map +1 -1
  53. package/dist/integrations/gitlab/rules.d.ts +10 -4
  54. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  55. package/dist/integrations/gitlab/rules.js +32 -8
  56. package/dist/integrations/gitlab/rules.js.map +1 -1
  57. package/dist/integrations/incidentio/integration.d.ts +2 -1
  58. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  59. package/dist/integrations/incidentio/integration.js +7 -7
  60. package/dist/integrations/incidentio/integration.js.map +1 -1
  61. package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
  62. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  63. package/dist/integrations/incidentio/issue-reconciler.js +36 -1
  64. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  65. package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
  66. package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
  67. package/dist/integrations/incidentio/reconciliation-config.js +2 -5
  68. package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
  69. package/dist/integrations/incidentio/routes.d.ts +24 -8
  70. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  71. package/dist/integrations/incidentio/routes.js +33 -35
  72. package/dist/integrations/incidentio/routes.js.map +1 -1
  73. package/dist/integrations/incidentio/rules.d.ts +0 -4
  74. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  75. package/dist/integrations/incidentio/rules.js +17 -14
  76. package/dist/integrations/incidentio/rules.js.map +1 -1
  77. package/dist/integrations/intake-discovery.d.ts +44 -0
  78. package/dist/integrations/intake-discovery.d.ts.map +1 -0
  79. package/dist/integrations/intake-discovery.js +60 -0
  80. package/dist/integrations/intake-discovery.js.map +1 -0
  81. package/dist/integrations/issue-reconcile-worker.js +1 -1
  82. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  83. package/dist/integrations/issue-reconciler.d.ts +7 -0
  84. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  85. package/dist/integrations/issue-reconciler.js +47 -12
  86. package/dist/integrations/issue-reconciler.js.map +1 -1
  87. package/dist/integrations/jira/integration.d.ts +3 -2
  88. package/dist/integrations/jira/integration.d.ts.map +1 -1
  89. package/dist/integrations/jira/integration.js +5 -7
  90. package/dist/integrations/jira/integration.js.map +1 -1
  91. package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
  92. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/jira/issue-reconciler.js +34 -1
  94. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
  96. package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
  97. package/dist/integrations/jira/reconciliation-config.js +2 -5
  98. package/dist/integrations/jira/reconciliation-config.js.map +1 -1
  99. package/dist/integrations/jira/routes.d.ts +0 -7
  100. package/dist/integrations/jira/routes.d.ts.map +1 -1
  101. package/dist/integrations/jira/routes.js +2 -12
  102. package/dist/integrations/jira/routes.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts +0 -4
  104. package/dist/integrations/jira/rules.d.ts.map +1 -1
  105. package/dist/integrations/jira/rules.js +3 -13
  106. package/dist/integrations/jira/rules.js.map +1 -1
  107. package/dist/integrations/kept-cards.d.ts +49 -0
  108. package/dist/integrations/kept-cards.d.ts.map +1 -0
  109. package/dist/integrations/kept-cards.js +97 -0
  110. package/dist/integrations/kept-cards.js.map +1 -0
  111. package/dist/integrations/linear/intake-discovery.d.ts +34 -0
  112. package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
  113. package/dist/integrations/linear/intake-discovery.js +112 -0
  114. package/dist/integrations/linear/intake-discovery.js.map +1 -0
  115. package/dist/integrations/linear/integration.d.ts.map +1 -1
  116. package/dist/integrations/linear/integration.js +1 -4
  117. package/dist/integrations/linear/integration.js.map +1 -1
  118. package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
  119. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  120. package/dist/integrations/linear/issue-reconciler.js +24 -20
  121. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  122. package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
  123. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  124. package/dist/integrations/linear/reconciliation-config.js +2 -8
  125. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  126. package/dist/integrations/linear/routes.d.ts +0 -2
  127. package/dist/integrations/linear/routes.d.ts.map +1 -1
  128. package/dist/integrations/linear/routes.js +3 -9
  129. package/dist/integrations/linear/routes.js.map +1 -1
  130. package/dist/integrations/platform/api-client.d.ts +2 -0
  131. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  132. package/dist/integrations/platform/api-client.js +6 -1
  133. package/dist/integrations/platform/api-client.js.map +1 -1
  134. package/dist/integrations/platform/connect/routes.js +4 -1
  135. package/dist/integrations/platform/connect/routes.js.map +1 -1
  136. package/dist/integrations/platform/github/event-worker.d.ts +12 -0
  137. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  138. package/dist/integrations/platform/github/event-worker.js +56 -5
  139. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  140. package/dist/integrations/platform/github/integration.d.ts +1 -0
  141. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  142. package/dist/integrations/platform/github/integration.js +8 -3
  143. package/dist/integrations/platform/github/integration.js.map +1 -1
  144. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  145. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  146. package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
  147. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  148. package/dist/integrations/platform/incidentio/integration.js +7 -7
  149. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  150. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  151. package/dist/integrations/platform/jira/integration.js +4 -7
  152. package/dist/integrations/platform/jira/integration.js.map +1 -1
  153. package/dist/integrations/platform/jira/routes.d.ts +0 -7
  154. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  155. package/dist/integrations/platform/jira/routes.js +2 -12
  156. package/dist/integrations/platform/jira/routes.js.map +1 -1
  157. package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
  158. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  159. package/dist/integrations/platform/linear/event-worker.js +1 -1
  160. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  161. package/dist/integrations/platform/linear/integration.d.ts +1 -0
  162. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  163. package/dist/integrations/platform/linear/integration.js +7 -7
  164. package/dist/integrations/platform/linear/integration.js.map +1 -1
  165. package/dist/integrations/platform/vanta/integration.d.ts +7 -2
  166. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  167. package/dist/integrations/platform/vanta/integration.js +22 -6
  168. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  169. package/dist/integrations/reconciliation-config.d.ts +0 -1
  170. package/dist/integrations/reconciliation-config.d.ts.map +1 -1
  171. package/dist/integrations/reconciliation-config.js +1 -8
  172. package/dist/integrations/reconciliation-config.js.map +1 -1
  173. package/dist/integrations/slack/channel-reply-processor.js +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  175. package/dist/integrations/startup-summary.d.ts +8 -0
  176. package/dist/integrations/startup-summary.d.ts.map +1 -0
  177. package/dist/integrations/startup-summary.js +36 -0
  178. package/dist/integrations/startup-summary.js.map +1 -0
  179. package/dist/integrations/vanta/sync.d.ts +9 -5
  180. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  181. package/dist/integrations/vanta/sync.js +16 -8
  182. package/dist/integrations/vanta/sync.js.map +1 -1
  183. package/dist/linked-repositories-changed.d.ts +14 -0
  184. package/dist/linked-repositories-changed.d.ts.map +1 -0
  185. package/dist/linked-repositories-changed.js +48 -0
  186. package/dist/linked-repositories-changed.js.map +1 -0
  187. package/dist/routes/contracts.d.ts +117 -0
  188. package/dist/routes/contracts.d.ts.map +1 -1
  189. package/dist/routes/contracts.js +44 -1
  190. package/dist/routes/contracts.js.map +1 -1
  191. package/dist/routes/run-queue.d.ts +17 -0
  192. package/dist/routes/run-queue.d.ts.map +1 -0
  193. package/dist/routes/run-queue.js +69 -0
  194. package/dist/routes/run-queue.js.map +1 -0
  195. package/dist/routes/surface.d.ts +8 -0
  196. package/dist/routes/surface.d.ts.map +1 -1
  197. package/dist/routes/surface.js +4 -2
  198. package/dist/routes/surface.js.map +1 -1
  199. package/dist/routes/work-item-selection.d.ts +4 -1
  200. package/dist/routes/work-item-selection.d.ts.map +1 -1
  201. package/dist/routes/work-item-selection.js +7 -2
  202. package/dist/routes/work-item-selection.js.map +1 -1
  203. package/dist/routes/work-items.d.ts +5 -0
  204. package/dist/routes/work-items.d.ts.map +1 -1
  205. package/dist/routes/work-items.js +17 -0
  206. package/dist/routes/work-items.js.map +1 -1
  207. package/dist/rules/dispatcher.d.ts +13 -1
  208. package/dist/rules/dispatcher.d.ts.map +1 -1
  209. package/dist/rules/dispatcher.js +9 -2
  210. package/dist/rules/dispatcher.js.map +1 -1
  211. package/dist/rules/review-source-tool.js +2 -1
  212. package/dist/rules/review-source-tool.js.map +1 -1
  213. package/dist/rules/types.d.ts +2 -2
  214. package/dist/rules/types.d.ts.map +1 -1
  215. package/dist/rules/types.js +4 -1
  216. package/dist/rules/types.js.map +1 -1
  217. package/dist/rules/validation.d.ts.map +1 -1
  218. package/dist/rules/validation.js +1 -0
  219. package/dist/rules/validation.js.map +1 -1
  220. package/dist/storage/domains/projects/base.d.ts +2 -0
  221. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  222. package/dist/storage/domains/projects/base.js +13 -1
  223. package/dist/storage/domains/projects/base.js.map +1 -1
  224. package/dist/storage/domains/source-control/base.d.ts +32 -0
  225. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  226. package/dist/storage/domains/source-control/base.js +54 -4
  227. package/dist/storage/domains/source-control/base.js.map +1 -1
  228. package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
  229. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  230. package/dist/storage/domains/source-control/inmemory.js +17 -0
  231. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  232. package/dist/storage/domains/work-items/base.d.ts +1 -0
  233. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  234. package/dist/storage/domains/work-items/base.js +10 -1
  235. package/dist/storage/domains/work-items/base.js.map +1 -1
  236. package/dist/timing.d.ts +8 -1
  237. package/dist/timing.d.ts.map +1 -1
  238. package/dist/timing.js +10 -2
  239. package/dist/timing.js.map +1 -1
  240. package/dist/work-item-branch.d.ts +1 -1
  241. package/dist/work-item-branch.d.ts.map +1 -1
  242. package/dist/work-item-branch.js +1 -0
  243. package/dist/work-item-branch.js.map +1 -1
  244. package/dist/work-items/source-external-id.d.ts +4 -0
  245. package/dist/work-items/source-external-id.d.ts.map +1 -0
  246. package/dist/work-items/source-external-id.js +9 -0
  247. package/dist/work-items/source-external-id.js.map +1 -0
  248. package/package.json +9 -9
@@ -1 +1 @@
1
- {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/incidentio/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { Intake, IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntegrationContext } from '../base.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { IncidentioEventRules } from './default-rules.js';\nimport { IncidentioRules } from './rules.js';\nimport type { IncidentioIssueIngress } from './rules.js';\n\nexport type IncidentioIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(itemRef: string, issue: IntakeIssue): IncidentioIssueIngress {\n return {\n id: itemRef,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n author: issue.author ?? null,\n incident: null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\nexport function attachIncidentioIssueReconciler(\n incidentio: { intake: Intake; rules: IncidentioEventRules },\n context: IntegrationContext,\n): IncidentioIssueReconciler | undefined {\n if (!context.runtime || !incidentio.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new IncidentioRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n incidentioRules: incidentio.rules,\n });\n\n return createIssueReconciler({\n integrationId: 'incidentio',\n intake: incidentio.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => item.externalSource?.externalId,\n metadata: (item, issue) => ({\n identifier: issue.identifier,\n issueRef: item.externalSource?.externalId ?? issue.id,\n autoStartCandidate: issue.stateType === 'unstarted' || issue.stateType === 'started',\n incidentioItemType: issue.source === 'Follow-up' ? 'follow-up' : 'incident',\n incidentioState: issue.state,\n incidentioStateType: issue.stateType,\n incidentioPriority: issue.priority,\n incidentioAssignee: issue.assignee,\n incidentioDescription: 'description' in issue && typeof issue.description === 'string' ? issue.description : null,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priority,\n source: issue.source,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)],\n });\n },\n });\n}\n"],"mappings":";;;;;;AAYA,SAAS,eAAe,SAAiB,OAA4C;CACnF,OAAO;EACL,IAAI;EACJ,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW,MAAM,aAAa;EAC9B,eAAe,MAAM,YAAY;EACjC,UAAU,MAAM,YAAY;EAC5B,QAAQ,MAAM,UAAU;EACxB,UAAU;EACV,QAAQ,CAAC,GAAI,MAAM,UAAU,CAAC,CAAE;EAChC,WAAW,MAAM;EACjB,WAAW,MAAM;CACnB;AACF;AAEA,SAAgB,gCACd,YACA,SACuC;CACvC,IAAI,CAAC,QAAQ,WAAW,CAAC,WAAW,OAAO,uBAAuB,OAAO,KAAA;CACzE,MAAM,SAAS,QAAQ,QAAQ;CAE/B,MAAM,QAAQ,IAAI,gBAAgB;EAChC,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B;EACA,iBAAiB,WAAW;CAC9B,CAAC;CAED,OAAO,sBAAsB;EAC3B,eAAe;EACf,QAAQ,WAAW;EACnB,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,aAAY,SAAQ,uBAAuB,cAAc,MAAM,CAAC,CAAC,WAAW,IAAI,GAAG,IAAI,CAAC,EAAE,SAAS;EACnG,UAAS,SAAQ,KAAK,gBAAgB;EACtC,WAAW,MAAM,WAAW;GAC1B,YAAY,MAAM;GAClB,UAAU,KAAK,gBAAgB,cAAc,MAAM;GACnD,oBAAoB,MAAM,cAAc,eAAe,MAAM,cAAc;GAC3E,oBAAoB,MAAM,WAAW,cAAc,cAAc;GACjE,iBAAiB,MAAM;GACvB,qBAAqB,MAAM;GAC3B,oBAAoB,MAAM;GAC1B,oBAAoB,MAAM;GAC1B,uBAAuB,iBAAiB,SAAS,OAAO,MAAM,gBAAgB,WAAW,MAAM,cAAc;GAC7G,OAAO,MAAM;GACb,WAAW,MAAM;GACjB,UAAU,MAAM;GAChB,QAAQ,MAAM;GACd,UAAU,MAAM;GAChB,WAAW,MAAM,aAAa,CAAC;GAC/B,SAAS,MAAM;GACf,QAAQ,MAAM;GACd,QAAQ,MAAM,UAAU,CAAC;GACzB,WAAW,MAAM;GACjB,WAAW,MAAM;EACnB;EACA,UAAU,OAAO,MAAM,OAAO,YAAY;GACxC,MAAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,gBAAgB,cAAc,MAAM,IAAI,KAAK,CAAC;GAC7E,CAAC;EACH;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"issue-reconciler.js","names":[],"sources":["../../../src/integrations/incidentio/issue-reconciler.ts"],"sourcesContent":["import { workItemPhaseSemantics } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { Intake, IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntegrationContext } from '../base.js';\nimport { withIntakeDiscovery } from '../intake-discovery.js';\nimport { createIssueReconciler } from '../issue-reconciler.js';\nimport type { IssueReconciler } from '../issue-reconciler.js';\nimport type { IncidentioEventRules } from './default-rules.js';\nimport { followUpIssues, scopeSourceIdsToProject } from './routes.js';\nimport { IncidentioRules } from './rules.js';\nimport type { IncidentioIssueIngress } from './rules.js';\n\nexport type IncidentioIssueReconciler = IssueReconciler;\n\nfunction issueToIngress(itemRef: string, issue: IntakeIssue): IncidentioIssueIngress {\n return {\n id: itemRef,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n author: issue.author ?? null,\n incident: null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n };\n}\n\n/**\n * One incident.io sweep: refresh carded items (metadata, closes), then list\n * what every project's board shows so follow-ups nobody has carded yet get\n * their card. incident.io sends Factory no events, so this is the only\n * first-sight path.\n */\nexport function attachIncidentioIssueReconciler(\n incidentio: { intake: Intake; rules: IncidentioEventRules; isFollowUpSource(sourceId: string): boolean },\n context: IntegrationContext,\n): IncidentioIssueReconciler | undefined {\n if (!context.runtime || !incidentio.intake.resolveIntakeDispatch) return undefined;\n const boards = context.runtime.boards;\n\n const rules = new IncidentioRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards,\n incidentioRules: incidentio.rules,\n });\n\n const reconcile = createIssueReconciler({\n integrationId: 'incidentio',\n intake: incidentio.intake,\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n ...(context.runtime.keptCards ? { cards: context.runtime.keptCards } : {}),\n isTerminal: item => workItemPhaseSemantics(toBoardSource(boards).forProject(item), item)?.kind === 'terminal',\n issueId: item => item.externalSource?.externalId,\n metadata: (item, issue) => ({\n identifier: issue.identifier,\n issueRef: item.externalSource?.externalId ?? issue.id,\n autoStartCandidate: issue.stateType === 'unstarted' || issue.stateType === 'started',\n incidentioItemType: issue.source === 'Follow-up' ? 'follow-up' : 'incident',\n incidentioState: issue.state,\n incidentioStateType: issue.stateType,\n incidentioPriority: issue.priority,\n incidentioAssignee: issue.assignee,\n incidentioDescription: 'description' in issue && typeof issue.description === 'string' ? issue.description : null,\n state: issue.state,\n stateType: issue.stateType,\n priority: issue.priority,\n source: issue.source,\n assignee: issue.assignee,\n assignees: issue.assignees ?? [],\n creator: issue.author,\n author: issue.author,\n labels: issue.labels ?? [],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n }),\n onClosed: async (item, issue, project) => {\n await rules.ingest({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n factoryProjectId: project.id,\n issues: [issueToIngress(item.externalSource?.externalId ?? issue.id, issue)],\n });\n },\n });\n\n return withIntakeDiscovery(reconcile, {\n integrationId: 'incidentio',\n intake: context.storage.intake,\n projects: context.storage.projects,\n open: async (project, selectedIds) => {\n const bound = await scopeSourceIdsToProject({\n intake: context.storage.intake,\n orgId: project.orgId,\n factoryProjectId: project.id,\n selectedIds,\n });\n // A board shows follow-ups only, so incidents are never listed.\n return bound\n .filter(sourceId => incidentio.isFollowUpSource(sourceId))\n .map(sourceId => async (cursor: string | undefined) => {\n const page = await incidentio.intake.listItems({\n orgId: project.orgId,\n userId: 'factory-rule-dispatcher',\n sourceIds: [sourceId],\n ...(cursor ? { cursor } : {}),\n });\n return { issues: followUpIssues(page.items), nextCursor: page.nextCursor };\n });\n },\n // incident.io lists follow-ups oldest first and cannot sort or filter them by\n // status, so a page cap would never reach the newest ones.\n maxPages: Number.POSITIVE_INFINITY,\n ingest: input => rules.ingest(input),\n });\n}\n"],"mappings":";;;;;;;;AAcA,SAAS,eAAe,SAAiB,OAA4C;CACnF,OAAO;EACL,IAAI;EACJ,YAAY,MAAM;EAClB,OAAO,MAAM;EACb,KAAK,MAAM;EACX,OAAO,MAAM,SAAS;EACtB,WAAW,MAAM,aAAa;EAC9B,eAAe,MAAM,YAAY;EACjC,UAAU,MAAM,YAAY;EAC5B,QAAQ,MAAM,UAAU;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W,MAAM;GACjB,WAAW,MAAM;EACnB;EACA,UAAU,OAAO,MAAM,OAAO,YAAY;GACxC,MAAM,MAAM,OAAO;IACjB,OAAO,QAAQ;IACf,QAAQ;IACR,kBAAkB,QAAQ;IAC1B,QAAQ,CAAC,eAAe,KAAK,gBAAgB,cAAc,MAAM,IAAI,KAAK,CAAC;GAC7E,CAAC;EACH;CACF,CAAC;CAED,OAAO,oBAAoB,WAAW;EACpC,eAAe;EACf,QAAQ,QAAQ,QAAQ;EACxB,UAAU,QAAQ,QAAQ;EAC1B,MAAM,OAAO,SAAS,gBAAgB;GAQpC,QAAO,MAPa,wBAAwB;IAC1C,QAAQ,QAAQ,QAAQ;IACxB,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B;GACF,CAAC,EAAA,CAGE,QAAO,aAAY,WAAW,iBAAiB,QAAQ,CAAC,CAAC,CACzD,KAAI,aAAY,OAAO,WAA+B;IACrD,MAAM,OAAO,MAAM,WAAW,OAAO,UAAU;KAC7C,OAAO,QAAQ;KACf,QAAQ;KACR,WAAW,CAAC,QAAQ;KACpB,GAAI,SAAS,EAAE,OAAO,IAAI,CAAC;IAC7B,CAAC;IACD,OAAO;KAAE,QAAQ,eAAe,KAAK,KAAK;KAAG,YAAY,KAAK;IAAW;GAC3E,CAAC;EACL;EAGA,UAAU,OAAO;EACjB,SAAQ,UAAS,MAAM,OAAO,KAAK;CACrC,CAAC;AACH"}
@@ -1,3 +1,2 @@
1
- export declare function incidentioReconciliationEnabled(): boolean;
2
1
  export declare function incidentioReconciliationInterval(): number | undefined;
3
2
  //# sourceMappingURL=reconciliation-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"names":[],"mappings":"AAIA,wBAAgB,+BAA+B,IAAI,OAAO,CAQzD;AAED,wBAAgB,gCAAgC,IAAI,MAAM,GAAG,SAAS,CAQrE"}
1
+ {"version":3,"file":"reconciliation-config.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"names":[],"mappings":"AAIA,wBAAgB,gCAAgC,IAAI,MAAM,GAAG,SAAS,CAQrE"}
@@ -1,9 +1,6 @@
1
- import { optionalBoolean, optionalPositiveInteger } from "../reconciliation-config.js";
1
+ import { optionalPositiveInteger } from "../reconciliation-config.js";
2
2
  // src/integrations/incidentio/reconciliation-config.ts
3
3
  const RECONCILIATION_LABEL = "incident.io reconciliation";
4
- function incidentioReconciliationEnabled() {
5
- return optionalBoolean("MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED", process.env.MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED, RECONCILIATION_LABEL) ?? true;
6
- }
7
4
  function incidentioReconciliationInterval() {
8
5
  const name = "MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS";
9
6
  const value = process.env.MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS;
@@ -11,6 +8,6 @@ function incidentioReconciliationInterval() {
11
8
  if (value?.trim() && interval === void 0) console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);
12
9
  return interval;
13
10
  }
14
- export { incidentioReconciliationEnabled, incidentioReconciliationInterval };
11
+ export { incidentioReconciliationInterval };
15
12
 
16
13
  //# sourceMappingURL=reconciliation-config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"reconciliation-config.js","names":[],"sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"sourcesContent":["import { optionalBoolean, optionalPositiveInteger } from '../reconciliation-config.js';\n\nconst RECONCILIATION_LABEL = 'incident.io reconciliation';\n\nexport function incidentioReconciliationEnabled(): boolean {\n return (\n optionalBoolean(\n 'MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED',\n process.env.MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED,\n RECONCILIATION_LABEL,\n ) ?? true\n );\n}\n\nexport function incidentioReconciliationInterval(): number | undefined {\n const name = 'MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS';\n const value = process.env.MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS;\n const interval = optionalPositiveInteger(value);\n if (value?.trim() && interval === undefined) {\n console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);\n }\n return interval;\n}\n"],"mappings":";;AAEA,MAAM,uBAAuB;AAE7B,SAAgB,kCAA2C;CACzD,OACE,gBACE,4CACA,QAAQ,IAAI,0CACZ,oBACF,KAAK;AAET;AAEA,SAAgB,mCAAuD;CACrE,MAAM,OAAO;CACb,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,WAAW,wBAAwB,KAAK;CAC9C,IAAI,OAAO,KAAK,KAAK,aAAa,KAAA,GAChC,QAAQ,KAAK,IAAI,qBAAqB,IAAI,KAAK,wCAAwC,KAAK,UAAU,KAAK,EAAE,EAAE;CAEjH,OAAO;AACT"}
1
+ {"version":3,"file":"reconciliation-config.js","names":[],"sources":["../../../src/integrations/incidentio/reconciliation-config.ts"],"sourcesContent":["import { optionalPositiveInteger } from '../reconciliation-config.js';\n\nconst RECONCILIATION_LABEL = 'incident.io reconciliation';\n\nexport function incidentioReconciliationInterval(): number | undefined {\n const name = 'MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS';\n const value = process.env.MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS;\n const interval = optionalPositiveInteger(value);\n if (value?.trim() && interval === undefined) {\n console.warn(`[${RECONCILIATION_LABEL}] ${name} must be a positive integer; received ${JSON.stringify(value)}.`);\n }\n return interval;\n}\n"],"mappings":";;AAEA,MAAM,uBAAuB;AAE7B,SAAgB,mCAAuD;CACrE,MAAM,OAAO;CACb,MAAM,QAAQ,QAAQ,IAAI;CAC1B,MAAM,WAAW,wBAAwB,KAAK;CAC9C,IAAI,OAAO,KAAK,KAAK,aAAa,KAAA,GAChC,QAAQ,KAAK,IAAI,qBAAqB,IAAI,KAAK,wCAAwC,KAAK,UAAU,KAAK,EAAE,EAAE;CAEjH,OAAO;AACT"}
@@ -13,10 +13,9 @@
13
13
  * reports `enabled:false` so the SPA can cleanly hide all incident.io UI.
14
14
  */
15
15
  import type { ApiRoute } from '@mastra/core/server';
16
- import type { Intake } from '../../capabilities/intake.js';
16
+ import type { Intake, IntakeItem } from '../../capabilities/intake.js';
17
17
  import type { RouteAuth } from '../../routes/route.js';
18
18
  import type { IntakeStorage } from '../../storage/domains/intake/base.js';
19
- import type { IncidentioRulesIngress } from './rules.js';
20
19
  /**
21
20
  * Non-secret diagnostic snapshot of every incident.io feature gate, mirroring
22
21
  * the Jira diagnostics shape. Only booleans — never values.
@@ -46,12 +45,6 @@ export interface MountIncidentioRoutesOptions {
46
45
  * project filter; when absent, only the disabled `status` route is served.
47
46
  */
48
47
  intake?: IntakeStorage;
49
- /**
50
- * Factory rules ingress for observed follow-ups. When present, a
51
- * board-scoped listing also materializes new cards through the incident.io
52
- * event rules — the same automatic intake Linear and Jira have.
53
- */
54
- ingestFactoryIssues?: (input: IncidentioRulesIngress) => Promise<unknown>;
55
48
  }
56
49
  /**
57
50
  * Narrow the caller's selected incident.io sources to the ones that feed this
@@ -67,10 +60,33 @@ export declare function scopeSourceIdsToProject({ intake, orgId, factoryProjectI
67
60
  factoryProjectId: string;
68
61
  selectedIds: string[];
69
62
  }): Promise<string[]>;
63
+ interface IncidentioIssuePayload {
64
+ id: string;
65
+ identifier: string;
66
+ title: string;
67
+ url: string;
68
+ author: string | null;
69
+ state: string;
70
+ stateType: string;
71
+ priorityLabel: string;
72
+ assignee: string | null;
73
+ incident: string | null;
74
+ labels: string[];
75
+ createdAt: string;
76
+ updatedAt: string;
77
+ sourceId: string | null;
78
+ }
79
+ /**
80
+ * The follow-ups a listing page serves, shared by the board route and the
81
+ * reconcile sweep that files their cards. Incidents stay out of intake even
82
+ * when a stale binding selects the incidents source.
83
+ */
84
+ export declare function followUpIssues(items: IntakeItem[]): IncidentioIssuePayload[];
70
85
  /**
71
86
  * Build the incident.io routes as Mastra `apiRoutes`. When the feature is
72
87
  * disabled, returns only the `status` route so the SPA can detect the
73
88
  * disabled state.
74
89
  */
75
90
  export declare function buildIncidentioRoutes(options: MountIncidentioRoutesOptions): ApiRoute[];
91
+ export {};
76
92
  //# sourceMappingURL=routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAIpD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,8BAA8B,CAAC;AAE3D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAE1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAQzD;;;GAGG;AACH,MAAM,WAAW,4BAA4B;IAC3C,oBAAoB,EAAE,OAAO,CAAC;IAC9B,kBAAkB,EAAE,OAAO,CAAC;CAC7B;AAED,MAAM,WAAW,4BAA4B;IAC3C;;;OAGG;IACH,UAAU,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC;IAC5C;;;OAGG;IACH,IAAI,CAAC,EAAE,SAAS,GAAG,UAAU,CAAC;IAC9B,2FAA2F;IAC3F,IAAI,EAAE,SAAS,CAAC;IAChB;;;OAGG;IACH,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB;;;;OAIG;IACH,mBAAmB,CAAC,EAAE,CAAC,KAAK,EAAE,sBAAsB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;CAC3E;AAED;;;;;;;GAOG;AACH,wBAAsB,uBAAuB,CAAC,EAC5C,MAAM,EACN,KAAK,EACL,gBAAgB,EAChB,WAAW,GACZ,EAA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C;IACzB,WAAW,EAAE,MAAM,EAAE,CAAC;CACvB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAKpB;AAoDD,UAAU,sBAAsB;IAC9B,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,UAAU,EAAE,GAAG,sBAAsB,EAAE,CAyB5E;AAED;;;;GAIG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,QAAQ,EAAE,CA8KvF"}
@@ -59,6 +59,35 @@ function incidentioFetchError(c, err) {
59
59
  }, 502);
60
60
  }
61
61
  /**
62
+ * The follow-ups a listing page serves, shared by the board route and the
63
+ * reconcile sweep that files their cards. Incidents stay out of intake even
64
+ * when a stale binding selects the incidents source.
65
+ */
66
+ function followUpIssues(items) {
67
+ return items.filter((item) => item.source.externalId.startsWith(FOLLOW_UP_PREFIX)).map((item) => {
68
+ const externalId = item.source.externalId;
69
+ const metadata = item.metadata ?? {};
70
+ const identifier = typeof metadata.identifier === "string" ? metadata.identifier : externalId;
71
+ const titlePrefix = `${identifier}: `;
72
+ return {
73
+ id: externalId,
74
+ identifier,
75
+ title: item.title.startsWith(titlePrefix) ? item.title.slice(titlePrefix.length) : item.title,
76
+ url: item.source.url ?? "",
77
+ author: typeof metadata.author === "string" ? metadata.author : null,
78
+ state: item.status ?? "",
79
+ stateType: typeof metadata.stateType === "string" ? metadata.stateType : "",
80
+ priorityLabel: typeof metadata.priority === "string" ? metadata.priority : "",
81
+ assignee: item.assignee ?? null,
82
+ incident: typeof metadata.incidentioIncidentId === "string" ? metadata.incidentioIncidentId : null,
83
+ labels: item.labels ?? [],
84
+ createdAt: item.createdAt ?? "",
85
+ updatedAt: item.updatedAt ?? "",
86
+ sourceId: item.sourceId || null
87
+ };
88
+ });
89
+ }
90
+ /**
62
91
  * Build the incident.io routes as Mastra `apiRoutes`. When the feature is
63
92
  * disabled, returns only the `status` route so the SPA can detect the
64
93
  * disabled state.
@@ -127,13 +156,12 @@ function buildIncidentioRoutes(options) {
127
156
  message: "incident.io intake is turned off in Settings."
128
157
  }, 404);
129
158
  const selectedIds = selection.sourceIds ?? [];
130
- const boundSourceIds = factoryProjectId ? await scopeSourceIdsToProject({
159
+ const sourceIds = (factoryProjectId ? await scopeSourceIdsToProject({
131
160
  intake,
132
161
  orgId: resolved.tenant.orgId,
133
162
  factoryProjectId,
134
163
  selectedIds
135
- }) : null;
136
- const sourceIds = boundSourceIds ?? selectedIds;
164
+ }) : null) ?? selectedIds;
137
165
  if (sourceIds.length === 0) return c.json({
138
166
  issues: [],
139
167
  nextCursor: null
@@ -145,38 +173,8 @@ function buildIncidentioRoutes(options) {
145
173
  sourceIds,
146
174
  ...after ? { cursor: after } : {}
147
175
  });
148
- const issuePayload = [];
149
- for (const item of page.items) {
150
- const externalId = item.source.externalId;
151
- if (!externalId.startsWith(FOLLOW_UP_PREFIX)) continue;
152
- const metadata = item.metadata ?? {};
153
- const identifier = typeof metadata.identifier === "string" ? metadata.identifier : externalId;
154
- const titlePrefix = `${identifier}: `;
155
- issuePayload.push({
156
- id: externalId,
157
- identifier,
158
- title: item.title.startsWith(titlePrefix) ? item.title.slice(titlePrefix.length) : item.title,
159
- url: item.source.url ?? "",
160
- author: typeof metadata.author === "string" ? metadata.author : null,
161
- state: item.status ?? "",
162
- stateType: typeof metadata.stateType === "string" ? metadata.stateType : "",
163
- priorityLabel: typeof metadata.priority === "string" ? metadata.priority : "",
164
- assignee: item.assignee ?? null,
165
- incident: typeof metadata.incidentioIncidentId === "string" ? metadata.incidentioIncidentId : null,
166
- labels: item.labels ?? [],
167
- createdAt: item.createdAt ?? "",
168
- updatedAt: item.updatedAt ?? "",
169
- sourceId: item.sourceId || null
170
- });
171
- }
172
- if (factoryProjectId && boundSourceIds && options.ingestFactoryIssues) await options.ingestFactoryIssues({
173
- orgId: resolved.tenant.orgId,
174
- userId: resolved.tenant.userId,
175
- factoryProjectId,
176
- issues: issuePayload
177
- });
178
176
  return c.json({
179
- issues: issuePayload,
177
+ issues: followUpIssues(page.items),
180
178
  nextCursor: page.nextCursor
181
179
  });
182
180
  } catch (err) {
@@ -237,6 +235,6 @@ function buildIncidentioRoutes(options) {
237
235
  }));
238
236
  return routes;
239
237
  }
240
- export { buildIncidentioRoutes, scopeSourceIdsToProject };
238
+ export { buildIncidentioRoutes, followUpIssues, scopeSourceIdsToProject };
241
239
 
242
240
  //# sourceMappingURL=routes.js.map
@@ -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 { 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 * it is bound to the Factory project. 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<string[]> {\n const selected = new Set(selectedIds);\n return (await intake.listBindings({ orgId, integrationId: 'incidentio' }))\n .filter(binding => binding.factoryProjectId === factoryProjectId && selected.has(binding.sourceId))\n .map(binding => binding.sourceId);\n}\n\n/**\n * Resolve the org-scoped tenant for 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 boundSourceIds = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const sourceIds = boundSourceIds ?? 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 && boundSourceIds && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload,\n });\n }\n return c.json({ issues: issuePayload, nextCursor: 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 boundSourceIds = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (boundSourceIds.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 || !boundSourceIds.includes(dispatch.sourceId)) {\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,eAMoB;CACpB,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,QAAQ,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAa,CAAC,EAAA,CACrE,QAAO,YAAW,QAAQ,qBAAqB,oBAAoB,SAAS,IAAI,QAAQ,QAAQ,CAAC,CAAC,CAClG,KAAI,YAAW,QAAQ,QAAQ;AACpC;;;;;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,OAAO;EACP,SAAS;CACX,GACA,GACF;CAEF,OAAO,EAAE,KAAK;EAAE,OAAO;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/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, IntakeItem } 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';\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\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 * it is bound to the Factory project. 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<string[]> {\n const selected = new Set(selectedIds);\n return (await intake.listBindings({ orgId, integrationId: 'incidentio' }))\n .filter(binding => binding.factoryProjectId === factoryProjectId && selected.has(binding.sourceId))\n .map(binding => binding.sourceId);\n}\n\n/**\n * Resolve the org-scoped tenant for 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 * The follow-ups a listing page serves, shared by the board route and the\n * reconcile sweep that files their cards. Incidents stay out of intake even\n * when a stale binding selects the incidents source.\n */\nexport function followUpIssues(items: IntakeItem[]): IncidentioIssuePayload[] {\n return items\n .filter(item => item.source.externalId.startsWith(FOLLOW_UP_PREFIX))\n .map(item => {\n const externalId = item.source.externalId;\n const metadata = item.metadata ?? {};\n const identifier = typeof metadata.identifier === 'string' ? metadata.identifier : externalId;\n const titlePrefix = `${identifier}: `;\n return {\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}\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 boundSourceIds = factoryProjectId\n ? await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const sourceIds = boundSourceIds ?? 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 return c.json({ issues: followUpIssues(page.items), 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 boundSourceIds = await scopeSourceIdsToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (boundSourceIds.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 || !boundSourceIds.includes(dispatch.sourceId)) {\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;;;;;;;;;AAuCzB,eAAsB,wBAAwB,EAC5C,QACA,OACA,kBACA,eAMoB;CACpB,MAAM,WAAW,IAAI,IAAI,WAAW;CACpC,QAAQ,MAAM,OAAO,aAAa;EAAE;EAAO,eAAe;CAAa,CAAC,EAAA,CACrE,QAAO,YAAW,QAAQ,qBAAqB,oBAAoB,SAAS,IAAI,QAAQ,QAAQ,CAAC,CAAC,CAClG,KAAI,YAAW,QAAQ,QAAQ;AACpC;;;;;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,OAA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CACF,CAAC,CACH;CAEA,OAAO;AACT"}
@@ -4,7 +4,6 @@ import type { ProjectBoardSource } from '../../boards/project-boards.js';
4
4
  import type { FactoryIncidentioRuleContext } from '../../rules/types.js';
5
5
  import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
6
6
  import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
7
- import type { IntegrationContext } from '../base.js';
8
7
  import type { IncidentioEventRules } from './default-rules.js';
9
8
  export interface IncidentioIssueIngress {
10
9
  /** Stable item reference — the prefixed incident.io follow-up id (`incidentio:follow-up:<ulid>`). */
@@ -55,8 +54,5 @@ export declare class IncidentioRules {
55
54
  ingested: number;
56
55
  }>;
57
56
  }
58
- export declare function attachIncidentioRules(incidentio: {
59
- readonly rules: IncidentioEventRules;
60
- }, context: IntegrationContext): ((input: IncidentioRulesIngress) => Promise<unknown>) | undefined;
61
57
  export {};
62
58
  //# sourceMappingURL=rules.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/incidentio/rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AASpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,KAAK,EAAE,4BAA4B,EAAuB,MAAM,sBAAsB,CAAC;AAG9F,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,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AI,CAAC;IACxB,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,sDAAsD;IACtD,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,6FAA6F;IAC7F,MAAM,EAAE,aAAa,GAAG,kBAAkB,CAAC;IAC3C,eAAe,EAAE,oBAAoB,CAAC;CACvC;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,EAAE,sBAAsB,EAAE,CAAC;CAClC;AAED,KAAK,aAAa,GAAG,WAAW,GAAG,UAAU,GAAG,SAAS,CAAC;AAE1D;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,4BAA4B,EAAE,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC,GAAG,eAAe,GAAG,SAAS,CAKlI;AAID,qBAAa,eAAe;;IACd,OAAO,CAAC,QAAQ,CAAC,OAAO;IAApC,YAA6B,OAAO,EAAE,sBAAsB,EAAI;IAO1D,MAAM,CAAC,KAAK,EAAE,sBAAsB,GAAG,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAwChG;CA4HF"}
@@ -28,6 +28,7 @@ function boardEventFor(context) {
28
28
  };
29
29
  return context.item ? void 0 : { type: "work_item.created" };
30
30
  }
31
+ const ingressIdFor = (issue) => `incidentio:${issue.id}:${issue.updatedAt}`;
31
32
  var IncidentioRules = class {
32
33
  options;
33
34
  constructor(options) {
@@ -60,11 +61,24 @@ var IncidentioRules = class {
60
61
  factoryProjectId: input.factoryProjectId
61
62
  });
62
63
  const itemsBySourceKey = new Map(items.map((item) => [item.externalSource?.externalId, item]));
64
+ const ingressIds = new Map(input.issues.map((issue) => [issue, ingressIdFor(issue)]));
65
+ const recorded = await this.options.storage.listRecordedIngress(input.orgId, input.factoryProjectId, [...ingressIds.values()]);
63
66
  const statuses = [];
67
+ const failures = [];
64
68
  for (const issue of input.issues) {
69
+ if (recorded.has(ingressIds.get(issue))) {
70
+ statuses.push("replayed");
71
+ continue;
72
+ }
65
73
  const relatedItem = itemsBySourceKey.get(issue.id);
66
- statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));
74
+ try {
75
+ statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));
76
+ } catch (error) {
77
+ failures.push(error);
78
+ }
67
79
  }
80
+ if (failures.length === 1) throw failures[0];
81
+ if (failures.length > 1) throw new AggregateError(failures, `${failures.length} incident.io follow-ups failed`);
68
82
  if (statuses.some((status) => status === "committed")) return {
69
83
  status: "committed",
70
84
  ingested: statuses.length
@@ -79,7 +93,7 @@ var IncidentioRules = class {
79
93
  };
80
94
  }
81
95
  async #ingestIssue(input, issue, relatedItem, attempt = 1) {
82
- const ingressId = `incidentio:${issue.id}:${issue.updatedAt}`;
96
+ const ingressId = ingressIdFor(issue);
83
97
  const actor = {
84
98
  type: "human",
85
99
  id: input.userId
@@ -184,17 +198,6 @@ var IncidentioRules = class {
184
198
  return committed.status;
185
199
  }
186
200
  };
187
- function attachIncidentioRules(incidentio, context) {
188
- if (!context.runtime) return void 0;
189
- const rules = new IncidentioRules({
190
- projects: context.storage.projects,
191
- storage: context.runtime.workItems,
192
- configVersion: context.runtime.configVersion,
193
- boards: context.runtime.boards,
194
- incidentioRules: incidentio.rules
195
- });
196
- return (input) => rules.ingest(input);
197
- }
198
- export { IncidentioRules, attachIncidentioRules, boardEventFor };
201
+ export { IncidentioRules, boardEventFor };
199
202
 
200
203
  //# sourceMappingURL=rules.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/incidentio/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 withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryIncidentioRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { IncidentioEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface IncidentioIssueIngress {\n /** Stable item reference — the prefixed incident.io follow-up id (`incidentio:follow-up:<ulid>`). */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the follow-up creator, when available. */\n author: string | null;\n /** Reference of the incident this follow-up belongs to, when available. */\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** incident.io source the follow-up was read from. */\n sourceId?: string | null;\n}\n\nexport interface IncidentioRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n incidentioRules: IncidentioEventRules;\n}\n\nexport interface IncidentioRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: IncidentioIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a incident.io sync reports: a follow-up seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open follow-up report none.\n */\nexport function boardEventFor(context: Pick<FactoryIncidentioRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'followUpClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class IncidentioRules {\n constructor(private readonly options: IncidentioRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: IncidentioRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'incidentio', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per follow-up per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: IncidentioRulesIngress,\n issue: IncidentioIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `incidentio:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed follow-ups without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'followUpClosed' : 'followUpObserved';\n const context: FactoryIncidentioRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'incidentio', id: ingressId },\n cause: `incidentio.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'incidentio-follow-up',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory incident.io rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: `incidentio.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory incident.io rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachIncidentioRules(\n incidentio: { readonly rules: IncidentioEventRules },\n context: IntegrationContext,\n): ((input: IncidentioRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new IncidentioRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n incidentioRules: incidentio.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA6ChC,SAAgB,cAAc,SAAsG;CAClI,IAAI,QAAQ,UAAU,kBACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,cAAc,UAAU;CAAE;CAEjG,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;AAEA,IAAa,kBAAb,MAA6B;CACE;CAA7B,YAAY,SAAkD;EAAjC,KAAA,UAAA;CAAkC;;CAG/D,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,OAAO,OAAqF;EAEhG,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,O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AAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF;AAEA,SAAgB,sBACd,YACA,SACmE;CACnE,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,gBAAgB;EAChC,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,iBAAiB,WAAW;CAC9B,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
1
+ {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/incidentio/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 withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryIncidentioRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IncidentioEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface IncidentioIssueIngress {\n /** Stable item reference — the prefixed incident.io follow-up id (`incidentio:follow-up:<ulid>`). */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the follow-up creator, when available. */\n author: string | null;\n /** Reference of the incident this follow-up belongs to, when available. */\n incident: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** incident.io source the follow-up was read from. */\n sourceId?: string | null;\n}\n\nexport interface IncidentioRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n incidentioRules: IncidentioEventRules;\n}\n\nexport interface IncidentioRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: IncidentioIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a incident.io sync reports: a follow-up seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open follow-up report none.\n */\nexport function boardEventFor(context: Pick<FactoryIncidentioRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'followUpClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nconst ingressIdFor = (issue: IncidentioIssueIngress) => `incidentio:${issue.id}:${issue.updatedAt}`;\n\nexport class IncidentioRules {\n constructor(private readonly options: IncidentioRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: IncidentioRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'incidentio', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const ingressIds = new Map(input.issues.map(issue => [issue, ingressIdFor(issue)]));\n const recorded = await this.options.storage.listRecordedIngress(\n input.orgId,\n input.factoryProjectId,\n [...ingressIds.values()],\n );\n const statuses: IngressStatus[] = [];\n const failures: unknown[] = [];\n for (const issue of input.issues) {\n if (recorded.has(ingressIds.get(issue)!)) {\n statuses.push('replayed');\n continue;\n }\n // One card per follow-up per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id);\n try {\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n } catch (error) {\n failures.push(error);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, `${failures.length} incident.io follow-ups failed`);\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: IncidentioRulesIngress,\n issue: IncidentioIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = ingressIdFor(issue);\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed follow-ups without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'followUpClosed' : 'followUpObserved';\n const context: FactoryIncidentioRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'incidentio', id: ingressId },\n cause: `incidentio.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'incidentio-follow-up',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.incidentioRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'incidentio'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory incident.io rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: `incidentio.${event}` },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory incident.io rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA6ChC,SAAgB,cAAc,SAAsG;CAClI,IAAI,QAAQ,UAAU,kBAC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;IACR,MAAM,WAAW,YAAY;IAC7B,QAAQ,WACJ,uCACA,iBAAiB,QACf,MAAM,QAAQ,MAAM,GAAG,GAAK,IAC5B;GACR;EACF;EACA,IAAI,mBAAmB,YAAY,UAAU,IAAI,iBAAiB;EAClE,IAAI,CAAC,YAAY,CAAC,qBAAqB,QAAQ,WAAW,YAAY;GACpE,MAAM,SAAS,MAAM,mBAAmB,SAAS,KAAK,QAAQ,SAAS;IACrE,OAAO,MAAM;IACb,kBAAkB,MAAM;GAC1B,CAAC;GACD,IAAI,QAAQ,YAAY,CAAC,EAAE,GAAG,OAAO,CAAC;EACxC;EAEA,MAAM,YAAY,MAAM,KAAK,QAAQ,QAAQ,qBAAqB;GAChE,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,YAAY,aAAa,MAAM;GAC/B,SAAS;IAAE,UAAU;IAAW,aAAa,cAAc;GAAQ;GACnE,eAAe,KAAK,QAAQ;GAC5B,kBAAkB,aAAa,YAAY;GAC3C;GACA;GACA;GACA,aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;EAChB,CAAC;EACD,IAAI,UAAU,WAAW,SAAS;GAEhC,IAAI,WAAW,yBACb,MAAM,IAAI,MAAM,2CAA2C,UAAU,6BAA6B;GAEpG,MAAM,QAAQ,cAAc,MAAM,KAAK,QAAQ,QAAQ,IAAI;IAAE,OAAO,MAAM;IAAO,IAAI,YAAY;GAAG,CAAC,IAAI;GACzG,IAAI,eAAe,CAAC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
@@ -0,0 +1,44 @@
1
+ import type { IntakeStorage } from '../storage/domains/intake/base.js';
2
+ import type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';
3
+ import type { IssueReconcileSummary } from './issue-reconciler.js';
4
+ export declare const INTAKE_DISCOVERY_MAX_PAGES = 5;
5
+ export type IntakeDiscoverySummary = IssueReconcileSummary & {
6
+ /** Listed issues replayed through the provider rules (first sight creates the card). */
7
+ observed: number;
8
+ };
9
+ interface IntakePage<TIssue> {
10
+ issues: TIssue[];
11
+ nextCursor: string | null;
12
+ }
13
+ type IntakePager<TIssue> = (cursor: string | undefined) => Promise<IntakePage<TIssue>>;
14
+ export interface IntakeDiscoveryOptions<TIssue> {
15
+ integrationId: string;
16
+ intake: Pick<IntakeStorage, 'ensureReady' | 'getConfig'>;
17
+ projects: Pick<FactoryProjectsStorage, 'listAll'>;
18
+ /**
19
+ * One pager per source bound to the project, so a busy source cannot spend
20
+ * the pages of the others. Empty when no selected source feeds the project.
21
+ */
22
+ open(project: FactoryProject, selectedIds: string[]): Promise<Array<IntakePager<TIssue>>>;
23
+ /**
24
+ * Pages read from each source per sweep. Five suits a provider that lists its
25
+ * most recently updated issues first; one that cannot sort must read them all.
26
+ */
27
+ maxPages?: number;
28
+ ingest(input: {
29
+ orgId: string;
30
+ userId: string;
31
+ factoryProjectId: string;
32
+ issues: TIssue[];
33
+ }): Promise<unknown>;
34
+ }
35
+ /**
36
+ * Extend a provider's reconcile sweep so it also files issues nobody has
37
+ * carded yet: after refreshing existing cards, list what each project's board
38
+ * shows and replay it through the provider rules. Providers that send Factory
39
+ * no events have no other first-sight path. A failing project or source is
40
+ * recorded and the sweep moves on.
41
+ */
42
+ export declare function withIntakeDiscovery<TIssue>(reconcile: () => Promise<IssueReconcileSummary>, options: IntakeDiscoveryOptions<TIssue>): () => Promise<IntakeDiscoverySummary>;
43
+ export {};
44
+ //# sourceMappingURL=intake-discovery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"intake-discovery.d.ts","sourceRoot":"","sources":["../../src/integrations/intake-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClG,OAAO,KAAK,EAAE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C"}
@@ -0,0 +1,60 @@
1
+ // src/integrations/intake-discovery.ts
2
+ const INTAKE_DISCOVERY_MAX_PAGES = 5;
3
+ /**
4
+ * Extend a provider's reconcile sweep so it also files issues nobody has
5
+ * carded yet: after refreshing existing cards, list what each project's board
6
+ * shows and replay it through the provider rules. Providers that send Factory
7
+ * no events have no other first-sight path. A failing project or source is
8
+ * recorded and the sweep moves on.
9
+ */
10
+ function withIntakeDiscovery(reconcile, options) {
11
+ return async () => {
12
+ const summary = {
13
+ ...await reconcile(),
14
+ observed: 0
15
+ };
16
+ for (const project of await options.projects.listAll()) try {
17
+ await options.intake.ensureReady();
18
+ const selection = (await options.intake.getConfig({
19
+ orgId: project.orgId,
20
+ integrationIds: [options.integrationId]
21
+ }))[options.integrationId];
22
+ if (!selection?.enabled) continue;
23
+ for (const listPage of await options.open(project, selection.sourceIds ?? [])) try {
24
+ let cursor;
25
+ const seenCursors = /* @__PURE__ */ new Set();
26
+ for (let page = 0; page < (options.maxPages ?? 5); page += 1) {
27
+ const { issues, nextCursor } = await listPage(cursor);
28
+ if (issues.length > 0) {
29
+ await options.ingest({
30
+ orgId: project.orgId,
31
+ userId: "factory-rule-dispatcher",
32
+ factoryProjectId: project.id,
33
+ issues
34
+ });
35
+ summary.observed += issues.length;
36
+ }
37
+ if (!nextCursor) break;
38
+ if (seenCursors.has(nextCursor)) throw new Error(`${options.integrationId} repeated a page cursor`);
39
+ seenCursors.add(nextCursor);
40
+ cursor = nextCursor;
41
+ }
42
+ } catch (error) {
43
+ recordFailure(summary, project, error);
44
+ }
45
+ } catch (error) {
46
+ recordFailure(summary, project, error);
47
+ }
48
+ return summary;
49
+ };
50
+ }
51
+ function recordFailure(summary, project, error) {
52
+ summary.failed += 1;
53
+ summary.errors.push({
54
+ projectId: project.id,
55
+ error: error instanceof Error ? error.message : String(error)
56
+ });
57
+ }
58
+ export { INTAKE_DISCOVERY_MAX_PAGES, withIntakeDiscovery };
59
+
60
+ //# sourceMappingURL=intake-discovery.js.map