@mastra/factory 0.29.0-alpha.0 → 0.29.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/README.md +20 -4
  2. package/dist/board-changes.d.ts +16 -0
  3. package/dist/board-changes.d.ts.map +1 -0
  4. package/dist/board-changes.js +40 -0
  5. package/dist/board-changes.js.map +1 -0
  6. package/dist/boards/index.js +2 -1
  7. package/dist/boards/semantics.d.ts +1 -3
  8. package/dist/boards/semantics.d.ts.map +1 -1
  9. package/dist/boards/semantics.js +1 -5
  10. package/dist/boards/semantics.js.map +1 -1
  11. package/dist/factory.d.ts +4 -0
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +51 -3
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/base.d.ts +9 -0
  16. package/dist/integrations/base.d.ts.map +1 -1
  17. package/dist/integrations/github/pull-request-source.js +2 -1
  18. package/dist/integrations/github/pull-request-source.js.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +1 -1
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/rules.d.ts +5 -2
  22. package/dist/integrations/github/rules.d.ts.map +1 -1
  23. package/dist/integrations/github/rules.js +16 -13
  24. package/dist/integrations/github/rules.js.map +1 -1
  25. package/dist/integrations/github/sandbox.js +2 -2
  26. package/dist/integrations/github/sandbox.js.map +1 -1
  27. package/dist/integrations/gitlab/default-rules.js +2 -1
  28. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  29. package/dist/integrations/gitlab/discovery.d.ts +16 -0
  30. package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
  31. package/dist/integrations/gitlab/discovery.js +107 -0
  32. package/dist/integrations/gitlab/discovery.js.map +1 -0
  33. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/integration.js +1 -2
  35. package/dist/integrations/gitlab/integration.js.map +1 -1
  36. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/issue-reconciler.js +1 -0
  38. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  39. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  40. package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
  41. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  42. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/reconciler.js +4 -2
  44. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  45. package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
  46. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  47. package/dist/integrations/gitlab/reconciliation-config.js +2 -8
  48. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  49. package/dist/integrations/gitlab/routes.d.ts +17 -0
  50. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  51. package/dist/integrations/gitlab/routes.js +28 -22
  52. package/dist/integrations/gitlab/routes.js.map +1 -1
  53. package/dist/integrations/gitlab/rules.d.ts +10 -4
  54. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  55. package/dist/integrations/gitlab/rules.js +32 -8
  56. package/dist/integrations/gitlab/rules.js.map +1 -1
  57. package/dist/integrations/incidentio/integration.d.ts +2 -1
  58. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  59. package/dist/integrations/incidentio/integration.js +7 -7
  60. package/dist/integrations/incidentio/integration.js.map +1 -1
  61. package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
  62. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  63. package/dist/integrations/incidentio/issue-reconciler.js +36 -1
  64. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  65. package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
  66. package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
  67. package/dist/integrations/incidentio/reconciliation-config.js +2 -5
  68. package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
  69. package/dist/integrations/incidentio/routes.d.ts +24 -8
  70. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  71. package/dist/integrations/incidentio/routes.js +33 -35
  72. package/dist/integrations/incidentio/routes.js.map +1 -1
  73. package/dist/integrations/incidentio/rules.d.ts +0 -4
  74. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  75. package/dist/integrations/incidentio/rules.js +17 -14
  76. package/dist/integrations/incidentio/rules.js.map +1 -1
  77. package/dist/integrations/intake-discovery.d.ts +44 -0
  78. package/dist/integrations/intake-discovery.d.ts.map +1 -0
  79. package/dist/integrations/intake-discovery.js +60 -0
  80. package/dist/integrations/intake-discovery.js.map +1 -0
  81. package/dist/integrations/issue-reconcile-worker.js +1 -1
  82. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  83. package/dist/integrations/issue-reconciler.d.ts +7 -0
  84. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  85. package/dist/integrations/issue-reconciler.js +47 -12
  86. package/dist/integrations/issue-reconciler.js.map +1 -1
  87. package/dist/integrations/jira/integration.d.ts +3 -2
  88. package/dist/integrations/jira/integration.d.ts.map +1 -1
  89. package/dist/integrations/jira/integration.js +5 -7
  90. package/dist/integrations/jira/integration.js.map +1 -1
  91. package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
  92. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/jira/issue-reconciler.js +34 -1
  94. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
  96. package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
  97. package/dist/integrations/jira/reconciliation-config.js +2 -5
  98. package/dist/integrations/jira/reconciliation-config.js.map +1 -1
  99. package/dist/integrations/jira/routes.d.ts +0 -7
  100. package/dist/integrations/jira/routes.d.ts.map +1 -1
  101. package/dist/integrations/jira/routes.js +2 -12
  102. package/dist/integrations/jira/routes.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts +0 -4
  104. package/dist/integrations/jira/rules.d.ts.map +1 -1
  105. package/dist/integrations/jira/rules.js +3 -13
  106. package/dist/integrations/jira/rules.js.map +1 -1
  107. package/dist/integrations/kept-cards.d.ts +49 -0
  108. package/dist/integrations/kept-cards.d.ts.map +1 -0
  109. package/dist/integrations/kept-cards.js +97 -0
  110. package/dist/integrations/kept-cards.js.map +1 -0
  111. package/dist/integrations/linear/intake-discovery.d.ts +34 -0
  112. package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
  113. package/dist/integrations/linear/intake-discovery.js +112 -0
  114. package/dist/integrations/linear/intake-discovery.js.map +1 -0
  115. package/dist/integrations/linear/integration.d.ts.map +1 -1
  116. package/dist/integrations/linear/integration.js +1 -4
  117. package/dist/integrations/linear/integration.js.map +1 -1
  118. package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
  119. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  120. package/dist/integrations/linear/issue-reconciler.js +24 -20
  121. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  122. package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
  123. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  124. package/dist/integrations/linear/reconciliation-config.js +2 -8
  125. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  126. package/dist/integrations/linear/routes.d.ts +0 -2
  127. package/dist/integrations/linear/routes.d.ts.map +1 -1
  128. package/dist/integrations/linear/routes.js +3 -9
  129. package/dist/integrations/linear/routes.js.map +1 -1
  130. package/dist/integrations/platform/api-client.d.ts +2 -0
  131. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  132. package/dist/integrations/platform/api-client.js +6 -1
  133. package/dist/integrations/platform/api-client.js.map +1 -1
  134. package/dist/integrations/platform/connect/routes.js +4 -1
  135. package/dist/integrations/platform/connect/routes.js.map +1 -1
  136. package/dist/integrations/platform/github/event-worker.d.ts +12 -0
  137. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  138. package/dist/integrations/platform/github/event-worker.js +56 -5
  139. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  140. package/dist/integrations/platform/github/integration.d.ts +1 -0
  141. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  142. package/dist/integrations/platform/github/integration.js +8 -3
  143. package/dist/integrations/platform/github/integration.js.map +1 -1
  144. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  145. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  146. package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
  147. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  148. package/dist/integrations/platform/incidentio/integration.js +7 -7
  149. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  150. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  151. package/dist/integrations/platform/jira/integration.js +4 -7
  152. package/dist/integrations/platform/jira/integration.js.map +1 -1
  153. package/dist/integrations/platform/jira/routes.d.ts +0 -7
  154. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  155. package/dist/integrations/platform/jira/routes.js +2 -12
  156. package/dist/integrations/platform/jira/routes.js.map +1 -1
  157. package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
  158. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  159. package/dist/integrations/platform/linear/event-worker.js +1 -1
  160. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  161. package/dist/integrations/platform/linear/integration.d.ts +1 -0
  162. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  163. package/dist/integrations/platform/linear/integration.js +7 -7
  164. package/dist/integrations/platform/linear/integration.js.map +1 -1
  165. package/dist/integrations/platform/vanta/integration.d.ts +7 -2
  166. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  167. package/dist/integrations/platform/vanta/integration.js +22 -6
  168. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  169. package/dist/integrations/reconciliation-config.d.ts +0 -1
  170. package/dist/integrations/reconciliation-config.d.ts.map +1 -1
  171. package/dist/integrations/reconciliation-config.js +1 -8
  172. package/dist/integrations/reconciliation-config.js.map +1 -1
  173. package/dist/integrations/slack/channel-reply-processor.js +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  175. package/dist/integrations/startup-summary.d.ts +8 -0
  176. package/dist/integrations/startup-summary.d.ts.map +1 -0
  177. package/dist/integrations/startup-summary.js +36 -0
  178. package/dist/integrations/startup-summary.js.map +1 -0
  179. package/dist/integrations/vanta/sync.d.ts +9 -5
  180. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  181. package/dist/integrations/vanta/sync.js +16 -8
  182. package/dist/integrations/vanta/sync.js.map +1 -1
  183. package/dist/linked-repositories-changed.d.ts +14 -0
  184. package/dist/linked-repositories-changed.d.ts.map +1 -0
  185. package/dist/linked-repositories-changed.js +48 -0
  186. package/dist/linked-repositories-changed.js.map +1 -0
  187. package/dist/routes/contracts.d.ts +117 -0
  188. package/dist/routes/contracts.d.ts.map +1 -1
  189. package/dist/routes/contracts.js +44 -1
  190. package/dist/routes/contracts.js.map +1 -1
  191. package/dist/routes/run-queue.d.ts +17 -0
  192. package/dist/routes/run-queue.d.ts.map +1 -0
  193. package/dist/routes/run-queue.js +69 -0
  194. package/dist/routes/run-queue.js.map +1 -0
  195. package/dist/routes/surface.d.ts +8 -0
  196. package/dist/routes/surface.d.ts.map +1 -1
  197. package/dist/routes/surface.js +4 -2
  198. package/dist/routes/surface.js.map +1 -1
  199. package/dist/routes/work-item-selection.d.ts +4 -1
  200. package/dist/routes/work-item-selection.d.ts.map +1 -1
  201. package/dist/routes/work-item-selection.js +7 -2
  202. package/dist/routes/work-item-selection.js.map +1 -1
  203. package/dist/routes/work-items.d.ts +5 -0
  204. package/dist/routes/work-items.d.ts.map +1 -1
  205. package/dist/routes/work-items.js +17 -0
  206. package/dist/routes/work-items.js.map +1 -1
  207. package/dist/rules/dispatcher.d.ts +13 -1
  208. package/dist/rules/dispatcher.d.ts.map +1 -1
  209. package/dist/rules/dispatcher.js +9 -2
  210. package/dist/rules/dispatcher.js.map +1 -1
  211. package/dist/rules/review-source-tool.js +2 -1
  212. package/dist/rules/review-source-tool.js.map +1 -1
  213. package/dist/storage/domains/projects/base.d.ts +2 -0
  214. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  215. package/dist/storage/domains/projects/base.js +13 -1
  216. package/dist/storage/domains/projects/base.js.map +1 -1
  217. package/dist/storage/domains/source-control/base.d.ts +32 -0
  218. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  219. package/dist/storage/domains/source-control/base.js +54 -4
  220. package/dist/storage/domains/source-control/base.js.map +1 -1
  221. package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
  222. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  223. package/dist/storage/domains/source-control/inmemory.js +17 -0
  224. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  225. package/dist/storage/domains/work-items/base.d.ts +1 -0
  226. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  227. package/dist/storage/domains/work-items/base.js +9 -0
  228. package/dist/storage/domains/work-items/base.js.map +1 -1
  229. package/dist/timing.d.ts +8 -1
  230. package/dist/timing.d.ts.map +1 -1
  231. package/dist/timing.js +10 -2
  232. package/dist/timing.js.map +1 -1
  233. package/dist/work-items/source-external-id.d.ts +4 -0
  234. package/dist/work-items/source-external-id.d.ts.map +1 -0
  235. package/dist/work-items/source-external-id.js +9 -0
  236. package/dist/work-items/source-external-id.js.map +1 -0
  237. package/package.json +8 -8
package/README.md CHANGED
@@ -676,6 +676,22 @@ const releaseBoard = defineBoard({
676
676
 
677
677
  **Migration:** `defineBoard()` still accepts the old field names and maps them to the new ones straight away: `title` → `name`, `role` → `runner.context`, `next` → `nextPhases`. It logs one warning per board that still uses them. Setting both `title` and `name`, or `role` and `runner.context`, to different values is rejected. `outcomes`, `onEnter` and `onExit` are ignored (see [Board lifecycle rules](#board-lifecycle-rules)); outcome targets are added to `nextPhases`. The board `defineBoard()` returns still has the old names as read-only copies — `board.title` and `phase.title` equal `name`, a working phase's `role` equals `runner.context`, and `phase.next` is set when the phase declared `next` — so code that reads them, or passes a defined board's phases to `defineBoard()` again, keeps working. They are deprecated; read `name`, `runner.context` and `nextPhases` instead. The board catalog (`GET /web/factory/projects/:id/boards`) still sends `title` and `role` beside the new fields for older clients. Card session keys do not change: a phase's context is its old role.
678
678
 
679
+ ### Run cap and the run queue
680
+
681
+ Each server process runs at most 10 automated runs at once. A run is a skill or prompt started on a card (`invokeSkill`), a message sent to a card's session (`sendMessage`), or pull request activity delivered to one (`signalActivity`). Runs past the cap wait, oldest first, until a slot frees. Raise or lower the cap with `dispatcher.maxInFlight`, or `MASTRACODE_DISPATCH_MAX_IN_FLIGHT` in the Mastra Code web server:
682
+
683
+ ```ts
684
+ const factory = new MastraFactory({ storage, dispatcher: { maxInFlight: 25 } });
685
+ ```
686
+
687
+ The cap counts per process, not per deployment: three replicas with the default run up to 30 at once.
688
+
689
+ The board shows how many automated runs are waiting, and opens a list of them, oldest first. A waiting card reads `Queued (#3)`. Manual starts take the same slots and are claimed ahead of these runs, but are not listed. `GET /web/factory/projects/:id/run-queue` returns the same data:
690
+
691
+ - `slots` — this server's `inUse` and `cap`, or `null` when it runs no dispatcher. Other replicas keep their own.
692
+ - `running` and `claimed` — the project's automated runs a server holds a slot for, on any replica. A manual start holding a slot counts in `slots.inUse` but not here, so `running` can be lower than `inUse`.
693
+ - `queuedCount` and `queued` — every automated run waiting for a slot, and the oldest 50 with their `position`, card, phase and the skill they will run. A retry still backing off is not waiting yet.
694
+
679
695
  ### The `factory-work-item` signal
680
696
 
681
697
  Every session bound to a card gets a `<factory-work-item>` state signal describing it, re-rendered only when the card, its sources or the binding change. It carries the card's key, title, URL, board and phase, next phases, labels, author and whether they're trusted, and the session's branch; its sources (issue and each pull or merge request, with state, head commit, a head branch that passes Factory's branch-name check, and the tool to fetch details); and Factory's state: whether the plan was approved, self-review rounds used, the last self-review and PR review verdicts with the commits they covered and findings, and the card's open change request. The session that reviews a pull request also gets the procedure to follow, the checkout steps and the pull request head to review. The source description is included, inside an `<untrusted-source-description>` block when an outside author wrote it. Comment threads are not included.
@@ -849,10 +865,10 @@ Custom phase signals and persisted tool-result ingestion use the item's installe
849
865
 
850
866
  ### Choose which sources feed a project
851
867
 
852
- Intake bindings are explicit. A Linear project, Jira project, GitLab project, incident.io source or GitHub repository is only offered as a candidate feed once it is bound to a Factory project; nothing is materialized just by opening a board. A binding decides only which project a source feeds. Where its cards land is up to the project's [intake routes](#intake-routes): a new card is filed in the default board's first phase, and the first route that matches it places it. To send one repository, Linear team or Jira project to its own board, add a route with a `source.repository` condition. A route sees where an item lives, not which binding brought it in: two Linear projects in the same team share the team key, so a route can't send them to different boards.
868
+ Intake bindings are explicit. A Linear project, Jira project, GitLab project, incident.io source or GitHub repository only feeds a Factory project once it is bound to it. The server files its items as cards; the board and search read only those cards and never ask a provider for its list, so nothing is filed just by opening a board. A binding decides only which project a source feeds. Where its cards land is up to the project's [intake routes](#intake-routes): a new card is filed in the default board's first phase, and the first route that matches it places it. To send one repository, Linear team or Jira project to its own board, add a route with a `source.repository` condition. A route sees where an item lives, not which binding brought it in: two Linear projects in the same team share the team key, so a route can't send them to different boards.
853
869
 
854
870
  - **Linear:** each project binding feeds one Factory project.
855
- - **Jira:** One Jira project can feed several Factory projects: each binding takes either all issues or only issues carrying its labels (Settings › Intake › Jira routing, or `labels` on `PUT /web/intake/bindings`). Each label belongs to one binding per Jira project, and only one binding per project can take all issues. Label bindings win over the all-issues binding; an issue carrying labels of two label bindings goes to the binding created first. The split happens in the JQL each Factory sends, so every issue is filed in exactly one Factory. Labels only decide placement when an issue is first filed: relabelling an issue, or editing a binding's labels, does not move existing cards. Remove one Factory's binding with `DELETE /web/intake/bindings?integrationId=jira&sourceId=…&factoryProjectId=…`. The create-Factory flow can select a Jira project and binds it to the new Factory. The browser checks routed projects for new issues every 30 seconds and on window focus; issues observed for a routed project materialize automatically as work items (mirroring Linear), and closed issues transition their linked card to done or canceled. Both `JiraIntegration` and `PlatformJiraIntegration` reconcile imported cards every five minutes by default so status and metadata continue to refresh without an open browser, and both accept a `rules` option to replace or disable the `issueObserved` / `issueClosed` defaults. Agents on Jira-sourced runs get `jira_get_issue` and `jira_create_comment`. Set `MASTRACODE_JIRA_RECONCILE_ENABLED=false` to disable reconciliation or `MASTRACODE_JIRA_RECONCILE_INTERVAL_MS` to a positive millisecond interval to change its cadence.
871
+ - **Jira:** One Jira project can feed several Factory projects: each binding takes either all issues or only issues carrying its labels (Settings › Intake › Jira routing, or `labels` on `PUT /web/intake/bindings`). Each label belongs to one binding per Jira project, and only one binding per project can take all issues. Label bindings win over the all-issues binding; an issue carrying labels of two label bindings goes to the binding created first. The split happens in the JQL each Factory sends, so every issue is filed in exactly one Factory. Labels only decide placement when an issue is first filed: relabelling an issue, or editing a binding's labels, does not move existing cards. Remove one Factory's binding with `DELETE /web/intake/bindings?integrationId=jira&sourceId=…&factoryProjectId=…`. The create-Factory flow can select a Jira project and binds it to the new Factory. Both `JiraIntegration` and `PlatformJiraIntegration` run a reconciliation sweep every five minutes by default, with or without an open browser: it reads the 150 most recently updated issues of each routed Jira project (five pages, counted per project so a busy one cannot starve the others) and files a work item for each new one, refreshes the status and metadata of imported cards, and transitions the linked card of a closed issue to done or canceled. Both accept a `rules` option to replace or disable the `issueObserved` / `issueClosed` defaults. Agents on Jira-sourced runs get `jira_get_issue` and `jira_create_comment`. Set `MASTRACODE_JIRA_RECONCILE_INTERVAL_MS` to a positive millisecond interval to change its cadence.
856
872
  - **GitHub:** every repository linked to the project feeds it. To send one repository's issues and pull requests to another board, add an intake route with a `source.repository` condition; for labelled issues, an `item.labels` condition. A label change on an issue updates its card's labels and never moves the card.
857
873
 
858
874
  Label routes (`GET`/`PUT /web/intake/label-routes`) and a binding's `board` were removed: use an intake route with any condition on the work item instead, such as `item.labels contains release` or `source.repository equals acme/app`. The label-route endpoints answer `410` with `label_routes_removed`, and a `board` an older client still sends on `PUT /web/intake/bindings` is ignored. Their stored rows stay, unread.
@@ -1165,7 +1181,7 @@ With no constructor options, the integration reads `GITLAB_ACCESS_TOKEN`, `GITLA
1165
1181
 
1166
1182
  `GITLAB_BASE_URL` must use HTTPS. Plain HTTP is accepted only for loopback development instances (`localhost`, `127.0.0.0/8`, or `::1`), where the access token is sent without transport encryption.
1167
1183
 
1168
- Linking a GitLab repository imports its open issues and merge requests (up to five pages each). Without a webhook, later items are discovered when their lists are requested, and changed merge-request heads are recorded when the merge-request list is requested. Existing cards can still be reconciled. For ongoing issue changes, comments, and merge-request lifecycle events, configure the direct project webhook with `GITLAB_WEBHOOK_SECRET`.
1184
+ Linking a GitLab repository imports its open issues and merge requests (up to five pages each). Without a webhook, the reconcile sweep discovers later items and records changed merge-request heads: every five minutes by default (`MASTRACODE_GITLAB_RECONCILE_INTERVAL_MS`), it lists the open, non-draft merge requests of each linked repository and the issues of each selected source routed to a Factory, up to five pages each, whether or not a board is open. Requesting a list never files a card. The same sweep reconciles existing cards. For ongoing issue changes, comments, and merge-request lifecycle events, configure the direct project webhook with `GITLAB_WEBHOOK_SECRET`.
1169
1185
 
1170
1186
  For a Mastra Platform/Nango connection, use `PlatformGitLabIntegration`. `MastraFactory` installs it automatically whenever Platform credentials are configured and no integration with id `gitlab` was supplied. It discovers every active connection of the organization on the Platform's `gitlab` (OAuth) integration, proxies provider requests through `/v2/connections/{connectionId}/proxy`, and polls the Platform event log for GitLab events. `MASTRA_GITLAB_CONNECTION_ID` (or the `connectionId` constructor option) is optional and only narrows discovery to one connection. An explicit integration with id `gitlab` takes precedence.
1171
1187
 
@@ -1203,7 +1219,7 @@ import { PlatformIncidentioIntegration } from '@mastra/factory/integrations/plat
1203
1219
  const incidentio = new PlatformIncidentioIntegration(); // Reads Platform credentials from the environment.
1204
1220
  ```
1205
1221
 
1206
- Both integrations expose incidents and incident follow-ups as separate Intake sources. Their provider-neutral Intake items can be imported onto any installed board, including custom boards. A reconciliation worker polls imported incidents and follow-ups every five minutes by default to refresh their provider state and metadata. Set `MASTRACODE_INCIDENT_IO_RECONCILE_ENABLED=false` to disable it or `MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS` to a positive millisecond interval to change its cadence. Follow-up state updates map Factory completion and cancellation to incident.io's `completed` and `not_doing` statuses. incident.io does not expose Intake comments through these adapters.
1222
+ Both integrations expose incidents and incident follow-ups as separate Intake sources. Their provider-neutral Intake items can be imported onto any installed board, including custom boards. A reconciliation worker runs every five minutes by default: it refreshes the provider state and metadata of imported incidents and follow-ups, and files a work item for each new follow-up in a source bound to a Factory project. incident.io lists follow-ups oldest first and cannot filter them by status, so the sweep reads every page of each bound source. Opening a board only reads the list. Set `MASTRACODE_INCIDENT_IO_RECONCILE_INTERVAL_MS` to a positive millisecond interval to change its cadence. Follow-up state updates map Factory completion and cancellation to incident.io's `completed` and `not_doing` statuses. incident.io does not expose Intake comments through these adapters.
1207
1223
 
1208
1224
  ### Linear workspace connections
1209
1225
 
@@ -0,0 +1,16 @@
1
+ import type { PubSub } from '@mastra/core/events';
2
+ /** One topic for every project, so a replica hears about all boards through one subscription. */
3
+ export declare const BOARD_CHANGES_TOPIC = "factory.board-changes";
4
+ export interface BoardChangeScope {
5
+ orgId: string;
6
+ factoryProjectId: string;
7
+ }
8
+ /**
9
+ * Tells other replicas that a project's board changed. Never awaited — a slow
10
+ * or dead broker must not hold up the write it describes. `origin` lets the
11
+ * publishing replica skip its own echo; it already handled the change.
12
+ */
13
+ export declare function publishBoardChange(pubsub: PubSub, origin: string, scope: BoardChangeScope): void;
14
+ /** Hears board changes made on other replicas; resolves to the unsubscribe. */
15
+ export declare function subscribeBoardChanges(pubsub: PubSub, origin: string, changed: (scope: BoardChangeScope) => void): Promise<() => Promise<void>>;
16
+ //# sourceMappingURL=board-changes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"board-changes.d.ts","sourceRoot":"","sources":["../src/board-changes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAiB,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGjE,iGAAiG;AACjG,eAAO,MAAM,mBAAmB,0BAA0B,CAAC;AAE3D,MAAM,WAAW,gBAAgB;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,gBAAgB,GAAG,IAAI,CAahG;AAED,+EAA+E;AAC/E,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,CAAC,KAAK,EAAE,gBAAgB,KAAK,IAAI,GACzC,OAAO,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAS9B"}
@@ -0,0 +1,40 @@
1
+ import { withAck } from "@mastra/core/events";
2
+ // src/board-changes.ts
3
+ /** One topic for every project, so a replica hears about all boards through one subscription. */
4
+ const BOARD_CHANGES_TOPIC = "factory.board-changes";
5
+ /**
6
+ * Tells other replicas that a project's board changed. Never awaited — a slow
7
+ * or dead broker must not hold up the write it describes. `origin` lets the
8
+ * publishing replica skip its own echo; it already handled the change.
9
+ */
10
+ function publishBoardChange(pubsub, origin, scope) {
11
+ pubsub.publish(BOARD_CHANGES_TOPIC, {
12
+ type: "factory.board.changed",
13
+ runId: origin,
14
+ data: {
15
+ orgId: scope.orgId,
16
+ factoryProjectId: scope.factoryProjectId
17
+ }
18
+ }).catch((error) => {
19
+ console.warn("[Factory] Failed to publish a board change", {
20
+ factoryProjectId: scope.factoryProjectId,
21
+ error: error instanceof Error ? error.message : String(error)
22
+ });
23
+ });
24
+ }
25
+ /** Hears board changes made on other replicas; resolves to the unsubscribe. */
26
+ async function subscribeBoardChanges(pubsub, origin, changed) {
27
+ const onEvent = withAck(async (event) => {
28
+ if (event.runId === origin) return;
29
+ const { orgId, factoryProjectId } = event.data ?? {};
30
+ if (typeof orgId === "string" && typeof factoryProjectId === "string") changed({
31
+ orgId,
32
+ factoryProjectId
33
+ });
34
+ });
35
+ await pubsub.subscribe(BOARD_CHANGES_TOPIC, onEvent, { startFrom: "latest" });
36
+ return () => pubsub.unsubscribe(BOARD_CHANGES_TOPIC, onEvent);
37
+ }
38
+ export { BOARD_CHANGES_TOPIC, publishBoardChange, subscribeBoardChanges };
39
+
40
+ //# sourceMappingURL=board-changes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"board-changes.js","names":[],"sources":["../src/board-changes.ts"],"sourcesContent":["import type { EventCallback, PubSub } from '@mastra/core/events';\nimport { withAck } from '@mastra/core/events';\n\n/** One topic for every project, so a replica hears about all boards through one subscription. */\nexport const BOARD_CHANGES_TOPIC = 'factory.board-changes';\n\nexport interface BoardChangeScope {\n orgId: string;\n factoryProjectId: string;\n}\n\n/**\n * Tells other replicas that a project's board changed. Never awaited — a slow\n * or dead broker must not hold up the write it describes. `origin` lets the\n * publishing replica skip its own echo; it already handled the change.\n */\nexport function publishBoardChange(pubsub: PubSub, origin: string, scope: BoardChangeScope): void {\n pubsub\n .publish(BOARD_CHANGES_TOPIC, {\n type: 'factory.board.changed',\n runId: origin,\n data: { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId },\n })\n .catch((error: unknown) => {\n console.warn('[Factory] Failed to publish a board change', {\n factoryProjectId: scope.factoryProjectId,\n error: error instanceof Error ? error.message : String(error),\n });\n });\n}\n\n/** Hears board changes made on other replicas; resolves to the unsubscribe. */\nexport async function subscribeBoardChanges(\n pubsub: PubSub,\n origin: string,\n changed: (scope: BoardChangeScope) => void,\n): Promise<() => Promise<void>> {\n const onEvent: EventCallback = withAck(async event => {\n if (event.runId === origin) return;\n const { orgId, factoryProjectId } = (event.data ?? {}) as Partial<BoardChangeScope>;\n if (typeof orgId === 'string' && typeof factoryProjectId === 'string') changed({ orgId, factoryProjectId });\n });\n // Without `latest`, a retaining broker replays changes made before this replica read anything.\n await pubsub.subscribe(BOARD_CHANGES_TOPIC, onEvent, { startFrom: 'latest' });\n return () => pubsub.unsubscribe(BOARD_CHANGES_TOPIC, onEvent);\n}\n"],"mappings":";;;AAIA,MAAa,sBAAsB;;;;;;AAYnC,SAAgB,mBAAmB,QAAgB,QAAgB,OAA+B;CAChG,OACG,QAAQ,qBAAqB;EAC5B,MAAM;EACN,OAAO;EACP,MAAM;GAAE,OAAO,MAAM;GAAO,kBAAkB,MAAM;EAAiB;CACvE,CAAC,CAAC,CACD,OAAO,UAAmB;EACzB,QAAQ,KAAK,8CAA8C;GACzD,kBAAkB,MAAM;GACxB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D,CAAC;CACH,CAAC;AACL;;AAGA,eAAsB,sBACpB,QACA,QACA,SAC8B;CAC9B,MAAM,UAAyB,QAAQ,OAAM,UAAS;EACpD,IAAI,MAAM,UAAU,QAAQ;EAC5B,MAAM,EAAE,OAAO,qBAAsB,MAAM,QAAQ,CAAC;EACpD,IAAI,OAAO,UAAU,YAAY,OAAO,qBAAqB,UAAU,QAAQ;GAAE;GAAO;EAAiB,CAAC;CAC5G,CAAC;CAED,MAAM,OAAO,UAAU,qBAAqB,SAAS,EAAE,WAAW,SAAS,CAAC;CAC5E,aAAa,OAAO,YAAY,qBAAqB,OAAO;AAC9D"}
@@ -1,7 +1,8 @@
1
1
  import { BoardDefinitionError, DEFAULT_PHASE_CONTEXT, FACTORY_AGENT_ID, REVIEW_CONTEXT, defineBoard } from "./define-board.js";
2
2
  import { DEFAULT_BOARD_ID } from "./default-board.js";
3
3
  import { cardRuleFacts } from "./card-facts.js";
4
- import { awaitsAcceptance, boardEventHandlers, boardFlow, boardForWorkItem, boardPhaseOutcomes, boundChangeRequestNumber, cardBoardFlow, cardOwnsBranch, eventBoardId, hasPullRequest, intakeTarget, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, resolveBoardToolRule, resolvePhaseSemantics, reviewedChangeRequest, reviewedPullRequest, reviewsPullRequest, rulePhaseContext, rulePhaseField, sourceExternalId, withBoardClosure, withBoardFlow, withIntakeTarget, workItemPhaseSemantics } from "./semantics.js";
4
+ import { awaitsAcceptance, boardEventHandlers, boardFlow, boardForWorkItem, boardPhaseOutcomes, boundChangeRequestNumber, cardBoardFlow, cardOwnsBranch, eventBoardId, hasPullRequest, intakeTarget, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, resolveBoardToolRule, resolvePhaseSemantics, reviewedChangeRequest, reviewedPullRequest, reviewsPullRequest, rulePhaseContext, rulePhaseField, withBoardClosure, withBoardFlow, withIntakeTarget, workItemPhaseSemantics } from "./semantics.js";
5
+ import { sourceExternalId } from "../work-items/source-external-id.js";
5
6
  import { boardRegistryOf, createBoardRegistry, defaultBoards } from "./registry.js";
6
7
  import { workBoard } from "./work.js";
7
8
  export { BoardDefinitionError, DEFAULT_BOARD_ID, DEFAULT_PHASE_CONTEXT, FACTORY_AGENT_ID, REVIEW_CONTEXT, awaitsAcceptance, boardEventHandlers, boardFlow, boardForWorkItem, boardPhaseOutcomes, boardRegistryOf, boundChangeRequestNumber, cardBoardFlow, cardOwnsBranch, cardRuleFacts, createBoardRegistry, defaultBoards, defineBoard, eventBoardId, hasPullRequest, intakeTarget, isPullRequestCard, isPullRequestReviewPhase, isTerminalWorkItem, newestOpenPullRequestNumber, newestOwnedOpenPullRequestNumber, pullRequestSourceNumber, pullRequestSources, resolveBoardClosure, resolveBoardToolRule, resolvePhaseSemantics, reviewedChangeRequest, reviewedPullRequest, reviewsPullRequest, rulePhaseContext, rulePhaseField, sourceExternalId, withBoardClosure, withBoardFlow, withIntakeTarget, workBoard, workItemPhaseSemantics };
@@ -91,8 +91,6 @@ export declare function pullRequestSources(item: SourcedItem): WorkItemSourceRow
91
91
  export declare function hasPullRequest(item: SourcedItem & {
92
92
  readonly source?: string;
93
93
  }): boolean;
94
- /** A source row's external id without the type/workspace scope storage prefixes it with. */
95
- export declare function sourceExternalId(source: Pick<WorkItemSourceRow, 'sourceType' | 'workspaceId' | 'externalId'>): string;
96
94
  /** The provider number (GitHub PR number, GitLab MR IID) a pull request source names. */
97
95
  export declare function pullRequestSourceNumber(source: Pick<WorkItemSourceRow, 'metadata'>): number | undefined;
98
96
  /**
@@ -224,5 +222,5 @@ export declare function rulePhaseField(boards: Pick<BoardRegistry, 'get'>, item:
224
222
  * or, for an issue card in its board's pull request review phase, the pull request attached to it.
225
223
  */
226
224
  export declare function boundChangeRequestNumber(boards: Pick<BoardRegistry, 'get'>, item: Card): string | undefined;
227
- export {};
225
+ export { sourceExternalId } from '../work-items/source-external-id.js';
228
226
  //# sourceMappingURL=semantics.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"semantics.d.ts","sourceRoot":"","sources":["../../src/boards/semantics.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,uBAAuB,EACvB,oBAAoB,EACpB,uBAAuB,EACvB,uBAAuB,EACxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,0CAA0C,CAAC;AACrF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mDAAmD,CAAC;AAI3F,OAAO,KAAK,EACV,qBAAqB,EACrB,eAAe,EAEf,cAAc,EACd,0BAA0B,EAC3B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAInE,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAC9B,iFAAiF;IACjF,QAAQ,CAAC,IAAI,CAAC,EAA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G,QAAQ,CAAC,GACtD;IAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,uBAAuB,CAAA;CAAE,CAG9C;AAED;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,KAAK,CAAC,EAAE,IAAI,EAAE,IAAI,GAAG,MAAM,GAAG,SAAS,CAU3G;AAED,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC"}
@@ -3,6 +3,7 @@ import "./default-board.js";
3
3
  import "./define-board.js";
4
4
  import { reviewBoard } from "./review.js";
5
5
  import { workBoard } from "./work.js";
6
+ import { sourceExternalId } from "../work-items/source-external-id.js";
6
7
  // src/boards/semantics.ts
7
8
  /**
8
9
  * Board that owns a work item. Rows created before boards were persisted carry no `board`;
@@ -138,11 +139,6 @@ function pullRequestSources(item) {
138
139
  function hasPullRequest(item) {
139
140
  return item.source !== void 0 && isPullRequestCard({ source: item.source }) || pullRequestSources(item).length > 0;
140
141
  }
141
- /** A source row's external id without the type/workspace scope storage prefixes it with. */
142
- function sourceExternalId(source) {
143
- const prefix = `${source.sourceType}:${source.workspaceId ? `${source.workspaceId}:` : ""}`;
144
- return source.externalId.startsWith(prefix) ? source.externalId.slice(prefix.length) : source.externalId;
145
- }
146
142
  /** The provider number (GitHub PR number, GitLab MR IID) a pull request source names. */
147
143
  function pullRequestSourceNumber(source) {
148
144
  const metadata = source.metadata ?? {};
@@ -1 +1 @@
1
- {"version":3,"file":"semantics.js","names":[],"sources":["../../src/boards/semantics.ts"],"sourcesContent":["import type {\n FactoryRuleBoardClosure,\n FactoryRuleBoardFlow,\n FactoryRuleIntakeTarget,\n FactoryRulePhaseContext,\n} from '../rules/types.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport type { MetricsPhaseOutcomes } from '../storage/domains/work-items/metrics.js';\nimport type { WorkItemSourceRow } from '../storage/domains/work-items/work-item-schema.js';\nimport { workItemBranch, workItemBranchSource } from '../work-item-branch.js';\nimport { DEFAULT_BOARD_ID } from './default-board.js';\nimport { REVIEW_CONTEXT } from './define-board.js';\nimport type {\n BoardEventIntegration,\n BoardEventRules,\n BoardPhase,\n BoardPhaseKind,\n BoardToolResultRuleHandler,\n} from './define-board.js';\nimport type { BoardRegistry, InstalledBoard } from './registry.js';\nimport { reviewBoard } from './review.js';\nimport { workBoard } from './work.js';\n\nexport interface PhaseSemantics {\n readonly kind: BoardPhaseKind;\n /** Seat that carries a working phase; absent for resting and terminal phases. */\n readonly role?: string;\n}\n\n/**\n * Board that owns a work item. Rows created before boards were persisted carry no `board`;\n * they belong to the default board. (Pull requests used to default to the retired Review board;\n * storage reads those rows as the default board, and keeps cards stored on Review there only in a\n * project that still uses it.)\n */\nexport function boardForWorkItem(item: Pick<Card, 'board'>): string {\n return item.board ?? DEFAULT_BOARD_ID;\n}\n\nconst flows = new WeakMap<object, FactoryRuleBoardFlow>();\n\n/**\n * The phases a board's pull request loop runs through, read from what each phase declares\n * rather than from its key:\n *\n * Only phases running in the {@link REVIEW_CONTEXT} seat count as reviews: it is the only seat\n * that records verdicts.\n *\n * - `pullRequestReview`: the first phase that grants `factory_review_source`. It takes pull\n * requests: a pull request's own card is reviewed there, an attached pull request is reviewed\n * there, verdicts on pull requests are recorded there, and a push or review request re-enters it.\n * - `selfReview`: the first working phase that grants `factory_record_review_verdict` without\n * `factory_review_source`: an independent review of the builder's branch before a pull request.\n * - `triage`: on a board with a `build` phase, the first working phase that neither builds (runs\n * in `buildRole`) nor reviews: it sorts new cards before anyone accepts them. A board that\n * builds nothing has no triage phase.\n * - `build`: the last working phase, in declaration order, that is neither of those and can move\n * into the review that follows it (`selfReview`, else `pullRequestReview`). Self-review sends\n * requested changes back here, and its seat (`buildRole`) is woken by pull request feedback.\n *\n * A board without a `factory_review_source` phase has no pull request loop.\n */\nexport function boardFlow(board: InstalledBoard | undefined): FactoryRuleBoardFlow {\n if (!board) return Object.freeze({});\n const cached = flows.get(board);\n if (cached) return cached;\n const entries = Object.entries(board.phases) as [string, BoardPhase<string>][];\n const grants = (phase: BoardPhase<string>, tool: string) =>\n phase.kind === 'working' &&\n phase.runner.context === REVIEW_CONTEXT &&\n (phase.tools ?? []).some(granted => granted === tool);\n const pullRequestReview = entries.find(([, phase]) => grants(phase, 'factory_review_source'))?.[0];\n const selfReview = entries.find(\n ([key, phase]) =>\n key !== pullRequestReview &&\n grants(phase, 'factory_record_review_verdict') &&\n !grants(phase, 'factory_review_source'),\n )?.[0];\n const handoff = selfReview ?? pullRequestReview;\n const build = handoff\n ? entries.findLast(\n ([key, phase]) =>\n phase.kind === 'working' &&\n key !== pullRequestReview &&\n key !== selfReview &&\n board.allowsTransition(key, handoff),\n )?.[0]\n : undefined;\n const buildRole = build ? board.roleForPhase(build) : undefined;\n // Only a board that builds sorts cards first; elsewhere a working phase is just its own step.\n const triage = build\n ? entries.find(\n ([key, phase]) =>\n phase.kind === 'working' &&\n key !== build &&\n phase.runner.context !== REVIEW_CONTEXT &&\n phase.runner.context !== buildRole,\n )?.[0]\n : undefined;\n const terminals = entries.filter(([, phase]) => phase.kind === 'terminal').map(([key]) => key);\n const completed = board.sourceClosed?.completed ?? terminals[0];\n const canceled = board.sourceClosed?.canceled ?? terminals.find(key => key !== completed) ?? completed;\n const ref = (phase: string) => Object.freeze({ phase, title: board.phases[phase]!.name });\n const flow = Object.freeze({\n initialPhase: board.initialPhase,\n ...(completed ? { completed: ref(completed) } : {}),\n ...(canceled ? { canceled: ref(canceled) } : {}),\n ...(triage ? { triage } : {}),\n ...(pullRequestReview ? { pullRequestReview } : {}),\n ...(selfReview ? { selfReview } : {}),\n ...(build ? { build } : {}),\n ...(buildRole ? { buildRole } : {}),\n });\n flows.set(board, flow);\n return flow;\n}\n\n/**\n * Where integrations file new items, and where one lands when no intake route takes it: the\n * project's Work board's initial phase, else (a project an app gave only its own boards) the\n * initial phase of its first board in catalog order. Undefined only for a project with no boards.\n */\nexport function intakeTarget(boards: Pick<BoardRegistry, 'get' | 'values'>): FactoryRuleIntakeTarget | undefined {\n const target = boards.get(DEFAULT_BOARD_ID) ?? boards.values().next().value;\n if (!target) return undefined;\n return Object.freeze({ board: target.id, initialPhase: target.initialPhase });\n}\n\n/** {@link intakeTarget} as a rule context field. */\nexport function withIntakeTarget(boards: Pick<BoardRegistry, 'get' | 'values'>): { intake?: FactoryRuleIntakeTarget } {\n const intake = intakeTarget(boards);\n return intake ? { intake } : {};\n}\n\n/** {@link boardFlow} of the board a card sits on. */\nexport function cardBoardFlow(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board'> | undefined,\n): FactoryRuleBoardFlow {\n return item ? boardFlow(boards.get(boardForWorkItem(item))) : Object.freeze({});\n}\n\n/**\n * Whether a card in `stage` is still waiting for someone to accept it: it rests, or it is being\n * triaged. Approval labels hold only such cards.\n */\nexport function awaitsAcceptance(board: InstalledBoard | undefined, stage: string): boolean {\n if (!board) return false;\n return board.phaseKind(stage) === 'resting' || stage === boardFlow(board).triage;\n}\n\n/** Whether `stage` is the phase where the board reviews pull requests. */\nexport function isPullRequestReviewPhase(board: InstalledBoard | undefined, stage: string | undefined): boolean {\n const phase = boardFlow(board).pullRequestReview;\n return phase !== undefined && phase === stage;\n}\n\n/**\n * Why a move breaks the shape of a card on a board with a pull request loop, or undefined when it\n * does not: a pull request's own card is only reviewed, so it enters no other working phase, and\n * the pull request review phase holds only cards that carry a pull request (their own, or one\n * attached to their issue). `nextPhases` cannot say this: a resting phase may lead to both, and\n * which one fits depends on the card.\n */\nexport function pullRequestCardRejection(\n board: InstalledBoard,\n card: { readonly standalonePullRequest: boolean; readonly hasPullRequest: boolean },\n toStage: string,\n): string | undefined {\n const review = boardFlow(board).pullRequestReview;\n if (!review) return undefined;\n const reviewName = board.phases[review]?.name ?? review;\n if (!card.hasPullRequest && toStage === review) {\n return `${reviewName} holds only cards with a pull request; this work item enters it once a pull request is attached to it.`;\n }\n if (!card.standalonePullRequest || toStage === review || !board.isWorking(toStage)) return undefined;\n const exits = [review, ...Object.keys(board.phases).filter(key => board.isTerminal(key))];\n return `A pull request card is only reviewed on the ${board.name} board; it cannot enter ${toStage}. Move it to ${exits.join(', ')}.`;\n}\n\n/** `{ flow }` for spreading into an integration rule context, or `{}` for an unbound evaluation. */\nexport function withBoardFlow(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board'> | undefined,\n): { flow?: FactoryRuleBoardFlow } {\n return item ? { flow: cardBoardFlow(boards, item) } : {};\n}\n\ninterface SourcedItem {\n readonly workItem?: { readonly sources?: readonly WorkItemSourceRow[] } | null;\n}\n\n/**\n * A card whose own primary source is a pull or merge request: an outside contributor's\n * PR filed on its own card, or a PR card filed before PRs attached to their issue's card.\n * An issue card with an attached PR is not one; see {@link hasPullRequest}.\n */\nexport function isPullRequestCard(item: { readonly source: string }): boolean {\n return item.source === 'github-pr' || item.source === 'gitlab-pr';\n}\n\n/** Every pull or merge request source on a card, oldest first. */\nexport function pullRequestSources(item: SourcedItem): WorkItemSourceRow[] {\n return (item.workItem?.sources ?? []).filter(source => source.sourceType === 'pull-request');\n}\n\n/** Whether a card carries a pull or merge request: its own, or one attached to its issue. */\nexport function hasPullRequest(item: SourcedItem & { readonly source?: string }): boolean {\n return (\n (item.source !== undefined && isPullRequestCard({ source: item.source })) || pullRequestSources(item).length > 0\n );\n}\n\n/** A source row's external id without the type/workspace scope storage prefixes it with. */\nexport function sourceExternalId(source: Pick<WorkItemSourceRow, 'sourceType' | 'workspaceId' | 'externalId'>): string {\n const prefix = `${source.sourceType}:${source.workspaceId ? `${source.workspaceId}:` : ''}`;\n return source.externalId.startsWith(prefix) ? source.externalId.slice(prefix.length) : source.externalId;\n}\n\n/** The provider number (GitHub PR number, GitLab MR IID) a pull request source names. */\nexport function pullRequestSourceNumber(source: Pick<WorkItemSourceRow, 'metadata'>): number | undefined {\n const metadata = source.metadata ?? {};\n const value = metadata.githubPullRequestNumber ?? metadata.gitlabMergeRequestIid ?? metadata.number;\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction openSource(source: Pick<WorkItemSourceRow, 'state' | 'metadata'>): boolean {\n const state = source.state ?? source.metadata?.state;\n return state !== 'closed' && state !== 'merged' && source.metadata?.merged !== true;\n}\n\n/**\n * The pull request a PR review pass on this card reviews: the one the card's\n * `openPullRequestNumber` names, else the newest open one, else the newest one.\n */\nexport function reviewedPullRequest(\n item: SourcedItem & { readonly metadata?: Record<string, unknown> | null },\n): WorkItemSourceRow | undefined {\n const sources = pullRequestSources(item);\n const pointer = item.metadata?.openPullRequestNumber;\n return (\n (typeof pointer === 'number' ? sources.find(source => pullRequestSourceNumber(source) === pointer) : undefined) ??\n sources.findLast(openSource) ??\n sources.at(-1)\n );\n}\n\n/** The newest still-open pull request on a card other than `except`, for re-pointing `openPullRequestNumber`. */\nexport function newestOpenPullRequestNumber(item: SourcedItem, except?: number): number | null {\n const open = pullRequestSources(item).filter(\n source => openSource(source) && pullRequestSourceNumber(source) !== except,\n );\n return (open.length ? pullRequestSourceNumber(open.at(-1)!) : undefined) ?? null;\n}\n\ninterface SessionedItem {\n readonly sessions: Readonly<Record<string, { readonly branch?: string | null } | undefined>>;\n}\n\ntype BranchedItem = Pick<Card, 'id' | 'externalSource'> & { readonly workItem: Pick<Card['workItem'], 'metadata'> };\n\n/**\n * Whether a pull request from `headBranch` was opened by the card's own sessions: the head is\n * one of its session branches, or the branch Factory builds the card on (stable even after its\n * session is deleted).\n */\nexport function cardOwnsBranch(item: SessionedItem & BranchedItem, headBranch: string | undefined): boolean {\n if (!headBranch) return false;\n const buildBranch = workItemBranch({\n id: item.id,\n source: workItemBranchSource(item.externalSource),\n metadata: item.workItem.metadata,\n });\n return buildBranch === headBranch || Object.values(item.sessions).some(session => session?.branch === headBranch);\n}\n\n/** The newest open pull request the card's own sessions opened, other than `except`. */\nexport function newestOwnedOpenPullRequestNumber(\n item: SourcedItem & SessionedItem & BranchedItem,\n except?: number,\n): number | null {\n const open = pullRequestSources(item).filter(\n source =>\n openSource(source) &&\n pullRequestSourceNumber(source) !== except &&\n typeof source.metadata?.headBranch === 'string' &&\n cardOwnsBranch(item, source.metadata.headBranch),\n );\n return (open.length ? pullRequestSourceNumber(open.at(-1)!) : undefined) ?? null;\n}\n\n/** The pull or merge request a card's PR review covers, whichever card shape carries it. */\nexport interface ReviewedChangeRequest {\n readonly provider: 'github' | 'gitlab';\n readonly number: number | undefined;\n readonly url: string | null;\n readonly headBranch: string | undefined;\n /** The card is the change request's own card rather than an issue card it is attached to. */\n readonly standalone: boolean;\n}\n\n/**\n * What a PR review on this card reviews: the card's own change request when the card is one,\n * otherwise the attached one {@link reviewedPullRequest} picks. Undefined for a card with none.\n */\nexport function reviewedChangeRequest(item: {\n readonly source: string;\n readonly url?: string | null;\n readonly metadata?: Record<string, unknown> | null;\n readonly workItem: {\n readonly url?: string | null;\n readonly metadata?: Record<string, unknown> | null;\n readonly sources?: readonly WorkItemSourceRow[];\n };\n}): ReviewedChangeRequest | undefined {\n if (isPullRequestCard(item)) {\n const metadata = item.workItem.metadata ?? {};\n const gitlab = item.source === 'gitlab-pr';\n const value = (gitlab ? metadata.gitlabMergeRequestIid : metadata.githubPullRequestNumber) ?? metadata.number;\n return {\n provider: gitlab ? 'gitlab' : 'github',\n number: typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined,\n url: item.url ?? item.workItem.url ?? null,\n headBranch: typeof metadata.headBranch === 'string' ? metadata.headBranch : undefined,\n standalone: true,\n };\n }\n const source = reviewedPullRequest(item);\n if (!source) return undefined;\n return {\n provider: source.integrationId === 'gitlab' ? 'gitlab' : 'github',\n number: pullRequestSourceNumber(source),\n url: source.url ?? null,\n headBranch: typeof source.metadata?.headBranch === 'string' ? source.metadata.headBranch : undefined,\n standalone: false,\n };\n}\n\n/**\n * Whether a pass already recorded a verdict on `change`. An issue card can carry\n * several pull requests, so a verdict stamped for another one doesn't count; a\n * verdict with no number (a standalone card, or one stamped before verdicts named\n * their pull request) covers the card.\n */\nexport function hasRecordedVerdict(\n item: Parameters<typeof reviewedChangeRequest>[0],\n change: Pick<ReviewedChangeRequest, 'number'> | undefined = reviewedChangeRequest(item),\n): boolean {\n const covered = item.metadata?.reviewedPullRequestNumber;\n const reviewedAnother = typeof covered === 'number' && change?.number !== undefined && covered !== change.number;\n return typeof item.metadata?.reviewVerdict === 'string' && !reviewedAnother;\n}\n\n/**\n * Whether the rule's card carries a change request its board reviews: the card has one, and its\n * board has a phase that takes pull requests ({@link boardFlow}).\n */\nexport function reviewsPullRequest(context: {\n readonly flow?: Pick<FactoryRuleBoardFlow, 'pullRequestReview'>;\n readonly item?: SourcedItem & { readonly source: string };\n}): boolean {\n return context.flow?.pullRequestReview !== undefined && context.item !== undefined && hasPullRequest(context.item);\n}\n\n/**\n * What the installed board says `phase` means. Returns undefined when the board is not\n * installed or does not declare the phase; callers must fail closed on undefined rather\n * than guess from the phase name.\n */\nexport function resolvePhaseSemantics(\n boards: BoardRegistry,\n boardId: string,\n phase: string,\n): PhaseSemantics | undefined {\n const board = boards.get(boardId);\n const kind = board?.phaseKind(phase);\n if (!board || !kind) return undefined;\n const role = board.roleForPhase(phase);\n return role === undefined ? { kind } : { kind, role };\n}\n\n/**\n * Tool-result rule the installed board declares for `toolName`. Undefined when the board is\n * not installed or declares no rule for the tool; callers must run nothing in that case.\n */\nexport function resolveBoardToolRule(\n boards: BoardRegistry,\n boardId: string,\n toolName: string,\n): BoardToolResultRuleHandler | undefined {\n return boards.get(boardId)?.tools[toolName]?.onResult;\n}\n\n/**\n * Integration event handlers the installed board declares for cards on it, or undefined when the\n * card is unbound, the board is not installed, or it declares none for this integration. Within the\n * map, `null` means the board switched that event off for its cards.\n */\nexport function boardEventHandlers<I extends BoardEventIntegration>(\n boards: Pick<BoardRegistry, 'get'>,\n boardId: string | undefined,\n integration: I,\n): BoardEventRules[I] | undefined {\n return boardId === undefined ? undefined : boards.get(boardId)?.events[integration];\n}\n\n/**\n * Board whose event handlers answer an integration evaluation: the bound card's board, except on\n * the evaluation that files a pull request's own Review card, which is about a card that does\n * not exist yet.\n */\nexport function eventBoardId(context: {\n readonly item?: unknown;\n readonly board?: string;\n readonly pullRequestIntake?: boolean;\n}): string | undefined {\n return context.item && !context.pullRequestIntake ? context.board : undefined;\n}\n\n/** What a card's single current phase means on its installed board, for integration rule contexts. */\nexport function rulePhaseContext(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): FactoryRulePhaseContext | undefined {\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!stage) return undefined;\n const board = boards.get(boardForWorkItem(item));\n const kind = board?.phaseKind(stage);\n if (!board || !kind) return undefined;\n const context = board.roleForPhase(stage);\n const phase = board.phases[stage];\n return Object.freeze({\n id: stage,\n kind,\n ...(context === undefined ? {} : { context, role: context }),\n nextPhases: Object.freeze([...(phase?.nextPhases ?? [])]),\n });\n}\n\n/**\n * Whether a persisted card has finished, judged by the board it sits on: the installed board's\n * phase kind first, then, for rows whose board is not installed, the phase kinds of the default\n * board Factory seeds or of the retired Review board. Unknown boards or phases are never terminal,\n * so a card is only ever released from ownership on the board's own say-so.\n */\nexport function isTerminalWorkItem(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): boolean {\n const semantics = workItemPhaseSemantics(boards, item);\n if (semantics) return semantics.kind === 'terminal';\n const board = boardForWorkItem(item);\n if (boards.has(board)) return false;\n const seed = board === DEFAULT_BOARD_ID ? workBoard : board === reviewBoard.id ? reviewBoard : undefined;\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n return stage !== undefined && seed !== undefined && seed.isTerminal(stage);\n}\n\n/** Semantics of the single stage a work item currently occupies; undefined for multi-stage rows. */\nexport function workItemPhaseSemantics(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): PhaseSemantics | undefined {\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!stage) return undefined;\n return resolvePhaseSemantics(boards, boardForWorkItem(item), stage);\n}\n\n/**\n * Flow-metric outcomes of each board's phases: the phase the board closes completed sources into\n * (else its first terminal phase) completes a card, other terminal phases cancel it, resting\n * phases queue it, and anything else (working, or a phase the board no longer declares) is in\n * flight.\n */\nexport function boardPhaseOutcomes(boards: Pick<BoardRegistry, 'get'>): MetricsPhaseOutcomes {\n return (item, stage) => {\n const board = boards.get(boardForWorkItem(item));\n const kind = board?.phaseKind(stage);\n if (!board || kind === undefined || kind === 'working') return 'pipeline';\n if (kind === 'resting') return 'queued';\n const completed = board.sourceClosed?.completed ?? Object.keys(board.phases).find(key => board.isTerminal(key));\n return stage === completed ? 'completed' : 'canceled';\n };\n}\n\n/**\n * Where source-closed rules send a persisted card: the `sourceClosed` mapping its installed\n * board declares, plus whether the card already sits in a terminal phase. Undefined when the\n * board is not installed or declares no mapping, so closing the source leaves the card alone.\n */\nexport function resolveBoardClosure(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): FactoryRuleBoardClosure | undefined {\n const board = boards.get(boardForWorkItem(item));\n if (!board?.sourceClosed) return undefined;\n const { completed, canceled } = board.sourceClosed;\n return {\n boardTitle: board.name,\n completed: { phase: completed, title: board.phases[completed]!.name },\n canceled: { phase: canceled, title: board.phases[canceled]!.name },\n itemTerminal: item.stages.some(stage => board.isTerminal(stage)),\n };\n}\n\n/** Rule-context fragment carrying the card's `boardClosure`, empty when the board declares none. */\nexport function withBoardClosure(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): { boardClosure?: FactoryRuleBoardClosure } {\n const boardClosure = resolveBoardClosure(boards, item);\n return boardClosure ? { boardClosure } : {};\n}\n\n/** `{ phase }` for spreading into an integration rule context, or `{}` when the phase is unknown. */\nexport function rulePhaseField(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): { readonly phase?: FactoryRulePhaseContext } {\n const phase = rulePhaseContext(boards, item);\n return phase ? { phase } : {};\n}\n\n/**\n * The change request a review session on this card may publish checks for: the card's own one,\n * or, for an issue card in its board's pull request review phase, the pull request attached to it.\n */\nexport function boundChangeRequestNumber(boards: Pick<BoardRegistry, 'get'>, item: Card): string | undefined {\n const source = workItemBranchSource(item.externalSource);\n const own = isPullRequestCard({ source });\n if (!own && (item.stages.length !== 1 || cardBoardFlow(boards, item).pullRequestReview !== item.stages[0])) {\n return undefined;\n }\n const number = reviewedChangeRequest({ ...item, source })?.number;\n if (number !== undefined) return String(number);\n // A GitHub key ends in its number (`github-pr:34`); a GitLab key is encoded, so its digits mean nothing.\n return source === 'github-pr' ? /(\\d+)$/.exec(item.externalSource?.externalId ?? '')?.[1] : undefined;\n}\n"],"mappings":";;;;;;;;;;;;AAmCA,SAAgB,iBAAiB,MAAmC;CAClE,OAAO,KAAK,SAAA;AACd;AAEA,MAAM,wBAAQ,IAAI,QAAsC;;;;;;;;;;;;;;;;;;;;;;AAuBxD,SAAgB,UAAU,OAAyD;CACjF,IAAI,CAAC,OAAO,OAAO,OAAO,OAAO,CAAC,CAAC;CACnC,MAAM,SAAS,MAAM,IAAI,KAAK;CAC9B,IAAI,QAAQ,OAAO;CACnB,MAAM,UAAU,OAAO,QAAQ,MAAM,MAAM;CAC3C,MAAM,UAAU,OAA2B,SACzC,MAAM,SAAS,aACf,MAAM,OAAO,YAAA,aACZ,MAAM,SAAS,CAAC,EAAA,CAAG,MAAK,YAAW,YAAY,IAAI;CACtD,MAAM,oBAAoB,QAAQ,MAAM,GAAG,WAAW,OAAO,OAAO,uBAAuB,CAAC,CAAC,GAAG;CAChG,MAAM,aAAa,QAAQ,MACxB,CAAC,KAAK,WACL,QAAQ,qBACR,OAAO,OAAO,+BAA+B,KAC7C,CAAC,OAAO,OAAO,uBAAuB,CAC1C,CAAC,GAAG;CACJ,MAAM,UAAU,cAAc;CAC9B,MAAM,QAAQ,UACV,QAAQ,UACL,CAAC,KAAK,WACL,MAAM,SAAS,aACf,QAAQ,qBACR,QAAQ,cAC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\n FactoryRuleBoardFlow,\n FactoryRuleIntakeTarget,\n FactoryRulePhaseContext,\n} from '../rules/types.js';\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport type { MetricsPhaseOutcomes } from '../storage/domains/work-items/metrics.js';\nimport type { WorkItemSourceRow } from '../storage/domains/work-items/work-item-schema.js';\nimport { workItemBranch, workItemBranchSource } from '../work-item-branch.js';\nimport { DEFAULT_BOARD_ID } from './default-board.js';\nimport { REVIEW_CONTEXT } from './define-board.js';\nimport type {\n BoardEventIntegration,\n BoardEventRules,\n BoardPhase,\n BoardPhaseKind,\n BoardToolResultRuleHandler,\n} from './define-board.js';\nimport type { BoardRegistry, InstalledBoard } from './registry.js';\nimport { reviewBoard } from './review.js';\nimport { workBoard } from './work.js';\n\nexport interface PhaseSemantics {\n readonly kind: BoardPhaseKind;\n /** Seat that carries a working phase; absent for resting and terminal phases. */\n readonly role?: string;\n}\n\n/**\n * Board that owns a work item. Rows created before boards were persisted carry no `board`;\n * they belong to the default board. (Pull requests used to default to the retired Review board;\n * storage reads those rows as the default board, and keeps cards stored on Review there only in a\n * project that still uses it.)\n */\nexport function boardForWorkItem(item: Pick<Card, 'board'>): string {\n return item.board ?? DEFAULT_BOARD_ID;\n}\n\nconst flows = new WeakMap<object, FactoryRuleBoardFlow>();\n\n/**\n * The phases a board's pull request loop runs through, read from what each phase declares\n * rather than from its key:\n *\n * Only phases running in the {@link REVIEW_CONTEXT} seat count as reviews: it is the only seat\n * that records verdicts.\n *\n * - `pullRequestReview`: the first phase that grants `factory_review_source`. It takes pull\n * requests: a pull request's own card is reviewed there, an attached pull request is reviewed\n * there, verdicts on pull requests are recorded there, and a push or review request re-enters it.\n * - `selfReview`: the first working phase that grants `factory_record_review_verdict` without\n * `factory_review_source`: an independent review of the builder's branch before a pull request.\n * - `triage`: on a board with a `build` phase, the first working phase that neither builds (runs\n * in `buildRole`) nor reviews: it sorts new cards before anyone accepts them. A board that\n * builds nothing has no triage phase.\n * - `build`: the last working phase, in declaration order, that is neither of those and can move\n * into the review that follows it (`selfReview`, else `pullRequestReview`). Self-review sends\n * requested changes back here, and its seat (`buildRole`) is woken by pull request feedback.\n *\n * A board without a `factory_review_source` phase has no pull request loop.\n */\nexport function boardFlow(board: InstalledBoard | undefined): FactoryRuleBoardFlow {\n if (!board) return Object.freeze({});\n const cached = flows.get(board);\n if (cached) return cached;\n const entries = Object.entries(board.phases) as [string, BoardPhase<string>][];\n const grants = (phase: BoardPhase<string>, tool: string) =>\n phase.kind === 'working' &&\n phase.runner.context === REVIEW_CONTEXT &&\n (phase.tools ?? []).some(granted => granted === tool);\n const pullRequestReview = entries.find(([, phase]) => grants(phase, 'factory_review_source'))?.[0];\n const selfReview = entries.find(\n ([key, phase]) =>\n key !== pullRequestReview &&\n grants(phase, 'factory_record_review_verdict') &&\n !grants(phase, 'factory_review_source'),\n )?.[0];\n const handoff = selfReview ?? pullRequestReview;\n const build = handoff\n ? entries.findLast(\n ([key, phase]) =>\n phase.kind === 'working' &&\n key !== pullRequestReview &&\n key !== selfReview &&\n board.allowsTransition(key, handoff),\n )?.[0]\n : undefined;\n const buildRole = build ? board.roleForPhase(build) : undefined;\n // Only a board that builds sorts cards first; elsewhere a working phase is just its own step.\n const triage = build\n ? entries.find(\n ([key, phase]) =>\n phase.kind === 'working' &&\n key !== build &&\n phase.runner.context !== REVIEW_CONTEXT &&\n phase.runner.context !== buildRole,\n )?.[0]\n : undefined;\n const terminals = entries.filter(([, phase]) => phase.kind === 'terminal').map(([key]) => key);\n const completed = board.sourceClosed?.completed ?? terminals[0];\n const canceled = board.sourceClosed?.canceled ?? terminals.find(key => key !== completed) ?? completed;\n const ref = (phase: string) => Object.freeze({ phase, title: board.phases[phase]!.name });\n const flow = Object.freeze({\n initialPhase: board.initialPhase,\n ...(completed ? { completed: ref(completed) } : {}),\n ...(canceled ? { canceled: ref(canceled) } : {}),\n ...(triage ? { triage } : {}),\n ...(pullRequestReview ? { pullRequestReview } : {}),\n ...(selfReview ? { selfReview } : {}),\n ...(build ? { build } : {}),\n ...(buildRole ? { buildRole } : {}),\n });\n flows.set(board, flow);\n return flow;\n}\n\n/**\n * Where integrations file new items, and where one lands when no intake route takes it: the\n * project's Work board's initial phase, else (a project an app gave only its own boards) the\n * initial phase of its first board in catalog order. Undefined only for a project with no boards.\n */\nexport function intakeTarget(boards: Pick<BoardRegistry, 'get' | 'values'>): FactoryRuleIntakeTarget | undefined {\n const target = boards.get(DEFAULT_BOARD_ID) ?? boards.values().next().value;\n if (!target) return undefined;\n return Object.freeze({ board: target.id, initialPhase: target.initialPhase });\n}\n\n/** {@link intakeTarget} as a rule context field. */\nexport function withIntakeTarget(boards: Pick<BoardRegistry, 'get' | 'values'>): { intake?: FactoryRuleIntakeTarget } {\n const intake = intakeTarget(boards);\n return intake ? { intake } : {};\n}\n\n/** {@link boardFlow} of the board a card sits on. */\nexport function cardBoardFlow(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board'> | undefined,\n): FactoryRuleBoardFlow {\n return item ? boardFlow(boards.get(boardForWorkItem(item))) : Object.freeze({});\n}\n\n/**\n * Whether a card in `stage` is still waiting for someone to accept it: it rests, or it is being\n * triaged. Approval labels hold only such cards.\n */\nexport function awaitsAcceptance(board: InstalledBoard | undefined, stage: string): boolean {\n if (!board) return false;\n return board.phaseKind(stage) === 'resting' || stage === boardFlow(board).triage;\n}\n\n/** Whether `stage` is the phase where the board reviews pull requests. */\nexport function isPullRequestReviewPhase(board: InstalledBoard | undefined, stage: string | undefined): boolean {\n const phase = boardFlow(board).pullRequestReview;\n return phase !== undefined && phase === stage;\n}\n\n/**\n * Why a move breaks the shape of a card on a board with a pull request loop, or undefined when it\n * does not: a pull request's own card is only reviewed, so it enters no other working phase, and\n * the pull request review phase holds only cards that carry a pull request (their own, or one\n * attached to their issue). `nextPhases` cannot say this: a resting phase may lead to both, and\n * which one fits depends on the card.\n */\nexport function pullRequestCardRejection(\n board: InstalledBoard,\n card: { readonly standalonePullRequest: boolean; readonly hasPullRequest: boolean },\n toStage: string,\n): string | undefined {\n const review = boardFlow(board).pullRequestReview;\n if (!review) return undefined;\n const reviewName = board.phases[review]?.name ?? review;\n if (!card.hasPullRequest && toStage === review) {\n return `${reviewName} holds only cards with a pull request; this work item enters it once a pull request is attached to it.`;\n }\n if (!card.standalonePullRequest || toStage === review || !board.isWorking(toStage)) return undefined;\n const exits = [review, ...Object.keys(board.phases).filter(key => board.isTerminal(key))];\n return `A pull request card is only reviewed on the ${board.name} board; it cannot enter ${toStage}. Move it to ${exits.join(', ')}.`;\n}\n\n/** `{ flow }` for spreading into an integration rule context, or `{}` for an unbound evaluation. */\nexport function withBoardFlow(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board'> | undefined,\n): { flow?: FactoryRuleBoardFlow } {\n return item ? { flow: cardBoardFlow(boards, item) } : {};\n}\n\ninterface SourcedItem {\n readonly workItem?: { readonly sources?: readonly WorkItemSourceRow[] } | null;\n}\n\n/**\n * A card whose own primary source is a pull or merge request: an outside contributor's\n * PR filed on its own card, or a PR card filed before PRs attached to their issue's card.\n * An issue card with an attached PR is not one; see {@link hasPullRequest}.\n */\nexport function isPullRequestCard(item: { readonly source: string }): boolean {\n return item.source === 'github-pr' || item.source === 'gitlab-pr';\n}\n\n/** Every pull or merge request source on a card, oldest first. */\nexport function pullRequestSources(item: SourcedItem): WorkItemSourceRow[] {\n return (item.workItem?.sources ?? []).filter(source => source.sourceType === 'pull-request');\n}\n\n/** Whether a card carries a pull or merge request: its own, or one attached to its issue. */\nexport function hasPullRequest(item: SourcedItem & { readonly source?: string }): boolean {\n return (\n (item.source !== undefined && isPullRequestCard({ source: item.source })) || pullRequestSources(item).length > 0\n );\n}\n\n/** The provider number (GitHub PR number, GitLab MR IID) a pull request source names. */\nexport function pullRequestSourceNumber(source: Pick<WorkItemSourceRow, 'metadata'>): number | undefined {\n const metadata = source.metadata ?? {};\n const value = metadata.githubPullRequestNumber ?? metadata.gitlabMergeRequestIid ?? metadata.number;\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction openSource(source: Pick<WorkItemSourceRow, 'state' | 'metadata'>): boolean {\n const state = source.state ?? source.metadata?.state;\n return state !== 'closed' && state !== 'merged' && source.metadata?.merged !== true;\n}\n\n/**\n * The pull request a PR review pass on this card reviews: the one the card's\n * `openPullRequestNumber` names, else the newest open one, else the newest one.\n */\nexport function reviewedPullRequest(\n item: SourcedItem & { readonly metadata?: Record<string, unknown> | null },\n): WorkItemSourceRow | undefined {\n const sources = pullRequestSources(item);\n const pointer = item.metadata?.openPullRequestNumber;\n return (\n (typeof pointer === 'number' ? sources.find(source => pullRequestSourceNumber(source) === pointer) : undefined) ??\n sources.findLast(openSource) ??\n sources.at(-1)\n );\n}\n\n/** The newest still-open pull request on a card other than `except`, for re-pointing `openPullRequestNumber`. */\nexport function newestOpenPullRequestNumber(item: SourcedItem, except?: number): number | null {\n const open = pullRequestSources(item).filter(\n source => openSource(source) && pullRequestSourceNumber(source) !== except,\n );\n return (open.length ? pullRequestSourceNumber(open.at(-1)!) : undefined) ?? null;\n}\n\ninterface SessionedItem {\n readonly sessions: Readonly<Record<string, { readonly branch?: string | null } | undefined>>;\n}\n\ntype BranchedItem = Pick<Card, 'id' | 'externalSource'> & { readonly workItem: Pick<Card['workItem'], 'metadata'> };\n\n/**\n * Whether a pull request from `headBranch` was opened by the card's own sessions: the head is\n * one of its session branches, or the branch Factory builds the card on (stable even after its\n * session is deleted).\n */\nexport function cardOwnsBranch(item: SessionedItem & BranchedItem, headBranch: string | undefined): boolean {\n if (!headBranch) return false;\n const buildBranch = workItemBranch({\n id: item.id,\n source: workItemBranchSource(item.externalSource),\n metadata: item.workItem.metadata,\n });\n return buildBranch === headBranch || Object.values(item.sessions).some(session => session?.branch === headBranch);\n}\n\n/** The newest open pull request the card's own sessions opened, other than `except`. */\nexport function newestOwnedOpenPullRequestNumber(\n item: SourcedItem & SessionedItem & BranchedItem,\n except?: number,\n): number | null {\n const open = pullRequestSources(item).filter(\n source =>\n openSource(source) &&\n pullRequestSourceNumber(source) !== except &&\n typeof source.metadata?.headBranch === 'string' &&\n cardOwnsBranch(item, source.metadata.headBranch),\n );\n return (open.length ? pullRequestSourceNumber(open.at(-1)!) : undefined) ?? null;\n}\n\n/** The pull or merge request a card's PR review covers, whichever card shape carries it. */\nexport interface ReviewedChangeRequest {\n readonly provider: 'github' | 'gitlab';\n readonly number: number | undefined;\n readonly url: string | null;\n readonly headBranch: string | undefined;\n /** The card is the change request's own card rather than an issue card it is attached to. */\n readonly standalone: boolean;\n}\n\n/**\n * What a PR review on this card reviews: the card's own change request when the card is one,\n * otherwise the attached one {@link reviewedPullRequest} picks. Undefined for a card with none.\n */\nexport function reviewedChangeRequest(item: {\n readonly source: string;\n readonly url?: string | null;\n readonly metadata?: Record<string, unknown> | null;\n readonly workItem: {\n readonly url?: string | null;\n readonly metadata?: Record<string, unknown> | null;\n readonly sources?: readonly WorkItemSourceRow[];\n };\n}): ReviewedChangeRequest | undefined {\n if (isPullRequestCard(item)) {\n const metadata = item.workItem.metadata ?? {};\n const gitlab = item.source === 'gitlab-pr';\n const value = (gitlab ? metadata.gitlabMergeRequestIid : metadata.githubPullRequestNumber) ?? metadata.number;\n return {\n provider: gitlab ? 'gitlab' : 'github',\n number: typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined,\n url: item.url ?? item.workItem.url ?? null,\n headBranch: typeof metadata.headBranch === 'string' ? metadata.headBranch : undefined,\n standalone: true,\n };\n }\n const source = reviewedPullRequest(item);\n if (!source) return undefined;\n return {\n provider: source.integrationId === 'gitlab' ? 'gitlab' : 'github',\n number: pullRequestSourceNumber(source),\n url: source.url ?? null,\n headBranch: typeof source.metadata?.headBranch === 'string' ? source.metadata.headBranch : undefined,\n standalone: false,\n };\n}\n\n/**\n * Whether a pass already recorded a verdict on `change`. An issue card can carry\n * several pull requests, so a verdict stamped for another one doesn't count; a\n * verdict with no number (a standalone card, or one stamped before verdicts named\n * their pull request) covers the card.\n */\nexport function hasRecordedVerdict(\n item: Parameters<typeof reviewedChangeRequest>[0],\n change: Pick<ReviewedChangeRequest, 'number'> | undefined = reviewedChangeRequest(item),\n): boolean {\n const covered = item.metadata?.reviewedPullRequestNumber;\n const reviewedAnother = typeof covered === 'number' && change?.number !== undefined && covered !== change.number;\n return typeof item.metadata?.reviewVerdict === 'string' && !reviewedAnother;\n}\n\n/**\n * Whether the rule's card carries a change request its board reviews: the card has one, and its\n * board has a phase that takes pull requests ({@link boardFlow}).\n */\nexport function reviewsPullRequest(context: {\n readonly flow?: Pick<FactoryRuleBoardFlow, 'pullRequestReview'>;\n readonly item?: SourcedItem & { readonly source: string };\n}): boolean {\n return context.flow?.pullRequestReview !== undefined && context.item !== undefined && hasPullRequest(context.item);\n}\n\n/**\n * What the installed board says `phase` means. Returns undefined when the board is not\n * installed or does not declare the phase; callers must fail closed on undefined rather\n * than guess from the phase name.\n */\nexport function resolvePhaseSemantics(\n boards: BoardRegistry,\n boardId: string,\n phase: string,\n): PhaseSemantics | undefined {\n const board = boards.get(boardId);\n const kind = board?.phaseKind(phase);\n if (!board || !kind) return undefined;\n const role = board.roleForPhase(phase);\n return role === undefined ? { kind } : { kind, role };\n}\n\n/**\n * Tool-result rule the installed board declares for `toolName`. Undefined when the board is\n * not installed or declares no rule for the tool; callers must run nothing in that case.\n */\nexport function resolveBoardToolRule(\n boards: BoardRegistry,\n boardId: string,\n toolName: string,\n): BoardToolResultRuleHandler | undefined {\n return boards.get(boardId)?.tools[toolName]?.onResult;\n}\n\n/**\n * Integration event handlers the installed board declares for cards on it, or undefined when the\n * card is unbound, the board is not installed, or it declares none for this integration. Within the\n * map, `null` means the board switched that event off for its cards.\n */\nexport function boardEventHandlers<I extends BoardEventIntegration>(\n boards: Pick<BoardRegistry, 'get'>,\n boardId: string | undefined,\n integration: I,\n): BoardEventRules[I] | undefined {\n return boardId === undefined ? undefined : boards.get(boardId)?.events[integration];\n}\n\n/**\n * Board whose event handlers answer an integration evaluation: the bound card's board, except on\n * the evaluation that files a pull request's own Review card, which is about a card that does\n * not exist yet.\n */\nexport function eventBoardId(context: {\n readonly item?: unknown;\n readonly board?: string;\n readonly pullRequestIntake?: boolean;\n}): string | undefined {\n return context.item && !context.pullRequestIntake ? context.board : undefined;\n}\n\n/** What a card's single current phase means on its installed board, for integration rule contexts. */\nexport function rulePhaseContext(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): FactoryRulePhaseContext | undefined {\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!stage) return undefined;\n const board = boards.get(boardForWorkItem(item));\n const kind = board?.phaseKind(stage);\n if (!board || !kind) return undefined;\n const context = board.roleForPhase(stage);\n const phase = board.phases[stage];\n return Object.freeze({\n id: stage,\n kind,\n ...(context === undefined ? {} : { context, role: context }),\n nextPhases: Object.freeze([...(phase?.nextPhases ?? [])]),\n });\n}\n\n/**\n * Whether a persisted card has finished, judged by the board it sits on: the installed board's\n * phase kind first, then, for rows whose board is not installed, the phase kinds of the default\n * board Factory seeds or of the retired Review board. Unknown boards or phases are never terminal,\n * so a card is only ever released from ownership on the board's own say-so.\n */\nexport function isTerminalWorkItem(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): boolean {\n const semantics = workItemPhaseSemantics(boards, item);\n if (semantics) return semantics.kind === 'terminal';\n const board = boardForWorkItem(item);\n if (boards.has(board)) return false;\n const seed = board === DEFAULT_BOARD_ID ? workBoard : board === reviewBoard.id ? reviewBoard : undefined;\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n return stage !== undefined && seed !== undefined && seed.isTerminal(stage);\n}\n\n/** Semantics of the single stage a work item currently occupies; undefined for multi-stage rows. */\nexport function workItemPhaseSemantics(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): PhaseSemantics | undefined {\n const stage = item.stages.length === 1 ? item.stages[0] : undefined;\n if (!stage) return undefined;\n return resolvePhaseSemantics(boards, boardForWorkItem(item), stage);\n}\n\n/**\n * Flow-metric outcomes of each board's phases: the phase the board closes completed sources into\n * (else its first terminal phase) completes a card, other terminal phases cancel it, resting\n * phases queue it, and anything else (working, or a phase the board no longer declares) is in\n * flight.\n */\nexport function boardPhaseOutcomes(boards: Pick<BoardRegistry, 'get'>): MetricsPhaseOutcomes {\n return (item, stage) => {\n const board = boards.get(boardForWorkItem(item));\n const kind = board?.phaseKind(stage);\n if (!board || kind === undefined || kind === 'working') return 'pipeline';\n if (kind === 'resting') return 'queued';\n const completed = board.sourceClosed?.completed ?? Object.keys(board.phases).find(key => board.isTerminal(key));\n return stage === completed ? 'completed' : 'canceled';\n };\n}\n\n/**\n * Where source-closed rules send a persisted card: the `sourceClosed` mapping its installed\n * board declares, plus whether the card already sits in a terminal phase. Undefined when the\n * board is not installed or declares no mapping, so closing the source leaves the card alone.\n */\nexport function resolveBoardClosure(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): FactoryRuleBoardClosure | undefined {\n const board = boards.get(boardForWorkItem(item));\n if (!board?.sourceClosed) return undefined;\n const { completed, canceled } = board.sourceClosed;\n return {\n boardTitle: board.name,\n completed: { phase: completed, title: board.phases[completed]!.name },\n canceled: { phase: canceled, title: board.phases[canceled]!.name },\n itemTerminal: item.stages.some(stage => board.isTerminal(stage)),\n };\n}\n\n/** Rule-context fragment carrying the card's `boardClosure`, empty when the board declares none. */\nexport function withBoardClosure(\n boards: BoardRegistry,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): { boardClosure?: FactoryRuleBoardClosure } {\n const boardClosure = resolveBoardClosure(boards, item);\n return boardClosure ? { boardClosure } : {};\n}\n\n/** `{ phase }` for spreading into an integration rule context, or `{}` when the phase is unknown. */\nexport function rulePhaseField(\n boards: Pick<BoardRegistry, 'get'>,\n item: Pick<Card, 'board' | 'externalSource' | 'stages'>,\n): { readonly phase?: FactoryRulePhaseContext } {\n const phase = rulePhaseContext(boards, item);\n return phase ? { phase } : {};\n}\n\n/**\n * The change request a review session on this card may publish checks for: the card's own one,\n * or, for an issue card in its board's pull request review phase, the pull request attached to it.\n */\nexport function boundChangeRequestNumber(boards: Pick<BoardRegistry, 'get'>, item: Card): string | undefined {\n const source = workItemBranchSource(item.externalSource);\n const own = isPullRequestCard({ source });\n if (!own && (item.stages.length !== 1 || cardBoardFlow(boards, item).pullRequestReview !== item.stages[0])) {\n return undefined;\n }\n const number = reviewedChangeRequest({ ...item, source })?.number;\n if (number !== undefined) return String(number);\n // A GitHub key ends in its number (`github-pr:34`); a GitLab key is encoded, so its digits mean nothing.\n return source === 'github-pr' ? /(\\d+)$/.exec(item.externalSource?.externalId ?? '')?.[1] : undefined;\n}\n\nexport { sourceExternalId } from '../work-items/source-external-id.js';\n"],"mappings":";;;;;;;;;;;;;AAmCA,SAAgB,iBAAiB,MAAmC;CAClE,OAAO,KAAK,SAAA;AACd;AAEA,MAAM,wBAAQ,IAAI,QAAsC;;;;;;;;;;;;;;;;;;;;;;AAuBxD,SAAgB,UAAU,OAAyD;CACjF,IAAI,CAAC,OAAO,OAAO,OAAO,OAAO,CAAC,CAAC;CACnC,MAAM,SAAS,MAAM,IAAI,KAAK;CAC9B,IAAI,QAAQ,OAAO;CACnB,MAAM,UAAU,OAAO,QAAQ,MAAM,MAAM;CAC3C,MAAM,UAAU,OAA2B,SACzC,MAAM,SAAS,aACf,MAAM,OAAO,YAAA,aACZ,MAAM,SAAS,CAAC,EAAA,CAAG,MAAK,YAAW,YAAY,IAAI;CACtD,MAAM,oBAAoB,QAAQ,MAAM,GAAG,WAAW,OAAO,OAAO,uBAAuB,CAAC,CAAC,GAAG;CAChG,MAAM,aAAa,QAAQ,MACxB,CAAC,KAAK,WACL,QAAQ,qBACR,OAAO,OAAO,+BAA+B,KAC7C,CAAC,OAAO,OAAO,uBAAuB,CAC1C,CAAC,GAAG;CACJ,MAAM,UAAU,cAAc;CAC9B,MAAM,QAAQ,UACV,Q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AAI,iBAAiB,IAAI,CAAC;CAC/C,IAAI,CAAC,OAAO,cAAc,OAAO,KAAA;CACjC,MAAM,EAAE,WAAW,aAAa,MAAM;CACtC,OAAO;EACL,YAAY,MAAM;EAClB,WAAW;GAAE,OAAO;GAAW,OAAO,MAAM,OAAO,UAAU,CAAE;EAAK;EACpE,UAAU;GAAE,OAAO;GAAU,OAAO,MAAM,OAAO,SAAS,CAAE;EAAK;EACjE,cAAc,KAAK,OAAO,MAAK,UAAS,MAAM,WAAW,KAAK,CAAC;CACjE;AACF;;AAGA,SAAgB,iBACd,QACA,MAC4C;CAC5C,MAAM,eAAe,oBAAoB,QAAQ,IAAI;CACrD,OAAO,eAAe,EAAE,aAAa,IAAI,CAAC;AAC5C;;AAGA,SAAgB,eACd,QACA,MAC8C;CAC9C,MAAM,QAAQ,iBAAiB,QAAQ,IAAI;CAC3C,OAAO,QAAQ,EAAE,MAAM,IAAI,CAAC;AAC9B;;;;;AAMA,SAAgB,yBAAyB,QAAoC,MAAgC;CAC3G,MAAM,SAAS,qBAAqB,KAAK,cAAc;CAEvD,IAAI,CADQ,kBAAkB,EAAE,OAAO,CAChC,MAAM,KAAK,OAAO,WAAW,KAAK,cAAc,QAAQ,IAAI,CAAC,CAAC,sBAAsB,KAAK,OAAO,KACrG;CAEF,MAAM,SAAS,sBAAsB;EAAE,GAAG;EAAM;CAAO,CAAC,CAAC,EAAE;CAC3D,IAAI,WAAW,KAAA,GAAW,OAAO,OAAO,MAAM;CAE9C,OAAO,WAAW,cAAc,SAAS,KAAK,KAAK,gBAAgB,cAAc,EAAE,CAAC,GAAG,KAAK,KAAA;AAC9F"}
package/dist/factory.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  * Integration readiness is derived from each instance's declared capabilities
19
19
  * and the storage domains those capabilities require.
20
20
  */
21
+ import type { MastraCodeConfig } from '@mastra/code-sdk';
21
22
  import type { BuiltinToolId } from '@mastra/core/agent-controller';
22
23
  import type { MastraBrowser } from '@mastra/core/browser';
23
24
  import type { PubSub } from '@mastra/core/events';
@@ -70,6 +71,8 @@ export interface MastraFactoryConfig {
70
71
  * one connection, every feature on.
71
72
  */
72
73
  storage: FactoryStorage;
74
+ /** Scorers for the mounted code agent. None run by default. */
75
+ scorers?: MastraCodeConfig['scorers'];
73
76
  /** Disable persistence of rich scorer results. Default: true. */
74
77
  disableScoreStorage?: boolean;
75
78
  /**
@@ -253,6 +256,7 @@ export type { FactorySandboxStart } from './workspace.js';
253
256
  * limit shared across deployments.
254
257
  */
255
258
  export interface MastraFactoryDispatcherConfig {
259
+ /** Automated agent runs one server process holds at once. Defaults to 10; runs past it wait in the run queue. */
256
260
  maxInFlight?: number;
257
261
  }
258
262
  export declare class MastraFactory {
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AASH,OAAO,KAAK,EAAiC,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAqB,MAAM,sBAAsB,CAAC;AAE9E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,KAAK,EAAkB,yBAAyB,EAAoB,MAAM,wBAAwB,CAAC;AAqB1G,OAAO,KAAK,EAAiB,cAAc,EAAE,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AK,GAAG,SAAS,gBAAgB,EAAE,CAAA;KAAE,GACzD,OAAO,CAAC;QAAE,QAAQ,EAAE,gBAAgB,EAAE,CAAC;QAAC,OAAO,EAAE,gBAAgB,EAAE,CAAC;QAAC,SAAS,EAAE,gBAAgB,EAAE,CAAA;KAAE,CAAC,CA6CvG;IAED;;;;;;;;;;;;;;;;;;;;OAoBG;IACG,qBAAqB,CAAC,cAAc,EAAE,cAAc,GAAG,OAAO,CAAC,qBAAqB,GAAG,SAAS,CAAC,CAKtG;IAED;;;;OAIG;IACG,OAAO,IAAI,OAAO,CAAC,UAAU,CAAC,CAmuDnC;IAED;;;;OAIG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAwB9B;IAED,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CA4C9B;CACF"}
package/dist/factory.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { buildAuthDisabledRoutes, buildAuthRoutes, createFactoryAuthGate, createFactoryInteractiveMarker, createFactoryRouteAuth, getFactoryAuthOrgId, getFactoryAuthUserFromContext, getFactoryAuthUserId } from "./auth.js";
2
+ import { publishBoardChange, subscribeBoardChanges } from "./board-changes.js";
2
3
  import { BoardWriteError, BoardWrites } from "./boards/board-writes.js";
3
4
  import { isDefinedBoard } from "./boards/define-board.js";
4
5
  import "./boards/index.js";
@@ -14,10 +15,13 @@ import { boardForWorkItem, boundChangeRequestNumber, isTerminalWorkItem } from "
14
15
  import { createGithubReviewStatusReporter, reviewStatusAnimationFromEnv } from "./integrations/github/review-status-reporter.js";
15
16
  import { isFactoryGithubLogin, trustedCollaborator } from "./integrations/github/rules.js";
16
17
  import { dismissStaleFactoryReviews } from "./integrations/github/stale-reviews.js";
18
+ import { KeptCards } from "./integrations/kept-cards.js";
17
19
  import { PlatformApiClient, platformApiClientConfigFromEnv } from "./integrations/platform/api-client.js";
18
20
  import { buildConnectToolsRoute, buildPlatformConnectRoutes } from "./integrations/platform/connect/routes.js";
19
21
  import { platformConnectTools } from "./integrations/platform/connect/session-tools.js";
22
+ import { logIntegrationSummary } from "./integrations/startup-summary.js";
20
23
  import { createSessionAsRowOwner, prepareSessionRunContext } from "./integrations/subscription-session.js";
24
+ import { shareLinkedRepositoryChanges } from "./linked-repositories-changed.js";
21
25
  import { buildFactoryMcpRoutes, resolveMcpAuthorizationServers } from "./mcp/routes.js";
22
26
  import { resolveDeploymentModelProviders } from "./routes/config.js";
23
27
  import { createCustomProvidersPrimer, primeCustomProvidersForRequestContext, registerCustomProvidersSource } from "./routes/custom-provider-source.js";
@@ -92,7 +96,7 @@ import { SkillOverridesStorage } from "./storage/domains/skill-overrides/base.js
92
96
  import { SourceControlStorage } from "./storage/domains/source-control/base.js";
93
97
  import { VoiceSettingsStorage } from "./storage/domains/voice-settings/base.js";
94
98
  import { WorkItemSplitModeError, WorkItemsStorage } from "./storage/domains/work-items/base.js";
95
- import { createRequestTimingMiddleware, factoryTimingEnabled, instrumentAsyncMethods, logTiming, timedPhase } from "./timing.js";
99
+ import { bootDiagnosticsEnabled, createRequestTimingMiddleware, factoryTimingEnabled, instrumentAsyncMethods, logTiming, timedPhase } from "./timing.js";
96
100
  import { deliverFactorySessionNotification } from "./tools/deliver.js";
97
101
  import { createFactoryTools } from "./tools/index.js";
98
102
  import { createSessionApprovalNotifier, createSessionRunEndReporter, createStageChangeNotifier, createWorkItemRunEndReporter } from "./tools/reports.js";
@@ -252,7 +256,10 @@ var MastraFactory = class {
252
256
  /** Names this replica on the dispatch-wake topic so it can skip its own echoes. */
253
257
  #dispatchWakeOrigin = globalThis.crypto.randomUUID();
254
258
  #unsubscribeDispatchWakes;
259
+ #unsubscribeBoardChanges;
260
+ #keptCards;
255
261
  #unsubscribeSandboxEnvChanges;
262
+ #unsubscribeLinkedRepositoryChanges;
256
263
  #startCoordinator;
257
264
  #factoryProcessor;
258
265
  #channelShutdowns = [];
@@ -263,6 +270,7 @@ var MastraFactory = class {
263
270
  #sessionResourceMigration;
264
271
  #workItemSplitBackfill;
265
272
  #prepareStartedAt;
273
+ #integrations = [];
266
274
  #reviewedChangeRequest;
267
275
  #preparing = false;
268
276
  constructor(config) {
@@ -441,6 +449,10 @@ var MastraFactory = class {
441
449
  const { PlatformLinearIntegration } = await import("./integrations/platform/linear/integration.js");
442
450
  integrations.push(new PlatformLinearIntegration());
443
451
  }
452
+ if (!integrations.some((integration) => integration.id === "vanta")) {
453
+ const { PlatformVantaIntegration } = await import("./integrations/platform/vanta/integration.js");
454
+ integrations.push(new PlatformVantaIntegration());
455
+ }
444
456
  }
445
457
  if (this.#config.platform?.github && !installedPlatformGithub) console.warn("[factory] 'platform.github' config was provided but the factory installed no GitHub integration of its own " + (explicitGithub ? "(an explicit integration with id 'github' takes precedence, so these options were ignored)." : "(no Platform credentials are configured and no explicit GitHub integration was passed)."));
446
458
  const integrationIds = /* @__PURE__ */ new Set();
@@ -448,11 +460,11 @@ var MastraFactory = class {
448
460
  if (integrationIds.has(integration.id)) throw new Error(`MastraFactory: duplicate integration id '${integration.id}' in 'integrations'.`);
449
461
  integrationIds.add(integration.id);
450
462
  }
463
+ this.#integrations = integrations;
451
464
  const configVersion = this.#configVersion;
452
465
  const intakeStorage = storage.registerDomain(new IntakeStorage());
453
466
  const auditStorage = storage.registerDomain(new AuditStorage());
454
467
  const workItemsStorage = storage.registerDomain(new WorkItemsStorage());
455
- workItemsStorage.onBoardChanged((scope) => touchFeed(eventBus, scope));
456
468
  workItemsStorage.onClaimableWork(() => publishDispatchWake(eventBus, this.#dispatchWakeOrigin));
457
469
  this.#unsubscribeDispatchWakes = subscribeDispatchWakes(eventBus, this.#dispatchWakeOrigin, () => this.#dispatcher?.wake()).catch((error) => {
458
470
  console.warn(`[factory] subscribing to dispatcher wakes failed; other replicas' work waits for this replica's own wakes: ${error instanceof Error ? error.message : error}`);
@@ -473,8 +485,34 @@ var MastraFactory = class {
473
485
  const queueHealthStorage = storage.registerDomain(new QueueHealthStorage());
474
486
  const integrationStorage = storage.registerDomain(new IntegrationStorage(secretEncryption));
475
487
  const factoryProjectsStorage = storage.registerDomain(new FactoryProjectsStorage());
488
+ const keptCards = new KeptCards({
489
+ projects: factoryProjectsStorage,
490
+ workItems: workItemsStorage
491
+ });
492
+ this.#keptCards = keptCards;
493
+ const boardChangeOrigin = globalThis.crypto.randomUUID();
494
+ workItemsStorage.onBoardChanged((scope) => {
495
+ touchFeed(eventBus, scope);
496
+ keptCards.changed(scope);
497
+ publishBoardChange(eventBus, boardChangeOrigin, scope);
498
+ });
499
+ factoryProjectsStorage.onDeleted((project) => {
500
+ const scope = {
501
+ orgId: project.orgId,
502
+ factoryProjectId: project.id
503
+ };
504
+ keptCards.changed(scope);
505
+ publishBoardChange(eventBus, boardChangeOrigin, scope);
506
+ });
507
+ this.#unsubscribeBoardChanges = subscribeBoardChanges(eventBus, boardChangeOrigin, (scope) => keptCards.changed(scope)).then((unsubscribe) => {
508
+ keptCards.trustAnnouncements();
509
+ return unsubscribe;
510
+ }, (error) => {
511
+ console.warn(`[factory] subscribing to board changes failed; background sweeps read every board from the database: ${error instanceof Error ? error.message : error}`);
512
+ });
476
513
  const filesystemStorage = storage.registerDomain(new FilesystemStorage());
477
514
  const sourceControlStorage = storage.registerDomain(new SourceControlStorage());
515
+ this.#unsubscribeLinkedRepositoryChanges = shareLinkedRepositoryChanges(eventBus, sourceControlStorage);
478
516
  const channelIdentityStorage = storage.registerDomain(new ChannelIdentityStorage());
479
517
  const skillOverridesStorage = storage.registerDomain(new SkillOverridesStorage());
480
518
  const domains = {
@@ -1108,6 +1146,7 @@ var MastraFactory = class {
1108
1146
  gitBranch: ""
1109
1147
  },
1110
1148
  storage: storage.getMastraStorage(),
1149
+ ...this.#config.scorers ? { scorers: this.#config.scorers } : {},
1111
1150
  disableScoreStorage: this.#config.disableScoreStorage ?? true,
1112
1151
  ...mastraStorageBackend ? { storageBackend: mastraStorageBackend } : {},
1113
1152
  knowledge: this.#config.knowledge ?? false,
@@ -1335,6 +1374,7 @@ var MastraFactory = class {
1335
1374
  cache: this.#projectBoards
1336
1375
  } } : {},
1337
1376
  factoryTransitionService: transitionService,
1377
+ runSlots: () => this.#dispatcher?.runSlots(),
1338
1378
  onFactoryRuntime: ({ transitionService: runtimeTransitionService, startCoordinator, prepareBinding }) => {
1339
1379
  this.#startCoordinator = startCoordinator;
1340
1380
  this.#dispatcher ??= new FactoryDecisionDispatcher({
@@ -1555,6 +1595,7 @@ var MastraFactory = class {
1555
1595
  integrations: integrationRegistrations,
1556
1596
  configVersion,
1557
1597
  boardRegistry: this.#projectBoards ?? this.#boards,
1598
+ ...this.#keptCards ? { keptCards: this.#keptCards } : {},
1558
1599
  factoryReady,
1559
1600
  domains,
1560
1601
  ...this.#environmentBuilds ? { onRepositoryPush: this.#environmentBuilds.onRepositoryPush } : {},
@@ -1578,7 +1619,8 @@ var MastraFactory = class {
1578
1619
  await this.#environmentBuilds?.probeSchedules();
1579
1620
  this.#sessionResourceMigration?.then((movedRunBindings) => movedRunBindings ? this.#factoryProcessor?.reconcileAllBoundThreads() : void 0).catch((error) => console.warn(`[factory] reconciling bound threads after the session resource migration failed: ${error instanceof Error ? error.message : error}`));
1580
1621
  this.#dispatcher?.start();
1581
- if (this.#prepareStartedAt !== void 0) logTiming(`boot ${Math.round(performance.now() - this.#prepareStartedAt)}ms`);
1622
+ if (bootDiagnosticsEnabled && this.#prepareStartedAt !== void 0) logTiming(`boot ${Math.round(performance.now() - this.#prepareStartedAt)}ms`);
1623
+ if (process.env.MASTRA_FACTORY_DEV === "true") logIntegrationSummary(this.#integrations);
1582
1624
  }
1583
1625
  /** Stop Factory-owned background work and channel transports before the host process shuts down. */
1584
1626
  async shutdown() {
@@ -1590,7 +1632,13 @@ var MastraFactory = class {
1590
1632
  this.#unsubscribeDispatchWakes = void 0;
1591
1633
  const unsubscribeSandboxEnvChanges = this.#unsubscribeSandboxEnvChanges;
1592
1634
  this.#unsubscribeSandboxEnvChanges = void 0;
1635
+ const unsubscribeBoardChanges = this.#unsubscribeBoardChanges;
1636
+ this.#unsubscribeBoardChanges = void 0;
1637
+ await unsubscribeBoardChanges?.then((unsubscribe) => unsubscribe?.()).catch(() => void 0);
1593
1638
  await unsubscribeSandboxEnvChanges?.then((unsubscribe) => unsubscribe?.()).catch(() => void 0);
1639
+ const unsubscribeLinkedRepositoryChanges = this.#unsubscribeLinkedRepositoryChanges;
1640
+ this.#unsubscribeLinkedRepositoryChanges = void 0;
1641
+ await unsubscribeLinkedRepositoryChanges?.then((unsubscribe) => unsubscribe()).catch(() => void 0);
1594
1642
  await unsubscribeDispatchWakes?.then((unsubscribe) => unsubscribe?.()).catch((error) => console.warn(`[factory] unsubscribing from dispatcher wakes failed: ${error instanceof Error ? error.message : error}`));
1595
1643
  const backfill = this.#workItemSplitBackfill;
1596
1644
  backfill?.controller.abort();