@mastra/factory 0.27.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 (426) hide show
  1. package/README.md +215 -41
  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/index.js +1 -1
  15. package/dist/boards/intake-routing.d.ts +30 -6
  16. package/dist/boards/intake-routing.d.ts.map +1 -1
  17. package/dist/boards/intake-routing.js +43 -5
  18. package/dist/boards/intake-routing.js.map +1 -1
  19. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  20. package/dist/boards/legacy-plan-role.js +8 -4
  21. package/dist/boards/legacy-plan-role.js.map +1 -1
  22. package/dist/boards/phase-automation.d.ts.map +1 -1
  23. package/dist/boards/phase-automation.js +7 -2
  24. package/dist/boards/phase-automation.js.map +1 -1
  25. package/dist/boards/project-boards.d.ts +18 -7
  26. package/dist/boards/project-boards.d.ts.map +1 -1
  27. package/dist/boards/project-boards.js +79 -15
  28. package/dist/boards/project-boards.js.map +1 -1
  29. package/dist/boards/stored-board.d.ts +59 -1
  30. package/dist/boards/stored-board.d.ts.map +1 -1
  31. package/dist/boards/stored-board.js +219 -7
  32. package/dist/boards/stored-board.js.map +1 -1
  33. package/dist/boards/work.js +1 -1
  34. package/dist/dispatch-wake.d.ts +13 -0
  35. package/dist/dispatch-wake.d.ts.map +1 -0
  36. package/dist/dispatch-wake.js +30 -0
  37. package/dist/dispatch-wake.js.map +1 -0
  38. package/dist/environment/build-runner.d.ts +1 -1
  39. package/dist/environment/build-runner.d.ts.map +1 -1
  40. package/dist/environment/build-runner.js +2 -2
  41. package/dist/environment/build-workflow.d.ts +1 -1
  42. package/dist/environment/build-workflow.d.ts.map +1 -1
  43. package/dist/environment/build-workflow.js +1 -1
  44. package/dist/environment/build.js +1 -1
  45. package/dist/factory.d.ts +63 -9
  46. package/dist/factory.d.ts.map +1 -1
  47. package/dist/factory.js +237 -59
  48. package/dist/factory.js.map +1 -1
  49. package/dist/index.d.ts +3 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js +10 -9
  52. package/dist/integrations/base.d.ts +6 -0
  53. package/dist/integrations/base.d.ts.map +1 -1
  54. package/dist/integrations/channel-thread-announcements.d.ts +5 -0
  55. package/dist/integrations/channel-thread-announcements.d.ts.map +1 -1
  56. package/dist/integrations/channel-thread-announcements.js +24 -2
  57. package/dist/integrations/channel-thread-announcements.js.map +1 -1
  58. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  59. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  60. package/dist/integrations/github/acceptance-labels.js +1 -1
  61. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  62. package/dist/integrations/github/default-rules.d.ts +2 -9
  63. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  64. package/dist/integrations/github/default-rules.js +7 -6
  65. package/dist/integrations/github/default-rules.js.map +1 -1
  66. package/dist/integrations/github/integration.js +2 -2
  67. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  68. package/dist/integrations/github/issue-reconciler.js +17 -1
  69. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  70. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  71. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  72. package/dist/integrations/github/review-status-comment.js +217 -0
  73. package/dist/integrations/github/review-status-comment.js.map +1 -0
  74. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  75. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  76. package/dist/integrations/github/review-status-reporter.js +100 -0
  77. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  78. package/dist/integrations/github/review-status.d.ts +28 -0
  79. package/dist/integrations/github/review-status.d.ts.map +1 -0
  80. package/dist/integrations/github/review-status.js +95 -0
  81. package/dist/integrations/github/review-status.js.map +1 -0
  82. package/dist/integrations/github/routes.d.ts.map +1 -1
  83. package/dist/integrations/github/routes.js +19 -21
  84. package/dist/integrations/github/routes.js.map +1 -1
  85. package/dist/integrations/github/rules.d.ts +13 -1
  86. package/dist/integrations/github/rules.d.ts.map +1 -1
  87. package/dist/integrations/github/rules.js +80 -9
  88. package/dist/integrations/github/rules.js.map +1 -1
  89. package/dist/integrations/github/sandbox.js +1 -1
  90. package/dist/integrations/github/session-subscriptions.js +3 -3
  91. package/dist/integrations/github/webhook.js +2 -2
  92. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  93. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  94. package/dist/integrations/gitlab/default-rules.js +4 -4
  95. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  96. package/dist/integrations/gitlab/integration.js +2 -2
  97. package/dist/integrations/gitlab/issue-reconciler.js +1 -1
  98. package/dist/integrations/gitlab/merge-request-reconciler.js +2 -2
  99. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  100. package/dist/integrations/gitlab/routes.js +2 -4
  101. package/dist/integrations/gitlab/routes.js.map +1 -1
  102. package/dist/integrations/gitlab/rules.d.ts +16 -0
  103. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  104. package/dist/integrations/gitlab/rules.js +71 -6
  105. package/dist/integrations/gitlab/rules.js.map +1 -1
  106. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  107. package/dist/integrations/gitlab/webhook-dispatch.js +1 -1
  108. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  109. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  110. package/dist/integrations/incidentio/default-rules.js +3 -4
  111. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  112. package/dist/integrations/incidentio/integration.js +3 -3
  113. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  114. package/dist/integrations/incidentio/routes.js +1 -4
  115. package/dist/integrations/incidentio/routes.js.map +1 -1
  116. package/dist/integrations/incidentio/rules.d.ts +7 -0
  117. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  118. package/dist/integrations/incidentio/rules.js +37 -5
  119. package/dist/integrations/incidentio/rules.js.map +1 -1
  120. package/dist/integrations/jira/default-rules.d.ts +1 -9
  121. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  122. package/dist/integrations/jira/default-rules.js +3 -4
  123. package/dist/integrations/jira/default-rules.js.map +1 -1
  124. package/dist/integrations/jira/integration.js +2 -2
  125. package/dist/integrations/jira/routes.d.ts.map +1 -1
  126. package/dist/integrations/jira/routes.js +2 -5
  127. package/dist/integrations/jira/routes.js.map +1 -1
  128. package/dist/integrations/jira/rules.d.ts +7 -0
  129. package/dist/integrations/jira/rules.d.ts.map +1 -1
  130. package/dist/integrations/jira/rules.js +37 -5
  131. package/dist/integrations/jira/rules.js.map +1 -1
  132. package/dist/integrations/linear/default-rules.d.ts +1 -9
  133. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  134. package/dist/integrations/linear/default-rules.js +3 -4
  135. package/dist/integrations/linear/default-rules.js.map +1 -1
  136. package/dist/integrations/linear/integration.js +2 -2
  137. package/dist/integrations/linear/routes.d.ts +21 -1
  138. package/dist/integrations/linear/routes.d.ts.map +1 -1
  139. package/dist/integrations/linear/routes.js +21 -6
  140. package/dist/integrations/linear/routes.js.map +1 -1
  141. package/dist/integrations/linear/rules.d.ts +7 -0
  142. package/dist/integrations/linear/rules.d.ts.map +1 -1
  143. package/dist/integrations/linear/rules.js +37 -5
  144. package/dist/integrations/linear/rules.js.map +1 -1
  145. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  146. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  147. package/dist/integrations/platform/connect/routes.js +42 -5
  148. package/dist/integrations/platform/connect/routes.js.map +1 -1
  149. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  150. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  151. package/dist/integrations/platform/connect/session-tools.js +30 -0
  152. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  153. package/dist/integrations/platform/github/event-worker.js +1 -1
  154. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  155. package/dist/integrations/platform/github/integration.js +9 -8
  156. package/dist/integrations/platform/github/integration.js.map +1 -1
  157. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  158. package/dist/integrations/platform/gitlab/integration.js +2 -2
  159. package/dist/integrations/platform/incidentio/integration.js +5 -5
  160. package/dist/integrations/platform/jira/agent-tools.js +1 -1
  161. package/dist/integrations/platform/jira/integration.js +2 -2
  162. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  163. package/dist/integrations/platform/jira/routes.js +2 -5
  164. package/dist/integrations/platform/jira/routes.js.map +1 -1
  165. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  166. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  167. package/dist/integrations/platform/linear/event-worker.js +9 -0
  168. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  169. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  170. package/dist/integrations/platform/linear/integration.js +150 -48
  171. package/dist/integrations/platform/linear/integration.js.map +1 -1
  172. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  173. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  175. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  176. package/dist/integrations/slack/chat-tools.d.ts +16 -0
  177. package/dist/integrations/slack/chat-tools.d.ts.map +1 -0
  178. package/dist/integrations/slack/chat-tools.js +215 -0
  179. package/dist/integrations/slack/chat-tools.js.map +1 -0
  180. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  181. package/dist/integrations/slack/connect-route.js +1 -1
  182. package/dist/integrations/slack/connect-route.js.map +1 -1
  183. package/dist/integrations/slack/integration.d.ts +19 -3
  184. package/dist/integrations/slack/integration.d.ts.map +1 -1
  185. package/dist/integrations/slack/integration.js +27 -8
  186. package/dist/integrations/slack/integration.js.map +1 -1
  187. package/dist/integrations/slack/run-error-card.js +1 -1
  188. package/dist/integrations/slack/share-file-tool.d.ts +8 -0
  189. package/dist/integrations/slack/share-file-tool.d.ts.map +1 -1
  190. package/dist/integrations/slack/share-file-tool.js +13 -4
  191. package/dist/integrations/slack/share-file-tool.js.map +1 -1
  192. package/dist/integrations/slack/slack.d.ts +12 -10
  193. package/dist/integrations/slack/slack.d.ts.map +1 -1
  194. package/dist/integrations/slack/slack.js +113 -46
  195. package/dist/integrations/slack/slack.js.map +1 -1
  196. package/dist/integrations/slack/tool-settings.d.ts +26 -0
  197. package/dist/integrations/slack/tool-settings.d.ts.map +1 -0
  198. package/dist/integrations/slack/tool-settings.js +35 -0
  199. package/dist/integrations/slack/tool-settings.js.map +1 -0
  200. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  201. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  202. package/dist/integrations/slack/voice-clips.js +201 -0
  203. package/dist/integrations/slack/voice-clips.js.map +1 -0
  204. package/dist/integrations/workos/integration.d.ts.map +1 -1
  205. package/dist/integrations/workos/integration.js +1 -3
  206. package/dist/integrations/workos/integration.js.map +1 -1
  207. package/dist/mcp/events.js +1 -1
  208. package/dist/mcp/routes.js +2 -2
  209. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  210. package/dist/routes/attention-activity.js +1 -1
  211. package/dist/routes/attention-providers.js +2 -2
  212. package/dist/routes/attention.js +2 -2
  213. package/dist/routes/automation-runs.d.ts.map +1 -1
  214. package/dist/routes/automation-runs.js +2 -5
  215. package/dist/routes/automation-runs.js.map +1 -1
  216. package/dist/routes/boards.d.ts +8 -6
  217. package/dist/routes/boards.d.ts.map +1 -1
  218. package/dist/routes/boards.js +73 -143
  219. package/dist/routes/boards.js.map +1 -1
  220. package/dist/routes/config.d.ts.map +1 -1
  221. package/dist/routes/config.js +6 -11
  222. package/dist/routes/config.js.map +1 -1
  223. package/dist/routes/contracts.d.ts +162 -2
  224. package/dist/routes/contracts.d.ts.map +1 -1
  225. package/dist/routes/contracts.js +98 -33
  226. package/dist/routes/contracts.js.map +1 -1
  227. package/dist/routes/fs.d.ts.map +1 -1
  228. package/dist/routes/fs.js +2 -5
  229. package/dist/routes/fs.js.map +1 -1
  230. package/dist/routes/intake-routes.d.ts.map +1 -1
  231. package/dist/routes/intake-routes.js +19 -12
  232. package/dist/routes/intake-routes.js.map +1 -1
  233. package/dist/routes/intake.d.ts.map +1 -1
  234. package/dist/routes/intake.js +4 -6
  235. package/dist/routes/intake.js.map +1 -1
  236. package/dist/routes/knowledge.d.ts.map +1 -1
  237. package/dist/routes/knowledge.js +1 -4
  238. package/dist/routes/knowledge.js.map +1 -1
  239. package/dist/routes/oauth.d.ts.map +1 -1
  240. package/dist/routes/oauth.js +1 -4
  241. package/dist/routes/oauth.js.map +1 -1
  242. package/dist/routes/projects.d.ts +3 -0
  243. package/dist/routes/projects.d.ts.map +1 -1
  244. package/dist/routes/projects.js +42 -28
  245. package/dist/routes/projects.js.map +1 -1
  246. package/dist/routes/provider-credentials.d.ts.map +1 -1
  247. package/dist/routes/provider-credentials.js +6 -0
  248. package/dist/routes/provider-credentials.js.map +1 -1
  249. package/dist/routes/route.d.ts +2 -0
  250. package/dist/routes/route.d.ts.map +1 -1
  251. package/dist/routes/route.js +5 -1
  252. package/dist/routes/route.js.map +1 -1
  253. package/dist/routes/skills.d.ts.map +1 -1
  254. package/dist/routes/skills.js +2 -5
  255. package/dist/routes/skills.js.map +1 -1
  256. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  257. package/dist/routes/source-control-sessions.js +3 -5
  258. package/dist/routes/source-control-sessions.js.map +1 -1
  259. package/dist/routes/source-control-settings.d.ts.map +1 -1
  260. package/dist/routes/source-control-settings.js +3 -2
  261. package/dist/routes/source-control-settings.js.map +1 -1
  262. package/dist/routes/surface.d.ts +3 -1
  263. package/dist/routes/surface.d.ts.map +1 -1
  264. package/dist/routes/surface.js +27 -17
  265. package/dist/routes/surface.js.map +1 -1
  266. package/dist/routes/telemetry.js +1 -1
  267. package/dist/routes/voice.d.ts +48 -0
  268. package/dist/routes/voice.d.ts.map +1 -0
  269. package/dist/routes/voice.js +248 -0
  270. package/dist/routes/voice.js.map +1 -0
  271. package/dist/routes/work-items.d.ts.map +1 -1
  272. package/dist/routes/work-items.js +9 -12
  273. package/dist/routes/work-items.js.map +1 -1
  274. package/dist/rules/decision-applicability.js +1 -1
  275. package/dist/rules/dispatcher.d.ts +42 -0
  276. package/dist/rules/dispatcher.d.ts.map +1 -1
  277. package/dist/rules/dispatcher.js +522 -136
  278. package/dist/rules/dispatcher.js.map +1 -1
  279. package/dist/rules/event-rules.d.ts +40 -1
  280. package/dist/rules/event-rules.d.ts.map +1 -1
  281. package/dist/rules/event-rules.js +59 -1
  282. package/dist/rules/event-rules.js.map +1 -1
  283. package/dist/rules/index.js +1 -1
  284. package/dist/rules/processor.d.ts +2 -0
  285. package/dist/rules/processor.d.ts.map +1 -1
  286. package/dist/rules/processor.js +5 -4
  287. package/dist/rules/processor.js.map +1 -1
  288. package/dist/rules/start-coordinator.js +2 -2
  289. package/dist/rules/terminal-cleanup.js.map +1 -1
  290. package/dist/rules/tools.js +5 -5
  291. package/dist/rules/transition-service.d.ts +9 -0
  292. package/dist/rules/transition-service.d.ts.map +1 -1
  293. package/dist/rules/transition-service.js +9 -7
  294. package/dist/rules/transition-service.js.map +1 -1
  295. package/dist/rules/types.d.ts +54 -3
  296. package/dist/rules/types.d.ts.map +1 -1
  297. package/dist/rules/types.js +2 -0
  298. package/dist/rules/types.js.map +1 -1
  299. package/dist/rules/validation.d.ts.map +1 -1
  300. package/dist/rules/validation.js +57 -2
  301. package/dist/rules/validation.js.map +1 -1
  302. package/dist/sandbox/session-retirement.js +2 -2
  303. package/dist/sandbox/session-sandbox.js +1 -1
  304. package/dist/session/credential-policy.d.ts +2 -2
  305. package/dist/session/credential-policy.d.ts.map +1 -1
  306. package/dist/session/credential-policy.js +4 -4
  307. package/dist/session/credential-policy.js.map +1 -1
  308. package/dist/session/default-model-hydration.d.ts +2 -2
  309. package/dist/session/default-model-hydration.d.ts.map +1 -1
  310. package/dist/session/default-model-hydration.js +4 -4
  311. package/dist/session/default-model-hydration.js.map +1 -1
  312. package/dist/session/factory-session.js +3 -3
  313. package/dist/session/self-review-gate.js +1 -1
  314. package/dist/session/session-threads.d.ts +8 -0
  315. package/dist/session/session-threads.d.ts.map +1 -1
  316. package/dist/session/session-threads.js +11 -1
  317. package/dist/session/session-threads.js.map +1 -1
  318. package/dist/session/source-control-tools.js +3 -3
  319. package/dist/skills/catalog.js +1 -1
  320. package/dist/storage/domains/audit/actions.d.ts +1 -1
  321. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  322. package/dist/storage/domains/audit/actions.js +2 -1
  323. package/dist/storage/domains/audit/actions.js.map +1 -1
  324. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  325. package/dist/storage/domains/audit/domain.js +2 -4
  326. package/dist/storage/domains/audit/domain.js.map +1 -1
  327. package/dist/storage/domains/boards/base.d.ts +32 -1
  328. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  329. package/dist/storage/domains/boards/base.js +155 -8
  330. package/dist/storage/domains/boards/base.js.map +1 -1
  331. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  332. package/dist/storage/domains/boards/schemas.js +13 -1
  333. package/dist/storage/domains/boards/schemas.js.map +1 -1
  334. package/dist/storage/domains/comments/base.js +3 -3
  335. package/dist/storage/domains/comments/domain.js +3 -3
  336. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  337. package/dist/storage/domains/comments/routes.js +2 -4
  338. package/dist/storage/domains/comments/routes.js.map +1 -1
  339. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  340. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  341. package/dist/storage/domains/memory-settings/base.js +1 -11
  342. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  343. package/dist/storage/domains/projects/base.d.ts +6 -0
  344. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  345. package/dist/storage/domains/projects/base.js +9 -1
  346. package/dist/storage/domains/projects/base.js.map +1 -1
  347. package/dist/storage/domains/source-control/base.d.ts +20 -0
  348. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  349. package/dist/storage/domains/source-control/base.js +42 -0
  350. package/dist/storage/domains/source-control/base.js.map +1 -1
  351. package/dist/storage/domains/source-control/inmemory.d.ts +5 -1
  352. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  353. package/dist/storage/domains/source-control/inmemory.js +23 -0
  354. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  355. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  356. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  357. package/dist/storage/domains/voice-settings/base.js +81 -0
  358. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  359. package/dist/storage/domains/work-items/base.d.ts +47 -7
  360. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  361. package/dist/storage/domains/work-items/base.js +251 -115
  362. package/dist/storage/domains/work-items/base.js.map +1 -1
  363. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  364. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  365. package/dist/storage/domains/work-items/cards.js +55 -5
  366. package/dist/storage/domains/work-items/cards.js.map +1 -1
  367. package/dist/storage/domains/work-items/claimable-work.d.ts +15 -0
  368. package/dist/storage/domains/work-items/claimable-work.d.ts.map +1 -0
  369. package/dist/storage/domains/work-items/claimable-work.js +51 -0
  370. package/dist/storage/domains/work-items/claimable-work.js.map +1 -0
  371. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  372. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  373. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  374. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  375. package/dist/timing.d.ts +1 -0
  376. package/dist/timing.d.ts.map +1 -1
  377. package/dist/timing.js +1 -1
  378. package/dist/timing.js.map +1 -1
  379. package/dist/tools/index.js +2 -2
  380. package/dist/tools/messaging-tools.js +1 -1
  381. package/dist/tools/read-tools.d.ts +2 -2
  382. package/dist/tools/read-tools.d.ts.map +1 -1
  383. package/dist/tools/read-tools.js +10 -9
  384. package/dist/tools/read-tools.js.map +1 -1
  385. package/dist/tools/scope.js +1 -1
  386. package/dist/tools/session-tools.d.ts +1 -1
  387. package/dist/tools/session-tools.d.ts.map +1 -1
  388. package/dist/tools/session-tools.js +9 -9
  389. package/dist/tools/session-tools.js.map +1 -1
  390. package/dist/tools/sessions-state-processor.d.ts +1 -1
  391. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  392. package/dist/tools/sessions-state-processor.js +9 -2
  393. package/dist/tools/sessions-state-processor.js.map +1 -1
  394. package/dist/tools/work-item-tools.js +4 -4
  395. package/dist/voice/rate-limit.d.ts +13 -0
  396. package/dist/voice/rate-limit.d.ts.map +1 -0
  397. package/dist/voice/rate-limit.js +36 -0
  398. package/dist/voice/rate-limit.js.map +1 -0
  399. package/dist/voice/realtime.d.ts +13 -0
  400. package/dist/voice/realtime.d.ts.map +1 -0
  401. package/dist/voice/realtime.js +56 -0
  402. package/dist/voice/realtime.js.map +1 -0
  403. package/dist/voice/transcription.d.ts +51 -0
  404. package/dist/voice/transcription.d.ts.map +1 -0
  405. package/dist/voice/transcription.js +112 -0
  406. package/dist/voice/transcription.js.map +1 -0
  407. package/dist/work-items/create-work-item.js +2 -2
  408. package/dist/work-items/decision-actions.js +2 -2
  409. package/dist/work-items/providers/gitlab.js +1 -1
  410. package/dist/work-items/providers/incidentio.js +1 -1
  411. package/dist/work-items/providers/index.js +1 -1
  412. package/dist/work-items/providers/jira.js +1 -1
  413. package/dist/work-items/providers/linear.js +1 -1
  414. package/dist/work-items/split-backfill.d.ts +13 -0
  415. package/dist/work-items/split-backfill.d.ts.map +1 -0
  416. package/dist/work-items/split-backfill.js +32 -0
  417. package/dist/work-items/split-backfill.js.map +1 -0
  418. package/dist/work-items/split-migration.d.ts +39 -2
  419. package/dist/work-items/split-migration.d.ts.map +1 -1
  420. package/dist/work-items/split-migration.js +171 -63
  421. package/dist/work-items/split-migration.js.map +1 -1
  422. package/dist/workspace.d.ts +2 -0
  423. package/dist/workspace.d.ts.map +1 -1
  424. package/dist/workspace.js +12 -9
  425. package/dist/workspace.js.map +1 -1
  426. package/package.json +10 -9
@@ -1,25 +1,29 @@
1
- import { FACTORY_RULE_STAGES, externalSourceForWorkItem, workItemSource } from "./types.js";
2
- import { assertFactoryDecisionTarget, validateFactoryRuleDecision } from "./validation.js";
3
- import { FactoryDispatchError, factoryDispatchFailureCode, factoryDispatchFailureMetadata } from "./dispatch-errors.js";
4
- import { FACTORY_RULE_MATERIALIZATION_KEY } from "../storage/domains/work-items/base.js";
5
- import { workItemProviderAdapter } from "../work-items/providers/index.js";
6
- import { cardRuleFacts } from "../boards/card-facts.js";
7
- import { boardForWorkItem, isPullRequestCard, isTerminalWorkItem, pullRequestReviewPhase, resolvePhaseSemantics, reviewsPullRequest, workItemPhaseSemantics } from "../boards/semantics.js";
8
1
  import "../boards/index.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";
4
+ import { autoApprovedExitTool, startsInAutoPhase } from "../boards/phase-automation.js";
9
5
  import { toBoardSource } from "../boards/project-boards.js";
10
- import { INTAKE_ROUTE_METADATA_KEY, landingPhase, placedByIntakeRoute, resolveIntakePlacement } from "../boards/intake-routing.js";
11
6
  import { moveCardToBoard } from "../boards/relocate.js";
12
- import { decisionOvertaken } from "./decision-applicability.js";
7
+ import { cardRuleFacts } from "../boards/card-facts.js";
13
8
  import { FACTORY_OPEN_RUN_STALE_MS, heartbeatSessionOpenRun, isOpenRunLiveElsewhere, listSessionOpenRuns, recordSessionRunStart, waitForSessionRunAudit } from "../session/run-audit.js";
14
- import { isHumanActorId } from "../storage/domains/audit/actors.js";
15
- import { autoApprovedExitTool, startsInAutoPhase } from "../boards/phase-automation.js";
16
9
  import { resolvePromptInvocation, resolveSkillInvocation, resolveSkillResumeInvocation } from "../skills/service.js";
10
+ import { isHumanActorId } from "../storage/domains/audit/actors.js";
17
11
  import { withWorkItemFeed } from "../storage/domains/comments/feed-context.js";
12
+ import { FACTORY_RULE_MATERIALIZATION_KEY } from "../storage/domains/work-items/base.js";
13
+ import { workItemProviderAdapter } from "../work-items/providers/index.js";
14
+ import { decisionOvertaken } from "./decision-applicability.js";
15
+ import { FactoryDispatchError, factoryDispatchFailureCode, factoryDispatchFailureMetadata } from "./dispatch-errors.js";
16
+ import { isStatusEventDecision } from "./event-rules.js";
17
+ import { FACTORY_RULE_STAGES, externalSourceForWorkItem, workItemSource } from "./types.js";
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;
26
+ const IDLE_RECHECK_MS = 36e5;
23
27
  const BATCH_SIZE = 10;
24
28
  const MAX_ATTEMPTS = 5;
25
29
  const MAX_PLAN_APPROVALS = 3;
@@ -29,11 +33,12 @@ const RUN_REGISTRY_HEARTBEAT_MS = 6e5;
29
33
  const SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS = 216e5;
30
34
  const MAX_IN_FLIGHT = 25;
31
35
  /**
32
- * Decisions that may start or wake an agent run and so hold a run slot. A
33
- * transition's message is queued as a separate sendMessage, so the transition
34
- * 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.
35
40
  */
36
- const isRunBearingDecision = (decision) => decision.type === "invokeSkill" || decision.type === "sendMessage";
41
+ const isRunBearingDecision = (decision) => decision.type === "invokeSkill" || decision.type === "sendMessage" || decision.type === "signalActivity";
37
42
  const isBookkeepingDecision = (decision) => !isRunBearingDecision(decision);
38
43
  const BOOKKEEPING_MAX_IN_FLIGHT = 4;
39
44
  const STALE_BINDING_SWEEP_INTERVAL_MS = 6e5;
@@ -41,6 +46,9 @@ const STALE_BINDING_TTL_MS = 864e5;
41
46
  const RECONCILE_INTERVAL_MS = 3e4;
42
47
  /** The card moved on before this run could act; it settles as superseded, not succeeded. */
43
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;
44
52
  /** A run that ran and ended in error; the session's own listener reports it to followers. */
45
53
  var RunEndedInError = class extends FactoryDispatchError {};
46
54
  const CREDENTIAL_RESOLUTION_FAILURE = "tenant model credential policy could not be resolved";
@@ -70,6 +78,12 @@ function runErrorFailure(label, error) {
70
78
  if (!cause) return new RunEndedInError("run_failed", `${label} ended in error.`);
71
79
  return new RunEndedInError(runErrorCode(error, cause), `${label} ended in error: ${cause}`);
72
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
+ }
73
87
  function isTerminalFailure(attempts, failureCode) {
74
88
  return attempts >= MAX_ATTEMPTS || !factoryDispatchFailureMetadata(failureCode).canRetry;
75
89
  }
@@ -84,7 +98,7 @@ function isPermanentProviderRejection(error) {
84
98
  const normalized = error.toLowerCase();
85
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");
86
100
  }
87
- function watchRun(session, { timeoutMs, approvePlans, onAgentEnd, label, runStillActive }) {
101
+ function watchRun(session, { timeoutMs, approvePlans, requestContext, onAgentEnd, label, runStillActive }) {
88
102
  let resolveAgentEnd;
89
103
  let agentEnd;
90
104
  let endReason;
@@ -152,7 +166,8 @@ function watchRun(session, { timeoutMs, approvePlans, onAgentEnd, label, runStil
152
166
  arm();
153
167
  await session.respondToToolSuspension({
154
168
  resumeData: { action: "approved" },
155
- toolCallId
169
+ toolCallId,
170
+ requestContext
156
171
  });
157
172
  observed = await wait();
158
173
  }
@@ -304,6 +319,19 @@ var FactoryDecisionDispatcher = class {
304
319
  #reportRunEnd;
305
320
  #feedReader;
306
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();
307
335
  #resolveLinkedWorkItemParentId;
308
336
  #factoryProjectExists;
309
337
  #maxInFlight;
@@ -314,8 +342,16 @@ var FactoryDecisionDispatcher = class {
314
342
  #skillCompletionObservationTimeoutMs;
315
343
  #lastReconcileAt;
316
344
  #reconcileInFlight;
345
+ /** A reconcile is due once activity stops, to drain results of runs that just ended. */
346
+ #reconcileOwed = true;
347
+ /** Last step seen on a bound session thread; counts as activity for one reconcile interval. */
348
+ #lastBoundThreadRunAt;
349
+ #started = false;
350
+ #stopping = false;
351
+ #wakeRequested = false;
352
+ #unsubscribeClaimableWork;
353
+ #loop;
317
354
  #timer;
318
- #activeClaim;
319
355
  /** Starts and run-bearing decisions; capped by `maxInFlight`. */
320
356
  #runInFlight = /* @__PURE__ */ new Set();
321
357
  /** Fast board bookkeeping (transitions, linked-card upserts); its own small cap. */
@@ -338,6 +374,7 @@ var FactoryDecisionDispatcher = class {
338
374
  this.#reportRunEnd = options.reportRunEnd;
339
375
  this.#feedReader = options.feedReader;
340
376
  this.#dismissStaleReviews = options.dismissStaleReviews;
377
+ this.#reportReviewStatus = options.reportReviewStatus;
341
378
  this.#resolveLinkedWorkItemParentId = options.resolveLinkedWorkItemParentId;
342
379
  this.#factoryProjectExists = options.factoryProjectExists;
343
380
  const maxInFlight = options.maxInFlight ?? MAX_IN_FLIGHT;
@@ -348,23 +385,111 @@ var FactoryDecisionDispatcher = class {
348
385
  this.#skillCompletionObservationTimeoutMs = positiveMs(options.skillCompletionObservationTimeoutMs, SKILL_COMPLETION_OBSERVATION_TIMEOUT_MS);
349
386
  }
350
387
  start() {
351
- if (this.#timer) return;
352
- this.#tick();
353
- this.#timer = setInterval(() => void this.#tick(), POLL_MS);
354
- this.#timer.unref?.();
388
+ if (this.#started) return;
389
+ this.#started = true;
390
+ this.#stopping = false;
391
+ this.#unsubscribeClaimableWork = this.#storage.onClaimableWork(() => this.wake());
392
+ this.wake();
355
393
  }
356
394
  async stop() {
357
- if (this.#timer) clearInterval(this.#timer);
358
- this.#timer = void 0;
359
- await this.#activeClaim;
395
+ this.#stopping = true;
396
+ this.#unsubscribeClaimableWork?.();
397
+ this.#unsubscribeClaimableWork = void 0;
398
+ this.#clearTimer();
399
+ await this.#loop;
360
400
  await Promise.allSettled([
361
401
  ...this.#runInFlight,
362
402
  ...this.#bookkeepingInFlight,
363
403
  ...this.#backgroundInFlight
364
404
  ]);
405
+ this.#started = false;
406
+ this.#stopping = false;
407
+ }
408
+ /**
409
+ * Runs a dispatch cycle now. Called after any write that leaves claimable
410
+ * work, locally or from another replica via pubsub. A wake during a running
411
+ * cycle makes the loop run once more instead of starting a second loop.
412
+ */
413
+ wake() {
414
+ if (!this.#started || this.#stopping) return;
415
+ this.#wakeRequested = true;
416
+ if (this.#loop) return;
417
+ this.#clearTimer();
418
+ this.#loop = this.#runLoop();
419
+ }
420
+ /**
421
+ * A run is stepping on a bound session thread. Interactive runs queue no
422
+ * work, so without this an idle loop would never see them and the trailing
423
+ * reconcile for results they leave behind would not happen. Each step keeps
424
+ * the loop active for one reconcile interval; only the first step after a
425
+ * settled pass wakes it, since an owed pass already rechecks every interval.
426
+ */
427
+ noteBoundThreadRun() {
428
+ if (!this.#reconcileToolResults) return;
429
+ this.#lastBoundThreadRunAt = Date.now();
430
+ if (this.#reconcileOwed) return;
431
+ this.#reconcileOwed = true;
432
+ this.wake();
365
433
  }
366
434
  async runOnce(now = /* @__PURE__ */ new Date()) {
367
- await Promise.all(await this.#claimAndStart(now));
435
+ this.#maybeSweepStaleBindings(now);
436
+ this.#maybeReconcileToolResults(now);
437
+ const { dispatches } = await this.#claimAndStart(now);
438
+ await Promise.all(dispatches);
439
+ }
440
+ #clearTimer() {
441
+ if (this.#timer) clearTimeout(this.#timer);
442
+ this.#timer = void 0;
443
+ }
444
+ async #runLoop() {
445
+ let delay = POLL_MS;
446
+ do {
447
+ this.#wakeRequested = false;
448
+ try {
449
+ delay = await this.#cycle();
450
+ } catch (error) {
451
+ console.error("Factory decision dispatch cycle failed", sanitizeDispatchError(error));
452
+ delay = POLL_MS;
453
+ }
454
+ } while (this.#wakeRequested && !this.#stopping);
455
+ this.#loop = void 0;
456
+ if (this.#stopping) return;
457
+ this.#timer = setTimeout(() => {
458
+ this.#timer = void 0;
459
+ this.wake();
460
+ }, delay);
461
+ this.#timer.unref?.();
462
+ }
463
+ /** One loop cycle; returns the delay until the next one. */
464
+ async #cycle() {
465
+ const now = /* @__PURE__ */ new Date();
466
+ this.#maybeSweepStaleBindings(now);
467
+ const active = this.#runInFlight.size > 0 || this.#bookkeepingInFlight.size > 0 || this.#controller.listActiveThreadRuns().length > 0 || this.#lastBoundThreadRunAt !== void 0 && now.getTime() - this.#lastBoundThreadRunAt < this.#reconcileIntervalMs;
468
+ if (!this.#reconcileToolResults) this.#reconcileOwed = false;
469
+ else if (active) this.#reconcileOwed = true;
470
+ if (this.#reconcileOwed && this.#maybeReconcileToolResults(now) && !active) this.#reconcileOwed = false;
471
+ let full;
472
+ try {
473
+ const claimed = await this.#claimAndStart(now);
474
+ full = claimed.full;
475
+ for (const dispatch of claimed.dispatches) dispatch.catch((error) => {
476
+ console.error("Factory decision dispatch failed", sanitizeDispatchError(error));
477
+ });
478
+ } catch (error) {
479
+ console.error("Factory decision dispatch cycle failed", sanitizeDispatchError(error));
480
+ return POLL_MS;
481
+ }
482
+ if (full || this.#runInFlight.size > 0 || this.#bookkeepingInFlight.size > 0) return POLL_MS;
483
+ const dueTimes = [];
484
+ if (this.#reconcileOwed) dueTimes.push((this.#lastReconcileAt?.getTime() ?? 0) + this.#reconcileIntervalMs);
485
+ try {
486
+ const nextClaimableAt = await this.#storage.nextClaimableAt();
487
+ if (nextClaimableAt) dueTimes.push(nextClaimableAt.getTime());
488
+ } catch (error) {
489
+ console.error("Factory decision dispatch cycle failed", sanitizeDispatchError(error));
490
+ return POLL_MS;
491
+ }
492
+ return Math.max(POLL_MS, Math.min(Math.min(...dueTimes, Infinity) - Date.now(), IDLE_RECHECK_MS));
368
493
  }
369
494
  /**
370
495
  * Claims a batch and starts dispatches without awaiting their completion.
@@ -374,8 +499,7 @@ var FactoryDecisionDispatcher = class {
374
499
  * decision. In-flight records stay protected from re-claim by lease renewal.
375
500
  */
376
501
  async #claimAndStart(now) {
377
- this.#maybeSweepStaleBindings(now);
378
- this.#maybeReconcileToolResults(now);
502
+ let full = false;
379
503
  const leaseExpiresAt = new Date(now.getTime() + LEASE_MS);
380
504
  const dispatches = [];
381
505
  const runCapacity = this.#maxInFlight - this.#runInFlight.size;
@@ -388,6 +512,7 @@ var FactoryDecisionDispatcher = class {
388
512
  limit
389
513
  });
390
514
  const decisionsLimit = limit - starts.length;
515
+ full = decisionsLimit <= 0;
391
516
  const decisions = decisionsLimit > 0 ? await this.#storage.claimDeferredDecisions({
392
517
  ownerId: this.#ownerId,
393
518
  now,
@@ -395,20 +520,26 @@ var FactoryDecisionDispatcher = class {
395
520
  limit: decisionsLimit,
396
521
  decisionFilter: isRunBearingDecision
397
522
  }) : [];
523
+ full ||= starts.length + decisions.length >= limit;
398
524
  dispatches.push(...starts.map((start) => this.#track(this.#runInFlight, this.#dispatchPendingStart(start, now))), ...decisions.map((decision) => this.#track(this.#runInFlight, this.#dispatchDecision(decision, now))));
399
525
  }
400
526
  const bookkeepingCapacity = BOOKKEEPING_MAX_IN_FLIGHT - this.#bookkeepingInFlight.size;
401
527
  if (bookkeepingCapacity > 0) {
528
+ const limit = Math.min(BATCH_SIZE, bookkeepingCapacity);
402
529
  const decisions = await this.#storage.claimDeferredDecisions({
403
530
  ownerId: this.#ownerId,
404
531
  now,
405
532
  leaseExpiresAt,
406
- limit: Math.min(BATCH_SIZE, bookkeepingCapacity),
533
+ limit,
407
534
  decisionFilter: isBookkeepingDecision
408
535
  });
536
+ full ||= decisions.length >= limit;
409
537
  dispatches.push(...decisions.map((decision) => this.#track(this.#bookkeepingInFlight, this.#dispatchDecision(decision, now))));
410
538
  }
411
- return dispatches;
539
+ return {
540
+ dispatches,
541
+ full
542
+ };
412
543
  }
413
544
  /**
414
545
  * Throttled, coalesced, non-blocking bound-thread reconcile: dispatch
@@ -416,8 +547,8 @@ var FactoryDecisionDispatcher = class {
416
547
  * are skipped while one is still in flight.
417
548
  */
418
549
  #maybeReconcileToolResults(now) {
419
- if (!this.#reconcileToolResults || this.#reconcileInFlight) return;
420
- if (this.#lastReconcileAt && now.getTime() - this.#lastReconcileAt.getTime() < this.#reconcileIntervalMs) return;
550
+ if (!this.#reconcileToolResults || this.#reconcileInFlight) return false;
551
+ if (this.#lastReconcileAt && now.getTime() - this.#lastReconcileAt.getTime() < this.#reconcileIntervalMs) return false;
421
552
  this.#lastReconcileAt = now;
422
553
  const run = this.#reconcileToolResults().catch((error) => {
423
554
  console.error("Factory tool-result reconcile failed", sanitizeDispatchError(error));
@@ -426,6 +557,7 @@ var FactoryDecisionDispatcher = class {
426
557
  });
427
558
  this.#reconcileInFlight = run;
428
559
  this.#track(this.#backgroundInFlight, run);
560
+ return true;
429
561
  }
430
562
  /** Slow-cadence revocation of leaked/legacy bindings; failures never block the claim path. */
431
563
  async #maybeSweepStaleBindings(now) {
@@ -456,23 +588,11 @@ var FactoryDecisionDispatcher = class {
456
588
  }
457
589
  #track(pool, dispatch) {
458
590
  pool.add(dispatch);
459
- dispatch.catch(() => {}).then(() => pool.delete(dispatch));
460
- return dispatch;
461
- }
462
- async #tick() {
463
- if (this.#activeClaim) return;
464
- this.#activeClaim = this.#claimAndStart(/* @__PURE__ */ new Date()).then((dispatches) => {
465
- for (const dispatch of dispatches) dispatch.catch((error) => {
466
- console.error("Factory decision dispatch failed", sanitizeDispatchError(error));
467
- });
468
- }, (error) => {
469
- console.error("Factory decision dispatch cycle failed", sanitizeDispatchError(error));
591
+ dispatch.catch(() => {}).then(() => {
592
+ pool.delete(dispatch);
593
+ if (pool !== this.#backgroundInFlight) this.wake();
470
594
  });
471
- try {
472
- await this.#activeClaim;
473
- } finally {
474
- this.#activeClaim = void 0;
475
- }
595
+ return dispatch;
476
596
  }
477
597
  async #dispatchDecision(record, now) {
478
598
  let executionCompleted = false;
@@ -484,12 +604,26 @@ var FactoryDecisionDispatcher = class {
484
604
  return;
485
605
  }
486
606
  await this.#supersedeProposals(record, decision);
607
+ if (record.attempts <= 1) await this.#reviewQueuedOnce(record, decision);
487
608
  await this.#withLease(async (leaseExpiresAt) => this.#storage.renewDeferredDecisionLease(leaseIdentity(record, this.#ownerId), leaseExpiresAt), async () => this.#executeDecision(record, decision));
488
609
  executionCompleted = true;
489
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
+ });
490
616
  } catch (error) {
491
617
  if (error instanceof FactoryDecisionSuperseded) {
492
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());
493
627
  return;
494
628
  }
495
629
  const failureCode = factoryDispatchFailureCode(error);
@@ -504,13 +638,91 @@ var FactoryDecisionDispatcher = class {
504
638
  advanceDeliveryGeneration: !executionCompleted
505
639
  });
506
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
+ });
507
646
  }
508
647
  }
509
648
  /**
510
- * Startup repair and terminal cleanup already settle a failed effect on a done or canceled
511
- * card as superseded; a failure landing after the card settled would otherwise page a person
512
- * until the next restart.
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.
513
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);
723
+ }
724
+ }
725
+ /** Terminal cleanup ran before this failure landed, so it never saw this row. */
514
726
  async #supersedeFailureOnSettledCard(record) {
515
727
  if (!record.workItemId) return;
516
728
  try {
@@ -573,72 +785,13 @@ var FactoryDecisionDispatcher = class {
573
785
  }];
574
786
  if (nextChain.length > 8) throw new Error("Factory rule causal depth exceeded.");
575
787
  switch (decision.type) {
576
- case "transition": {
577
- const item = await this.#requireItem(record);
578
- if (!await this.#storage.getTransitionResultByIngress(record.orgId, record.factoryProjectId, `decision:${record.idempotencyKey}`)) assertFactoryDecisionTarget(decision, await this.#boards.load(record), item.board ?? void 0);
579
- const result = await this.#transitionService.transition({
580
- orgId: record.orgId,
581
- factoryProjectId: record.factoryProjectId,
582
- workItemId: item.id,
583
- board: decision.board,
584
- stage: decision.stage,
585
- expectedRevision: item.revision,
586
- actor: record.approvedBy ? {
587
- type: "human",
588
- id: record.approvedBy
589
- } : {
590
- type: "system",
591
- id: "factory-rule-dispatcher"
592
- },
593
- ingress: {
594
- type: "rule",
595
- identity: `decision:${record.idempotencyKey}`
596
- },
597
- cause: "rule_decision",
598
- causalChain: nextChain,
599
- ...decision.reenter ? { reenter: true } : {}
600
- });
601
- if (result.status === "rejected") throw new Error(`${result.code}: ${result.reason}`);
602
- const transitionMessage = decision.message;
603
- if (!transitionMessage) return;
604
- const moved = await this.#storage.get({
605
- orgId: record.orgId,
606
- id: item.id
607
- });
608
- if (!moved) return;
609
- const messageKey = `${record.idempotencyKey}:message`;
610
- const queued = await this.#storage.commitRuleEvaluation({
611
- orgId: record.orgId,
612
- factoryProjectId: record.factoryProjectId,
613
- workItemId: item.id,
614
- ingress: {
615
- identity: `decision:${messageKey}@${moved.revision}`,
616
- triggerType: "transition.message"
617
- },
618
- configVersion: this.#transitionService.configVersion,
619
- expectedRevision: moved.revision,
620
- actor: record.actor ?? {
621
- type: "system",
622
- id: "factory-rule-dispatcher"
623
- },
624
- outcome: { status: "accepted" },
625
- decisions: [{
626
- type: "sendMessage",
627
- idempotencyKey: messageKey,
628
- message: transitionMessage.text,
629
- priority: "high",
630
- idleBehavior: "wake",
631
- ...transitionMessage.role !== void 0 ? { role: transitionMessage.role } : {}
632
- }],
633
- causalChain: nextChain,
634
- now: /* @__PURE__ */ new Date()
635
- });
636
- if (queued.status === "missing") return;
637
- if (queued.status === "stale") throw new Error("Factory transition message was not queued: the work item changed concurrently.");
638
- const queuedStatus = queued.result.status;
639
- 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);
640
794
  return;
641
- }
642
795
  case "upsertLinkedWorkItem":
643
796
  await this.#upsertLinkedItem(record, decision, nextChain);
644
797
  return;
@@ -680,27 +833,10 @@ var FactoryDecisionDispatcher = class {
680
833
  const kickoffLanded = async () => (await session.thread.listActiveMessages()).some((message) => message.id === deliveryId);
681
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);
682
835
  const runStillActive = () => this.#controller.listActiveThreadRuns().some((active) => active.threadId === binding.threadId);
683
- while (true) {
684
- const openRun = watchRun(session, {
685
- timeoutMs: this.#skillCompletionObservationTimeoutMs,
686
- approvePlans: false,
687
- label: "Factory skill run",
688
- runStillActive
689
- });
690
- try {
691
- const open = (await listSessionOpenRuns(session)).filter((entry) => entry.bindingId === binding.id);
692
- if (open.length === 0) break;
693
- 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.`);
694
- if (!runStillActive()) break;
695
- if (!await openRun.wait()) break;
696
- } finally {
697
- openRun.close();
698
- }
699
- await waitForSessionRunAudit(session);
700
- }
836
+ await this.#waitForOpenRun(session, binding, "Factory skill run");
701
837
  if (await this.#roleSuperseded(record, decision.role)) throw new FactoryDecisionSuperseded();
702
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.`);
703
- if (await kickoffLanded()) return;
839
+ if (await kickoffLanded()) return this.#replayLanded(record, decision, session, runStillActive);
704
840
  if (await kickoffStale()) throw new FactoryDecisionSuperseded();
705
841
  const kickoffContents = await withWorkItemFeed(this.#feedReader, {
706
842
  orgId: record.orgId,
@@ -715,8 +851,9 @@ var FactoryDecisionDispatcher = class {
715
851
  type: "user",
716
852
  tagName: "user"
717
853
  };
718
- if (await kickoffLanded()) return;
854
+ if (await kickoffLanded()) return this.#replayLanded(record, decision, session, runStillActive);
719
855
  if (await kickoffStale()) throw new FactoryDecisionSuperseded();
856
+ await this.#reviewQueuedOnce(record, decision);
720
857
  if (decision.cancelInFlight && session.stream.isActive()) session.abort();
721
858
  const precedingMessage = decision.precedingMessage;
722
859
  if (precedingMessage) {
@@ -739,6 +876,7 @@ var FactoryDecisionDispatcher = class {
739
876
  const run = watchRun(session, {
740
877
  timeoutMs: this.#skillCompletionObservationTimeoutMs,
741
878
  approvePlans: await this.#plansAreAutoApproved(record),
879
+ requestContext,
742
880
  onAgentEnd: () => this.#roleSuperseded(record, decision.role),
743
881
  label: "Factory skill run",
744
882
  runStillActive
@@ -766,6 +904,11 @@ var FactoryDecisionDispatcher = class {
766
904
  settled = await sendKickoff();
767
905
  }
768
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
+ });
769
912
  try {
770
913
  await this.#reportingRunEnd({
771
914
  binding,
@@ -774,8 +917,20 @@ var FactoryDecisionDispatcher = class {
774
917
  attempts: record.attempts,
775
918
  superseded: async () => await run.supersededAtEnd() ?? await this.#roleSuperseded(record, decision.role)
776
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
+ }
777
927
  } catch (error) {
778
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
+ });
779
934
  }
780
935
  } finally {
781
936
  run.close();
@@ -817,6 +972,9 @@ var FactoryDecisionDispatcher = class {
817
972
  }), true);
818
973
  return;
819
974
  }
975
+ case "signalActivity":
976
+ await this.#signalActivity(record, decision);
977
+ return;
820
978
  case "dismissStaleReviews":
821
979
  if (!this.#dismissStaleReviews) throw new Error("GitHub review dismissal is not configured.");
822
980
  await this.#dismissStaleReviews(decision);
@@ -1073,6 +1231,156 @@ var FactoryDecisionDispatcher = class {
1073
1231
  stage: board.initialPhase
1074
1232
  };
1075
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
+ }
1076
1384
  async #requireItem(record) {
1077
1385
  if (!record.workItemId) throw new Error("Factory decision is not linked to a work item.");
1078
1386
  const item = await this.#storage.get({
@@ -1095,6 +1403,50 @@ var FactoryDecisionDispatcher = class {
1095
1403
  if (!binding) throw new FactoryDispatchError("session_unavailable", role ? `No active Factory binding for role ${role}.` : "No active Factory binding.");
1096
1404
  return binding;
1097
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
+ }
1098
1450
  async #messageBinding(record, decision) {
1099
1451
  if (decision.prepareBinding && decision.role !== void 0) return this.#requireOrPrepareBinding(record, decision.role);
1100
1452
  return this.#findBinding(record, decision.role);
@@ -1171,6 +1523,38 @@ var FactoryDecisionDispatcher = class {
1171
1523
  factoryProjectId
1172
1524
  }), item) === "submit_plan";
1173
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
+ }
1174
1558
  async #requireSession(binding) {
1175
1559
  const session = await this.#findSession(binding);
1176
1560
  if (!session) throw new FactoryDispatchError("session_unavailable", "Bound Factory session not found.");
@@ -1314,6 +1698,7 @@ var FactoryDecisionDispatcher = class {
1314
1698
  ...record,
1315
1699
  workItemId: binding.workItemId
1316
1700
  }),
1701
+ requestContext,
1317
1702
  label: "Factory kickoff run",
1318
1703
  runStillActive: () => this.#controller.listActiveThreadRuns().some((active) => active.threadId === binding.threadId)
1319
1704
  });
@@ -1375,6 +1760,7 @@ const FACTORY_DISPATCH_CONSTANTS = {
1375
1760
  runRegistryHeartbeatMs: RUN_REGISTRY_HEARTBEAT_MS,
1376
1761
  openRunStaleMs: FACTORY_OPEN_RUN_STALE_MS,
1377
1762
  maxInFlight: MAX_IN_FLIGHT,
1763
+ reviewStatusTimeoutMs: REVIEW_STATUS_TIMEOUT_MS,
1378
1764
  stages: FACTORY_RULE_STAGES
1379
1765
  };
1380
1766
  export { FACTORY_DISPATCH_CONSTANTS, FactoryDecisionDispatcher };