@mastra/factory 0.28.0-alpha.5 → 0.28.0-alpha.7

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 (289) hide show
  1. package/README.md +52 -28
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +5 -5
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/board-writes.d.ts +1 -1
  6. package/dist/boards/board-writes.d.ts.map +1 -1
  7. package/dist/boards/board-writes.js +7 -8
  8. package/dist/boards/board-writes.js.map +1 -1
  9. package/dist/boards/index.d.ts +1 -1
  10. package/dist/boards/index.d.ts.map +1 -1
  11. package/dist/boards/index.js +2 -2
  12. package/dist/boards/project-boards.d.ts +30 -4
  13. package/dist/boards/project-boards.d.ts.map +1 -1
  14. package/dist/boards/project-boards.js +71 -19
  15. package/dist/boards/project-boards.js.map +1 -1
  16. package/dist/boards/registry.d.ts +7 -1
  17. package/dist/boards/registry.d.ts.map +1 -1
  18. package/dist/boards/registry.js +16 -3
  19. package/dist/boards/registry.js.map +1 -1
  20. package/dist/boards/semantics.d.ts +5 -4
  21. package/dist/boards/semantics.d.ts.map +1 -1
  22. package/dist/boards/semantics.js +5 -4
  23. package/dist/boards/semantics.js.map +1 -1
  24. package/dist/boards/work-migrations.d.ts +4 -3
  25. package/dist/boards/work-migrations.d.ts.map +1 -1
  26. package/dist/boards/work-migrations.js +6 -5
  27. package/dist/boards/work-migrations.js.map +1 -1
  28. package/dist/boards/work-seeds.d.ts +9 -0
  29. package/dist/boards/work-seeds.d.ts.map +1 -0
  30. package/dist/boards/work-seeds.js +56 -0
  31. package/dist/boards/work-seeds.js.map +1 -0
  32. package/dist/boards/work.d.ts +2 -2
  33. package/dist/boards/work.d.ts.map +1 -1
  34. package/dist/boards/work.js +0 -16
  35. package/dist/boards/work.js.map +1 -1
  36. package/dist/environment/build-runner.d.ts.map +1 -1
  37. package/dist/environment/build-runner.js +2 -2
  38. package/dist/environment/build-runner.js.map +1 -1
  39. package/dist/environment/build-workflow.d.ts.map +1 -1
  40. package/dist/environment/build-workflow.js +6 -5
  41. package/dist/environment/build-workflow.js.map +1 -1
  42. package/dist/environment/build.d.ts +15 -2
  43. package/dist/environment/build.d.ts.map +1 -1
  44. package/dist/environment/build.js +32 -9
  45. package/dist/environment/build.js.map +1 -1
  46. package/dist/factory.d.ts +8 -4
  47. package/dist/factory.d.ts.map +1 -1
  48. package/dist/factory.js +57 -59
  49. package/dist/factory.js.map +1 -1
  50. package/dist/feed-events.d.ts +2 -3
  51. package/dist/feed-events.d.ts.map +1 -1
  52. package/dist/feed-events.js +4 -5
  53. package/dist/feed-events.js.map +1 -1
  54. package/dist/index.d.ts +2 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +3 -1
  57. package/dist/integrations/base.d.ts +0 -11
  58. package/dist/integrations/base.d.ts.map +1 -1
  59. package/dist/integrations/github/integration.d.ts.map +1 -1
  60. package/dist/integrations/github/integration.js +7 -3
  61. package/dist/integrations/github/integration.js.map +1 -1
  62. package/dist/integrations/github/issue-reconciler.js +2 -2
  63. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  64. package/dist/integrations/github/provenance.js +1 -1
  65. package/dist/integrations/github/provenance.js.map +1 -1
  66. package/dist/integrations/github/reconcile-worker.d.ts +5 -1
  67. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  68. package/dist/integrations/github/reconcile-worker.js +39 -6
  69. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  70. package/dist/integrations/github/routes.d.ts +4 -3
  71. package/dist/integrations/github/routes.d.ts.map +1 -1
  72. package/dist/integrations/github/routes.js +9 -86
  73. package/dist/integrations/github/routes.js.map +1 -1
  74. package/dist/integrations/github/rules.d.ts +67 -0
  75. package/dist/integrations/github/rules.d.ts.map +1 -1
  76. package/dist/integrations/github/rules.js +215 -12
  77. package/dist/integrations/github/rules.js.map +1 -1
  78. package/dist/integrations/github/sandbox.d.ts +10 -2
  79. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  80. package/dist/integrations/github/sandbox.js +20 -4
  81. package/dist/integrations/github/sandbox.js.map +1 -1
  82. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  83. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  84. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  85. package/dist/integrations/gitlab/rules.js +6 -5
  86. package/dist/integrations/gitlab/rules.js.map +1 -1
  87. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/rules.js +5 -2
  89. package/dist/integrations/incidentio/rules.js.map +1 -1
  90. package/dist/integrations/issue-reconciler.js +1 -1
  91. package/dist/integrations/issue-reconciler.js.map +1 -1
  92. package/dist/integrations/jira/rules.d.ts.map +1 -1
  93. package/dist/integrations/jira/rules.js +5 -2
  94. package/dist/integrations/jira/rules.js.map +1 -1
  95. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  96. package/dist/integrations/linear/agent-tools.js +1 -1
  97. package/dist/integrations/linear/agent-tools.js.map +1 -1
  98. package/dist/integrations/linear/rules.d.ts.map +1 -1
  99. package/dist/integrations/linear/rules.js +2 -2
  100. package/dist/integrations/linear/rules.js.map +1 -1
  101. package/dist/integrations/platform/github/event-worker.d.ts +4 -1
  102. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  103. package/dist/integrations/platform/github/event-worker.js +39 -3
  104. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  105. package/dist/integrations/platform/github/integration.d.ts +8 -0
  106. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  107. package/dist/integrations/platform/github/integration.js +21 -3
  108. package/dist/integrations/platform/github/integration.js.map +1 -1
  109. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  110. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  111. package/dist/integrations/platform/linear/event-worker.js +1 -1
  112. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  113. package/dist/integrations/slack/integration.d.ts +0 -2
  114. package/dist/integrations/slack/integration.d.ts.map +1 -1
  115. package/dist/integrations/slack/integration.js +0 -5
  116. package/dist/integrations/slack/integration.js.map +1 -1
  117. package/dist/integrations/slack/slack.d.ts +3 -18
  118. package/dist/integrations/slack/slack.d.ts.map +1 -1
  119. package/dist/integrations/slack/slack.js +3 -74
  120. package/dist/integrations/slack/slack.js.map +1 -1
  121. package/dist/links.d.ts +1 -2
  122. package/dist/links.d.ts.map +1 -1
  123. package/dist/links.js +1 -2
  124. package/dist/links.js.map +1 -1
  125. package/dist/mcp/routes.js +1 -1
  126. package/dist/mcp/routes.js.map +1 -1
  127. package/dist/routes/attention-parked.js +1 -1
  128. package/dist/routes/attention-parked.js.map +1 -1
  129. package/dist/routes/attention-providers.d.ts +0 -25
  130. package/dist/routes/attention-providers.d.ts.map +1 -1
  131. package/dist/routes/attention-providers.js +2 -150
  132. package/dist/routes/attention-providers.js.map +1 -1
  133. package/dist/routes/attention.d.ts +0 -2
  134. package/dist/routes/attention.d.ts.map +1 -1
  135. package/dist/routes/attention.js +2 -13
  136. package/dist/routes/attention.js.map +1 -1
  137. package/dist/routes/boards.d.ts +1 -1
  138. package/dist/routes/boards.d.ts.map +1 -1
  139. package/dist/routes/boards.js.map +1 -1
  140. package/dist/routes/contracts.d.ts +121 -14
  141. package/dist/routes/contracts.d.ts.map +1 -1
  142. package/dist/routes/contracts.js +73 -3
  143. package/dist/routes/contracts.js.map +1 -1
  144. package/dist/routes/feed-events.d.ts +15 -0
  145. package/dist/routes/feed-events.d.ts.map +1 -0
  146. package/dist/routes/feed-events.js +68 -0
  147. package/dist/routes/feed-events.js.map +1 -0
  148. package/dist/routes/knowledge.js +1 -1
  149. package/dist/routes/projects.d.ts +1 -1
  150. package/dist/routes/projects.d.ts.map +1 -1
  151. package/dist/routes/projects.js +13 -7
  152. package/dist/routes/projects.js.map +1 -1
  153. package/dist/routes/sandbox-envs.d.ts +26 -0
  154. package/dist/routes/sandbox-envs.d.ts.map +1 -0
  155. package/dist/routes/sandbox-envs.js +180 -0
  156. package/dist/routes/sandbox-envs.js.map +1 -0
  157. package/dist/routes/surface.d.ts +0 -7
  158. package/dist/routes/surface.d.ts.map +1 -1
  159. package/dist/routes/surface.js +1 -5
  160. package/dist/routes/surface.js.map +1 -1
  161. package/dist/routes/work-items.d.ts +0 -3
  162. package/dist/routes/work-items.d.ts.map +1 -1
  163. package/dist/routes/work-items.js +1 -2
  164. package/dist/routes/work-items.js.map +1 -1
  165. package/dist/rules/dispatcher.d.ts +0 -3
  166. package/dist/rules/dispatcher.d.ts.map +1 -1
  167. package/dist/rules/dispatcher.js +8 -9
  168. package/dist/rules/dispatcher.js.map +1 -1
  169. package/dist/sandbox/sandbox-env-cache.d.ts +33 -0
  170. package/dist/sandbox/sandbox-env-cache.d.ts.map +1 -0
  171. package/dist/sandbox/sandbox-env-cache.js +140 -0
  172. package/dist/sandbox/sandbox-env-cache.js.map +1 -0
  173. package/dist/sandbox/sandbox-env.d.ts +77 -0
  174. package/dist/sandbox/sandbox-env.d.ts.map +1 -0
  175. package/dist/sandbox/sandbox-env.js +130 -0
  176. package/dist/sandbox/sandbox-env.js.map +1 -0
  177. package/dist/storage/domains/audit/actions.d.ts +2 -1
  178. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  179. package/dist/storage/domains/audit/actions.js +5 -4
  180. package/dist/storage/domains/audit/actions.js.map +1 -1
  181. package/dist/storage/domains/boards/base.d.ts +15 -1
  182. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  183. package/dist/storage/domains/boards/base.js +21 -5
  184. package/dist/storage/domains/boards/base.js.map +1 -1
  185. package/dist/storage/domains/channel-identity/base.d.ts +0 -4
  186. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
  187. package/dist/storage/domains/channel-identity/base.js +0 -7
  188. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  189. package/dist/storage/domains/sandbox-envs/base.d.ts +70 -0
  190. package/dist/storage/domains/sandbox-envs/base.d.ts.map +1 -0
  191. package/dist/storage/domains/sandbox-envs/base.js +227 -0
  192. package/dist/storage/domains/sandbox-envs/base.js.map +1 -0
  193. package/dist/storage/domains/work-items/base.d.ts +8 -9
  194. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  195. package/dist/storage/domains/work-items/base.js +20 -86
  196. package/dist/storage/domains/work-items/base.js.map +1 -1
  197. package/dist/storage/domains/work-items/cards.d.ts +3 -3
  198. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  199. package/dist/storage/domains/work-items/cards.js +10 -10
  200. package/dist/storage/domains/work-items/cards.js.map +1 -1
  201. package/dist/storage/domains/work-items/metrics.d.ts +1 -1
  202. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
  203. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  204. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -2
  205. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  206. package/dist/storage/domains/work-items/work-item-schema.js +8 -8
  207. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  208. package/dist/tools/read-tools.d.ts +0 -2
  209. package/dist/tools/read-tools.d.ts.map +1 -1
  210. package/dist/tools/read-tools.js +3 -14
  211. package/dist/tools/read-tools.js.map +1 -1
  212. package/dist/tools/work-item-tools.d.ts +0 -3
  213. package/dist/tools/work-item-tools.d.ts.map +1 -1
  214. package/dist/tools/work-item-tools.js +8 -18
  215. package/dist/tools/work-item-tools.js.map +1 -1
  216. package/dist/work-items/create-work-item.d.ts.map +1 -1
  217. package/dist/work-items/create-work-item.js +3 -2
  218. package/dist/work-items/create-work-item.js.map +1 -1
  219. package/dist/work-items/description-context.d.ts +5 -0
  220. package/dist/work-items/description-context.d.ts.map +1 -0
  221. package/dist/work-items/description-context.js +17 -0
  222. package/dist/work-items/description-context.js.map +1 -0
  223. package/dist/work-items/split-migration.d.ts.map +1 -1
  224. package/dist/work-items/split-migration.js +1 -6
  225. package/dist/work-items/split-migration.js.map +1 -1
  226. package/dist/workspace.d.ts +3 -0
  227. package/dist/workspace.d.ts.map +1 -1
  228. package/dist/workspace.js +21 -4
  229. package/dist/workspace.js.map +1 -1
  230. package/factory-skills/configure-factory-rules/SKILL.md +3 -3
  231. package/factory-skills/factory-rereview/SKILL.md +2 -2
  232. package/factory-skills/factory-review/SKILL.md +2 -2
  233. package/factory-skills/factory-triage/SKILL.md +3 -2
  234. package/package.json +7 -7
  235. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
  236. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
  237. package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
  238. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
  239. package/dist/integrations/slack/emoji.d.ts +0 -3
  240. package/dist/integrations/slack/emoji.d.ts.map +0 -1
  241. package/dist/integrations/slack/emoji.js +0 -11
  242. package/dist/integrations/slack/emoji.js.map +0 -1
  243. package/dist/integrations/slack/feed-publisher.d.ts +0 -26
  244. package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
  245. package/dist/integrations/slack/feed-publisher.js +0 -43
  246. package/dist/integrations/slack/feed-publisher.js.map +0 -1
  247. package/dist/routes/attention-activity.d.ts +0 -23
  248. package/dist/routes/attention-activity.d.ts.map +0 -1
  249. package/dist/routes/attention-activity.js +0 -154
  250. package/dist/routes/attention-activity.js.map +0 -1
  251. package/dist/storage/domains/comments/activity.d.ts +0 -40
  252. package/dist/storage/domains/comments/activity.d.ts.map +0 -1
  253. package/dist/storage/domains/comments/activity.js +0 -93
  254. package/dist/storage/domains/comments/activity.js.map +0 -1
  255. package/dist/storage/domains/comments/actor.d.ts +0 -51
  256. package/dist/storage/domains/comments/actor.d.ts.map +0 -1
  257. package/dist/storage/domains/comments/actor.js +0 -37
  258. package/dist/storage/domains/comments/actor.js.map +0 -1
  259. package/dist/storage/domains/comments/base.d.ts +0 -245
  260. package/dist/storage/domains/comments/base.d.ts.map +0 -1
  261. package/dist/storage/domains/comments/base.js +0 -539
  262. package/dist/storage/domains/comments/base.js.map +0 -1
  263. package/dist/storage/domains/comments/domain.d.ts +0 -135
  264. package/dist/storage/domains/comments/domain.d.ts.map +0 -1
  265. package/dist/storage/domains/comments/domain.js +0 -284
  266. package/dist/storage/domains/comments/domain.js.map +0 -1
  267. package/dist/storage/domains/comments/feed-context.d.ts +0 -22
  268. package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
  269. package/dist/storage/domains/comments/feed-context.js +0 -88
  270. package/dist/storage/domains/comments/feed-context.js.map +0 -1
  271. package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
  272. package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
  273. package/dist/storage/domains/comments/feed-sync.js +0 -1
  274. package/dist/storage/domains/comments/parse.d.ts +0 -23
  275. package/dist/storage/domains/comments/parse.d.ts.map +0 -1
  276. package/dist/storage/domains/comments/parse.js +0 -89
  277. package/dist/storage/domains/comments/parse.js.map +0 -1
  278. package/dist/storage/domains/comments/routes.d.ts +0 -24
  279. package/dist/storage/domains/comments/routes.d.ts.map +0 -1
  280. package/dist/storage/domains/comments/routes.js +0 -301
  281. package/dist/storage/domains/comments/routes.js.map +0 -1
  282. package/dist/storage/domains/comments/schema.d.ts +0 -5
  283. package/dist/storage/domains/comments/schema.d.ts.map +0 -1
  284. package/dist/storage/domains/comments/schema.js +0 -178
  285. package/dist/storage/domains/comments/schema.js.map +0 -1
  286. package/dist/storage/domains/comments/wire.d.ts +0 -40
  287. package/dist/storage/domains/comments/wire.d.ts.map +0 -1
  288. package/dist/storage/domains/comments/wire.js +0 -36
  289. package/dist/storage/domains/comments/wire.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/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 { FactoryJiraRuleContext, 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 { JiraEventRules } 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 JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\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 Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\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 jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\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 JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\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: JiraRulesIngress): 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: 'jira', type: 'issue', externalId: issue.id })),\n });\n const items = await this.options.storage.list({ 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 Jira issue per project; other projects may file their own.\n statuses.push(await this.#ingestIssue(input, issue, itemsBySourceKey.get(issue.id)));\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: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues 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 ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\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.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\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 Jira 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: 'jira.issueObserved' },\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 Jira 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 attachJiraRules(\n jira: { readonly rules: JiraEventRules },\n context: IntegrationContext,\n): ((input: JiraRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new JiraRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion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} 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 { FactoryJiraRuleContext, 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 { JiraEventRules } 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 JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\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 Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\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 jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\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 JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\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: JiraRulesIngress): 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: 'jira', 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 Jira issue 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: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues 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 ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\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.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\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 Jira 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: 'jira.issueObserved' },\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 Jira 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 attachJiraRules(\n jira: { readonly rules: JiraEventRules },\n context: IntegrationContext,\n): ((input: JiraRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new JiraRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n jiraRules: jira.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;;;;;AA+ChC,SAAgB,cAAc,SAAgG;CAC5H,IAAI,QAAQ,UAAU,eACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,cAAc,UAAU;CAAE;CAEjG,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;AAEA,IAAa,YAAb,MAAuB;CACQ;CAA7B,YAAY,SAA4C;EAA3B,KAAA,UAAA;CAA4B;;CAGzD,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,OAAO,OAA+E;EAE1F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EACtD,MAAM,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK;EAGnD,MAAM,KAAK,QAAQ,QAAQ,gBAAgB;GACzC,OAAO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AAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,WAAW,KAAK;CAClB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"agent-tools.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/agent-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,iBAAS,wBAAwB,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,IAAI;;yIAkCzG;AAED,iBAAS,uBAAuB,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM;;;8IAsCxE;AAED,iBAAS,4BAA4B,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM;;6IAwC7E;AAED,iBAAS,0BAA0B,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM;;;;2IA4C3E;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,EAC1C,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,gEAAgE;IAChE,MAAM,EAAE,iBAAiB,CAAC;CAC3B,GAAG,OAAO,CACT,MAAM,CACJ,MAAM,EACJ,UAAU,CAAC,OAAO,wBAAwB,CAAC,GAC3C,UAAU,CAAC,OAAO,uBAAuB,CAAC,GAC1C,UAAU,CAAC,OAAO,4BAA4B,CAAC,GAC/C,UAAU,CAAC,OAAO,0BAA0B,CAAC,CAChD,CACF,CA2BA"}
1
+ {"version":3,"file":"agent-tools.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/agent-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,iBAAS,wBAAwB,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,GAAG,IAAI;;yIAkCzG;AAED,iBAAS,uBAAuB,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM;;;8IAwCxE;AAED,iBAAS,4BAA4B,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM;;6IAwC7E;AAED,iBAAS,0BAA0B,CAAC,MAAM,EAAE,iBAAiB,EAAE,KAAK,EAAE,MAAM;;;;2IA4C3E;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,EAC1C,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,gEAAgE;IAChE,MAAM,EAAE,iBAAiB,CAAC;CAC3B,GAAG,OAAO,CACT,MAAM,CACJ,MAAM,EACJ,UAAU,CAAC,OAAO,wBAAwB,CAAC,GAC3C,UAAU,CAAC,OAAO,uBAAuB,CAAC,GAC1C,UAAU,CAAC,OAAO,4BAA4B,CAAC,GAC/C,UAAU,CAAC,OAAO,0BAA0B,CAAC,CAChD,CACF,CA2BA"}
@@ -35,7 +35,7 @@ function createLinearCommentTool(linear, orgId) {
35
35
  description: "Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.",
36
36
  inputSchema: z.object({
37
37
  issue: z.string().min(1).describe("The Linear issue identifier (e.g. \"ENG-123\") or issue UUID."),
38
- body: z.string().min(1).describe("The comment body, as Linear-flavored markdown.")
38
+ body: z.string().min(1).describe("The comment body, as Linear-flavored markdown. Linear does not render HTML (no <details>, <summary> or <!-- comments -->); for a collapsible section, open it with a \"+++ Section title\" line and close it with a lone \"+++\" line.")
39
39
  }),
40
40
  execute: async ({ issue, body }) => {
41
41
  const connection = await linear.loadConnection(orgId);
@@ -1 +1 @@
1
- {"version":3,"file":"agent-tools.js","names":[],"sources":["../../../src/integrations/linear/agent-tools.ts"],"sourcesContent":["/**\n * Linear tools exposed to the coding agent.\n *\n * Wired into the agent through the SDK's async `extraTools` provider: on each\n * tool-set resolution we map the session's factory project to its owning org\n * and only expose the Linear tools when that org has a Linear connection.\n * Projects whose org never connected Linear (or when the\n * feature is disabled) see no Linear tools at all — the model is never shown\n * tools it can't use.\n *\n * Tenancy mirrors the Linear API routes: everything is scoped by the org that\n * owns the project, and tokens are refreshed through the integration's shared\n * connection lifecycle.\n */\n\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\nfunction createLinearGetIssueTool(linear: LinearIntegration, orgId: string, workspaceUrlKey: string | null) {\n // The URL pattern lets the agent link a ticket it mentions without fetching it first.\n const linkHint = workspaceUrlKey\n ? ` Issues in this workspace link as https://linear.app/${workspaceUrlKey}/issue/<identifier> (e.g. https://linear.app/${workspaceUrlKey}/issue/ENG-123).`\n : ' To link an issue, use the `url` field of the fetched issue.';\n return createTool({\n id: 'linear_get_issue',\n description: `Fetch a Linear issue's full details — title, description, state, assignee, labels, priority, and discussion comments. Use this whenever you're working on a Linear issue (e.g. ENG-123) to get its complete context.${linkHint}`,\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n }),\n execute: async ({ issue }: { issue: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to fetch issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const detail = await linear.intake.getIssue({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n });\n if (!detail) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return detail;\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to fetch Linear issue: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearCommentTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_create_comment',\n description:\n 'Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.',\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n body: z.string().min(1).describe('The comment body, as Linear-flavored markdown.'),\n }),\n execute: async ({ issue, body }: { issue: string; body: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to post comments.' };\n }\n if (!linear.canPostComments(connection)) {\n return {\n error: 'The Linear connection does not have comment permissions. Reconnect Linear in Settings to grant them.',\n };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const comment = await linear.intake.createComment({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n body,\n });\n if (!comment) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return { posted: true, url: comment.url };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to post Linear comment: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearListProjectsTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_list_projects',\n description:\n 'List the Linear projects and teams in the connected workspace, with the source id linear_list_issues needs. Use this to find a project (e.g. from a linear.app/<workspace>/project/<name-slug>-<id> URL, by matching its name; drop the trailing id from the slug) before listing its issues.',\n inputSchema: z.object({\n query: z.string().optional().describe('Case-insensitive text to match against project and team names.'),\n }),\n execute: async ({ query }: { query?: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to list projects.' };\n }\n try {\n // Linear sources are scoped by org alone; no Linear implementation reads userId.\n const sources = await linear.intake.listSources({ orgId, userId: '' });\n // Fold hyphens into spaces so a URL slug like \"agent-browser\" matches \"Agent Browser\".\n const normalize = (text: string) =>\n text\n .toLowerCase()\n .replace(/[\\s-]+/g, ' ')\n .trim();\n const needle = normalize(query ?? '');\n const matches = needle ? sources.filter(source => normalize(source.name).includes(needle)) : sources;\n return {\n projects: matches\n .filter(source => source.type === 'project')\n .map(source => ({ sourceId: source.id, name: source.name })),\n teams: matches\n .filter(source => source.type === 'team')\n .map(source => ({ sourceId: source.id, name: source.name, key: source.metadata?.teamKey ?? null })),\n };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to list Linear projects: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearListIssuesTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_list_issues',\n description:\n 'List the open issues (triage, backlog, todo and in progress; completed and canceled are left out) in one Linear project or team, most recently updated first. Get the source id from linear_list_projects, and read an issue in full with linear_get_issue. Pass nextCursor back as cursor for the next page.',\n inputSchema: z.object({\n source: z.string().min(1).describe('The project or team source id returned by linear_list_projects.'),\n labels: z.array(z.string().trim().min(1)).optional().describe('Only return issues carrying one of these label names.'),\n cursor: z.string().optional().describe('The nextCursor from a previous call, to fetch the next page.'),\n }),\n execute: async ({ source, labels, cursor }: { source: string; labels?: string[]; cursor?: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to list issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const page = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: [source.trim()],\n ...(labels?.length ? { labels } : {}),\n ...(cursor ? { cursor } : {}),\n });\n return {\n issues: page.issues.map(issue => ({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state,\n priority: issue.priority,\n assignee: issue.assignee,\n labels: issue.labels,\n updatedAt: issue.updatedAt,\n })),\n nextCursor: page.nextCursor,\n };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to list Linear issues: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\n/**\n * Async `extraTools` provider: expose Linear tools only when the session's\n * project belongs to an org with an active Linear connection.\n */\nexport async function buildLinearAgentTools({\n requestContext,\n linear,\n}: {\n requestContext: RequestContext;\n /** The integration instance providing the Linear API client. */\n linear: LinearIntegration;\n}): Promise<\n Record<\n string,\n | ReturnType<typeof createLinearGetIssueTool>\n | ReturnType<typeof createLinearCommentTool>\n | ReturnType<typeof createLinearListProjectsTool>\n | ReturnType<typeof createLinearListIssuesTool>\n >\n> {\n if (!linear.authEnabled) return {};\n\n const ctx = requestContext.get('controller') as\n AgentControllerRequestContext<{ factoryProjectId?: string }> | undefined;\n if (!ctx) return {};\n\n // Prefer the Factory recorded on the session. Factory sessions run under the\n // Factory as their resource, so the resource is the fallback; a legacy\n // session whose resource is its own id resolves to no project.\n const projectId = ctx.getState().factoryProjectId ?? ctx.resourceId;\n if (!projectId) return {};\n\n const orgId = await linear.resolveOrgId(projectId);\n if (!orgId) return {};\n const check = await linear.checkConnection(orgId);\n if (!check.connected) return {};\n\n return {\n linear_get_issue: createLinearGetIssueTool(linear, orgId, check.workspaceUrlKey),\n linear_list_projects: createLinearListProjectsTool(linear, orgId),\n linear_list_issues: createLinearListIssuesTool(linear, orgId),\n // Only offered when the granted OAuth scope allows posting comments —\n // connections made before `comments:create` was requested are read-only\n // until the org reconnects Linear.\n ...(check.canComment ? { linear_create_comment: createLinearCommentTool(linear, orgId) } : {}),\n };\n}\n"],"mappings":";;;;AAuBA,SAAS,yBAA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;MACb,UAAU,MAAM;MAChB,UAAU,MAAM;MAChB,QAAQ,MAAM;MACd,WAAW,MAAM;KACnB,EAAE;KACF,YAAY,KAAK;IACnB;GACF,SAAS,KAAK;IACZ,IAAI,eAAe,2BACjB,OAAO,EAAE,OAAO,IAAI,QAAQ;IAE9B,OAAO,EAAE,OAAO,iCAAiC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,IAAI;GACtG;EACF;CACF,CAAC;AACH;;;;;AAMA,eAAsB,sBAAsB,EAC1C,gBACA,UAaA;CACA,IAAI,CAAC,OAAO,aAAa,OAAO,CAAC;CAEjC,MAAM,MAAM,eAAe,IAAI,YAAY;CAE3C,IAAI,CAAC,KAAK,OAAO,CAAC;CAKlB,MAAM,YAAY,IAAI,SAAS,CAAC,CAAC,oBAAoB,IAAI;CACzD,IAAI,CAAC,WAAW,OAAO,CAAC;CAExB,MAAM,QAAQ,MAAM,OAAO,aAAa,SAAS;CACjD,IAAI,CAAC,OAAO,OAAO,CAAC;CACpB,MAAM,QAAQ,MAAM,OAAO,gBAAgB,KAAK;CAChD,IAAI,CAAC,MAAM,WAAW,OAAO,CAAC;CAE9B,OAAO;EACL,kBAAkB,yBAAyB,QAAQ,OAAO,MAAM,eAAe;EAC/E,sBAAsB,6BAA6B,QAAQ,KAAK;EAChE,oBAAoB,2BAA2B,QAAQ,KAAK;EAI5D,GAAI,MAAM,aAAa,EAAE,uBAAuB,wBAAwB,QAAQ,KAAK,EAAE,IAAI,CAAC;CAC9F;AACF"}
1
+ {"version":3,"file":"agent-tools.js","names":[],"sources":["../../../src/integrations/linear/agent-tools.ts"],"sourcesContent":["/**\n * Linear tools exposed to the coding agent.\n *\n * Wired into the agent through the SDK's async `extraTools` provider: on each\n * tool-set resolution we map the session's factory project to its owning org\n * and only expose the Linear tools when that org has a Linear connection.\n * Projects whose org never connected Linear (or when the\n * feature is disabled) see no Linear tools at all — the model is never shown\n * tools it can't use.\n *\n * Tenancy mirrors the Linear API routes: everything is scoped by the org that\n * owns the project, and tokens are refreshed through the integration's shared\n * connection lifecycle.\n */\n\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { LinearIntegration } from './integration.js';\nimport { LinearReauthRequiredError } from './integration.js';\n\nfunction createLinearGetIssueTool(linear: LinearIntegration, orgId: string, workspaceUrlKey: string | null) {\n // The URL pattern lets the agent link a ticket it mentions without fetching it first.\n const linkHint = workspaceUrlKey\n ? ` Issues in this workspace link as https://linear.app/${workspaceUrlKey}/issue/<identifier> (e.g. https://linear.app/${workspaceUrlKey}/issue/ENG-123).`\n : ' To link an issue, use the `url` field of the fetched issue.';\n return createTool({\n id: 'linear_get_issue',\n description: `Fetch a Linear issue's full details — title, description, state, assignee, labels, priority, and discussion comments. Use this whenever you're working on a Linear issue (e.g. ENG-123) to get its complete context.${linkHint}`,\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n }),\n execute: async ({ issue }: { issue: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to fetch issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const detail = await linear.intake.getIssue({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n });\n if (!detail) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return detail;\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to fetch Linear issue: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearCommentTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_create_comment',\n description:\n 'Post a comment on a Linear issue (e.g. to report investigation findings, link a PR, or ask a clarifying question). The comment is posted as the connected Linear integration, so make clear it comes from the agent.',\n inputSchema: z.object({\n issue: z.string().min(1).describe('The Linear issue identifier (e.g. \"ENG-123\") or issue UUID.'),\n body: z.string().min(1).describe(\n 'The comment body, as Linear-flavored markdown. Linear does not render HTML (no <details>, <summary> or <!-- comments -->); for a collapsible section, open it with a \"+++ Section title\" line and close it with a lone \"+++\" line.',\n ),\n }),\n execute: async ({ issue, body }: { issue: string; body: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to post comments.' };\n }\n if (!linear.canPostComments(connection)) {\n return {\n error: 'The Linear connection does not have comment permissions. Reconnect Linear in Settings to grant them.',\n };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const comment = await linear.intake.createComment({\n connection: { type: 'oauth', accessToken },\n issueId: issue.trim(),\n body,\n });\n if (!comment) {\n return { error: `Linear issue \"${issue}\" was not found in this workspace.` };\n }\n return { posted: true, url: comment.url };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to post Linear comment: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearListProjectsTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_list_projects',\n description:\n 'List the Linear projects and teams in the connected workspace, with the source id linear_list_issues needs. Use this to find a project (e.g. from a linear.app/<workspace>/project/<name-slug>-<id> URL, by matching its name; drop the trailing id from the slug) before listing its issues.',\n inputSchema: z.object({\n query: z.string().optional().describe('Case-insensitive text to match against project and team names.'),\n }),\n execute: async ({ query }: { query?: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to list projects.' };\n }\n try {\n // Linear sources are scoped by org alone; no Linear implementation reads userId.\n const sources = await linear.intake.listSources({ orgId, userId: '' });\n // Fold hyphens into spaces so a URL slug like \"agent-browser\" matches \"Agent Browser\".\n const normalize = (text: string) =>\n text\n .toLowerCase()\n .replace(/[\\s-]+/g, ' ')\n .trim();\n const needle = normalize(query ?? '');\n const matches = needle ? sources.filter(source => normalize(source.name).includes(needle)) : sources;\n return {\n projects: matches\n .filter(source => source.type === 'project')\n .map(source => ({ sourceId: source.id, name: source.name })),\n teams: matches\n .filter(source => source.type === 'team')\n .map(source => ({ sourceId: source.id, name: source.name, key: source.metadata?.teamKey ?? null })),\n };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to list Linear projects: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\nfunction createLinearListIssuesTool(linear: LinearIntegration, orgId: string) {\n return createTool({\n id: 'linear_list_issues',\n description:\n 'List the open issues (triage, backlog, todo and in progress; completed and canceled are left out) in one Linear project or team, most recently updated first. Get the source id from linear_list_projects, and read an issue in full with linear_get_issue. Pass nextCursor back as cursor for the next page.',\n inputSchema: z.object({\n source: z.string().min(1).describe('The project or team source id returned by linear_list_projects.'),\n labels: z.array(z.string().trim().min(1)).optional().describe('Only return issues carrying one of these label names.'),\n cursor: z.string().optional().describe('The nextCursor from a previous call, to fetch the next page.'),\n }),\n execute: async ({ source, labels, cursor }: { source: string; labels?: string[]; cursor?: string }) => {\n const connection = await linear.loadConnection(orgId);\n if (!connection) {\n return { error: 'Linear is not connected for this repository. Connect Linear in Settings to list issues.' };\n }\n try {\n const accessToken = await linear.getFreshAccessToken(connection);\n const page = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds: [source.trim()],\n ...(labels?.length ? { labels } : {}),\n ...(cursor ? { cursor } : {}),\n });\n return {\n issues: page.issues.map(issue => ({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state,\n priority: issue.priority,\n assignee: issue.assignee,\n labels: issue.labels,\n updatedAt: issue.updatedAt,\n })),\n nextCursor: page.nextCursor,\n };\n } catch (err) {\n if (err instanceof LinearReauthRequiredError) {\n return { error: err.message };\n }\n return { error: `Failed to list Linear issues: ${err instanceof Error ? err.message : String(err)}` };\n }\n },\n });\n}\n\n/**\n * Async `extraTools` provider: expose Linear tools only when the session's\n * project belongs to an org with an active Linear connection.\n */\nexport async function buildLinearAgentTools({\n requestContext,\n linear,\n}: {\n requestContext: RequestContext;\n /** The integration instance providing the Linear API client. */\n linear: LinearIntegration;\n}): Promise<\n Record<\n string,\n | ReturnType<typeof createLinearGetIssueTool>\n | ReturnType<typeof createLinearCommentTool>\n | ReturnType<typeof createLinearListProjectsTool>\n | ReturnType<typeof createLinearListIssuesTool>\n >\n> {\n if (!linear.authEnabled) return {};\n\n const ctx = requestContext.get('controller') as\n AgentControllerRequestContext<{ factoryProjectId?: string }> | undefined;\n if (!ctx) return {};\n\n // Prefer the Factory recorded on the session. Factory sessions run under the\n // Factory as their resource, so the resource is the fallback; a legacy\n // session whose resource is its own id resolves to no project.\n const projectId = ctx.getState().factoryProjectId ?? ctx.resourceId;\n if (!projectId) return {};\n\n const orgId = await linear.resolveOrgId(projectId);\n if (!orgId) return {};\n const check = await linear.checkConnection(orgId);\n if (!check.connected) return {};\n\n return {\n linear_get_issue: createLinearGetIssueTool(linear, orgId, check.workspaceUrlKey),\n linear_list_projects: createLinearListProjectsTool(linear, orgId),\n linear_list_issues: createLinearListIssuesTool(linear, orgId),\n // Only offered when the granted OAuth scope allows posting comments —\n // connections made before `comments:create` was requested are read-only\n // until the org reconnects Linear.\n ...(check.canComment ? { linear_create_comment: createLinearCommentTool(linear, orgId) } : {}),\n };\n}\n"],"mappings":";;;;AAuBA,SAAS,yBAAyB,QAA2B,OAAe,iBAAgC;CAE1G,MAAM,WAAW,kBACb,wDAAwD,gBAAgB,+CAA+C,gBAAgB,oBACvI;CACJ,OAAO,WAAW;EAChB,IAAI;EACJ,aAAa,uNAAuN;EACpO,aAAa,EAAE,OAAO,EACpB,OAAO,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,+DAA6D,EACjG,CAAC;EACD,SAAS,OAAO,EAAE,YAA+B;GAC/C,MAAM,aAAa,MAAM,OAAO,eAAe,K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,gBAAgB,CAAA;CAAE,EAC5C,OAAO,EAAE,kBAAkB,GAC1B,CAAC,CAAC,KAAK,EAAE,kBAAkB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC,GAAG,SAAS,CAU/D"}
@@ -55,7 +55,7 @@ var LinearRules = class {
55
55
  externalId: `linear:${issue.identifier}`
56
56
  }))
57
57
  });
58
- const items = await this.options.storage.list({
58
+ const items = await this.options.storage.listShared({
59
59
  orgId: input.orgId,
60
60
  factoryProjectId: input.factoryProjectId
61
61
  });
@@ -64,7 +64,7 @@ var LinearRules = class {
64
64
  for (const issue of input.issues) {
65
65
  const byIssueId = items.filter((item) => item.workItem.metadata?.linearIssueId === issue.id);
66
66
  const relatedItem = itemsBySourceKey.get(`linear:${issue.identifier}`) ?? byIssueId.find((item) => !isTerminalWorkItem(this.#boards(input), item)) ?? byIssueId[0];
67
- statuses.push(await this.#ingestIssue(input, issue, relatedItem));
67
+ statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));
68
68
  }
69
69
  if (statuses.some((status) => status === "committed")) return {
70
70
  status: "committed",
@@ -1 +1 @@
1
- {"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/linear/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 isTerminalWorkItem,\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 { FactoryLinearRuleContext, 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 { LinearEventRules } 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 LinearIssueIngress {\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 Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team). */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\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 linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Linear sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryLinearRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\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 LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\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: LinearRulesIngress): 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: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` })),\n });\n const items = await this.options.storage.list({ 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 Linear issue per project; other projects may file their own.\n // The identifier finds the card filed under it; after Linear renamed the\n // identifier, the stable issue id finds it, preferring a live card over\n // finished ones, as the issue detail route does.\n const byIssueId = items.filter(item => item.workItem.metadata?.linearIssueId === issue.id);\n const relatedItem =\n itemsBySourceKey.get(`linear:${issue.identifier}`) ??\n byIssueId.find(item => !isTerminalWorkItem(this.#boards(input), item)) ??\n byIssueId[0];\n statuses.push(await this.#ingestIssue(input, issue, 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: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues 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 ? 'issueClosed' : 'issueObserved';\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\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.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\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 Linear 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: 'linear.issueObserved' },\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 Linear 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 attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;AAuBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QA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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 isTerminalWorkItem,\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 { FactoryLinearRuleContext, 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 { LinearEventRules } 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 LinearIssueIngress {\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 Linear user who created the issue, when available. */\n creator: string | null;\n team: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Linear source the issue was read from (project or team). */\n sourceId?: string | null;\n projectId?: string | null;\n}\n\nexport interface LinearRulesOptions {\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 linearRules: LinearEventRules;\n}\n\nexport interface LinearRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: LinearIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Linear sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryLinearRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\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 LinearRules {\n constructor(private readonly options: LinearRulesOptions) {}\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: LinearRulesIngress): 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: 'linear', type: 'issue', externalId: `linear:${issue.identifier}` })),\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 Linear issue per project; other projects may file their own.\n // The identifier finds the card filed under it; after Linear renamed the\n // identifier, the stable issue id finds it, preferring a live card over\n // finished ones, as the issue detail route does.\n const byIssueId = items.filter(item => item.workItem.metadata?.linearIssueId === issue.id);\n const relatedItem =\n itemsBySourceKey.get(`linear:${issue.identifier}`) ??\n byIssueId.find(item => !isTerminalWorkItem(this.#boards(input), item)) ??\n byIssueId[0];\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: LinearRulesIngress,\n issue: LinearIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `linear:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues 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 ? 'issueClosed' : 'issueObserved';\n const context: FactoryLinearRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'linear', id: ingressId },\n cause: `linear.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'linear-issue',\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.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.linearRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'linear'),\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 Linear 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: 'linear.issueObserved' },\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 Linear 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 attachLinearRules(\n linear: { readonly rules: LinearEventRules },\n context: IntegrationContext,\n): ((input: LinearRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new LinearRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n linearRules: linear.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;AAuBA,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;;;;;AA4ChC,SAAgB,cAAc,SAAkG;CAC9H,IAAI,QAAQ,UAAU,eACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,cAAc,UAAU;CAAE;CAEjG,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;AAEA,IAAa,cAAb,MAAyB;CACM;CAA7B,YAAY,SAA8C;EAA7B,KAAA,UAAA;CAA8B;;CAG3D,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,OAAO,OAAiF;EAE5F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB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,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;AAEA,SAAgB,kBACd,QACA,SAC+D;CAC/D,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,YAAY;EAC5B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,aAAa,OAAO;CACtB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
@@ -4,7 +4,7 @@ import type { WorkerDeps } from '@mastra/core/worker';
4
4
  import type { IntegrationStorageHandle } from '../../../storage/domains/integrations/base.js';
5
5
  import type { GithubIssueReconciler } from '../../github/issue-reconciler.js';
6
6
  import type { GithubReconcileRepositorySource } from '../../github/reconcile-worker.js';
7
- import type { GithubPullRequestReconciler } from '../../github/rules.js';
7
+ import type { GithubPullRequestDiscovery, GithubPullRequestReconciler } from '../../github/rules.js';
8
8
  import { dispatchGithubWebhook } from '../../github/webhook.js';
9
9
  import type { GithubWebhookDispatchIntegration, ParsedGithubWebhook } from '../../github/webhook.js';
10
10
  import type { PlatformApiClient } from '../api-client.js';
@@ -35,6 +35,7 @@ export interface PlatformGithubEventWorkerConfig {
35
35
  ingestFactoryEvent?: (event: ParsedGithubWebhook) => Promise<unknown>;
36
36
  reconcileFactoryState?: GithubPullRequestReconciler;
37
37
  reconcileIssuesFactoryState?: GithubIssueReconciler;
38
+ discoverPullRequests?: GithubPullRequestDiscovery;
38
39
  /** When false the worker skips event tailing and only runs enabled reconciliation sweeps. */
39
40
  pollEventsEnabled?: boolean;
40
41
  intervalMs?: number;
@@ -42,6 +43,8 @@ export interface PlatformGithubEventWorkerConfig {
42
43
  reconcileIntervalMs?: number;
43
44
  pullRequestReconcileIntervalMs?: number;
44
45
  issueReconcileIntervalMs?: number;
46
+ /** Defaults to five minutes, or the pull request interval when that is shorter. */
47
+ pullRequestDiscoveryIntervalMs?: number;
45
48
  now?: () => number;
46
49
  dispatch?: typeof dispatchGithubWebhook;
47
50
  }
@@ -1 +1 @@
1
- {"version":3,"file":"event-worker.d.ts","sourceRoot":"","sources":["../../../../src/integrations/platform/github/event-worker.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACnD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAEtD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,+CAA+C,CAAC;AAE9F,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,kCAAkC,CAAC;AAC9E,OAAO,KAAK,EAAE,+BAA+B,EAAE,MAAM,kCAAkC,CAAC;AACxF,OAAO,KAAK,EAAE,2BAA2B,EAAuB,MAAM,uBAAuB,CAAC;AAE9F,OAAO,EAAE,qBAAqB,EAA6C,MAAM,yBAAyB,CAAC;AAC3G,OAAO,KAAK,EACV,gCAAgC,EAEhC,mBAAmB,EACpB,MAAM,yBAAyB,CAAC;AACjC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAmC1D,KAAK,WAAW,GAAG;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,cAAc,EAAE,MAAM,CAAA;CAAE,CAAC;AACzE,KAAK,iCAAiC,GAAG;IACvC,OAAO,EAAE,CAAC,CAAC;IACX,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CAAC;CAC3C,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG,wBAAwB,CAC/D,MAAM,CAAC,MAAM,EAA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AC/C,OAAO,EAAE,0BAA0B,CAAC;IACpC;;;;;;OAMG;IACH,aAAa,EAAE,+BAA+B,CAAC;IAC/C,kBAAkB,CAAC,EAAE,CAAC,KAAK,EAAE,mBAAmB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACtE,qBAAqB,CAAC,EAAE,2BAA2B,CAAC;IACpD,2BAA2B,CAAC,EAAE,qBAAqB,CAAC;IACpD,oBAAoB,CAAC,EAAE,0BAA0B,CAAC;IAClD,6FAA6F;IAC7F,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,4CAA4C;IAC5C,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,8BAA8B,CAAC,EAAE,MAAM,CAAC;IACxC,wBAAwB,CAAC,EAAE,MAAM,CAAC;IAClC,mFAAmF;IACnF,8BAA8B,CAAC,EAAE,MAAM,CAAC;IACxC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,OAAO,qBAAqB,CAAC;CACzC;AAED,qBAAa,yBAA0B,SAAQ,YAAY;;IACzD,QAAQ,CAAC,IAAI,4BAA4B;IAkCzC,YAAY,MAAM,EAAE,+BAA+B,EA0ClD;IAEK,IAAI,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAG1C;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAY3B;IAEK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAW1B;IAED,IAAI,SAAS,IAAI,OAAO,CAEvB;CAsYF"}
@@ -1,3 +1,4 @@
1
+ import "../../github/reconcile-worker.js";
1
2
  import { listPullRequestSubscriptionsForWebhook, retirePullRequestSubscription } from "../../github/subscriptions.js";
2
3
  import { dispatchGithubWebhook, isFactoryAppSender, resolveAuthorizedBots } from "../../github/webhook.js";
3
4
  import { PlatformApiError } from "../api-client.js";
@@ -42,9 +43,11 @@ var PlatformGithubEventWorker = class extends MastraWorker {
42
43
  #ingestFactoryEvent;
43
44
  #reconcileFactoryState;
44
45
  #reconcileIssuesFactoryState;
46
+ #discoverPullRequests;
45
47
  #pollEventsEnabled;
46
48
  #pullRequestReconcileIntervalMs;
47
49
  #issueReconcileIntervalMs;
50
+ #pullRequestDiscoveryIntervalMs;
48
51
  #intervalMs;
49
52
  #now;
50
53
  #dispatch;
@@ -60,6 +63,7 @@ var PlatformGithubEventWorker = class extends MastraWorker {
60
63
  #startedAt = 0;
61
64
  #lastPullRequestReconcileAt = Number.NEGATIVE_INFINITY;
62
65
  #lastIssueReconcileAt = Number.NEGATIVE_INFINITY;
66
+ #lastPullRequestDiscoveryAt = Number.NEGATIVE_INFINITY;
63
67
  #settings = {
64
68
  version: 1,
65
69
  repositories: {}
@@ -73,15 +77,18 @@ var PlatformGithubEventWorker = class extends MastraWorker {
73
77
  this.#ingestFactoryEvent = config.ingestFactoryEvent;
74
78
  this.#reconcileFactoryState = config.reconcileFactoryState;
75
79
  this.#reconcileIssuesFactoryState = config.reconcileIssuesFactoryState;
80
+ this.#discoverPullRequests = config.discoverPullRequests;
76
81
  this.#pollEventsEnabled = config.pollEventsEnabled ?? true;
77
82
  const legacyReconcileIntervalMs = config.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS;
78
83
  this.#pullRequestReconcileIntervalMs = config.pullRequestReconcileIntervalMs ?? legacyReconcileIntervalMs;
79
84
  this.#issueReconcileIntervalMs = config.issueReconcileIntervalMs ?? legacyReconcileIntervalMs;
85
+ this.#pullRequestDiscoveryIntervalMs = config.pullRequestDiscoveryIntervalMs ?? Math.min(3e5, this.#pullRequestReconcileIntervalMs);
80
86
  this.#intervalMs = config.intervalMs ?? DEFAULT_POLL_INTERVAL_MS;
81
87
  if (!Number.isFinite(this.#intervalMs) || this.#intervalMs <= 0) throw new Error("Platform GitHub event polling interval must be a positive number.");
82
88
  if (!Number.isFinite(this.#pullRequestReconcileIntervalMs) || this.#pullRequestReconcileIntervalMs <= 0) throw new Error("Platform GitHub pull request reconcile interval must be a positive number.");
83
89
  if (!Number.isFinite(this.#issueReconcileIntervalMs) || this.#issueReconcileIntervalMs <= 0) throw new Error("Platform GitHub issue reconcile interval must be a positive number.");
84
- this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, Math.min(this.#intervalMs, this.#pullRequestReconcileIntervalMs, this.#issueReconcileIntervalMs) * 3);
90
+ if (!Number.isFinite(this.#pullRequestDiscoveryIntervalMs) || this.#pullRequestDiscoveryIntervalMs <= 0) throw new Error("Platform GitHub pull request discovery interval must be a positive number.");
91
+ this.#leaseTtlMs = Math.max(MIN_LEASE_TTL_MS, Math.min(this.#intervalMs, this.#pullRequestReconcileIntervalMs, this.#issueReconcileIntervalMs, this.#pullRequestDiscoveryIntervalMs) * 3);
85
92
  this.#now = config.now ?? Date.now;
86
93
  this.#dispatch = config.dispatch ?? dispatchGithubWebhook;
87
94
  this.#sourceControl = config.sourceControl;
@@ -193,7 +200,11 @@ var PlatformGithubEventWorker = class extends MastraWorker {
193
200
  return retryInMs;
194
201
  }
195
202
  #reconcileCadence() {
196
- const cadences = [this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : void 0, this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : void 0].filter((interval) => interval !== void 0);
203
+ const cadences = [
204
+ this.#reconcileFactoryState ? this.#pullRequestReconcileIntervalMs : void 0,
205
+ this.#reconcileIssuesFactoryState ? this.#issueReconcileIntervalMs : void 0,
206
+ this.#discoverPullRequests ? this.#pullRequestDiscoveryIntervalMs : void 0
207
+ ].filter((interval) => interval !== void 0);
197
208
  return cadences.length > 0 ? Math.min(...cadences) : this.#intervalMs;
198
209
  }
199
210
  async #maybeReconcile(repositories) {
@@ -201,9 +212,11 @@ var PlatformGithubEventWorker = class extends MastraWorker {
201
212
  const now = this.#now();
202
213
  const reconcilePullRequests = Boolean(this.#reconcileFactoryState && now - this.#lastPullRequestReconcileAt >= this.#pullRequestReconcileIntervalMs);
203
214
  const reconcileIssues = Boolean(this.#reconcileIssuesFactoryState && now - this.#lastIssueReconcileAt >= this.#issueReconcileIntervalMs);
204
- if (!reconcilePullRequests && !reconcileIssues) return;
215
+ const discoverPullRequests = Boolean(this.#discoverPullRequests && now - this.#lastPullRequestDiscoveryAt >= this.#pullRequestDiscoveryIntervalMs);
216
+ if (!reconcilePullRequests && !reconcileIssues && !discoverPullRequests) return;
205
217
  if (reconcilePullRequests) this.#lastPullRequestReconcileAt = now;
206
218
  if (reconcileIssues) this.#lastIssueReconcileAt = now;
219
+ if (discoverPullRequests) this.#lastPullRequestDiscoveryAt = now;
207
220
  const targets = repositories.flatMap((repository) => repository.fullName ? [{
208
221
  id: repository.id,
209
222
  fullName: repository.fullName,
@@ -236,6 +249,29 @@ var PlatformGithubEventWorker = class extends MastraWorker {
236
249
  });
237
250
  }
238
251
  }
252
+ if (discoverPullRequests && this.#discoverPullRequests && this.#hasLease) {
253
+ const startedAt = Date.now();
254
+ try {
255
+ const { errors, ...counts } = await this.#discoverPullRequests(targets);
256
+ const context = {
257
+ ...counts,
258
+ candidateRepositories: targets.length,
259
+ durationMs: Date.now() - startedAt
260
+ };
261
+ if (counts.failed > 0) this.deps?.logger.warn("Platform GitHub pull request discovery completed with failures", {
262
+ ...context,
263
+ errors
264
+ });
265
+ else if (counts.created > 0 || counts.repaired > 0) this.deps?.logger.info("Platform GitHub pull request discovery replayed missed opens", context);
266
+ else this.deps?.logger.debug("Platform GitHub pull request discovery completed", context);
267
+ } catch (error) {
268
+ this.deps?.logger.error("Platform GitHub pull request discovery failed", {
269
+ repositories: targets.length,
270
+ durationMs: Date.now() - startedAt,
271
+ error: error instanceof Error ? error.message : String(error)
272
+ });
273
+ }
274
+ }
239
275
  if (reconcileIssues && this.#reconcileIssuesFactoryState && this.#hasLease) {
240
276
  const startedAt = Date.now();
241
277
  try {