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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (399) hide show
  1. package/README.md +244 -123
  2. package/dist/boards/board-events.d.ts +23 -3
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +44 -7
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts +1 -1
  7. package/dist/boards/board-writes.d.ts.map +1 -1
  8. package/dist/boards/board-writes.js +16 -1
  9. package/dist/boards/board-writes.js.map +1 -1
  10. package/dist/boards/card-facts.d.ts +1 -1
  11. package/dist/boards/card-facts.d.ts.map +1 -1
  12. package/dist/boards/card-facts.js +4 -0
  13. package/dist/boards/card-facts.js.map +1 -1
  14. package/dist/boards/default-board.d.ts +7 -0
  15. package/dist/boards/default-board.d.ts.map +1 -0
  16. package/dist/boards/default-board.js +10 -0
  17. package/dist/boards/default-board.js.map +1 -0
  18. package/dist/boards/define-board.d.ts +39 -17
  19. package/dist/boards/define-board.d.ts.map +1 -1
  20. package/dist/boards/define-board.js +64 -42
  21. package/dist/boards/define-board.js.map +1 -1
  22. package/dist/boards/index.d.ts +5 -8
  23. package/dist/boards/index.d.ts.map +1 -1
  24. package/dist/boards/index.js +5 -19
  25. package/dist/boards/intake-routing.d.ts +27 -5
  26. package/dist/boards/intake-routing.d.ts.map +1 -1
  27. package/dist/boards/intake-routing.js +69 -16
  28. package/dist/boards/intake-routing.js.map +1 -1
  29. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  30. package/dist/boards/legacy-plan-role.js +7 -2
  31. package/dist/boards/legacy-plan-role.js.map +1 -1
  32. package/dist/boards/phase-automation.d.ts +7 -0
  33. package/dist/boards/phase-automation.d.ts.map +1 -1
  34. package/dist/boards/phase-automation.js +16 -5
  35. package/dist/boards/phase-automation.js.map +1 -1
  36. package/dist/boards/phase-runner.d.ts +18 -10
  37. package/dist/boards/phase-runner.d.ts.map +1 -1
  38. package/dist/boards/phase-runner.js +39 -34
  39. package/dist/boards/phase-runner.js.map +1 -1
  40. package/dist/boards/project-boards.d.ts +9 -6
  41. package/dist/boards/project-boards.d.ts.map +1 -1
  42. package/dist/boards/project-boards.js +56 -18
  43. package/dist/boards/project-boards.js.map +1 -1
  44. package/dist/boards/registry.d.ts.map +1 -1
  45. package/dist/boards/registry.js +3 -1
  46. package/dist/boards/registry.js.map +1 -1
  47. package/dist/boards/relocate.d.ts +1 -1
  48. package/dist/boards/relocate.d.ts.map +1 -1
  49. package/dist/boards/relocate.js +3 -2
  50. package/dist/boards/relocate.js.map +1 -1
  51. package/dist/boards/review.d.ts +5 -2
  52. package/dist/boards/review.d.ts.map +1 -1
  53. package/dist/boards/review.js +12 -11
  54. package/dist/boards/review.js.map +1 -1
  55. package/dist/boards/semantics.d.ts +159 -20
  56. package/dist/boards/semantics.d.ts.map +1 -1
  57. package/dist/boards/semantics.js +256 -23
  58. package/dist/boards/semantics.js.map +1 -1
  59. package/dist/boards/stored-board.d.ts +32 -18
  60. package/dist/boards/stored-board.d.ts.map +1 -1
  61. package/dist/boards/stored-board.js +31 -97
  62. package/dist/boards/stored-board.js.map +1 -1
  63. package/dist/boards/work-migrations.d.ts +19 -0
  64. package/dist/boards/work-migrations.d.ts.map +1 -0
  65. package/dist/boards/work-migrations.js +257 -0
  66. package/dist/boards/work-migrations.js.map +1 -0
  67. package/dist/boards/work-routes.d.ts +53 -0
  68. package/dist/boards/work-routes.d.ts.map +1 -0
  69. package/dist/boards/work-routes.js +256 -0
  70. package/dist/boards/work-routes.js.map +1 -0
  71. package/dist/boards/work.d.ts +8 -19
  72. package/dist/boards/work.d.ts.map +1 -1
  73. package/dist/boards/work.js +38 -270
  74. package/dist/boards/work.js.map +1 -1
  75. package/dist/factory.d.ts +3 -3
  76. package/dist/factory.d.ts.map +1 -1
  77. package/dist/factory.js +58 -30
  78. package/dist/factory.js.map +1 -1
  79. package/dist/index.d.ts +2 -2
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +2 -3
  82. package/dist/integrations/base.d.ts +6 -2
  83. package/dist/integrations/base.d.ts.map +1 -1
  84. package/dist/integrations/closing-references.d.ts +15 -0
  85. package/dist/integrations/closing-references.d.ts.map +1 -0
  86. package/dist/integrations/closing-references.js +69 -0
  87. package/dist/integrations/closing-references.js.map +1 -0
  88. package/dist/integrations/github/default-rules.d.ts +15 -66
  89. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  90. package/dist/integrations/github/default-rules.js +129 -71
  91. package/dist/integrations/github/default-rules.js.map +1 -1
  92. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/github/issue-reconciler.js +3 -1
  94. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/github/pull-request-source.d.ts +8 -0
  96. package/dist/integrations/github/pull-request-source.d.ts.map +1 -0
  97. package/dist/integrations/github/pull-request-source.js +17 -0
  98. package/dist/integrations/github/pull-request-source.js.map +1 -0
  99. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -1
  100. package/dist/integrations/github/review-status-reporter.js +7 -3
  101. package/dist/integrations/github/review-status-reporter.js.map +1 -1
  102. package/dist/integrations/github/routes.js +1 -1
  103. package/dist/integrations/github/rules.d.ts +13 -2
  104. package/dist/integrations/github/rules.d.ts.map +1 -1
  105. package/dist/integrations/github/rules.js +202 -34
  106. package/dist/integrations/github/rules.js.map +1 -1
  107. package/dist/integrations/github/session-subscriptions.js +2 -2
  108. package/dist/integrations/github/session-subscriptions.js.map +1 -1
  109. package/dist/integrations/github/token-refresh.d.ts +2 -1
  110. package/dist/integrations/github/token-refresh.d.ts.map +1 -1
  111. package/dist/integrations/github/token-refresh.js.map +1 -1
  112. package/dist/integrations/gitlab/agent-tools.js +1 -1
  113. package/dist/integrations/gitlab/default-rules.d.ts +73 -31
  114. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  115. package/dist/integrations/gitlab/default-rules.js +106 -43
  116. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  117. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  118. package/dist/integrations/gitlab/issue-reconciler.js +2 -1
  119. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  120. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  121. package/dist/integrations/gitlab/merge-request-reconciler.js +11 -4
  122. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  123. package/dist/integrations/gitlab/rules.d.ts +6 -1
  124. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  125. package/dist/integrations/gitlab/rules.js +116 -23
  126. package/dist/integrations/gitlab/rules.js.map +1 -1
  127. package/dist/integrations/gitlab/session-subscriptions.js +1 -1
  128. package/dist/integrations/incidentio/agent-tools.js +1 -1
  129. package/dist/integrations/incidentio/default-rules.js +3 -3
  130. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  131. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  132. package/dist/integrations/incidentio/issue-reconciler.js +2 -1
  133. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  134. package/dist/integrations/incidentio/rules.d.ts +3 -1
  135. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  136. package/dist/integrations/incidentio/rules.js +14 -11
  137. package/dist/integrations/incidentio/rules.js.map +1 -1
  138. package/dist/integrations/jira/agent-tools.js +1 -1
  139. package/dist/integrations/jira/default-rules.js +3 -3
  140. package/dist/integrations/jira/default-rules.js.map +1 -1
  141. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  142. package/dist/integrations/jira/issue-reconciler.js +2 -1
  143. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  144. package/dist/integrations/jira/rules.d.ts +3 -1
  145. package/dist/integrations/jira/rules.d.ts.map +1 -1
  146. package/dist/integrations/jira/rules.js +14 -11
  147. package/dist/integrations/jira/rules.js.map +1 -1
  148. package/dist/integrations/linear/agent-tools.d.ts +9 -1
  149. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  150. package/dist/integrations/linear/agent-tools.js +80 -2
  151. package/dist/integrations/linear/agent-tools.js.map +1 -1
  152. package/dist/integrations/linear/default-rules.js +3 -3
  153. package/dist/integrations/linear/default-rules.js.map +1 -1
  154. package/dist/integrations/linear/integration.d.ts +4 -1
  155. package/dist/integrations/linear/integration.d.ts.map +1 -1
  156. package/dist/integrations/linear/integration.js +21 -1
  157. package/dist/integrations/linear/integration.js.map +1 -1
  158. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  159. package/dist/integrations/linear/issue-reconciler.js +2 -1
  160. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  161. package/dist/integrations/linear/routes.d.ts +2 -1
  162. package/dist/integrations/linear/routes.d.ts.map +1 -1
  163. package/dist/integrations/linear/routes.js +4 -3
  164. package/dist/integrations/linear/routes.js.map +1 -1
  165. package/dist/integrations/linear/rules.d.ts +3 -1
  166. package/dist/integrations/linear/rules.d.ts.map +1 -1
  167. package/dist/integrations/linear/rules.js +15 -12
  168. package/dist/integrations/linear/rules.js.map +1 -1
  169. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  170. package/dist/integrations/platform/github/integration.js +33 -21
  171. package/dist/integrations/platform/github/integration.js.map +1 -1
  172. package/dist/integrations/platform/jira/agent-tools.js +1 -1
  173. package/dist/integrations/platform/linear/integration.d.ts +1 -1
  174. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  175. package/dist/integrations/platform/linear/integration.js +6 -5
  176. package/dist/integrations/platform/linear/integration.js.map +1 -1
  177. package/dist/integrations/slack/chat-tools.js +1 -1
  178. package/dist/integrations/slack/reply-tool.js +1 -1
  179. package/dist/integrations/slack/share-file-tool.js +1 -1
  180. package/dist/integrations/slack/slack.d.ts +10 -4
  181. package/dist/integrations/slack/slack.d.ts.map +1 -1
  182. package/dist/integrations/slack/slack.js +19 -9
  183. package/dist/integrations/slack/slack.js.map +1 -1
  184. package/dist/links.d.ts.map +1 -1
  185. package/dist/links.js +3 -2
  186. package/dist/links.js.map +1 -1
  187. package/dist/mcp/routes.js +2 -2
  188. package/dist/routes/attention-parked.d.ts +1 -0
  189. package/dist/routes/attention-parked.d.ts.map +1 -1
  190. package/dist/routes/attention-parked.js +1 -1
  191. package/dist/routes/attention-parked.js.map +1 -1
  192. package/dist/routes/automation-runs.d.ts +4 -0
  193. package/dist/routes/automation-runs.d.ts.map +1 -1
  194. package/dist/routes/automation-runs.js +15 -0
  195. package/dist/routes/automation-runs.js.map +1 -1
  196. package/dist/routes/boards.d.ts +1 -1
  197. package/dist/routes/boards.d.ts.map +1 -1
  198. package/dist/routes/boards.js +1 -17
  199. package/dist/routes/boards.js.map +1 -1
  200. package/dist/routes/config.d.ts +4 -0
  201. package/dist/routes/config.d.ts.map +1 -1
  202. package/dist/routes/config.js +15 -0
  203. package/dist/routes/config.js.map +1 -1
  204. package/dist/routes/contracts.d.ts +125 -14
  205. package/dist/routes/contracts.d.ts.map +1 -1
  206. package/dist/routes/contracts.js +34 -15
  207. package/dist/routes/contracts.js.map +1 -1
  208. package/dist/routes/fs.d.ts +4 -0
  209. package/dist/routes/fs.d.ts.map +1 -1
  210. package/dist/routes/fs.js +8 -4
  211. package/dist/routes/fs.js.map +1 -1
  212. package/dist/routes/intake-routes.d.ts.map +1 -1
  213. package/dist/routes/intake-routes.js.map +1 -1
  214. package/dist/routes/intake.d.ts.map +1 -1
  215. package/dist/routes/intake.js +1 -0
  216. package/dist/routes/intake.js.map +1 -1
  217. package/dist/routes/projects.d.ts.map +1 -1
  218. package/dist/routes/projects.js +8 -2
  219. package/dist/routes/projects.js.map +1 -1
  220. package/dist/routes/provider-credentials.d.ts.map +1 -1
  221. package/dist/routes/provider-credentials.js +10 -5
  222. package/dist/routes/provider-credentials.js.map +1 -1
  223. package/dist/routes/running-packages.d.ts +13 -0
  224. package/dist/routes/running-packages.d.ts.map +1 -0
  225. package/dist/routes/running-packages.js +45 -0
  226. package/dist/routes/running-packages.js.map +1 -0
  227. package/dist/routes/surface.d.ts +10 -1
  228. package/dist/routes/surface.d.ts.map +1 -1
  229. package/dist/routes/surface.js +104 -35
  230. package/dist/routes/surface.js.map +1 -1
  231. package/dist/routes/work-items.d.ts.map +1 -1
  232. package/dist/routes/work-items.js +23 -3
  233. package/dist/routes/work-items.js.map +1 -1
  234. package/dist/rules/binding-context.d.ts.map +1 -1
  235. package/dist/rules/binding-context.js +1 -0
  236. package/dist/rules/binding-context.js.map +1 -1
  237. package/dist/rules/dispatcher.d.ts +0 -1
  238. package/dist/rules/dispatcher.d.ts.map +1 -1
  239. package/dist/rules/dispatcher.js +340 -42
  240. package/dist/rules/dispatcher.js.map +1 -1
  241. package/dist/rules/event-rules.d.ts +33 -2
  242. package/dist/rules/event-rules.d.ts.map +1 -1
  243. package/dist/rules/event-rules.js +46 -11
  244. package/dist/rules/event-rules.js.map +1 -1
  245. package/dist/rules/index.d.ts +2 -4
  246. package/dist/rules/index.d.ts.map +1 -1
  247. package/dist/rules/index.js +2 -3
  248. package/dist/rules/phase-goal.d.ts +54 -0
  249. package/dist/rules/phase-goal.d.ts.map +1 -0
  250. package/dist/rules/phase-goal.js +70 -0
  251. package/dist/rules/phase-goal.js.map +1 -0
  252. package/dist/rules/phase-tools.d.ts +11 -0
  253. package/dist/rules/phase-tools.d.ts.map +1 -0
  254. package/dist/rules/phase-tools.js +19 -0
  255. package/dist/rules/phase-tools.js.map +1 -0
  256. package/dist/rules/processor.d.ts.map +1 -1
  257. package/dist/rules/processor.js +112 -11
  258. package/dist/rules/processor.js.map +1 -1
  259. package/dist/rules/review-source-tool.d.ts +4 -1
  260. package/dist/rules/review-source-tool.d.ts.map +1 -1
  261. package/dist/rules/review-source-tool.js +24 -4
  262. package/dist/rules/review-source-tool.js.map +1 -1
  263. package/dist/rules/rule-group.d.ts +1 -1
  264. package/dist/rules/rule-group.d.ts.map +1 -1
  265. package/dist/rules/rule-group.js +2 -1
  266. package/dist/rules/rule-group.js.map +1 -1
  267. package/dist/rules/start-coordinator.d.ts +5 -1
  268. package/dist/rules/start-coordinator.d.ts.map +1 -1
  269. package/dist/rules/start-coordinator.js +9 -3
  270. package/dist/rules/start-coordinator.js.map +1 -1
  271. package/dist/rules/tools.d.ts.map +1 -1
  272. package/dist/rules/tools.js +39 -28
  273. package/dist/rules/tools.js.map +1 -1
  274. package/dist/rules/transition-service.d.ts +2 -7
  275. package/dist/rules/transition-service.d.ts.map +1 -1
  276. package/dist/rules/transition-service.js +61 -54
  277. package/dist/rules/transition-service.js.map +1 -1
  278. package/dist/rules/types.d.ts +83 -29
  279. package/dist/rules/types.d.ts.map +1 -1
  280. package/dist/rules/types.js +5 -41
  281. package/dist/rules/types.js.map +1 -1
  282. package/dist/rules/validation.d.ts.map +1 -1
  283. package/dist/rules/validation.js +32 -2
  284. package/dist/rules/validation.js.map +1 -1
  285. package/dist/secret-encryption.d.ts +21 -0
  286. package/dist/secret-encryption.d.ts.map +1 -1
  287. package/dist/secret-encryption.js +31 -4
  288. package/dist/secret-encryption.js.map +1 -1
  289. package/dist/session/self-review-gate.d.ts +6 -2
  290. package/dist/session/self-review-gate.d.ts.map +1 -1
  291. package/dist/session/self-review-gate.js +8 -4
  292. package/dist/session/self-review-gate.js.map +1 -1
  293. package/dist/session/session-threads.d.ts +2 -3
  294. package/dist/session/session-threads.d.ts.map +1 -1
  295. package/dist/session/session-threads.js.map +1 -1
  296. package/dist/session/source-control-tools.js +1 -1
  297. package/dist/session/work-item-state-processor.d.ts +27 -0
  298. package/dist/session/work-item-state-processor.d.ts.map +1 -0
  299. package/dist/session/work-item-state-processor.js +288 -0
  300. package/dist/session/work-item-state-processor.js.map +1 -0
  301. package/dist/storage/domains/boards/base.d.ts +44 -27
  302. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  303. package/dist/storage/domains/boards/base.js +76 -121
  304. package/dist/storage/domains/boards/base.js.map +1 -1
  305. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  306. package/dist/storage/domains/boards/schemas.js +12 -0
  307. package/dist/storage/domains/boards/schemas.js.map +1 -1
  308. package/dist/storage/domains/work-items/base.d.ts +32 -2
  309. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  310. package/dist/storage/domains/work-items/base.js +109 -26
  311. package/dist/storage/domains/work-items/base.js.map +1 -1
  312. package/dist/storage/domains/work-items/cards.d.ts +24 -2
  313. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  314. package/dist/storage/domains/work-items/cards.js +118 -8
  315. package/dist/storage/domains/work-items/cards.js.map +1 -1
  316. package/dist/storage/domains/work-items/legacy-review.d.ts +63 -0
  317. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -0
  318. package/dist/storage/domains/work-items/legacy-review.js +95 -0
  319. package/dist/storage/domains/work-items/legacy-review.js.map +1 -0
  320. package/dist/storage/domains/work-items/metrics.d.ts +12 -4
  321. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
  322. package/dist/storage/domains/work-items/metrics.js +14 -32
  323. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  324. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  325. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  326. package/dist/storage/domains/work-items/work-item-schema.js +5 -0
  327. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  328. package/dist/tools/approval-tools.d.ts.map +1 -1
  329. package/dist/tools/approval-tools.js +28 -9
  330. package/dist/tools/approval-tools.js.map +1 -1
  331. package/dist/tools/index.d.ts +1 -1
  332. package/dist/tools/index.js +1 -1
  333. package/dist/tools/index.js.map +1 -1
  334. package/dist/tools/messaging-tools.d.ts +3 -0
  335. package/dist/tools/messaging-tools.d.ts.map +1 -1
  336. package/dist/tools/messaging-tools.js +2 -1
  337. package/dist/tools/messaging-tools.js.map +1 -1
  338. package/dist/tools/read-tools.d.ts +8 -2
  339. package/dist/tools/read-tools.d.ts.map +1 -1
  340. package/dist/tools/read-tools.js +83 -23
  341. package/dist/tools/read-tools.js.map +1 -1
  342. package/dist/tools/reports.d.ts +1 -0
  343. package/dist/tools/reports.d.ts.map +1 -1
  344. package/dist/tools/reports.js +2 -1
  345. package/dist/tools/reports.js.map +1 -1
  346. package/dist/tools/run-watch.d.ts +1 -1
  347. package/dist/tools/run-watch.d.ts.map +1 -1
  348. package/dist/tools/run-watch.js +1 -0
  349. package/dist/tools/run-watch.js.map +1 -1
  350. package/dist/tools/sandbox-tools.js +1 -1
  351. package/dist/tools/session-tools.js +1 -1
  352. package/dist/tools/sessions-state-processor.d.ts +2 -0
  353. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  354. package/dist/tools/sessions-state-processor.js +4 -2
  355. package/dist/tools/sessions-state-processor.js.map +1 -1
  356. package/dist/tools/side-sessions.d.ts +2 -0
  357. package/dist/tools/side-sessions.d.ts.map +1 -1
  358. package/dist/tools/side-sessions.js +2 -1
  359. package/dist/tools/side-sessions.js.map +1 -1
  360. package/dist/tools/work-item-tools.js +3 -3
  361. package/dist/tools/work-item-tools.js.map +1 -1
  362. package/dist/work-item-branch.d.ts +13 -0
  363. package/dist/work-item-branch.d.ts.map +1 -1
  364. package/dist/work-item-branch.js +16 -1
  365. package/dist/work-item-branch.js.map +1 -1
  366. package/dist/work-items/create-work-item.d.ts +6 -0
  367. package/dist/work-items/create-work-item.d.ts.map +1 -1
  368. package/dist/work-items/create-work-item.js +25 -1
  369. package/dist/work-items/create-work-item.js.map +1 -1
  370. package/dist/work-items/split-migration.d.ts.map +1 -1
  371. package/dist/work-items/split-migration.js +1 -0
  372. package/dist/work-items/split-migration.js.map +1 -1
  373. package/dist/workspace.d.ts.map +1 -1
  374. package/dist/workspace.js +53 -10
  375. package/dist/workspace.js.map +1 -1
  376. package/factory-skills/configure-factory-rules/SKILL.md +11 -9
  377. package/factory-skills/factory-build/SKILL.md +64 -0
  378. package/factory-skills/factory-gitlab-rereview/SKILL.md +1 -1
  379. package/factory-skills/factory-gitlab-review/SKILL.md +2 -2
  380. package/factory-skills/factory-plan/SKILL.md +8 -10
  381. package/factory-skills/factory-rereview/SKILL.md +3 -3
  382. package/factory-skills/factory-review/SKILL.md +14 -4
  383. package/factory-skills/factory-self-review/SKILL.md +31 -11
  384. package/factory-skills/factory-triage/SKILL.md +25 -10
  385. package/package.json +10 -10
  386. package/dist/boards/index.js.map +0 -1
  387. package/dist/boards/pull-request-review.d.ts +0 -14
  388. package/dist/boards/pull-request-review.d.ts.map +0 -1
  389. package/dist/boards/pull-request-review.js +0 -81
  390. package/dist/boards/pull-request-review.js.map +0 -1
  391. package/dist/boards/work-tool-rules.d.ts +0 -8
  392. package/dist/boards/work-tool-rules.d.ts.map +0 -1
  393. package/dist/boards/work-tool-rules.js +0 -19
  394. package/dist/boards/work-tool-rules.js.map +0 -1
  395. package/dist/rules/resolve.d.ts +0 -15
  396. package/dist/rules/resolve.d.ts.map +0 -1
  397. package/dist/rules/resolve.js +0 -22
  398. package/dist/rules/resolve.js.map +0 -1
  399. package/factory-skills/factory-complete-issue/SKILL.md +0 -24
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-tools.js","names":[],"sources":["../../src/tools/work-item-tools.ts"],"sourcesContent":["/**\n * Factory tools that change work items: file one, move it, settle its\n * decisions, and follow it. They act as the session's person (a human actor),\n * through the same code the board's routes use.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { IntakeRoutesReader } from '../boards/intake-routing.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factoryWorkItemUrl } from '../links.js';\nimport { transitionBodySchema } from '../routes/contracts.js';\nimport type { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { CommentsDomain } from '../storage/domains/comments/domain.js';\nimport { WorkItemRelationError } from '../storage/domains/work-items/base.js';\nimport type { UpdateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { createFactoryWorkItem } from '../work-items/create-work-item.js';\nimport type { FactoryAuditEmit } from '../work-items/create-work-item.js';\nimport {\n dismissFactoryDecision,\n resolveFactoryProposal,\n retryFactoryDecision,\n} from '../work-items/decision-actions.js';\nimport type { FactoryDecisionActionResult } from '../work-items/decision-actions.js';\nimport {\n MAX_TEXT,\n findWorkItem,\n workItemRefSchema,\n truncate,\n workItemNotFound,\n workItemNumber,\n workItemStage,\n} from './read-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryWorkItemToolDependencies {\n workItems: WorkItemsStorage;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The project's intake routes, which place a filed card. */\n intakeRoutes?: IntakeRoutesReader;\n /** Governed stage moves; filing and moving items refuse while it is unavailable. */\n transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;\n /** Writes audit rows with an explicit actor; tool calls have no HTTP request to read one from. */\n auditRecorder: AuditRecorder;\n /** The feed's front door: validates, touches open boards and mirrors to linked channels. */\n feed: Pick<CommentsDomain, 'createComment'>;\n /** Finds the caller session's source-control provider, whose linked repositories a card can name. */\n sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n}\n\nconst repositorySchema = z\n .string()\n .trim()\n .min(3)\n .max(200)\n .regex(/^[^/\\s]+\\/[^/\\s]+$/, 'Use the owner/name form, e.g. \"mastra-ai/mastra\".')\n .describe('A repository linked to this Factory, as owner/name.');\n\nconst decisionId = z.string().trim().uuid().describe('Decision id, from factory_list_attention or inspect.');\n\nfunction briefItem(item: Card) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n stage: workItemStage(item),\n url:\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null,\n };\n}\n\nfunction settled(result: FactoryDecisionActionResult) {\n if (!result.ok) throw new Error(result.message);\n const { decision } = result;\n return { decisionId: decision.id, status: decision.status, workItemId: decision.workItemId };\n}\n\n/** The work-item write and subscription tools for one user session's turn. */\nexport function createFactoryWorkItemTools(\n scope: FactoryToolScope,\n deps: FactoryWorkItemToolDependencies,\n): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const audit: FactoryAuditEmit = async input => {\n await deps.auditRecorder.record({\n orgId: scope.orgId,\n // Turns nobody signed in started are recorded as this session's agent, as their moves are.\n actorId: scope.interactive ? scope.userId : `agent:session:${scope.sessionId}`,\n actorType: scope.interactive ? 'human' : 'agent',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ...input,\n });\n };\n const requireItem = async (ref: string) => {\n const item = await findWorkItem(deps.workItems, scope, ref);\n if (!item) throw workItemNotFound(ref);\n return item;\n };\n /**\n * Check `slug` is a repository linked to this Factory and that a card with\n * `metadata` would run in it (a card synced from an issue follows the\n * issue's repository, which a slug can't override).\n */\n const requireRepository = async (slug: string, item?: Pick<Card, 'metadata' | 'workItem'>) => {\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!sourceControl) throw new Error('This session has no source-control provider to look repositories up in.');\n const resolve = (repository?: string) =>\n resolveWorkItemRepository({\n sourceControl,\n ...project,\n item: {\n metadata: repository ? { repository } : (item?.metadata ?? null),\n workItem: item?.workItem ?? { metadata: null },\n },\n });\n const resolution = await resolve(slug);\n if (resolution.status === 'resolved' && resolution.slug === slug) return;\n if (resolution.status === 'resolved') {\n throw new Error(`This card runs in ${resolution.slug}, which comes from its linked issue and can't be changed.`);\n }\n const linked = await resolve();\n const candidates =\n linked.status === 'ambiguous' ? linked.candidates : linked.status === 'resolved' ? [linked.slug] : [];\n throw new Error(\n candidates.length > 0\n ? `${slug} is not linked to this Factory. Linked repositories: ${candidates.join(', ')}.`\n : `${slug} is not linked to this Factory, and it has no linked repositories.`,\n );\n };\n const follow = (item: Card, reason: 'created' | 'subscribed') =>\n deps.workItems.subscribeToWorkItem({\n ...project,\n workItemId: item.id,\n sessionId: scope.sessionId,\n threadId: scope.threadId,\n resourceId: scope.resourceId,\n userId: scope.userId,\n reason,\n });\n\n return {\n factory_create_work_item: createTool({\n id: 'factory_create_work_item',\n description:\n \"File a new work item on this Factory's Work board (or wherever the project's intake routes send it) for the person you are working with. It enters its board's first phase, or the phase an intake route names, and this session follows it. Check factory_list_work_items for an existing item first. Name the repository when the Factory links more than one; runs refuse to start on a card that doesn't say which.\",\n inputSchema: z\n .object({\n title: z.string().trim().min(1).max(512).describe('Short title, as it should read on the card.'),\n brief: z\n .string()\n .trim()\n .min(1)\n .max(8000)\n .describe('What needs doing and why; posted as the first comment on the card.'),\n repository: repositorySchema.optional(),\n })\n .strict(),\n execute: async ({ title, brief, repository }) => {\n if (repository) await requireRepository(repository);\n const created = await createFactoryWorkItem({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n transitionService: deps.transitionService,\n intakeRoutes: deps.intakeRoutes,\n audit,\n ...project,\n userId: scope.userId,\n ...(scope.actorProfile ? { origin: { actorProfile: scope.actorProfile } } : {}),\n input: { title, ...(repository ? { metadata: { repository } } : {}) },\n });\n if (created.status === 'refused') throw new Error(created.message);\n if (created.status === 'rejected') throw new Error(`The board refused the new item: ${created.reason}`);\n const { item } = created;\n // The card exists from here on: report follow-up failures alongside it\n // rather than failing the call, so the agent doesn't file it twice.\n const warnings: string[] = [];\n try {\n const comment = await deps.feed.createComment({\n orgId: scope.orgId,\n workItemId: item.id,\n author: { kind: 'user', id: scope.userId },\n body: brief,\n });\n if (comment.status !== 'created') {\n warnings.push(\n `The brief was not posted (${comment.status === 'invalid' ? comment.message : comment.status}).`,\n );\n }\n } catch (error) {\n warnings.push(`The brief was not posted: ${error instanceof Error ? error.message : String(error)}`);\n }\n try {\n await follow(item, 'created');\n } catch (error) {\n warnings.push(\n `This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return warnings.length ? { ...briefItem(item), warnings } : briefItem(item);\n },\n }),\n\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n \"Move a work item to another stage of its board, as the person you are working with. The board's rules decide whether the move is allowed and what it starts.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n stage: z.string().trim().min(1).max(64).describe('Destination stage, e.g. \"planning\" or \"done\".'),\n })\n .strict(),\n execute: async ({ workItem, stage }) => {\n if (!deps.transitionService) throw new Error('Factory stage transitions are not available right now.');\n const item = await requireItem(workItem);\n const parsed = transitionBodySchema.safeParse({\n board: boardForWorkItem(item),\n stage,\n expectedRevision: item.revision,\n requestId: randomUUID(),\n cause: 'factory_tools',\n });\n if (!parsed.success) throw new Error(`\"${stage}\" is not a valid stage name.`);\n const result = await deps.transitionService.transition({\n ...parsed.data,\n ...project,\n workItemId: item.id,\n ...(scope.interactive\n ? {\n actor: { type: 'human' as const, id: scope.userId },\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ingress: { ...parsed.data.ingress, identity: `human:${scope.userId}:${parsed.data.ingress.identity}` },\n }\n : {\n // Nobody signed in started this turn: move as this session's agent, so the\n // plan gate and the agent's done gates apply and the move arms no runs.\n actor: { type: 'agent' as const, bindingId: `session:${scope.sessionId}`, role: 'session' },\n ingress: {\n type: 'agent' as const,\n identity: `session:${scope.sessionId}:${parsed.data.ingress.identity}`,\n },\n }),\n });\n if (result.status === 'rejected') throw new Error(`The move was refused (${result.code}): ${result.reason}`);\n return { workItemId: item.id, stage: result.stage, revision: result.revision };\n },\n }),\n\n factory_update_work_item: createTool({\n id: 'factory_update_work_item',\n description:\n \"Edit a work item's fields as the person you are working with: its title, the repository its runs use, its parent item, or pre-approving its plans. Move stages with factory_transition_work_item and start roles with factory_start_session; post to the card's feed for anything else.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n title: z.string().trim().min(1).max(500).optional().describe('New card title.'),\n repository: repositorySchema.optional(),\n parentWorkItem: workItemRefSchema\n .nullable()\n .optional()\n .describe('Parent work item (id or #number), or null to detach it from its parent.'),\n })\n .strict()\n .refine(input => Object.keys(input).some(key => key !== 'workItem'), 'Pass at least one field to change.'),\n execute: async ({ workItem, title, repository, parentWorkItem }) => {\n const item = await requireItem(workItem);\n if (repository) await requireRepository(repository, item);\n let parentWorkItemId: string | null | undefined;\n if (parentWorkItem === null) parentWorkItemId = null;\n else if (parentWorkItem !== undefined) parentWorkItemId = (await requireItem(parentWorkItem)).id;\n const patch: UpdateWorkItemInput = {\n ...(title !== undefined ? { title } : {}),\n ...(repository ? { metadata: { repository } } : {}),\n ...(parentWorkItemId !== undefined ? { parentWorkItemId } : {}),\n };\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await deps.workItems.update({ orgId: scope.orgId, id: item.id, userId: scope.userId, patch });\n } catch (error) {\n if (error instanceof WorkItemRelationError) throw new Error(`The parent was refused: ${error.message}`);\n throw error;\n }\n if (!updated) throw workItemNotFound(workItem);\n const fields = [\n ...(title !== undefined ? ['title'] : []),\n ...(repository ? ['metadata'] : []),\n ...(parentWorkItemId !== undefined ? ['parentWorkItemId'] : []),\n ];\n await audit({\n action: 'factory.work_item.updated',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'work_item', id: updated.item.id, name: updated.item.title }],\n metadata: { fields, cause: 'factory_tools' },\n });\n const metadata = updated.item.metadata ?? {};\n return {\n workItem: briefItem(updated.item),\n updated: fields.map(field => (field === 'metadata' ? 'repository' : field)),\n repository: typeof metadata.repository === 'string' ? metadata.repository : null,\n parentWorkItemId: updated.item.parentWorkItemId,\n };\n },\n }),\n\n factory_retry_decision: createTool({\n id: 'factory_retry_decision',\n description:\n 'Retry one failed Factory run once its cause is fixed. Refused when the failure cannot be fixed by retrying or the item has moved on.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) =>\n settled(\n await retryFactoryDecision({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n ...project,\n decisionId,\n }),\n ),\n }),\n\n factory_dismiss_decision: createTool({\n id: 'factory_dismiss_decision',\n description: 'Dismiss one proposed Factory run that is no longer wanted.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) => {\n requirePerson(scope, 'dismiss a proposed run');\n return settled(\n await dismissFactoryDecision({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n }),\n );\n },\n }),\n\n factory_resolve_proposal: createTool({\n id: 'factory_resolve_proposal',\n description:\n \"Approve or dismiss one proposed Factory run. Approving starts the run and lets the item's later runs start without asking.\",\n inputSchema: z.object({ decisionId, action: z.enum(['approve', 'dismiss']) }).strict(),\n execute: async ({ decisionId, action }) => {\n requirePerson(scope, 'approve or dismiss a proposed run');\n return settled(\n await resolveFactoryProposal({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n action,\n }),\n );\n },\n }),\n\n factory_subscribe_work_item: createTool({\n id: 'factory_subscribe_work_item',\n description:\n 'Follow a work item from this session, so you hear about its progress and its sessions report to you. Items you file or start are followed already.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const subscription = await follow(item, 'subscribed');\n return { workItem: briefItem(item), subscribed: true, reason: subscription.reason };\n },\n }),\n\n factory_unsubscribe_work_item: createTool({\n id: 'factory_unsubscribe_work_item',\n description: 'Stop following a work item from this session.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const removed = await deps.workItems.unsubscribeFromWorkItem({\n orgId: scope.orgId,\n workItemId: item.id,\n sessionId: scope.sessionId,\n });\n return { workItem: briefItem(item), subscribed: false, wasSubscribed: removed };\n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AC;GAAE,CAAC,CAAC,CAAC,OAAO;GACrF,SAAS,OAAO,EAAE,YAAY,aAAa;IACzC,cAAc,OAAO,mCAAmC;IACxD,OAAO,QACL,MAAM,uBAAuB;KAC3B,WAAW,KAAK;KAChB;KACA,GAAG;KACH,QAAQ,MAAM;KACd;KACA;IACF,CAAC,CACH;GACF;EACF,CAAC;EAED,6BAA6B,WAAW;GACtC,IAAI;GACJ,aACE;GACF,aAAa,EAAE,OAAO,EAAE,UAAU,kBAAkB,CAAC,CAAC,CAAC,OAAO;GAC9D,SAAS,OAAO,EAAE,eAAe;IAC/B,MAAM,OAAO,MAAM,YAAY,QAAQ;IACvC,MAAM,eAAe,MAAM,OAAO,MAAM,YAAY;IACpD,OAAO;KAAE,UAAU,UAAU,IAAI;KAAG,YAAY;KAAM,QAAQ,aAAa;IAAO;GACpF;EACF,CAAC;EAED,+BAA+B,WAAW;GACxC,IAAI;GACJ,aAAa;GACb,aAAa,EAAE,OAAO,EAAE,UAAU,kBAAkB,CAAC,CAAC,CAAC,OAAO;GAC9D,SAAS,OAAO,EAAE,eAAe;IAC/B,MAAM,OAAO,MAAM,YAAY,QAAQ;IACvC,MAAM,UAAU,MAAM,KAAK,UAAU,wBAAwB;KAC3D,OAAO,MAAM;KACb,YAAY,KAAK;KACjB,WAAW,MAAM;IACnB,CAAC;IACD,OAAO;KAAE,UAAU,UAAU,IAAI;KAAG,YAAY;KAAO,eAAe;IAAQ;GAChF;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"work-item-tools.js","names":[],"sources":["../../src/tools/work-item-tools.ts"],"sourcesContent":["/**\n * Factory tools that change work items: file one, move it, settle its\n * decisions, and follow it. They act as the session's person (a human actor),\n * through the same code the board's routes use.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport { boardForWorkItem } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport type { IntakeRoutesReader } from '../boards/intake-routing.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { factoryWorkItemUrl } from '../links.js';\nimport { transitionBodySchema } from '../routes/contracts.js';\nimport type { FactoryTransitionService } from '../rules/transition-service.js';\nimport type { SourceControlSessionLookup } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { CommentsDomain } from '../storage/domains/comments/domain.js';\nimport { WorkItemRelationError } from '../storage/domains/work-items/base.js';\nimport type { UpdateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { createFactoryWorkItem } from '../work-items/create-work-item.js';\nimport type { FactoryAuditEmit } from '../work-items/create-work-item.js';\nimport {\n dismissFactoryDecision,\n resolveFactoryProposal,\n retryFactoryDecision,\n} from '../work-items/decision-actions.js';\nimport type { FactoryDecisionActionResult } from '../work-items/decision-actions.js';\nimport {\n MAX_TEXT,\n findWorkItem,\n workItemRefSchema,\n truncate,\n workItemNotFound,\n workItemNumber,\n workItemStage,\n} from './read-tools.js';\nimport { requirePerson } from './scope.js';\nimport type { FactoryToolScope } from './scope.js';\n\nexport interface FactoryWorkItemToolDependencies {\n workItems: WorkItemsStorage;\n /** A fixed registry, or the per-project boards. */\n boards: BoardRegistry | ProjectBoardSource;\n /** The project's intake routes, which place a filed card. */\n intakeRoutes?: IntakeRoutesReader;\n /** Governed stage moves; filing and moving items refuse while it is unavailable. */\n transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;\n /** Writes audit rows with an explicit actor; tool calls have no HTTP request to read one from. */\n auditRecorder: AuditRecorder;\n /** The feed's front door: validates, touches open boards and mirrors to linked channels. */\n feed: Pick<CommentsDomain, 'createComment'>;\n /** Finds the caller session's source-control provider, whose linked repositories a card can name. */\n sessions: Pick<SourceControlSessionLookup, 'getSourceControlBySessionId'>;\n}\n\nconst repositorySchema = z\n .string()\n .trim()\n .min(3)\n .max(200)\n .regex(/^[^/\\s]+\\/[^/\\s]+$/, 'Use the owner/name form, e.g. \"mastra-ai/mastra\".')\n .describe('A repository linked to this Factory, as owner/name.');\n\nconst decisionId = z.string().trim().uuid().describe('Decision id, from factory_list_attention or inspect.');\n\nfunction briefItem(item: Card) {\n return {\n id: item.id,\n number: workItemNumber(item),\n title: truncate(item.title, MAX_TEXT),\n stage: workItemStage(item),\n url:\n factoryWorkItemUrl({\n factoryProjectId: item.factoryProjectId,\n board: boardForWorkItem(item),\n workItemId: item.id,\n }) ?? null,\n };\n}\n\nfunction settled(result: FactoryDecisionActionResult) {\n if (!result.ok) throw new Error(result.message);\n const { decision } = result;\n return { decisionId: decision.id, status: decision.status, workItemId: decision.workItemId };\n}\n\n/** The work-item write and subscription tools for one user session's turn. */\nexport function createFactoryWorkItemTools(\n scope: FactoryToolScope,\n deps: FactoryWorkItemToolDependencies,\n): IntegrationTools {\n const project = { orgId: scope.orgId, factoryProjectId: scope.factoryProjectId };\n const audit: FactoryAuditEmit = async input => {\n await deps.auditRecorder.record({\n orgId: scope.orgId,\n // Turns nobody signed in started are recorded as this session's agent, as their moves are.\n actorId: scope.interactive ? scope.userId : `agent:session:${scope.sessionId}`,\n actorType: scope.interactive ? 'human' : 'agent',\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ...input,\n });\n };\n const requireItem = async (ref: string) => {\n const item = await findWorkItem(deps.workItems, scope, ref);\n if (!item) throw workItemNotFound(ref);\n return item;\n };\n /**\n * Check `slug` is a repository linked to this Factory and that a card with\n * `metadata` would run in it (a card synced from an issue follows the\n * issue's repository, which a slug can't override).\n */\n const requireRepository = async (slug: string, item?: Pick<Card, 'metadata' | 'workItem'>) => {\n const sourceControl = await deps.sessions.getSourceControlBySessionId(scope.sessionId);\n if (!sourceControl) throw new Error('This session has no source-control provider to look repositories up in.');\n const resolve = (repository?: string) =>\n resolveWorkItemRepository({\n sourceControl,\n ...project,\n item: {\n metadata: repository ? { repository } : (item?.metadata ?? null),\n workItem: item?.workItem ?? { metadata: null },\n },\n });\n const resolution = await resolve(slug);\n if (resolution.status === 'resolved' && resolution.slug === slug) return;\n if (resolution.status === 'resolved') {\n throw new Error(`This card runs in ${resolution.slug}, which comes from its linked issue and can't be changed.`);\n }\n const linked = await resolve();\n const candidates =\n linked.status === 'ambiguous' ? linked.candidates : linked.status === 'resolved' ? [linked.slug] : [];\n throw new Error(\n candidates.length > 0\n ? `${slug} is not linked to this Factory. Linked repositories: ${candidates.join(', ')}.`\n : `${slug} is not linked to this Factory, and it has no linked repositories.`,\n );\n };\n const follow = (item: Card, reason: 'created' | 'subscribed') =>\n deps.workItems.subscribeToWorkItem({\n ...project,\n workItemId: item.id,\n sessionId: scope.sessionId,\n threadId: scope.threadId,\n resourceId: scope.resourceId,\n userId: scope.userId,\n reason,\n });\n\n return {\n factory_create_work_item: createTool({\n id: 'factory_create_work_item',\n description:\n \"File a new work item on this Factory's Work board (or wherever the project's intake routes send it) for the person you are working with. It enters its board's first phase, or the phase an intake route names, and this session follows it. Check factory_list_work_items for an existing item first. Name the repository when the Factory links more than one; runs refuse to start on a card that doesn't say which.\",\n inputSchema: z\n .object({\n title: z.string().trim().min(1).max(512).describe('Short title, as it should read on the card.'),\n brief: z\n .string()\n .trim()\n .min(1)\n .max(8000)\n .describe('What needs doing and why; posted as the first comment on the card.'),\n repository: repositorySchema.optional(),\n })\n .strict(),\n execute: async ({ title, brief, repository }) => {\n if (repository) await requireRepository(repository);\n const created = await createFactoryWorkItem({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n transitionService: deps.transitionService,\n intakeRoutes: deps.intakeRoutes,\n audit,\n ...project,\n userId: scope.userId,\n ...(scope.actorProfile ? { origin: { actorProfile: scope.actorProfile } } : {}),\n input: { title, ...(repository ? { metadata: { repository } } : {}) },\n });\n if (created.status === 'refused') throw new Error(created.message);\n if (created.status === 'rejected') throw new Error(`The board refused the new item: ${created.reason}`);\n const { item } = created;\n // The card exists from here on: report follow-up failures alongside it\n // rather than failing the call, so the agent doesn't file it twice.\n const warnings: string[] = [];\n try {\n const comment = await deps.feed.createComment({\n orgId: scope.orgId,\n workItemId: item.id,\n author: { kind: 'user', id: scope.userId },\n body: brief,\n });\n if (comment.status !== 'created') {\n warnings.push(\n `The brief was not posted (${comment.status === 'invalid' ? comment.message : comment.status}).`,\n );\n }\n } catch (error) {\n warnings.push(`The brief was not posted: ${error instanceof Error ? error.message : String(error)}`);\n }\n try {\n await follow(item, 'created');\n } catch (error) {\n warnings.push(\n `This session does not follow it yet: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n return warnings.length ? { ...briefItem(item), warnings } : briefItem(item);\n },\n }),\n\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n \"Move a work item to another stage of its board, as the person you are working with. The board's rules decide whether the move is allowed and what it starts.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n stage: z.string().trim().min(1).max(64).describe('Destination stage, e.g. \"planning\" or \"done\".'),\n })\n .strict(),\n execute: async ({ workItem, stage }) => {\n if (!deps.transitionService) throw new Error('Factory stage transitions are not available right now.');\n const item = await requireItem(workItem);\n const parsed = transitionBodySchema.safeParse({\n board: boardForWorkItem(item),\n stage,\n expectedRevision: item.revision,\n requestId: randomUUID(),\n cause: 'factory_tools',\n });\n if (!parsed.success) throw new Error(`\"${stage}\" is not a valid stage name.`);\n const result = await deps.transitionService.transition({\n ...parsed.data,\n ...project,\n workItemId: item.id,\n ...(scope.interactive\n ? {\n actor: { type: 'human' as const, id: scope.userId },\n ...(scope.actorProfile ? { actorProfile: scope.actorProfile } : {}),\n ingress: { ...parsed.data.ingress, identity: `human:${scope.userId}:${parsed.data.ingress.identity}` },\n }\n : {\n // Nobody signed in started this turn: move as this session's agent, so the\n // plan gate and the agent's done gates apply and the move arms no runs.\n actor: { type: 'agent' as const, bindingId: `session:${scope.sessionId}`, role: 'session' },\n ingress: {\n type: 'agent' as const,\n identity: `session:${scope.sessionId}:${parsed.data.ingress.identity}`,\n },\n }),\n });\n if (result.status === 'rejected') throw new Error(`The move was refused (${result.code}): ${result.reason}`);\n return { workItemId: item.id, stage: result.stage, revision: result.revision };\n },\n }),\n\n factory_update_work_item: createTool({\n id: 'factory_update_work_item',\n description:\n \"Edit a work item's fields as the person you are working with: its title, the repository its runs use, or its parent item. Move stages with factory_transition_work_item and start roles with factory_start_session; post to the card's feed for anything else.\",\n inputSchema: z\n .object({\n workItem: workItemRefSchema,\n title: z.string().trim().min(1).max(500).optional().describe('New card title.'),\n repository: repositorySchema.optional(),\n parentWorkItem: workItemRefSchema\n .nullable()\n .optional()\n .describe('Parent work item (id or #number), or null to detach it from its parent.'),\n })\n .strict()\n .refine(input => Object.keys(input).some(key => key !== 'workItem'), 'Pass at least one field to change.'),\n execute: async ({ workItem, title, repository, parentWorkItem }) => {\n const item = await requireItem(workItem);\n if (repository) await requireRepository(repository, item);\n let parentWorkItemId: string | null | undefined;\n if (parentWorkItem === null) parentWorkItemId = null;\n else if (parentWorkItem !== undefined) parentWorkItemId = (await requireItem(parentWorkItem)).id;\n const patch: UpdateWorkItemInput = {\n ...(title !== undefined ? { title } : {}),\n ...(repository ? { metadata: { repository } } : {}),\n ...(parentWorkItemId !== undefined ? { parentWorkItemId } : {}),\n };\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await deps.workItems.update({ orgId: scope.orgId, id: item.id, userId: scope.userId, patch });\n } catch (error) {\n if (error instanceof WorkItemRelationError) throw new Error(`The parent was refused: ${error.message}`);\n throw error;\n }\n if (!updated) throw workItemNotFound(workItem);\n const fields = [\n ...(title !== undefined ? ['title'] : []),\n ...(repository ? ['metadata'] : []),\n ...(parentWorkItemId !== undefined ? ['parentWorkItemId'] : []),\n ];\n await audit({\n action: 'factory.work_item.updated',\n factoryProjectId: scope.factoryProjectId,\n targets: [{ type: 'work_item', id: updated.item.id, name: updated.item.title }],\n metadata: { fields, cause: 'factory_tools' },\n });\n const metadata = updated.item.metadata ?? {};\n return {\n workItem: briefItem(updated.item),\n updated: fields.map(field => (field === 'metadata' ? 'repository' : field)),\n repository: typeof metadata.repository === 'string' ? metadata.repository : null,\n parentWorkItemId: updated.item.parentWorkItemId,\n };\n },\n }),\n\n factory_retry_decision: createTool({\n id: 'factory_retry_decision',\n description:\n 'Retry one failed Factory run once its cause is fixed. Refused when the failure cannot be fixed by retrying or the item has moved on.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) =>\n settled(\n await retryFactoryDecision({\n workItems: deps.workItems,\n boards: await toBoardSource(deps.boards).load(project),\n ...project,\n decisionId,\n }),\n ),\n }),\n\n factory_dismiss_decision: createTool({\n id: 'factory_dismiss_decision',\n description: 'Dismiss one proposed Factory run that is no longer wanted.',\n inputSchema: z.object({ decisionId }).strict(),\n execute: async ({ decisionId }) => {\n requirePerson(scope, 'dismiss a proposed run');\n return settled(\n await dismissFactoryDecision({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n }),\n );\n },\n }),\n\n factory_resolve_proposal: createTool({\n id: 'factory_resolve_proposal',\n description:\n \"Approve or dismiss one proposed Factory run. Approving starts the run and lets the item's later runs start without asking.\",\n inputSchema: z.object({ decisionId, action: z.enum(['approve', 'dismiss']) }).strict(),\n execute: async ({ decisionId, action }) => {\n requirePerson(scope, 'approve or dismiss a proposed run');\n return settled(\n await resolveFactoryProposal({\n workItems: deps.workItems,\n audit,\n ...project,\n userId: scope.userId,\n decisionId,\n action,\n }),\n );\n },\n }),\n\n factory_subscribe_work_item: createTool({\n id: 'factory_subscribe_work_item',\n description:\n 'Follow a work item from this session, so you hear about its progress and its sessions report to you. Items you file or start are followed already.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const subscription = await follow(item, 'subscribed');\n return { workItem: briefItem(item), subscribed: true, reason: subscription.reason };\n },\n }),\n\n factory_unsubscribe_work_item: createTool({\n id: 'factory_unsubscribe_work_item',\n description: 'Stop following a work item from this session.',\n inputSchema: z.object({ workItem: workItemRefSchema }).strict(),\n execute: async ({ workItem }) => {\n const item = await requireItem(workItem);\n const removed = await deps.workItems.unsubscribeFromWorkItem({\n orgId: scope.orgId,\n workItemId: item.id,\n sessionId: scope.sessionId,\n });\n return { workItem: briefItem(item), subscribed: false, wasSubscribed: removed };\n },\n }),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,mBAAmB,EACtB,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,IAAI,GAAG,CAAC,CACR,MAAM,sBAAsB,qDAAmD,CAAC,CAChF,SAAS,qDAAqD;AAEjE,MAAM,aAAa,EAAE,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,SAAS,sDAAsD;AAE3G,SAAS,UAAU,MAAY;CAC7B,OAAO;EACL,IAAI,KAAK;EACT,QAAQ,eAAe,IAAI;EAC3B,OAAO,SAAS,KAAK,OAAA,GAAe;EACpC,OAAO,cAAc,IAAI;EACzB,KACE,mBAAmB;GACjB,kBAAkB,KAAK;GACvB,OAAO,iBAAiB,IAAI;GAC5B,YAAY,KAAK;EACnB,CAAC,KAAK;CACV;AACF;AAEA,SAAS,QAAQ,QAAqC;CACpD,IAAI,CAAC,OAAO,IAAI,MAAM,IAAI,MAAM,OAAO,OAAO;CAC9C,MAAM,EAAE,aAAa;CACrB,OAAO;EAAE,YAAY,SAAS;EAAI,QAAQ,SAAS;EAAQ,YAAY,SAAS;CAAW;AAC7F;;AAGA,SAAgB,2BACd,OACA,MACkB;CAClB,MAAM,UAAU;EAAE,OAAO,MAAM;EAAO,kBAAkB,MAAM;CAAiB;CAC/E,MAAM,QAA0B,OAAM,UAAS;EAC7C,MAAM,KAAK,cAAc,OAAO;GAC9B,OAAO,MAAM;GAEb,SAAS,MAAM,cAAc,MAAM,SAAS,iBAAiB,MAAM;GACnE,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ou
28
28
  * the id-derived branch.
29
29
  */
30
30
  export declare function workItemBranch(item: WorkItemBranchInput): string;
31
+ /**
32
+ * The branch a card's pull or merge request is reviewed on. A PR's own card gets
33
+ * the same name {@link workItemBranch} gives it; an issue card reviewing a PR
34
+ * attached to it gets a branch apart from its builder's issue branch, so the
35
+ * reviewer and the builder never share a checkout.
36
+ */
37
+ export declare function pullRequestBranch(input: {
38
+ id: string;
39
+ provider: 'github' | 'gitlab';
40
+ number: number;
41
+ }): string;
31
42
  /** The pre-suffix GitHub branch, for reusing sessions opened before card names were unique. */
32
43
  export declare function legacyGithubWorkItemBranch(branch: string): string | undefined;
33
44
  /**
@@ -38,4 +49,6 @@ export declare function legacyGithubWorkItemBranch(branch: string): string | und
38
49
  export declare function pullRequestNumberFromBranch(branch: string): number | undefined;
39
50
  /** The GitLab MR IID encoded in Factory's collision-resistant review branch. */
40
51
  export declare function mergeRequestNumberFromBranch(branch: string): number | undefined;
52
+ /** Whether a provider-reported branch name is safe to show an agent or pass to git. */
53
+ export declare function isSafeBranchName(value: string): boolean;
41
54
  //# sourceMappingURL=work-item-branch.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-branch.d.ts","sourceRoot":"","sources":["../src/work-item-branch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,sCAAsC,CAAC;AAEnF;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAC5B,cAAc,GACd,WAAW,GACX,cAAc,GACd,WAAW,GACX,cAAc,GACd,YAAY,GACZ,sBAAsB,GACtB,cAAc,GACd,QAAQ,CAAC;AAEb,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,oBAAoB,CAAC;IAC7B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAC3C;AAED,qFAAqF;AACrF,wBAAgB,oBAAoB,CAAC,cAAc,EAAE,sBA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EAAE,sBAAsB,GAAG,IAAI,GAAG,SAAS,GAAG,oBAAoB,CAYpH;AAOD,mGAAmG;AACnG,wBAAgB,cAAc,CAAC,IAAI,EAAE,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG,MAAM,GAAG,SAAS,CAOzG;AAED,yHAAyH;AACzH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,IAAI,CAAC,mBAAmB,EAAE,QAAQ,GAAG,UAAU,CAAC,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,GACzE,MAAM,CAKR;AAgBD;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,mBAAmB,GAAG,MAAM,CA+BhE;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,QAAQ,GAAG,QAAQ,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,MAAM,CAM9G;AAED,+FAA+F;AAC/F,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAG7E;AAED;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAI9E;AAED,gFAAgF;AAChF,wBAAgB,4BAA4B,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAI/E;AAED,uFAAuF;AACvF,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAUvD"}
@@ -69,6 +69,17 @@ function workItemBranch(item) {
69
69
  }
70
70
  return `factory/item-${item.id}`;
71
71
  }
72
+ /**
73
+ * The branch a card's pull or merge request is reviewed on. A PR's own card gets
74
+ * the same name {@link workItemBranch} gives it; an issue card reviewing a PR
75
+ * attached to it gets a branch apart from its builder's issue branch, so the
76
+ * reviewer and the builder never share a checkout.
77
+ */
78
+ function pullRequestBranch(input) {
79
+ const suffix = itemSuffix(input.id);
80
+ if (input.provider === "gitlab") return suffix ? `factory/gitlab-mr-${input.number}-${suffix}` : `factory/item-${input.id}-mr-${input.number}`;
81
+ return suffix ? `factory/pr-${input.number}-${suffix}` : `factory/pr-${input.number}`;
82
+ }
72
83
  /** The pre-suffix GitHub branch, for reusing sessions opened before card names were unique. */
73
84
  function legacyGithubWorkItemBranch(branch) {
74
85
  return /^(factory\/(?:issue|pr)-[1-9]\d*)-[a-z0-9]{1,12}$/.exec(branch)?.[1];
@@ -89,6 +100,10 @@ function mergeRequestNumberFromBranch(branch) {
89
100
  const number = match ? Number(match[1]) : void 0;
90
101
  return number !== void 0 && Number.isSafeInteger(number) ? number : void 0;
91
102
  }
92
- export { legacyGithubWorkItemBranch, mergeRequestNumberFromBranch, pullRequestNumberFromBranch, workItemBranch, workItemBranchSource, workItemNumber, workItemThreadTitle };
103
+ /** Whether a provider-reported branch name is safe to show an agent or pass to git. */
104
+ function isSafeBranchName(value) {
105
+ return /^[A-Za-z0-9][A-Za-z0-9._/@+-]*$/.test(value) && !value.includes("..") && !value.includes("//") && !value.includes("@{") && !value.endsWith(".") && !value.endsWith("/") && !value.endsWith(".lock");
106
+ }
107
+ export { isSafeBranchName, legacyGithubWorkItemBranch, mergeRequestNumberFromBranch, pullRequestBranch, pullRequestNumberFromBranch, workItemBranch, workItemBranchSource, workItemNumber, workItemThreadTitle };
93
108
 
94
109
  //# sourceMappingURL=work-item-branch.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-branch.js","names":[],"sources":["../src/work-item-branch.ts"],"sourcesContent":["import type { ExternalWorkItemSource } from './storage/domains/work-items/base.js';\n\n/**\n * Where a card came from, in the vocabulary branch naming reads. Server rows\n * map their `externalSource` into this with {@link workItemBranchSource}; the\n * board's own `WorkItem['source']` is already this union.\n */\nexport type WorkItemBranchSource =\n | 'github-issue'\n | 'github-pr'\n | 'gitlab-issue'\n | 'gitlab-pr'\n | 'linear-issue'\n | 'jira-issue'\n | 'incidentio-follow-up'\n | 'slack-thread'\n | 'manual';\n\nexport interface WorkItemBranchInput {\n id: string;\n source: WorkItemBranchSource;\n metadata?: Record<string, unknown> | null;\n}\n\n/** Map a stored item's provenance onto the source vocabulary branch naming reads. */\nexport function workItemBranchSource(externalSource: ExternalWorkItemSource | null | undefined): WorkItemBranchSource {\n if (!externalSource) return 'manual';\n if (externalSource.integrationId === 'linear') return 'linear-issue';\n if (externalSource.integrationId === 'gitlab') {\n return externalSource.type === 'pull-request' ? 'gitlab-pr' : 'gitlab-issue';\n }\n if (externalSource.integrationId === 'jira') return 'jira-issue';\n if (externalSource.integrationId === 'incidentio') return 'incidentio-follow-up';\n // Only GitHub, GitLab, Linear, Jira, and incident.io carry provider identities; anything\n // else (a Slack thread, say) is a plain work item rather than a mislabeled GitHub issue.\n if (externalSource.integrationId !== 'github') return 'manual';\n return externalSource.type === 'pull-request' ? 'github-pr' : 'github-issue';\n}\n\nfunction branchNumber(metadata: Record<string, unknown>, key: string): number | undefined {\n const value = metadata[key] ?? metadata.number;\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\n/** The provider number a GitHub card carries — the `#12` its runs and thread titles name it by. */\nexport function workItemNumber(item: Pick<WorkItemBranchInput, 'source' | 'metadata'>): number | undefined {\n const metadata = item.metadata ?? {};\n if (item.source === 'github-issue') return branchNumber(metadata, 'githubIssueNumber');\n if (item.source === 'github-pr') return branchNumber(metadata, 'githubPullRequestNumber');\n if (item.source === 'gitlab-issue') return branchNumber(metadata, 'gitlabIssueIid');\n if (item.source === 'gitlab-pr') return branchNumber(metadata, 'gitlabMergeRequestIid');\n return undefined;\n}\n\n/** How a card names its thread: a Linear title already opens with its identifier, a GitHub card gets its number here. */\nexport function workItemThreadTitle(\n item: Pick<WorkItemBranchInput, 'source' | 'metadata'> & { title: string },\n): string {\n const number = workItemNumber(item);\n if (number === undefined) return item.title;\n const kind = item.source === 'github-pr' ? 'PR' : item.source === 'gitlab-pr' ? 'MR' : 'Issue';\n return `${kind} #${number}: ${item.title}`;\n}\n\n/**\n * The last twelve alphanumerics of a work item id: the per-item suffix that keeps\n * provider numbers from colliding across the repositories of one factory. Issue\n * #13 exists in every repository, and a factory's sessions are unique per\n * user and branch across all of its repositories, so a branch named by the\n * number alone can only be held once per factory.\n */\nfunction itemSuffix(id: string): string {\n return id\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '')\n .slice(-12);\n}\n\n/**\n * The git branch an item's runs and sessions share, one grammar for both sides\n * of the wire: the dispatcher names autonomous run branches with it and the\n * board opens card sessions on it, so both converge on one checkout per item.\n * Provider numbers are only unique within a repository, so GitHub and GitLab\n * branches carry the item suffix as well. Cards without a provider identity\n * (manual, Slack) and cards whose metadata lost their identifier fall back to\n * the id-derived branch.\n */\nexport function workItemBranch(item: WorkItemBranchInput): string {\n const metadata = item.metadata ?? {};\n const providerNumber = workItemNumber(item);\n if (providerNumber !== undefined && (item.source === 'github-issue' || item.source === 'github-pr')) {\n const suffix = itemSuffix(item.id);\n const kind = item.source === 'github-issue' ? 'issue' : 'pr';\n return suffix ? `factory/${kind}-${providerNumber}-${suffix}` : `factory/${kind}-${providerNumber}`;\n }\n if (\n (item.source === 'linear-issue' || item.source === 'jira-issue' || item.source === 'incidentio-follow-up') &&\n typeof metadata.identifier === 'string'\n ) {\n const identifier = metadata.identifier.trim();\n if (identifier) {\n const provider = item.source === 'linear-issue' ? 'linear' : item.source === 'jira-issue' ? 'jira' : 'incidentio';\n return `factory/${provider}-${identifier.toLowerCase()}`;\n }\n }\n if (item.source === 'gitlab-pr' && providerNumber !== undefined) {\n const uniqueSuffix = itemSuffix(item.id);\n if (uniqueSuffix) return `factory/gitlab-mr-${providerNumber}-${uniqueSuffix}`;\n }\n if (item.source === 'gitlab-issue' && typeof metadata.identifier === 'string') {\n const identifier = metadata.identifier\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-');\n const uniqueSuffix = itemSuffix(item.id);\n if (identifier && uniqueSuffix) return `factory/gitlab-${identifier.slice(0, 60)}-${uniqueSuffix}`;\n }\n return `factory/item-${item.id}`;\n}\n\n/** The pre-suffix GitHub branch, for reusing sessions opened before card names were unique. */\nexport function legacyGithubWorkItemBranch(branch: string): string | undefined {\n const match = /^(factory\\/(?:issue|pr)-[1-9]\\d*)-[a-z0-9]{1,12}$/.exec(branch);\n return match?.[1];\n}\n\n/**\n * The pull request a `factory/pr-<number>-<item suffix>` branch was named after, the\n * inverse of {@link workItemBranch}. Branches from before the suffix (`factory/pr-<number>`)\n * still parse so existing checkouts can resolve their PR.\n */\nexport function pullRequestNumberFromBranch(branch: string): number | undefined {\n const match = /^factory\\/pr-([1-9]\\d*)(?:-[a-z0-9]{1,12})?$/.exec(branch);\n const number = match ? Number(match[1]) : undefined;\n return number !== undefined && Number.isSafeInteger(number) ? number : undefined;\n}\n\n/** The GitLab MR IID encoded in Factory's collision-resistant review branch. */\nexport function mergeRequestNumberFromBranch(branch: string): number | undefined {\n const match = /^factory\\/gitlab-mr-([1-9]\\d*)-[a-z0-9]{1,12}$/.exec(branch);\n const number = match ? Number(match[1]) : undefined;\n return number !== undefined && Number.isSafeInteger(number) ? number : undefined;\n}\n"],"mappings":";;AAyBA,SAAgB,qBAAqB,gBAAiF;CACpH,IAAI,CAAC,gBAAgB,OAAO;CAC5B,IAAI,eAAe,kBAAkB,UAAU,OAAO;CACtD,IAAI,eAAe,kBAAkB,UACnC,OAAO,eAAe,SAAS,iBAAiB,cAAc;CAEhE,IAAI,eAAe,kBAAkB,QAAQ,OAAO;CACpD,IAAI,eAAe,kBAAkB,cAAc,OAAO;CAG1D,IAAI,eAAe,kBAAkB,UAAU,OAAO;CACtD,OAAO,eAAe,SAAS,iBAAiB,cAAc;AAChE;AAEA,SAAS,aAAa,UAAmC,KAAiC;CACxF,MAAM,QAAQ,SAAS,QAAQ,SAAS;CACxC,OAAO,OAAO,UAAU,YAAY,OAAO,UAAU,KAAK,KAAK,QAAQ,IAAI,Q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WAAW,eAAe,mBAAmB,KAAA,GAAW;EAC/D,MAAM,eAAe,WAAW,KAAK,EAAE;EACvC,IAAI,cAAc,OAAO,qBAAqB,eAAe,GAAG;CAClE;CACA,IAAI,KAAK,WAAW,kBAAkB,OAAO,SAAS,eAAe,UAAU;EAC7E,MAAM,aAAa,SAAS,WACzB,KAAK,CAAC,CACN,YAAY,CAAC,CACb,QAAQ,kBAAkB,GAAG;EAChC,MAAM,eAAe,WAAW,KAAK,EAAE;EACvC,IAAI,cAAc,cAAc,OAAO,kBAAkB,WAAW,MAAM,GAAG,EAAE,EAAE,GAAG;CACtF;CACA,OAAO,gBAAgB,KAAK;AAC9B;;AAGA,SAAgB,2BAA2B,QAAoC;CAE7E,OADc,oDAAoD,KAAK,MAC5D,CAAC,GAAG;AACjB;;;;;;AAOA,SAAgB,4BAA4B,QAAoC;CAC9E,MAAM,QAAQ,+CAA+C,KAAK,MAAM;CACxE,MAAM,SAAS,QAAQ,OAAO,MAAM,EAAE,IAAI,KAAA;CAC1C,OAAO,WAAW,KAAA,KAAa,OAAO,cAAc,MAAM,IAAI,SAAS,KAAA;AACzE;;AAGA,SAAgB,6BAA6B,QAAoC;CAC/E,MAAM,QAAQ,iDAAiD,KAAK,MAAM;CAC1E,MAAM,SAAS,QAAQ,OAAO,MAAM,EAAE,IAAI,KAAA;CAC1C,OAAO,WAAW,KAAA,KAAa,OAAO,cAAc,MAAM,IAAI,SAAS,KAAA;AACzE"}
1
+ {"version":3,"file":"work-item-branch.js","names":[],"sources":["../src/work-item-branch.ts"],"sourcesContent":["import type { ExternalWorkItemSource } from './storage/domains/work-items/base.js';\n\n/**\n * Where a card came from, in the vocabulary branch naming reads. Server rows\n * map their `externalSource` into this with {@link workItemBranchSource}; the\n * board's own `WorkItem['source']` is already this union.\n */\nexport type WorkItemBranchSource =\n | 'github-issue'\n | 'github-pr'\n | 'gitlab-issue'\n | 'gitlab-pr'\n | 'linear-issue'\n | 'jira-issue'\n | 'incidentio-follow-up'\n | 'slack-thread'\n | 'manual';\n\nexport interface WorkItemBranchInput {\n id: string;\n source: WorkItemBranchSource;\n metadata?: Record<string, unknown> | null;\n}\n\n/** Map a stored item's provenance onto the source vocabulary branch naming reads. */\nexport function workItemBranchSource(externalSource: ExternalWorkItemSource | null | undefined): WorkItemBranchSource {\n if (!externalSource) return 'manual';\n if (externalSource.integrationId === 'linear') return 'linear-issue';\n if (externalSource.integrationId === 'gitlab') {\n return externalSource.type === 'pull-request' ? 'gitlab-pr' : 'gitlab-issue';\n }\n if (externalSource.integrationId === 'jira') return 'jira-issue';\n if (externalSource.integrationId === 'incidentio') return 'incidentio-follow-up';\n // Only GitHub, GitLab, Linear, Jira, and incident.io carry provider identities; anything\n // else (a Slack thread, say) is a plain work item rather than a mislabeled GitHub issue.\n if (externalSource.integrationId !== 'github') return 'manual';\n return externalSource.type === 'pull-request' ? 'github-pr' : 'github-issue';\n}\n\nfunction branchNumber(metadata: Record<string, unknown>, key: string): number | undefined {\n const value = metadata[key] ?? metadata.number;\n return typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : undefined;\n}\n\n/** The provider number a GitHub card carries — the `#12` its runs and thread titles name it by. */\nexport function workItemNumber(item: Pick<WorkItemBranchInput, 'source' | 'metadata'>): number | undefined {\n const metadata = item.metadata ?? {};\n if (item.source === 'github-issue') return branchNumber(metadata, 'githubIssueNumber');\n if (item.source === 'github-pr') return branchNumber(metadata, 'githubPullRequestNumber');\n if (item.source === 'gitlab-issue') return branchNumber(metadata, 'gitlabIssueIid');\n if (item.source === 'gitlab-pr') return branchNumber(metadata, 'gitlabMergeRequestIid');\n return undefined;\n}\n\n/** How a card names its thread: a Linear title already opens with its identifier, a GitHub card gets its number here. */\nexport function workItemThreadTitle(\n item: Pick<WorkItemBranchInput, 'source' | 'metadata'> & { title: string },\n): string {\n const number = workItemNumber(item);\n if (number === undefined) return item.title;\n const kind = item.source === 'github-pr' ? 'PR' : item.source === 'gitlab-pr' ? 'MR' : 'Issue';\n return `${kind} #${number}: ${item.title}`;\n}\n\n/**\n * The last twelve alphanumerics of a work item id: the per-item suffix that keeps\n * provider numbers from colliding across the repositories of one factory. Issue\n * #13 exists in every repository, and a factory's sessions are unique per\n * user and branch across all of its repositories, so a branch named by the\n * number alone can only be held once per factory.\n */\nfunction itemSuffix(id: string): string {\n return id\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '')\n .slice(-12);\n}\n\n/**\n * The git branch an item's runs and sessions share, one grammar for both sides\n * of the wire: the dispatcher names autonomous run branches with it and the\n * board opens card sessions on it, so both converge on one checkout per item.\n * Provider numbers are only unique within a repository, so GitHub and GitLab\n * branches carry the item suffix as well. Cards without a provider identity\n * (manual, Slack) and cards whose metadata lost their identifier fall back to\n * the id-derived branch.\n */\nexport function workItemBranch(item: WorkItemBranchInput): string {\n const metadata = item.metadata ?? {};\n const providerNumber = workItemNumber(item);\n if (providerNumber !== undefined && (item.source === 'github-issue' || item.source === 'github-pr')) {\n const suffix = itemSuffix(item.id);\n const kind = item.source === 'github-issue' ? 'issue' : 'pr';\n return suffix ? `factory/${kind}-${providerNumber}-${suffix}` : `factory/${kind}-${providerNumber}`;\n }\n if (\n (item.source === 'linear-issue' || item.source === 'jira-issue' || item.source === 'incidentio-follow-up') &&\n typeof metadata.identifier === 'string'\n ) {\n const identifier = metadata.identifier.trim();\n if (identifier) {\n const provider = item.source === 'linear-issue' ? 'linear' : item.source === 'jira-issue' ? 'jira' : 'incidentio';\n return `factory/${provider}-${identifier.toLowerCase()}`;\n }\n }\n if (item.source === 'gitlab-pr' && providerNumber !== undefined) {\n const uniqueSuffix = itemSuffix(item.id);\n if (uniqueSuffix) return `factory/gitlab-mr-${providerNumber}-${uniqueSuffix}`;\n }\n if (item.source === 'gitlab-issue' && typeof metadata.identifier === 'string') {\n const identifier = metadata.identifier\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-');\n const uniqueSuffix = itemSuffix(item.id);\n if (identifier && uniqueSuffix) return `factory/gitlab-${identifier.slice(0, 60)}-${uniqueSuffix}`;\n }\n return `factory/item-${item.id}`;\n}\n\n/**\n * The branch a card's pull or merge request is reviewed on. A PR's own card gets\n * the same name {@link workItemBranch} gives it; an issue card reviewing a PR\n * attached to it gets a branch apart from its builder's issue branch, so the\n * reviewer and the builder never share a checkout.\n */\nexport function pullRequestBranch(input: { id: string; provider: 'github' | 'gitlab'; number: number }): string {\n const suffix = itemSuffix(input.id);\n if (input.provider === 'gitlab') {\n return suffix ? `factory/gitlab-mr-${input.number}-${suffix}` : `factory/item-${input.id}-mr-${input.number}`;\n }\n return suffix ? `factory/pr-${input.number}-${suffix}` : `factory/pr-${input.number}`;\n}\n\n/** The pre-suffix GitHub branch, for reusing sessions opened before card names were unique. */\nexport function legacyGithubWorkItemBranch(branch: string): string | undefined {\n const match = /^(factory\\/(?:issue|pr)-[1-9]\\d*)-[a-z0-9]{1,12}$/.exec(branch);\n return match?.[1];\n}\n\n/**\n * The pull request a `factory/pr-<number>-<item suffix>` branch was named after, the\n * inverse of {@link workItemBranch}. Branches from before the suffix (`factory/pr-<number>`)\n * still parse so existing checkouts can resolve their PR.\n */\nexport function pullRequestNumberFromBranch(branch: string): number | undefined {\n const match = /^factory\\/pr-([1-9]\\d*)(?:-[a-z0-9]{1,12})?$/.exec(branch);\n const number = match ? Number(match[1]) : undefined;\n return number !== undefined && Number.isSafeInteger(number) ? number : undefined;\n}\n\n/** The GitLab MR IID encoded in Factory's collision-resistant review branch. */\nexport function mergeRequestNumberFromBranch(branch: string): number | undefined {\n const match = /^factory\\/gitlab-mr-([1-9]\\d*)-[a-z0-9]{1,12}$/.exec(branch);\n const number = match ? Number(match[1]) : undefined;\n return number !== undefined && Number.isSafeInteger(number) ? number : undefined;\n}\n\n/** Whether a provider-reported branch name is safe to show an agent or pass to git. */\nexport function isSafeBranchName(value: string): boolean {\n return (\n /^[A-Za-z0-9][A-Za-z0-9._/@+-]*$/.test(value) &&\n !value.includes('..') &&\n !value.includes('//') &&\n !value.includes('@{') &&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;CAE7E,OADc,oDAAoD,KAAK,MAC5D,CAAC,GAAG;AACjB;;;;;;AAOA,SAAgB,4BAA4B,QAAoC;CAC9E,MAAM,QAAQ,+CAA+C,KAAK,MAAM;CACxE,MAAM,SAAS,QAAQ,OAAO,MAAM,EAAE,IAAI,KAAA;CAC1C,OAAO,WAAW,KAAA,KAAa,OAAO,cAAc,MAAM,IAAI,SAAS,KAAA;AACzE;;AAGA,SAAgB,6BAA6B,QAAoC;CAC/E,MAAM,QAAQ,iDAAiD,KAAK,MAAM;CAC1E,MAAM,SAAS,QAAQ,OAAO,MAAM,EAAE,IAAI,KAAA;CAC1C,OAAO,WAAW,KAAA,KAAa,OAAO,cAAc,MAAM,IAAI,SAAS,KAAA;AACzE;;AAGA,SAAgB,iBAAiB,OAAwB;CACvD,OACE,kCAAkC,KAAK,KAAK,KAC5C,CAAC,MAAM,SAAS,IAAI,KACpB,CAAC,MAAM,SAAS,IAAI,KACpB,CAAC,MAAM,SAAS,IAAI,KACpB,CAAC,MAAM,SAAS,GAAG,KACnB,CAAC,MAAM,SAAS,GAAG,KACnB,CAAC,MAAM,SAAS,OAAO;AAE3B"}
@@ -10,6 +10,12 @@ import type { CreateWorkItemInput, Card, WorkItemsStorage } from '../storage/dom
10
10
  /** Records one audit event for the caller; routes bind it to the request, tools to the session's person. */
11
11
  export type FactoryAuditEmit = (input: EmitAuditInput) => Promise<void>;
12
12
  type TransitionResult = Awaited<ReturnType<FactoryTransitionService['transition']>>;
13
+ /**
14
+ * Board metadata key holding the `#number` of a card filed without an issue
15
+ * behind it. Kept apart from `number`, which integrations read as the source
16
+ * issue's number.
17
+ */
18
+ export declare const CARD_NUMBER_METADATA_KEY = "cardNumber";
13
19
  export type CreateFactoryWorkItemResult =
14
20
  /** A new card, entered into its board's first phase and audited. */
15
21
  {
@@ -1 +1 @@
1
- {"version":3,"file":"create-work-item.d.ts","sourceRoot":"","sources":["../../src/work-items/create-work-item.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAG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,CAAC,2BAA2B,CAAC,CA6JlE"}
@@ -1,3 +1,4 @@
1
+ import "../boards/default-board.js";
1
2
  import "../boards/index.js";
2
3
  import { cardRuleFacts } from "../boards/card-facts.js";
3
4
  import { INTAKE_ROUTE_METADATA_KEY, resolveIntakePlacement } from "../boards/intake-routing.js";
@@ -10,6 +11,24 @@ import { WorkItemUpdateConflictError } from "../storage/domains/work-items/base.
10
11
  /** Attempts at each step after the upsert before a card that keeps changing under its creator is left as is. */
11
12
  const STEP_ATTEMPTS = 3;
12
13
  /**
14
+ * Board metadata key holding the `#number` of a card filed without an issue
15
+ * behind it. Kept apart from `number`, which integrations read as the source
16
+ * issue's number.
17
+ */
18
+ const CARD_NUMBER_METADATA_KEY = "cardNumber";
19
+ /** One past the highest number given to a manually filed card in the project. */
20
+ async function nextCardNumber(workItems, orgId, factoryProjectId) {
21
+ let highest = 0;
22
+ for (const card of await workItems.listShared({
23
+ orgId,
24
+ factoryProjectId
25
+ })) {
26
+ const number = card.metadata?.[CARD_NUMBER_METADATA_KEY];
27
+ if (typeof number === "number" && number > highest) highest = number;
28
+ }
29
+ return highest + 1;
30
+ }
31
+ /**
13
32
  * Upserts the card into its board's first phase, enters that phase as the
14
33
  * person (rolling the card back if its entry rules refuse it), then audits
15
34
  * `factory.work_item.created`. Throws `WorkItemRelationError` for a bad parent.
@@ -37,12 +56,17 @@ async function createFactoryWorkItem({ workItems, boards, transitionService, aud
37
56
  message: `New work items must enter through the '${board.initialPhase}' phase of board '${boardId}'.`
38
57
  };
39
58
  await workItems.ensureReady();
59
+ const metadata = input.externalSource ? input.metadata : {
60
+ ...input.metadata,
61
+ [CARD_NUMBER_METADATA_KEY]: await nextCardNumber(workItems, orgId, factoryProjectId)
62
+ };
40
63
  const result = await workItems.upsert({
41
64
  orgId,
42
65
  userId,
43
66
  factoryProjectId,
44
67
  input: {
45
68
  ...input,
69
+ ...metadata ? { metadata } : {},
46
70
  board: boardId,
47
71
  stages: initialStages
48
72
  },
@@ -184,6 +208,6 @@ async function createFactoryWorkItem({ workItems, boards, transitionService, aud
184
208
  item
185
209
  };
186
210
  }
187
- export { createFactoryWorkItem };
211
+ export { CARD_NUMBER_METADATA_KEY, createFactoryWorkItem };
188
212
 
189
213
  //# sourceMappingURL=create-work-item.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"create-work-item.js","names":[],"sources":["../../src/work-items/create-work-item.ts"],"sourcesContent":["/**\n * Filing a work item, shared by the board's create route and the Factory tools\n * so a card filed from a session goes through exactly what \"New card\" does.\n */\n\nimport { cardRuleFacts } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { INTAKE_ROUTE_METADATA_KEY, resolveIntakePlacement } from '../boards/intake-routing.js';\nimport type { IntakeRoutesReader } from '../boards/intake-routing.js';\nimport type { FactoryTransitionRequest, FactoryTransitionService } from '../rules/transition-service.js';\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { CreateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\n/** Records one audit event for the caller; routes bind it to the request, tools to the session's person. */\nexport type FactoryAuditEmit = (input: EmitAuditInput) => Promise<void>;\n\ntype TransitionResult = Awaited<ReturnType<FactoryTransitionService['transition']>>;\n\n/** Attempts at each step after the upsert before a card that keeps changing under its creator is left as is. */\nconst STEP_ATTEMPTS = 3;\n\nexport type CreateFactoryWorkItemResult =\n /** A new card, entered into its board's first phase and audited. */\n | { status: 'created'; item: Card }\n /** The source key matched an existing card, which was updated instead (the caller audits the patch). */\n | { status: 'reused'; item: Card }\n | {\n status: 'refused';\n code: 'invalid_board' | 'governed_transition_required' | 'factory_transitions_unavailable';\n message: string;\n }\n /** The first phase's entry rules (or the move to an intake route's phase) refused the card; it was removed again unless a concurrent create had already reused it. */\n | { status: 'rejected'; code: Extract<TransitionResult, { status: 'rejected' }>['code']; reason: string };\n\nexport interface CreateFactoryWorkItemArgs {\n workItems: WorkItemsStorage;\n boards: BoardRegistry;\n transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;\n audit: FactoryAuditEmit;\n orgId: string;\n /** Who files the card; becomes its `created_by` and the human actor of its first phase entry. */\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n /** The project's intake routes; they place a card filed without a board or stages. */\n intakeRoutes?: IntakeRoutesReader;\n /** Where a browser request came from; a session's tool call carries none. */\n origin?: Pick<FactoryTransitionRequest, 'actorProfile' | 'context'>;\n}\n\n/**\n * Upserts the card into its board's first phase, enters that phase as the\n * person (rolling the card back if its entry rules refuse it), then audits\n * `factory.work_item.created`. Throws `WorkItemRelationError` for a bad parent.\n */\nexport async function createFactoryWorkItem({\n workItems,\n boards,\n transitionService,\n audit,\n orgId,\n userId,\n factoryProjectId,\n input,\n intakeRoutes,\n origin,\n}: CreateFactoryWorkItemArgs): Promise<CreateFactoryWorkItemResult> {\n // A card filed without a board or stages goes where the project's intake routes say; one\n // that names either went where the person chose.\n const placement =\n intakeRoutes && input.board === undefined && input.stages === undefined\n ? resolveIntakePlacement(\n await intakeRoutes.listIntakeRoutes({ orgId, factoryProjectId }),\n cardRuleFacts({\n title: input.title,\n metadata: input.metadata ?? null,\n externalSource: input.externalSource ?? null,\n }),\n boards,\n )\n : undefined;\n const boardId = placement?.board ?? input.board ?? 'work';\n const board = boards.get(boardId);\n if (!board) return { status: 'refused', code: 'invalid_board', message: `Board '${boardId}' is not installed.` };\n const initialStages = input.stages ?? [board.initialPhase];\n if (initialStages.length !== 1 || initialStages[0] !== board.initialPhase) {\n return {\n status: 'refused',\n code: 'governed_transition_required',\n message: `New work items must enter through the '${board.initialPhase}' phase of board '${boardId}'.`,\n };\n }\n\n await workItems.ensureReady();\n const result = await workItems.upsert({\n orgId,\n userId,\n factoryProjectId,\n input: {\n ...input,\n board: boardId,\n stages: initialStages,\n },\n reuseMode: 'non-stage',\n });\n // A reused card keeps its own placement, so only a card this call created records the route.\n if (!result.created) return { status: 'reused', item: result.item };\n\n const id = result.item.id;\n // A concurrent create for the same source can reuse this card at any step below. That caller\n // has already returned it as `reused`, so a step that loses the revision race is retried at the\n // current revision, and the card is never rolled back once anyone else has touched it. A reuse\n // that only refreshes source facts keeps the revision but moves `updatedAt`, so the rollback\n // deletes only while both still match this call's last write.\n let revision: number | undefined = result.item.revision;\n let updatedAt = result.item.updatedAt;\n let contended = false;\n const reread = async () => {\n contended = true;\n revision = (await workItems.getForProject(orgId, factoryProjectId, id))?.revision;\n };\n const rollBack = async () => {\n if (contended || revision === undefined) return;\n await workItems.delete({ orgId, id, expectedRevision: revision, expectedUpdatedAt: updatedAt });\n };\n const notFound = { status: 'rejected', code: 'invalid_transition', reason: 'Work item not found.' } as const;\n\n if (placement) {\n for (let attempt = 1; revision !== undefined; attempt++) {\n try {\n const stamped = await workItems.update({\n orgId,\n id,\n userId,\n patch: { metadata: { [INTAKE_ROUTE_METADATA_KEY]: placement.routeId } },\n expectedRevision: revision,\n });\n revision = stamped?.item.revision;\n if (stamped) updatedAt = stamped.item.updatedAt;\n break;\n } catch (error) {\n const stale = error instanceof WorkItemUpdateConflictError && error.reason === 'revision';\n if (!stale || attempt >= STEP_ATTEMPTS) throw error;\n await reread();\n }\n }\n if (revision === undefined) return notFound;\n }\n if (!transitionService) {\n await rollBack();\n return {\n status: 'refused',\n code: 'factory_transitions_unavailable',\n message: 'Factory stage transitions are not available right now.',\n };\n }\n const transition = async (\n request: Omit<FactoryTransitionRequest, 'expectedRevision'>,\n ): Promise<TransitionResult | undefined> => {\n for (let attempt = 1; revision !== undefined; attempt++) {\n const transitioned = await transitionService.transition({ ...request, expectedRevision: revision });\n // The result carries no timestamp, so `updatedAt` stays at the last write this call saw; the\n // commit has moved the card past it, so a later rollback keeps the card instead of guessing.\n if (transitioned.status === 'accepted') revision = transitioned.revision;\n if (transitioned.status !== 'rejected' || transitioned.code !== 'stale' || attempt >= STEP_ATTEMPTS) {\n return transitioned;\n }\n await reread();\n }\n return undefined;\n };\n\n const entered = await transition({\n orgId,\n factoryProjectId,\n workItemId: id,\n board: boardId,\n stage: board.initialPhase,\n actor: { type: 'human', id: userId },\n ...origin,\n ingress: { type: 'human', identity: `work-item:${id}:initial-entry` },\n cause: 'work_item_created',\n initialEntry: true,\n });\n if (!entered) return notFound;\n if (entered.status === 'rejected') {\n await rollBack();\n return { status: 'rejected', code: entered.code, reason: entered.reason };\n }\n if (placement && placement.phase !== board.initialPhase) {\n const moved = await transition({\n orgId,\n factoryProjectId,\n workItemId: id,\n board: boardId,\n stage: placement.phase,\n // The route moves the card, not the person: a run it starts still needs their consent.\n actor: { type: 'system', id: 'factory-intake-route' },\n ingress: { type: 'rule', identity: `work-item:${id}:intake-route` },\n cause: 'work_item_created',\n });\n if (!moved) return notFound;\n if (moved.status === 'rejected') {\n await rollBack();\n return { status: 'rejected', code: moved.code, reason: moved.reason };\n }\n }\n const item = (await workItems.getForProject(orgId, factoryProjectId, id)) ?? result.item;\n await audit({\n action: 'factory.work_item.created',\n factoryProjectId,\n targets: [{ type: 'work_item', id: item.id, name: item.title }],\n metadata: { externalSource: item.externalSource, stages: item.stages },\n });\n return { status: 'created', item };\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,gBAAgB;;;;;;AAoCtB,eAAsB,sBAAsB,EAC1C,WACA,QACA,mBACA,OACA,OACA,QACA,kBACA,OACA,cACA,UACkE;CAGlE,MAAM,YACJ,gBAAgB,MAAM,UAAU,KAAA,KAAa,MAAM,WAAW,KAAA,IAC1D,uBACE,MAAM,aAAa,iBAAiB;EAAE;EAAO;CAAiB,CAAC,GAC/D,cAAc;EACZ,OAAO,MAAM;EACb,UAAU,MAAM,YAAY;EAC5B,gBAAgB,MAAM,kBAAkB;CAC1C,CAAC,GACD,MACF,IACA,KAAA;CACN,MAAM,UAAU,WAAW,SAAS,MAAM,SAAS;CACnD,MAAM,QAAQ,OAAO,IAAI,OAAO;CAChC,IAAI,CAAC,OAAO,OAAO;EAAE,QAAQ;EAAW,MAAM;EAAiB,SAAS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F;CACA,MAAM,OAAQ,MAAM,UAAU,cAAc,OAAO,kBAAkB,EAAE,KAAM,OAAO;CACpF,MAAM,MAAM;EACV,QAAQ;EACR;EACA,SAAS,CAAC;GAAE,MAAM;GAAa,IAAI,KAAK;GAAI,MAAM,KAAK;EAAM,CAAC;EAC9D,UAAU;GAAE,gBAAgB,KAAK;GAAgB,QAAQ,KAAK;EAAO;CACvE,CAAC;CACD,OAAO;EAAE,QAAQ;EAAW;CAAK;AACnC"}
1
+ {"version":3,"file":"create-work-item.js","names":[],"sources":["../../src/work-items/create-work-item.ts"],"sourcesContent":["/**\n * Filing a work item, shared by the board's create route and the Factory tools\n * so a card filed from a session goes through exactly what \"New card\" does.\n */\n\nimport { DEFAULT_BOARD_ID } from '../boards/default-board.js';\nimport { cardRuleFacts } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { INTAKE_ROUTE_METADATA_KEY, resolveIntakePlacement } from '../boards/intake-routing.js';\nimport type { IntakeRoutesReader } from '../boards/intake-routing.js';\nimport type { FactoryTransitionRequest, FactoryTransitionService } from '../rules/transition-service.js';\nimport type { EmitAuditInput } from '../storage/domains/audit/domain.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { CreateWorkItemInput, Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\n/** Records one audit event for the caller; routes bind it to the request, tools to the session's person. */\nexport type FactoryAuditEmit = (input: EmitAuditInput) => Promise<void>;\n\ntype TransitionResult = Awaited<ReturnType<FactoryTransitionService['transition']>>;\n\n/** Attempts at each step after the upsert before a card that keeps changing under its creator is left as is. */\nconst STEP_ATTEMPTS = 3;\n\n/**\n * Board metadata key holding the `#number` of a card filed without an issue\n * behind it. Kept apart from `number`, which integrations read as the source\n * issue's number.\n */\nexport const CARD_NUMBER_METADATA_KEY = 'cardNumber';\n\n/** One past the highest number given to a manually filed card in the project. */\nasync function nextCardNumber(workItems: WorkItemsStorage, orgId: string, factoryProjectId: string): Promise<number> {\n let highest = 0;\n for (const card of await workItems.listShared({ orgId, factoryProjectId })) {\n const number = card.metadata?.[CARD_NUMBER_METADATA_KEY];\n if (typeof number === 'number' && number > highest) highest = number;\n }\n return highest + 1;\n}\n\nexport type CreateFactoryWorkItemResult =\n /** A new card, entered into its board's first phase and audited. */\n | { status: 'created'; item: Card }\n /** The source key matched an existing card, which was updated instead (the caller audits the patch). */\n | { status: 'reused'; item: Card }\n | {\n status: 'refused';\n code: 'invalid_board' | 'governed_transition_required' | 'factory_transitions_unavailable';\n message: string;\n }\n /** The first phase's entry rules (or the move to an intake route's phase) refused the card; it was removed again unless a concurrent create had already reused it. */\n | { status: 'rejected'; code: Extract<TransitionResult, { status: 'rejected' }>['code']; reason: string };\n\nexport interface CreateFactoryWorkItemArgs {\n workItems: WorkItemsStorage;\n boards: BoardRegistry;\n transitionService: Pick<FactoryTransitionService, 'transition'> | undefined;\n audit: FactoryAuditEmit;\n orgId: string;\n /** Who files the card; becomes its `created_by` and the human actor of its first phase entry. */\n userId: string;\n factoryProjectId: string;\n input: CreateWorkItemInput;\n /** The project's intake routes; they place a card filed without a board or stages. */\n intakeRoutes?: IntakeRoutesReader;\n /** Where a browser request came from; a session's tool call carries none. */\n origin?: Pick<FactoryTransitionRequest, 'actorProfile' | 'context'>;\n}\n\n/**\n * Upserts the card into its board's first phase, enters that phase as the\n * person (rolling the card back if its entry rules refuse it), then audits\n * `factory.work_item.created`. Throws `WorkItemRelationError` for a bad parent.\n */\nexport async function createFactoryWorkItem({\n workItems,\n boards,\n transitionService,\n audit,\n orgId,\n userId,\n factoryProjectId,\n input,\n intakeRoutes,\n origin,\n}: CreateFactoryWorkItemArgs): Promise<CreateFactoryWorkItemResult> {\n // A card filed without a board or stages goes where the project's intake routes say; one\n // that names either went where the person chose.\n const placement =\n intakeRoutes && input.board === undefined && input.stages === undefined\n ? resolveIntakePlacement(\n await intakeRoutes.listIntakeRoutes({ orgId, factoryProjectId }),\n cardRuleFacts({\n title: input.title,\n metadata: input.metadata ?? null,\n externalSource: input.externalSource ?? null,\n }),\n boards,\n )\n : undefined;\n const boardId = placement?.board ?? input.board ?? DEFAULT_BOARD_ID;\n const board = boards.get(boardId);\n if (!board) return { status: 'refused', code: 'invalid_board', message: `Board '${boardId}' is not installed.` };\n const initialStages = input.stages ?? [board.initialPhase];\n if (initialStages.length !== 1 || initialStages[0] !== board.initialPhase) {\n return {\n status: 'refused',\n code: 'governed_transition_required',\n message: `New work items must enter through the '${board.initialPhase}' phase of board '${boardId}'.`,\n };\n }\n\n await workItems.ensureReady();\n // A card with no issue behind it has no number of its own, so it gets the project's next one.\n const metadata = input.externalSource\n ? input.metadata\n : {\n ...input.metadata,\n [CARD_NUMBER_METADATA_KEY]: await nextCardNumber(workItems, orgId, factoryProjectId),\n };\n const result = await workItems.upsert({\n orgId,\n userId,\n factoryProjectId,\n input: {\n ...input,\n ...(metadata ? { metadata } : {}),\n board: boardId,\n stages: initialStages,\n },\n reuseMode: 'non-stage',\n });\n // A reused card keeps its own placement, so only a card this call created records the route.\n if (!result.created) return { status: 'reused', item: result.item };\n\n const id = result.item.id;\n // A concurrent create for the same source can reuse this card at any step below. That caller\n // has already returned it as `reused`, so a step that loses the revision race is retried at the\n // current revision, and the card is never rolled back once anyone else has touched it. A reuse\n // that only refreshes source facts keeps the revision but moves `updatedAt`, so the rollback\n // deletes only while both still match this call's last write.\n let revision: number | undefined = result.item.revision;\n let updatedAt = result.item.updatedAt;\n let contended = false;\n const reread = async () => {\n contended = true;\n revision = (await workItems.getForProject(orgId, factoryProjectId, id))?.revision;\n };\n const rollBack = async () => {\n if (contended || revision === undefined) return;\n await workItems.delete({ orgId, id, expectedRevision: revision, expectedUpdatedAt: updatedAt });\n };\n const notFound = { status: 'rejected', code: 'invalid_transition', reason: 'Work item not found.' } as const;\n\n if (placement) {\n for (let attempt = 1; revision !== undefined; attempt++) {\n try {\n const stamped = await workItems.update({\n orgId,\n id,\n userId,\n patch: { metadata: { [INTAKE_ROUTE_METADATA_KEY]: placement.routeId } },\n expectedRevision: revision,\n });\n revision = stamped?.item.revision;\n if (stamped) updatedAt = stamped.item.updatedAt;\n break;\n } catch (error) {\n const stale = error instanceof WorkItemUpdateConflictError && error.reason === 'revision';\n if (!stale || attempt >= STEP_ATTEMPTS) throw error;\n await reread();\n }\n }\n if (revision === undefined) return notFound;\n }\n if (!transitionService) {\n await rollBack();\n return {\n status: 'refused',\n code: 'factory_transitions_unavailable',\n message: 'Factory stage transitions are not available right now.',\n };\n }\n const transition = async (\n request: Omit<FactoryTransitionRequest, 'expectedRevision'>,\n ): Promise<TransitionResult | undefined> => {\n for (let attempt = 1; revision !== undefined; attempt++) {\n const transitioned = await transitionService.transition({ ...request, expectedRevision: revision });\n // The result carries no timestamp, so `updatedAt` stays at the last write this call saw; the\n // commit has moved the card past it, so a later rollback keeps the card instead of guessing.\n if (transitioned.status === 'accepted') revision = transitioned.revision;\n if (transitioned.status !== 'rejected' || transitioned.code !== 'stale' || attempt >= STEP_ATTEMPTS) {\n return transitioned;\n }\n await reread();\n }\n return undefined;\n };\n\n const entered = await transition({\n orgId,\n factoryProjectId,\n workItemId: id,\n board: boardId,\n stage: board.initialPhase,\n actor: { type: 'human', id: userId },\n ...origin,\n ingress: { type: 'human', identity: `work-item:${id}:initial-entry` },\n cause: 'work_item_created',\n initialEntry: true,\n });\n if (!entered) return notFound;\n if (entered.status === 'rejected') {\n await rollBack();\n return { status: 'rejected', code: entered.code, reason: entered.reason };\n }\n if (placement && placement.phase !== board.initialPhase) {\n const moved = await transition({\n orgId,\n factoryProjectId,\n workItemId: id,\n board: boardId,\n stage: placement.phase,\n // The route moves the card, not the person: a run it starts still needs their consent.\n actor: { type: 'system', id: 'factory-intake-route' },\n ingress: { type: 'rule', identity: `work-item:${id}:intake-route` },\n cause: 'work_item_created',\n });\n if (!moved) return notFound;\n if (moved.status === 'rejected') {\n await rollBack();\n return { status: 'rejected', code: moved.code, reason: moved.reason };\n }\n }\n const item = (await workItems.getForProject(orgId, factoryProjectId, id)) ?? result.item;\n await audit({\n action: 'factory.work_item.created',\n factoryProjectId,\n targets: [{ type: 'work_item', id: item.id, name: item.title }],\n metadata: { externalSource: item.externalSource, stages: item.stages },\n });\n return { status: 'created', item };\n}\n"],"mappings":";;;;;;;;;;;AAqBA,MAAM,gBAAgB;;;;;;AAOtB,MAAa,2BAA2B;;AAGxC,eAAe,eAAe,WAA6B,OAAe,kBAA2C;CACnH,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,MAAM,UAAU,WAAW;EAAE;EAAO;CAAiB,CAAC,GAAG;EAC1E,MAAM,SAAS,KAAK,WAAW;EAC/B,IAAI,OAAO,WAAW,YAAY,SAAS,SAAS,UAAU;CAChE;CACA,OAAO,UAAU;AACnB;;;;;;AAoCA,eAAsB,sBAAsB,EAC1C,WACA,QACA,mBACA,OACA,OACA,QACA,kBACA,OACA,cACA,UACkE;CAGlE,MAAM,YACJ,gBAAgB,MAAM,UAAU,KAAA,KAAa,MAAM,WAAW,KAAA,IAC1D,uBACE,MAAM,aAAa,iBAAiB;EAAE;EAAO;CAAiB,CAAC,GAC/D,cAAc;EACZ,OAAO,MAAM;EACb,UAAU,MAAM,YAAY;EAC5B,gBAAgB,MAAM,kBAAkB;CAC1C,CAAC,GACD,MACF,IACA,KAAA;CACN,MAAM,UAAU,WAAW,SAAS,MAAM,SAAA;CAC1C,MAAM,QAAQ,OAAO,IAAI,OAAO;CAChC,IAAI,CAAC,OAAO,OAAO;EAAE,QAAQ;EAAW,MAAM;EAAiB,SAAS,UAAU,QAAQ;CAAqB;CAC/G,MAAM,gBAAgB,MAAM,UAAU,CAAC,MAAM,YAAY;CACzD,IAAI,cAAc,WAAW,KAAK,cAAc,OAAO,MAAM,cAC3D,OAAO;EACL,QAAQ;EACR,MAAM;EACN,SAAS,0CAA0C,MAAM,aAAa,oBAAoB,QAAQ;CACpG;CAGF,MAAM,UAAU,YAAY;CAE5B,MAAM,WAAW,MAAM,iBACnB,MAAM,WACN;EACE,GAAG,M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;IACrD,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,+EAA+E;IAC/E,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB,6EAA6E;IAC7E,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,aAAa,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7D,uFAAuF;IACvF,KAAK,CAAC,EAAE,eAAe,GAAG,IAAI,CAAC;IAC/B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0EAA0E;IAC1E,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,mFAAmF;AACnF,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,KAAK,GAAG,iBAAiB,CAAC,EACxD,EACE,MAAc,EACd,GAAiB,EACjB,GAAG,EACH,OAAO,EACP,KAAK,EACL,QAAoB,EACpB,MAAM,EACN,KAAK,EACL,kBAA6C,EAC7C,GAAc,GACf,GAAE,2BAAgC,GAClC,OAAO,CAAC,mBAAmB,CAAC,CAqH9B"}
@@ -92,6 +92,7 @@ function splitLegacyWorkItem(row, { workItemId, revision }) {
92
92
  labels: provider.labels,
93
93
  author: provider.author,
94
94
  metadata: metadata.provider,
95
+ role: "origin",
95
96
  revision: 1,
96
97
  synced_at: null,
97
98
  created_at: row.created_at,
@@ -1 +1 @@
1
- {"version":3,"file":"split-migration.js","names":[],"sources":["../../src/work-items/split-migration.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionValue, FactoryStorage, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { factoryDecisionHash } from '../storage/domains/work-items/base.js';\nimport type { WorkItemDbRow } from '../storage/domains/work-items/base.js';\nimport { bumpBoardVersions } from '../storage/domains/work-items/board-version.js';\nimport type { BoardScope } from '../storage/domains/work-items/board-version.js';\nimport {\n WORK_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport type {\n BoardItemDbRecord,\n WorkItemDbRecord,\n WorkItemSourceDbRecord,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport { splitCardMetadata, workItemProviderAdapter } from './providers/index.js';\n\nconst LEGACY = WORK_ITEMS_SCHEMA.name;\nconst WORK_ITEMS = FACTORY_WORK_ITEMS_SCHEMA.name;\nconst SOURCES = FACTORY_WORK_ITEM_SOURCES_SCHEMA.name;\nconst BOARD_ITEMS = FACTORY_BOARD_ITEMS_SCHEMA.name;\nconst PAGE_SIZE = 200;\nconst LOGGED_SKIPS = 10;\nconst PROGRESS_LOG_INTERVAL_MS = 10_000;\n\nconst fmt = (value: number) => value.toLocaleString('en-US');\n\n/** One line: skips repeat while an older replica keeps writing, so only a sample is named. */\nfunction summaryLine(title: string, report: WorkItemSplitReport): string {\n const counts = [\n `${fmt(report.cards)} cards checked`,\n `${fmt(report.workItems)} copied`,\n `${fmt(report.recopied)} recopied`,\n `${fmt(report.unchanged)} unchanged`,\n `${fmt(report.deferred)} deferred`,\n `${fmt(report.skipped.length)} skipped`,\n ];\n if (report.aborted) counts.push('stopped early');\n let line = `${title}: ${counts.join(', ')}`;\n if (report.skipped.length) {\n const sample = report.skipped\n .slice(0, LOGGED_SKIPS)\n .map(skip => `${skip.id} (${skip.reason.replace(/\\s+/g, ' ')})`);\n const more = report.skipped.length - sample.length;\n line += ` — ${sample.join('; ')}${more ? `; and ${fmt(more)} more` : ''}`;\n }\n return line;\n}\n\nexport interface MigratedBoardItem {\n workItemId: string;\n revision: number;\n updatedAt: Date;\n migratedFromUpdatedAt: Date | null;\n migratedFromHash: string | null;\n}\n\nexport interface WorkItemSplitCard {\n /** Fingerprint observed when planning; rejects a stale migration plan under the row lock. */\n previousHash?: string | null;\n workItem: WorkItemDbRecord;\n source: WorkItemSourceDbRecord | null;\n boardItem: BoardItemDbRecord;\n}\n\nexport interface WorkItemSplitSkip {\n id: string;\n reason: string;\n}\n\nexport interface WorkItemSplitPlan {\n inserts: WorkItemSplitCard[];\n recopies: WorkItemSplitCard[];\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n}\n\nexport interface WorkItemSplitReport {\n dryRun: boolean;\n projects: number;\n cards: number;\n /** Rows the `include` filter left for a later pass. */\n deferred: number;\n workItems: number;\n sources: number;\n boardItems: number;\n recopied: number;\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n aborted: boolean;\n}\n\nfunction time(value: Date | string | null | undefined): number {\n return value ? new Date(value).getTime() : Number.NEGATIVE_INFINITY;\n}\n\nfunction legacyHash(row: WorkItemDbRow): string {\n const copied = {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: row.factory_project_id,\n board: row.board,\n external_source: row.external_source,\n parent_work_item_id: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n triage_type: row.triage_type,\n accepted_at: row.accepted_at,\n autonomy_armed_at: row.autonomy_armed_at,\n plans_preapproved_at: row.plans_preapproved_at,\n revision: row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n // stableJson does not invoke Date.toJSON; normalize before hashing.\n return factoryDecisionHash(JSON.parse(JSON.stringify(copied)));\n}\n\nexport function splitLegacyWorkItem(\n row: WorkItemDbRow,\n { workItemId, revision }: { workItemId: string; revision?: number },\n): WorkItemSplitCard {\n const adapter = workItemProviderAdapter(row.external_source ?? null);\n const provider = adapter.toSource(row.external_source ?? null, row.metadata);\n const metadata = splitCardMetadata(row.metadata, adapter.providerMetadataKeys);\n return {\n workItem: {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n title: row.title,\n parent_work_item_id: null,\n revision: 1,\n created_at: row.created_at,\n updated_at: row.updated_at,\n },\n source: provider\n ? {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n provider: provider.provider,\n integration_id: provider.integrationId,\n source_type: provider.sourceType,\n workspace_id: provider.workspaceId,\n external_id: provider.externalId,\n source_key: provider.sourceKey,\n url: provider.url,\n key: provider.key,\n state: provider.state,\n labels: provider.labels,\n author: provider.author,\n metadata: metadata.provider,\n revision: 1,\n synced_at: null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n }\n : null,\n boardItem: {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n board: row.board ?? null,\n parent_board_item_id: row.parent_work_item_id ?? null,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: metadata.board,\n triage_type: row.triage_type ?? null,\n accepted_at: row.accepted_at ?? null,\n autonomy_armed_at: row.autonomy_armed_at ?? null,\n plans_preapproved_at: row.plans_preapproved_at ?? null,\n comment_count: row.comment_count ?? 0,\n // The first recount must be able to correct a copied legacy count.\n feed_activity_at: null,\n revision: revision ?? row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n migrated_from_updated_at: row.updated_at,\n migrated_from_hash: legacyHash(row),\n },\n };\n}\n\nexport function planWorkItemSplit(\n rows: readonly WorkItemDbRow[],\n migrated: ReadonlyMap<string, MigratedBoardItem> = new Map(),\n newId: () => string = randomUUID,\n): WorkItemSplitPlan {\n const plan: WorkItemSplitPlan = { inserts: [], recopies: [], unchanged: 0, skipped: [] };\n for (const row of rows) {\n const existing = migrated.get(row.id);\n if (existing?.migratedFromHash === legacyHash(row)) {\n plan.unchanged += 1;\n continue;\n }\n if (existing && time(existing.updatedAt) > time(existing.migratedFromUpdatedAt)) {\n plan.skipped.push({ id: row.id, reason: 'Split board item changed after migration' });\n continue;\n }\n try {\n const card = splitLegacyWorkItem(row, {\n workItemId: existing?.workItemId ?? newId(),\n ...(existing ? { revision: Math.max(existing.revision, row.revision) + 1 } : {}),\n });\n if (existing) card.previousHash = existing.migratedFromHash;\n (existing ? plan.recopies : plan.inserts).push(card);\n } catch (error) {\n plan.skipped.push({ id: row.id, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n return plan;\n}\n\nasync function migratedBoardItems(\n ops: FactoryStorageOps,\n ids: readonly string[],\n): Promise<Map<string, MigratedBoardItem>> {\n if (!ids.length) return new Map();\n const rows = await ops.findMany<BoardItemDbRecord>(BOARD_ITEMS, { id: { in: [...ids] } });\n return new Map(\n rows.map(row => [\n row.id,\n {\n workItemId: row.work_item_id,\n revision: row.revision,\n updatedAt: row.updated_at,\n migratedFromUpdatedAt: row.migrated_from_updated_at,\n migratedFromHash: row.migrated_from_hash,\n },\n ]),\n );\n}\n\nclass MigrationConflict extends Error {}\n\nasync function writeCard(ops: FactoryStorageOps, card: WorkItemSplitCard, recopy: boolean): Promise<boolean> {\n if (!recopy) {\n // Both paths take this card-specific lock before any card rows. A project-wide\n // lock here would invert the row-lock order of parent/child and bulk deletions.\n const guard = await ops.updateAtomic(\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name,\n { id: card.boardItem.id },\n () => null,\n );\n if (!guard)\n await ops.insertOne(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, {\n id: card.boardItem.id,\n org_id: card.boardItem.org_id,\n factory_project_id: card.boardItem.factory_project_id,\n });\n if (await ops.findOne(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, { id: card.boardItem.id })) return false;\n const existing = await ops.findOne<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id });\n if (existing) {\n if (existing.migrated_from_hash === card.boardItem.migrated_from_hash) return false;\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n await ops.insertOne<WorkItemDbRecord>(WORK_ITEMS, card.workItem);\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n await ops.insertOne<BoardItemDbRecord>(BOARD_ITEMS, card.boardItem);\n return true;\n }\n // updateAtomic locks the board row until this transaction commits, so a new\n // transition cannot land between the overwrite guard and the copy.\n let unchanged = false;\n let baseline = Number.NEGATIVE_INFINITY;\n const board = await ops.updateAtomic<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id }, current => {\n if (current.migrated_from_hash === card.boardItem.migrated_from_hash) {\n unchanged = true;\n return null;\n }\n if (current.migrated_from_hash !== card.previousHash) {\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n if (time(current.updated_at) > time(current.migrated_from_updated_at)) {\n throw new MigrationConflict('Split board item changed after migration');\n }\n baseline = time(current.migrated_from_updated_at);\n return {\n ...card.boardItem,\n ...(current.feed_activity_at\n ? { comment_count: current.comment_count, feed_activity_at: current.feed_activity_at }\n : {}),\n revision: Math.max(current.revision, card.boardItem.revision) + 1,\n };\n });\n if (unchanged) return false;\n if (!board) throw new MigrationConflict('Split board item disappeared during migration');\n await ops.updateAtomic<WorkItemDbRecord>(WORK_ITEMS, { id: card.workItem.id }, current => {\n if (time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split work item changed after migration');\n }\n return { ...card.workItem, revision: current.revision + 1 };\n });\n const sources = await ops.findMany<WorkItemSourceDbRecord>(SOURCES, { work_item_id: card.workItem.id });\n if (sources.some(source => source.id !== card.workItem.id)) {\n throw new MigrationConflict('Split source set changed after migration');\n }\n for (const source of sources) {\n await ops.updateAtomic<WorkItemSourceDbRecord>(SOURCES, { id: source.id }, current => {\n if (current.synced_at != null || time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split source changed after migration');\n }\n return null;\n });\n }\n if (sources.length) await ops.deleteMany(SOURCES, { id: { in: sources.map(source => source.id) } });\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n return true;\n}\n\nexport interface LegacyWatermark {\n updatedAt: Date;\n id: string;\n}\n\nexport interface WorkItemSplitMarker {\n /** Newest legacy row when the finished pass began; null when the legacy table was empty. */\n watermark: LegacyWatermark | null;\n completedAt: Date;\n}\n\nconst SPLIT_STATE = FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA.name;\nconst SPLIT_MARKER_ID = 'work_item_split';\n\n/** The newest legacy write, by `(updated_at, id)`; one indexed row. */\nexport async function readLegacyWatermark(ops: FactoryStorageOps): Promise<LegacyWatermark | null> {\n const [row] = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: 1,\n },\n );\n return row ? { updatedAt: row.updated_at, id: row.id } : null;\n}\n\nexport async function readWorkItemSplitMarker(ops: FactoryStorageOps): Promise<WorkItemSplitMarker | null> {\n const row = await ops.findOne<{ legacy_updated_at: Date | null; legacy_id: string | null; completed_at: Date }>(\n SPLIT_STATE,\n { id: SPLIT_MARKER_ID },\n );\n if (!row) return null;\n return {\n watermark: row.legacy_updated_at && row.legacy_id ? { updatedAt: row.legacy_updated_at, id: row.legacy_id } : null,\n completedAt: row.completed_at,\n };\n}\n\n/** Marks every legacy row up to `watermark` as copied. */\nexport async function recordWorkItemSplitComplete(\n ops: FactoryStorageOps,\n watermark: LegacyWatermark | null,\n): Promise<void> {\n await ops.upsertOne(SPLIT_STATE, ['id'], {\n id: SPLIT_MARKER_ID,\n legacy_updated_at: watermark?.updatedAt ?? null,\n legacy_id: watermark?.id ?? null,\n completed_at: new Date(),\n });\n}\n\n/**\n * Copies legacy cards that have no split rows yet, inside the caller's\n * transaction. Tombstoned cards and cards whose source another card already\n * holds are left alone; the source is checked first because a unique violation\n * would abort the caller's Postgres transaction. Returns the copied ids.\n */\nexport async function copyLegacyRows(ops: FactoryStorageOps, rows: readonly WorkItemDbRow[]): Promise<string[]> {\n const copied: string[] = [];\n for (const row of rows) {\n let card: WorkItemSplitCard;\n try {\n card = splitLegacyWorkItem(row, { workItemId: randomUUID() });\n } catch {\n continue;\n }\n if (\n card.source &&\n (await ops.findOne(SOURCES, {\n org_id: card.source.org_id,\n factory_project_id: card.source.factory_project_id,\n provider: card.source.provider,\n external_id: card.source.external_id,\n }))\n ) {\n continue;\n }\n try {\n if (await writeCard(ops, card, false)) copied.push(row.id);\n } catch (error) {\n if (!(error instanceof MigrationConflict)) throw error;\n }\n }\n return copied;\n}\n\nexport interface MigrateWorkItemSplitOptions {\n dryRun?: boolean;\n ops?: FactoryStorageOps;\n /** Receives single-line progress and summary messages. */\n log?: (line: string) => void;\n /** Names the pass in log lines, e.g. `boot pass`. */\n label?: string;\n /** Minimum time between progress lines; a pass shorter than this logs none. */\n progressIntervalMs?: number;\n now?: () => number;\n /** Rows this returns false for are counted as deferred and not looked up. */\n include?: (row: WorkItemDbRow) => boolean | Promise<boolean>;\n /** Scan only legacy rows written after this watermark, in `(updated_at, id)` order. */\n since?: LegacyWatermark | null;\n pageSize?: number;\n /** Checked between cards and pages; an aborted pass reports `aborted`. */\n signal?: AbortSignal;\n}\n\n/** Legacy rows are read-only; each card and all its split rows land atomically. */\nexport async function migrateWorkItemSplit(\n storage: Pick<FactoryStorage, 'ops' | 'withTransaction'>,\n {\n dryRun = false,\n ops = storage.ops,\n log,\n include,\n since,\n pageSize = PAGE_SIZE,\n signal,\n label,\n progressIntervalMs = PROGRESS_LOG_INTERVAL_MS,\n now = Date.now,\n }: MigrateWorkItemSplitOptions = {},\n): Promise<WorkItemSplitReport> {\n const report: WorkItemSplitReport = {\n dryRun,\n projects: 0,\n cards: 0,\n deferred: 0,\n workItems: 0,\n sources: 0,\n boardItems: 0,\n recopied: 0,\n unchanged: 0,\n skipped: [],\n aborted: false,\n };\n const projects = new Set<string>();\n const orderBy: Array<[string, 'asc']> = since\n ? [\n ['updated_at', 'asc'],\n ['id', 'asc'],\n ]\n : [\n ['org_id', 'asc'],\n ['factory_project_id', 'asc'],\n ['created_at', 'asc'],\n ['id', 'asc'],\n ];\n let cursor: CollectionValue[] | undefined = since ? [since.updatedAt, since.id] : undefined;\n const title = `work item split${dryRun ? ' (dry run)' : ''}${label ? ` (${label})` : ''}`;\n let lastProgressAt = now();\n // Counted only once a progress line is due, so a fast pass pays nothing; unknown for a `since` scan.\n let total: number | null | undefined = since ? null : undefined;\n const progress = async () => {\n if (!log || now() - lastProgressAt < progressIntervalMs) return;\n if (total === undefined) total = (await ops.count?.(LEGACY, {})) ?? null;\n lastProgressAt = now();\n const checked = total === null ? fmt(report.cards) : `${fmt(report.cards)}/${fmt(total)}`;\n log(`${title}: ${checked} cards checked, ${fmt(report.workItems)} copied, ${fmt(report.skipped.length)} skipped`);\n };\n while (!signal?.aborted) {\n const page = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n { orderBy, limit: pageSize, ...(cursor ? { cursor: { values: cursor } } : {}) },\n );\n if (!page.length) break;\n const last = page[page.length - 1]!;\n cursor = since ? [last.updated_at, last.id] : [last.org_id, last.factory_project_id, last.created_at, last.id];\n report.cards += page.length;\n const rows: WorkItemDbRow[] = [];\n for (const row of page) {\n projects.add(`${row.org_id}\\u0000${row.factory_project_id}`);\n if (!include || (await include(row))) rows.push(row);\n else report.deferred += 1;\n }\n const written = new Map<string, BoardScope>();\n if (rows.length) {\n const tombstones = await ops.findMany<{ id: string }>(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, {\n id: { in: rows.map(row => row.id) },\n });\n const deleted = new Set(tombstones.map(row => row.id));\n report.unchanged += deleted.size;\n const plan = planWorkItemSplit(\n rows.filter(row => !deleted.has(row.id)),\n await migratedBoardItems(\n ops,\n rows.map(row => row.id),\n ),\n );\n report.unchanged += plan.unchanged;\n report.skipped.push(...plan.skipped);\n for (const { card, recopy } of [\n ...plan.inserts.map(card => ({ card, recopy: false })),\n ...plan.recopies.map(card => ({ card, recopy: true })),\n ]) {\n if (signal?.aborted) break;\n if (!dryRun) {\n try {\n const changed = await storage.withTransaction(tx => writeCard(tx, card, recopy));\n if (!changed) {\n report.unchanged += 1;\n continue;\n }\n } catch (error) {\n if (!(error instanceof UniqueViolationError) && !(error instanceof MigrationConflict)) throw error;\n const raced = (await migratedBoardItems(ops, [card.boardItem.id])).get(card.boardItem.id);\n if (raced?.migratedFromHash === card.boardItem.migrated_from_hash) report.unchanged += 1;\n else {\n const reason =\n error instanceof UniqueViolationError &&\n (error.collection === SOURCES || error.collection === BOARD_ITEMS)\n ? `Conflicting source: ${error.message}`\n : error.message;\n report.skipped.push({ id: card.boardItem.id, reason });\n }\n continue;\n }\n }\n await progress();\n report.workItems += 1;\n report.sources += card.source ? 1 : 0;\n report.boardItems += 1;\n if (recopy) report.recopied += 1;\n written.set(`${card.boardItem.org_id}\\u0000${card.boardItem.factory_project_id}`, {\n orgId: card.boardItem.org_id,\n factoryProjectId: card.boardItem.factory_project_id,\n });\n }\n }\n // Per page, so cached boards pick up a long pass's cards as they land.\n if (!dryRun && written.size) await bumpBoardVersions(ops, [...written.values()]);\n if (page.length < pageSize) break;\n await progress();\n }\n report.aborted = signal?.aborted ?? false;\n report.projects = projects.size;\n if (log && (report.workItems || report.skipped.length || dryRun)) log(summaryLine(title, report));\n return report;\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,SAAS,kBAAkB;AACjC,MAAM,aAAa,0BAA0B;AAC7C,MAAM,UAAU,iCAAiC;AACjD,MAAM,cAAc,2BAA2B;AAC/C,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,2BAA2B;AAEjC,MAAM,OAAO,UAAkB,MAAM,eAAe,OAAO;;AAG3D,SAAS,YAAY,OAAe,QAAqC;CACvE,MAAM,SAAS;EACb,GAAG,IAAI,OAAO,KAAK,EAAE;EACrB,GAAG,IAAI,OAAO,SAAS,EAAE;EACzB,GAAG,IAAI,OAAO,QAAQ,EAAE;EACxB,GAAG,IAAI,OAAO,SAAS,EAAE;EACzB,GAAG,IAAI,OAAO,QAAQ,EAAE;EACxB,GAAG,IAAI,OAAO,QAAQ,MAAM,EAAE;CAChC;CACA,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,uBAAuB,MAAM,YAC7B,MAAM;MACZ,OAAO,QAAQ,KAAK;OAAE,IAAI,KAAK,UAAU;OAAI;MAAO,CAAC;KACvD;KACA;IACF;IAEF,MAAM,SAAS;IACf,OAAO,aAAa;IACpB,OAAO,WAAW,KAAK,SAAS,IAAI;IACpC,OAAO,cAAc;IACrB,IAAI,QAAQ,OAAO,YAAY;IAC/B,QAAQ,IAAI,GAAG,KAAK,UAAU,OAAO,QAAQ,KAAK,UAAU,sBAAsB;KAChF,OAAO,KAAK,UAAU;KACtB,kBAAkB,KAAK,UAAU;IACnC,CAAC;GACH;EACF;EAEA,IAAI,CAAC,UAAU,QAAQ,MAAM,MAAM,kBAAkB,KAAK,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC;EAC/E,IAAI,KAAK,SAAS,UAAU;EAC5B,MAAM,SAAS;CACjB;CACA,OAAO,UAAU,QAAQ,WAAW;CACpC,OAAO,WAAW,SAAS;CAC3B,IAAI,QAAQ,OAAO,aAAa,OAAO,QAAQ,UAAU,SAAS,IAAI,YAAY,OAAO,MAAM,CAAC;CAChG,OAAO;AACT"}
1
+ {"version":3,"file":"split-migration.js","names":[],"sources":["../../src/work-items/split-migration.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionValue, FactoryStorage, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { factoryDecisionHash } from '../storage/domains/work-items/base.js';\nimport type { WorkItemDbRow } from '../storage/domains/work-items/base.js';\nimport { bumpBoardVersions } from '../storage/domains/work-items/board-version.js';\nimport type { BoardScope } from '../storage/domains/work-items/board-version.js';\nimport {\n WORK_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEMS_SCHEMA,\n FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA,\n FACTORY_WORK_ITEMS_SCHEMA,\n FACTORY_WORK_ITEM_SOURCES_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA,\n FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport type {\n BoardItemDbRecord,\n WorkItemDbRecord,\n WorkItemSourceDbRecord,\n} from '../storage/domains/work-items/work-item-schema.js';\nimport { splitCardMetadata, workItemProviderAdapter } from './providers/index.js';\n\nconst LEGACY = WORK_ITEMS_SCHEMA.name;\nconst WORK_ITEMS = FACTORY_WORK_ITEMS_SCHEMA.name;\nconst SOURCES = FACTORY_WORK_ITEM_SOURCES_SCHEMA.name;\nconst BOARD_ITEMS = FACTORY_BOARD_ITEMS_SCHEMA.name;\nconst PAGE_SIZE = 200;\nconst LOGGED_SKIPS = 10;\nconst PROGRESS_LOG_INTERVAL_MS = 10_000;\n\nconst fmt = (value: number) => value.toLocaleString('en-US');\n\n/** One line: skips repeat while an older replica keeps writing, so only a sample is named. */\nfunction summaryLine(title: string, report: WorkItemSplitReport): string {\n const counts = [\n `${fmt(report.cards)} cards checked`,\n `${fmt(report.workItems)} copied`,\n `${fmt(report.recopied)} recopied`,\n `${fmt(report.unchanged)} unchanged`,\n `${fmt(report.deferred)} deferred`,\n `${fmt(report.skipped.length)} skipped`,\n ];\n if (report.aborted) counts.push('stopped early');\n let line = `${title}: ${counts.join(', ')}`;\n if (report.skipped.length) {\n const sample = report.skipped\n .slice(0, LOGGED_SKIPS)\n .map(skip => `${skip.id} (${skip.reason.replace(/\\s+/g, ' ')})`);\n const more = report.skipped.length - sample.length;\n line += ` — ${sample.join('; ')}${more ? `; and ${fmt(more)} more` : ''}`;\n }\n return line;\n}\n\nexport interface MigratedBoardItem {\n workItemId: string;\n revision: number;\n updatedAt: Date;\n migratedFromUpdatedAt: Date | null;\n migratedFromHash: string | null;\n}\n\nexport interface WorkItemSplitCard {\n /** Fingerprint observed when planning; rejects a stale migration plan under the row lock. */\n previousHash?: string | null;\n workItem: WorkItemDbRecord;\n source: WorkItemSourceDbRecord | null;\n boardItem: BoardItemDbRecord;\n}\n\nexport interface WorkItemSplitSkip {\n id: string;\n reason: string;\n}\n\nexport interface WorkItemSplitPlan {\n inserts: WorkItemSplitCard[];\n recopies: WorkItemSplitCard[];\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n}\n\nexport interface WorkItemSplitReport {\n dryRun: boolean;\n projects: number;\n cards: number;\n /** Rows the `include` filter left for a later pass. */\n deferred: number;\n workItems: number;\n sources: number;\n boardItems: number;\n recopied: number;\n unchanged: number;\n skipped: WorkItemSplitSkip[];\n aborted: boolean;\n}\n\nfunction time(value: Date | string | null | undefined): number {\n return value ? new Date(value).getTime() : Number.NEGATIVE_INFINITY;\n}\n\nfunction legacyHash(row: WorkItemDbRow): string {\n const copied = {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: row.factory_project_id,\n board: row.board,\n external_source: row.external_source,\n parent_work_item_id: row.parent_work_item_id,\n title: row.title,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: row.metadata,\n triage_type: row.triage_type,\n accepted_at: row.accepted_at,\n autonomy_armed_at: row.autonomy_armed_at,\n plans_preapproved_at: row.plans_preapproved_at,\n revision: row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n };\n // stableJson does not invoke Date.toJSON; normalize before hashing.\n return factoryDecisionHash(JSON.parse(JSON.stringify(copied)));\n}\n\nexport function splitLegacyWorkItem(\n row: WorkItemDbRow,\n { workItemId, revision }: { workItemId: string; revision?: number },\n): WorkItemSplitCard {\n const adapter = workItemProviderAdapter(row.external_source ?? null);\n const provider = adapter.toSource(row.external_source ?? null, row.metadata);\n const metadata = splitCardMetadata(row.metadata, adapter.providerMetadataKeys);\n return {\n workItem: {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n title: row.title,\n parent_work_item_id: null,\n revision: 1,\n created_at: row.created_at,\n updated_at: row.updated_at,\n },\n source: provider\n ? {\n id: workItemId,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n provider: provider.provider,\n integration_id: provider.integrationId,\n source_type: provider.sourceType,\n workspace_id: provider.workspaceId,\n external_id: provider.externalId,\n source_key: provider.sourceKey,\n url: provider.url,\n key: provider.key,\n state: provider.state,\n labels: provider.labels,\n author: provider.author,\n metadata: metadata.provider,\n role: 'origin',\n revision: 1,\n synced_at: null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n }\n : null,\n boardItem: {\n id: row.id,\n org_id: row.org_id,\n factory_project_id: String(row.factory_project_id),\n work_item_id: workItemId,\n board: row.board ?? null,\n parent_board_item_id: row.parent_work_item_id ?? null,\n stages: row.stages,\n stage_history: row.stage_history,\n sessions: row.sessions,\n metadata: metadata.board,\n triage_type: row.triage_type ?? null,\n accepted_at: row.accepted_at ?? null,\n autonomy_armed_at: row.autonomy_armed_at ?? null,\n plans_preapproved_at: row.plans_preapproved_at ?? null,\n comment_count: row.comment_count ?? 0,\n // The first recount must be able to correct a copied legacy count.\n feed_activity_at: null,\n revision: revision ?? row.revision,\n created_by: row.created_by,\n created_at: row.created_at,\n updated_at: row.updated_at,\n migrated_from_updated_at: row.updated_at,\n migrated_from_hash: legacyHash(row),\n },\n };\n}\n\nexport function planWorkItemSplit(\n rows: readonly WorkItemDbRow[],\n migrated: ReadonlyMap<string, MigratedBoardItem> = new Map(),\n newId: () => string = randomUUID,\n): WorkItemSplitPlan {\n const plan: WorkItemSplitPlan = { inserts: [], recopies: [], unchanged: 0, skipped: [] };\n for (const row of rows) {\n const existing = migrated.get(row.id);\n if (existing?.migratedFromHash === legacyHash(row)) {\n plan.unchanged += 1;\n continue;\n }\n if (existing && time(existing.updatedAt) > time(existing.migratedFromUpdatedAt)) {\n plan.skipped.push({ id: row.id, reason: 'Split board item changed after migration' });\n continue;\n }\n try {\n const card = splitLegacyWorkItem(row, {\n workItemId: existing?.workItemId ?? newId(),\n ...(existing ? { revision: Math.max(existing.revision, row.revision) + 1 } : {}),\n });\n if (existing) card.previousHash = existing.migratedFromHash;\n (existing ? plan.recopies : plan.inserts).push(card);\n } catch (error) {\n plan.skipped.push({ id: row.id, reason: error instanceof Error ? error.message : String(error) });\n }\n }\n return plan;\n}\n\nasync function migratedBoardItems(\n ops: FactoryStorageOps,\n ids: readonly string[],\n): Promise<Map<string, MigratedBoardItem>> {\n if (!ids.length) return new Map();\n const rows = await ops.findMany<BoardItemDbRecord>(BOARD_ITEMS, { id: { in: [...ids] } });\n return new Map(\n rows.map(row => [\n row.id,\n {\n workItemId: row.work_item_id,\n revision: row.revision,\n updatedAt: row.updated_at,\n migratedFromUpdatedAt: row.migrated_from_updated_at,\n migratedFromHash: row.migrated_from_hash,\n },\n ]),\n );\n}\n\nclass MigrationConflict extends Error {}\n\nasync function writeCard(ops: FactoryStorageOps, card: WorkItemSplitCard, recopy: boolean): Promise<boolean> {\n if (!recopy) {\n // Both paths take this card-specific lock before any card rows. A project-wide\n // lock here would invert the row-lock order of parent/child and bulk deletions.\n const guard = await ops.updateAtomic(\n FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name,\n { id: card.boardItem.id },\n () => null,\n );\n if (!guard)\n await ops.insertOne(FACTORY_WORK_ITEM_SPLIT_LOCKS_SCHEMA.name, {\n id: card.boardItem.id,\n org_id: card.boardItem.org_id,\n factory_project_id: card.boardItem.factory_project_id,\n });\n if (await ops.findOne(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, { id: card.boardItem.id })) return false;\n const existing = await ops.findOne<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id });\n if (existing) {\n if (existing.migrated_from_hash === card.boardItem.migrated_from_hash) return false;\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n await ops.insertOne<WorkItemDbRecord>(WORK_ITEMS, card.workItem);\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n await ops.insertOne<BoardItemDbRecord>(BOARD_ITEMS, card.boardItem);\n return true;\n }\n // updateAtomic locks the board row until this transaction commits, so a new\n // transition cannot land between the overwrite guard and the copy.\n let unchanged = false;\n let baseline = Number.NEGATIVE_INFINITY;\n const board = await ops.updateAtomic<BoardItemDbRecord>(BOARD_ITEMS, { id: card.boardItem.id }, current => {\n if (current.migrated_from_hash === card.boardItem.migrated_from_hash) {\n unchanged = true;\n return null;\n }\n if (current.migrated_from_hash !== card.previousHash) {\n throw new MigrationConflict('Migration baseline changed since planning');\n }\n if (time(current.updated_at) > time(current.migrated_from_updated_at)) {\n throw new MigrationConflict('Split board item changed after migration');\n }\n baseline = time(current.migrated_from_updated_at);\n return {\n ...card.boardItem,\n ...(current.feed_activity_at\n ? { comment_count: current.comment_count, feed_activity_at: current.feed_activity_at }\n : {}),\n revision: Math.max(current.revision, card.boardItem.revision) + 1,\n };\n });\n if (unchanged) return false;\n if (!board) throw new MigrationConflict('Split board item disappeared during migration');\n await ops.updateAtomic<WorkItemDbRecord>(WORK_ITEMS, { id: card.workItem.id }, current => {\n if (time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split work item changed after migration');\n }\n return { ...card.workItem, revision: current.revision + 1 };\n });\n const sources = await ops.findMany<WorkItemSourceDbRecord>(SOURCES, { work_item_id: card.workItem.id });\n if (sources.some(source => source.id !== card.workItem.id)) {\n throw new MigrationConflict('Split source set changed after migration');\n }\n for (const source of sources) {\n await ops.updateAtomic<WorkItemSourceDbRecord>(SOURCES, { id: source.id }, current => {\n if (current.synced_at != null || time(current.updated_at) > baseline) {\n throw new MigrationConflict('Split source changed after migration');\n }\n return null;\n });\n }\n if (sources.length) await ops.deleteMany(SOURCES, { id: { in: sources.map(source => source.id) } });\n if (card.source) await ops.insertOne<WorkItemSourceDbRecord>(SOURCES, card.source);\n return true;\n}\n\nexport interface LegacyWatermark {\n updatedAt: Date;\n id: string;\n}\n\nexport interface WorkItemSplitMarker {\n /** Newest legacy row when the finished pass began; null when the legacy table was empty. */\n watermark: LegacyWatermark | null;\n completedAt: Date;\n}\n\nconst SPLIT_STATE = FACTORY_WORK_ITEM_SPLIT_STATE_SCHEMA.name;\nconst SPLIT_MARKER_ID = 'work_item_split';\n\n/** The newest legacy write, by `(updated_at, id)`; one indexed row. */\nexport async function readLegacyWatermark(ops: FactoryStorageOps): Promise<LegacyWatermark | null> {\n const [row] = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n {\n orderBy: [\n ['updated_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: 1,\n },\n );\n return row ? { updatedAt: row.updated_at, id: row.id } : null;\n}\n\nexport async function readWorkItemSplitMarker(ops: FactoryStorageOps): Promise<WorkItemSplitMarker | null> {\n const row = await ops.findOne<{ legacy_updated_at: Date | null; legacy_id: string | null; completed_at: Date }>(\n SPLIT_STATE,\n { id: SPLIT_MARKER_ID },\n );\n if (!row) return null;\n return {\n watermark: row.legacy_updated_at && row.legacy_id ? { updatedAt: row.legacy_updated_at, id: row.legacy_id } : null,\n completedAt: row.completed_at,\n };\n}\n\n/** Marks every legacy row up to `watermark` as copied. */\nexport async function recordWorkItemSplitComplete(\n ops: FactoryStorageOps,\n watermark: LegacyWatermark | null,\n): Promise<void> {\n await ops.upsertOne(SPLIT_STATE, ['id'], {\n id: SPLIT_MARKER_ID,\n legacy_updated_at: watermark?.updatedAt ?? null,\n legacy_id: watermark?.id ?? null,\n completed_at: new Date(),\n });\n}\n\n/**\n * Copies legacy cards that have no split rows yet, inside the caller's\n * transaction. Tombstoned cards and cards whose source another card already\n * holds are left alone; the source is checked first because a unique violation\n * would abort the caller's Postgres transaction. Returns the copied ids.\n */\nexport async function copyLegacyRows(ops: FactoryStorageOps, rows: readonly WorkItemDbRow[]): Promise<string[]> {\n const copied: string[] = [];\n for (const row of rows) {\n let card: WorkItemSplitCard;\n try {\n card = splitLegacyWorkItem(row, { workItemId: randomUUID() });\n } catch {\n continue;\n }\n if (\n card.source &&\n (await ops.findOne(SOURCES, {\n org_id: card.source.org_id,\n factory_project_id: card.source.factory_project_id,\n provider: card.source.provider,\n external_id: card.source.external_id,\n }))\n ) {\n continue;\n }\n try {\n if (await writeCard(ops, card, false)) copied.push(row.id);\n } catch (error) {\n if (!(error instanceof MigrationConflict)) throw error;\n }\n }\n return copied;\n}\n\nexport interface MigrateWorkItemSplitOptions {\n dryRun?: boolean;\n ops?: FactoryStorageOps;\n /** Receives single-line progress and summary messages. */\n log?: (line: string) => void;\n /** Names the pass in log lines, e.g. `boot pass`. */\n label?: string;\n /** Minimum time between progress lines; a pass shorter than this logs none. */\n progressIntervalMs?: number;\n now?: () => number;\n /** Rows this returns false for are counted as deferred and not looked up. */\n include?: (row: WorkItemDbRow) => boolean | Promise<boolean>;\n /** Scan only legacy rows written after this watermark, in `(updated_at, id)` order. */\n since?: LegacyWatermark | null;\n pageSize?: number;\n /** Checked between cards and pages; an aborted pass reports `aborted`. */\n signal?: AbortSignal;\n}\n\n/** Legacy rows are read-only; each card and all its split rows land atomically. */\nexport async function migrateWorkItemSplit(\n storage: Pick<FactoryStorage, 'ops' | 'withTransaction'>,\n {\n dryRun = false,\n ops = storage.ops,\n log,\n include,\n since,\n pageSize = PAGE_SIZE,\n signal,\n label,\n progressIntervalMs = PROGRESS_LOG_INTERVAL_MS,\n now = Date.now,\n }: MigrateWorkItemSplitOptions = {},\n): Promise<WorkItemSplitReport> {\n const report: WorkItemSplitReport = {\n dryRun,\n projects: 0,\n cards: 0,\n deferred: 0,\n workItems: 0,\n sources: 0,\n boardItems: 0,\n recopied: 0,\n unchanged: 0,\n skipped: [],\n aborted: false,\n };\n const projects = new Set<string>();\n const orderBy: Array<[string, 'asc']> = since\n ? [\n ['updated_at', 'asc'],\n ['id', 'asc'],\n ]\n : [\n ['org_id', 'asc'],\n ['factory_project_id', 'asc'],\n ['created_at', 'asc'],\n ['id', 'asc'],\n ];\n let cursor: CollectionValue[] | undefined = since ? [since.updatedAt, since.id] : undefined;\n const title = `work item split${dryRun ? ' (dry run)' : ''}${label ? ` (${label})` : ''}`;\n let lastProgressAt = now();\n // Counted only once a progress line is due, so a fast pass pays nothing; unknown for a `since` scan.\n let total: number | null | undefined = since ? null : undefined;\n const progress = async () => {\n if (!log || now() - lastProgressAt < progressIntervalMs) return;\n if (total === undefined) total = (await ops.count?.(LEGACY, {})) ?? null;\n lastProgressAt = now();\n const checked = total === null ? fmt(report.cards) : `${fmt(report.cards)}/${fmt(total)}`;\n log(`${title}: ${checked} cards checked, ${fmt(report.workItems)} copied, ${fmt(report.skipped.length)} skipped`);\n };\n while (!signal?.aborted) {\n const page = await ops.findMany<WorkItemDbRow>(\n LEGACY,\n {},\n { orderBy, limit: pageSize, ...(cursor ? { cursor: { values: cursor } } : {}) },\n );\n if (!page.length) break;\n const last = page[page.length - 1]!;\n cursor = since ? [last.updated_at, last.id] : [last.org_id, last.factory_project_id, last.created_at, last.id];\n report.cards += page.length;\n const rows: WorkItemDbRow[] = [];\n for (const row of page) {\n projects.add(`${row.org_id}\\u0000${row.factory_project_id}`);\n if (!include || (await include(row))) rows.push(row);\n else report.deferred += 1;\n }\n const written = new Map<string, BoardScope>();\n if (rows.length) {\n const tombstones = await ops.findMany<{ id: string }>(FACTORY_BOARD_ITEM_TOMBSTONES_SCHEMA.name, {\n id: { in: rows.map(row => row.id) },\n });\n const deleted = new Set(tombstones.map(row => row.id));\n report.unchanged += deleted.size;\n const plan = planWorkItemSplit(\n rows.filter(row => !deleted.has(row.id)),\n await migratedBoardItems(\n ops,\n rows.map(row => row.id),\n ),\n );\n report.unchanged += plan.unchanged;\n report.skipped.push(...plan.skipped);\n for (const { card, recopy } of [\n ...plan.inserts.map(card => ({ card, recopy: false })),\n ...plan.recopies.map(card => ({ card, recopy: true })),\n ]) {\n if (signal?.aborted) break;\n if (!dryRun) {\n try {\n const changed = await storage.withTransaction(tx => writeCard(tx, card, recopy));\n if (!changed) {\n report.unchanged += 1;\n continue;\n }\n } catch (error) {\n if (!(error instanceof UniqueViolationError) && !(error instanceof MigrationConflict)) throw error;\n const raced = (await migratedBoardItems(ops, [card.boardItem.id])).get(card.boardItem.id);\n if (raced?.migratedFromHash === card.boardItem.migrated_from_hash) report.unchanged += 1;\n else {\n const reason =\n error instanceof UniqueViolationError &&\n (error.collection === SOURCES || error.collection === BOARD_ITEMS)\n ? `Conflicting source: ${error.message}`\n : error.message;\n report.skipped.push({ id: card.boardItem.id, reason });\n }\n continue;\n }\n }\n await progress();\n report.workItems += 1;\n report.sources += card.source ? 1 : 0;\n report.boardItems += 1;\n if (recopy) report.recopied += 1;\n written.set(`${card.boardItem.org_id}\\u0000${card.boardItem.factory_project_id}`, {\n orgId: card.boardItem.org_id,\n factoryProjectId: card.boardItem.factory_project_id,\n });\n }\n }\n // Per page, so cached boards pick up a long pass's cards as they land.\n if (!dryRun && written.size) await bumpBoardVersions(ops, [...written.values()]);\n if (page.length < pageSize) break;\n await progress();\n }\n report.aborted = signal?.aborted ?? false;\n report.projects = projects.size;\n if (log && (report.workItems || report.skipped.length || dryRun)) log(summaryLine(title, report));\n return report;\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,SAAS,kBAAkB;AACjC,MAAM,aAAa,0BAA0B;AAC7C,MAAM,UAAU,iCAAiC;AACjD,MAAM,cAAc,2BAA2B;AAC/C,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,2BAA2B;AAEjC,MAAM,OAAO,UAAkB,MAAM,eAAe,OAAO;;AAG3D,SAAS,YAAY,OAAe,QAAqC;CACvE,MAAM,SAAS;EACb,GAAG,IAAI,OAAO,KAAK,EAAE;EACrB,GAAG,IAAI,OAAO,SAAS,EAAE;EACzB,GAAG,IAAI,OAAO,QAAQ,EAAE;EACxB,GAAG,IAAI,OAAO,SAAS,EAAE;EACzB,GAAG,IAAI,OAAO,QAAQ,EAAE;EACxB,GAAG,IAAI,OAAO,QAAQ,MAAM,EAAE;CAChC;CACA,IAAI,OAAO,SAAS,OAAO,KAAK,eAAe;CAC/C,IAAI,OAAO,GAAG,MAAM,IAAI,OAAO,KAAK,IAAI;CACxC,IAAI,OAAO,QAAQ,QAAQ;EACzB,MAAM,SAAS,OAAO,QACnB,MAAM,GAAG,YAAY,CAAC,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