@mastra/factory 0.28.0-alpha.9 → 0.29.0-alpha.0

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 (348) hide show
  1. package/README.md +67 -46
  2. package/dist/boards/board-writes.d.ts +3 -3
  3. package/dist/boards/board-writes.d.ts.map +1 -1
  4. package/dist/boards/board-writes.js +24 -20
  5. package/dist/boards/board-writes.js.map +1 -1
  6. package/dist/boards/project-boards.d.ts +20 -0
  7. package/dist/boards/project-boards.d.ts.map +1 -1
  8. package/dist/boards/project-boards.js +35 -11
  9. package/dist/boards/project-boards.js.map +1 -1
  10. package/dist/boards/registry.d.ts.map +1 -1
  11. package/dist/boards/registry.js +0 -3
  12. package/dist/boards/registry.js.map +1 -1
  13. package/dist/boards/reroute.d.ts +31 -0
  14. package/dist/boards/reroute.d.ts.map +1 -0
  15. package/dist/boards/reroute.js +71 -0
  16. package/dist/boards/reroute.js.map +1 -0
  17. package/dist/capabilities/version-control.d.ts +6 -1
  18. package/dist/capabilities/version-control.d.ts.map +1 -1
  19. package/dist/environment/build-runner.d.ts +13 -2
  20. package/dist/environment/build-runner.d.ts.map +1 -1
  21. package/dist/environment/build-runner.js +42 -0
  22. package/dist/environment/build-runner.js.map +1 -1
  23. package/dist/environment/build-schedule.js +1 -1
  24. package/dist/environment/build-schedule.js.map +1 -1
  25. package/dist/environment/build-workflow.d.ts +6 -4
  26. package/dist/environment/build-workflow.d.ts.map +1 -1
  27. package/dist/environment/build-workflow.js +70 -66
  28. package/dist/environment/build-workflow.js.map +1 -1
  29. package/dist/environment/build.d.ts +22 -7
  30. package/dist/environment/build.d.ts.map +1 -1
  31. package/dist/environment/build.js +73 -15
  32. package/dist/environment/build.js.map +1 -1
  33. package/dist/environment/heads.d.ts +1 -1
  34. package/dist/environment/heads.d.ts.map +1 -1
  35. package/dist/environment/heads.js +4 -1
  36. package/dist/environment/heads.js.map +1 -1
  37. package/dist/environment/repository-access.d.ts +15 -0
  38. package/dist/environment/repository-access.d.ts.map +1 -0
  39. package/dist/environment/repository-access.js +60 -0
  40. package/dist/environment/repository-access.js.map +1 -0
  41. package/dist/factory.d.ts +5 -2
  42. package/dist/factory.d.ts.map +1 -1
  43. package/dist/factory.js +40 -30
  44. package/dist/factory.js.map +1 -1
  45. package/dist/integrations/base.d.ts +8 -0
  46. package/dist/integrations/base.d.ts.map +1 -1
  47. package/dist/integrations/dependabot/default-rules.d.ts +38 -0
  48. package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
  49. package/dist/integrations/dependabot/default-rules.js +63 -0
  50. package/dist/integrations/dependabot/default-rules.js.map +1 -0
  51. package/dist/integrations/dependabot/rules.d.ts +42 -0
  52. package/dist/integrations/dependabot/rules.d.ts.map +1 -0
  53. package/dist/integrations/dependabot/rules.js +187 -0
  54. package/dist/integrations/dependabot/rules.js.map +1 -0
  55. package/dist/integrations/dependabot/sync.d.ts +76 -0
  56. package/dist/integrations/dependabot/sync.d.ts.map +1 -0
  57. package/dist/integrations/dependabot/sync.js +111 -0
  58. package/dist/integrations/dependabot/sync.js.map +1 -0
  59. package/dist/integrations/github/routes.d.ts.map +1 -1
  60. package/dist/integrations/github/routes.js +7 -2
  61. package/dist/integrations/github/routes.js.map +1 -1
  62. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  63. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  64. package/dist/integrations/github/sandbox-release.js +16 -1
  65. package/dist/integrations/github/sandbox-release.js.map +1 -1
  66. package/dist/integrations/github/sandbox.d.ts +12 -0
  67. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  68. package/dist/integrations/github/sandbox.js +22 -1
  69. package/dist/integrations/github/sandbox.js.map +1 -1
  70. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  71. package/dist/integrations/platform/connect/routes.js +4 -0
  72. package/dist/integrations/platform/connect/routes.js.map +1 -1
  73. package/dist/integrations/platform/github/event-worker.d.ts +5 -0
  74. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  75. package/dist/integrations/platform/github/event-worker.js +33 -2
  76. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  77. package/dist/integrations/platform/github/integration.d.ts +19 -1
  78. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  79. package/dist/integrations/platform/github/integration.js +183 -105
  80. package/dist/integrations/platform/github/integration.js.map +1 -1
  81. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  82. package/dist/integrations/platform/jira/integration.js +5 -1
  83. package/dist/integrations/platform/jira/integration.js.map +1 -1
  84. package/dist/integrations/platform/vanta/integration.d.ts +33 -0
  85. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
  86. package/dist/integrations/platform/vanta/integration.js +133 -0
  87. package/dist/integrations/platform/vanta/integration.js.map +1 -0
  88. package/dist/integrations/slack/integration.d.ts.map +1 -1
  89. package/dist/integrations/slack/integration.js +7 -4
  90. package/dist/integrations/slack/integration.js.map +1 -1
  91. package/dist/integrations/vanta/default-rules.d.ts +34 -0
  92. package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
  93. package/dist/integrations/vanta/default-rules.js +61 -0
  94. package/dist/integrations/vanta/default-rules.js.map +1 -0
  95. package/dist/integrations/vanta/rules.d.ts +40 -0
  96. package/dist/integrations/vanta/rules.d.ts.map +1 -0
  97. package/dist/integrations/vanta/rules.js +208 -0
  98. package/dist/integrations/vanta/rules.js.map +1 -0
  99. package/dist/integrations/vanta/sync.d.ts +36 -0
  100. package/dist/integrations/vanta/sync.d.ts.map +1 -0
  101. package/dist/integrations/vanta/sync.js +73 -0
  102. package/dist/integrations/vanta/sync.js.map +1 -0
  103. package/dist/mcp/routes.d.ts.map +1 -1
  104. package/dist/mcp/routes.js +3 -5
  105. package/dist/mcp/routes.js.map +1 -1
  106. package/dist/routes/board-snapshot.d.ts +24 -1
  107. package/dist/routes/board-snapshot.d.ts.map +1 -1
  108. package/dist/routes/board-snapshot.js +75 -7
  109. package/dist/routes/board-snapshot.js.map +1 -1
  110. package/dist/routes/boards.d.ts +2 -3
  111. package/dist/routes/boards.d.ts.map +1 -1
  112. package/dist/routes/boards.js.map +1 -1
  113. package/dist/routes/contracts.d.ts +307 -0
  114. package/dist/routes/contracts.d.ts.map +1 -1
  115. package/dist/routes/contracts.js +253 -9
  116. package/dist/routes/contracts.js.map +1 -1
  117. package/dist/routes/intake-routes.d.ts +3 -0
  118. package/dist/routes/intake-routes.d.ts.map +1 -1
  119. package/dist/routes/intake-routes.js +44 -0
  120. package/dist/routes/intake-routes.js.map +1 -1
  121. package/dist/routes/knowledge.d.ts.map +1 -1
  122. package/dist/routes/knowledge.js +3 -2
  123. package/dist/routes/knowledge.js.map +1 -1
  124. package/dist/routes/projects.d.ts.map +1 -1
  125. package/dist/routes/projects.js +5 -0
  126. package/dist/routes/projects.js.map +1 -1
  127. package/dist/routes/sandbox-envs.d.ts +2 -0
  128. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  129. package/dist/routes/sandbox-envs.js +3 -0
  130. package/dist/routes/sandbox-envs.js.map +1 -1
  131. package/dist/routes/source-control-sessions.d.ts +1 -1
  132. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  133. package/dist/routes/source-control-sessions.js +109 -3
  134. package/dist/routes/source-control-sessions.js.map +1 -1
  135. package/dist/routes/source-control-settings.d.ts +2 -0
  136. package/dist/routes/source-control-settings.d.ts.map +1 -1
  137. package/dist/routes/source-control-settings.js +5 -0
  138. package/dist/routes/source-control-settings.js.map +1 -1
  139. package/dist/routes/surface.d.ts +8 -1
  140. package/dist/routes/surface.d.ts.map +1 -1
  141. package/dist/routes/surface.js +74 -10
  142. package/dist/routes/surface.js.map +1 -1
  143. package/dist/routes/work-item-activity.d.ts +11 -0
  144. package/dist/routes/work-item-activity.d.ts.map +1 -0
  145. package/dist/routes/work-item-activity.js +25 -0
  146. package/dist/routes/work-item-activity.js.map +1 -0
  147. package/dist/routes/work-item-selection.d.ts +14 -0
  148. package/dist/routes/work-item-selection.d.ts.map +1 -0
  149. package/dist/routes/work-item-selection.js +44 -0
  150. package/dist/routes/work-item-selection.js.map +1 -0
  151. package/dist/routes/work-item-starters.d.ts +29 -0
  152. package/dist/routes/work-item-starters.d.ts.map +1 -0
  153. package/dist/routes/work-item-starters.js +152 -0
  154. package/dist/routes/work-item-starters.js.map +1 -0
  155. package/dist/routes/work-items.d.ts.map +1 -1
  156. package/dist/routes/work-items.js +239 -16
  157. package/dist/routes/work-items.js.map +1 -1
  158. package/dist/rules/dispatch-errors.d.ts +3 -0
  159. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  160. package/dist/rules/dispatch-errors.js +9 -0
  161. package/dist/rules/dispatch-errors.js.map +1 -1
  162. package/dist/rules/dispatcher.d.ts +4 -1
  163. package/dist/rules/dispatcher.d.ts.map +1 -1
  164. package/dist/rules/dispatcher.js +122 -33
  165. package/dist/rules/dispatcher.js.map +1 -1
  166. package/dist/rules/index.d.ts +2 -2
  167. package/dist/rules/index.d.ts.map +1 -1
  168. package/dist/rules/index.js +2 -2
  169. package/dist/rules/processor.d.ts +2 -0
  170. package/dist/rules/processor.d.ts.map +1 -1
  171. package/dist/rules/processor.js +18 -4
  172. package/dist/rules/processor.js.map +1 -1
  173. package/dist/rules/start-coordinator.d.ts +6 -1
  174. package/dist/rules/start-coordinator.d.ts.map +1 -1
  175. package/dist/rules/start-coordinator.js +6 -2
  176. package/dist/rules/start-coordinator.js.map +1 -1
  177. package/dist/rules/transition-service.d.ts +20 -2
  178. package/dist/rules/transition-service.d.ts.map +1 -1
  179. package/dist/rules/transition-service.js +43 -20
  180. package/dist/rules/transition-service.js.map +1 -1
  181. package/dist/rules/types.d.ts +71 -3
  182. package/dist/rules/types.d.ts.map +1 -1
  183. package/dist/rules/types.js +10 -2
  184. package/dist/rules/types.js.map +1 -1
  185. package/dist/rules/validation.d.ts.map +1 -1
  186. package/dist/rules/validation.js +5 -0
  187. package/dist/rules/validation.js.map +1 -1
  188. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  189. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  190. package/dist/sandbox/context-sandboxes.js +120 -0
  191. package/dist/sandbox/context-sandboxes.js.map +1 -0
  192. package/dist/sandbox/session-retirement.d.ts +11 -4
  193. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  194. package/dist/sandbox/session-retirement.js +39 -13
  195. package/dist/sandbox/session-retirement.js.map +1 -1
  196. package/dist/session/factory-session.d.ts +20 -5
  197. package/dist/session/factory-session.d.ts.map +1 -1
  198. package/dist/session/factory-session.js +20 -6
  199. package/dist/session/factory-session.js.map +1 -1
  200. package/dist/session/live-sessions.d.ts +1 -1
  201. package/dist/session/live-sessions.d.ts.map +1 -1
  202. package/dist/session/live-sessions.js +12 -2
  203. package/dist/session/live-sessions.js.map +1 -1
  204. package/dist/storage/domains/audit/actions.d.ts +1 -1
  205. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  206. package/dist/storage/domains/audit/actions.js +2 -1
  207. package/dist/storage/domains/audit/actions.js.map +1 -1
  208. package/dist/storage/domains/audit/actors.d.ts.map +1 -1
  209. package/dist/storage/domains/audit/actors.js +1 -1
  210. package/dist/storage/domains/audit/actors.js.map +1 -1
  211. package/dist/storage/domains/boards/base.d.ts +25 -5
  212. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  213. package/dist/storage/domains/boards/base.js +57 -20
  214. package/dist/storage/domains/boards/base.js.map +1 -1
  215. package/dist/storage/domains/intake/base.d.ts +1 -1
  216. package/dist/storage/domains/intake/base.js +2 -2
  217. package/dist/storage/domains/intake/base.js.map +1 -1
  218. package/dist/storage/domains/projects/base.d.ts +16 -2
  219. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  220. package/dist/storage/domains/projects/base.js +32 -5
  221. package/dist/storage/domains/projects/base.js.map +1 -1
  222. package/dist/storage/domains/work-items/base.d.ts +60 -8
  223. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  224. package/dist/storage/domains/work-items/base.js +180 -18
  225. package/dist/storage/domains/work-items/base.js.map +1 -1
  226. package/dist/storage/domains/work-items/cards.d.ts +1 -0
  227. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  228. package/dist/storage/domains/work-items/cards.js +32 -8
  229. package/dist/storage/domains/work-items/cards.js.map +1 -1
  230. package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
  231. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
  232. package/dist/storage/domains/work-items/legacy-review.js +62 -3
  233. package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
  234. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -0
  235. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  236. package/dist/storage/domains/work-items/work-item-schema.js +46 -18
  237. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  238. package/dist/tools/annotations.d.ts.map +1 -1
  239. package/dist/tools/annotations.js +4 -0
  240. package/dist/tools/annotations.js.map +1 -1
  241. package/dist/tools/approval-tools.d.ts +20 -0
  242. package/dist/tools/approval-tools.d.ts.map +1 -1
  243. package/dist/tools/approval-tools.js +79 -30
  244. package/dist/tools/approval-tools.js.map +1 -1
  245. package/dist/tools/audit-events-tool.d.ts +29 -0
  246. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  247. package/dist/tools/audit-events-tool.js +180 -0
  248. package/dist/tools/audit-events-tool.js.map +1 -0
  249. package/dist/tools/index.d.ts +2 -1
  250. package/dist/tools/index.d.ts.map +1 -1
  251. package/dist/tools/index.js +2 -0
  252. package/dist/tools/index.js.map +1 -1
  253. package/dist/tools/messaging-tools.d.ts.map +1 -1
  254. package/dist/tools/messaging-tools.js +1 -1
  255. package/dist/tools/messaging-tools.js.map +1 -1
  256. package/dist/tools/permissions.d.ts.map +1 -1
  257. package/dist/tools/permissions.js +1 -0
  258. package/dist/tools/permissions.js.map +1 -1
  259. package/dist/tools/read-tools.d.ts +0 -2
  260. package/dist/tools/read-tools.d.ts.map +1 -1
  261. package/dist/tools/read-tools.js +2 -7
  262. package/dist/tools/read-tools.js.map +1 -1
  263. package/dist/tools/reports.d.ts +3 -0
  264. package/dist/tools/reports.d.ts.map +1 -1
  265. package/dist/tools/reports.js +3 -3
  266. package/dist/tools/reports.js.map +1 -1
  267. package/dist/tools/run-watch.d.ts +14 -2
  268. package/dist/tools/run-watch.d.ts.map +1 -1
  269. package/dist/tools/run-watch.js +24 -4
  270. package/dist/tools/run-watch.js.map +1 -1
  271. package/dist/tools/session-tools.d.ts.map +1 -1
  272. package/dist/tools/session-tools.js +17 -6
  273. package/dist/tools/session-tools.js.map +1 -1
  274. package/dist/tools/sessions-state-processor.js +1 -1
  275. package/dist/tools/sessions-state-processor.js.map +1 -1
  276. package/dist/tools/side-sessions.d.ts.map +1 -1
  277. package/dist/tools/side-sessions.js +1 -1
  278. package/dist/tools/side-sessions.js.map +1 -1
  279. package/dist/tools/work-item-tools.d.ts.map +1 -1
  280. package/dist/tools/work-item-tools.js +12 -2
  281. package/dist/tools/work-item-tools.js.map +1 -1
  282. package/dist/work-item-branch.d.ts +1 -1
  283. package/dist/work-item-branch.d.ts.map +1 -1
  284. package/dist/work-item-branch.js +2 -0
  285. package/dist/work-item-branch.js.map +1 -1
  286. package/dist/work-items/board-check.d.ts +11 -0
  287. package/dist/work-items/board-check.d.ts.map +1 -0
  288. package/dist/work-items/board-check.js +20 -0
  289. package/dist/work-items/board-check.js.map +1 -0
  290. package/dist/work-items/board-filter-options.d.ts +5 -0
  291. package/dist/work-items/board-filter-options.d.ts.map +1 -0
  292. package/dist/work-items/board-filter-options.js +27 -0
  293. package/dist/work-items/board-filter-options.js.map +1 -0
  294. package/dist/work-items/board-phases.d.ts +28 -0
  295. package/dist/work-items/board-phases.d.ts.map +1 -0
  296. package/dist/work-items/board-phases.js +165 -0
  297. package/dist/work-items/board-phases.js.map +1 -0
  298. package/dist/work-items/card-facts.d.ts +24 -0
  299. package/dist/work-items/card-facts.d.ts.map +1 -0
  300. package/dist/work-items/card-facts.js +75 -0
  301. package/dist/work-items/card-facts.js.map +1 -0
  302. package/dist/work-items/card-labels.d.ts +5 -0
  303. package/dist/work-items/card-labels.d.ts.map +1 -0
  304. package/dist/work-items/card-labels.js +13 -0
  305. package/dist/work-items/card-labels.js.map +1 -0
  306. package/dist/work-items/card-number.d.ts +10 -0
  307. package/dist/work-items/card-number.d.ts.map +1 -0
  308. package/dist/work-items/card-number.js +15 -0
  309. package/dist/work-items/card-number.js.map +1 -0
  310. package/dist/work-items/card-people.d.ts +25 -0
  311. package/dist/work-items/card-people.d.ts.map +1 -0
  312. package/dist/work-items/card-people.js +100 -0
  313. package/dist/work-items/card-people.js.map +1 -0
  314. package/dist/work-items/card-search-text.d.ts +4 -0
  315. package/dist/work-items/card-search-text.d.ts.map +1 -0
  316. package/dist/work-items/card-search-text.js +15 -0
  317. package/dist/work-items/card-search-text.js.map +1 -0
  318. package/dist/work-items/card-source-filters.d.ts +23 -0
  319. package/dist/work-items/card-source-filters.d.ts.map +1 -0
  320. package/dist/work-items/card-source-filters.js +25 -0
  321. package/dist/work-items/card-source-filters.js.map +1 -0
  322. package/dist/work-items/create-work-item.d.ts +0 -6
  323. package/dist/work-items/create-work-item.d.ts.map +1 -1
  324. package/dist/work-items/create-work-item.js +2 -7
  325. package/dist/work-items/create-work-item.js.map +1 -1
  326. package/dist/work-items/list-related-cards.d.ts +4 -0
  327. package/dist/work-items/list-related-cards.d.ts.map +1 -0
  328. package/dist/work-items/list-related-cards.js +24 -0
  329. package/dist/work-items/list-related-cards.js.map +1 -0
  330. package/dist/work-items/related-cards.d.ts +21 -0
  331. package/dist/work-items/related-cards.d.ts.map +1 -0
  332. package/dist/work-items/related-cards.js +45 -0
  333. package/dist/work-items/related-cards.js.map +1 -0
  334. package/dist/work-items/search-words.d.ts +5 -0
  335. package/dist/work-items/search-words.d.ts.map +1 -0
  336. package/dist/work-items/search-words.js +12 -0
  337. package/dist/work-items/search-words.js.map +1 -0
  338. package/dist/work-items/split-migration.d.ts.map +1 -1
  339. package/dist/work-items/split-migration.js +6 -2
  340. package/dist/work-items/split-migration.js.map +1 -1
  341. package/dist/workspace.d.ts +0 -1
  342. package/dist/workspace.d.ts.map +1 -1
  343. package/dist/workspace.js +140 -78
  344. package/dist/workspace.js.map +1 -1
  345. package/factory-skills/factory-build/SKILL.md +1 -1
  346. package/factory-skills/factory-self-review/SKILL.md +1 -1
  347. package/factory-skills/factory-triage/SKILL.md +4 -4
  348. package/package.json +17 -16
package/README.md CHANGED
@@ -58,6 +58,14 @@ function summarizeCard(card: Card) {
58
58
 
59
59
  Each work item has one board item. Factory's card-to-card parent link is `parentBoardItemId`. Provider sub-issue ancestry is not populated into `card.workItem.parentWorkItemId`; migrated work items leave that field null. Existing card IDs, comments, subscriptions, run bindings, and `/work-items/:id` URLs stay unchanged. The work item gets its own ID. For one release, work-item API responses also retain the legacy top-level title, external source, and merged metadata fields.
60
60
 
61
+ `GET /web/factory/projects/:id/work-items` lists a project's cards. Pass `sessionId` to list only the cards holding that session and the cards related to them: a card's parent and children, and a pull request with the card whose session branch it was pushed from. Repeat `sessionId` to list several sessions' cards. Pass `scope=sessions` to list the cards holding any session and the cards related to them, without naming the sessions; it can't be combined with `sessionId`. Pass `started=false` to list the cards holding no session, most recently updated first: `limit` sets how many are sent (20 unless given, 50 at most), `q` keeps the cards whose title, key, number or source id contains every word in it, in any case, and `total` in the response counts every card that matched, sent or not. `started=false` can't be combined with `scope` or `sessionId`, and `q` is accepted only with it. Repeat `source` (up to 100 values) to list the cards filed from those sources, each named by its source id or its URL, whatever sessions the cards hold; it can't be combined with `started`, `scope` or `sessionId`. Repeat `workItemId` (up to 100 values) to list the cards with those ids and no other, whatever sessions they hold; an id no card has is left out, so asking for one card that was deleted answers 200 with an empty list. It can't be combined with `source`, `started`, `scope` or `sessionId`. A query the route can't answer gets a 400, never the whole board. Apart from `total`, the response has the same shape in every case, and `runningSessionIds` and `parkedSessionIds` cover only the listed cards.
62
+
63
+ The whole-board listing also returns a `cursor`, and each card carries `changedAt`, when it last changed. Send the cursor back as `since` to get only what moved since that read: `workItems` then holds the cards changed, `removedIds` the cards deleted, and `check` a value naming every card on the board and when it last changed, with the next `cursor`. A reader merges these into the board it kept, then compares `boardCheck` of its merged cards (exported from `@mastra/factory/work-items/board-check`) with `check`, and reads the board whole again when they differ. A `since` the server can't answer from is ignored, not refused, so the answer is the listing as it would be without it, with no `removedIds`: a malformed cursor, a board that returned no `cursor`, or a listing narrowed by `sessionId`, `scope`, `started`, `source` or `workItemId`.
64
+
65
+ Two reads answer questions about a project's cards without listing them. `GET /web/factory/projects/:id/work-items/starters` counts the cards on the default board that each new-session starter would act on: cards whose run failed, pull requests with changes requested, pull requests waiting for review (with when the oldest was opened), triaged cards waiting on a person, untriaged cards, bugs with no plan, the label with the most cards not started, and stale pull requests. Failed runs are read from the 50 newest run decisions, as on the cards. `GET /web/factory/projects/:id/work-items/activity?since=<ISO 8601 instant>` returns how many cards the project has, and when cards were created and completed from `since` on; a missing or malformed `since` is a 400. Its answer carries an `ETag`: ask again for the same `since` with `If-None-Match`, and an answer that did not change comes back as a 304 with no body.
66
+
67
+ Two more reads serve a board without sending every card. `GET /web/factory/projects/:id/boards/:boardKey/phases` returns one entry per phase of the board in `phases`, in the board's order: `phase` is its id, `total` counts the cards in it, and `cards` names the first of them as `{ id, version }`. `version` names the card's body: it is another value whenever anything in the body is, including a change that leaves `changedAt` as it was. `limit` sets how many each phase names (50 unless given, 200 at most), `window=<phase>:<count>` (repeatable) names more cards of one phase, and `item=<card id>` asks for one card wherever it lies: the answer names it in `item` as `{ id, version, places }`, where `places` gives each phase the view lists it under and its `position` there (how many cards the phase lists before it), and `cards=true` sends its body. No phase names more cards for it, so the answer is the same size for the oldest card of a phase as for the newest. `places` is empty when the search or filters leave the card out, and `item` is absent when the board does not hold the card. `sort` is `recent` (latest entry into the phase first, the default), `recent-mine` (the cards the signed-in user last moved into the phase first), `created-newest` or `created-oldest`. `q` keeps the cards whose title, key, number or source id contains every word in it; `label`, `source`, `linearProject`, `teammate`, `author`, `assignee`, `reviewer` and `worked` (all repeatable) keep the cards matching every field given. `boardTotal` counts the board's cards whatever the search and filters, `matchingTotal` the cards matching them, a card in two phases once. `related` names the cards related to a named card that no phase names, the first `limit` of each card's, and `relatedTotal` counts them all, and `runningSessionIds` and `parkedSessionIds` cover the named cards. Pass `cards=true` to also receive the body of every named card in `workItems`, each with its `version`; without it, read the cards whose `version` differs from the copy you kept with `GET /web/factory/projects/:id/work-items?workItemId=<id>`, which sends each card with its `version` too. A card in none of the board's phases is counted in the first one. A malformed parameter is a 400 `invalid_phases_query`; a board the project doesn't have is a 404; a `window` for a phase the board doesn't have is ignored. `GET /web/factory/projects/:id/work-items/filter-options` returns what a board can be filtered by, over every card of the project: `labels`, sorted; `people`, each person a source names as author, assignee or requested reviewer, as `{ id, name, source }`; and `actorIds`, the Factory users who filed, moved or started a card. Both answers carry an `ETag`; send it back as `If-None-Match` and an unchanged answer is a 304.
68
+
61
69
  #### Migration and dry run
62
70
 
63
71
  Factory keeps the legacy `work_items` table and copies each card into the new tables. Before it starts serving, it copies only open cards. Done and canceled cards are copied in the background afterwards and appear on the board shortly after startup. While that runs, opening a card, or receiving a Linear, Jira, GitHub, GitLab, or incident.io event for it, copies that card on demand, so a reopened issue keeps its original card. Board lists, such as the Done column, fill in as the background copy progresses.
@@ -116,7 +124,7 @@ There is no dual-write rollback: an older Factory version sees the legacy snapsh
116
124
 
117
125
  Each project's boards live in its database, and the stored row is the board.
118
126
 
119
- - **Factory's boards**: the built-in Work board and the boards you pass to `new MastraFactory({ boards })` (app boards). Factory stores each in a project once: when the project is created, and in existing projects the first time a process loads them, which includes the preload at startup. Work goes only into a project that has no boards yet: a project that already holds a board, such as one your app wrote with `factory.upsertBoard()`, gets no Work from Factory. A project created now (the create call onboarding makes) gets Work without a Triage phase: Intake, Planning, Building, Review, Done and Canceled. Every other project, including one created on an older release that stores its boards only now, gets Work with Triage, as Factory always stored it, and resetting Factory's Work restores Factory's built-in Work, with Triage if Factory first stored the project's Work with it (an app's `work` board upserted with `projects: 'all'` resets to the app's; one upserted only to named projects resets to Factory's). Add Triage back in Settings › Work board if you want it. The project keeps a key's board from then on. A Factory release or an app change never rewrites it (except through a [board migration](#board-migrations)), and a board the project deleted is not stored again. A key you add later is stored once in every project that hasn't had it. The retired Review board is never stored, and its `review` key is reserved: no board can be created or written under it. A project that still has open cards on it is served the code Review board, read-only (see [The retired Review board](#the-retired-review-board)).
127
+ - **Factory's boards**: the built-in Work board and the boards you pass to `new MastraFactory({ boards })` (app boards). Factory stores each in a project once: when the project is created, and in existing projects the first time a process loads them, which includes the preload at startup. Work goes only into a project that has no boards yet: a project that already holds a board, such as one your app wrote with `factory.upsertBoard()`, gets no Work from Factory. A project created now (the create call onboarding makes) gets Work without a Triage phase: Intake, Planning, Building, Review, Done and Canceled. Every other project, including one created on an older release that stores its boards only now, gets Work with Triage, as Factory always stored it, and resetting Factory's Work restores Factory's built-in Work, with Triage if Factory first stored the project's Work with it (an app's `work` board upserted with `projects: 'all'` resets to the app's; one upserted only to named projects resets to Factory's). Add Triage back in Settings › Work board if you want it. The project keeps a key's board from then on. A Factory release or an app change never rewrites it (except through a [board migration](#board-migrations)), and a board the project deleted is not stored again. A key you add later is stored once in every project that hasn't had it. The retired Review board is never stored. A project that still has open cards on it, and no board of its own under `review`, is served the code Review board, read-only (see [The retired Review board](#the-retired-review-board)).
120
128
  - **The project's own boards**: boards an admin created through the boards API, or that an app wrote with [`factory.upsertBoard()`](#writing-a-board-into-projects).
121
129
 
122
130
  A project's boards are the Work and app boards in code order, followed by the others. The catalog, card creation through the API and Factory tools, transitions, the dispatcher, phase runs and the attention views all read that list. Existing apps need no change.
@@ -138,7 +146,7 @@ Everything else can change: names and descriptions, every runner field (skill, c
138
146
 
139
147
  **Boards that no longer fit the code.** A Work or app board is served even when it has fallen out of step with a newer release's code, with the code behaviour that still fits it. The board's tool rules always stay; its event rules and transition policy need every phase the code declares, and `sourceClosed` needs both its phases, still terminal. A move Factory's code makes that the board's `nextPhases` don't allow is reported too; when code makes it, the move is refused (and retried until its attempts run out), and the card stays where it is. Each dropped behaviour is reported in the board's `problems`, for example `Board "release" runs without its code event rules (…): phase "testing" isn't stored.` or `Board "work" doesn't let phase "planning" move cards to "execute", so Factory's code can't make that move.` A board stored under an app board's key that the app stopped defining is served as one of the project's own boards.
140
148
 
141
- Creating a board under a built-in or app board's key is refused with `409 code_board`, and so is deleting the Work board, whose code rules run by its key; reset it instead. App boards can be deleted like the project's own; Factory doesn't store them again, and `factory.upsertBoard()` brings one back. The retired Review board's `review` key is reserved: creating, editing, resetting or deleting a board under it is refused with `409 reserved_board`, because a new board under that key would take over the cards stored there.
149
+ Creating a board under a built-in or app board's key is refused with `409 code_board`, and so is deleting the Work board, whose code rules run by its key; reset it instead. App boards can be deleted like the project's own; Factory doesn't store them again, and `factory.upsertBoard()` brings one back.
142
150
 
143
151
  **When a board isn't stored.** If storing Factory's boards in a project fails, the boards it couldn't store aren't served, the catalog reports `Board "<key>" isn't stored in this project yet; Factory stores it on the next load.`, and `GET …/boards/:boardKey` answers `404 board_not_found`; the project's next load tries again. Factory serves code boards itself only for every project when the boards storage could not start, and on a replica that has not loaded a project yet, until its first load.
144
152
 
@@ -150,7 +158,7 @@ A release that changes what Factory's own boards need can carry a board migratio
150
158
 
151
159
  #### Writing a board into projects
152
160
 
153
- `factory.upsertBoard()` writes a board definition into projects after `prepare()`: each named project (or all of them) that has no board under its key gets it, and each one that has it, edited or not, has it replaced at the next revision. Run it after `prepare()` at every startup to ship your boards: with `projects: 'all'`, a project that has no boards yet when it first loads (one created later, during onboarding, or one that never loaded) gets the board too, before Factory's own, so a project that gets your `work` board never gets Factory's Work beside it. Factory only adds Work to a project with no boards. That lasts for the process, which is why it runs at every startup; a project that already has boards is changed only by the call itself. The board is checked once, as the boards API checks it, each replacement passes the checks an edit does (cards in a removed phase refuse it with `phase_in_use` there), and each write is audited as `factory.board.created` or `factory.board.updated` by `system:factory`. It returns the projects it stored the board in, the ones it replaced it in, and the ones that already had it unchanged. A refused board throws `BoardWriteError`, whose `code` is the boards API's error code (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use`, `project_not_found`, or `reserved_board` for the retired Review board's `review` key). A board under a new key has no code behaviour; an app board's key keeps the app board's, so it also brings back an app board a project deleted.
161
+ `factory.upsertBoard()` writes a board definition into projects after `prepare()`: each named project (or all of them) that has no board under its key gets it, and each one that has it, edited or not, has it replaced at the next revision. Run it after `prepare()` at every startup to ship your boards: with `projects: 'all'`, a project that has no boards yet when it first loads (one created later, during onboarding, or one that never loaded) gets the board too, before Factory's own, so a project that gets your `work` board never gets Factory's Work beside it. Factory only adds Work to a project with no boards. That lasts for the process, which is why it runs at every startup; a project that already has boards is changed only by the call itself. The board is checked once, as the boards API checks it, each replacement passes the checks an edit does (cards in a removed phase refuse it with `phase_in_use` there), and each write is audited as `factory.board.created` or `factory.board.updated` by `system:factory`. It returns the projects it stored the board in, the ones it replaced it in, and the ones that already had it unchanged. A refused board throws `BoardWriteError`, whose `code` is the boards API's error code (`invalid_board`, `unknown_skill`, `code_behaviour`, `phase_in_use`, `project_not_found`, or `board_in_use` when the key is `review` and [the retired Review board](#the-retired-review-board) still has an open card in a project). Projects are written one at a time and the call stops at the first one that refuses. The projects written before it keep the board, so move or finish what was refused and run the call again. A board under a new key has no code behaviour; an app board's key keeps the app board's, so it also brings back an app board a project deleted.
154
162
 
155
163
  ```ts
156
164
  const bugs = {
@@ -171,7 +179,7 @@ const { inserted, updated, unchanged } = await factory.upsertBoard(bugs, { proje
171
179
  **Editing rules for stored boards.**
172
180
 
173
181
  - Board and phase keys never change. Renaming changes `name`. Any phase may become the first phase, as long as it is `resting`.
174
- - Removing a phase, or changing its `kind`, while cards sit in it is refused with `409 phase_in_use` and the count per phase. Deleting a board that has cards is refused with `409 board_in_use`. Factory never moves cards for you. A card created between the check and the write can still land on a removed phase; it then shows as an unsupported item until it is moved.
182
+ - Removing a phase, or changing its `kind`, while cards sit in it is refused with `409 phase_in_use` and the count per phase. Deleting a board that has cards is refused with `409 board_in_use`. Factory never moves cards for you, except the retired Review board's when a board takes its key (see [The retired Review board](#the-retired-review-board)). A card created between the check and the write can still land on a removed phase; it then shows as an unsupported item until it is moved.
175
183
  - A runner skill that does not exist is refused (`422 unknown_skill`). A review skill outside the `review` context is saved with a warning in `problems`. A skill that disappears later never stops a board from loading; it shows in the catalog's `problems`.
176
184
 
177
185
  **Replicas.** Each board write replaces the project's board version. The replica that wrote it sees the change at once; other replicas notice within a second, the next time they touch that project.
@@ -184,10 +192,10 @@ const { inserted, updated, unchanged } = await factory.upsertBoard(bugs, { proje
184
192
  | -------- | --------------------------------------------------------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
185
193
  | `GET` | `/web/factory/projects/:id/boards` | — | The catalog, with each board's `source`, `editable` and `problems`. |
186
194
  | `GET` | `/web/factory/projects/:id/boards/:boardKey` | — | The definition, `revision`, `source`, `editable`, `problems`, `codeBehaviour` (per phase: `requiredNextPhases`, the moves Factory's code makes from it) and `canEdit` (whether you may change it). |
187
- | `POST` | `/web/factory/projects/:id/boards` | The board, with `key`. | `201` and the board. `409 code_board` for a code board's key, `409 board_exists` for a stored board's, `409 reserved_board` for `review`. |
188
- | `PATCH` | `/web/factory/projects/:id/boards/:boardKey` | The whole board without `key`, plus `expectedRevision`. | The board. Replaces every field. `422 code_behaviour` for an edit code behaviour can't honour, `409 reserved_board` for `review`. |
189
- | `POST` | `/web/factory/projects/:id/boards/:boardKey/reset` | `{ expectedRevision }` | The board, rewritten to Factory's current definition at the next revision. `409 not_code_board` for the project's own boards, `409 reserved_board` for `review`. |
190
- | `DELETE` | `/web/factory/projects/:id/boards/:boardKey?expectedRevision=n` | — | `204`. `409 code_board` for the Work board, `409 reserved_board` for `review`. |
195
+ | `POST` | `/web/factory/projects/:id/boards` | The board, with `key`. | `201` and the board. `409 code_board` for a code board's key, `409 board_exists` for a stored board's. |
196
+ | `PATCH` | `/web/factory/projects/:id/boards/:boardKey` | The whole board without `key`, plus `expectedRevision`. | The board. Replaces every field. `422 code_behaviour` for an edit code behaviour can't honour. |
197
+ | `POST` | `/web/factory/projects/:id/boards/:boardKey/reset` | `{ expectedRevision }` | The board, rewritten to Factory's current definition at the next revision. `409 not_code_board` for the project's own boards. |
198
+ | `DELETE` | `/web/factory/projects/:id/boards/:boardKey?expectedRevision=n` | — | `204`. `409 code_board` for the Work board. |
191
199
 
192
200
  A stale `expectedRevision` is refused with `409 revision_mismatch`; reload the board and try again.
193
201
 
@@ -554,9 +562,11 @@ New projects get no Review board; Work's Review phase (`pr-review`) does its job
554
562
  - **Still in use**: the project has at least one card stored on `review` that isn't in Done or Canceled. It keeps the Review board exactly as before: the board is served (read-only), its cards stay on it in their phases, Review and Re-review start the reviewer in its Reviewing phase, and merging or closing a pull request moves its card to Done or Canceled there. No card can be created on it. `/factories/:id/review` opens it.
555
563
  - **Redundant**: every card stored on `review` is in Done or Canceled, or there are none. The board isn't served. Those cards read as Work cards (Intake, Done and Canceled are unchanged; `review` reads as `pr-review`), and the next normal write stores them on `work`. `/factories/:id/review` opens Work filtered to cards with a pull request. Once a project's last open Review card finishes, the board goes away; it never comes back.
556
564
 
557
- A project that ran an earlier release may also hold a stored `review` board row from when Review was seeded. It is never served either way. When Factory wrote it and nobody edited it since, the board catalog ignores it; a row a person edited is listed under the catalog's `problems`, because its edits are not served.
565
+ `review` is a board key like any other. A project that stores a board under it, or an app that passes one in `boards`, has that board: it is listed and edited like the rest, it is served in place of the retired Review board, and the cards put on it are its cards in their stored phases, never read as Work. The cards the retired board left stored on `review` are not the new board's. The write that gives the project its board (a create, `factory.upsertBoard()`, or an edit of the seeded row below) stores their Work placement in the same transaction, with the old `review` phase as `pr-review`, so they stay where they were shown and the new board starts empty. While the retired board still has a card that isn't Done or Canceled, that write is refused with `409 board_in_use`; move or finish those cards first. An app board can't be refused, so when Factory stores an app's `review` board in a project, every card the retired board left there moves to Work, open ones included.
566
+
567
+ A project that ran an earlier release may also hold a stored `review` board row from when Review was seeded. While Factory wrote it and nobody edited it since, it is not a board of the project's own: the board catalog ignores it and its cards are the retired board's. Creating a board under `review` there writes the new board over that row, and editing the row (`PATCH`) makes it the project's board too; either way it is served from then on. Where the app defines a `review` board, Factory rewrites that seeded row to the app's definition on the project's next load, the one time it rewrites a stored board outside a migration.
558
568
 
559
- Either way, new pull requests follow the project's intake routes, and the default `pull-requests` route files them on Work › Review, so nothing new lands on Review unless one of the project's own routes targets it. In a project whose Review board is redundant, a route that targets `review` stops matching and arrivals fall through to the next route. A board config or skill override for `review` is ignored, and `review` is reserved: a custom board can't use that ID. For an existing install:
569
+ Either way, new pull requests follow the project's intake routes, and the default `pull-requests` route files them on Work › Review, so nothing new lands on Review unless one of the project's own routes targets it. In a project whose Review board is redundant, a route that targets `review` stops matching and arrivals fall through to the next route. A board config or skill override for the retired board is ignored. For an existing install:
560
570
 
561
571
  - A run in flight on an old Review card keeps its binding; its Reviewing phase runs its runner (`factory-review`).
562
572
  - Pairs filed before this change (a pull request card plus the card that authored it) stay two cards and keep working.
@@ -581,6 +591,16 @@ phases: {
581
591
 
582
592
  **Remaining limitations:** `factory-ui` still renders the built-in stage and role pipeline.
583
593
 
594
+ #### Card sandboxes
595
+
596
+ Each session context a card uses (`triage`, `work`, `review`, or a custom board's `runner.context`) is its own session with its own sandbox, so a card can hold one sandbox per context. Factory stops a context's sandbox as soon as the card no longer needs it:
597
+
598
+ - **Leaving a context.** When a move takes the card out of the last phase of a context into a phase that runs in another context (or none), Factory stops that context's sandbox, for example Triage → Planning stops the triage sandbox. Moves within one context stop nothing: Planning → Building keeps the `work` sandbox running. A run still in flight on the left session in this process, such as the agent whose own tool call made the move or a person chatting in it, keeps the sandbox until it ends, and Factory stops it then unless the card is back in that context.
599
+ - **Finishing.** Entering a terminal phase stops every sandbox the card holds. A Factory process that never opened a sandbox stops it by identity through the configured sandbox provider, so a card finished on any replica stops its sandboxes.
600
+ - **Coming back.** Stopping keeps the session, its branch and its files. A card that comes back to a context (PR review → Triage) resumes the same sandbox: E2B resumes the paused VM, Docker restarts the container, and the local sandbox reuses its directory. Platform sandboxes are not stopped remotely; they idle out under the environment's policy and the next run reattaches.
601
+
602
+ Stopping is best-effort: a committed move never fails because a sandbox did not stop, and a card moved again before the stop runs keeps its sandbox. Deleting a session still destroys its sandbox.
603
+
584
604
  #### The pull request loop on any board
585
605
 
586
606
  Nothing in Factory's runtime reads Work's board key or phase keys. Each part of the issue → build → self-review → pull request → review → merge loop is found by what a board's phases declare, so a board you create in the UI, through the API or in code runs the same loop under its own key and phase names:
@@ -602,25 +622,25 @@ Boards and phases take `name` and an optional `description`. A phase lists the p
602
622
  - `runner` — `{ agentId?, skill?, context?, instructions?, goal? }`. The runner is the only way a phase starts work: when a card enters the phase, from any source and including a card filed straight into it, Factory starts `skill` in the `context` session. `context` names the session the phase runs in (defaults to `work`); phases that share a context share a session. When the agent moves its own card into another phase of its context, that phase's `skill` still starts: its kickoff is queued onto the agent's run. Moving a card back into the phase it is in (a re-entry, such as a re-review after a push) supersedes the run in flight and resumes the skill. `skill` names a built-in Factory skill or one of your app's skills (see [Skills for custom boards](#skills-for-custom-boards)); a phase without one starts nothing. The kickoff names the card only by its URL (or title, quoted as untrusted data when an outside author wrote it); the agent reads everything else from the [`factory-work-item` signal](#the-factory-work-item-signal). `instructions` (up to 1,000 characters) are added to the kickoff. `agentId` defaults to `code-agent`, the only agent Factory runs today.
603
623
  - `runner.goal` — `{ objective, maxRuns? }`: the run pursues `objective` (up to 2,000 characters) as a Mastra goal. Factory stores it on the session's thread as the run starts, with the session's model as judge, and after each run the judge decides from the objective text and the latest messages whether the work is done, should continue (Factory starts another run, up to `maxRuns`, 1–50) or is waiting for a person. Waiting leaves the goal active and the card in its phase; the next message a person sends resumes it, and a skill asks people with `ask_user`, which parks the run in Factory's attention view. When `maxRuns` runs out, the goal pauses and the card stays: resume it from the session or move the card. When the card leaves the phase, by anyone, Factory marks the goal done. The judge sees only the objective and the latest messages, so state the done and waiting criteria in the objective. Work's Building pursues the approved plan this way, with up to 20 runs.
604
624
  - `autoStart` and `autoStartWhen` — the phase's runs start without a person's approval, for every card or only for cards matching the rule. To start only trusted authors' cards, add `author.trusted equals true` to `autoStartWhen`; by default, [intake routes](#intake-routes) file GitHub and GitLab cards from outside the write-access circle in Work › Intake, where nothing starts on its own.
605
- - `exitTool` — a tool name, or `{ id, autoApprove, autoApproveWhen }`, that ends the phase. The phase holds the card until that tool succeeds (for `submit_plan`, with an approved plan) in the session that works the card there: until then an agent or board rule asking to move the card on to another working phase is rejected with `approval_required`. Once it has succeeded during the card's current visit to the phase, the agent moves the card itself with `factory_transition_work_item` (the factory-phase signal tells it so and lists `nextPhases`), or a board tool rule for the exit tool (`tools`) moves it; the tool's success never moves the card by itself. A person can move the card at any time. The phase needs at least one next phase. `autoApprove` and `autoApproveWhen` only decide whether the tool approves itself, for every card or only cards matching the rule, or waits for a person; they are the only way plans are approved without a person. Factory sessions already run tools without asking, so for `submit_plan` this means an auto-approved plan is accepted without a person. Work's Planning declares `{ id: 'submit_plan', autoApprove: false }`: every plan waits for a person, who approves `submit_plan` in a signed-in chat (or moves the card), and then `factory-plan` moves the card to Building.
625
+ - `exitTool` — a tool name, or `{ id, autoApprove, autoApproveWhen }`, that ends the phase. The phase holds the card until that tool succeeds (for `submit_plan`, with an approved plan) in the session that works the card there: until then an agent or board rule asking to move the card on to another working phase is rejected with `approval_required`. Once it has succeeded during the card's current visit to the phase, the agent moves the card itself with `factory_transition_work_item` (the factory-phase signal tells it so and lists `nextPhases`), or a board tool rule for the exit tool (`tools`) moves it; the tool's success never moves the card by itself. A person can move the card at any time. The phase needs at least one next phase. `autoApprove` and `autoApproveWhen` only decide whether the tool approves itself, for every card or only cards matching the rule, or waits for a person; they are the only way plans are approved without a person. Factory sessions already run tools without asking, so for `submit_plan` this means an auto-approved plan is accepted without a person. Any other exit tool that pauses for a yes or no is approved the same way, and the sessions following the card are told a run waits on them only when a person has to answer. Work's Planning declares `{ id: 'submit_plan', autoApprove: false }`: every plan waits for a person, who approves `submit_plan` in a signed-in chat (or moves the card), and then `factory-plan` moves the card to Building.
606
626
  - `tools` — Factory tools the phase gives the session that works the card in it (the session whose context is the phase's `runner.context`): `factory_record_review_verdict` and `factory_review_source`. Tools follow the card: when it moves to a phase without them, the session loses them on its next turn, and a verdict tool call made after the card moved is refused. Every bound session keeps `factory_transition_work_item`. Work's Review grants both; a self-review phase, on a board that has one, grants only the verdict tool.
607
627
 
608
628
  Rules test a card's facts, read from its work item as the provider reported it:
609
629
 
610
- | Fact | What it is |
611
- | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
612
- | `item.labels` | The item's labels. |
613
- | `item.title` | The card's title. |
614
- | `item.author` | Who opened the item. |
615
- | `item.key` | The provider's key: `acme/app#42` (GitHub), `acme/app!7` (GitLab merge request), `ENG-12` (Linear), `OPS-3` (Jira), `INC-7` (incident.io). |
616
- | `item.state` | The provider's state: `open`, `closed` or `merged` on GitHub and GitLab, the workflow state name (`In Progress`) on Linear and Jira. |
617
- | `item.assignees` | Who the item is assigned to, as a list. |
618
- | `item.pullRequest` | The number of the card's open pull or merge request, absent when it has none. |
619
- | `author.trusted` | Whether the author is trusted (see below). |
620
- | `source.kind` | `issue`, `pull_request`, … |
621
- | `source.integration` | The integration that filed it: `github`, `gitlab`, `linear`, `jira`, `incidentio`, … |
622
- | `source.provider` | The provider the work item comes from; the integration for every integration Factory ships. |
623
- | `source.repository` | Where the item lives: the GitHub repository or GitLab project path (`acme/app`, `acme/platform/api`), the Linear team key (`ENG`) or the Jira project key (`OPS`). Absent for incident.io and manual cards. |
630
+ | Fact | What it is |
631
+ | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
632
+ | `item.labels` | The item's labels. |
633
+ | `item.title` | The card's title. |
634
+ | `item.author` | Who opened the item. |
635
+ | `item.key` | The provider's key: `acme/app#42` (GitHub), `acme/app!7` (GitLab merge request), `ENG-12` (Linear), `OPS-3` (Jira), `INC-7` (incident.io). |
636
+ | `item.state` | The provider's state: `open`, `closed` or `merged` on GitHub and GitLab, the workflow state name (`In Progress`) on Linear and Jira. |
637
+ | `item.assignees` | Who the item is assigned to, as a list. |
638
+ | `item.pullRequest` | The number of the card's open pull or merge request, absent when it has none. |
639
+ | `author.trusted` | Whether the author is trusted (see below). |
640
+ | `source.kind` | `issue`, `pull_request`, … |
641
+ | `source.integration` | The integration that filed it: `github`, `gitlab`, `linear`, `jira`, `incidentio`, … |
642
+ | `source.provider` | The provider the work item comes from; the integration for every integration Factory ships. |
643
+ | `source.repository` | Where the item lives, compared case-insensitively. GitHub: `owner/repo` (`mastra-ai/mastra`, never the bare `mastra`). GitLab: the full project path, subgroups included (`acme/platform/api`). Linear: the team key (`ENG`). Jira: the project key (`PLAT`). Absent for incident.io items (test `source.provider equals incidentio` instead) and for manual cards, which have no `source.*` facts (test `source.kind not_exists`). |
624
644
 
625
645
  Strings compare case-insensitively, so `source.repository equals Acme/App` matches `acme/app`. A list fact (`item.labels`, `item.assignees`) is tested by its members: `item.assignees equals ada` matches when Ada is one of the assignees, and an empty list counts as missing, so `item.assignees exists` matches only assigned items. A fact the item doesn't have fails every operator except `not_exists`, `not_equals`, `not_contains` and `not_in`.
626
646
 
@@ -1240,30 +1260,31 @@ A repository maintainer with write or admin access can start a Factory review fr
1240
1260
 
1241
1261
  A person's own Factory session (a user session) gets tools to find, file and manage the Factory's work items through its agent. Factory scopes the tools from the stored session row, never from the thread's `factoryProjectId` tag: the session must belong to a Factory in the caller's organization, and a private session only works for its owner. With authentication disabled, the shared `local` tenant applies. Sessions doing work for someone else, either bound to a work item's run or started as a side session, only get `factory_message_origin`, so they can report back and answer messages.
1242
1262
 
1243
- | Tool | Input |
1244
- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
1245
- | `factory_list_work_items` | Optional `query` (title text or `#number`), `stage`, `board`, `role`, `active`, `requestedBy: 'me'`, `subscribed`, `limit` (default 25, max 50) |
1246
- | `factory_inspect_work_item` | `workItem` (id or `#number`) |
1247
- | `factory_list_attention` | Optional `limit` (max 50) |
1248
- | `factory_create_work_item` | `title`, `description`, optional `repository` (`owner/name`, one this Factory links) |
1249
- | `factory_update_work_item` | `workItem` plus any of `title`, `description`, `repository`, `parentWorkItem` (or `null` to detach) |
1250
- | `factory_subscribe_work_item` | `workItem` |
1251
- | `factory_unsubscribe_work_item` | `workItem` |
1252
- | `factory_transition_work_item` | `workItem`, `stage` |
1253
- | `factory_retry_decision` | `decisionId` |
1254
- | `factory_dismiss_decision` | `decisionId` |
1255
- | `factory_resolve_proposal` | `decisionId`, `action` (`approve` or `dismiss`) |
1256
- | `factory_start_session` | `prompt` (up to 8000 characters), optional `title`, optional `model`; for a work-item role, `workItem` and `role` |
1257
- | `factory_answer_approval` | `sessionId`, `toolCallId`, `decision` (approve or decline), optional `reason` |
1258
- | `factory_switch_session_model` | `sessionId`, `modelId` |
1259
- | `factory_signal_session` | `sessionId`, `message` (up to 4000 characters), optional `priority` (`low`, `medium`, `high`, `urgent`; default `medium`) |
1260
- | `factory_message_origin` | `message`, optional `inReplyTo` (the message's notification id), optional `status` (`progress`, `blocked`, `done`, `failed`) |
1263
+ | Tool | Input |
1264
+ | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1265
+ | `factory_list_work_items` | Optional `query` (title text or `#number`), `stage`, `board`, `role`, `active`, `requestedBy: 'me'`, `subscribed`, `limit` (default 25, max 50) |
1266
+ | `factory_inspect_work_item` | `workItem` (id or `#number`) |
1267
+ | `factory_list_attention` | Optional `limit` (max 50) |
1268
+ | `factory_list_audit_events` | Optional `actor` (`me`, a user id or `agent:<threadId>`), `includeAgentRuns`, `namespace`, `actions`, `workItem`, `since`, `until`, `cursor`, `limit` (max 50) |
1269
+ | `factory_create_work_item` | `title`, `description`, optional `repository` (`owner/name`, one this Factory links) |
1270
+ | `factory_update_work_item` | `workItem` plus any of `title`, `description`, `repository`, `parentWorkItem` (or `null` to detach) |
1271
+ | `factory_subscribe_work_item` | `workItem` |
1272
+ | `factory_unsubscribe_work_item` | `workItem` |
1273
+ | `factory_transition_work_item` | `workItem`, `stage` |
1274
+ | `factory_retry_decision` | `decisionId` |
1275
+ | `factory_dismiss_decision` | `decisionId` |
1276
+ | `factory_resolve_proposal` | `decisionId`, `action` (`approve` or `dismiss`) |
1277
+ | `factory_start_session` | `prompt` (up to 8000 characters), optional `title`, optional `model`; for a work-item role, `workItem` and `role` |
1278
+ | `factory_answer_approval` | `sessionId`, `toolCallId`, `decision` (approve or decline), optional `reason` |
1279
+ | `factory_switch_session_model` | `sessionId`, `modelId` |
1280
+ | `factory_signal_session` | `sessionId`, `message` (up to 4000 characters), optional `priority` (`low`, `medium`, `high`, `urgent`; default `medium`) |
1281
+ | `factory_message_origin` | `message`, optional `inReplyTo` (the message's notification id), optional `status` (`progress`, `blocked`, `done`, `failed`) |
1261
1282
 
1262
1283
  Read tools and `factory_message_origin` are available on every turn. The other tools only appear on turns a signed-in person started, so text arriving from a notification, webhook or channel can't drive them. The one exception is `factory_signal_session`: on those turns it can still message the side sessions this session started and the active sessions of work items it follows, so the session can answer the sessions it is waiting on. None of them asks for approval: they are allowed on the session when it's created, unless the person has set their own policy for the tool or for the `mcp` category.
1263
1284
 
1264
1285
  `factory_switch_session_model` changes the model of a side, work item or review session you own in the same Factory, without recreating it. It refuses a model this server can't run. A running session switches right away; a stopped one uses the model on its next run.
1265
1286
 
1266
- `factory_create_work_item` files the card as the caller where the project's [intake routes](#intake-routes) send it, or in the Work board's first phase when no route matches (a project without Work: its first board's), stores the description that its runs start from, and subscribes the session. Name the `repository` when the Factory links more than one: a run can't start on a card that doesn't say which. `factory_update_work_item` sets it afterwards, like choosing a repository on the card, and also edits the title, the description and the parent item. It can't pre-approve plans: a plan waits for a person unless the board's phase auto-approves it. Both refuse a repository the Factory doesn't link, and a card synced from an issue keeps the issue's repository. Stages, the board and role sessions aren't fields it edits; stages move with `factory_transition_work_item`. Subscriptions are stored per work item and session in the `factory_work_item_subscriptions` collection and are removed with the item, so any number of sessions can follow one item.
1287
+ `factory_create_work_item` files the card as the caller where the project's [intake routes](#intake-routes) send it, or in the Work board's first phase when no route matches (a project without Work: its first board's), stores the description that its runs start from, and subscribes the session. Name the `repository` when the Factory links more than one: a run can't start on a card that doesn't say which. `factory_update_work_item` sets it afterwards, like choosing a repository on the card, and also edits the title, the description and the parent item. It can't pre-approve plans: a plan waits for a person unless the board's phase auto-approves it. Both refuse a repository the Factory doesn't link, and a card synced from an issue keeps the issue's repository. Stages, the board and role sessions aren't fields it edits; stages move with `factory_transition_work_item`. A session that moves a card follows it from then on, so it hears from the run the move starts. Subscriptions are stored per work item and session in the `factory_work_item_subscriptions` collection and are removed with the item, so any number of sessions can follow one item.
1267
1288
 
1268
1289
  #### Messaging between sessions
1269
1290
 
@@ -1280,7 +1301,7 @@ How a message is delivered depends on its priority. `urgent` always delivers, ev
1280
1301
  - **Side session** (no `workItem`): a standalone session with no work item, for a one-off job. It uses the same repository as the session that started it. Factory stores that session on the new session's row (`origin_session_id`, `origin_thread_id`) and copies the parent's visibility. It runs on the model of the session that started it, or on `model` when one is passed. That model has to be one the session's credentials can run; an unknown or unrunnable model is refused before anything is created. When the parent has no model set, the side session keeps the Factory's default worker model.
1281
1302
  - **Work-item role** (`workItem` and `role`): starts a role the item's board seats, the same way **Start** does in the Factory UI. The card does not move and no autonomy is armed. The tool refuses when the role already has a session, naming it so the agent can message it instead, and refuses an item linked to several repositories. The caller is subscribed to the item, and the run is recorded as `factory.run.started` with the caller as the person who started it.
1282
1303
 
1283
- Both modes attribute the new session to the caller, so it runs with the caller's credentials (the caller's own keys under the `user` model scope, the organization's under `factory`). A work-item role keeps the Factory's default worker model. The first message runs with only the caller as its user, never the rest of the parent turn's context. The tool needs no approval but, like the other management tools, only appears on turns a signed-in person started.
1304
+ A side session belongs to the caller and runs with the caller's credentials. A work-item role belongs to the caller only in a Factory on the `user` model scope. Where card work runs on the organization's keys (`factory` and `hybrid`), the role's session belongs to the Factory itself, as every phase session there does, whoever started or moved the card: the person is recorded as the one who started it, and their session follows the card so it hears when that run waits on someone and can approve or decline from there. Without an organization model key the start is refused with a message saying to add one. A work-item role keeps the Factory's default worker model. The first message runs with only the session's owner as its user, never the rest of the parent turn's context. The tool needs no approval but, like the other management tools, only appears on turns a signed-in person started.
1284
1305
 
1285
1306
  #### Reports
1286
1307
 
@@ -1298,7 +1319,7 @@ Progress reports from one session replace each other while unread. `done`, `fail
1298
1319
 
1299
1320
  Every run of a work session or side session ends with exactly one final report, however the run started: the board, a person typing into the session, a wake from another session's message, or a run after a server restart. Each Factory session gets a listener when it is created. A session with an active run binding reports to everyone following its work item, including for the run that moved the item to a finished stage and so ended its own binding; a side session reports to the session that started it; a person's own session reports to nobody. When a run ends, Factory checks each recipient's thread for a final report the agent sent since the run started, and sends one itself to the recipients that lack it: `done` when the run completed, `failed` when it ended in error (quoting the error), and `blocked`, naming the tool, when the run stopped waiting for an answer or for someone to approve a tool call. A reply with a final `status` counts as the final report, and any reply counts for a completed run. A run that completes after the agent reported `blocked` is waiting for an answer, so it gets no `done`; a run someone stopped gets no report. A board run that fails before it ever runs (no session, a configuration the run can't succeed with) reports `failed` once no retry remains. These backstop reports carry a `backstop` attribute.
1300
1321
 
1301
- A run that holds a tool call for approval stays open, so the same listener tells those sessions right away: an urgent `approval` notification names the session, the tool, its arguments and the `toolCallId`, once per call. A session that follows the work item, or started the side session, can answer it with `factory_answer_approval`, as the person signed in to it; the answer is audited as `factory.run.approved` or `factory.run.dismissed`. Other people's private sessions can't be answered, and an approval whose run already ended can't be either: the tool says so, and the session can be messaged to try again.
1322
+ A run that holds a tool call for approval stays open, so the same listener tells those sessions right away: an urgent `approval` notification names the session, the tool, its arguments and the `toolCallId`, once per call. A session that follows the work item, or started the side session, can answer it with `factory_answer_approval`, as the person signed in to it; the answer is audited as `factory.run.approved` or `factory.run.dismissed`. A tool that pauses itself for a bare yes or no, such as `submit_plan`, ends the run instead: the `blocked` report then names the session and the `toolCallId` to approve or decline the same way, while a tool that needs a typed answer is answered in its session. Whoever answers, the run carries on as the session's owner. Other people's private sessions can't be answered, and an approval whose run already ended can't be either: the tool says so, and the session can be messaged to try again.
1302
1323
 
1303
1324
  When a followed work item changes stage, subscribers whose session is running get a `low` priority `stage` notice. A stage change never wakes an offline session; it sees the current stage in its state signal instead.
1304
1325
 
@@ -14,8 +14,8 @@ export interface BoardWritesDeps {
14
14
  storage: StoredBoardsStorage;
15
15
  /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */
16
16
  boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;
17
- /** Read to refuse edits that would strand cards. */
18
- workItems: Pick<WorkItemsStorage, 'listShared'>;
17
+ /** Read to refuse edits that would strand cards; the retired Review board's cards leave `review` through it. */
18
+ workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;
19
19
  }
20
20
  /** Who writes: stored as the board's author, and the audit event's actor. */
21
21
  export interface BoardWriter {
@@ -43,7 +43,7 @@ export declare class BoardWrites {
43
43
  constructor(deps: BoardWritesDeps);
44
44
  /**
45
45
  * Code boards can't be created over, and Work can't be deleted while its code handlers run by its
46
- * key; the retired Review board's key can't be used at all.
46
+ * key.
47
47
  */
48
48
  refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void;
49
49
  existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord>;
@@ -1 +1 @@
1
- {"version":3,"file":"board-writes.d.ts","sourceRoot":"","sources":["../../src/boards/board-writes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAG7B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAEzE,OAAO,KAAK,EACV,gBAAgB,EAChB,iBAAiB,EACjB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G,EAAE,MAAM,EACX,UAAU,EAAE,IAAI,CAAC,gBAAgB,EAAE,KAAK,CAAC,EACzC,EAAE,gBAAgB,EAAE,MAAM,EAAE,EAAE;QAAE,gBAAgB,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,WAAW,CAAA;KAAE,GAC9E,OAAO,CAAC;QAAE,GAAG,EAAE,iBAAiB,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAyBvD;IAED,mDAAmD;IAC7C,MAAM,CACV,KAAK,EAAE,gBAAgB,EACvB,GAAG,EAAE,MAAM,EACX,EAAE,gBAAgB,EAAE,MAAM,EAAE,EAAE;QAAE,gBAAgB,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,WAAW,CAAA;KAAE,GAC9E,OAAO,CAAC,IAAI,CAAC,CAgBf;IAED,mGAAmG;IAC7F,KAAK,CACT,KAAK,EAAE,gBAAgB,EACvB,GAAG,EAAE,MAAM,EACX,EAAE,gBAAgB,EAAE,MAAM,EAAE,EAAE;QAAE,gBAAgB,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,WAAW,CAAA;KAAE,GAC9E,OAAO,CAAC,iBAAiB,CAAC,CAsB5B;CA0DF"}
@@ -1,7 +1,8 @@
1
1
  import { findBoardSkillProblems } from "../skills/app-skills.js";
2
2
  import { StoredBoardError } from "../storage/domains/boards/base.js";
3
- import "../storage/domains/work-items/legacy-review.js";
3
+ import { ReviewBoardInUseError } from "../storage/domains/work-items/legacy-review.js";
4
4
  import { codeBoardOf } from "./define-board.js";
5
+ import { isUntouchedReviewSeed } from "./project-boards.js";
5
6
  import { boardRegistryOf } from "./registry.js";
6
7
  import { boardForWorkItem } from "./semantics.js";
7
8
  import { codeBehaviourConflicts, compileStoredBoard, sameBoardDefinition, storedBoardInputSchema } from "./stored-board.js";
@@ -35,20 +36,14 @@ async function stored(write) {
35
36
  error: error.code,
36
37
  message: error.message
37
38
  });
39
+ if (error instanceof ReviewBoardInUseError) throw new BoardWriteError(409, {
40
+ error: "board_in_use",
41
+ message: error.message,
42
+ cards: error.cards
43
+ });
38
44
  throw error;
39
45
  }
40
46
  }
41
- /**
42
- * The retired Review board's key is never written: a project still using it is served it from
43
- * code, and a board under its key elsewhere would take over the cards stored there.
44
- */
45
- function refuseReservedBoard(key) {
46
- if (key !== "review") return;
47
- throw new BoardWriteError(409, {
48
- error: "reserved_board",
49
- message: `Board "${key}" is reserved for the retired Review board.`
50
- });
51
- }
52
47
  var BoardWrites = class {
53
48
  deps;
54
49
  constructor(deps) {
@@ -56,10 +51,9 @@ var BoardWrites = class {
56
51
  }
57
52
  /**
58
53
  * Code boards can't be created over, and Work can't be deleted while its code handlers run by its
59
- * key; the retired Review board's key can't be used at all.
54
+ * key.
60
55
  */
61
56
  refuseCodeBoard(key, action) {
62
- refuseReservedBoard(key);
63
57
  const { boards } = this.deps;
64
58
  const code = boards.codeRegistry.get(key);
65
59
  if (!code) return;
@@ -90,7 +84,6 @@ var BoardWrites = class {
90
84
  error: "invalid_board",
91
85
  message: issueMessage(parsed.error.issues)
92
86
  });
93
- refuseReservedBoard(parsed.data.key);
94
87
  const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);
95
88
  if (code) {
96
89
  const conflicts = codeBehaviourConflicts(parsed.data, code);
@@ -114,7 +107,7 @@ var BoardWrites = class {
114
107
  if (typeof key === "string") this.refuseCodeBoard(key, "create");
115
108
  const board = this.validate(input);
116
109
  await this.deps.boards.describe(scope);
117
- const row = await stored(() => this.deps.storage.create(scope, board, writer.id));
110
+ const row = await stored(() => this.deps.storage.create(scope, board, writer.id, this.#takeReviewKey(scope, board.key, null), board.key === "review" ? isUntouchedReviewSeed : void 0));
118
111
  this.deps.boards.invalidate(scope);
119
112
  await this.#audit(scope, writer, "created", board);
120
113
  return row;
@@ -126,14 +119,13 @@ var BoardWrites = class {
126
119
  * with another one rereads and tries again.
127
120
  */
128
121
  async upsert(scope, board, writer) {
129
- refuseReservedBoard(board.key);
130
122
  const { storage, boards } = this.deps;
131
123
  await boards.describe(scope);
132
124
  for (let attempt = 1;; attempt++) {
133
125
  const row = await storage.get(scope, board.key);
134
126
  try {
135
127
  if (!row) {
136
- if (!await storage.insertIfMissing(scope, board, writer.id)) throw new BoardWriteError(409, {
128
+ if (!await stored(() => storage.insertIfMissing(scope, board, writer.id, this.#takeReviewKey(scope, board.key, null)))) throw new BoardWriteError(409, {
137
129
  error: "revision_mismatch",
138
130
  message: `Board "${board.key}" was stored by another write; try again.`
139
131
  });
@@ -169,11 +161,13 @@ var BoardWrites = class {
169
161
  row,
170
162
  written: false
171
163
  };
172
- await this.#checkPhasesFree(scope, row, input.phases);
164
+ const takeKey = this.#takeReviewKey(scope, key, row);
165
+ if (!takeKey) await this.#checkPhasesFree(scope, row, input.phases);
173
166
  const { key: _key, ...replacement } = input;
174
167
  const replaced = await stored(() => storage.replace(scope, key, replacement, {
175
168
  expectedRevision,
176
- actor: writer.id
169
+ actor: writer.id,
170
+ before: takeKey
177
171
  }));
178
172
  boards.invalidate(scope);
179
173
  await this.#audit(scope, writer, "updated", input);
@@ -221,6 +215,16 @@ var BoardWrites = class {
221
215
  await this.#audit(scope, writer, "reset", row);
222
216
  return reset;
223
217
  }
218
+ /**
219
+ * What a write does first, in its transaction, when it gives the project a board of its own
220
+ * under `review` (none is stored, or only the seed an earlier release left): the cards the
221
+ * retired Review board left stored there get their Work placement, so the new board starts
222
+ * empty. Refused while one of them is still open.
223
+ */
224
+ #takeReviewKey(scope, key, row) {
225
+ if (key !== "review" || row && !isUntouchedReviewSeed(row)) return void 0;
226
+ return (ops) => this.deps.workItems.releaseReviewCards(ops, scope, { open: "refuse" });
227
+ }
224
228
  /** The cards on a board, and how many sit in each phase. */
225
229
  async #occupancy(scope, key) {
226
230
  const phases = /* @__PURE__ */ new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"board-writes.js","names":[],"sources":["../../src/boards/board-writes.ts"],"sourcesContent":["/**\n * Writes to a project's stored boards, shared by the boards API and `MastraFactory#upsertBoard()`.\n *\n * Every write is checked against the rules `defineBoard()` enforces, the skills its runners name,\n * the code behaviour of a code board's copy, and the cards sitting on the board. It then\n * invalidates the project's board cache and records an audit event.\n */\n\nimport type { z } from 'zod';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD } from '../storage/domains/work-items/legacy-review.js';\nimport { codeBoardOf } from './define-board.js';\nimport type { ProjectBoardCache } from './project-boards.js';\nimport { boardRegistryOf } from './registry.js';\nimport { boardForWorkItem } from './semantics.js';\nimport {\n codeBehaviourConflicts,\n compileStoredBoard,\n sameBoardDefinition,\n storedBoardInputSchema,\n} from './stored-board.js';\nimport { workBoard } from './work.js';\n\nexport interface BoardWritesDeps {\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n /** Read to refuse edits that would strand cards. */\n workItems: Pick<WorkItemsStorage, 'listShared'>;\n}\n\n/** Who writes: stored as the board's author, and the audit event's actor. */\nexport interface BoardWriter {\n id: string;\n audit(input: EmitAuditInput): Promise<void>;\n}\n\n/** A refused board write. `status` and `body` are what the boards API answers with. */\nexport class BoardWriteError extends Error {\n override name = 'BoardWriteError';\n constructor(\n readonly status: 404 | 409 | 422,\n readonly body: { error: string; message?: string } & Record<string, unknown>,\n ) {\n super(body.message ?? body.error);\n }\n\n get code(): string {\n return this.body.error;\n }\n}\n\nexport function issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\nconst UPSERT_ATTEMPTS = 3;\n\n/** Storage refusals (a stale revision, a missing or existing board) as board write errors. */\nasync function stored<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (error instanceof StoredBoardError) {\n throw new BoardWriteError(error.code === 'board_not_found' ? 404 : 409, {\n error: error.code,\n message: error.message,\n });\n }\n throw error;\n }\n}\n\n/**\n * The retired Review board's key is never written: a project still using it is served it from\n * code, and a board under its key elsewhere would take over the cards stored there.\n */\nfunction refuseReservedBoard(key: string): void {\n if (key !== LEGACY_REVIEW_BOARD) return;\n throw new BoardWriteError(409, {\n error: 'reserved_board',\n message: `Board \"${key}\" is reserved for the retired Review board.`,\n });\n}\n\nexport class BoardWrites {\n constructor(private readonly deps: BoardWritesDeps) {}\n\n /**\n * Code boards can't be created over, and Work can't be deleted while its code handlers run by its\n * key; the retired Review board's key can't be used at all.\n */\n refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void {\n refuseReservedBoard(key);\n const { boards } = this.deps;\n const code = boards.codeRegistry.get(key);\n if (!code) return;\n const stored = boards.seedFor(key) !== undefined;\n if (action === 'edit' && stored) return;\n if (action === 'delete' && stored && codeBoardOf(code) !== workBoard) return;\n throw new BoardWriteError(409, {\n error: 'code_board',\n message:\n action === 'delete' && stored\n ? `Board \"${key}\" is defined in code and can't be deleted; reset it to its default instead.`\n : `Board \"${key}\" is defined in code and can't be ${action === 'create' ? 'created over' : 'changed'} here.`,\n });\n }\n\n async existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord> {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new BoardWriteError(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /**\n * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code\n * board's copy is also checked against the code behaviour of its board and phase keys.\n */\n validate(input: unknown): StoredBoardInput {\n const { boards } = this.deps;\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new BoardWriteError(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n refuseReservedBoard(parsed.data.key);\n const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);\n if (code) {\n const conflicts = codeBehaviourConflicts(parsed.data, code);\n if (conflicts.length > 0) {\n throw new BoardWriteError(422, { error: 'code_behaviour', message: conflicts.join(' '), conflicts });\n }\n }\n const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);\n const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills);\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** Creates a board under a key no code board uses. */\n async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord> {\n const key = (input as { key?: unknown } | null)?.key;\n if (typeof key === 'string') this.refuseCodeBoard(key, 'create');\n const board = this.validate(input);\n // Factory stores its boards only into a project that has none, so they go in first.\n await this.deps.boards.describe(scope);\n const row = await stored(() => this.deps.storage.create(scope, board, writer.id));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return row;\n }\n\n /**\n * Stores a validated board in a project, after its first load stored Factory's boards: creates\n * it when the project has none under its key, and otherwise replaces the project's board, edited\n * or not, at its current revision, with the same checks as an edit. A write that loses a race\n * with another one rereads and tries again.\n */\n async upsert(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n writer: BoardWriter,\n ): Promise<'inserted' | 'updated' | 'unchanged'> {\n refuseReservedBoard(board.key);\n const { storage, boards } = this.deps;\n await boards.describe(scope);\n for (let attempt = 1; ; attempt++) {\n const row = await storage.get(scope, board.key);\n try {\n if (!row) {\n if (!(await storage.insertIfMissing(scope, board, writer.id))) {\n throw new BoardWriteError(409, {\n error: 'revision_mismatch',\n message: `Board \"${board.key}\" was stored by another write; try again.`,\n });\n }\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return 'inserted';\n }\n const { key, ...definition } = board;\n const { written } = await this.replace(scope, key, definition, { expectedRevision: row.revision, writer });\n return written ? 'updated' : 'unchanged';\n } catch (error) {\n const lost =\n error instanceof BoardWriteError && (error.code === 'revision_mismatch' || error.code === 'board_not_found');\n if (!lost || attempt >= UPSERT_ATTEMPTS) throw error;\n }\n }\n }\n\n /**\n * Replaces a board's definition at `expectedRevision`. Saving it unchanged writes nothing;\n * `written` says whether anything was stored.\n */\n async replace(\n scope: StoredBoardScope,\n key: string,\n definition: Omit<StoredBoardInput, 'key'>,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<{ row: StoredBoardRecord; written: boolean }> {\n const { storage, boards } = this.deps;\n this.refuseCodeBoard(key, 'edit');\n const seed = boards.seedFor(key);\n // The project's first load stores Factory's boards.\n if (seed) await boards.describe(scope);\n const row = await this.existing(scope, key);\n const input = this.validate({ key, ...definition });\n if (row.revision === expectedRevision && sameBoardDefinition(row, input)) {\n return { row, written: false };\n }\n await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n const replaced = await stored(() =>\n storage.replace(scope, key, replacement, { expectedRevision, actor: writer.id }),\n );\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'updated', input);\n return { row: replaced, written: true };\n }\n\n /** Deletes a stored board that no card sits on. */\n async remove(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<void> {\n this.refuseCodeBoard(key, 'delete');\n // The project's first load stores Factory's boards.\n if (this.deps.boards.seedFor(key)) await this.deps.boards.describe(scope);\n const row = await this.existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new BoardWriteError(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n await stored(() => this.deps.storage.delete(scope, key, { expectedRevision }));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'deleted', row);\n }\n\n /** Rewrites a board Factory stores to Factory's current definition of it, at the next revision. */\n async reset(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<StoredBoardRecord> {\n const { storage, boards } = this.deps;\n const seed = boards.seedFor(key);\n if (!seed) {\n this.refuseCodeBoard(key, 'edit');\n await this.existing(scope, key);\n throw new BoardWriteError(409, {\n error: 'not_code_board',\n message: `Board \"${key}\" was created in this project and has no default to reset to.`,\n });\n }\n await boards.describe(scope);\n const row = await this.existing(scope, key);\n // A board the app upserts for every project resets to the app's. Factory's Work resets to the\n // Work the project was stored with: today's for a project Factory created with it, Work with\n // Triage for every other.\n const definition = boards.seedFor(key, row) ?? seed;\n await this.#checkPhasesFree(scope, row, definition.phases);\n const reset = await stored(() => storage.resetTo(scope, key, definition, { expectedRevision, actor: writer.id }));\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'reset', row);\n return reset;\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: StoredBoardScope, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.listShared(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(\n scope: StoredBoardScope,\n row: StoredBoardRecord,\n next: readonly StoredPhaseInput[],\n ): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new BoardWriteError(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #audit(\n scope: StoredBoardScope,\n writer: BoardWriter,\n action: 'created' | 'updated' | 'deleted' | 'reset',\n board: { key: string; name: string },\n ): Promise<void> {\n await writer.audit({\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n });\n }\n}\n"],"mappings":";;;;;;;;;;AAiDA,IAAa,kBAAb,cAAqC,MAAM;CAG9B;CACA;CAHX,OAAgB;CAChB,YACE,QACA,MACA;EACA,MAAM,KAAK,WAAW,KAAK,KAAK;EAHvB,KAAA,SAAA;EACA,KAAA,OAAA;CAGX;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK,KAAK;CACnB;AACF;AAEA,SAAgB,aAAa,QAA6C;CACxE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,IAAI,MAAM,YAAY,MAAM,OAAQ,CAAC,CACnG,KAAK,IAAI;AACd;AAEA,MAAM,gBAAgB;AACtB,MAAM,kBAAkB;;AAGxB,eAAe,OAAU,OAAqC;CAC5D,IAAI;EACF,OAAO,MAAM,MAAM;CACrB,SAAS,OAAO;EACd,IAAI,iBAAiB,kBACnB,MAAM,IAAI,gBAAgB,MAAM,SAAS,oBAAoB,MAAM,KAAK;GACtE,OAAO,MAAM;GACb,SAAS,MAAM;EACjB,CAAC;EAEH,MAAM;CACR;AACF;;;;;AAMA,SAAS,oBAAoB,KAAmB;CAC9C,IAAI,QAAA,UAA6B;CACjC,MAAM,IAAI,gBAAgB,KAAK;EAC7B,OAAO;EACP,SAAS,UAAU,IAAI;CACzB,CAAC;AAC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,KAAK,MAAM,SAAS,IAAI,IAAI,KAAK,MAAM,GAAG,OAAO,IAAI,QAAQ,OAAO,IAAI,KAAK,KAAK,KAAK,CAAC;EAC1F;EACA,OAAO;GAAE;GAAO;EAAO;CACzB;;CAGA,MAAM,iBACJ,OACA,KACA,MACe;EACf,MAAM,QAAQ,IAAI,IAAI,KAAK,KAAI,UAAS,CAAC,MAAM,KAAK,MAAM,IAAI,CAAC,CAAC;EAChE,MAAM,UAAU,IAAI,OAAO,QAAO,UAAS,MAAM,IAAI,MAAM,GAAG,MAAM,MAAM,IAAI,CAAC,CAAC,KAAI,UAAS,MAAM,GAAG;EACtG,IAAI,QAAQ,WAAW,GAAG;EAC1B,MAAM,aAAa,MAAM,KAAK,WAAW,OAAO,IAAI,GAAG,EAAA,CAAG;EAC1D,MAAM,QAAQ,OAAO,YAAY,QAAQ,SAAQ,QAAQ,UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,KAAK,UAAU,IAAI,GAAG,CAAE,CAAC,IAAI,CAAC,CAAE,CAAC;EACjH,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG;EACrC,MAAM,IAAI,gBAAgB,KAAK;GAC7B,OAAO;GACP,SAAS,gBAAgB,OAAO,QAAQ,KAAK,CAAC,CAC3C,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC,CAC5C,KAAK,IAAI,EAAE;GACd,QAAQ;EACV,CAAC;CACH;CAEA,MAAM,OACJ,OACA,QACA,QACA,OACe;EACf,MAAM,OAAO,MAAM;GACjB,QAAQ,iBAAiB;GACzB,kBAAkB,MAAM;GACxB,SAAS,CAAC;IAAE,MAAM;IAAS,IAAI,MAAM;IAAK,MAAM,MAAM;GAAK,CAAC;EAC9D,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"board-writes.js","names":[],"sources":["../../src/boards/board-writes.ts"],"sourcesContent":["/**\n * Writes to a project's stored boards, shared by the boards API and `MastraFactory#upsertBoard()`.\n *\n * Every write is checked against the rules `defineBoard()` enforces, the skills its runners name,\n * the code behaviour of a code board's copy, and the cards sitting on the board. It then\n * invalidates the project's board cache and records an audit event.\n */\n\nimport type { z } from 'zod';\n\nimport { findBoardSkillProblems } from '../skills/app-skills.js';\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { StoredBoardError } from '../storage/domains/boards/base.js';\nimport type {\n BoardWriteStep,\n StoredBoardInput,\n StoredBoardRecord,\n StoredBoardScope,\n StoredBoardsStorage,\n StoredPhaseInput,\n} from '../storage/domains/boards/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { LEGACY_REVIEW_BOARD, ReviewBoardInUseError } from '../storage/domains/work-items/legacy-review.js';\nimport { codeBoardOf } from './define-board.js';\nimport { isUntouchedReviewSeed } from './project-boards.js';\nimport type { ProjectBoardCache } from './project-boards.js';\nimport { boardRegistryOf } from './registry.js';\nimport { boardForWorkItem } from './semantics.js';\nimport {\n codeBehaviourConflicts,\n compileStoredBoard,\n sameBoardDefinition,\n storedBoardInputSchema,\n} from './stored-board.js';\nimport { workBoard } from './work.js';\n\nexport interface BoardWritesDeps {\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n /** Read to refuse edits that would strand cards; the retired Review board's cards leave `review` through it. */\n workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;\n}\n\n/** Who writes: stored as the board's author, and the audit event's actor. */\nexport interface BoardWriter {\n id: string;\n audit(input: EmitAuditInput): Promise<void>;\n}\n\n/** A refused board write. `status` and `body` are what the boards API answers with. */\nexport class BoardWriteError extends Error {\n override name = 'BoardWriteError';\n constructor(\n readonly status: 404 | 409 | 422,\n readonly body: { error: string; message?: string } & Record<string, unknown>,\n ) {\n super(body.message ?? body.error);\n }\n\n get code(): string {\n return this.body.error;\n }\n}\n\nexport function issueMessage(issues: readonly z.core.$ZodIssue[]): string {\n return issues\n .map(issue => (issue.path.length > 0 ? `${issue.path.join('.')}: ${issue.message}` : issue.message))\n .join('; ');\n}\n\nconst UNKNOWN_SKILL = 'but no such skill exists';\nconst UPSERT_ATTEMPTS = 3;\n\n/** Storage refusals (a stale revision, a missing or existing board) as board write errors. */\nasync function stored<T>(write: () => Promise<T>): Promise<T> {\n try {\n return await write();\n } catch (error) {\n if (error instanceof StoredBoardError) {\n throw new BoardWriteError(error.code === 'board_not_found' ? 404 : 409, {\n error: error.code,\n message: error.message,\n });\n }\n if (error instanceof ReviewBoardInUseError) {\n throw new BoardWriteError(409, { error: 'board_in_use', message: error.message, cards: error.cards });\n }\n throw error;\n }\n}\n\nexport class BoardWrites {\n constructor(private readonly deps: BoardWritesDeps) {}\n\n /**\n * Code boards can't be created over, and Work can't be deleted while its code handlers run by its\n * key.\n */\n refuseCodeBoard(key: string, action: 'create' | 'edit' | 'delete'): void {\n const { boards } = this.deps;\n const code = boards.codeRegistry.get(key);\n if (!code) return;\n const stored = boards.seedFor(key) !== undefined;\n if (action === 'edit' && stored) return;\n if (action === 'delete' && stored && codeBoardOf(code) !== workBoard) return;\n throw new BoardWriteError(409, {\n error: 'code_board',\n message:\n action === 'delete' && stored\n ? `Board \"${key}\" is defined in code and can't be deleted; reset it to its default instead.`\n : `Board \"${key}\" is defined in code and can't be ${action === 'create' ? 'created over' : 'changed'} here.`,\n });\n }\n\n async existing(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord> {\n const row = await this.deps.storage.get(scope, key);\n if (!row) throw new BoardWriteError(404, { error: 'board_not_found', message: `Board \"${key}\" does not exist.` });\n return row;\n }\n\n /**\n * Validates a definition the way `defineBoard()` does, plus the skills its runners name. A code\n * board's copy is also checked against the code behaviour of its board and phase keys.\n */\n validate(input: unknown): StoredBoardInput {\n const { boards } = this.deps;\n const parsed = storedBoardInputSchema.safeParse(input);\n if (!parsed.success) {\n throw new BoardWriteError(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const code = boards.seedFor(parsed.data.key) && boards.codeRegistry.get(parsed.data.key);\n if (code) {\n const conflicts = codeBehaviourConflicts(parsed.data, code);\n if (conflicts.length > 0) {\n throw new BoardWriteError(422, { error: 'code_behaviour', message: conflicts.join(' '), conflicts });\n }\n }\n const board = code ? compileStoredBoard(parsed.data, code) : compileStoredBoard(parsed.data);\n const problems = findBoardSkillProblems(boardRegistryOf([board]), boards.codeSkills);\n const unknown = problems.filter(problem => problem.includes(UNKNOWN_SKILL));\n if (unknown.length > 0) throw new BoardWriteError(422, { error: 'unknown_skill', message: unknown.join(' ') });\n return parsed.data;\n }\n\n /** Creates a board under a key no code board uses. */\n async create(scope: StoredBoardScope, input: unknown, writer: BoardWriter): Promise<StoredBoardRecord> {\n const key = (input as { key?: unknown } | null)?.key;\n if (typeof key === 'string') this.refuseCodeBoard(key, 'create');\n const board = this.validate(input);\n // Factory stores its boards only into a project that has none, so they go in first.\n await this.deps.boards.describe(scope);\n const row = await stored(() =>\n this.deps.storage.create(\n scope,\n board,\n writer.id,\n this.#takeReviewKey(scope, board.key, null),\n // The row an earlier release seeded for the retired Review board is nobody's board.\n board.key === LEGACY_REVIEW_BOARD ? isUntouchedReviewSeed : undefined,\n ),\n );\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return row;\n }\n\n /**\n * Stores a validated board in a project, after its first load stored Factory's boards: creates\n * it when the project has none under its key, and otherwise replaces the project's board, edited\n * or not, at its current revision, with the same checks as an edit. A write that loses a race\n * with another one rereads and tries again.\n */\n async upsert(\n scope: StoredBoardScope,\n board: StoredBoardInput,\n writer: BoardWriter,\n ): Promise<'inserted' | 'updated' | 'unchanged'> {\n const { storage, boards } = this.deps;\n await boards.describe(scope);\n for (let attempt = 1; ; attempt++) {\n const row = await storage.get(scope, board.key);\n try {\n if (!row) {\n const inserted = await stored(() =>\n storage.insertIfMissing(scope, board, writer.id, this.#takeReviewKey(scope, board.key, null)),\n );\n if (!inserted) {\n throw new BoardWriteError(409, {\n error: 'revision_mismatch',\n message: `Board \"${board.key}\" was stored by another write; try again.`,\n });\n }\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'created', board);\n return 'inserted';\n }\n const { key, ...definition } = board;\n const { written } = await this.replace(scope, key, definition, { expectedRevision: row.revision, writer });\n return written ? 'updated' : 'unchanged';\n } catch (error) {\n const lost =\n error instanceof BoardWriteError && (error.code === 'revision_mismatch' || error.code === 'board_not_found');\n if (!lost || attempt >= UPSERT_ATTEMPTS) throw error;\n }\n }\n }\n\n /**\n * Replaces a board's definition at `expectedRevision`. Saving it unchanged writes nothing;\n * `written` says whether anything was stored.\n */\n async replace(\n scope: StoredBoardScope,\n key: string,\n definition: Omit<StoredBoardInput, 'key'>,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<{ row: StoredBoardRecord; written: boolean }> {\n const { storage, boards } = this.deps;\n this.refuseCodeBoard(key, 'edit');\n const seed = boards.seedFor(key);\n // The project's first load stores Factory's boards.\n if (seed) await boards.describe(scope);\n const row = await this.existing(scope, key);\n const input = this.validate({ key, ...definition });\n if (row.revision === expectedRevision && sameBoardDefinition(row, input)) {\n return { row, written: false };\n }\n const takeKey = this.#takeReviewKey(scope, key, row);\n // No card is on a seed nobody made into a board: the ones stored there are the retired board's.\n if (!takeKey) await this.#checkPhasesFree(scope, row, input.phases);\n const { key: _key, ...replacement } = input;\n const replaced = await stored(() =>\n storage.replace(scope, key, replacement, {\n expectedRevision,\n actor: writer.id,\n before: takeKey,\n }),\n );\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'updated', input);\n return { row: replaced, written: true };\n }\n\n /** Deletes a stored board that no card sits on. */\n async remove(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<void> {\n this.refuseCodeBoard(key, 'delete');\n // The project's first load stores Factory's boards.\n if (this.deps.boards.seedFor(key)) await this.deps.boards.describe(scope);\n const row = await this.existing(scope, key);\n const { cards } = await this.#occupancy(scope, key);\n if (cards > 0) {\n throw new BoardWriteError(409, {\n error: 'board_in_use',\n message: `Board \"${key}\" still has cards; move or delete them first.`,\n cards,\n });\n }\n await stored(() => this.deps.storage.delete(scope, key, { expectedRevision }));\n this.deps.boards.invalidate(scope);\n await this.#audit(scope, writer, 'deleted', row);\n }\n\n /** Rewrites a board Factory stores to Factory's current definition of it, at the next revision. */\n async reset(\n scope: StoredBoardScope,\n key: string,\n { expectedRevision, writer }: { expectedRevision: number; writer: BoardWriter },\n ): Promise<StoredBoardRecord> {\n const { storage, boards } = this.deps;\n const seed = boards.seedFor(key);\n if (!seed) {\n this.refuseCodeBoard(key, 'edit');\n await this.existing(scope, key);\n throw new BoardWriteError(409, {\n error: 'not_code_board',\n message: `Board \"${key}\" was created in this project and has no default to reset to.`,\n });\n }\n await boards.describe(scope);\n const row = await this.existing(scope, key);\n // A board the app upserts for every project resets to the app's. Factory's Work resets to the\n // Work the project was stored with: today's for a project Factory created with it, Work with\n // Triage for every other.\n const definition = boards.seedFor(key, row) ?? seed;\n await this.#checkPhasesFree(scope, row, definition.phases);\n const reset = await stored(() => storage.resetTo(scope, key, definition, { expectedRevision, actor: writer.id }));\n boards.invalidate(scope);\n await this.#audit(scope, writer, 'reset', row);\n return reset;\n }\n\n /**\n * What a write does first, in its transaction, when it gives the project a board of its own\n * under `review` (none is stored, or only the seed an earlier release left): the cards the\n * retired Review board left stored there get their Work placement, so the new board starts\n * empty. Refused while one of them is still open.\n */\n #takeReviewKey(scope: StoredBoardScope, key: string, row: StoredBoardRecord | null): BoardWriteStep | undefined {\n if (key !== LEGACY_REVIEW_BOARD || (row && !isUntouchedReviewSeed(row))) return undefined;\n return ops => this.deps.workItems.releaseReviewCards(ops, scope, { open: 'refuse' });\n }\n\n /** The cards on a board, and how many sit in each phase. */\n async #occupancy(scope: StoredBoardScope, key: string): Promise<{ cards: number; phases: Map<string, number> }> {\n const phases = new Map<string, number>();\n let cards = 0;\n for (const item of await this.deps.workItems.listShared(scope)) {\n if (boardForWorkItem(item) !== key) continue;\n cards++;\n for (const stage of new Set(item.stages)) phases.set(stage, (phases.get(stage) ?? 0) + 1);\n }\n return { cards, phases };\n }\n\n /** Refuses a change that removes, or changes the kind of, a phase cards sit in. */\n async #checkPhasesFree(\n scope: StoredBoardScope,\n row: StoredBoardRecord,\n next: readonly StoredPhaseInput[],\n ): Promise<void> {\n const kinds = new Map(next.map(phase => [phase.key, phase.kind]));\n const changed = row.phases.filter(phase => kinds.get(phase.key) !== phase.kind).map(phase => phase.key);\n if (changed.length === 0) return;\n const occupancy = (await this.#occupancy(scope, row.key)).phases;\n const inUse = Object.fromEntries(changed.flatMap(key => (occupancy.get(key) ? [[key, occupancy.get(key)!]] : [])));\n if (Object.keys(inUse).length === 0) return;\n throw new BoardWriteError(409, {\n error: 'phase_in_use',\n message: `Cards sit in ${Object.entries(inUse)\n .map(([key, count]) => `\"${key}\" (${count})`)\n .join(', ')}; move them before removing those phases or changing their kind.`,\n phases: inUse,\n });\n }\n\n async #audit(\n scope: StoredBoardScope,\n writer: BoardWriter,\n action: 'created' | 'updated' | 'deleted' | 'reset',\n board: { key: string; name: string },\n ): Promise<void> {\n await writer.audit({\n action: `factory.board.${action}`,\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'board', id: board.key, name: board.name }],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;AAmDA,IAAa,kBAAb,cAAqC,MAAM;CAG9B;CACA;CAHX,OAAgB;CAChB,YACE,QACA,MACA;EACA,MAAM,KAAK,WAAW,KAAK,KAAK;EAHvB,KAAA,SAAA;EACA,KAAA,OAAA;CAGX;CAEA,IAAI,OAAe;EACjB,OAAO,KAAK,KAAK;CACnB;AACF;AAEA,SAAgB,aAAa,QAA6C;CACxE,OAAO,OACJ,KAAI,UAAU,MAAM,KAAK,SAAS,IAAI,GAAG,MAAM,KAAK,KAAK,GAAG,EAAE,IAAI,MAAM,YAAY,MA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AAA,CAAG;EAC1D,MAAM,QAAQ,OAAO,YAAY,QAAQ,SAAQ,QAAQ,UAAU,IAAI,GAAG,IAAI,CAAC,CAAC,KAAK,UAAU,IAAI,GAAG,CAAE,CAAC,IAAI,CAAC,CAAE,CAAC;EACjH,IAAI,OAAO,KAAK,KAAK,CAAC,CAAC,WAAW,GAAG;EACrC,MAAM,IAAI,gBAAgB,KAAK;GAC7B,OAAO;GACP,SAAS,gBAAgB,OAAO,QAAQ,KAAK,CAAC,CAC3C,KAAK,CAAC,KAAK,WAAW,IAAI,IAAI,KAAK,MAAM,EAAE,CAAC,CAC5C,KAAK,IAAI,EAAE;GACd,QAAQ;EACV,CAAC;CACH;CAEA,MAAM,OACJ,OACA,QACA,QACA,OACe;EACf,MAAM,OAAO,MAAM;GACjB,QAAQ,iBAAiB;GACzB,kBAAkB,MAAM;GACxB,SAAS,CAAC;IAAE,MAAM;IAAS,IAAI,MAAM;IAAK,MAAM,MAAM;GAAK,CAAC;EAC9D,CAAC;CACH;AACF"}
@@ -3,7 +3,22 @@ import type { FactoryStorageOps } from '@mastra/core/storage';
3
3
  import type { StoredBoardInput, StoredBoardRecord, StoredBoardScope, StoredBoardsStorage } from '../storage/domains/boards/base.js';
4
4
  import type { RetiredAutomationSettings } from '../storage/domains/projects/base.js';
5
5
  import type { WorkItemsStorage } from '../storage/domains/work-items/base.js';
6
+ import type { ReviewBoardInUse } from '../storage/domains/work-items/legacy-review.js';
6
7
  import type { BoardRegistry } from './registry.js';
8
+ /**
9
+ * Whether `row` is the Review board as Factory seeded it: written once by Factory, never
10
+ * revised, and shaped like the seed. The actor alone is not proof, as any caller can pass it.
11
+ */
12
+ export declare function isUntouchedReviewSeed(row: StoredBoardRecord): boolean;
13
+ /**
14
+ * Whether a project has a board of its own under `review`: a stored row other than the seed an
15
+ * earlier release left behind. Cards stored on it are its own; anywhere else they are the retired
16
+ * Review board's. An app that defines the board owns it in a project from when its row is stored
17
+ * there. Without stored boards (`stored: false`) the app's boards are served as they are.
18
+ */
19
+ export declare function ownReviewBoard(codeRegistry: BoardRegistry, { stored }?: {
20
+ stored?: boolean | undefined;
21
+ }): ReviewBoardInUse;
7
22
  /**
8
23
  * The creator Factory records on the Work board it stores in a project as the project is
9
24
  * created: that board is today's Work, and reset gives it back. Any other Work row Factory stored
@@ -66,6 +81,11 @@ export interface ProjectBoardCacheOptions {
66
81
  * a project is served Review alongside its boards; without this, no project is.
67
82
  */
68
83
  reviewBoardInUse?: (scope: StoredBoardScope) => Promise<boolean>;
84
+ /**
85
+ * Stores the Work placement of every card the retired Review board left on `review`, through
86
+ * `ops`. Run in the transaction that stores an app's board under that key in a project.
87
+ */
88
+ releaseReviewCards?: (ops: FactoryStorageOps, scope: StoredBoardScope) => Promise<void>;
69
89
  recheckMs?: number;
70
90
  now?: () => number;
71
91
  warn?: (message: string) => void;