@mastra/factory 0.28.0-alpha.1 → 0.28.0-alpha.3

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 (399) hide show
  1. package/README.md +244 -123
  2. package/dist/boards/board-events.d.ts +23 -3
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +44 -7
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts +1 -1
  7. package/dist/boards/board-writes.d.ts.map +1 -1
  8. package/dist/boards/board-writes.js +16 -1
  9. package/dist/boards/board-writes.js.map +1 -1
  10. package/dist/boards/card-facts.d.ts +1 -1
  11. package/dist/boards/card-facts.d.ts.map +1 -1
  12. package/dist/boards/card-facts.js +4 -0
  13. package/dist/boards/card-facts.js.map +1 -1
  14. package/dist/boards/default-board.d.ts +7 -0
  15. package/dist/boards/default-board.d.ts.map +1 -0
  16. package/dist/boards/default-board.js +10 -0
  17. package/dist/boards/default-board.js.map +1 -0
  18. package/dist/boards/define-board.d.ts +39 -17
  19. package/dist/boards/define-board.d.ts.map +1 -1
  20. package/dist/boards/define-board.js +64 -42
  21. package/dist/boards/define-board.js.map +1 -1
  22. package/dist/boards/index.d.ts +5 -8
  23. package/dist/boards/index.d.ts.map +1 -1
  24. package/dist/boards/index.js +5 -19
  25. package/dist/boards/intake-routing.d.ts +27 -5
  26. package/dist/boards/intake-routing.d.ts.map +1 -1
  27. package/dist/boards/intake-routing.js +69 -16
  28. package/dist/boards/intake-routing.js.map +1 -1
  29. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  30. package/dist/boards/legacy-plan-role.js +7 -2
  31. package/dist/boards/legacy-plan-role.js.map +1 -1
  32. package/dist/boards/phase-automation.d.ts +7 -0
  33. package/dist/boards/phase-automation.d.ts.map +1 -1
  34. package/dist/boards/phase-automation.js +16 -5
  35. package/dist/boards/phase-automation.js.map +1 -1
  36. package/dist/boards/phase-runner.d.ts +18 -10
  37. package/dist/boards/phase-runner.d.ts.map +1 -1
  38. package/dist/boards/phase-runner.js +39 -34
  39. package/dist/boards/phase-runner.js.map +1 -1
  40. package/dist/boards/project-boards.d.ts +9 -6
  41. package/dist/boards/project-boards.d.ts.map +1 -1
  42. package/dist/boards/project-boards.js +56 -18
  43. package/dist/boards/project-boards.js.map +1 -1
  44. package/dist/boards/registry.d.ts.map +1 -1
  45. package/dist/boards/registry.js +3 -1
  46. package/dist/boards/registry.js.map +1 -1
  47. package/dist/boards/relocate.d.ts +1 -1
  48. package/dist/boards/relocate.d.ts.map +1 -1
  49. package/dist/boards/relocate.js +3 -2
  50. package/dist/boards/relocate.js.map +1 -1
  51. package/dist/boards/review.d.ts +5 -2
  52. package/dist/boards/review.d.ts.map +1 -1
  53. package/dist/boards/review.js +12 -11
  54. package/dist/boards/review.js.map +1 -1
  55. package/dist/boards/semantics.d.ts +159 -20
  56. package/dist/boards/semantics.d.ts.map +1 -1
  57. package/dist/boards/semantics.js +256 -23
  58. package/dist/boards/semantics.js.map +1 -1
  59. package/dist/boards/stored-board.d.ts +32 -18
  60. package/dist/boards/stored-board.d.ts.map +1 -1
  61. package/dist/boards/stored-board.js +31 -97
  62. package/dist/boards/stored-board.js.map +1 -1
  63. package/dist/boards/work-migrations.d.ts +19 -0
  64. package/dist/boards/work-migrations.d.ts.map +1 -0
  65. package/dist/boards/work-migrations.js +257 -0
  66. package/dist/boards/work-migrations.js.map +1 -0
  67. package/dist/boards/work-routes.d.ts +53 -0
  68. package/dist/boards/work-routes.d.ts.map +1 -0
  69. package/dist/boards/work-routes.js +256 -0
  70. package/dist/boards/work-routes.js.map +1 -0
  71. package/dist/boards/work.d.ts +8 -19
  72. package/dist/boards/work.d.ts.map +1 -1
  73. package/dist/boards/work.js +38 -270
  74. package/dist/boards/work.js.map +1 -1
  75. package/dist/factory.d.ts +3 -3
  76. package/dist/factory.d.ts.map +1 -1
  77. package/dist/factory.js +58 -30
  78. package/dist/factory.js.map +1 -1
  79. package/dist/index.d.ts +2 -2
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +2 -3
  82. package/dist/integrations/base.d.ts +6 -2
  83. package/dist/integrations/base.d.ts.map +1 -1
  84. package/dist/integrations/closing-references.d.ts +15 -0
  85. package/dist/integrations/closing-references.d.ts.map +1 -0
  86. package/dist/integrations/closing-references.js +69 -0
  87. package/dist/integrations/closing-references.js.map +1 -0
  88. package/dist/integrations/github/default-rules.d.ts +15 -66
  89. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  90. package/dist/integrations/github/default-rules.js +129 -71
  91. package/dist/integrations/github/default-rules.js.map +1 -1
  92. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/github/issue-reconciler.js +3 -1
  94. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/github/pull-request-source.d.ts +8 -0
  96. package/dist/integrations/github/pull-request-source.d.ts.map +1 -0
  97. package/dist/integrations/github/pull-request-source.js +17 -0
  98. package/dist/integrations/github/pull-request-source.js.map +1 -0
  99. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -1
  100. package/dist/integrations/github/review-status-reporter.js +7 -3
  101. package/dist/integrations/github/review-status-reporter.js.map +1 -1
  102. package/dist/integrations/github/routes.js +1 -1
  103. package/dist/integrations/github/rules.d.ts +13 -2
  104. package/dist/integrations/github/rules.d.ts.map +1 -1
  105. package/dist/integrations/github/rules.js +202 -34
  106. package/dist/integrations/github/rules.js.map +1 -1
  107. package/dist/integrations/github/session-subscriptions.js +2 -2
  108. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  109. package/dist/integrations/github/token-refresh.d.ts +2 -1
  110. package/dist/integrations/github/token-refresh.d.ts.map +1 -1
  111. package/dist/integrations/github/token-refresh.js.map +1 -1
  112. package/dist/integrations/gitlab/agent-tools.js +1 -1
  113. package/dist/integrations/gitlab/default-rules.d.ts +73 -31
  114. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  115. package/dist/integrations/gitlab/default-rules.js +106 -43
  116. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  117. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  118. package/dist/integrations/gitlab/issue-reconciler.js +2 -1
  119. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  120. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  121. package/dist/integrations/gitlab/merge-request-reconciler.js +11 -4
  122. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  123. package/dist/integrations/gitlab/rules.d.ts +6 -1
  124. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  125. package/dist/integrations/gitlab/rules.js +116 -23
  126. package/dist/integrations/gitlab/rules.js.map +1 -1
  127. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  128. package/dist/integrations/incidentio/agent-tools.js +1 -1
  129. package/dist/integrations/incidentio/default-rules.js +3 -3
  130. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  131. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  132. package/dist/integrations/incidentio/issue-reconciler.js +2 -1
  133. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  134. package/dist/integrations/incidentio/rules.d.ts +3 -1
  135. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  136. package/dist/integrations/incidentio/rules.js +14 -11
  137. package/dist/integrations/incidentio/rules.js.map +1 -1
  138. package/dist/integrations/jira/agent-tools.js +1 -1
  139. package/dist/integrations/jira/default-rules.js +3 -3
  140. package/dist/integrations/jira/default-rules.js.map +1 -1
  141. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  142. package/dist/integrations/jira/issue-reconciler.js +2 -1
  143. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  144. package/dist/integrations/jira/rules.d.ts +3 -1
  145. package/dist/integrations/jira/rules.d.ts.map +1 -1
  146. package/dist/integrations/jira/rules.js +14 -11
  147. package/dist/integrations/jira/rules.js.map +1 -1
  148. package/dist/integrations/linear/agent-tools.d.ts +9 -1
  149. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  150. package/dist/integrations/linear/agent-tools.js +80 -2
  151. package/dist/integrations/linear/agent-tools.js.map +1 -1
  152. package/dist/integrations/linear/default-rules.js +3 -3
  153. package/dist/integrations/linear/default-rules.js.map +1 -1
  154. package/dist/integrations/linear/integration.d.ts +4 -1
  155. package/dist/integrations/linear/integration.d.ts.map +1 -1
  156. package/dist/integrations/linear/integration.js +21 -1
  157. package/dist/integrations/linear/integration.js.map +1 -1
  158. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  159. package/dist/integrations/linear/issue-reconciler.js +2 -1
  160. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  161. package/dist/integrations/linear/routes.d.ts +2 -1
  162. package/dist/integrations/linear/routes.d.ts.map +1 -1
  163. package/dist/integrations/linear/routes.js +4 -3
  164. package/dist/integrations/linear/routes.js.map +1 -1
  165. package/dist/integrations/linear/rules.d.ts +3 -1
  166. package/dist/integrations/linear/rules.d.ts.map +1 -1
  167. package/dist/integrations/linear/rules.js +15 -12
  168. package/dist/integrations/linear/rules.js.map +1 -1
  169. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  170. package/dist/integrations/platform/github/integration.js +33 -21
  171. package/dist/integrations/platform/github/integration.js.map +1 -1
  172. package/dist/integrations/platform/jira/agent-tools.js +1 -1
  173. package/dist/integrations/platform/linear/integration.d.ts +1 -1
  174. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  175. package/dist/integrations/platform/linear/integration.js +6 -5
  176. package/dist/integrations/platform/linear/integration.js.map +1 -1
  177. package/dist/integrations/slack/chat-tools.js +1 -1
  178. package/dist/integrations/slack/reply-tool.js +1 -1
  179. package/dist/integrations/slack/share-file-tool.js +1 -1
  180. package/dist/integrations/slack/slack.d.ts +10 -4
  181. package/dist/integrations/slack/slack.d.ts.map +1 -1
  182. package/dist/integrations/slack/slack.js +19 -9
  183. package/dist/integrations/slack/slack.js.map +1 -1
  184. package/dist/links.d.ts.map +1 -1
  185. package/dist/links.js +3 -2
  186. package/dist/links.js.map +1 -1
  187. package/dist/mcp/routes.js +2 -2
  188. package/dist/routes/attention-parked.d.ts +1 -0
  189. package/dist/routes/attention-parked.d.ts.map +1 -1
  190. package/dist/routes/attention-parked.js +1 -1
  191. package/dist/routes/attention-parked.js.map +1 -1
  192. package/dist/routes/automation-runs.d.ts +4 -0
  193. package/dist/routes/automation-runs.d.ts.map +1 -1
  194. package/dist/routes/automation-runs.js +15 -0
  195. package/dist/routes/automation-runs.js.map +1 -1
  196. package/dist/routes/boards.d.ts +1 -1
  197. package/dist/routes/boards.d.ts.map +1 -1
  198. package/dist/routes/boards.js +1 -17
  199. package/dist/routes/boards.js.map +1 -1
  200. package/dist/routes/config.d.ts +4 -0
  201. package/dist/routes/config.d.ts.map +1 -1
  202. package/dist/routes/config.js +15 -0
  203. package/dist/routes/config.js.map +1 -1
  204. package/dist/routes/contracts.d.ts +125 -14
  205. package/dist/routes/contracts.d.ts.map +1 -1
  206. package/dist/routes/contracts.js +34 -15
  207. package/dist/routes/contracts.js.map +1 -1
  208. package/dist/routes/fs.d.ts +4 -0
  209. package/dist/routes/fs.d.ts.map +1 -1
  210. package/dist/routes/fs.js +8 -4
  211. package/dist/routes/fs.js.map +1 -1
  212. package/dist/routes/intake-routes.d.ts.map +1 -1
  213. package/dist/routes/intake-routes.js.map +1 -1
  214. package/dist/routes/intake.d.ts.map +1 -1
  215. package/dist/routes/intake.js +1 -0
  216. package/dist/routes/intake.js.map +1 -1
  217. package/dist/routes/projects.d.ts.map +1 -1
  218. package/dist/routes/projects.js +8 -2
  219. package/dist/routes/projects.js.map +1 -1
  220. package/dist/routes/provider-credentials.d.ts.map +1 -1
  221. package/dist/routes/provider-credentials.js +10 -5
  222. package/dist/routes/provider-credentials.js.map +1 -1
  223. package/dist/routes/running-packages.d.ts +13 -0
  224. package/dist/routes/running-packages.d.ts.map +1 -0
  225. package/dist/routes/running-packages.js +45 -0
  226. package/dist/routes/running-packages.js.map +1 -0
  227. package/dist/routes/surface.d.ts +10 -1
  228. package/dist/routes/surface.d.ts.map +1 -1
  229. package/dist/routes/surface.js +104 -35
  230. package/dist/routes/surface.js.map +1 -1
  231. package/dist/routes/work-items.d.ts.map +1 -1
  232. package/dist/routes/work-items.js +23 -3
  233. package/dist/routes/work-items.js.map +1 -1
  234. package/dist/rules/binding-context.d.ts.map +1 -1
  235. package/dist/rules/binding-context.js +1 -0
  236. package/dist/rules/binding-context.js.map +1 -1
  237. package/dist/rules/dispatcher.d.ts +0 -1
  238. package/dist/rules/dispatcher.d.ts.map +1 -1
  239. package/dist/rules/dispatcher.js +340 -42
  240. package/dist/rules/dispatcher.js.map +1 -1
  241. package/dist/rules/event-rules.d.ts +33 -2
  242. package/dist/rules/event-rules.d.ts.map +1 -1
  243. package/dist/rules/event-rules.js +46 -11
  244. package/dist/rules/event-rules.js.map +1 -1
  245. package/dist/rules/index.d.ts +2 -4
  246. package/dist/rules/index.d.ts.map +1 -1
  247. package/dist/rules/index.js +2 -3
  248. package/dist/rules/phase-goal.d.ts +54 -0
  249. package/dist/rules/phase-goal.d.ts.map +1 -0
  250. package/dist/rules/phase-goal.js +70 -0
  251. package/dist/rules/phase-goal.js.map +1 -0
  252. package/dist/rules/phase-tools.d.ts +11 -0
  253. package/dist/rules/phase-tools.d.ts.map +1 -0
  254. package/dist/rules/phase-tools.js +19 -0
  255. package/dist/rules/phase-tools.js.map +1 -0
  256. package/dist/rules/processor.d.ts.map +1 -1
  257. package/dist/rules/processor.js +112 -11
  258. package/dist/rules/processor.js.map +1 -1
  259. package/dist/rules/review-source-tool.d.ts +4 -1
  260. package/dist/rules/review-source-tool.d.ts.map +1 -1
  261. package/dist/rules/review-source-tool.js +24 -4
  262. package/dist/rules/review-source-tool.js.map +1 -1
  263. package/dist/rules/rule-group.d.ts +1 -1
  264. package/dist/rules/rule-group.d.ts.map +1 -1
  265. package/dist/rules/rule-group.js +2 -1
  266. package/dist/rules/rule-group.js.map +1 -1
  267. package/dist/rules/start-coordinator.d.ts +5 -1
  268. package/dist/rules/start-coordinator.d.ts.map +1 -1
  269. package/dist/rules/start-coordinator.js +9 -3
  270. package/dist/rules/start-coordinator.js.map +1 -1
  271. package/dist/rules/tools.d.ts.map +1 -1
  272. package/dist/rules/tools.js +39 -28
  273. package/dist/rules/tools.js.map +1 -1
  274. package/dist/rules/transition-service.d.ts +2 -7
  275. package/dist/rules/transition-service.d.ts.map +1 -1
  276. package/dist/rules/transition-service.js +61 -54
  277. package/dist/rules/transition-service.js.map +1 -1
  278. package/dist/rules/types.d.ts +83 -29
  279. package/dist/rules/types.d.ts.map +1 -1
  280. package/dist/rules/types.js +5 -41
  281. package/dist/rules/types.js.map +1 -1
  282. package/dist/rules/validation.d.ts.map +1 -1
  283. package/dist/rules/validation.js +32 -2
  284. package/dist/rules/validation.js.map +1 -1
  285. package/dist/secret-encryption.d.ts +21 -0
  286. package/dist/secret-encryption.d.ts.map +1 -1
  287. package/dist/secret-encryption.js +31 -4
  288. package/dist/secret-encryption.js.map +1 -1
  289. package/dist/session/self-review-gate.d.ts +6 -2
  290. package/dist/session/self-review-gate.d.ts.map +1 -1
  291. package/dist/session/self-review-gate.js +8 -4
  292. package/dist/session/self-review-gate.js.map +1 -1
  293. package/dist/session/session-threads.d.ts +2 -3
  294. package/dist/session/session-threads.d.ts.map +1 -1
  295. package/dist/session/session-threads.js.map +1 -1
  296. package/dist/session/source-control-tools.js +1 -1
  297. package/dist/session/work-item-state-processor.d.ts +27 -0
  298. package/dist/session/work-item-state-processor.d.ts.map +1 -0
  299. package/dist/session/work-item-state-processor.js +288 -0
  300. package/dist/session/work-item-state-processor.js.map +1 -0
  301. package/dist/storage/domains/boards/base.d.ts +44 -27
  302. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  303. package/dist/storage/domains/boards/base.js +76 -121
  304. package/dist/storage/domains/boards/base.js.map +1 -1
  305. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  306. package/dist/storage/domains/boards/schemas.js +12 -0
  307. package/dist/storage/domains/boards/schemas.js.map +1 -1
  308. package/dist/storage/domains/work-items/base.d.ts +32 -2
  309. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  310. package/dist/storage/domains/work-items/base.js +109 -26
  311. package/dist/storage/domains/work-items/base.js.map +1 -1
  312. package/dist/storage/domains/work-items/cards.d.ts +24 -2
  313. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  314. package/dist/storage/domains/work-items/cards.js +118 -8
  315. package/dist/storage/domains/work-items/cards.js.map +1 -1
  316. package/dist/storage/domains/work-items/legacy-review.d.ts +63 -0
  317. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -0
  318. package/dist/storage/domains/work-items/legacy-review.js +95 -0
  319. package/dist/storage/domains/work-items/legacy-review.js.map +1 -0
  320. package/dist/storage/domains/work-items/metrics.d.ts +12 -4
  321. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
  322. package/dist/storage/domains/work-items/metrics.js +14 -32
  323. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  324. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  325. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  326. package/dist/storage/domains/work-items/work-item-schema.js +5 -0
  327. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  328. package/dist/tools/approval-tools.d.ts.map +1 -1
  329. package/dist/tools/approval-tools.js +28 -9
  330. package/dist/tools/approval-tools.js.map +1 -1
  331. package/dist/tools/index.d.ts +1 -1
  332. package/dist/tools/index.js +1 -1
  333. package/dist/tools/index.js.map +1 -1
  334. package/dist/tools/messaging-tools.d.ts +3 -0
  335. package/dist/tools/messaging-tools.d.ts.map +1 -1
  336. package/dist/tools/messaging-tools.js +2 -1
  337. package/dist/tools/messaging-tools.js.map +1 -1
  338. package/dist/tools/read-tools.d.ts +8 -2
  339. package/dist/tools/read-tools.d.ts.map +1 -1
  340. package/dist/tools/read-tools.js +83 -23
  341. package/dist/tools/read-tools.js.map +1 -1
  342. package/dist/tools/reports.d.ts +1 -0
  343. package/dist/tools/reports.d.ts.map +1 -1
  344. package/dist/tools/reports.js +2 -1
  345. package/dist/tools/reports.js.map +1 -1
  346. package/dist/tools/run-watch.d.ts +1 -1
  347. package/dist/tools/run-watch.d.ts.map +1 -1
  348. package/dist/tools/run-watch.js +1 -0
  349. package/dist/tools/run-watch.js.map +1 -1
  350. package/dist/tools/sandbox-tools.js +1 -1
  351. package/dist/tools/session-tools.js +1 -1
  352. package/dist/tools/sessions-state-processor.d.ts +2 -0
  353. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  354. package/dist/tools/sessions-state-processor.js +4 -2
  355. package/dist/tools/sessions-state-processor.js.map +1 -1
  356. package/dist/tools/side-sessions.d.ts +2 -0
  357. package/dist/tools/side-sessions.d.ts.map +1 -1
  358. package/dist/tools/side-sessions.js +2 -1
  359. package/dist/tools/side-sessions.js.map +1 -1
  360. package/dist/tools/work-item-tools.js +3 -3
  361. package/dist/tools/work-item-tools.js.map +1 -1
  362. package/dist/work-item-branch.d.ts +13 -0
  363. package/dist/work-item-branch.d.ts.map +1 -1
  364. package/dist/work-item-branch.js +16 -1
  365. package/dist/work-item-branch.js.map +1 -1
  366. package/dist/work-items/create-work-item.d.ts +6 -0
  367. package/dist/work-items/create-work-item.d.ts.map +1 -1
  368. package/dist/work-items/create-work-item.js +25 -1
  369. package/dist/work-items/create-work-item.js.map +1 -1
  370. package/dist/work-items/split-migration.d.ts.map +1 -1
  371. package/dist/work-items/split-migration.js +1 -0
  372. package/dist/work-items/split-migration.js.map +1 -1
  373. package/dist/workspace.d.ts.map +1 -1
  374. package/dist/workspace.js +53 -10
  375. package/dist/workspace.js.map +1 -1
  376. package/factory-skills/configure-factory-rules/SKILL.md +11 -9
  377. package/factory-skills/factory-build/SKILL.md +64 -0
  378. package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
  379. package/factory-skills/factory-gitlab-review/SKILL.md +2 -2
  380. package/factory-skills/factory-plan/SKILL.md +8 -10
  381. package/factory-skills/factory-rereview/SKILL.md +3 -3
  382. package/factory-skills/factory-review/SKILL.md +14 -4
  383. package/factory-skills/factory-self-review/SKILL.md +31 -11
  384. package/factory-skills/factory-triage/SKILL.md +25 -10
  385. package/package.json +9 -9
  386. package/dist/boards/index.js.map +0 -1
  387. package/dist/boards/pull-request-review.d.ts +0 -14
  388. package/dist/boards/pull-request-review.d.ts.map +0 -1
  389. package/dist/boards/pull-request-review.js +0 -81
  390. package/dist/boards/pull-request-review.js.map +0 -1
  391. package/dist/boards/work-tool-rules.d.ts +0 -8
  392. package/dist/boards/work-tool-rules.d.ts.map +0 -1
  393. package/dist/boards/work-tool-rules.js +0 -19
  394. package/dist/boards/work-tool-rules.js.map +0 -1
  395. package/dist/rules/resolve.d.ts +0 -15
  396. package/dist/rules/resolve.d.ts.map +0 -1
  397. package/dist/rules/resolve.js +0 -22
  398. package/dist/rules/resolve.js.map +0 -1
  399. package/factory-skills/factory-complete-issue/SKILL.md +0 -24
@@ -1,6 +1,9 @@
1
1
  import "../boards/index.js";
2
+ import { workStageCarries } from "../boards/legacy-plan-role.js";
3
+ import { boardFlow, boardForWorkItem, resolveBoardToolRule, reviewsPullRequest, workItemPhaseSemantics } from "../boards/semantics.js";
4
+ import { PHASE_EXIT_METADATA_KEY, exitToolSucceeded } from "../boards/phase-automation.js";
2
5
  import { toBoardSource } from "../boards/project-boards.js";
3
- import { boardForWorkItem, resolveBoardToolRule, reviewsPullRequest, workItemPhaseSemantics } from "../boards/semantics.js";
6
+ import { WorkItemUpdateConflictError } from "../storage/domains/work-items/base.js";
4
7
  import { findSessionRunBinding, getFactorySessionCoordinates } from "./binding-context.js";
5
8
  import { workItemSource } from "./types.js";
6
9
  import { assertFactoryDecisionTarget, normalizeFactoryRuleJsonValue, validateFactoryRuleDecisions } from "./validation.js";
@@ -23,6 +26,26 @@ function isApprovedPlanResult(result) {
23
26
  const content = result.value.content;
24
27
  return typeof content === "string" && content.startsWith("Plan approved.");
25
28
  }
29
+ const STAMP_ATTEMPTS = 3;
30
+ /** When the card's current visit to `stage` began, if it is in `stage` alone. */
31
+ function openEntry(item, stage) {
32
+ if (item.stages.length !== 1 || item.stages[0] !== stage) return void 0;
33
+ return item.stageHistory?.findLast((entry) => entry.stage === stage && entry.exitedAt === void 0)?.enteredAt;
34
+ }
35
+ /**
36
+ * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`,
37
+ * with an approved plan) in the session that works the card there. Undefined otherwise.
38
+ */
39
+ function finishedPhase(boards, board, item, role, toolResult) {
40
+ const stage = item.stages.length === 1 ? item.stages[0] : void 0;
41
+ const definition = boards.get(board);
42
+ const phase = stage === void 0 ? void 0 : definition?.phases[stage];
43
+ if (phase?.kind !== "working" || phase.exitTool?.id !== toolResult.toolName) return void 0;
44
+ if (toolResult.status !== "success") return void 0;
45
+ if (toolResult.toolName === "submit_plan" && !isApprovedPlanResult(toolResult)) return void 0;
46
+ if (role !== phase.runner.context && workStageCarries(definition, stage, role, void 0) !== true) return;
47
+ return stage;
48
+ }
26
49
  function reviewRuntimeFromRequestContext(requestContext, defaultThinkingLevel) {
27
50
  if (!requestContext || typeof requestContext.get !== "function") throw new Error("Factory review phase requires a controller request context.");
28
51
  const context = requestContext.get("controller");
@@ -42,7 +65,7 @@ function boundedError(value) {
42
65
  }
43
66
  function boundedResult(value) {
44
67
  try {
45
- return normalizeFactoryRuleJsonValue(value);
68
+ return normalizeFactoryRuleJsonValue(value === void 0 ? null : JSON.parse(JSON.stringify(value)));
46
69
  } catch {
47
70
  return { message: "Tool result was not serializable." };
48
71
  }
@@ -98,6 +121,18 @@ function currentCompletedToolMessage(messages, toolCallIds) {
98
121
  if (completedToolResults(message).some((result) => toolCallIds.has(result.toolCallId))) return message;
99
122
  }
100
123
  }
124
+ /**
125
+ * The tool results the step about to run follows: the latest assistant message, past any signals
126
+ * after it. A run continued after a tool call (such as submit_plan's approval) carries steps
127
+ * without their tool results, so the step ids alone can miss the result the agent acts on next.
128
+ */
129
+ function latestToolResultMessage(messages) {
130
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
131
+ const message = messages[index];
132
+ if (message.role === "signal") continue;
133
+ return message.role === "assistant" && completedToolResults(message).length > 0 ? message : void 0;
134
+ }
135
+ }
101
136
  async function phaseCacheKey(value, linked) {
102
137
  const serialized = JSON.stringify({
103
138
  ...value,
@@ -193,7 +228,12 @@ var FactoryPhaseStateProcessor = class {
193
228
  this.options.onBoundThreadRun?.();
194
229
  const completedToolCallIds = completedStepToolCallIds(args.steps);
195
230
  const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);
196
- if (completedMessage) await this.ingestMessages(binding, [completedMessage], completedToolCallIds);
231
+ if (completedMessage) {
232
+ await this.ingestMessages(binding, [completedMessage], completedToolCallIds);
233
+ return;
234
+ }
235
+ const latest = latestToolResultMessage(args.messages);
236
+ if (latest) await this.ingestMessages(binding, [latest]);
197
237
  }
198
238
  /**
199
239
  * Loads the caller's row once per invocation. The input hook always refreshes
@@ -236,12 +276,19 @@ var FactoryPhaseStateProcessor = class {
236
276
  if (!binding) return;
237
277
  if (binding.status !== "active") {
238
278
  if (!hasBase || prior?.status !== "active") return;
279
+ const moved = await this.options.storage.get({
280
+ orgId: binding.orgId,
281
+ id: binding.workItemId
282
+ });
283
+ const movedBoards = moved ? await this.boards.load(binding) : void 0;
284
+ const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : void 0;
285
+ const movedName = movedTo ? movedBoards?.get(boardForWorkItem(moved))?.phases[movedTo]?.name ?? movedTo : void 0;
239
286
  return {
240
287
  id: STATE_ID,
241
- cacheKey: `factory:none:${prior.bindingId ?? "revoked"}`,
288
+ cacheKey: `factory:none:${prior.bindingId ?? "revoked"}${movedTo ? `:${movedTo}` : ""}`,
242
289
  mode: "snapshot",
243
290
  tagName: "factory-phase",
244
- contents: "\n",
291
+ contents: movedName ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\n` : "\n",
245
292
  value: { phase: { status: "none" } },
246
293
  attributes: { status: "none" },
247
294
  metadata: { value: { phase: { status: "none" } } }
@@ -268,9 +315,13 @@ var FactoryPhaseStateProcessor = class {
268
315
  role: binding.role,
269
316
  configVersion: this.options.configVersion
270
317
  };
318
+ const flow = boardFlow(boards.get(board));
271
319
  const value = reviewsPullRequest({
272
- board,
273
- item: { source: workItemSource(item.externalSource) }
320
+ flow,
321
+ item: {
322
+ source: workItemSource(item.externalSource),
323
+ workItem: item.workItem
324
+ }
274
325
  }) ? {
275
326
  ...baseValue,
276
327
  board,
@@ -282,14 +333,30 @@ var FactoryPhaseStateProcessor = class {
282
333
  const cacheKey = await phaseCacheKey(value, linked);
283
334
  if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey) return;
284
335
  const linkedText = linked.length ? `\nLinked items: ${linked.map((candidate) => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join("; ")}` : "";
285
- const phase = boards.get(board)?.phases[stage];
336
+ const definition = boards.get(board);
337
+ const phase = definition?.phases[stage];
286
338
  const phaseLabel = phase?.name ?? stage;
287
- const exitText = phase?.kind === "working" && phase.exitTool ? boards.get(board)?.tools[phase.exitTool.id] ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === "submit_plan" ? " and is approved" : ""}; that moves the card on. Next phases: ${phase.nextPhases.map(escapeText).join(", ")}. You can move it on to a working phase yourself with factory_transition_work_item only when ${escapeText(phase.exitTool.id)} is auto-approved for this card; otherwise a person approves the handoff.\n` : `This phase ends when ${escapeText(phase.exitTool.id)} succeeds. Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(", ")}.\n` : "";
339
+ const nextText = phase ? `Next phases: ${phase.nextPhases.length ? phase.nextPhases.map((key) => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`).join("; ") : "none"}\n` : "";
340
+ const exitText = phase?.kind === "working" && phase.exitTool ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === "submit_plan" ? " with an approved plan" : ""}; until then the card stays here. ${definition?.tools[phase.exitTool.id] ? "Its result moves the card on." : `Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(", ")}.`}\n` : "";
341
+ const flowPhase = (key) => key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : void 0;
342
+ const completed = flow.completed?.phase;
343
+ const canceled = flow.canceled?.phase === completed ? void 0 : flow.canceled?.phase;
344
+ const flowParts = [
345
+ definition ? `rest: ${flowPhase(definition.initialPhase)}` : void 0,
346
+ flow.triage ? `triage: ${flowPhase(flow.triage)}` : void 0,
347
+ flow.build ? `build: ${flowPhase(flow.build)}` : void 0,
348
+ flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : void 0,
349
+ flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : void 0,
350
+ completed ? `completed: ${flowPhase(completed)}` : void 0,
351
+ canceled ? `canceled: ${flowPhase(canceled)}` : void 0
352
+ ].filter((part) => part !== void 0);
353
+ const flowText = flowParts.length ? `Board phases by part: ${flowParts.join("; ")}\n` : "";
354
+ const handedOnText = phase?.kind === "working" && phase.runner.context !== binding.role && workStageCarries(definition, stage, binding.role, void 0) !== true ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions, and move the card only if it must come back to you.\n` : "";
288
355
  const runtime = value.modelId && value.thinkingLevel ? {
289
356
  modelId: value.modelId,
290
357
  thinkingLevel: value.thinkingLevel
291
358
  } : null;
292
- const snapshotContents = `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\nWork item: ${escapeText(item.title)} (${item.id})\nRole: ${escapeText(binding.role)}\nRevision: ${item.revision}\nConfig: ${escapeText(this.options.configVersion)}\n` + (runtime ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\n` : "") + ((board === "work" || board === "review") && stage === "intake" ? "This card rests in Intake: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\n" : "") + exitText + `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;
359
+ const snapshotContents = `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\nWork item: ${escapeText(item.title)} (${item.id})\nRole: ${escapeText(binding.role)}\nRevision: ${item.revision}\nConfig: ${escapeText(this.options.configVersion)}\n` + (runtime ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\n` : "") + (phase?.kind === "resting" ? `This card rests in ${escapeText(phaseLabel)}: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\n` : "") + nextText + flowText + exitText + handedOnText + `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;
293
360
  const isDelta = hasBase && prior?.status === "active";
294
361
  return {
295
362
  id: STATE_ID,
@@ -374,9 +441,43 @@ var FactoryPhaseStateProcessor = class {
374
441
  await this.ingestToolResult(binding, item, toolResult);
375
442
  }
376
443
  }
377
- async ingestToolResult(binding, item, toolResult) {
444
+ async ingestToolResult(binding, loaded, toolResult) {
445
+ let item = loaded;
378
446
  const board = boardForWorkItem(item);
379
447
  const boards = await this.boards.load(binding);
448
+ const finished = finishedPhase(boards, board, item, binding.role, toolResult);
449
+ const at = (/* @__PURE__ */ new Date()).toISOString();
450
+ const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY])?.toolCallId;
451
+ if (finished !== void 0 && stampedCall !== toolResult.toolCallId && !exitToolSucceeded(item, finished, toolResult.toolName)) {
452
+ const entry = openEntry(item, finished);
453
+ for (let attempt = 1;; attempt++) try {
454
+ const stamped = await this.options.storage.update({
455
+ orgId: binding.orgId,
456
+ id: item.id,
457
+ userId: `agent:${binding.id}`,
458
+ patch: { metadata: {
459
+ [PHASE_EXIT_METADATA_KEY]: {
460
+ phase: finished,
461
+ tool: toolResult.toolName,
462
+ toolCallId: toolResult.toolCallId,
463
+ at
464
+ },
465
+ ...toolResult.toolName === "submit_plan" ? { planApprovedAt: at } : {}
466
+ } },
467
+ expectedRevision: item.revision
468
+ });
469
+ if (stamped) item = stamped.item;
470
+ break;
471
+ } catch (error) {
472
+ if (!(error instanceof WorkItemUpdateConflictError)) throw error;
473
+ const current = await this.options.storage.get({
474
+ orgId: binding.orgId,
475
+ id: item.id
476
+ });
477
+ if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === void 0) return;
478
+ item = current;
479
+ }
480
+ }
380
481
  const rule = resolveBoardToolRule(boards, board, toolResult.toolName);
381
482
  if (!rule) return;
382
483
  const ingressId = JSON.stringify([
@@ -1 +1 @@
1
- {"version":3,"file":"processor.js","names":[],"sources":["../../src/rules/processor.ts"],"sourcesContent":["import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model';\nimport type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type {\n ComputeStateSignalArgs,\n ComputeStateSignalResult,\n ProcessInputArgs,\n ProcessInputStepArgs,\n Processor,\n} from '@mastra/core/processors';\n\nimport { boardForWorkItem, resolveBoardToolRule, reviewsPullRequest, workItemPhaseSemantics } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, Card } from '../storage/domains/work-items/base.js';\nimport { findSessionRunBinding, getFactorySessionCoordinates } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { workItemSource } from './types.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleStage,\n FactoryToolResultRuleContext,\n} from './types.js';\nimport {\n assertFactoryDecisionTarget,\n normalizeFactoryRuleJsonValue,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst STATE_ID = 'factory-phase';\nconst RULE_TIMEOUT_MS = 5_000;\nconst TRANSCRIPT_PAGE_SIZE = 50;\nconst MAX_LINKED_ITEMS = 5;\nfunction ruleStage(boards: BoardRegistry, item: Card | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card {\n return ruleStage(boards, item) !== undefined;\n}\n\ntype PersistedMessageReader = {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n filter?: { dateRange?: { start?: Date } };\n orderBy: { field: 'createdAt'; direction: 'ASC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n};\n\ntype CompletedToolResult = {\n assistantMessageId: string;\n messageCreatedAt: Date;\n toolCallId: string;\n toolName: string;\n input: FactoryRuleJsonValue;\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n};\n\nfunction isApprovedPlanResult(result: CompletedToolResult): boolean {\n if (result.toolName !== 'submit_plan' || result.status !== 'success') return false;\n if (typeof result.value === 'string') return result.value.startsWith('Plan approved.');\n if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false;\n const content = result.value.content;\n return typeof content === 'string' && content.startsWith('Plan approved.');\n}\n\ntype RuntimeSnapshot = {\n modelId: string;\n thinkingLevel: ThinkingLevel;\n};\n\ntype ActivePhaseSnapshotBase = {\n bindingId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n role: string;\n configVersion: string;\n status: 'active';\n};\n\ntype ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & {\n board: string;\n modelId?: string;\n thinkingLevel?: ThinkingLevel;\n};\n\ntype PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' };\n\nfunction reviewRuntimeFromRequestContext(\n requestContext: ComputeStateSignalArgs['requestContext'],\n defaultThinkingLevel: ThinkingLevel | undefined,\n): RuntimeSnapshot {\n if (!requestContext || typeof requestContext.get !== 'function') {\n throw new Error('Factory review phase requires a controller request context.');\n }\n const context = requestContext.get<'controller', AgentControllerRequestContext<MastraCodeState>>('controller');\n const modelId = context?.session?.modelId.trim();\n if (!modelId) {\n throw new Error('Factory review phase requires a selected session model.');\n }\n return {\n modelId,\n thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, defaultThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: Card): string | null {\n const source = item.externalSource;\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction boundedError(value: unknown): FactoryRuleJsonValue {\n const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.';\n return { message: message.slice(0, 2_000) };\n}\n\nfunction boundedResult(value: unknown): FactoryRuleJsonValue {\n try {\n return normalizeFactoryRuleJsonValue(value);\n } catch {\n return { message: 'Tool result was not serializable.' };\n }\n}\n\nfunction messageParts(message: MastraDBMessage): unknown[] {\n const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n if (Array.isArray(content)) return content;\n if (Array.isArray(content?.parts)) return content.parts;\n return Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n}\n\nfunction completedStepToolCallIds(steps: unknown[]): Set<string> {\n const ids = new Set<string>();\n for (const rawStep of steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults;\n if (!Array.isArray(toolResults)) continue;\n for (const rawResult of toolResults) {\n if (!rawResult || typeof rawResult !== 'object') continue;\n const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId;\n if (typeof toolCallId === 'string') ids.add(toolCallId);\n }\n }\n return ids;\n}\n\nfunction completedToolResults(message: MastraDBMessage): CompletedToolResult[] {\n if (message.role !== 'assistant') return [];\n const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);\n const completed: CompletedToolResult[] = [];\n for (const rawPart of messageParts(message)) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : part;\n const state = invocation.state;\n if (state !== 'result' && state !== 'error') continue;\n const toolCallId = invocation.toolCallId;\n const toolName = invocation.toolName ?? invocation.name;\n if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue;\n completed.push({\n assistantMessageId: message.id,\n messageCreatedAt: createdAt,\n toolCallId,\n toolName: toolName.slice(0, 256),\n input: boundedResult(invocation.args ?? {}),\n status: state === 'error' ? 'error' : 'success',\n value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result),\n });\n }\n return completed;\n}\n\nfunction currentCompletedToolMessage(\n messages: MastraDBMessage[],\n toolCallIds: ReadonlySet<string>,\n): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: Card[]): Promise<string> {\n const serialized = JSON.stringify({\n ...value,\n linked: linked.map(item => [item.id, item.revision, item.stages[0]]),\n });\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString(\n 'hex',\n );\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nfunction phaseFromSignal(signal: { metadata?: Record<string, unknown> } | undefined): PhaseSnapshotValue | undefined {\n return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase;\n}\n\nfunction latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined {\n for (const signal of [...args.activeStateSignals].reverse()) {\n const phase = phaseFromSignal(signal);\n if (phase) return phase;\n }\n return phaseFromSignal(args.lastSnapshot);\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nconst reportedUnavailableMemorySettings = new WeakSet<object>();\n\n/**\n * Marks this run's Factory memory settings as unavailable so memory falls back\n * to auto, and tells the thread once per request that saved choices were not\n * applied. The reserved request-context key keeps clients from spoofing it.\n */\nexport function reportMemorySettingsUnavailable(\n requestContext: NonNullable<ProcessInputArgs['requestContext']>,\n reason: string,\n): void {\n requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason });\n console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason });\n if (reportedUnavailableMemorySettings.has(requestContext)) return;\n reportedUnavailableMemorySettings.add(requestContext);\n const controller = requestContext.get('controller') as\n | Pick<AgentControllerRequestContext<MastraCodeState>, 'emitEvent'>\n | undefined;\n controller?.emitEvent?.({\n type: 'error',\n error: new Error(\n 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.',\n ),\n errorType: 'factory_memory_settings_unavailable',\n retryable: false,\n });\n}\n\nexport class FactoryPhaseStateProcessor implements Processor<'factory-phase'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n /** Request contexts whose caller row is already resolved for this request. */\n private readonly loadedMemorySettings = new WeakSet<object>();\n private readonly boards: ProjectBoardSource;\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The session's routed thinking default, used when the session has not picked a level. */\n defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;\n /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */\n onBoundThreadRun?: () => void;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: Card;\n assistantMessageId: string;\n toolCallId: string;\n toolName: string;\n toolInput: FactoryRuleJsonValue;\n toolResult: FactoryRuleJsonValue;\n status: 'success' | 'error';\n }) => Promise<void>;\n },\n ) {\n this.boards = toBoardSource(options.boards);\n }\n\n /**\n * Memory settings are caller state, not run state. Factory invokes this while\n * resolving its configured processor list, before Agent resolves dynamic\n * Memory and enumerates Memory's processors. This guarantees both the Memory\n * options and its model callbacks see the authoritative row for this\n * invocation. Doing this in `processInputStep` would be too late: Memory's\n * input-step hook runs before configured processors.\n */\n async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise<void> {\n await this.loadCallerMemorySettings(requestContext, undefined, true);\n }\n\n async processInput(args: ProcessInputArgs): Promise<MessageList> {\n await this.loadCallerMemorySettings(args.requestContext);\n return args.messageList;\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<MessageList | undefined> {\n const address = getFactorySessionCoordinates(args.requestContext);\n let binding: FactoryRunBindingRecord | null | undefined;\n try {\n binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined;\n } catch {\n await this.loadCallerMemorySettings(args.requestContext, undefined);\n return;\n }\n // Resumed runs skip the input-processor phase, so re-check here: it is a\n // no-op once `processInput` already placed the row for this request. Passing\n // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a\n // recovered session reaches its project row from this hook too.\n await this.loadCallerMemorySettings(args.requestContext, binding);\n if (!binding || binding.status !== 'active') return;\n this.options.onBoundThreadRun?.();\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n }\n }\n\n /**\n * Loads the caller's row once per invocation. The input hook always refreshes\n * it in case the controller reused a request context; later step hooks reuse\n * that value (`undefined` means it has not been loaded yet; `null` means an\n * empty row).\n *\n * The WeakSet covers loaders that do not set the context key themselves, so a\n * request is still loaded once. A failed load records an unavailable sentinel\n * (memory then runs both roles on auto with default thresholds) and is not\n * marked loaded so the next step can retry.\n */\n private async loadCallerMemorySettings(\n requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'],\n binding?: FactoryRunBindingRecord | null,\n force = false,\n ): Promise<void> {\n if (!requestContext || !this.options.loadMemorySettings) return;\n const currentSettings = requestContext.get('mastra__factoryMemorySettings') as\n | { status?: unknown }\n | null\n | undefined;\n if (force) this.loadedMemorySettings.delete(requestContext);\n if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return;\n if (!force && this.loadedMemorySettings.has(requestContext)) return;\n try {\n let runBinding = binding ?? null;\n if (binding === undefined) {\n const address = getFactorySessionCoordinates(requestContext);\n runBinding = address\n ? await this.options.storage.findRunBindingBySession(address)\n : // Crash-recovered sessions come back with empty state, so the binding\n // table is the last source of the project whose row applies. Without\n // this the run would silently read the caller's personal row.\n await findSessionRunBinding(requestContext, this.options.storage);\n }\n await this.options.loadMemorySettings({ requestContext, binding: runBinding });\n this.loadedMemorySettings.add(requestContext);\n } catch (error) {\n reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error));\n }\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const address = getFactorySessionCoordinates(args.requestContext);\n if (!address) return;\n const binding = await this.options.storage.findRunBindingBySession(address);\n const prior = latestPhase(args);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n\n if (!binding) return;\n if (binding.status !== 'active') {\n if (!hasBase || prior?.status !== 'active') return;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: '\\n',\n value: { phase: { status: 'none' } },\n attributes: { status: 'none' },\n metadata: { value: { phase: { status: 'none' } } },\n };\n }\n\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const boards = await this.boards.load(binding);\n const stage = ruleStage(boards, item);\n if (!item || !stage) return;\n const allItems = await this.options.storage.listShared({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n });\n const linked = allItems\n .filter(candidate => candidate.parentWorkItemId === item.id || item.parentWorkItemId === candidate.id)\n .slice(0, MAX_LINKED_ITEMS);\n const board = boardForWorkItem(item);\n const baseValue: ActivePhaseSnapshotBase = {\n status: 'active',\n bindingId: binding.id,\n itemId: item.id,\n revision: item.revision,\n stage,\n role: binding.role,\n configVersion: this.options.configVersion,\n };\n const value: ActivePhaseSnapshotValue = reviewsPullRequest({\n board,\n item: { source: workItemSource(item.externalSource) },\n })\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.defaultThinkingLevel?.(args.requestContext),\n ),\n }\n : { ...baseValue, board };\n const cacheKey = await phaseCacheKey(value, linked);\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n\n const linkedText = linked.length\n ? `\\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}`\n : '';\n const phase = boards.get(board)?.phases[stage];\n const phaseLabel = phase?.name ?? stage;\n const exitText =\n phase?.kind === 'working' && phase.exitTool\n ? boards.get(board)?.tools[phase.exitTool.id]\n ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' and is approved' : ''}; that moves the card on. Next phases: ${phase.nextPhases.map(escapeText).join(', ')}. You can move it on to a working phase yourself with factory_transition_work_item only when ${escapeText(phase.exitTool.id)} is auto-approved for this card; otherwise a person approves the handoff.\\n`\n : `This phase ends when ${escapeText(phase.exitTool.id)} succeeds. Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(', ')}.\\n`\n : '';\n const runtime =\n value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null;\n const snapshotContents =\n `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\\n` +\n `Work item: ${escapeText(item.title)} (${item.id})\\n` +\n `Role: ${escapeText(binding.role)}\\nRevision: ${item.revision}\\nConfig: ${escapeText(this.options.configVersion)}\\n` +\n (runtime\n ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\\n`\n : '') +\n ((board === 'work' || board === 'review') && stage === 'intake'\n ? 'This card rests in Intake: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\\n'\n : '') +\n exitText +\n `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;\n const isDelta = hasBase && prior?.status === 'active';\n return {\n id: STATE_ID,\n cacheKey,\n mode: isDelta ? 'delta' : 'snapshot',\n tagName: 'factory-phase',\n contents: isDelta ? `Factory phase update:\\n${snapshotContents}` : snapshotContents,\n value: { phase: value },\n ...(isDelta ? { delta: { phase: value } } : {}),\n attributes: {\n status: 'active',\n board,\n stage,\n role: binding.role,\n revision: item.revision,\n ...(runtime ?? {}),\n },\n metadata: { value: { phase: value } },\n };\n }\n\n async reconcileAllBoundThreads(): Promise<void> {\n if (!this.options.messageReader) return;\n const bindings = await this.options.storage.listActiveRunBindings();\n for (const binding of bindings) await this.reconcileBinding(binding);\n }\n\n async reconcileBinding(binding: FactoryRunBindingRecord): Promise<void> {\n const reader = this.options.messageReader;\n if (!reader || binding.status !== 'active') return;\n // One keyed read up front: a binding whose item is gone or no longer in a\n // single rule stage would ingest nothing, so skip the cursor and message\n // reads entirely instead of paying them on every walk.\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);\n let page = 0;\n while (true) {\n const result = await reader.listMessages({\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n page,\n perPage: TRANSCRIPT_PAGE_SIZE,\n ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}),\n orderBy: { field: 'createdAt', direction: 'ASC' },\n });\n await this.ingestMessages(binding, result.messages, undefined, item);\n const last = result.messages.at(-1);\n if (last) {\n await this.options.storage.advanceToolResultCursor({\n bindingId: binding.id,\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n lastMessageId: last.id,\n lastMessageCreatedAt: last.createdAt instanceof Date ? last.createdAt : new Date(last.createdAt),\n updatedAt: new Date(),\n });\n }\n if (!result.hasMore) break;\n page += 1;\n }\n }\n\n private async ingestMessages(\n binding: FactoryRunBindingRecord,\n messages: MastraDBMessage[],\n toolCallIds?: ReadonlySet<string>,\n preloadedItem?: Card,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n for (const message of messages) {\n for (const toolResult of completedToolResults(message)) {\n if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue;\n try {\n await this.options.recordPullRequestProvenance?.({\n binding,\n item,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolInput: toolResult.input,\n toolResult: toolResult.value,\n status: toolResult.status,\n });\n } catch {\n // Provenance is supporting evidence and must not block authoritative rule ingress.\n }\n await this.ingestToolResult(binding, item, toolResult);\n }\n }\n }\n\n private async ingestToolResult(\n binding: FactoryRunBindingRecord,\n item: Card,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n const board = boardForWorkItem(item);\n const boards = await this.boards.load(binding);\n const rule = resolveBoardToolRule(boards, board, toolResult.toolName);\n if (!rule) return;\n const ingressId = JSON.stringify([\n binding.id,\n binding.threadId,\n toolResult.assistantMessageId,\n toolResult.toolCallId,\n ]);\n const prior = await this.options.storage.getTransitionResultByIngress(\n binding.orgId,\n binding.factoryProjectId,\n ingressId,\n );\n if (prior) return;\n const context: FactoryToolResultRuleContext = {\n tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId },\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'toolResult', id: ingressId },\n cause: `Completed ${toolResult.toolName}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n item: {\n id: item.id,\n source: workItemSource(item.externalSource),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board,\n itemRevision: item.revision,\n toolName: toolResult.toolName,\n threadId: binding.threadId,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n result: { status: toolResult.status, value: toolResult.value },\n };\n\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: FactoryCommitDecision[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context))));\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n const validated = validateFactoryRuleDecisions([decision]);\n for (const entry of validated) assertFactoryDecisionTarget(entry, boards, board);\n decisions = validated;\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory tool-result rule failed.',\n };\n }\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: ingressId, triggerType: 'tool.result' },\n configVersion: this.options.configVersion,\n expectedRevision: item.revision,\n actor: { ...context.actor },\n outcome,\n decisions: decisions.map(entry => ({ ...entry })),\n causalChain: [],\n now: new Date(),\n // The bound agent's own tool call carries the same consent as its governed moves.\n consentedBy: `agent:${binding.id}`,\n });\n if (committed.status !== 'committed' || !this.options.transitionService) return;\n for (const entry of decisions) {\n if (entry.type !== 'transition') continue;\n await this.options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n board: entry.board,\n stage: entry.stage,\n ...(entry.reenter ? { reenter: true } : {}),\n expectedRevision: item.revision,\n actor: { type: 'system', id: 'factory-tool-result-rule' },\n ingress: { type: 'rule', identity: `decision:${entry.idempotencyKey}` },\n cause: 'tool_result_rule',\n causalChain: [{ ingressId, decisionType: entry.type }],\n ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}),\n ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;AAkCA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,SAAS,UAAU,QAAuB,MAAmD;CAC3F,OAAO,QAAQ,uBAAuB,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAA;AACzE;AAEA,SAAS,gBAAgB,QAAuB,MAA6C;CAC3F,OAAO,UAAU,QAAQ,IAAI,MAAM,KAAA;AACrC;AAuBA,SAAS,qBAAqB,QAAsC;CAClE,IAAI,OAAO,aAAa,iBAAiB,OAAO,WAAW,WAAW,OAAO;CAC7E,IAAI,OAAO,OAAO,UAAU,UAAU,OAAO,OAAO,MAAM,WAAW,gBAAgB;CACrF,IAAI,CAAC,OAAO,SAAS,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aAAa,CAAC;GACd,qBAAK,IAAI,KAAK;GAEd,aAAa,SAAS,QAAQ;EAChC,CAAC,EAAA,CACa,WAAW,eAAe,CAAC,KAAK,QAAQ,mBAAmB;EACzE,KAAK,MAAM,SAAS,WAAW;GAC7B,IAAI,MAAM,SAAS,cAAc;GACjC,MAAM,KAAK,QAAQ,kBAAkB,WAAW;IAC9C,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,KAAK;IACjB,OAAO,MAAM;IACb,OAAO,MAAM;IACb,GAAI,MAAM,UAAU,EAAE,SAAS,KAAK,IAAI,CAAC;IACzC,kBAAkB,KAAK;IACvB,OAAO;KAAE,MAAM;KAAU,IAAI;IAA2B;IACxD,SAAS;KAAE,MAAM;KAAQ,UAAU,YAAY,MAAM;IAAiB;IACtE,OAAO;IACP,aAAa,CAAC;KAAE;KAAW,cAAc,MAAM;IAAK,CAAC;IACrD,GAAI,qBAAqB,UAAU,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACjE,GAAI,WAAW,WAAW,YAAY,EAAE,eAAe,WAAW,SAAS,IAAI,CAAC;GAClF,CAAC;EACH;CACF;AACF"}
1
+ {"version":3,"file":"processor.js","names":[],"sources":["../../src/rules/processor.ts"],"sourcesContent":["import { resolveRequestThinkingLevel } from '@mastra/code-sdk/agents/model';\nimport type { ThinkingLevel } from '@mastra/code-sdk/providers/openai-codex';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { MastraDBMessage, MessageList } from '@mastra/core/agent/message-list';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type {\n ComputeStateSignalArgs,\n ComputeStateSignalResult,\n ProcessInputArgs,\n ProcessInputStepArgs,\n Processor,\n} from '@mastra/core/processors';\n\nimport {\n boardFlow,\n boardForWorkItem,\n resolveBoardToolRule,\n reviewsPullRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { workStageCarries } from '../boards/legacy-plan-role.js';\nimport { exitToolSucceeded, PHASE_EXIT_METADATA_KEY } from '../boards/phase-automation.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { FactoryRunBindingRecord, WorkItemsStorage, Card } from '../storage/domains/work-items/base.js';\nimport { findSessionRunBinding, getFactorySessionCoordinates } from './binding-context.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { workItemSource } from './types.js';\nimport type {\n FactoryCommitDecision,\n FactoryRuleDecision,\n FactoryRuleJsonValue,\n FactoryRuleStage,\n FactoryToolResultRuleContext,\n} from './types.js';\nimport {\n assertFactoryDecisionTarget,\n normalizeFactoryRuleJsonValue,\n validateFactoryRuleDecisions,\n} from './validation.js';\n\nconst STATE_ID = 'factory-phase';\nconst RULE_TIMEOUT_MS = 5_000;\nconst TRANSCRIPT_PAGE_SIZE = 50;\nconst MAX_LINKED_ITEMS = 5;\nfunction ruleStage(boards: BoardRegistry, item: Card | null | undefined): string | undefined {\n return item && workItemPhaseSemantics(boards, item) ? item.stages[0] : undefined;\n}\n\nfunction itemInRuleStage(boards: BoardRegistry, item: Card | null | undefined): item is Card {\n return ruleStage(boards, item) !== undefined;\n}\n\ntype PersistedMessageReader = {\n listMessages(input: {\n threadId: string;\n resourceId?: string;\n page: number;\n perPage: number;\n filter?: { dateRange?: { start?: Date } };\n orderBy: { field: 'createdAt'; direction: 'ASC' };\n }): Promise<{ messages: MastraDBMessage[]; hasMore: boolean }>;\n};\n\ntype CompletedToolResult = {\n assistantMessageId: string;\n messageCreatedAt: Date;\n toolCallId: string;\n toolName: string;\n input: FactoryRuleJsonValue;\n status: 'success' | 'error';\n value: FactoryRuleJsonValue;\n};\n\nfunction isApprovedPlanResult(result: CompletedToolResult): boolean {\n if (result.toolName !== 'submit_plan' || result.status !== 'success') return false;\n if (typeof result.value === 'string') return result.value.startsWith('Plan approved.');\n if (!result.value || typeof result.value !== 'object' || Array.isArray(result.value)) return false;\n const content = result.value.content;\n return typeof content === 'string' && content.startsWith('Plan approved.');\n}\n\nconst STAMP_ATTEMPTS = 3;\n\n/** When the card's current visit to `stage` began, if it is in `stage` alone. */\nfunction openEntry(item: Card, stage: string): string | undefined {\n if (item.stages.length !== 1 || item.stages[0] !== stage) return undefined;\n return item.stageHistory?.findLast(entry => entry.stage === stage && entry.exitedAt === undefined)?.enteredAt;\n}\n\n/**\n * The phase this result finishes: the card's phase whose exit tool succeeded (for `submit_plan`,\n * with an approved plan) in the session that works the card there. Undefined otherwise.\n */\nfunction finishedPhase(\n boards: BoardRegistry,\n board: string,\n item: Card,\n role: string,\n toolResult: CompletedToolResult,\n): string | undefined {\n const stage = item.stages.length === 1 ? item.stages[0]! : undefined;\n const definition = boards.get(board);\n const phase = stage === undefined ? undefined : definition?.phases[stage];\n if (phase?.kind !== 'working' || phase.exitTool?.id !== toolResult.toolName) return undefined;\n if (toolResult.status !== 'success') return undefined;\n if (toolResult.toolName === 'submit_plan' && !isApprovedPlanResult(toolResult)) return undefined;\n // Only the session that works the card in this phase finishes it: one in another context that\n // still holds the card (a triage session, say) calling the same tool leaves the phase unfinished.\n // A Work card planned before Planning ran in the `work` context still holds its `plan` session.\n if (role !== phase.runner.context && workStageCarries(definition, stage!, role, undefined) !== true) {\n return undefined;\n }\n return stage;\n}\n\ntype RuntimeSnapshot = {\n modelId: string;\n thinkingLevel: ThinkingLevel;\n};\n\ntype ActivePhaseSnapshotBase = {\n bindingId: string;\n itemId: string;\n revision: number;\n stage: FactoryRuleStage;\n role: string;\n configVersion: string;\n status: 'active';\n};\n\ntype ActivePhaseSnapshotValue = ActivePhaseSnapshotBase & {\n board: string;\n modelId?: string;\n thinkingLevel?: ThinkingLevel;\n};\n\ntype PhaseSnapshotValue = ActivePhaseSnapshotValue | { bindingId?: string; status: 'none' };\n\nfunction reviewRuntimeFromRequestContext(\n requestContext: ComputeStateSignalArgs['requestContext'],\n defaultThinkingLevel: ThinkingLevel | undefined,\n): RuntimeSnapshot {\n if (!requestContext || typeof requestContext.get !== 'function') {\n throw new Error('Factory review phase requires a controller request context.');\n }\n const context = requestContext.get<'controller', AgentControllerRequestContext<MastraCodeState>>('controller');\n const modelId = context?.session?.modelId.trim();\n if (!modelId) {\n throw new Error('Factory review phase requires a selected session model.');\n }\n return {\n modelId,\n thinkingLevel: resolveRequestThinkingLevel({ state: context?.state }, undefined, defaultThinkingLevel),\n };\n}\n\nfunction workItemSourceKey(item: Card): string | null {\n const source = item.externalSource;\n return source ? `${source.integrationId}:${source.type}:${source.externalId}` : null;\n}\n\nfunction boundedError(value: unknown): FactoryRuleJsonValue {\n const message = value instanceof Error ? value.message : typeof value === 'string' ? value : 'Tool execution failed.';\n return { message: message.slice(0, 2_000) };\n}\n\nfunction boundedResult(value: unknown): FactoryRuleJsonValue {\n try {\n // A result read during the run is the tool's in-memory value (submit_plan's holds undefined\n // fields); read it as the JSON the thread stores, so it means the same now as after the run.\n return normalizeFactoryRuleJsonValue(value === undefined ? null : JSON.parse(JSON.stringify(value)));\n } catch {\n return { message: 'Tool result was not serializable.' };\n }\n}\n\nfunction messageParts(message: MastraDBMessage): unknown[] {\n const content = message.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n if (Array.isArray(content)) return content;\n if (Array.isArray(content?.parts)) return content.parts;\n return Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n}\n\nfunction completedStepToolCallIds(steps: unknown[]): Set<string> {\n const ids = new Set<string>();\n for (const rawStep of steps) {\n if (!rawStep || typeof rawStep !== 'object') continue;\n const toolResults = (rawStep as { toolResults?: unknown[] }).toolResults;\n if (!Array.isArray(toolResults)) continue;\n for (const rawResult of toolResults) {\n if (!rawResult || typeof rawResult !== 'object') continue;\n const toolCallId = (rawResult as { toolCallId?: unknown }).toolCallId;\n if (typeof toolCallId === 'string') ids.add(toolCallId);\n }\n }\n return ids;\n}\n\nfunction completedToolResults(message: MastraDBMessage): CompletedToolResult[] {\n if (message.role !== 'assistant') return [];\n const createdAt = message.createdAt instanceof Date ? message.createdAt : new Date(message.createdAt);\n const completed: CompletedToolResult[] = [];\n for (const rawPart of messageParts(message)) {\n if (!rawPart || typeof rawPart !== 'object') continue;\n const part = rawPart as Record<string, unknown>;\n const invocation =\n part.type === 'tool-invocation' && part.toolInvocation && typeof part.toolInvocation === 'object'\n ? (part.toolInvocation as Record<string, unknown>)\n : part;\n const state = invocation.state;\n if (state !== 'result' && state !== 'error') continue;\n const toolCallId = invocation.toolCallId;\n const toolName = invocation.toolName ?? invocation.name;\n if (typeof toolCallId !== 'string' || typeof toolName !== 'string') continue;\n completed.push({\n assistantMessageId: message.id,\n messageCreatedAt: createdAt,\n toolCallId,\n toolName: toolName.slice(0, 256),\n input: boundedResult(invocation.args ?? {}),\n status: state === 'error' ? 'error' : 'success',\n value: state === 'error' ? boundedError(invocation.result ?? invocation.error) : boundedResult(invocation.result),\n });\n }\n return completed;\n}\n\nfunction currentCompletedToolMessage(\n messages: MastraDBMessage[],\n toolCallIds: ReadonlySet<string>,\n): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if (completedToolResults(message).some(result => toolCallIds.has(result.toolCallId))) return message;\n }\n return undefined;\n}\n\n/**\n * The tool results the step about to run follows: the latest assistant message, past any signals\n * after it. A run continued after a tool call (such as submit_plan's approval) carries steps\n * without their tool results, so the step ids alone can miss the result the agent acts on next.\n */\nfunction latestToolResultMessage(messages: MastraDBMessage[]): MastraDBMessage | undefined {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]!;\n if ((message.role as string) === 'signal') continue;\n return message.role === 'assistant' && completedToolResults(message).length > 0 ? message : undefined;\n }\n return undefined;\n}\n\nasync function phaseCacheKey(value: ActivePhaseSnapshotValue, linked: Card[]): Promise<string> {\n const serialized = JSON.stringify({\n ...value,\n linked: linked.map(item => [item.id, item.revision, item.stages[0]]),\n });\n return Buffer.from(await globalThis.crypto.subtle.digest('SHA-256', new TextEncoder().encode(serialized))).toString(\n 'hex',\n );\n}\n\nfunction escapeText(value: string): string {\n return value.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;');\n}\n\nfunction phaseFromSignal(signal: { metadata?: Record<string, unknown> } | undefined): PhaseSnapshotValue | undefined {\n return (signal?.metadata?.value as { phase?: PhaseSnapshotValue } | undefined)?.phase;\n}\n\nfunction latestPhase(args: ComputeStateSignalArgs): PhaseSnapshotValue | undefined {\n for (const signal of [...args.activeStateSignals].reverse()) {\n const phase = phaseFromSignal(signal);\n if (phase) return phase;\n }\n return phaseFromSignal(args.lastSnapshot);\n}\n\nasync function withRuleTimeout<T>(operation: Promise<T>): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nconst reportedUnavailableMemorySettings = new WeakSet<object>();\n\n/**\n * Marks this run's Factory memory settings as unavailable so memory falls back\n * to auto, and tells the thread once per request that saved choices were not\n * applied. The reserved request-context key keeps clients from spoofing it.\n */\nexport function reportMemorySettingsUnavailable(\n requestContext: NonNullable<ProcessInputArgs['requestContext']>,\n reason: string,\n): void {\n requestContext.set('mastra__factoryMemorySettings', { status: 'unavailable', reason });\n console.warn('[Factory Memory Settings] Failed to load settings for run', { error: reason });\n if (reportedUnavailableMemorySettings.has(requestContext)) return;\n reportedUnavailableMemorySettings.add(requestContext);\n const controller = requestContext.get('controller') as\n | Pick<AgentControllerRequestContext<MastraCodeState>, 'emitEvent'>\n | undefined;\n controller?.emitEvent?.({\n type: 'error',\n error: new Error(\n 'Memory settings could not be loaded for this run, so observational memory is using Auto models and default thresholds.',\n ),\n errorType: 'factory_memory_settings_unavailable',\n retryable: false,\n });\n}\n\nexport class FactoryPhaseStateProcessor implements Processor<'factory-phase'> {\n readonly id = STATE_ID;\n readonly stateId = STATE_ID;\n /** Request contexts whose caller row is already resolved for this request. */\n private readonly loadedMemorySettings = new WeakSet<object>();\n private readonly boards: ProjectBoardSource;\n\n constructor(\n private readonly options: {\n configVersion: string;\n storage: WorkItemsStorage;\n boards: BoardRegistry | ProjectBoardSource;\n loadMemorySettings?: (args: {\n requestContext: ProcessInputStepArgs['requestContext'];\n binding: FactoryRunBindingRecord | null;\n }) => Promise<void>;\n /** The session's routed thinking default, used when the session has not picked a level. */\n defaultThinkingLevel?: (requestContext: ComputeStateSignalArgs['requestContext']) => Promise<ThinkingLevel>;\n /** Called on every step of a run on an active bound thread, so an idle dispatcher reconciles its tool results. */\n onBoundThreadRun?: () => void;\n transitionService?: Pick<FactoryTransitionService, 'transition'>;\n messageReader?: PersistedMessageReader;\n recordPullRequestProvenance?: (input: {\n binding: FactoryRunBindingRecord;\n item: Card;\n assistantMessageId: string;\n toolCallId: string;\n toolName: string;\n toolInput: FactoryRuleJsonValue;\n toolResult: FactoryRuleJsonValue;\n status: 'success' | 'error';\n }) => Promise<void>;\n },\n ) {\n this.boards = toBoardSource(options.boards);\n }\n\n /**\n * Memory settings are caller state, not run state. Factory invokes this while\n * resolving its configured processor list, before Agent resolves dynamic\n * Memory and enumerates Memory's processors. This guarantees both the Memory\n * options and its model callbacks see the authoritative row for this\n * invocation. Doing this in `processInputStep` would be too late: Memory's\n * input-step hook runs before configured processors.\n */\n async prepareMemorySettings(requestContext: ProcessInputArgs['requestContext']): Promise<void> {\n await this.loadCallerMemorySettings(requestContext, undefined, true);\n }\n\n async processInput(args: ProcessInputArgs): Promise<MessageList> {\n await this.loadCallerMemorySettings(args.requestContext);\n return args.messageList;\n }\n\n async processInputStep(args: ProcessInputStepArgs): Promise<MessageList | undefined> {\n const address = getFactorySessionCoordinates(args.requestContext);\n let binding: FactoryRunBindingRecord | null | undefined;\n try {\n binding = address ? await this.options.storage.findRunBindingBySession(address) : undefined;\n } catch {\n await this.loadCallerMemorySettings(args.requestContext, undefined);\n return;\n }\n // Resumed runs skip the input-processor phase, so re-check here: it is a\n // no-op once `processInput` already placed the row for this request. Passing\n // `undefined` (not `null`) keeps the recovery lookup inside the loader, so a\n // recovered session reaches its project row from this hook too.\n await this.loadCallerMemorySettings(args.requestContext, binding);\n if (!binding || binding.status !== 'active') return;\n this.options.onBoundThreadRun?.();\n const completedToolCallIds = completedStepToolCallIds(args.steps);\n const completedMessage = currentCompletedToolMessage(args.messages, completedToolCallIds);\n if (completedMessage) {\n await this.ingestMessages(binding, [completedMessage], completedToolCallIds);\n return;\n }\n const latest = latestToolResultMessage(args.messages);\n if (latest) await this.ingestMessages(binding, [latest]);\n }\n\n /**\n * Loads the caller's row once per invocation. The input hook always refreshes\n * it in case the controller reused a request context; later step hooks reuse\n * that value (`undefined` means it has not been loaded yet; `null` means an\n * empty row).\n *\n * The WeakSet covers loaders that do not set the context key themselves, so a\n * request is still loaded once. A failed load records an unavailable sentinel\n * (memory then runs both roles on auto with default thresholds) and is not\n * marked loaded so the next step can retry.\n */\n private async loadCallerMemorySettings(\n requestContext: ProcessInputStepArgs['requestContext'] | ProcessInputArgs['requestContext'],\n binding?: FactoryRunBindingRecord | null,\n force = false,\n ): Promise<void> {\n if (!requestContext || !this.options.loadMemorySettings) return;\n const currentSettings = requestContext.get('mastra__factoryMemorySettings') as\n | { status?: unknown }\n | null\n | undefined;\n if (force) this.loadedMemorySettings.delete(requestContext);\n if (!force && currentSettings !== undefined && currentSettings?.status !== 'unavailable') return;\n if (!force && this.loadedMemorySettings.has(requestContext)) return;\n try {\n let runBinding = binding ?? null;\n if (binding === undefined) {\n const address = getFactorySessionCoordinates(requestContext);\n runBinding = address\n ? await this.options.storage.findRunBindingBySession(address)\n : // Crash-recovered sessions come back with empty state, so the binding\n // table is the last source of the project whose row applies. Without\n // this the run would silently read the caller's personal row.\n await findSessionRunBinding(requestContext, this.options.storage);\n }\n await this.options.loadMemorySettings({ requestContext, binding: runBinding });\n this.loadedMemorySettings.add(requestContext);\n } catch (error) {\n reportMemorySettingsUnavailable(requestContext, error instanceof Error ? error.message : String(error));\n }\n }\n\n async computeStateSignal(args: ComputeStateSignalArgs): Promise<ComputeStateSignalResult> {\n const address = getFactorySessionCoordinates(args.requestContext);\n if (!address) return;\n const binding = await this.options.storage.findRunBindingBySession(address);\n const prior = latestPhase(args);\n const hasBase = Boolean(args.lastSnapshot) && args.contextWindow.hasSnapshot;\n\n if (!binding) return;\n if (binding.status !== 'active') {\n if (!hasBase || prior?.status !== 'active') return;\n // Say where the card went, so the session stops its work instead of guessing why its phase vanished.\n const moved = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const movedBoards = moved ? await this.boards.load(binding) : undefined;\n const movedTo = moved && movedBoards ? ruleStage(movedBoards, moved) : undefined;\n const movedName = movedTo\n ? (movedBoards?.get(boardForWorkItem(moved!))?.phases[movedTo]?.name ?? movedTo)\n : undefined;\n return {\n id: STATE_ID,\n cacheKey: `factory:none:${prior.bindingId ?? 'revoked'}${movedTo ? `:${movedTo}` : ''}`,\n mode: 'snapshot',\n tagName: 'factory-phase',\n contents: movedName\n ? `This session no longer works its Factory card; the card is now in ${escapeText(movedName)}. Your part is done: do not continue its work here. Answer questions only.\\n`\n : '\\n',\n value: { phase: { status: 'none' } },\n attributes: { status: 'none' },\n metadata: { value: { phase: { status: 'none' } } },\n };\n }\n\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n const boards = await this.boards.load(binding);\n const stage = ruleStage(boards, item);\n if (!item || !stage) return;\n const allItems = await this.options.storage.listShared({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n });\n const linked = allItems\n .filter(candidate => candidate.parentWorkItemId === item.id || item.parentWorkItemId === candidate.id)\n .slice(0, MAX_LINKED_ITEMS);\n const board = boardForWorkItem(item);\n const baseValue: ActivePhaseSnapshotBase = {\n status: 'active',\n bindingId: binding.id,\n itemId: item.id,\n revision: item.revision,\n stage,\n role: binding.role,\n configVersion: this.options.configVersion,\n };\n const flow = boardFlow(boards.get(board));\n const value: ActivePhaseSnapshotValue = reviewsPullRequest({\n flow,\n item: { source: workItemSource(item.externalSource), workItem: item.workItem },\n })\n ? {\n ...baseValue,\n board,\n ...reviewRuntimeFromRequestContext(\n args.requestContext,\n await this.options.defaultThinkingLevel?.(args.requestContext),\n ),\n }\n : { ...baseValue, board };\n const cacheKey = await phaseCacheKey(value, linked);\n if (hasBase && (args.tracking?.currentCacheKey ?? args.lastSnapshot?.metadata?.state?.cacheKey) === cacheKey)\n return;\n\n const linkedText = linked.length\n ? `\\nLinked items: ${linked.map(candidate => `${workItemSource(candidate.externalSource)} ${candidate.title}`).join('; ')}`\n : '';\n const definition = boards.get(board);\n const phase = definition?.phases[stage];\n const phaseLabel = phase?.name ?? stage;\n const nextText = phase\n ? `Next phases: ${\n phase.nextPhases.length\n ? phase.nextPhases\n .map(key => `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})`)\n .join('; ')\n : 'none'\n }\\n`\n : '';\n const exitText =\n phase?.kind === 'working' && phase.exitTool\n ? `This phase ends when ${escapeText(phase.exitTool.id)} succeeds${phase.exitTool.id === 'submit_plan' ? ' with an approved plan' : ''}; until then the card stays here. ${\n definition?.tools[phase.exitTool.id]\n ? 'Its result moves the card on.'\n : `Then move the card with factory_transition_work_item to one of: ${phase.nextPhases.map(escapeText).join(', ')}.`\n }\\n`\n : '';\n // Skills name phases by role in the pull request loop, never by key: this line maps them.\n const flowPhase = (key: string | undefined) =>\n key ? `${escapeText(definition?.phases[key]?.name ?? key)} (${escapeText(key)})` : undefined;\n const completed = flow.completed?.phase;\n const canceled = flow.canceled?.phase === completed ? undefined : flow.canceled?.phase;\n const flowParts = [\n definition ? `rest: ${flowPhase(definition.initialPhase)}` : undefined,\n flow.triage ? `triage: ${flowPhase(flow.triage)}` : undefined,\n flow.build ? `build: ${flowPhase(flow.build)}` : undefined,\n flow.selfReview ? `self-review: ${flowPhase(flow.selfReview)}` : undefined,\n flow.pullRequestReview ? `pull request review: ${flowPhase(flow.pullRequestReview)}` : undefined,\n completed ? `completed: ${flowPhase(completed)}` : undefined,\n canceled ? `canceled: ${flowPhase(canceled)}` : undefined,\n ].filter(part => part !== undefined);\n const flowText = flowParts.length ? `Board phases by part: ${flowParts.join('; ')}\\n` : '';\n // The card moved to a phase another context works; this session's tools for it are gone.\n const handedOnText =\n phase?.kind === 'working' &&\n phase.runner.context !== binding.role &&\n // A Work card planned before Planning ran in `work` keeps its `plan` session there.\n workStageCarries(definition, stage, binding.role, undefined) !== true\n ? `This card is now in ${escapeText(phaseLabel)}, which runs in the ${escapeText(phase.runner.context)} context in another session. Your part is done: do not continue its work here. Answer questions, and move the card only if it must come back to you.\\n`\n : '';\n const runtime =\n value.modelId && value.thinkingLevel ? { modelId: value.modelId, thinkingLevel: value.thinkingLevel } : null;\n const snapshotContents =\n `Factory ${board} phase: ${escapeText(phaseLabel)} (${escapeText(stage)})\\n` +\n `Work item: ${escapeText(item.title)} (${item.id})\\n` +\n `Role: ${escapeText(binding.role)}\\nRevision: ${item.revision}\\nConfig: ${escapeText(this.options.configVersion)}\\n` +\n (runtime\n ? `Runtime: model=${escapeText(runtime.modelId)}, reasoning-setting=${escapeText(runtime.thinkingLevel)}\\n`\n : '') +\n (phase?.kind === 'resting'\n ? `This card rests in ${escapeText(phaseLabel)}: its work is paused. Answer questions without moving it; when the user asks to resume, request the transition into the working stage first, then continue the work in this session.\\n`\n : '') +\n nextText +\n flowText +\n exitText +\n handedOnText +\n `Use factory_transition_work_item with expectedRevision ${item.revision} to request a phase change.${escapeText(linkedText)}`;\n const isDelta = hasBase && prior?.status === 'active';\n return {\n id: STATE_ID,\n cacheKey,\n mode: isDelta ? 'delta' : 'snapshot',\n tagName: 'factory-phase',\n contents: isDelta ? `Factory phase update:\\n${snapshotContents}` : snapshotContents,\n value: { phase: value },\n ...(isDelta ? { delta: { phase: value } } : {}),\n attributes: {\n status: 'active',\n board,\n stage,\n role: binding.role,\n revision: item.revision,\n ...(runtime ?? {}),\n },\n metadata: { value: { phase: value } },\n };\n }\n\n async reconcileAllBoundThreads(): Promise<void> {\n if (!this.options.messageReader) return;\n const bindings = await this.options.storage.listActiveRunBindings();\n for (const binding of bindings) await this.reconcileBinding(binding);\n }\n\n async reconcileBinding(binding: FactoryRunBindingRecord): Promise<void> {\n const reader = this.options.messageReader;\n if (!reader || binding.status !== 'active') return;\n // One keyed read up front: a binding whose item is gone or no longer in a\n // single rule stage would ingest nothing, so skip the cursor and message\n // reads entirely instead of paying them on every walk.\n const item = await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n const cursor = await this.options.storage.getToolResultCursor(binding.orgId, binding.factoryProjectId, binding.id);\n let page = 0;\n while (true) {\n const result = await reader.listMessages({\n threadId: binding.threadId,\n resourceId: binding.resourceId,\n page,\n perPage: TRANSCRIPT_PAGE_SIZE,\n ...(cursor ? { filter: { dateRange: { start: cursor.lastMessageCreatedAt } } } : {}),\n orderBy: { field: 'createdAt', direction: 'ASC' },\n });\n await this.ingestMessages(binding, result.messages, undefined, item);\n const last = result.messages.at(-1);\n if (last) {\n await this.options.storage.advanceToolResultCursor({\n bindingId: binding.id,\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n lastMessageId: last.id,\n lastMessageCreatedAt: last.createdAt instanceof Date ? last.createdAt : new Date(last.createdAt),\n updatedAt: new Date(),\n });\n }\n if (!result.hasMore) break;\n page += 1;\n }\n }\n\n private async ingestMessages(\n binding: FactoryRunBindingRecord,\n messages: MastraDBMessage[],\n toolCallIds?: ReadonlySet<string>,\n preloadedItem?: Card,\n ): Promise<void> {\n const item = preloadedItem ?? (await this.options.storage.get({ orgId: binding.orgId, id: binding.workItemId }));\n if (!itemInRuleStage(await this.boards.load(binding), item)) return;\n for (const message of messages) {\n for (const toolResult of completedToolResults(message)) {\n if (toolCallIds && !toolCallIds.has(toolResult.toolCallId)) continue;\n try {\n await this.options.recordPullRequestProvenance?.({\n binding,\n item,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n toolName: toolResult.toolName,\n toolInput: toolResult.input,\n toolResult: toolResult.value,\n status: toolResult.status,\n });\n } catch {\n // Provenance is supporting evidence and must not block authoritative rule ingress.\n }\n await this.ingestToolResult(binding, item, toolResult);\n }\n }\n }\n\n private async ingestToolResult(\n binding: FactoryRunBindingRecord,\n loaded: Card,\n toolResult: CompletedToolResult,\n ): Promise<void> {\n let item = loaded;\n const board = boardForWorkItem(item);\n const boards = await this.boards.load(binding);\n const finished = finishedPhase(boards, board, item, binding.role, toolResult);\n // The exit tool finished the phase: the card may now leave it (the agent moves it). A result\n // read again later (the step, then the thread) stamps once: the stamp names its tool call.\n const at = new Date().toISOString();\n const stampedCall = (item.metadata?.[PHASE_EXIT_METADATA_KEY] as { toolCallId?: unknown } | undefined)?.toolCallId;\n if (\n finished !== undefined &&\n stampedCall !== toolResult.toolCallId &&\n !exitToolSucceeded(item, finished, toolResult.toolName)\n ) {\n const entry = openEntry(item, finished);\n for (let attempt = 1; ; attempt++) {\n try {\n const stamped = await this.options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n [PHASE_EXIT_METADATA_KEY]: {\n phase: finished,\n tool: toolResult.toolName,\n toolCallId: toolResult.toolCallId,\n at,\n },\n ...(toolResult.toolName === 'submit_plan' ? { planApprovedAt: at } : {}),\n },\n },\n expectedRevision: item.revision,\n });\n if (stamped) item = stamped.item;\n break;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n // Another write landed first. While the card is still in the same visit to the phase,\n // the result still finishes it; once the card moved on, it no longer needs finishing.\n const current = await this.options.storage.get({ orgId: binding.orgId, id: item.id });\n if (!current || attempt >= STAMP_ATTEMPTS || openEntry(current, finished) !== entry || entry === undefined) {\n return;\n }\n item = current;\n }\n }\n }\n const rule = resolveBoardToolRule(boards, board, toolResult.toolName);\n if (!rule) return;\n const ingressId = JSON.stringify([\n binding.id,\n binding.threadId,\n toolResult.assistantMessageId,\n toolResult.toolCallId,\n ]);\n const prior = await this.options.storage.getTransitionResultByIngress(\n binding.orgId,\n binding.factoryProjectId,\n ingressId,\n );\n if (prior) return;\n const context: FactoryToolResultRuleContext = {\n tenant: { orgId: binding.orgId, projectId: binding.factoryProjectId },\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'toolResult', id: ingressId },\n cause: `Completed ${toolResult.toolName}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n item: {\n id: item.id,\n source: workItemSource(item.externalSource),\n sourceKey: workItemSourceKey(item),\n parentWorkItemId: item.parentWorkItemId,\n title: item.title,\n url: item.externalSource?.url ?? null,\n stages: item.stages,\n workItem: item.workItem,\n acceptedAt: item.acceptedAt,\n metadata: item.metadata,\n },\n board,\n itemRevision: item.revision,\n toolName: toolResult.toolName,\n threadId: binding.threadId,\n assistantMessageId: toolResult.assistantMessageId,\n toolCallId: toolResult.toolCallId,\n result: { status: toolResult.status, value: toolResult.value },\n };\n\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: FactoryCommitDecision[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = await withRuleTimeout(Promise.resolve(rule(Object.freeze(context))));\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n const validated = validateFactoryRuleDecisions([decision]);\n for (const entry of validated) assertFactoryDecisionTarget(entry, boards, board);\n decisions = validated;\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory tool-result rule failed.',\n };\n }\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n ingress: { identity: ingressId, triggerType: 'tool.result' },\n configVersion: this.options.configVersion,\n expectedRevision: item.revision,\n actor: { ...context.actor },\n outcome,\n decisions: decisions.map(entry => ({ ...entry })),\n causalChain: [],\n now: new Date(),\n // The bound agent's own tool call carries the same consent as its governed moves.\n consentedBy: `agent:${binding.id}`,\n });\n if (committed.status !== 'committed' || !this.options.transitionService) return;\n for (const entry of decisions) {\n if (entry.type !== 'transition') continue;\n await this.options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: item.id,\n board: entry.board,\n stage: entry.stage,\n ...(entry.reenter ? { reenter: true } : {}),\n expectedRevision: item.revision,\n actor: { type: 'system', id: 'factory-tool-result-rule' },\n ingress: { type: 'rule', identity: `decision:${entry.idempotencyKey}` },\n cause: 'tool_result_rule',\n causalChain: [{ ingressId, decisionType: entry.type }],\n ...(isApprovedPlanResult(toolResult) ? { planApproved: true } : {}),\n ...(toolResult.status === 'success' ? { completedTool: toolResult.toolName } : {}),\n });\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AA2CA,MAAM,WAAW;AACjB,MAAM,kBAAkB;AACxB,MAAM,uBAAuB;AAC7B,MAAM,mBAAmB;AACzB,SAAS,UAAU,QAAuB,MAAmD;CAC3F,OAAO,QAAQ,uBAAuB,QAAQ,IAAI,IAAI,KAAK,OAAO,KAAK,KAAA;AACzE;AAEA,SAAS,gBAAgB,QAAuB,MAA6C;CAC3F,OAAO,UAAU,QAAQ,IAAI,MAAM,KAAA;AACrC;AAuBA,SAAS,qBAAqB,QAAsC;CAClE,IAAI,OAAO,aAAa,iBAAiB,OAAO,WAAW,WAAW,OAAO;CAC7E,IAAI,OAAO,OAAO,UAAU,UAAU,OAAO,OAAO,MAAM,WAAW,gBAAgB;CACrF,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO,UAAU,YAAY,MAAM,QAAQ,O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SAAS,WAAW;GAC7B,IAAI,MAAM,SAAS,cAAc;GACjC,MAAM,KAAK,QAAQ,kBAAkB,WAAW;IAC9C,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,KAAK;IACjB,OAAO,MAAM;IACb,OAAO,MAAM;IACb,GAAI,MAAM,UAAU,EAAE,SAAS,KAAK,IAAI,CAAC;IACzC,kBAAkB,KAAK;IACvB,OAAO;KAAE,MAAM;KAAU,IAAI;IAA2B;IACxD,SAAS;KAAE,MAAM;KAAQ,UAAU,YAAY,MAAM;IAAiB;IACtE,OAAO;IACP,aAAa,CAAC;KAAE;KAAW,cAAc,MAAM;IAAK,CAAC;IACrD,GAAI,qBAAqB,UAAU,IAAI,EAAE,cAAc,KAAK,IAAI,CAAC;IACjE,GAAI,WAAW,WAAW,YAAY,EAAE,eAAe,WAAW,SAAS,IAAI,CAAC;GAClF,CAAC;EACH;CACF;AACF"}
@@ -1,4 +1,6 @@
1
1
  import type { RequestContext } from '@mastra/core/request-context';
2
+ import type { BoardRegistry } from '../boards/index.js';
3
+ import type { ProjectBoardSource } from '../boards/project-boards.js';
2
4
  import type { IntegrationTools } from '../integrations/base.js';
3
5
  import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
4
6
  import type { FactorySessionSourceLookup } from './binding-context.js';
@@ -79,7 +81,7 @@ export declare function resolveReviewSourceUiOrigin(raw: string | undefined): st
79
81
  *
80
82
  * The tool is intentionally omitted (returns `{}`) whenever it cannot produce
81
83
  * a complete, correct provenance shape: no resolvable session address, no
82
- * active binding, a non-review-role binding, no bound work item, or no
84
+ * active binding, a card whose phase does not grant the tool to this session, no bound work item, or no
83
85
  * configured browser-facing UI origin. Skills treat tool-absent identically to
84
86
  * tool-failed: stop-don't-publish.
85
87
  */
@@ -101,5 +103,6 @@ export declare function createReviewSourceTool(options: {
101
103
  * skill's tool-not-available branch stops publication.
102
104
  */
103
105
  uiOrigin: string | null;
106
+ boards?: BoardRegistry | ProjectBoardSource;
104
107
  }): Promise<IntegrationTools>;
105
108
  //# sourceMappingURL=review-source-tool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"review-source-tool.d.ts","sourceRoot":"","sources":["../../src/rules/review-source-tool.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAInE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,KAAK,EAAQ,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,sBAAsB,CAAC;AAGvE,MAAM,WAAW,kBAAkB;IACjC;;;;;;OAMG;IACH,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;;;;OAQG;IACH,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B;;;;OAIG;IACH,YAAY,EAAE;QACZ,aAAa,EAAE,MAAM,CAAC;QACtB,IAAI,EAAE,MAAM,CAAC;QACb,UAAU,EAAE,MAAM,CAAC;QACnB,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;KACpB,GAAG,IAAI,CAAC;IACT;;;;;;;;;OASG;IACH,eAAe,EACX;QAAE,QAAQ,EAAE,QAAQ,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,GAC5C;QAAE,QAAQ,EAAE,QAAQ,CAAC;QAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,GAC9D,IAAI,CAAC;CACV;AAED;;;;;;;;;GASG;AACH,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAElF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACpD,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,8BAA8B,GAAG,sBA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AC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAElF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,sBAAsB,CAAC,OAAO,EAAE;IACpD,cAAc,EAAE,cAAc,CAAC;IAC/B,OAAO,EAAE,IAAI,CAAC,gBAAgB,EAAE,8BAA8B,GAAG,sBAAsB,GAAG,KAAK,CAAC,CAAC;IACjG,QAAQ,CAAC,EAAE,0BAA0B,CAAC;IACtC;;;;;;;;;;;;OAYG;IACH,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,CAAC,EAAE,aAAa,GAAG,kBAAkB,CAAC;CAC7C,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAwC5B"}
@@ -1,6 +1,9 @@
1
+ import { reviewedPullRequest, sourceExternalId } from "../boards/semantics.js";
2
+ import "../boards/index.js";
1
3
  import { resolveFactorySessionAddress } from "./binding-context.js";
2
- import { z } from "zod";
4
+ import { phaseGrantsTool } from "./phase-tools.js";
3
5
  import { createTool } from "@mastra/core/tools";
6
+ import { z } from "zod";
4
7
  // src/rules/review-source-tool.ts
5
8
  /**
6
9
  * Normalize the operator-provided browser-facing UI origin (the
@@ -32,7 +35,7 @@ function resolveReviewSourceUiOrigin(raw) {
32
35
  *
33
36
  * The tool is intentionally omitted (returns `{}`) whenever it cannot produce
34
37
  * a complete, correct provenance shape: no resolvable session address, no
35
- * active binding, a non-review-role binding, no bound work item, or no
38
+ * active binding, a card whose phase does not grant the tool to this session, no bound work item, or no
36
39
  * configured browser-facing UI origin. Skills treat tool-absent identically to
37
40
  * tool-failed: stop-don't-publish.
38
41
  */
@@ -45,12 +48,13 @@ async function createReviewSourceTool(options) {
45
48
  });
46
49
  if (!resolution) return {};
47
50
  const binding = resolution.binding ?? await options.storage.findActiveRunBinding(resolution.address);
48
- if (!binding || binding.role !== "review") return {};
51
+ if (!binding) return {};
49
52
  const item = await options.storage.get({
50
53
  orgId: binding.orgId,
51
54
  id: binding.workItemId
52
55
  });
53
56
  if (!item) return {};
57
+ if (!await phaseGrantsTool(options.boards, binding, item, "factory_review_source")) return {};
54
58
  const output = {
55
59
  sessionUrl: buildSessionUrl({
56
60
  uiOrigin: options.uiOrigin,
@@ -72,7 +76,22 @@ async function createReviewSourceTool(options) {
72
76
  function buildSessionUrl(input) {
73
77
  return `${input.uiOrigin.replace(/\/+$/, "")}/factories/${encodeURIComponent(input.factoryProjectId)}/workspaces/${encodeURIComponent(input.sessionId)}/threads/${encodeURIComponent(input.threadId)}`;
74
78
  }
79
+ /**
80
+ * The pull request a review pass on an issue card looks at, when one is attached. The tool only
81
+ * exists in a phase that grants it, so the card is in its board's pull request review.
82
+ */
83
+ function attachedReviewedPullRequest(item) {
84
+ if (item.externalSource?.type === "pull-request") return null;
85
+ return reviewedPullRequest(item);
86
+ }
75
87
  function readReviewTarget(item) {
88
+ const attached = attachedReviewedPullRequest(item);
89
+ if (attached) return {
90
+ integrationId: attached.integrationId,
91
+ type: attached.sourceType,
92
+ externalId: sourceExternalId(attached),
93
+ url: attached.url || null
94
+ };
76
95
  const source = item.externalSource;
77
96
  if (!source) return null;
78
97
  return {
@@ -97,7 +116,8 @@ function readBoundRepository(item) {
97
116
  return null;
98
117
  }
99
118
  function readPullRequestAuthor(item) {
100
- const author = item.workItem.author;
119
+ const attached = attachedReviewedPullRequest(item);
120
+ const author = attached ? attached.author : item.workItem.author;
101
121
  if (typeof author === "string" && author.trim()) return author.trim();
102
122
  return null;
103
123
  }
@@ -1 +1 @@
1
- {"version":3,"file":"review-source-tool.js","names":[],"sources":["../../src/rules/review-source-tool.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactorySessionSourceLookup } from './binding-context.js';\nimport { resolveFactorySessionAddress } from './binding-context.js';\n\nexport interface ReviewSourceOutput {\n /**\n * Browser-facing deep-link back to the Factory session that produced this\n * review — the only field a review body publishes. Everything else on this\n * shape is an input to in-run cross-checks and the session handoff, never a\n * published field, so the GitHub/GitLab audience never sees the upstream\n * Linear/Jira slug through the review comment.\n */\n sessionUrl: string;\n /**\n * PR/MR author recorded on the review card at intake — for GitHub this is\n * `pullRequest.user.login`, for GitLab it is the GitLab username. The skill\n * cross-checks it against the same REST field of the reviewed PR\n * (`gh api repos/<owner>/<repo>/pulls/<number> --jq .user.login`; `gh pr view`\n * formats App authors as `app/<slug>` instead of `<slug>[bot]`) or the\n * equivalent MR fetch; a mismatch means the session is bound to a different\n * PR/MR than the one being reviewed.\n */\n triggeredBy: string | null;\n /**\n * The externalSource recorded on the review card itself — the PR/MR the\n * session was intake-bound to. The skill cross-checks the reviewed PR/MR\n * against this shape so a review can never quietly land on the wrong target.\n */\n reviewTarget: {\n integrationId: string;\n type: string;\n externalId: string;\n url: string | null;\n } | null;\n /**\n * Repository identity stamped on the review card at intake — the\n * binding-side value for the null-`url` cross-check fallback. The skill must\n * compare this against an identity resolved independently of the card (e.g.\n * `gh api repos/<owner>/<repo> --jq .id` — the numeric REST id — for the\n * session checkout's repository);\n * comparing two values derived from the same checkout proves nothing.\n * `null` when intake recorded no repository identity — in that case there\n * is no verifiable bound repository and the fallback must not publish.\n */\n boundRepository:\n | { provider: 'github'; repositoryId: number }\n | { provider: 'gitlab'; host: string | null; projectId: number }\n | null;\n}\n\n/**\n * Normalize the operator-provided browser-facing UI origin (the\n * `MASTRACODE_PUBLIC_URL` env var) into the `uiOrigin` the tool accepts.\n *\n * Blank counts as unset: `mastracode/web/.env.schema` ships\n * `MASTRACODE_PUBLIC_URL=` as the operator-facing line, so an empty or\n * whitespace-only value is the expected \"not configured\" state — it must map\n * to `null` (tool omitted) rather than register the tool and publish a\n * hostless `sessionUrl` into a public review body.\n */\nexport function resolveReviewSourceUiOrigin(raw: string | undefined): string | null {\n return raw?.trim().replace(/\\/+$/, '') || null;\n}\n\n/**\n * `factory_review_source` — read the routing facts behind the current review\n * session (session deep-link, PR/MR author, the review target) so the review\n * agent can attribute its verdict to a concrete originating run and detect a\n * mis-targeted review before it publishes.\n *\n * The tool exists to make cross-PR misattribution detectable both in-run and\n * after the fact: a review lands on GitHub/GitLab with the Factory session URL\n * that produced it, and the human who investigates a suspicious review can\n * jump straight to the run.\n *\n * All fields are derived server-side from the bound work item — nothing enters\n * from the agent's tool arguments — so the session URL always points at the\n * caller's own session, never one it was asked to name.\n *\n * The tool is intentionally omitted (returns `{}`) whenever it cannot produce\n * a complete, correct provenance shape: no resolvable session address, no\n * active binding, a non-review-role binding, no bound work item, or no\n * configured browser-facing UI origin. Skills treat tool-absent identically to\n * tool-failed: stop-don't-publish.\n */\nexport async function createReviewSourceTool(options: {\n requestContext: RequestContext;\n storage: Pick<WorkItemsStorage, 'findActiveRunBindingByThread' | 'findActiveRunBinding' | 'get'>;\n sessions?: FactorySessionSourceLookup;\n /**\n * Browser-facing UI origin, no trailing slash. In a separate-SPA deployment\n * (API host distinct from UI host) this is the UI host — the origin the\n * emitted session link opens in. `MastraFactoryConfig.publicUrl` is the API\n * origin and must not be used here; the caller resolves the UI origin (see\n * `factory.ts`) via the `MASTRACODE_PUBLIC_URL` env var.\n *\n * `null` means no browser-facing origin is configured. Match the Slack\n * session-link surface (`integrations/slack/slack.ts:168-171`, `:809-812`),\n * which omits the deep-link entirely rather than publishing an API/localhost\n * URL into a public body: the tool is dropped from the toolset, and the\n * skill's tool-not-available branch stops publication.\n */\n uiOrigin: string | null;\n}): Promise<IntegrationTools> {\n if (options.uiOrigin === null) return {};\n const resolution = await resolveFactorySessionAddress({\n requestContext: options.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n if (!resolution) return {};\n const binding = resolution.binding ?? (await options.storage.findActiveRunBinding(resolution.address));\n // The tool exists only for review-role sessions. Work/plan/triage runs never\n // publish reviews on GitHub, so exposing them the tool would just clutter\n // their prompt.\n if (!binding || binding.role !== 'review') return {};\n\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) return {};\n\n const sessionUrl = buildSessionUrl({\n uiOrigin: options.uiOrigin,\n factoryProjectId: binding.factoryProjectId,\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n });\n const triggeredBy = readPullRequestAuthor(item);\n const reviewTarget = readReviewTarget(item);\n const boundRepository = readBoundRepository(item);\n // Every field is pre-resolved server-side and returned as a plain object.\n // The tool takes no arguments and does no further I/O, so a review-role\n // session either sees a complete provenance shape or the tool is absent —\n // the skill treats those branches identically (stop-don't-publish).\n const output: ReviewSourceOutput = { sessionUrl, triggeredBy, reviewTarget, boundRepository };\n\n return {\n factory_review_source: createTool({\n id: 'factory_review_source',\n description:\n 'Read the routing facts behind this review session: a deep-link back to the Factory session that produced the review, the PR/MR author recorded on the review card, and the review target (the PR/MR the session was intake-bound to). Publish the session URL in the required `Factory Session` block of every review body so a misattributed review can always be traced back to the run that produced it. Cross-check `triggeredBy` and `reviewTarget` against the PR/MR you fetched in Phase 1, using `boundRepository` as the intake-stamped repository identity when `reviewTarget.url` is null; do not publish the `triggeredBy`, `reviewTarget`, or `boundRepository` fields.',\n inputSchema: z.object({}),\n execute: async (): Promise<ReviewSourceOutput> => output,\n }),\n };\n}\n\nfunction buildSessionUrl(input: {\n uiOrigin: string;\n factoryProjectId: string;\n sessionId: string;\n threadId: string;\n}): string {\n const origin = input.uiOrigin.replace(/\\/+$/, '');\n return `${origin}/factories/${encodeURIComponent(input.factoryProjectId)}/workspaces/${encodeURIComponent(input.sessionId)}/threads/${encodeURIComponent(input.threadId)}`;\n}\n\nfunction readReviewTarget(item: Card): ReviewSourceOutput['reviewTarget'] {\n const source = item.externalSource;\n if (!source) return null;\n return {\n integrationId: source.integrationId,\n type: source.type,\n externalId: source.externalId,\n url: typeof source.url === 'string' && source.url ? source.url : null,\n };\n}\n\nfunction readBoundRepository(item: Card): ReviewSourceOutput['boundRepository'] {\n const metadata = item.workItem.metadata;\n if (!metadata) return null;\n // Intake stamps repository identity on every PR/MR card:\n // `github/default-rules.ts` writes `githubRepositoryId`, and\n // `gitlab/default-rules.ts` writes `gitlabHost` + `gitlabProjectId`.\n if (typeof metadata.githubRepositoryId === 'number') {\n return { provider: 'github', repositoryId: metadata.githubRepositoryId };\n }\n if (typeof metadata.gitlabProjectId === 'number') {\n return {\n provider: 'gitlab',\n host: typeof metadata.gitlabHost === 'string' && metadata.gitlabHost ? metadata.gitlabHost : null,\n projectId: metadata.gitlabProjectId,\n };\n }\n return null;\n}\n\nfunction readPullRequestAuthor(item: Card): string | null {\n const author = item.workItem.author;\n if (typeof author === 'string' && author.trim()) return author.trim();\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;AAiEA,SAAgB,4BAA4B,KAAwC;CAClF,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE,KAAK;AAC5C;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,uBAAuB,SAkBf;CAC5B,IAAI,QAAQ,aAAa,MAAM,OAAO,CAAC;CACvC,MAAM,aAAa,MAAM,6BAA6B;EACpD,gBAAgB,QAAQ;EACxB,SAAS,QAAQ;EACjB,UAAU,QAAQ;CACpB,CAAC;CACD,IAAI,CAAC,YAAY,OAAO,CAAC;CACzB,MAAM,UAAU,WAAW,WAAY,MAAM,QAAQ,QAAQ,qBAAqB,WAAW,OAAO;CAIpG,IAAI,CAAC,WAAW,QAAQ,SAAS,UAAU,OAAO,CAAC;CAEnD,MAAM,OAAO,MAAM,QAAQ,QAAQ,IAAI;EAAE,OAAO,QAAQ;EAAO,IAAI,QAAQ;CAAW,CAAC;CACvF,IAAI,CAAC,MAAM,OAAO,CAAC;CAenB,MAAM,SAA6B;EAAE,YAblB,gBAAgB;GACjC,UAAU,QAAQ;GAClB,kBAAkB,QAAQ;GAC1B,WAAW,QAAQ;GACnB,UAAU,QAAQ;EACpB,CAQ8C;EAAG,aAP7B,sBAAsB,IAOiB;EAAG,cANzC,iBAAiB,IAMmC;EAAG,iBALpD,oBAAoB,IAK8C;CAAE;CAE5F,OAAO,EACL,uBAAuB,WAAW;EAChC,IAAI;EACJ,aACE;EACF,aAAa,EAAE,OAAO,CAAC,CAAC;EACxB,SAAS,YAAyC;CACpD,CAAC,EACH;AACF;AAEA,SAAS,gBAAgB,OAKd;CAET,OAAO,GADQ,MAAM,SAAS,QAAQ,QAAQ,EAC/B,EAAE,aAAa,mBAAmB,MAAM,gBAAgB,EAAE,cAAc,mBAAmB,MAAM,SAAS,EAAE,WAAW,mBAAmB,MAAM,QAAQ;AACzK;AAEA,SAAS,iBAAiB,MAAgD;CACxE,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO;EACL,eAAe,OAAO;EACtB,MAAM,OAAO;EACb,YAAY,OAAO;EACnB,KAAK,OAAO,OAAO,QAAQ,YAAY,OAAO,MAAM,OAAO,MAAM;CACnE;AACF;AAEA,SAAS,oBAAoB,MAAmD;CAC9E,MAAM,WAAW,KAAK,SAAS;CAC/B,IAAI,CAAC,UAAU,OAAO;CAItB,IAAI,OAAO,SAAS,uBAAuB,UACzC,OAAO;EAAE,UAAU;EAAU,cAAc,SAAS;CAAmB;CAEzE,IAAI,OAAO,SAAS,oBAAoB,UACtC,OAAO;EACL,UAAU;EACV,MAAM,OAAO,SAAS,eAAe,YAAY,SAAS,aAAa,SAAS,aAAa;EAC7F,WAAW,SAAS;CACtB;CAEF,OAAO;AACT;AAEA,SAAS,sBAAsB,MAA2B;CACxD,MAAM,SAAS,KAAK,SAAS;CAC7B,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK;CACpE,OAAO;AACT"}
1
+ {"version":3,"file":"review-source-tool.js","names":[],"sources":["../../src/rules/review-source-tool.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { reviewedPullRequest, sourceExternalId } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactorySessionSourceLookup } from './binding-context.js';\nimport { resolveFactorySessionAddress } from './binding-context.js';\nimport { phaseGrantsTool } from './phase-tools.js';\n\nexport interface ReviewSourceOutput {\n /**\n * Browser-facing deep-link back to the Factory session that produced this\n * review — the only field a review body publishes. Everything else on this\n * shape is an input to in-run cross-checks and the session handoff, never a\n * published field, so the GitHub/GitLab audience never sees the upstream\n * Linear/Jira slug through the review comment.\n */\n sessionUrl: string;\n /**\n * PR/MR author recorded on the review card at intake — for GitHub this is\n * `pullRequest.user.login`, for GitLab it is the GitLab username. The skill\n * cross-checks it against the same REST field of the reviewed PR\n * (`gh api repos/<owner>/<repo>/pulls/<number> --jq .user.login`; `gh pr view`\n * formats App authors as `app/<slug>` instead of `<slug>[bot]`) or the\n * equivalent MR fetch; a mismatch means the session is bound to a different\n * PR/MR than the one being reviewed.\n */\n triggeredBy: string | null;\n /**\n * The externalSource recorded on the review card itself — the PR/MR the\n * session was intake-bound to. The skill cross-checks the reviewed PR/MR\n * against this shape so a review can never quietly land on the wrong target.\n */\n reviewTarget: {\n integrationId: string;\n type: string;\n externalId: string;\n url: string | null;\n } | null;\n /**\n * Repository identity stamped on the review card at intake — the\n * binding-side value for the null-`url` cross-check fallback. The skill must\n * compare this against an identity resolved independently of the card (e.g.\n * `gh api repos/<owner>/<repo> --jq .id` — the numeric REST id — for the\n * session checkout's repository);\n * comparing two values derived from the same checkout proves nothing.\n * `null` when intake recorded no repository identity — in that case there\n * is no verifiable bound repository and the fallback must not publish.\n */\n boundRepository:\n | { provider: 'github'; repositoryId: number }\n | { provider: 'gitlab'; host: string | null; projectId: number }\n | null;\n}\n\n/**\n * Normalize the operator-provided browser-facing UI origin (the\n * `MASTRACODE_PUBLIC_URL` env var) into the `uiOrigin` the tool accepts.\n *\n * Blank counts as unset: `mastracode/web/.env.schema` ships\n * `MASTRACODE_PUBLIC_URL=` as the operator-facing line, so an empty or\n * whitespace-only value is the expected \"not configured\" state — it must map\n * to `null` (tool omitted) rather than register the tool and publish a\n * hostless `sessionUrl` into a public review body.\n */\nexport function resolveReviewSourceUiOrigin(raw: string | undefined): string | null {\n return raw?.trim().replace(/\\/+$/, '') || null;\n}\n\n/**\n * `factory_review_source` — read the routing facts behind the current review\n * session (session deep-link, PR/MR author, the review target) so the review\n * agent can attribute its verdict to a concrete originating run and detect a\n * mis-targeted review before it publishes.\n *\n * The tool exists to make cross-PR misattribution detectable both in-run and\n * after the fact: a review lands on GitHub/GitLab with the Factory session URL\n * that produced it, and the human who investigates a suspicious review can\n * jump straight to the run.\n *\n * All fields are derived server-side from the bound work item — nothing enters\n * from the agent's tool arguments — so the session URL always points at the\n * caller's own session, never one it was asked to name.\n *\n * The tool is intentionally omitted (returns `{}`) whenever it cannot produce\n * a complete, correct provenance shape: no resolvable session address, no\n * active binding, a card whose phase does not grant the tool to this session, no bound work item, or no\n * configured browser-facing UI origin. Skills treat tool-absent identically to\n * tool-failed: stop-don't-publish.\n */\nexport async function createReviewSourceTool(options: {\n requestContext: RequestContext;\n storage: Pick<WorkItemsStorage, 'findActiveRunBindingByThread' | 'findActiveRunBinding' | 'get'>;\n sessions?: FactorySessionSourceLookup;\n /**\n * Browser-facing UI origin, no trailing slash. In a separate-SPA deployment\n * (API host distinct from UI host) this is the UI host — the origin the\n * emitted session link opens in. `MastraFactoryConfig.publicUrl` is the API\n * origin and must not be used here; the caller resolves the UI origin (see\n * `factory.ts`) via the `MASTRACODE_PUBLIC_URL` env var.\n *\n * `null` means no browser-facing origin is configured. Match the Slack\n * session-link surface (`integrations/slack/slack.ts:168-171`, `:809-812`),\n * which omits the deep-link entirely rather than publishing an API/localhost\n * URL into a public body: the tool is dropped from the toolset, and the\n * skill's tool-not-available branch stops publication.\n */\n uiOrigin: string | null;\n boards?: BoardRegistry | ProjectBoardSource;\n}): Promise<IntegrationTools> {\n if (options.uiOrigin === null) return {};\n const resolution = await resolveFactorySessionAddress({\n requestContext: options.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n if (!resolution) return {};\n const binding = resolution.binding ?? (await options.storage.findActiveRunBinding(resolution.address));\n if (!binding) return {};\n\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) return {};\n // Only the session reviewing the card in a phase that grants the tool publishes reviews.\n if (!(await phaseGrantsTool(options.boards, binding, item, 'factory_review_source'))) return {};\n\n const sessionUrl = buildSessionUrl({\n uiOrigin: options.uiOrigin,\n factoryProjectId: binding.factoryProjectId,\n sessionId: binding.sessionId,\n threadId: binding.threadId,\n });\n const triggeredBy = readPullRequestAuthor(item);\n const reviewTarget = readReviewTarget(item);\n const boundRepository = readBoundRepository(item);\n // Every field is pre-resolved server-side and returned as a plain object.\n // The tool takes no arguments and does no further I/O, so a review-role\n // session either sees a complete provenance shape or the tool is absent —\n // the skill treats those branches identically (stop-don't-publish).\n const output: ReviewSourceOutput = { sessionUrl, triggeredBy, reviewTarget, boundRepository };\n\n return {\n factory_review_source: createTool({\n id: 'factory_review_source',\n description:\n 'Read the routing facts behind this review session: a deep-link back to the Factory session that produced the review, the PR/MR author recorded on the review card, and the review target (the PR/MR the session was intake-bound to). Publish the session URL in the required `Factory Session` block of every review body so a misattributed review can always be traced back to the run that produced it. Cross-check `triggeredBy` and `reviewTarget` against the PR/MR you fetched in Phase 1, using `boundRepository` as the intake-stamped repository identity when `reviewTarget.url` is null; do not publish the `triggeredBy`, `reviewTarget`, or `boundRepository` fields.',\n inputSchema: z.object({}),\n execute: async (): Promise<ReviewSourceOutput> => output,\n }),\n };\n}\n\nfunction buildSessionUrl(input: {\n uiOrigin: string;\n factoryProjectId: string;\n sessionId: string;\n threadId: string;\n}): string {\n const origin = input.uiOrigin.replace(/\\/+$/, '');\n return `${origin}/factories/${encodeURIComponent(input.factoryProjectId)}/workspaces/${encodeURIComponent(input.sessionId)}/threads/${encodeURIComponent(input.threadId)}`;\n}\n\n/**\n * The pull request a review pass on an issue card looks at, when one is attached. The tool only\n * exists in a phase that grants it, so the card is in its board's pull request review.\n */\nfunction attachedReviewedPullRequest(item: Card) {\n if (item.externalSource?.type === 'pull-request') return null;\n return reviewedPullRequest(item);\n}\n\nfunction readReviewTarget(item: Card): ReviewSourceOutput['reviewTarget'] {\n const attached = attachedReviewedPullRequest(item);\n if (attached) {\n return {\n integrationId: attached.integrationId,\n type: attached.sourceType,\n externalId: sourceExternalId(attached),\n url: attached.url || null,\n };\n }\n const source = item.externalSource;\n if (!source) return null;\n return {\n integrationId: source.integrationId,\n type: source.type,\n externalId: source.externalId,\n url: typeof source.url === 'string' && source.url ? source.url : null,\n };\n}\n\nfunction readBoundRepository(item: Card): ReviewSourceOutput['boundRepository'] {\n const metadata = item.workItem.metadata;\n if (!metadata) return null;\n // Intake stamps repository identity on every PR/MR card:\n // `github/default-rules.ts` writes `githubRepositoryId`, and\n // `gitlab/default-rules.ts` writes `gitlabHost` + `gitlabProjectId`.\n if (typeof metadata.githubRepositoryId === 'number') {\n return { provider: 'github', repositoryId: metadata.githubRepositoryId };\n }\n if (typeof metadata.gitlabProjectId === 'number') {\n return {\n provider: 'gitlab',\n host: typeof metadata.gitlabHost === 'string' && metadata.gitlabHost ? metadata.gitlabHost : null,\n projectId: metadata.gitlabProjectId,\n };\n }\n return null;\n}\n\nfunction readPullRequestAuthor(item: Card): string | null {\n // An attached pull request's author is its own; the card's issue author never stands in for it.\n const attached = attachedReviewedPullRequest(item);\n const author = attached ? attached.author : item.workItem.author;\n if (typeof author === 'string' && author.trim()) return author.trim();\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAqEA,SAAgB,4BAA4B,KAAwC;CAClF,OAAO,KAAK,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE,KAAK;AAC5C;;;;;;;;;;;;;;;;;;;;;;AAuBA,eAAsB,uBAAuB,SA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jD,IAAI,UACF,OAAO;EACL,eAAe,SAAS;EACxB,MAAM,SAAS;EACf,YAAY,iBAAiB,QAAQ;EACrC,KAAK,SAAS,OAAO;CACvB;CAEF,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO;EACL,eAAe,OAAO;EACtB,MAAM,OAAO;EACb,YAAY,OAAO;EACnB,KAAK,OAAO,OAAO,QAAQ,YAAY,OAAO,MAAM,OAAO,MAAM;CACnE;AACF;AAEA,SAAS,oBAAoB,MAAmD;CAC9E,MAAM,WAAW,KAAK,SAAS;CAC/B,IAAI,CAAC,UAAU,OAAO;CAItB,IAAI,OAAO,SAAS,uBAAuB,UACzC,OAAO;EAAE,UAAU;EAAU,cAAc,SAAS;CAAmB;CAEzE,IAAI,OAAO,SAAS,oBAAoB,UACtC,OAAO;EACL,UAAU;EACV,MAAM,OAAO,SAAS,eAAe,YAAY,SAAS,aAAa,SAAS,aAAa;EAC7F,WAAW,SAAS;CACtB;CAEF,OAAO;AACT;AAEA,SAAS,sBAAsB,MAA2B;CAExD,MAAM,WAAW,4BAA4B,IAAI;CACjD,MAAM,SAAS,WAAW,SAAS,SAAS,KAAK,SAAS;CAC1D,IAAI,OAAO,WAAW,YAAY,OAAO,KAAK,GAAG,OAAO,OAAO,KAAK;CACpE,OAAO;AACT"}
@@ -9,7 +9,7 @@ export declare const RULE_OPERATORS: readonly ['equals', 'not_equals', 'contains
9
9
  export type RuleOperator = (typeof RULE_OPERATORS)[number];
10
10
  export declare const MAX_RULE_GROUP_DEPTH = 3;
11
11
  /** Facts a phase condition can test about a card (see `cardRuleFacts`). */
12
- export declare const CARD_RULE_FIELDS: readonly ['item.labels', 'item.title', 'item.author', 'author.trusted', 'source.kind', 'source.integration'];
12
+ export declare const CARD_RULE_FIELDS: readonly ['item.labels', 'item.title', 'item.author', 'author.trusted', 'source.kind', 'source.integration', 'item.pullRequest'];
13
13
  export type RuleValue = string | number | boolean | Array<string | number | boolean>;
14
14
  export interface RuleCondition {
15
15
  field: string;
@@ -1 +1 @@
1
- {"version":3,"file":"rule-group.d.ts","sourceRoot":"","sources":["../../src/rules/rule-group.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB;;;;;GAKG;AACH,eAAO,MAAM,cAAc,YACzB,QAAQ,EACR,YAAY,EACZ,UAAU,EACV,cAAc,EACd,IAAI,EACJ,QAAQ,EACR,QAAQ,EACR,YAAY,EACZ,cAAc,EACd,WAAW,EACX,uBAAuB,EACvB,oBAAoB,CACZ,CAAC;AACX,MAAM,MAAM,YAAY,GAAG,CAAC,OAAO,cAAc,CAAC,CAAC,MAAM,CAAC,CAAC;AAE3D,eAAO,MAAM,oBAAoB,IAAI,CAAC;AAItC,2EAA2E;AAC3E,eAAO,MAAM,gBAAgB,YAC3B,aAAa,EACb,YAAY,EACZ,aAAa,EACb,gBAAgB,EAChB,aAAa,EACb,oBAAoB,CACZ,CAAC;AAEX,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,KAAK,CAAC,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC,CAAC;AAErF,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,YAAY,CAAC;IACvB,KAAK,CAAC,EAAE,SAAS,CAAC;CACnB;AAED,MAAM,WAAW,SAAS;IACxB,QAAQ,EAAE,KAAK,GAAG,IAAI,CAAC;IACvB,UAAU,EAAE,KAAK,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;CAC9C;AAED,MAAM,MAAM,SAAS,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AA4C1D,wHAAwH;AACxH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAa5F;AAED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HAAwH;AACxH,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAa5F;AAED,eAAO,MAAM,mBAAmB,6EAAoC,CAAC;AA2DrE,4GAA4G;AAC5G,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,SAAS,GAAG,IAAI,GAAG,SAAS,EAAE,KAAK,EAAE,SAAS,GAAG,OAAO,CAMhG"}
@@ -30,7 +30,8 @@ const CARD_RULE_FIELDS = [
30
30
  "item.author",
31
31
  "author.trusted",
32
32
  "source.kind",
33
- "source.integration"
33
+ "source.integration",
34
+ "item.pullRequest"
34
35
  ];
35
36
  const scalarSchema = z.union([
36
37
  z.string().max(MAX_STRING_VALUE_LENGTH),