@mastra/factory 0.28.0-alpha.0 → 0.28.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 (335) hide show
  1. package/README.md +210 -42
  2. package/dist/boards/board-events.d.ts +34 -0
  3. package/dist/boards/board-events.d.ts.map +1 -0
  4. package/dist/boards/board-events.js +50 -0
  5. package/dist/boards/board-events.js.map +1 -0
  6. package/dist/boards/board-writes.d.ts +86 -0
  7. package/dist/boards/board-writes.d.ts.map +1 -0
  8. package/dist/boards/board-writes.js +252 -0
  9. package/dist/boards/board-writes.js.map +1 -0
  10. package/dist/boards/define-board.d.ts +16 -5
  11. package/dist/boards/define-board.d.ts.map +1 -1
  12. package/dist/boards/define-board.js +30 -8
  13. package/dist/boards/define-board.js.map +1 -1
  14. package/dist/boards/intake-routing.d.ts +30 -6
  15. package/dist/boards/intake-routing.d.ts.map +1 -1
  16. package/dist/boards/intake-routing.js +43 -5
  17. package/dist/boards/intake-routing.js.map +1 -1
  18. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  19. package/dist/boards/legacy-plan-role.js +8 -4
  20. package/dist/boards/legacy-plan-role.js.map +1 -1
  21. package/dist/boards/phase-automation.d.ts.map +1 -1
  22. package/dist/boards/phase-automation.js +7 -2
  23. package/dist/boards/phase-automation.js.map +1 -1
  24. package/dist/boards/project-boards.d.ts +18 -7
  25. package/dist/boards/project-boards.d.ts.map +1 -1
  26. package/dist/boards/project-boards.js +78 -14
  27. package/dist/boards/project-boards.js.map +1 -1
  28. package/dist/boards/stored-board.d.ts +59 -1
  29. package/dist/boards/stored-board.d.ts.map +1 -1
  30. package/dist/boards/stored-board.js +219 -7
  31. package/dist/boards/stored-board.js.map +1 -1
  32. package/dist/factory.d.ts +63 -9
  33. package/dist/factory.d.ts.map +1 -1
  34. package/dist/factory.js +187 -22
  35. package/dist/factory.js.map +1 -1
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -3
  39. package/dist/integrations/base.d.ts +6 -0
  40. package/dist/integrations/base.d.ts.map +1 -1
  41. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  42. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  43. package/dist/integrations/github/acceptance-labels.js +1 -1
  44. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  45. package/dist/integrations/github/default-rules.d.ts +2 -9
  46. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  47. package/dist/integrations/github/default-rules.js +7 -6
  48. package/dist/integrations/github/default-rules.js.map +1 -1
  49. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  50. package/dist/integrations/github/issue-reconciler.js +17 -1
  51. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  52. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  53. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  54. package/dist/integrations/github/review-status-comment.js +217 -0
  55. package/dist/integrations/github/review-status-comment.js.map +1 -0
  56. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  57. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  58. package/dist/integrations/github/review-status-reporter.js +100 -0
  59. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  60. package/dist/integrations/github/review-status.d.ts +28 -0
  61. package/dist/integrations/github/review-status.d.ts.map +1 -0
  62. package/dist/integrations/github/review-status.js +95 -0
  63. package/dist/integrations/github/review-status.js.map +1 -0
  64. package/dist/integrations/github/routes.d.ts.map +1 -1
  65. package/dist/integrations/github/routes.js +2 -5
  66. package/dist/integrations/github/routes.js.map +1 -1
  67. package/dist/integrations/github/rules.d.ts +13 -1
  68. package/dist/integrations/github/rules.d.ts.map +1 -1
  69. package/dist/integrations/github/rules.js +77 -6
  70. package/dist/integrations/github/rules.js.map +1 -1
  71. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  72. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  73. package/dist/integrations/gitlab/default-rules.js +4 -4
  74. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  75. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  76. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  77. package/dist/integrations/gitlab/routes.js +1 -3
  78. package/dist/integrations/gitlab/routes.js.map +1 -1
  79. package/dist/integrations/gitlab/rules.d.ts +16 -0
  80. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  81. package/dist/integrations/gitlab/rules.js +69 -4
  82. package/dist/integrations/gitlab/rules.js.map +1 -1
  83. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  84. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  85. package/dist/integrations/incidentio/default-rules.js +3 -4
  86. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  87. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/routes.js +1 -4
  89. package/dist/integrations/incidentio/routes.js.map +1 -1
  90. package/dist/integrations/incidentio/rules.d.ts +7 -0
  91. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  92. package/dist/integrations/incidentio/rules.js +35 -3
  93. package/dist/integrations/incidentio/rules.js.map +1 -1
  94. package/dist/integrations/jira/default-rules.d.ts +1 -9
  95. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  96. package/dist/integrations/jira/default-rules.js +3 -4
  97. package/dist/integrations/jira/default-rules.js.map +1 -1
  98. package/dist/integrations/jira/routes.d.ts.map +1 -1
  99. package/dist/integrations/jira/routes.js +1 -4
  100. package/dist/integrations/jira/routes.js.map +1 -1
  101. package/dist/integrations/jira/rules.d.ts +7 -0
  102. package/dist/integrations/jira/rules.d.ts.map +1 -1
  103. package/dist/integrations/jira/rules.js +35 -3
  104. package/dist/integrations/jira/rules.js.map +1 -1
  105. package/dist/integrations/linear/default-rules.d.ts +1 -9
  106. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/default-rules.js +3 -4
  108. package/dist/integrations/linear/default-rules.js.map +1 -1
  109. package/dist/integrations/linear/routes.d.ts.map +1 -1
  110. package/dist/integrations/linear/routes.js +1 -4
  111. package/dist/integrations/linear/routes.js.map +1 -1
  112. package/dist/integrations/linear/rules.d.ts +7 -0
  113. package/dist/integrations/linear/rules.d.ts.map +1 -1
  114. package/dist/integrations/linear/rules.js +35 -3
  115. package/dist/integrations/linear/rules.js.map +1 -1
  116. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  117. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  118. package/dist/integrations/platform/connect/routes.js +42 -5
  119. package/dist/integrations/platform/connect/routes.js.map +1 -1
  120. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  121. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  122. package/dist/integrations/platform/connect/session-tools.js +30 -0
  123. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  124. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  125. package/dist/integrations/platform/github/integration.js +1 -3
  126. package/dist/integrations/platform/github/integration.js.map +1 -1
  127. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  128. package/dist/integrations/platform/jira/routes.js +1 -4
  129. package/dist/integrations/platform/jira/routes.js.map +1 -1
  130. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  131. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  132. package/dist/integrations/platform/linear/event-worker.js +9 -0
  133. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  134. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  135. package/dist/integrations/platform/linear/integration.js +1 -3
  136. package/dist/integrations/platform/linear/integration.js.map +1 -1
  137. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  138. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  139. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  140. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  141. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  142. package/dist/integrations/slack/connect-route.js +1 -1
  143. package/dist/integrations/slack/connect-route.js.map +1 -1
  144. package/dist/integrations/slack/integration.d.ts.map +1 -1
  145. package/dist/integrations/slack/integration.js +2 -0
  146. package/dist/integrations/slack/integration.js.map +1 -1
  147. package/dist/integrations/slack/slack.d.ts +12 -10
  148. package/dist/integrations/slack/slack.d.ts.map +1 -1
  149. package/dist/integrations/slack/slack.js +110 -43
  150. package/dist/integrations/slack/slack.js.map +1 -1
  151. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  152. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  153. package/dist/integrations/slack/voice-clips.js +201 -0
  154. package/dist/integrations/slack/voice-clips.js.map +1 -0
  155. package/dist/integrations/workos/integration.d.ts.map +1 -1
  156. package/dist/integrations/workos/integration.js +1 -3
  157. package/dist/integrations/workos/integration.js.map +1 -1
  158. package/dist/mcp/routes.js +1 -1
  159. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  160. package/dist/routes/attention-activity.js +1 -1
  161. package/dist/routes/attention-providers.js +1 -1
  162. package/dist/routes/automation-runs.d.ts.map +1 -1
  163. package/dist/routes/automation-runs.js +1 -4
  164. package/dist/routes/automation-runs.js.map +1 -1
  165. package/dist/routes/boards.d.ts +8 -6
  166. package/dist/routes/boards.d.ts.map +1 -1
  167. package/dist/routes/boards.js +73 -143
  168. package/dist/routes/boards.js.map +1 -1
  169. package/dist/routes/config.d.ts.map +1 -1
  170. package/dist/routes/config.js +3 -8
  171. package/dist/routes/config.js.map +1 -1
  172. package/dist/routes/contracts.d.ts +132 -0
  173. package/dist/routes/contracts.d.ts.map +1 -1
  174. package/dist/routes/contracts.js +77 -29
  175. package/dist/routes/contracts.js.map +1 -1
  176. package/dist/routes/fs.d.ts.map +1 -1
  177. package/dist/routes/fs.js +1 -4
  178. package/dist/routes/fs.js.map +1 -1
  179. package/dist/routes/intake-routes.d.ts.map +1 -1
  180. package/dist/routes/intake-routes.js +19 -12
  181. package/dist/routes/intake-routes.js.map +1 -1
  182. package/dist/routes/intake.d.ts.map +1 -1
  183. package/dist/routes/intake.js +3 -5
  184. package/dist/routes/intake.js.map +1 -1
  185. package/dist/routes/knowledge.d.ts.map +1 -1
  186. package/dist/routes/knowledge.js +1 -4
  187. package/dist/routes/knowledge.js.map +1 -1
  188. package/dist/routes/oauth.d.ts.map +1 -1
  189. package/dist/routes/oauth.js +1 -4
  190. package/dist/routes/oauth.js.map +1 -1
  191. package/dist/routes/projects.d.ts +3 -0
  192. package/dist/routes/projects.d.ts.map +1 -1
  193. package/dist/routes/projects.js +7 -4
  194. package/dist/routes/projects.js.map +1 -1
  195. package/dist/routes/provider-credentials.d.ts.map +1 -1
  196. package/dist/routes/provider-credentials.js +6 -0
  197. package/dist/routes/provider-credentials.js.map +1 -1
  198. package/dist/routes/route.d.ts +2 -0
  199. package/dist/routes/route.d.ts.map +1 -1
  200. package/dist/routes/route.js +5 -1
  201. package/dist/routes/route.js.map +1 -1
  202. package/dist/routes/skills.d.ts.map +1 -1
  203. package/dist/routes/skills.js +1 -4
  204. package/dist/routes/skills.js.map +1 -1
  205. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  206. package/dist/routes/source-control-sessions.js +1 -3
  207. package/dist/routes/source-control-sessions.js.map +1 -1
  208. package/dist/routes/source-control-settings.d.ts.map +1 -1
  209. package/dist/routes/source-control-settings.js +3 -2
  210. package/dist/routes/source-control-settings.js.map +1 -1
  211. package/dist/routes/surface.d.ts +3 -1
  212. package/dist/routes/surface.d.ts.map +1 -1
  213. package/dist/routes/surface.js +11 -1
  214. package/dist/routes/surface.js.map +1 -1
  215. package/dist/routes/voice.d.ts +48 -0
  216. package/dist/routes/voice.d.ts.map +1 -0
  217. package/dist/routes/voice.js +248 -0
  218. package/dist/routes/voice.js.map +1 -0
  219. package/dist/routes/work-items.d.ts.map +1 -1
  220. package/dist/routes/work-items.js +1 -4
  221. package/dist/routes/work-items.js.map +1 -1
  222. package/dist/rules/decision-applicability.js +1 -1
  223. package/dist/rules/dispatcher.d.ts +28 -0
  224. package/dist/rules/dispatcher.d.ts.map +1 -1
  225. package/dist/rules/dispatcher.js +391 -93
  226. package/dist/rules/dispatcher.js.map +1 -1
  227. package/dist/rules/event-rules.d.ts +40 -1
  228. package/dist/rules/event-rules.d.ts.map +1 -1
  229. package/dist/rules/event-rules.js +59 -1
  230. package/dist/rules/event-rules.js.map +1 -1
  231. package/dist/rules/processor.js +1 -1
  232. package/dist/rules/processor.js.map +1 -1
  233. package/dist/rules/transition-service.d.ts +9 -0
  234. package/dist/rules/transition-service.d.ts.map +1 -1
  235. package/dist/rules/transition-service.js +4 -2
  236. package/dist/rules/transition-service.js.map +1 -1
  237. package/dist/rules/types.d.ts +54 -3
  238. package/dist/rules/types.d.ts.map +1 -1
  239. package/dist/rules/types.js +2 -0
  240. package/dist/rules/types.js.map +1 -1
  241. package/dist/rules/validation.d.ts.map +1 -1
  242. package/dist/rules/validation.js +57 -2
  243. package/dist/rules/validation.js.map +1 -1
  244. package/dist/session/credential-policy.d.ts +2 -2
  245. package/dist/session/credential-policy.d.ts.map +1 -1
  246. package/dist/session/credential-policy.js +3 -3
  247. package/dist/session/credential-policy.js.map +1 -1
  248. package/dist/session/default-model-hydration.d.ts +2 -2
  249. package/dist/session/default-model-hydration.d.ts.map +1 -1
  250. package/dist/session/default-model-hydration.js +4 -4
  251. package/dist/session/default-model-hydration.js.map +1 -1
  252. package/dist/session/session-threads.d.ts +8 -0
  253. package/dist/session/session-threads.d.ts.map +1 -1
  254. package/dist/session/session-threads.js +11 -1
  255. package/dist/session/session-threads.js.map +1 -1
  256. package/dist/skills/catalog.js +1 -1
  257. package/dist/storage/domains/audit/actions.d.ts +1 -1
  258. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  259. package/dist/storage/domains/audit/actions.js +2 -1
  260. package/dist/storage/domains/audit/actions.js.map +1 -1
  261. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  262. package/dist/storage/domains/audit/domain.js +1 -3
  263. package/dist/storage/domains/audit/domain.js.map +1 -1
  264. package/dist/storage/domains/boards/base.d.ts +32 -1
  265. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  266. package/dist/storage/domains/boards/base.js +155 -8
  267. package/dist/storage/domains/boards/base.js.map +1 -1
  268. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  269. package/dist/storage/domains/boards/schemas.js +13 -1
  270. package/dist/storage/domains/boards/schemas.js.map +1 -1
  271. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  272. package/dist/storage/domains/comments/routes.js +1 -3
  273. package/dist/storage/domains/comments/routes.js.map +1 -1
  274. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  275. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  276. package/dist/storage/domains/memory-settings/base.js +1 -11
  277. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  278. package/dist/storage/domains/projects/base.d.ts +6 -0
  279. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  280. package/dist/storage/domains/projects/base.js +9 -1
  281. package/dist/storage/domains/projects/base.js.map +1 -1
  282. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  283. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  284. package/dist/storage/domains/voice-settings/base.js +81 -0
  285. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  286. package/dist/storage/domains/work-items/base.d.ts +31 -2
  287. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  288. package/dist/storage/domains/work-items/base.js +197 -44
  289. package/dist/storage/domains/work-items/base.js.map +1 -1
  290. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  291. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  292. package/dist/storage/domains/work-items/cards.js +54 -4
  293. package/dist/storage/domains/work-items/cards.js.map +1 -1
  294. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  295. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  296. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  297. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  298. package/dist/timing.d.ts +1 -0
  299. package/dist/timing.d.ts.map +1 -1
  300. package/dist/timing.js +1 -1
  301. package/dist/timing.js.map +1 -1
  302. package/dist/tools/read-tools.d.ts +2 -2
  303. package/dist/tools/read-tools.d.ts.map +1 -1
  304. package/dist/tools/read-tools.js +7 -6
  305. package/dist/tools/read-tools.js.map +1 -1
  306. package/dist/tools/session-tools.d.ts +1 -1
  307. package/dist/tools/session-tools.d.ts.map +1 -1
  308. package/dist/tools/session-tools.js.map +1 -1
  309. package/dist/tools/sessions-state-processor.d.ts +1 -1
  310. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  311. package/dist/tools/sessions-state-processor.js +9 -2
  312. package/dist/tools/sessions-state-processor.js.map +1 -1
  313. package/dist/tools/work-item-tools.js +2 -2
  314. package/dist/voice/rate-limit.d.ts +13 -0
  315. package/dist/voice/rate-limit.d.ts.map +1 -0
  316. package/dist/voice/rate-limit.js +36 -0
  317. package/dist/voice/rate-limit.js.map +1 -0
  318. package/dist/voice/realtime.d.ts +13 -0
  319. package/dist/voice/realtime.d.ts.map +1 -0
  320. package/dist/voice/realtime.js +56 -0
  321. package/dist/voice/realtime.js.map +1 -0
  322. package/dist/voice/transcription.d.ts +51 -0
  323. package/dist/voice/transcription.d.ts.map +1 -0
  324. package/dist/voice/transcription.js +112 -0
  325. package/dist/voice/transcription.js.map +1 -0
  326. package/dist/work-items/split-backfill.d.ts +13 -0
  327. package/dist/work-items/split-backfill.d.ts.map +1 -0
  328. package/dist/work-items/split-backfill.js +32 -0
  329. package/dist/work-items/split-backfill.js.map +1 -0
  330. package/dist/work-items/split-migration.d.ts +39 -2
  331. package/dist/work-items/split-migration.d.ts.map +1 -1
  332. package/dist/work-items/split-migration.js +170 -62
  333. package/dist/work-items/split-migration.js.map +1 -1
  334. package/dist/workspace.js +2 -2
  335. package/package.json +9 -8
@@ -1,10 +1,10 @@
1
1
  import "../boards/index.js";
2
- import { INTAKE_ROUTE_METADATA_KEY, landingPhase, placedByIntakeRoute, resolveIntakePlacement } from "../boards/intake-routing.js";
2
+ import { INTAKE_ROUTE_METADATA_KEY, landingPhase, placedByIntakeRoute, resolveEventRoute, resolveIntakePlacement, routesHandleEvent } from "../boards/intake-routing.js";
3
+ import { boardForWorkItem, isPullRequestCard, isTerminalWorkItem, pullRequestReviewPhase, resolvePhaseSemantics, reviewsPullRequest, workItemPhaseSemantics } from "../boards/semantics.js";
3
4
  import { autoApprovedExitTool, startsInAutoPhase } from "../boards/phase-automation.js";
4
5
  import { toBoardSource } from "../boards/project-boards.js";
5
6
  import { moveCardToBoard } from "../boards/relocate.js";
6
7
  import { cardRuleFacts } from "../boards/card-facts.js";
7
- import { boardForWorkItem, isPullRequestCard, isTerminalWorkItem, pullRequestReviewPhase, resolvePhaseSemantics, reviewsPullRequest, workItemPhaseSemantics } from "../boards/semantics.js";
8
8
  import { FACTORY_OPEN_RUN_STALE_MS, heartbeatSessionOpenRun, isOpenRunLiveElsewhere, listSessionOpenRuns, recordSessionRunStart, waitForSessionRunAudit } from "../session/run-audit.js";
9
9
  import { resolvePromptInvocation, resolveSkillInvocation, resolveSkillResumeInvocation } from "../skills/service.js";
10
10
  import { isHumanActorId } from "../storage/domains/audit/actors.js";
@@ -13,12 +13,15 @@ import { FACTORY_RULE_MATERIALIZATION_KEY } from "../storage/domains/work-items/
13
13
  import { workItemProviderAdapter } from "../work-items/providers/index.js";
14
14
  import { decisionOvertaken } from "./decision-applicability.js";
15
15
  import { FactoryDispatchError, factoryDispatchFailureCode, factoryDispatchFailureMetadata } from "./dispatch-errors.js";
16
+ import { isStatusEventDecision } from "./event-rules.js";
16
17
  import { FACTORY_RULE_STAGES, externalSourceForWorkItem, workItemSource } from "./types.js";
17
18
  import { assertFactoryDecisionTarget, validateFactoryRuleDecision } from "./validation.js";
18
19
  import { RequestContext } from "@mastra/core/request-context";
19
20
  import { PROVIDER_CALL_ERROR_NAME, classifyProviderError } from "@mastra/core/error";
20
21
  // src/rules/dispatcher.ts
21
22
  const LEASE_MS = 3e4;
23
+ /** How long the run waits on a status-comment write; well inside one lease so a slow provider never costs the claim. */
24
+ const REVIEW_STATUS_TIMEOUT_MS = 1e4;
22
25
  const POLL_MS = 1e3;
23
26
  const IDLE_RECHECK_MS = 36e5;
24
27
  const BATCH_SIZE = 10;
@@ -30,11 +33,12 @@ const RUN_REGISTRY_HEARTBEAT_MS = 6e5;
30
33
  const SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS = 216e5;
31
34
  const MAX_IN_FLIGHT = 25;
32
35
  /**
33
- * Decisions that may start or wake an agent run and so hold a run slot. A
34
- * transition's message is queued as a separate sendMessage, so the transition
35
- * itself stays bookkeeping.
36
+ * Decisions that may start or wake an agent run, or wait for one to end, and so
37
+ * hold a run slot. A transition's message is queued as a separate sendMessage,
38
+ * so a transition stays bookkeeping, and so does a status event's route move:
39
+ * it never waits for a run inline, it hands itself back until the run ends.
36
40
  */
37
- const isRunBearingDecision = (decision) => decision.type === "invokeSkill" || decision.type === "sendMessage";
41
+ const isRunBearingDecision = (decision) => decision.type === "invokeSkill" || decision.type === "sendMessage" || decision.type === "signalActivity";
38
42
  const isBookkeepingDecision = (decision) => !isRunBearingDecision(decision);
39
43
  const BOOKKEEPING_MAX_IN_FLIGHT = 4;
40
44
  const STALE_BINDING_SWEEP_INTERVAL_MS = 6e5;
@@ -42,6 +46,9 @@ const STALE_BINDING_TTL_MS = 864e5;
42
46
  const RECONCILE_INTERVAL_MS = 3e4;
43
47
  /** The card moved on before this run could act; it settles as superseded, not succeeded. */
44
48
  var FactoryDecisionSuperseded = class extends Error {};
49
+ /** The decision cannot act yet and did nothing: it goes back to the queue and is claimed again later. */
50
+ var FactoryDecisionPostponed = class extends Error {};
51
+ const POSTPONE_MS = 1e4;
45
52
  /** A run that ran and ended in error; the session's own listener reports it to followers. */
46
53
  var RunEndedInError = class extends FactoryDispatchError {};
47
54
  const CREDENTIAL_RESOLUTION_FAILURE = "tenant model credential policy could not be resolved";
@@ -71,6 +78,12 @@ function runErrorFailure(label, error) {
71
78
  if (!cause) return new RunEndedInError("run_failed", `${label} ended in error.`);
72
79
  return new RunEndedInError(runErrorCode(error, cause), `${label} ended in error: ${cause}`);
73
80
  }
81
+ /** A pull request review run: the only runs that keep a status comment on the pull request. */
82
+ function isReviewRun(decision) {
83
+ if (!decision || typeof decision !== "object") return false;
84
+ const value = decision;
85
+ return value.type === "invokeSkill" && value.role === "review";
86
+ }
74
87
  function isTerminalFailure(attempts, failureCode) {
75
88
  return attempts >= MAX_ATTEMPTS || !factoryDispatchFailureMetadata(failureCode).canRetry;
76
89
  }
@@ -85,7 +98,7 @@ function isPermanentProviderRejection(error) {
85
98
  const normalized = error.toLowerCase();
86
99
  return /\bhttp(?:\/\d(?:\.\d)?)?\s*400\b/.test(normalized) || /\bstatus(?:\s*code)?\s*[:=]?\s*400\b/.test(normalized) || /\b400\s*(?:bad request|status)\b/.test(normalized) || normalized.includes("model not supported") || normalized.includes("model is not supported") || normalized.includes("unsupported model") || normalized.includes("not supported with") || normalized.includes("unauthorized") || normalized.includes("authentication") || normalized.includes("invalid") && normalized.includes("model");
87
100
  }
88
- function watchRun(session, { timeoutMs, approvePlans, onAgentEnd, label, runStillActive }) {
101
+ function watchRun(session, { timeoutMs, approvePlans, requestContext, onAgentEnd, label, runStillActive }) {
89
102
  let resolveAgentEnd;
90
103
  let agentEnd;
91
104
  let endReason;
@@ -153,7 +166,8 @@ function watchRun(session, { timeoutMs, approvePlans, onAgentEnd, label, runStil
153
166
  arm();
154
167
  await session.respondToToolSuspension({
155
168
  resumeData: { action: "approved" },
156
- toolCallId
169
+ toolCallId,
170
+ requestContext
157
171
  });
158
172
  observed = await wait();
159
173
  }
@@ -305,6 +319,19 @@ var FactoryDecisionDispatcher = class {
305
319
  #reportRunEnd;
306
320
  #feedReader;
307
321
  #dismissStaleReviews;
322
+ #reportReviewStatus;
323
+ /** Review attempts that already said `queued`, and those that watched their run start. */
324
+ #reviewQueued = /* @__PURE__ */ new WeakSet();
325
+ #reviewWatched = /* @__PURE__ */ new WeakSet();
326
+ /** Re-claims that found an earlier attempt's kickoff landed and its run already over. */
327
+ #reviewReplayed = /* @__PURE__ */ new WeakSet();
328
+ /** Last pending status-comment write per run, so writes stay ordered. */
329
+ /**
330
+ * Per review run: the write chain, the newest step issued, and how many
331
+ * writes were issued and how far the landed ones reach, so a write that
332
+ * outlived its wait and landed after a newer one can be repaired.
333
+ */
334
+ #reviewStatusRuns = /* @__PURE__ */ new Map();
308
335
  #resolveLinkedWorkItemParentId;
309
336
  #factoryProjectExists;
310
337
  #maxInFlight;
@@ -347,6 +374,7 @@ var FactoryDecisionDispatcher = class {
347
374
  this.#reportRunEnd = options.reportRunEnd;
348
375
  this.#feedReader = options.feedReader;
349
376
  this.#dismissStaleReviews = options.dismissStaleReviews;
377
+ this.#reportReviewStatus = options.reportReviewStatus;
350
378
  this.#resolveLinkedWorkItemParentId = options.resolveLinkedWorkItemParentId;
351
379
  this.#factoryProjectExists = options.factoryProjectExists;
352
380
  const maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT;
@@ -576,12 +604,26 @@ var FactoryDecisionDispatcher = class {
576
604
  return;
577
605
  }
578
606
  await this.#supersedeProposals(record, decision);
607
+ if (record.attempts <= 1) await this.#reviewQueuedOnce(record, decision);
579
608
  await this.#withLease(async (leaseExpiresAt) => this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt), async () => this.#executeDecision(record, decision));
580
609
  executionCompleted = true;
581
610
  if (!await this.#storage.completeDeferredDecision(leaseIdentity(record, this.#ownerId), /* @__PURE__ */ new Date())) throw new Error("Factory decision lease was lost before completion.");
611
+ if (this.#reviewWatched.has(record) || this.#reviewReplayed.has(record)) await this.#reviewStatus(record, decision, {
612
+ phase: "completed",
613
+ endedAt: /* @__PURE__ */ new Date(),
614
+ ...this.#reviewReplayed.has(record) ? { replayed: true } : {}
615
+ });
582
616
  } catch (error) {
583
617
  if (error instanceof FactoryDecisionSuperseded) {
584
618
  await this.#storage.supersedeLeasedDecision(leaseIdentity(record, this.#ownerId), /* @__PURE__ */ new Date());
619
+ await this.#reviewStatus(record, record.decision, {
620
+ phase: "cancelled",
621
+ endedAt: /* @__PURE__ */ new Date()
622
+ });
623
+ return;
624
+ }
625
+ if (error instanceof FactoryDecisionPostponed) {
626
+ await this.#storage.postponeDeferredDecision(leaseIdentity(record, this.#ownerId), new Date(now.getTime() + POSTPONE_MS), /* @__PURE__ */ new Date());
585
627
  return;
586
628
  }
587
629
  const failureCode = factoryDispatchFailureCode(error);
@@ -596,6 +638,88 @@ var FactoryDecisionDispatcher = class {
596
638
  advanceDeliveryGeneration: !executionCompleted
597
639
  });
598
640
  if (terminal && failed) await this.#supersedeFailureOnSettledCard(failed);
641
+ if (terminal || this.#reviewQueued.has(record)) await this.#reviewStatus(failed ?? record, record.decision, {
642
+ phase: terminal ? "failed" : "retrying",
643
+ endedAt: /* @__PURE__ */ new Date(),
644
+ reason: factoryDispatchFailureMetadata(failureCode).label
645
+ });
646
+ }
647
+ }
648
+ /**
649
+ * An earlier attempt's kickoff already landed, so this attempt only has to
650
+ * see that run end before a review's status can be finalized. The open-run
651
+ * wait covers runs in the ledger; a run that landed but died before
652
+ * registering there can still be live in this process, so wait it out too.
653
+ */
654
+ async #replayLanded(record, decision, session, runStillActive) {
655
+ if (!isReviewRun(decision)) return;
656
+ if (runStillActive()) {
657
+ const run = watchRun(session, {
658
+ timeoutMs: this.#skillCompletionObservationTimeoutMs,
659
+ approvePlans: false,
660
+ label: "Factory skill run",
661
+ runStillActive
662
+ });
663
+ try {
664
+ if (runStillActive()) await run.wait();
665
+ } finally {
666
+ run.close();
667
+ }
668
+ }
669
+ this.#reviewReplayed.add(record);
670
+ }
671
+ async #reviewQueuedOnce(record, decision) {
672
+ if (this.#reviewQueued.has(record)) return;
673
+ this.#reviewQueued.add(record);
674
+ await this.#reviewStatus(record, decision, { phase: "queued" });
675
+ }
676
+ /** Best-effort: a status comment is never worth failing or delaying the review it describes. */
677
+ async #reviewStatus(record, decision, step) {
678
+ const report = this.#reportReviewStatus;
679
+ if (!report || !record.workItemId || !isReviewRun(decision)) return;
680
+ const event = {
681
+ orgId: record.orgId,
682
+ factoryProjectId: record.factoryProjectId,
683
+ workItemId: record.workItemId,
684
+ run: record.id,
685
+ requestedAt: record.createdAt,
686
+ generation: record.deliveryGeneration,
687
+ attempt: record.attempts,
688
+ ...step
689
+ };
690
+ const run = this.#reviewStatusRuns.get(record.id) ?? {
691
+ tail: Promise.resolve(),
692
+ issued: 0,
693
+ landed: 0,
694
+ latest: event
695
+ };
696
+ this.#reviewStatusRuns.set(record.id, run);
697
+ const previous = run.tail;
698
+ const seq = ++run.issued;
699
+ run.latest = event;
700
+ const send = (next) => report(next).catch((error) => {
701
+ console.warn("Factory review status update failed", sanitizeDispatchError(error));
702
+ });
703
+ let waited;
704
+ const delivered = Promise.race([previous, new Promise((resolve) => {
705
+ waited = setTimeout(resolve, REVIEW_STATUS_TIMEOUT_MS);
706
+ })]).finally(() => clearTimeout(waited)).then(async () => {
707
+ await send(event);
708
+ if (run.landed > seq) await send(run.latest);
709
+ run.landed = Math.max(run.landed, seq);
710
+ });
711
+ run.tail = delivered;
712
+ delivered.then(() => {
713
+ if (run.tail === delivered && run.landed >= run.issued && this.#reviewStatusRuns.get(record.id) === run) this.#reviewStatusRuns.delete(record.id);
714
+ });
715
+ let timer;
716
+ const timedOut = new Promise((resolve) => {
717
+ timer = setTimeout(() => resolve("timeout"), REVIEW_STATUS_TIMEOUT_MS);
718
+ });
719
+ try {
720
+ if (await Promise.race([delivered, timedOut]) === "timeout") console.warn(`Factory review status update (${step.phase}) still pending; continuing the run without it`);
721
+ } finally {
722
+ clearTimeout(timer);
599
723
  }
600
724
  }
601
725
  /** Terminal cleanup ran before this failure landed, so it never saw this row. */
@@ -661,72 +785,13 @@ var FactoryDecisionDispatcher = class {
661
785
  }];
662
786
  if (nextChain.length > 8) throw new Error("Factory rule causal depth exceeded.");
663
787
  switch (decision.type) {
664
- case "transition": {
665
- const item = await this.#requireItem(record);
666
- if (!await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, `decision:${record.idempotencyKey}`)) assertFactoryDecisionTarget(decision, await this.#boards.load(record), item.board ?? void 0);
667
- const result = await this.#transitionService.transition({
668
- orgId: record.orgId,
669
- factoryProjectId: record.factoryProjectId,
670
- workItemId: item.id,
671
- board: decision.board,
672
- stage: decision.stage,
673
- expectedRevision: item.revision,
674
- actor: record.approvedBy ? {
675
- type: "human",
676
- id: record.approvedBy
677
- } : {
678
- type: "system",
679
- id: "factory-rule-dispatcher"
680
- },
681
- ingress: {
682
- type: "rule",
683
- identity: `decision:${record.idempotencyKey}`
684
- },
685
- cause: "rule_decision",
686
- causalChain: nextChain,
687
- ...decision.reenter ? { reenter: true } : {}
688
- });
689
- if (result.status === "rejected") throw new Error(`${result.code}: ${result.reason}`);
690
- const transitionMessage = decision.message;
691
- if (!transitionMessage) return;
692
- const moved = await this.#storage.get({
693
- orgId: record.orgId,
694
- id: item.id
695
- });
696
- if (!moved) return;
697
- const messageKey = `${record.idempotencyKey}:message`;
698
- const queued = await this.#storage.commitRuleEvaluation({
699
- orgId: record.orgId,
700
- factoryProjectId: record.factoryProjectId,
701
- workItemId: item.id,
702
- ingress: {
703
- identity: `decision:${messageKey}@${moved.revision}`,
704
- triggerType: "transition.message"
705
- },
706
- configVersion: this.#transitionService.configVersion,
707
- expectedRevision: moved.revision,
708
- actor: record.actor ?? {
709
- type: "system",
710
- id: "factory-rule-dispatcher"
711
- },
712
- outcome: { status: "accepted" },
713
- decisions: [{
714
- type: "sendMessage",
715
- idempotencyKey: messageKey,
716
- message: transitionMessage.text,
717
- priority: "high",
718
- idleBehavior: "wake",
719
- ...transitionMessage.role !== void 0 ? { role: transitionMessage.role } : {}
720
- }],
721
- causalChain: nextChain,
722
- now: /* @__PURE__ */ new Date()
723
- });
724
- if (queued.status === "missing") return;
725
- if (queued.status === "stale") throw new Error("Factory transition message was not queued: the work item changed concurrently.");
726
- const queuedStatus = queued.result.status;
727
- if (queuedStatus !== "accepted") throw new Error(`Factory transition message was not queued: ${queuedStatus ?? "unknown"}.`);
788
+ case "transition":
789
+ if (decision.event) await this.#routeEvent(record, decision.event, nextChain, decision);
790
+ else await this.#applyTransition(record, decision, nextChain);
791
+ return;
792
+ case "routeEvent":
793
+ await this.#routeEvent(record, decision.event, nextChain);
728
794
  return;
729
- }
730
795
  case "upsertLinkedWorkItem":
731
796
  await this.#upsertLinkedItem(record, decision, nextChain);
732
797
  return;
@@ -768,27 +833,10 @@ var FactoryDecisionDispatcher = class {
768
833
  const kickoffLanded = async () => (await session.thread.listActiveMessages()).some((message) => message.id === deliveryId);
769
834
  const kickoffStale = async () => await this.#roleSuperseded(record, decision.role) || (await this.#findBinding(record, decision.role))?.id !== binding.id || await this.#decisionOvertaken(record, decision.role);
770
835
  const runStillActive = () => this.#controller.listActiveThreadRuns().some((active) => active.threadId === binding.threadId);
771
- while (true) {
772
- const openRun = watchRun(session, {
773
- timeoutMs: this.#skillCompletionObservationTimeoutMs,
774
- approvePlans: false,
775
- label: "Factory skill run",
776
- runStillActive
777
- });
778
- try {
779
- const open = (await listSessionOpenRuns(session)).filter((entry) => entry.bindingId === binding.id);
780
- if (open.length === 0) break;
781
- if (open.some((entry) => isOpenRunLiveElsewhere(entry, this.#ownerId))) throw new FactoryDispatchError("session_unavailable", `Factory binding ${binding.id} has a run in flight on another dispatcher.`);
782
- if (!runStillActive()) break;
783
- if (!await openRun.wait()) break;
784
- } finally {
785
- openRun.close();
786
- }
787
- await waitForSessionRunAudit(session);
788
- }
836
+ await this.#waitForOpenRun(session, binding, "Factory skill run");
789
837
  if (await this.#roleSuperseded(record, decision.role)) throw new FactoryDecisionSuperseded();
790
838
  if ((await this.#requireBinding(record, decision.role)).id !== binding.id) throw new FactoryDispatchError("session_unavailable", `Factory binding ${binding.id} changed while waiting for its open run to end.`);
791
- if (await kickoffLanded()) return;
839
+ if (await kickoffLanded()) return this.#replayLanded(record, decision, session, runStillActive);
792
840
  if (await kickoffStale()) throw new FactoryDecisionSuperseded();
793
841
  const kickoffContents = await withWorkItemFeed(this.#feedReader, {
794
842
  orgId: record.orgId,
@@ -803,8 +851,9 @@ var FactoryDecisionDispatcher = class {
803
851
  type: "user",
804
852
  tagName: "user"
805
853
  };
806
- if (await kickoffLanded()) return;
854
+ if (await kickoffLanded()) return this.#replayLanded(record, decision, session, runStillActive);
807
855
  if (await kickoffStale()) throw new FactoryDecisionSuperseded();
856
+ await this.#reviewQueuedOnce(record, decision);
808
857
  if (decision.cancelInFlight && session.stream.isActive()) session.abort();
809
858
  const precedingMessage = decision.precedingMessage;
810
859
  if (precedingMessage) {
@@ -827,6 +876,7 @@ var FactoryDecisionDispatcher = class {
827
876
  const run = watchRun(session, {
828
877
  timeoutMs: this.#skillCompletionObservationTimeoutMs,
829
878
  approvePlans: await this.#plansAreAutoApproved(record),
879
+ requestContext,
830
880
  onAgentEnd: () => this.#roleSuperseded(record, decision.role),
831
881
  label: "Factory skill run",
832
882
  runStillActive
@@ -854,6 +904,11 @@ var FactoryDecisionDispatcher = class {
854
904
  settled = await sendKickoff();
855
905
  }
856
906
  await this.#recordRunStart(session, binding, deliveryId, record.approvedBy ?? void 0, run.endReason, item?.title);
907
+ this.#reviewWatched.add(record);
908
+ await this.#reviewStatus(record, decision, {
909
+ phase: "reviewing",
910
+ startedAt: since
911
+ });
857
912
  try {
858
913
  await this.#reportingRunEnd({
859
914
  binding,
@@ -862,8 +917,20 @@ var FactoryDecisionDispatcher = class {
862
917
  attempts: record.attempts,
863
918
  superseded: async () => await run.supersededAtEnd() ?? await this.#roleSuperseded(record, decision.role)
864
919
  }, () => this.#withOpenRunHeartbeat(session, deliveryId, () => run.settle()));
920
+ if (await run.supersededAtEnd()) {
921
+ this.#reviewWatched.delete(record);
922
+ await this.#reviewStatus(record, decision, {
923
+ phase: "cancelled",
924
+ endedAt: /* @__PURE__ */ new Date()
925
+ });
926
+ }
865
927
  } catch (error) {
866
928
  if (!(await run.supersededAtEnd() ?? await this.#roleSuperseded(record, decision.role))) throw error;
929
+ this.#reviewWatched.delete(record);
930
+ await this.#reviewStatus(record, decision, {
931
+ phase: "cancelled",
932
+ endedAt: /* @__PURE__ */ new Date()
933
+ });
867
934
  }
868
935
  } finally {
869
936
  run.close();
@@ -905,6 +972,9 @@ var FactoryDecisionDispatcher = class {
905
972
  }), true);
906
973
  return;
907
974
  }
975
+ case "signalActivity":
976
+ await this.#signalActivity(record, decision);
977
+ return;
908
978
  case "dismissStaleReviews":
909
979
  if (!this.#dismissStaleReviews) throw new Error("GitHub review dismissal is not configured.");
910
980
  await this.#dismissStaleReviews(decision);
@@ -1161,6 +1231,156 @@ var FactoryDecisionDispatcher = class {
1161
1231
  stage: board.initialPhase
1162
1232
  };
1163
1233
  }
1234
+ /** Moves the card as a rule decided, then queues the decision's message for the card's session. */
1235
+ async #applyTransition(record, decision, nextChain) {
1236
+ const item = await this.#requireItem(record);
1237
+ if (!await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, `decision:${record.idempotencyKey}`)) assertFactoryDecisionTarget(decision, await this.#boards.load(record), item.board ?? void 0);
1238
+ const result = await this.#transitionService.transition({
1239
+ orgId: record.orgId,
1240
+ factoryProjectId: record.factoryProjectId,
1241
+ workItemId: item.id,
1242
+ board: decision.board,
1243
+ stage: decision.stage,
1244
+ expectedRevision: item.revision,
1245
+ actor: record.approvedBy ? {
1246
+ type: "human",
1247
+ id: record.approvedBy
1248
+ } : {
1249
+ type: "system",
1250
+ id: "factory-rule-dispatcher"
1251
+ },
1252
+ ingress: {
1253
+ type: "rule",
1254
+ identity: `decision:${record.idempotencyKey}`
1255
+ },
1256
+ cause: "rule_decision",
1257
+ causalChain: nextChain,
1258
+ ...decision.reenter ? { reenter: true } : {}
1259
+ });
1260
+ if (result.status === "rejected") throw new Error(`${result.code}: ${result.reason}`);
1261
+ const transitionMessage = decision.message;
1262
+ if (!transitionMessage) return;
1263
+ const moved = await this.#storage.get({
1264
+ orgId: record.orgId,
1265
+ id: item.id
1266
+ });
1267
+ if (!moved) return;
1268
+ const messageKey = `${record.idempotencyKey}:message`;
1269
+ const queued = await this.#storage.commitRuleEvaluation({
1270
+ orgId: record.orgId,
1271
+ factoryProjectId: record.factoryProjectId,
1272
+ workItemId: item.id,
1273
+ ingress: {
1274
+ identity: `decision:${messageKey}@${moved.revision}`,
1275
+ triggerType: "transition.message"
1276
+ },
1277
+ configVersion: this.#transitionService.configVersion,
1278
+ expectedRevision: moved.revision,
1279
+ actor: record.actor ?? {
1280
+ type: "system",
1281
+ id: "factory-rule-dispatcher"
1282
+ },
1283
+ outcome: { status: "accepted" },
1284
+ decisions: [{
1285
+ type: "sendMessage",
1286
+ idempotencyKey: messageKey,
1287
+ message: transitionMessage.text,
1288
+ priority: "high",
1289
+ idleBehavior: "wake",
1290
+ ...transitionMessage.role !== void 0 ? { role: transitionMessage.role } : {}
1291
+ }],
1292
+ causalChain: nextChain,
1293
+ now: /* @__PURE__ */ new Date()
1294
+ });
1295
+ if (queued.status === "missing") return;
1296
+ if (queued.status === "stale") throw new Error("Factory transition message was not queued: the work item changed concurrently.");
1297
+ const queuedStatus = queued.result.status;
1298
+ if (queuedStatus !== "accepted") throw new Error(`Factory transition message was not queued: ${queuedStatus ?? "unknown"}.`);
1299
+ }
1300
+ /**
1301
+ * Moves a card where the project's intake routes send it on a status event. A move into a
1302
+ * working or resting phase waits for the run in flight on the card to end, going back to the
1303
+ * queue without holding a dispatch slot until it has; a move into a
1304
+ * terminal phase does not, so terminal cleanup stops that run at once, as a close always has.
1305
+ * A close moves only an unfinished card and a reopen only a finished one. When no route on the
1306
+ * card's board handles the event at all, the rule's own move (a board's `sourceClosed` phase)
1307
+ * applies instead; when one does but none matches, the card stays. A route's move is a system
1308
+ * move by the route: recorded in the card's history and audit, keyed so a replayed delivery
1309
+ * moves nothing twice.
1310
+ */
1311
+ async #routeEvent(record, event, causalChain, fallback) {
1312
+ const identity = `event-route:${record.idempotencyKey}`;
1313
+ if (await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, identity)) return;
1314
+ if (await this.#statusEventOvertaken(record)) throw new FactoryDecisionSuperseded();
1315
+ const resolve = async () => {
1316
+ const item = await this.#requireItem(record);
1317
+ const board = (await this.#boards.load(record)).get(boardForWorkItem(item));
1318
+ if (!board) return void 0;
1319
+ const stage = item.stages.length === 1 ? item.stages[0] : void 0;
1320
+ const finished = stage !== void 0 && board.isTerminal(stage);
1321
+ if (event.type === "work_item.closed" ? finished : !finished) return void 0;
1322
+ const routes = this.#intakeRoutes ? await this.#intakeRoutes.listIntakeRoutes({
1323
+ orgId: record.orgId,
1324
+ factoryProjectId: record.factoryProjectId
1325
+ }) : [];
1326
+ if (!routesHandleEvent(routes, event, board)) return {
1327
+ item,
1328
+ board,
1329
+ fallback: true
1330
+ };
1331
+ const route = resolveEventRoute(routes, event, cardRuleFacts(item), board);
1332
+ if (!route || stage === route.phase) return void 0;
1333
+ return {
1334
+ item,
1335
+ board,
1336
+ route
1337
+ };
1338
+ };
1339
+ const first = await resolve();
1340
+ if (!first) return;
1341
+ if ("fallback" in first) {
1342
+ if (fallback) await this.#applyTransition(record, fallback, causalChain);
1343
+ return;
1344
+ }
1345
+ if (!first.board.isTerminal(first.route.phase)) {
1346
+ const binding = await this.#findBinding(record);
1347
+ const session = binding ? await this.#findSession(binding) : void 0;
1348
+ if (binding && session && await this.#hasRunInFlight(session, binding)) throw new FactoryDecisionPostponed();
1349
+ }
1350
+ const { item, board, route } = first;
1351
+ const result = await this.#transitionService.transition({
1352
+ orgId: record.orgId,
1353
+ factoryProjectId: record.factoryProjectId,
1354
+ workItemId: item.id,
1355
+ board: board.id,
1356
+ stage: route.phase,
1357
+ expectedRevision: item.revision,
1358
+ actor: {
1359
+ type: "system",
1360
+ id: `intake-route:${route.routeId}`
1361
+ },
1362
+ ingress: {
1363
+ type: "rule",
1364
+ identity
1365
+ },
1366
+ cause: "event_route",
1367
+ causalChain,
1368
+ eventRoute: {
1369
+ routeId: route.routeId,
1370
+ allowWorkingPhase: route.allowWorkingPhase
1371
+ }
1372
+ });
1373
+ if (result.status === "rejected" && result.code === "stale") throw new Error(`${result.code}: ${result.reason}`);
1374
+ }
1375
+ /**
1376
+ * Whether a later status event was queued for the same card: the source's last word wins, so a
1377
+ * close still queued when the issue is reopened moves nothing. Of events queued in the same
1378
+ * millisecond, the one with the greatest id is the last; one already settled had its turn.
1379
+ */
1380
+ async #statusEventOvertaken(record) {
1381
+ if (!record.workItemId) return false;
1382
+ return (await this.#storage.listDeferredDecisions(record.orgId, record.factoryProjectId, { workItemId: record.workItemId })).some((other) => other.id !== record.id && isStatusEventDecision(other.decision) && (other.createdAt.getTime() > record.createdAt.getTime() || other.createdAt.getTime() === record.createdAt.getTime() && other.completedAt === null && other.id > record.id));
1383
+ }
1164
1384
  async #requireItem(record) {
1165
1385
  if (!record.workItemId) throw new Error("Factory decision is not linked to a work item.");
1166
1386
  const item = await this.#storage.get({
@@ -1183,6 +1403,50 @@ var FactoryDecisionDispatcher = class {
1183
1403
  if (!binding) throw new FactoryDispatchError("session_unavailable", role ? `No active Factory binding for role ${role}.` : "No active Factory binding.");
1184
1404
  return binding;
1185
1405
  }
1406
+ /**
1407
+ * Points the card's live session at new activity on its source. The message
1408
+ * is written here from the decision's pointers, never from provider text.
1409
+ * Activity while the session is busy waits as one pending notification per
1410
+ * card and kind of activity, counting how many arrived; an idle session is
1411
+ * woken unless the decision asks to only persist. A card nobody is working
1412
+ * has nobody to tell, so it is dropped.
1413
+ */
1414
+ async #signalActivity(record, decision) {
1415
+ if (!record.workItemId) return;
1416
+ const binding = await this.#findBinding(record);
1417
+ if (!binding) return;
1418
+ const startedBy = (await this.#storage.get({
1419
+ orgId: record.orgId,
1420
+ id: record.workItemId
1421
+ }))?.sessions[binding.role]?.startedBy;
1422
+ if (!startedBy) throw new Error(`Factory binding ${binding.id} has no authenticated session owner.`);
1423
+ await this.#primeCredentials?.({
1424
+ orgId: record.orgId,
1425
+ userId: startedBy
1426
+ });
1427
+ const session = await this.#requireSession(binding);
1428
+ const author = decision.author ? `@${decision.author}${decision.authorTrusted ? "" : " (untrusted author)"}` : decision.authorTrusted ? void 0 : "an untrusted author";
1429
+ const message = decision.event === "work_item.commented" ? `New comment${author ? ` by ${author}` : ""} on ${decision.reference}: ${decision.url}` : `${decision.reference} was edited${author ? ` by ${author}` : ""}: ${decision.url}`;
1430
+ const wakes = decision.authorTrusted && decision.idleBehavior !== "persist";
1431
+ await awaitNotification(() => session.sendNotificationSignal({
1432
+ source: "factory",
1433
+ kind: "source-activity",
1434
+ summary: message,
1435
+ priority: wakes ? "medium" : "low",
1436
+ sourceId: record.id,
1437
+ dedupeKey: record.idempotencyKey,
1438
+ coalesceKey: `${record.workItemId}:${decision.event}`
1439
+ }, {
1440
+ ifActive: { behavior: "persist" },
1441
+ ifIdle: { behavior: wakes ? "wake" : "persist" },
1442
+ requestContext: factoryRequestContext({
1443
+ session,
1444
+ binding,
1445
+ userId: startedBy,
1446
+ orgId: record.orgId
1447
+ })
1448
+ }));
1449
+ }
1186
1450
  async #messageBinding(record, decision) {
1187
1451
  if (decision.prepareBinding && decision.role !== void 0) return this.#requireOrPrepareBinding(record, decision.role);
1188
1452
  return this.#findBinding(record, decision.role);
@@ -1259,6 +1523,38 @@ var FactoryDecisionDispatcher = class {
1259
1523
  factoryProjectId
1260
1524
  }), item) === "submit_plan";
1261
1525
  }
1526
+ /**
1527
+ * Whether a run is in flight on `binding`: live here, or live on another dispatcher. An open-run
1528
+ * entry with nothing live behind it is an orphan of a dead process and does not count.
1529
+ */
1530
+ async #hasRunInFlight(session, binding) {
1531
+ const open = (await listSessionOpenRuns(session)).filter((entry) => entry.bindingId === binding.id);
1532
+ if (open.length === 0) return false;
1533
+ if (open.some((entry) => isOpenRunLiveElsewhere(entry, this.#ownerId))) return true;
1534
+ return this.#controller.listActiveThreadRuns().some((active) => active.threadId === binding.threadId);
1535
+ }
1536
+ /** Waits for the run in flight on `binding` to end, so a kickoff never overlaps it. */
1537
+ async #waitForOpenRun(session, binding, label) {
1538
+ const runStillActive = () => this.#controller.listActiveThreadRuns().some((active) => active.threadId === binding.threadId);
1539
+ while (true) {
1540
+ const openRun = watchRun(session, {
1541
+ timeoutMs: this.#skillCompletionObservationTimeoutMs,
1542
+ approvePlans: false,
1543
+ label,
1544
+ runStillActive
1545
+ });
1546
+ try {
1547
+ const open = (await listSessionOpenRuns(session)).filter((entry) => entry.bindingId === binding.id);
1548
+ if (open.length === 0) break;
1549
+ if (open.some((entry) => isOpenRunLiveElsewhere(entry, this.#ownerId))) throw new FactoryDispatchError("session_unavailable", `Factory binding ${binding.id} has a run in flight on another dispatcher.`);
1550
+ if (!runStillActive()) break;
1551
+ if (!await openRun.wait()) break;
1552
+ } finally {
1553
+ openRun.close();
1554
+ }
1555
+ await waitForSessionRunAudit(session);
1556
+ }
1557
+ }
1262
1558
  async #requireSession(binding) {
1263
1559
  const session = await this.#findSession(binding);
1264
1560
  if (!session) throw new FactoryDispatchError("session_unavailable", "Bound Factory session not found.");
@@ -1402,6 +1698,7 @@ var FactoryDecisionDispatcher = class {
1402
1698
  ...record,
1403
1699
  workItemId: binding.workItemId
1404
1700
  }),
1701
+ requestContext,
1405
1702
  label: "Factory kickoff run",
1406
1703
  runStillActive: () => this.#controller.listActiveThreadRuns().some((active) => active.threadId === binding.threadId)
1407
1704
  });
@@ -1463,6 +1760,7 @@ const FACTORY_DISPATCH_CONSTANTS = {
1463
1760
  runRegistryHeartbeatMs: RUN_REGISTRY_HEARTBEAT_MS,
1464
1761
  openRunStaleMs: FACTORY_OPEN_RUN_STALE_MS,
1465
1762
  maxInFlight: MAX_IN_FLIGHT,
1763
+ reviewStatusTimeoutMs: REVIEW_STATUS_TIMEOUT_MS,
1466
1764
  stages: FACTORY_RULE_STAGES
1467
1765
  };
1468
1766
  export { FACTORY_DISPATCH_CONSTANTS, FactoryDecisionDispatcher };