@mastra/factory 0.29.0-alpha.4 → 0.29.0-alpha.5

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 (315) hide show
  1. package/README.md +119 -60
  2. package/dist/boards/board-events.d.ts +89 -9
  3. package/dist/boards/board-events.d.ts.map +1 -1
  4. package/dist/boards/board-events.js +176 -13
  5. package/dist/boards/board-events.js.map +1 -1
  6. package/dist/boards/board-writes.d.ts.map +1 -1
  7. package/dist/boards/board-writes.js +14 -1
  8. package/dist/boards/board-writes.js.map +1 -1
  9. package/dist/boards/busy-card.d.ts +11 -0
  10. package/dist/boards/busy-card.d.ts.map +1 -0
  11. package/dist/boards/busy-card.js +15 -0
  12. package/dist/boards/busy-card.js.map +1 -0
  13. package/dist/boards/card-facts.d.ts.map +1 -1
  14. package/dist/boards/card-facts.js +18 -4
  15. package/dist/boards/card-facts.js.map +1 -1
  16. package/dist/boards/index.d.ts +2 -1
  17. package/dist/boards/index.d.ts.map +1 -1
  18. package/dist/boards/index.js +3 -2
  19. package/dist/boards/intake-dry-run.d.ts +109 -0
  20. package/dist/boards/intake-dry-run.d.ts.map +1 -0
  21. package/dist/boards/intake-dry-run.js +158 -0
  22. package/dist/boards/intake-dry-run.js.map +1 -0
  23. package/dist/boards/intake-lookup.d.ts +32 -0
  24. package/dist/boards/intake-lookup.d.ts.map +1 -0
  25. package/dist/boards/intake-lookup.js +12 -0
  26. package/dist/boards/intake-lookup.js.map +1 -0
  27. package/dist/boards/intake-order.d.ts +32 -0
  28. package/dist/boards/intake-order.d.ts.map +1 -0
  29. package/dist/boards/intake-order.js +60 -0
  30. package/dist/boards/intake-order.js.map +1 -0
  31. package/dist/boards/intake-routing.d.ts +246 -35
  32. package/dist/boards/intake-routing.d.ts.map +1 -1
  33. package/dist/boards/intake-routing.js +437 -52
  34. package/dist/boards/intake-routing.js.map +1 -1
  35. package/dist/boards/reroute.d.ts +7 -3
  36. package/dist/boards/reroute.d.ts.map +1 -1
  37. package/dist/boards/reroute.js +21 -4
  38. package/dist/boards/reroute.js.map +1 -1
  39. package/dist/boards/semantics.d.ts +8 -28
  40. package/dist/boards/semantics.d.ts.map +1 -1
  41. package/dist/boards/semantics.js +7 -39
  42. package/dist/boards/semantics.js.map +1 -1
  43. package/dist/boards/work-routes.d.ts +31 -11
  44. package/dist/boards/work-routes.d.ts.map +1 -1
  45. package/dist/boards/work-routes.js +104 -20
  46. package/dist/boards/work-routes.js.map +1 -1
  47. package/dist/factory.d.ts +27 -1
  48. package/dist/factory.d.ts.map +1 -1
  49. package/dist/factory.js +31 -9
  50. package/dist/factory.js.map +1 -1
  51. package/dist/integrations/base.d.ts +9 -0
  52. package/dist/integrations/base.d.ts.map +1 -1
  53. package/dist/integrations/dependabot/rules.js +1 -1
  54. package/dist/integrations/dependabot/rules.js.map +1 -1
  55. package/dist/integrations/github/default-rules.d.ts +22 -1
  56. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  57. package/dist/integrations/github/default-rules.js +23 -5
  58. package/dist/integrations/github/default-rules.js.map +1 -1
  59. package/dist/integrations/github/intake-lookup.d.ts +16 -0
  60. package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
  61. package/dist/integrations/github/intake-lookup.js +76 -0
  62. package/dist/integrations/github/intake-lookup.js.map +1 -0
  63. package/dist/integrations/github/integration.d.ts +19 -5
  64. package/dist/integrations/github/integration.d.ts.map +1 -1
  65. package/dist/integrations/github/integration.js +21 -6
  66. package/dist/integrations/github/integration.js.map +1 -1
  67. package/dist/integrations/github/review-status-reporter.js +1 -1
  68. package/dist/integrations/github/routes.d.ts.map +1 -1
  69. package/dist/integrations/github/routes.js +14 -2
  70. package/dist/integrations/github/routes.js.map +1 -1
  71. package/dist/integrations/github/rules.d.ts +12 -1
  72. package/dist/integrations/github/rules.d.ts.map +1 -1
  73. package/dist/integrations/github/rules.js +218 -30
  74. package/dist/integrations/github/rules.js.map +1 -1
  75. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  76. package/dist/integrations/github/sandbox.js +30 -4
  77. package/dist/integrations/github/sandbox.js.map +1 -1
  78. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  79. package/dist/integrations/gitlab/default-rules.js +19 -3
  80. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  81. package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
  82. package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
  83. package/dist/integrations/gitlab/intake-lookup.js +85 -0
  84. package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
  85. package/dist/integrations/gitlab/integration.d.ts +5 -0
  86. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  87. package/dist/integrations/gitlab/integration.js +21 -1
  88. package/dist/integrations/gitlab/integration.js.map +1 -1
  89. package/dist/integrations/gitlab/rules.d.ts +20 -0
  90. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  91. package/dist/integrations/gitlab/rules.js +108 -12
  92. package/dist/integrations/gitlab/rules.js.map +1 -1
  93. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  94. package/dist/integrations/incidentio/rules.js +14 -4
  95. package/dist/integrations/incidentio/rules.js.map +1 -1
  96. package/dist/integrations/jira/rules.d.ts.map +1 -1
  97. package/dist/integrations/jira/rules.js +12 -2
  98. package/dist/integrations/jira/rules.js.map +1 -1
  99. package/dist/integrations/linear/rules.d.ts.map +1 -1
  100. package/dist/integrations/linear/rules.js +13 -2
  101. package/dist/integrations/linear/rules.js.map +1 -1
  102. package/dist/integrations/platform/github/event-worker.js +9 -1
  103. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  104. package/dist/integrations/platform/github/integration.d.ts +6 -6
  105. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  106. package/dist/integrations/platform/github/integration.js +22 -3
  107. package/dist/integrations/platform/github/integration.js.map +1 -1
  108. package/dist/integrations/pull-request-head.d.ts +1 -1
  109. package/dist/integrations/pull-request-head.d.ts.map +1 -1
  110. package/dist/integrations/pull-request-head.js +5 -0
  111. package/dist/integrations/pull-request-head.js.map +1 -1
  112. package/dist/integrations/vanta/rules.js +1 -1
  113. package/dist/integrations/vanta/rules.js.map +1 -1
  114. package/dist/routes/board-snapshot.d.ts +8 -1
  115. package/dist/routes/board-snapshot.d.ts.map +1 -1
  116. package/dist/routes/board-snapshot.js +33 -7
  117. package/dist/routes/board-snapshot.js.map +1 -1
  118. package/dist/routes/boards.js.map +1 -1
  119. package/dist/routes/config.d.ts +6 -0
  120. package/dist/routes/config.d.ts.map +1 -1
  121. package/dist/routes/config.js +5 -2
  122. package/dist/routes/config.js.map +1 -1
  123. package/dist/routes/contracts.d.ts +1258 -0
  124. package/dist/routes/contracts.d.ts.map +1 -1
  125. package/dist/routes/contracts.js +586 -13
  126. package/dist/routes/contracts.js.map +1 -1
  127. package/dist/routes/intake-check.d.ts +92 -0
  128. package/dist/routes/intake-check.d.ts.map +1 -0
  129. package/dist/routes/intake-check.js +322 -0
  130. package/dist/routes/intake-check.js.map +1 -0
  131. package/dist/routes/intake-routes.d.ts +10 -2
  132. package/dist/routes/intake-routes.d.ts.map +1 -1
  133. package/dist/routes/intake-routes.js +292 -11
  134. package/dist/routes/intake-routes.js.map +1 -1
  135. package/dist/routes/mastra-gateway.d.ts.map +1 -1
  136. package/dist/routes/mastra-gateway.js +3 -2
  137. package/dist/routes/mastra-gateway.js.map +1 -1
  138. package/dist/routes/project-sessions.d.ts +49 -0
  139. package/dist/routes/project-sessions.d.ts.map +1 -0
  140. package/dist/routes/project-sessions.js +93 -0
  141. package/dist/routes/project-sessions.js.map +1 -0
  142. package/dist/routes/run-queue.d.ts +6 -6
  143. package/dist/routes/run-queue.d.ts.map +1 -1
  144. package/dist/routes/run-queue.js +28 -8
  145. package/dist/routes/run-queue.js.map +1 -1
  146. package/dist/routes/session-rows.d.ts +30 -0
  147. package/dist/routes/session-rows.d.ts.map +1 -0
  148. package/dist/routes/session-rows.js +98 -0
  149. package/dist/routes/session-rows.js.map +1 -0
  150. package/dist/routes/source-control-sessions.d.ts +4 -5
  151. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  152. package/dist/routes/source-control-sessions.js +8 -87
  153. package/dist/routes/source-control-sessions.js.map +1 -1
  154. package/dist/routes/surface.d.ts +13 -1
  155. package/dist/routes/surface.d.ts.map +1 -1
  156. package/dist/routes/surface.js +24 -26
  157. package/dist/routes/surface.js.map +1 -1
  158. package/dist/routes/work-item-starters.d.ts +1 -0
  159. package/dist/routes/work-item-starters.d.ts.map +1 -1
  160. package/dist/routes/work-item-starters.js +14 -2
  161. package/dist/routes/work-item-starters.js.map +1 -1
  162. package/dist/routes/work-items.d.ts +13 -0
  163. package/dist/routes/work-items.d.ts.map +1 -1
  164. package/dist/routes/work-items.js +87 -34
  165. package/dist/routes/work-items.js.map +1 -1
  166. package/dist/rules/dispatch-errors.js +1 -1
  167. package/dist/rules/dispatch-errors.js.map +1 -1
  168. package/dist/rules/dispatcher.d.ts +39 -7
  169. package/dist/rules/dispatcher.d.ts.map +1 -1
  170. package/dist/rules/dispatcher.js +361 -122
  171. package/dist/rules/dispatcher.js.map +1 -1
  172. package/dist/rules/event-rules.d.ts +69 -1
  173. package/dist/rules/event-rules.d.ts.map +1 -1
  174. package/dist/rules/event-rules.js +151 -5
  175. package/dist/rules/event-rules.js.map +1 -1
  176. package/dist/rules/review-source-tool.js +1 -1
  177. package/dist/rules/rule-group.d.ts +18 -1
  178. package/dist/rules/rule-group.d.ts.map +1 -1
  179. package/dist/rules/rule-group.js +52 -8
  180. package/dist/rules/rule-group.js.map +1 -1
  181. package/dist/rules/run-bearing.d.ts +8 -0
  182. package/dist/rules/run-bearing.d.ts.map +1 -0
  183. package/dist/rules/run-bearing.js +11 -0
  184. package/dist/rules/run-bearing.js.map +1 -0
  185. package/dist/rules/start-coordinator.d.ts +2 -3
  186. package/dist/rules/start-coordinator.d.ts.map +1 -1
  187. package/dist/rules/start-coordinator.js +26 -34
  188. package/dist/rules/start-coordinator.js.map +1 -1
  189. package/dist/rules/tools.js +2 -1
  190. package/dist/rules/tools.js.map +1 -1
  191. package/dist/rules/transition-service.d.ts +16 -0
  192. package/dist/rules/transition-service.d.ts.map +1 -1
  193. package/dist/rules/transition-service.js +34 -10
  194. package/dist/rules/transition-service.js.map +1 -1
  195. package/dist/rules/types.d.ts +18 -5
  196. package/dist/rules/types.d.ts.map +1 -1
  197. package/dist/rules/types.js +2 -1
  198. package/dist/rules/types.js.map +1 -1
  199. package/dist/rules/update-fold.d.ts +32 -0
  200. package/dist/rules/update-fold.d.ts.map +1 -0
  201. package/dist/rules/update-fold.js +60 -0
  202. package/dist/rules/update-fold.js.map +1 -0
  203. package/dist/rules/validation.d.ts.map +1 -1
  204. package/dist/rules/validation.js +54 -6
  205. package/dist/rules/validation.js.map +1 -1
  206. package/dist/session/resource-migration.d.ts.map +1 -1
  207. package/dist/session/resource-migration.js +2 -3
  208. package/dist/session/resource-migration.js.map +1 -1
  209. package/dist/session/run-audit.d.ts +9 -0
  210. package/dist/session/run-audit.d.ts.map +1 -1
  211. package/dist/session/run-audit.js +9 -1
  212. package/dist/session/run-audit.js.map +1 -1
  213. package/dist/session/self-review-gate.d.ts +26 -2
  214. package/dist/session/self-review-gate.d.ts.map +1 -1
  215. package/dist/session/self-review-gate.js +60 -10
  216. package/dist/session/self-review-gate.js.map +1 -1
  217. package/dist/session/session-row-query.d.ts +25 -0
  218. package/dist/session/session-row-query.d.ts.map +1 -0
  219. package/dist/session/session-row-query.js +47 -0
  220. package/dist/session/session-row-query.js.map +1 -0
  221. package/dist/session/session-row-status.d.ts +16 -0
  222. package/dist/session/session-row-status.d.ts.map +1 -0
  223. package/dist/session/session-row-status.js +14 -0
  224. package/dist/session/session-row-status.js.map +1 -0
  225. package/dist/session/session-row-view.d.ts +14 -0
  226. package/dist/session/session-row-view.d.ts.map +1 -0
  227. package/dist/session/session-row-view.js +125 -0
  228. package/dist/session/session-row-view.js.map +1 -0
  229. package/dist/session/session-rows.d.ts +46 -0
  230. package/dist/session/session-rows.d.ts.map +1 -0
  231. package/dist/session/session-rows.js +232 -0
  232. package/dist/session/session-rows.js.map +1 -0
  233. package/dist/session/session-threads.d.ts.map +1 -1
  234. package/dist/session/session-threads.js +1 -0
  235. package/dist/session/session-threads.js.map +1 -1
  236. package/dist/session/source-control-tools.d.ts +14 -7
  237. package/dist/session/source-control-tools.d.ts.map +1 -1
  238. package/dist/session/source-control-tools.js +10 -2
  239. package/dist/session/source-control-tools.js.map +1 -1
  240. package/dist/session/work-item-repository.d.ts +44 -0
  241. package/dist/session/work-item-repository.d.ts.map +1 -1
  242. package/dist/session/work-item-repository.js +80 -1
  243. package/dist/session/work-item-repository.js.map +1 -1
  244. package/dist/session/work-item-state-processor.d.ts.map +1 -1
  245. package/dist/session/work-item-state-processor.js +44 -8
  246. package/dist/session/work-item-state-processor.js.map +1 -1
  247. package/dist/storage/domains/audit/actions.d.ts +2 -1
  248. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  249. package/dist/storage/domains/audit/actions.js +3 -1
  250. package/dist/storage/domains/audit/actions.js.map +1 -1
  251. package/dist/storage/domains/boards/base.d.ts +162 -14
  252. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  253. package/dist/storage/domains/boards/base.js +415 -41
  254. package/dist/storage/domains/boards/base.js.map +1 -1
  255. package/dist/storage/domains/boards/schemas.d.ts +6 -0
  256. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  257. package/dist/storage/domains/boards/schemas.js +95 -1
  258. package/dist/storage/domains/boards/schemas.js.map +1 -1
  259. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  260. package/dist/storage/domains/projects/base.js +19 -10
  261. package/dist/storage/domains/projects/base.js.map +1 -1
  262. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  263. package/dist/storage/domains/source-control/base.js +5 -2
  264. package/dist/storage/domains/source-control/base.js.map +1 -1
  265. package/dist/storage/domains/work-items/base.d.ts +48 -17
  266. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  267. package/dist/storage/domains/work-items/base.js +128 -75
  268. package/dist/storage/domains/work-items/base.js.map +1 -1
  269. package/dist/storage/domains/work-items/cards.d.ts +3 -2
  270. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  271. package/dist/storage/domains/work-items/cards.js +4 -2
  272. package/dist/storage/domains/work-items/cards.js.map +1 -1
  273. package/dist/storage/probed-list.d.ts +11 -0
  274. package/dist/storage/probed-list.d.ts.map +1 -0
  275. package/dist/storage/probed-list.js +52 -0
  276. package/dist/storage/probed-list.js.map +1 -0
  277. package/dist/tools/audit-events-tool.d.ts +2 -2
  278. package/dist/tools/read-tools.d.ts +0 -3
  279. package/dist/tools/read-tools.d.ts.map +1 -1
  280. package/dist/tools/read-tools.js +4 -42
  281. package/dist/tools/read-tools.js.map +1 -1
  282. package/dist/tools/session-tools.d.ts.map +1 -1
  283. package/dist/tools/session-tools.js +5 -9
  284. package/dist/tools/session-tools.js.map +1 -1
  285. package/dist/tools/work-item-tools.d.ts +3 -0
  286. package/dist/tools/work-item-tools.d.ts.map +1 -1
  287. package/dist/tools/work-item-tools.js +8 -4
  288. package/dist/tools/work-item-tools.js.map +1 -1
  289. package/dist/work-item-branch.d.ts +4 -0
  290. package/dist/work-item-branch.d.ts.map +1 -1
  291. package/dist/work-item-branch.js +7 -1
  292. package/dist/work-item-branch.js.map +1 -1
  293. package/dist/work-items/card-context-sessions.d.ts +50 -0
  294. package/dist/work-items/card-context-sessions.d.ts.map +1 -0
  295. package/dist/work-items/card-context-sessions.js +84 -0
  296. package/dist/work-items/card-context-sessions.js.map +1 -0
  297. package/dist/work-items/change-requests.d.ts +87 -0
  298. package/dist/work-items/change-requests.d.ts.map +1 -0
  299. package/dist/work-items/change-requests.js +134 -0
  300. package/dist/work-items/change-requests.js.map +1 -0
  301. package/dist/work-items/create-work-item.d.ts +7 -2
  302. package/dist/work-items/create-work-item.d.ts.map +1 -1
  303. package/dist/work-items/create-work-item.js +44 -13
  304. package/dist/work-items/create-work-item.js.map +1 -1
  305. package/dist/work-items/list-related-cards.d.ts.map +1 -1
  306. package/dist/work-items/list-related-cards.js +1 -1
  307. package/dist/work-items/list-related-cards.js.map +1 -1
  308. package/dist/work-items/providers/github.d.ts.map +1 -1
  309. package/dist/work-items/providers/github.js +1 -0
  310. package/dist/work-items/providers/github.js.map +1 -1
  311. package/factory-skills/factory-build/SKILL.md +1 -1
  312. package/factory-skills/factory-plan/SKILL.md +5 -3
  313. package/factory-skills/factory-self-review/SKILL.md +2 -0
  314. package/factory-skills/factory-triage/SKILL.md +1 -1
  315. package/package.json +8 -8
@@ -40,9 +40,8 @@ export declare class UntrustedSharedSessionError extends Error {
40
40
  constructor(sessionId: string);
41
41
  }
42
42
  export declare class WorkItemRepositoryError extends Error {
43
- readonly code: 'repository_mismatch' | 'repository_ambiguous' | 'repository_unlinked';
44
- readonly candidates: string[];
45
- constructor(code: 'repository_mismatch' | 'repository_ambiguous' | 'repository_unlinked', message: string, candidates?: string[]);
43
+ readonly code: 'repository_mismatch' | 'repository_unlinked';
44
+ constructor(code: 'repository_mismatch' | 'repository_unlinked', message: string);
46
45
  }
47
46
  export declare class FactoryStartTransitionError extends Error {
48
47
  readonly result: Extract<FactoryTransitionResult, {
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.d.ts","sourceRoot":"","sources":["../../src/rules/start-coordinator.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAG9D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAItE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2CA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AED,KAAK,iBAAiB,GAAG,eAAe,CAAC,eAAe,CAAC,CAAC;AA0C1D,qBAAa,uBAAuB;;IAclC,YACE,UAAU,EAAE,iBAAiB,EAC7B,OAAO,EAAE,gBAAgB,EACzB,iBAAiB,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,YAAY,CAAC,EAChE,aAAa,CAAC,EACV,0BAA0B,GAC1B,CAAC,CACC,OAAO,EAAE,mBAAmB,KACzB,0BAA0B,GAAG,SAAS,GAAG,OAAO,CAAC,0BAA0B,GAAG,SAAS,CAAC,CAAC,EAClG,MAAM,CAAC,EAAE,aAAa,EACtB,YAAY,CAAC,EAAE;QAAE,QAAQ,EAAE,sBAAsB,CAAC;QAAC,aAAa,EAAE,oBAAoB,CAAA;KAAE;IACxF,uIAAuI;IACvI,MAAM,CAAC,EAAE,aAAa,GAAG,kBAAkB,EAU5C;IAEK,OAAO,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,0BAA0B,CAAC,CAgN/E;CACF"}
@@ -4,7 +4,7 @@ import { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase } from "../b
4
4
  import { toBoardSource } from "../boards/project-boards.js";
5
5
  import { primeTenantCredentialsForTenant } from "../routes/tenant-credentials.js";
6
6
  import { hydrateFactorySession, resolveFactorySessionModel } from "../session/factory-session.js";
7
- import { resolveWorkItemRepository } from "../session/work-item-repository.js";
7
+ import { isRunRepositoryInstruction, repositoryChosenByRun, resolveRunRepository, runRepositoryInstruction } from "../session/work-item-repository.js";
8
8
  import { isFactoryPrincipalId } from "../storage/domains/projects/base.js";
9
9
  import { externallyAuthoredWorkItem } from "./types.js";
10
10
  import { RequestContext } from "@mastra/core/request-context";
@@ -34,11 +34,9 @@ async function runMemoryResource(controller, input) {
34
34
  }
35
35
  var WorkItemRepositoryError = class extends Error {
36
36
  code;
37
- candidates;
38
- constructor(code, message, candidates = []) {
37
+ constructor(code, message) {
39
38
  super(message);
40
39
  this.code = code;
41
- this.candidates = candidates;
42
40
  this.name = "WorkItemRepositoryError";
43
41
  }
44
42
  };
@@ -70,6 +68,18 @@ async function resolveSourceSession(storage, request) {
70
68
  projectRepositoryId
71
69
  };
72
70
  }
71
+ async function sessionRepositorySlug(storage, orgId, projectRepositoryId) {
72
+ const link = await storage.projectRepositories.get({
73
+ orgId,
74
+ id: projectRepositoryId
75
+ });
76
+ const repository = link && await storage.repositories.get({
77
+ orgId,
78
+ id: link.repositoryId
79
+ });
80
+ if (!repository) throw new Error("Factory session repository not found");
81
+ return repository.slug;
82
+ }
73
83
  async function configureThread(session, request) {
74
84
  const threadId = session.thread.requireId();
75
85
  await session.thread.rename({
@@ -125,39 +135,21 @@ var FactoryStartCoordinator = class {
125
135
  orgId: request.orgId,
126
136
  integrationIds: ["linear"]
127
137
  });
128
- let repository = await resolveWorkItemRepository({
138
+ const runItem = storedItem ?? {
139
+ metadata: request.workItem.input.metadata ?? null,
140
+ workItem: { metadata: request.workItem.input.metadata ?? null }
141
+ };
142
+ const repository = await resolveRunRepository({
129
143
  sourceControl,
130
144
  orgId: request.orgId,
131
145
  factoryProjectId: request.factoryProjectId,
132
- item: storedItem ?? {
133
- metadata: request.workItem.input.metadata ?? null,
134
- workItem: { metadata: request.workItem.input.metadata ?? null }
135
- },
136
- linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject
146
+ item: runItem,
147
+ linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,
148
+ boundProjectRepositoryId: sourceSession.projectRepositoryId
137
149
  });
138
- if (repository.status === "ambiguous") {
139
- if (storedItem?.sessions[request.workItem.role]?.sessionId !== sourceSession.sessionId) throw new WorkItemRepositoryError("repository_ambiguous", `Choose a repository for this work item: ${repository.candidates.join(", ")}.`, repository.candidates);
140
- const link = await sourceControl.projectRepositories.get({
141
- orgId: request.orgId,
142
- id: sourceSession.projectRepositoryId
143
- });
144
- const linked = link && await sourceControl.repositories.get({
145
- orgId: request.orgId,
146
- id: link.repositoryId
147
- });
148
- const currentLinks = link ? await sourceControl.projectRepositories.list({
149
- orgId: request.orgId,
150
- connectionId: link.connectionId
151
- }) : [];
152
- if (!linked || !repository.candidates.includes(linked.slug) || !currentLinks.some((candidate) => candidate.id === sourceSession.projectRepositoryId)) throw new WorkItemRepositoryError("repository_unlinked", "The existing session repository is not linked to this Factory.");
153
- repository = {
154
- status: "resolved",
155
- slug: linked.slug,
156
- projectRepositoryId: sourceSession.projectRepositoryId
157
- };
158
- }
159
150
  if (repository.status === "unlinked") throw new WorkItemRepositoryError("repository_unlinked", repository.hint);
160
- if (repository.projectRepositoryId !== sourceSession.projectRepositoryId) throw new WorkItemRepositoryError("repository_mismatch", `This run session is bound to a different repository than ${repository.slug}.`);
151
+ if (repository.projectRepositoryId !== sourceSession.projectRepositoryId && !repositoryChosenByRun(runItem, repository.slug)) throw new WorkItemRepositoryError("repository_mismatch", `This run session is bound to a different repository than ${repository.slug}.`);
152
+ const ownSlug = repository.projectRepositoryId === sourceSession.projectRepositoryId ? repository.slug : await sessionRepositorySlug(sourceControl, request.orgId, sourceSession.projectRepositoryId);
161
153
  const requestContext = request.requestContext ?? new RequestContext();
162
154
  const existingUser = requestContext.get("user");
163
155
  if (!existingUser || typeof existingUser !== "object") requestContext.set("user", {
@@ -189,14 +181,14 @@ var FactoryStartCoordinator = class {
189
181
  requestContext,
190
182
  tags: sessionTags
191
183
  });
192
- const targetRepositoryInstruction = `Target repository: ${repository.slug}. Before editing files or creating a pull request, verify this session's checkout matches the target repository.`;
184
+ const targetRepositoryInstruction = runRepositoryInstruction(repository, ownSlug);
193
185
  const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];
194
186
  await session.state.set({
195
187
  ...sessionTags,
196
188
  factoryOrgId: request.orgId,
197
189
  factoryModelScope: sessionModel.modelScope,
198
190
  factoryOwnerUserId: sourceSession.userId,
199
- pluginInstructions: [...existingPluginInstructions.filter((instruction) => instruction !== targetRepositoryInstruction), targetRepositoryInstruction],
191
+ pluginInstructions: [...existingPluginInstructions.filter((instruction) => !isRunRepositoryInstruction(instruction)), targetRepositoryInstruction],
200
192
  ...untrustedCheckout ? {
201
193
  untrustedCheckout: true,
202
194
  ...baseRef ? { baseRef } : {}
@@ -1 +1 @@
1
- {"version":3,"file":"start-coordinator.js","names":[],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { hydrateFactorySession, resolveFactorySessionModel } from '../session/factory-session.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { externallyAuthoredWorkItem } from './types.js';\nimport type { FactoryRuleActor, FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /**\n * Who started the work, where that is not the session's owner: the Factory owns the\n * sessions it runs, and the move a start makes is still the mover's.\n */\n startedBy?: FactoryRuleActor;\n sessionId: string;\n expectedBindingId?: string;\n threadTitle: string;\n kickoffKey: string;\n /** Where the arrival path lands the card; a session opened on an existing card names none. */\n destinationStage?: FactoryRuleStage;\n /** The run's effective scope; a hybrid Factory's runs use the Factory's model and credentials. */\n modelScope: EffectiveModelScope;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n}\n\nexport class UntrustedSharedSessionError extends Error {\n constructor(readonly sessionId: string) {\n super(\n `Session ${sessionId} already shares memory with this Factory, so it cannot run untrusted content. Start the run in a new session.`,\n );\n this.name = 'UntrustedSharedSessionError';\n }\n}\n\n/**\n * The memory resource a run works on. Trusted runs share the Factory's resource.\n * A run that reads attacker-controllable content (a pull request checkout, or a\n * card written outside the write-access circle) keeps its own resource, so it can\n * neither plant observations that trusted runs read nor read what they observed.\n * A session that was isolated stays isolated; one already sharing memory refuses\n * untrusted work instead of carrying that memory into it.\n */\nasync function runMemoryResource(\n controller: Pick<FactoryController, 'queryThreadById'>,\n input: { sessionId: string; factoryProjectId: string; untrusted: boolean },\n): Promise<string> {\n const existing = await controller.queryThreadById({ threadId: input.sessionId });\n if (existing?.resourceId === input.sessionId) return input.sessionId;\n if (!input.untrusted) return existing?.resourceId ?? input.factoryProjectId;\n if (existing) throw new UntrustedSharedSessionError(input.sessionId);\n return input.sessionId;\n}\n\nexport class WorkItemRepositoryError extends Error {\n constructor(\n readonly code: 'repository_mismatch' | 'repository_ambiguous' | 'repository_unlinked',\n message: string,\n readonly candidates: string[] = [],\n ) {\n super(message);\n this.name = 'WorkItemRepositoryError';\n }\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession & { projectRepositoryId: string }> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepositoryId = session.projectRepositoryId;\n if (!projectRepositoryId) throw new Error('Factory session repository not found');\n const projectRepository = await storage.projectRepositories.get({ orgId: request.orgId, id: projectRepositoryId });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return { ...session, projectRepositoryId };\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n // Derived from the work item, not a user rename, so leave the title\n // unpinned and let auto-naming keep refining it.\n await session.thread.rename({ title: request.threadTitle, pin: false });\n await session.thread.setSetting({ key: 'factorySessionId', value: request.sessionId });\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>);\n readonly #intake?: IntakeStorage;\n readonly #projects?: FactoryProjectsStorage;\n readonly #modelDefaults?: ModelDefaultsStorage;\n readonly #boards?: ProjectBoardSource;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>),\n intake?: IntakeStorage,\n sessionModel?: { projects: FactoryProjectsStorage; modelDefaults: ModelDefaultsStorage },\n /** Tells a pull request review run from the card's other review runs; without it every review run with a pull request is untrusted. */\n boards?: BoardRegistry | ProjectBoardSource,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#intake = intake;\n this.#projects = sessionModel?.projects;\n this.#modelDefaults = sessionModel?.modelDefaults;\n this.#boards = boards ? toBoardSource(boards) : undefined;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n const sourceControl =\n typeof this.#sourceControl === 'function' ? await this.#sourceControl(request) : this.#sourceControl;\n if (!sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(sourceControl, request);\n const sessionModel =\n this.#projects && this.#modelDefaults\n ? await resolveFactorySessionModel({\n projects: this.#projects,\n modelDefaults: this.#modelDefaults,\n factoryProjectId: request.factoryProjectId,\n orgId: request.orgId,\n ownerUserId: sourceSession.userId,\n context: 'run',\n })\n : { modelScope: request.modelScope, modelId: request.defaultModelId };\n const storedItem = request.workItem.id\n ? await storage.get({ orgId: request.orgId, id: request.workItem.id })\n : null;\n const intakeConfig = await this.#intake?.getConfig({ orgId: request.orgId, integrationIds: ['linear'] });\n let repository = await resolveWorkItemRepository({\n sourceControl,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n item: storedItem ?? {\n metadata: request.workItem.input.metadata ?? null,\n workItem: { metadata: request.workItem.input.metadata ?? null },\n },\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n });\n if (repository.status === 'ambiguous') {\n // A retry of this role's existing session keeps its already-chosen\n // repository; a newly minted session must not choose for the card.\n if (storedItem?.sessions[request.workItem.role]?.sessionId !== sourceSession.sessionId) {\n throw new WorkItemRepositoryError(\n 'repository_ambiguous',\n `Choose a repository for this work item: ${repository.candidates.join(', ')}.`,\n repository.candidates,\n );\n }\n const link = await sourceControl.projectRepositories.get({\n orgId: request.orgId,\n id: sourceSession.projectRepositoryId,\n });\n const linked = link && (await sourceControl.repositories.get({ orgId: request.orgId, id: link.repositoryId }));\n const currentLinks = link\n ? await sourceControl.projectRepositories.list({ orgId: request.orgId, connectionId: link.connectionId })\n : [];\n if (\n !linked ||\n !repository.candidates.includes(linked.slug) ||\n !currentLinks.some(candidate => candidate.id === sourceSession.projectRepositoryId)\n ) {\n throw new WorkItemRepositoryError(\n 'repository_unlinked',\n 'The existing session repository is not linked to this Factory.',\n );\n }\n repository = { status: 'resolved', slug: linked.slug, projectRepositoryId: sourceSession.projectRepositoryId };\n }\n if (repository.status === 'unlinked') {\n throw new WorkItemRepositoryError('repository_unlinked', repository.hint);\n }\n if (repository.projectRepositoryId !== sourceSession.projectRepositoryId) {\n throw new WorkItemRepositoryError(\n 'repository_mismatch',\n `This run session is bound to a different repository than ${repository.slug}.`,\n );\n }\n const requestContext = request.requestContext ?? new RequestContext();\n // Preserve an authenticated caller when present. Autonomous starts still\n // need a principal so deployed credential resolution can authenticate the\n // request before selecting the stamped session owner's exclusive scope.\n const existingUser = requestContext.get('user');\n if (!existingUser || typeof existingUser !== 'object') {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n // An issue card's PR review checks out the attached pull request's head, so it counts too.\n // The run's stage is where the card is going: a card started from its resting phase into\n // its board's pull request review is moved only after the session is ready.\n const runStage = request.destinationStage ?? storedItem?.stages[0];\n const reviewsAttachedPullRequest =\n request.workItem.role === REVIEW_CONTEXT &&\n storedItem != null &&\n hasPullRequest({ workItem: storedItem.workItem }) &&\n (!this.#boards ||\n isPullRequestReviewPhase((await this.#boards.load(request)).get(boardForWorkItem(storedItem)), runStage));\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' || reviewsAttachedPullRequest;\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = storedItem\n ? storedItem.workItem.metadata?.baseBranch\n : request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const memoryResourceId = await runMemoryResource(this.#controller, {\n sessionId: sourceSession.sessionId,\n factoryProjectId: request.factoryProjectId,\n untrusted:\n untrustedCheckout ||\n externallyAuthoredWorkItem(\n storedItem ?? {\n externalSource: request.workItem.input.externalSource ?? null,\n metadata: request.workItem.input.metadata ?? null,\n },\n ),\n });\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n // The run is addressed by its session id; its threads and memory belong to\n // the Factory, so concurrent runs share one memory resource.\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: memoryResourceId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n const targetRepositoryInstruction = `Target repository: ${repository.slug}. Before editing files or creating a pull request, verify this session's checkout matches the target repository.`;\n const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: sourceSession.userId,\n pluginInstructions: [\n ...existingPluginInstructions.filter(instruction => instruction !== targetRepositoryInstruction),\n targetRepositoryInstruction,\n ],\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n await primeTenantCredentialsForTenant({\n orgId: request.orgId,\n userId: sourceSession.userId,\n credentialScope: sessionModel.modelScope,\n });\n // Apply the factory's main model before any model-dependent run work.\n // Observational-memory settings are loaded per invocation by the input processor.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: sourceSession.userId,\n defaultModelId: sessionModel.modelId,\n });\n // The tool is `requireApproval`, and that prompt parks the run whether or not\n // someone pressed Start — a person is reading the plan, not an approval queue.\n // Starting the run was already the say-so; the rules engine still governs.\n await session.permissions.setForTool({ toolName: 'factory_transition_work_item', policy: 'allow' });\n const threadId = await configureThread(session, request);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n expectedBindingId: request.expectedBindingId,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: memoryResourceId,\n kickoffKey: request.kickoffKey,\n kickoffMessage: null,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n const destinationStage = request.destinationStage;\n if (destinationStage && (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== destinationStage)) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: boardForWorkItem(prepared.item),\n stage: destinationStage,\n expectedRevision: prepared.item.revision,\n actor:\n request.startedBy ??\n (isFactoryPrincipalId(request.userId)\n ? { type: 'system', id: request.userId }\n : { type: 'human', id: request.userId }),\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed');\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: memoryResourceId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AA+CA,IAAa,8BAAb,cAAiD,MAAM;CAChC;CAArB,YAAY,WAA4B;EACtC,MACE,WAAW,UAAU,8GACvB;EAHmB,KAAA,YAAA;EAInB,KAAK,OAAO;CACd;AACF;;;;;;;;;AAUA,eAAe,kBACb,YACA,OACiB;CACjB,MAAM,WAAW,MAAM,WAAW,gBAAgB,EAAE,UAAU,MAAM,UAAU,CAAC;CAC/E,IAAI,UAAU,eAAe,MAAM,WAAW,OAAO,MAAM;CAC3D,IAAI,CAAC,MAAM,WAAW,OAAO,UAAU,cAAc,MAAM;CAC3D,IAAI,UAAU,MAAM,IAAI,4BAA4B,MAAM,SAAS;CACnE,OAAO,MAAM;AACf;AAEA,IAAa,0BAAb,cAA6C,MAAM;CAEtC;CAEA;CAHX,YACE,MACA,SACA,aAAgC,CAAC,GACjC;EACA,MAAM,OAAO;EAJJ,KAAA,OAAA;EAEA,KAAA,aAAA;EAGT,KAAK,OAAO;CACd;AACF;AAEA,IAAa,8BAAb,cAAiD,MAAM;CACrD;CAEA,YAAY,QAAkE;EAC5E,MAAM,OAAO,MAAM;EACnB,KAAK,OAAO;EACZ,KAAK,SAAS;CAChB;AACF;AAiBA,eAAe,qBACb,SACA,SACiE;CACjE,MAAM,UAAU,MAAM,QAAQ,SAAS,eAAe,QAAQ,SAAS;CACvE,IAAI,CAAC,WAAW,QAAQ,UAAU,QAAQ,SAAS,QAAQ,WAAW,QAAQ,QAC5E,MAAM,IAAI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;GACZ,YAAY,QAAQ;GACpB,gBAAgB;EAClB,CAAC;EACD,MAAM,QAAQ,OAAO,WAAW;GAAE,KAAK;GAAqB,OAAO,SAAS,KAAK;EAAG,CAAC;EAErF,IAAI,WAAW,SAAS,KAAK;EAC7B,MAAM,mBAAmB,QAAQ;EACjC,IAAI,qBAAqB,SAAS,KAAK,OAAO,WAAW,KAAK,SAAS,KAAK,OAAO,OAAO,mBAAmB;GAC3G,IAAI,CAAC,KAAK,oBAAoB,MAAM,IAAI,MAAM,4CAA4C;GAC1F,MAAM,aAAa,MAAM,KAAK,mBAAmB,WAAW;IAC1D,OAAO,QAAQ;IACf,kBAAkB,QAAQ;IAC1B,YAAY,SAAS,KAAK;IAC1B,OAAO,iBAAiB,SAAS,IAAI;IACrC,OAAO;IACP,kBAAkB,SAAS,KAAK;IAChC,OACE,QAAQ,cACP,qBAAqB,QAAQ,MAAM,IAChC;KAAE,MAAM;KAAU,IAAI,QAAQ;IAAO,IACrC;KAAE,MAAM;KAAS,IAAI,QAAQ;IAAO;IAC1C,SAAS;KAAE,MAAM;KAAS,UAAU,SAAS,QAAQ,WAAW;IAAa;IAC7E,OAAO;GACT,CAAC;GACD,IAAI,WAAW,WAAW,YAAY;IACpC,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,QAAQ;IAC5D,MAAM,IAAI,4BAA4B,UAAU;GAClD;GACA,WAAW,WAAW;EACxB;EAEA,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,MAAM;EAC1D,SAAS,aAAa,SAAS;EAE/B,OAAO;GACL,YAAY,SAAS,KAAK;GAC1B,WAAW,SAAS,QAAQ;GAC5B;GACA,YAAY;GACZ,WAAW,cAAc;GACzB,QAAQ,cAAc;GACtB;GACA,eAAe,SAAS,aAAa;GACrC,UAAU,SAAS;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"start-coordinator.js","names":[],"sources":["../../src/rules/start-coordinator.ts"],"sourcesContent":["import type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport { RequestContext } from '@mastra/core/request-context';\n\nimport { boardForWorkItem, hasPullRequest, isPullRequestReviewPhase, REVIEW_CONTEXT } from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport { primeTenantCredentialsForTenant } from '../routes/tenant-credentials.js';\nimport { hydrateFactorySession, resolveFactorySessionModel } from '../session/factory-session.js';\nimport {\n isRunRepositoryInstruction,\n repositoryChosenByRun,\n resolveRunRepository,\n runRepositoryInstruction,\n} from '../session/work-item-repository.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { EffectiveModelScope, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlSession, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { CreateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { externallyAuthoredWorkItem } from './types.js';\nimport type { FactoryRuleActor, FactoryRuleStage, FactoryTransitionResult } from './types.js';\n\nexport interface FactoryStartRequest {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /**\n * Who started the work, where that is not the session's owner: the Factory owns the\n * sessions it runs, and the move a start makes is still the mover's.\n */\n startedBy?: FactoryRuleActor;\n sessionId: string;\n expectedBindingId?: string;\n threadTitle: string;\n kickoffKey: string;\n /** Where the arrival path lands the card; a session opened on an existing card names none. */\n destinationStage?: FactoryRuleStage;\n /** The run's effective scope; a hybrid Factory's runs use the Factory's model and credentials. */\n modelScope: EffectiveModelScope;\n defaultModelId?: string;\n workItem: {\n id?: string;\n role: string;\n input: CreateWorkItemInput;\n };\n requestContext?: RequestContext;\n}\n\nexport class UntrustedSharedSessionError extends Error {\n constructor(readonly sessionId: string) {\n super(\n `Session ${sessionId} already shares memory with this Factory, so it cannot run untrusted content. Start the run in a new session.`,\n );\n this.name = 'UntrustedSharedSessionError';\n }\n}\n\n/**\n * The memory resource a run works on. Trusted runs share the Factory's resource.\n * A run that reads attacker-controllable content (a pull request checkout, or a\n * card written outside the write-access circle) keeps its own resource, so it can\n * neither plant observations that trusted runs read nor read what they observed.\n * A session that was isolated stays isolated; one already sharing memory refuses\n * untrusted work instead of carrying that memory into it.\n */\nasync function runMemoryResource(\n controller: Pick<FactoryController, 'queryThreadById'>,\n input: { sessionId: string; factoryProjectId: string; untrusted: boolean },\n): Promise<string> {\n const existing = await controller.queryThreadById({ threadId: input.sessionId });\n if (existing?.resourceId === input.sessionId) return input.sessionId;\n if (!input.untrusted) return existing?.resourceId ?? input.factoryProjectId;\n if (existing) throw new UntrustedSharedSessionError(input.sessionId);\n return input.sessionId;\n}\n\nexport class WorkItemRepositoryError extends Error {\n constructor(\n readonly code: 'repository_mismatch' | 'repository_unlinked',\n message: string,\n ) {\n super(message);\n this.name = 'WorkItemRepositoryError';\n }\n}\n\nexport class FactoryStartTransitionError extends Error {\n readonly result: Extract<FactoryTransitionResult, { status: 'rejected' }>;\n\n constructor(result: Extract<FactoryTransitionResult, { status: 'rejected' }>) {\n super(result.reason);\n this.name = 'FactoryStartTransitionError';\n this.result = result;\n }\n}\n\nexport interface FactoryStartPreparedResult {\n workItemId: string;\n bindingId: string;\n threadId: string;\n resourceId: string;\n sessionId: string;\n branch: string;\n revision: number;\n kickoffStatus: 'pending' | 'leased' | 'retry' | 'sent' | 'failed';\n replayed: boolean;\n}\n\ntype FactoryController = AgentController<MastraCodeState>;\ntype FactorySession = Awaited<ReturnType<FactoryController['createSession']>>;\n\nasync function resolveSourceSession(\n storage: SourceControlStorageHandle,\n request: FactoryStartRequest,\n): Promise<SourceControlSession & { projectRepositoryId: string }> {\n const session = await storage.sessions.getBySessionId(request.sessionId);\n if (!session || session.orgId !== request.orgId || session.userId !== request.userId) {\n throw new Error('Factory session not found');\n }\n const projectRepositoryId = session.projectRepositoryId;\n if (!projectRepositoryId) throw new Error('Factory session repository not found');\n const projectRepository = await storage.projectRepositories.get({ orgId: request.orgId, id: projectRepositoryId });\n if (!projectRepository) throw new Error('Factory session repository not found');\n const connection = await storage.connections.get({ orgId: request.orgId, id: projectRepository.connectionId });\n if (!connection || connection.factoryProjectId !== request.factoryProjectId) {\n throw new Error('Factory session does not belong to this project');\n }\n return { ...session, projectRepositoryId };\n}\n\nasync function sessionRepositorySlug(\n storage: SourceControlStorageHandle,\n orgId: string,\n projectRepositoryId: string,\n): Promise<string> {\n const link = await storage.projectRepositories.get({ orgId, id: projectRepositoryId });\n const repository = link && (await storage.repositories.get({ orgId, id: link.repositoryId }));\n if (!repository) throw new Error('Factory session repository not found');\n return repository.slug;\n}\n\nasync function configureThread(session: FactorySession, request: FactoryStartRequest): Promise<string> {\n const threadId = session.thread.requireId();\n // Derived from the work item, not a user rename, so leave the title\n // unpinned and let auto-naming keep refining it.\n await session.thread.rename({ title: request.threadTitle, pin: false });\n await session.thread.setSetting({ key: 'factorySessionId', value: request.sessionId });\n return threadId;\n}\n\nexport class FactoryStartCoordinator {\n readonly #controller: FactoryController;\n readonly #storage: WorkItemsStorage;\n readonly #transitionService?: Pick<FactoryTransitionService, 'transition'>;\n readonly #sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>);\n readonly #intake?: IntakeStorage;\n readonly #projects?: FactoryProjectsStorage;\n readonly #modelDefaults?: ModelDefaultsStorage;\n readonly #boards?: ProjectBoardSource;\n\n constructor(\n controller: FactoryController,\n storage: WorkItemsStorage,\n transitionService?: Pick<FactoryTransitionService, 'transition'>,\n sourceControl?:\n | SourceControlStorageHandle\n | ((\n request: FactoryStartRequest,\n ) => SourceControlStorageHandle | undefined | Promise<SourceControlStorageHandle | undefined>),\n intake?: IntakeStorage,\n sessionModel?: { projects: FactoryProjectsStorage; modelDefaults: ModelDefaultsStorage },\n /** Tells a pull request review run from the card's other review runs; without it every review run with a pull request is untrusted. */\n boards?: BoardRegistry | ProjectBoardSource,\n ) {\n this.#controller = controller;\n this.#storage = storage;\n this.#transitionService = transitionService;\n this.#sourceControl = sourceControl;\n this.#intake = intake;\n this.#projects = sessionModel?.projects;\n this.#modelDefaults = sessionModel?.modelDefaults;\n this.#boards = boards ? toBoardSource(boards) : undefined;\n }\n\n async prepare(request: FactoryStartRequest): Promise<FactoryStartPreparedResult> {\n const storage = this.#storage;\n const sourceControl =\n typeof this.#sourceControl === 'function' ? await this.#sourceControl(request) : this.#sourceControl;\n if (!sourceControl) throw new Error('Factory source control storage is unavailable');\n const sourceSession = await resolveSourceSession(sourceControl, request);\n const sessionModel =\n this.#projects && this.#modelDefaults\n ? await resolveFactorySessionModel({\n projects: this.#projects,\n modelDefaults: this.#modelDefaults,\n factoryProjectId: request.factoryProjectId,\n orgId: request.orgId,\n ownerUserId: sourceSession.userId,\n context: 'run',\n })\n : { modelScope: request.modelScope, modelId: request.defaultModelId };\n const storedItem = request.workItem.id\n ? await storage.get({ orgId: request.orgId, id: request.workItem.id })\n : null;\n const intakeConfig = await this.#intake?.getConfig({ orgId: request.orgId, integrationIds: ['linear'] });\n const runItem = storedItem ?? {\n metadata: request.workItem.input.metadata ?? null,\n workItem: { metadata: request.workItem.input.metadata ?? null },\n };\n // A card that names no repository runs in the session's own repository,\n // and its agent determines from the card which repository to work in.\n const repository = await resolveRunRepository({\n sourceControl,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n item: runItem,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n boundProjectRepositoryId: sourceSession.projectRepositoryId,\n });\n if (repository.status === 'unlinked') {\n throw new WorkItemRepositoryError('repository_unlinked', repository.hint);\n }\n if (\n repository.projectRepositoryId !== sourceSession.projectRepositoryId &&\n !repositoryChosenByRun(runItem, repository.slug)\n ) {\n throw new WorkItemRepositoryError(\n 'repository_mismatch',\n `This run session is bound to a different repository than ${repository.slug}.`,\n );\n }\n const ownSlug =\n repository.projectRepositoryId === sourceSession.projectRepositoryId\n ? repository.slug\n : await sessionRepositorySlug(sourceControl, request.orgId, sourceSession.projectRepositoryId);\n const requestContext = request.requestContext ?? new RequestContext();\n // Preserve an authenticated caller when present. Autonomous starts still\n // need a principal so deployed credential resolution can authenticate the\n // request before selecting the stamped session owner's exclusive scope.\n const existingUser = requestContext.get('user');\n if (!existingUser || typeof existingUser !== 'object') {\n requestContext.set('user', {\n workosId: request.userId,\n organizationId: request.orgId,\n });\n }\n // Sessions kicked off against third-party content (a PR under review, or\n // any pull-request-sourced work item) get `untrustedCheckout` so the SDK\n // never ingests the checkout's AGENTS.md/CLAUDE.md into the system prompt\n // or reminders — those files are attacker-writable in a PR branch.\n // An issue card's PR review checks out the attached pull request's head, so it counts too.\n // The run's stage is where the card is going: a card started from its resting phase into\n // its board's pull request review is moved only after the session is ready.\n const runStage = request.destinationStage ?? storedItem?.stages[0];\n const reviewsAttachedPullRequest =\n request.workItem.role === REVIEW_CONTEXT &&\n storedItem != null &&\n hasPullRequest({ workItem: storedItem.workItem }) &&\n (!this.#boards ||\n isPullRequestReviewPhase((await this.#boards.load(request)).get(boardForWorkItem(storedItem)), runStage));\n const untrustedCheckout =\n request.workItem.input.externalSource?.type === 'pull-request' || reviewsAttachedPullRequest;\n // The trusted ref the SDK may serve project instruction files from on an\n // untrusted checkout (the PR's base branch). Prefer the session record's\n // base branch; fall back to the intake metadata captured from the PR.\n const metadataBaseBranch = storedItem\n ? storedItem.workItem.metadata?.baseBranch\n : request.workItem.input.metadata?.baseBranch;\n const baseRef =\n (sourceSession.baseBranch || undefined) ??\n (typeof metadataBaseBranch === 'string' && metadataBaseBranch ? metadataBaseBranch : undefined);\n const memoryResourceId = await runMemoryResource(this.#controller, {\n sessionId: sourceSession.sessionId,\n factoryProjectId: request.factoryProjectId,\n untrusted:\n untrustedCheckout ||\n externallyAuthoredWorkItem(\n storedItem ?? {\n externalSource: request.workItem.input.externalSource ?? null,\n metadata: request.workItem.input.metadata ?? null,\n },\n ),\n });\n const sessionTags = {\n factoryProjectId: request.factoryProjectId,\n projectRepositoryId: sourceSession.projectRepositoryId,\n };\n // The run is addressed by its session id; its threads and memory belong to\n // the Factory, so concurrent runs share one memory resource.\n const session = await this.#controller.createSession({\n id: sourceSession.sessionId,\n ownerId: request.userId,\n resourceId: memoryResourceId,\n threadId: sourceSession.sessionId,\n requestContext,\n tags: sessionTags,\n });\n // Bound-agent authority gates (the transition tool, the factory-phase\n // processor, workspace token selection) resolve the session address from\n // controller state. Seed it server-side — `tags` covers fresh creation,\n // the explicit setState covers get-or-create returning a session another\n // caller created without them — so autonomous runs never depend on a\n // browser connecting to populate the state. `untrustedCheckout` is a\n // boolean so it rides only on state (tags are string-valued).\n const targetRepositoryInstruction = runRepositoryInstruction(repository, ownSlug);\n const existingPluginInstructions = session.state.get()?.pluginInstructions ?? [];\n await session.state.set({\n ...sessionTags,\n // The authoritative org id for every downstream identity read (the\n // memory seam's organizationId): the session owner is a USER id, not an\n // org, so it must never be improvised from ownerId.\n factoryOrgId: request.orgId,\n factoryModelScope: sessionModel.modelScope,\n factoryOwnerUserId: sourceSession.userId,\n pluginInstructions: [\n ...existingPluginInstructions.filter(instruction => !isRunRepositoryInstruction(instruction)),\n targetRepositoryInstruction,\n ],\n ...(untrustedCheckout ? { untrustedCheckout: true, ...(baseRef ? { baseRef } : {}) } : {}),\n });\n await primeTenantCredentialsForTenant({\n orgId: request.orgId,\n userId: sourceSession.userId,\n credentialScope: sessionModel.modelScope,\n });\n // Apply the factory's main model before any model-dependent run work.\n // Observational-memory settings are loaded per invocation by the input processor.\n await hydrateFactorySession(session, {\n orgId: request.orgId,\n modelScope: sessionModel.modelScope,\n ownerUserId: sourceSession.userId,\n defaultModelId: sessionModel.modelId,\n });\n // The tool is `requireApproval`, and that prompt parks the run whether or not\n // someone pressed Start — a person is reading the plan, not an approval queue.\n // Starting the run was already the say-so; the rules engine still governs.\n await session.permissions.setForTool({ toolName: 'factory_transition_work_item', policy: 'allow' });\n const threadId = await configureThread(session, request);\n const prepared = await storage.prepareRunStart({\n orgId: request.orgId,\n userId: request.userId,\n factoryProjectId: request.factoryProjectId,\n workItem: { id: request.workItem.id, input: request.workItem.input },\n role: request.workItem.role,\n expectedBindingId: request.expectedBindingId,\n session: { sessionId: sourceSession.sessionId, branch: sourceSession.branch, threadId },\n resourceId: memoryResourceId,\n kickoffKey: request.kickoffKey,\n kickoffMessage: null,\n });\n await session.thread.setSetting({ key: 'factoryWorkItemId', value: prepared.item.id });\n\n let revision = prepared.item.revision;\n const destinationStage = request.destinationStage;\n if (destinationStage && (prepared.item.stages.length !== 1 || prepared.item.stages[0] !== destinationStage)) {\n if (!this.#transitionService) throw new Error('Factory transition service is unavailable.');\n const transition = await this.#transitionService.transition({\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n workItemId: prepared.item.id,\n board: boardForWorkItem(prepared.item),\n stage: destinationStage,\n expectedRevision: prepared.item.revision,\n actor:\n request.startedBy ??\n (isFactoryPrincipalId(request.userId)\n ? { type: 'system', id: request.userId }\n : { type: 'human', id: request.userId }),\n ingress: { type: 'human', identity: `start:${request.kickoffKey}:transition` },\n cause: 'run_start',\n });\n if (transition.status === 'rejected') {\n await storage.markPendingStart(prepared.binding.id, 'failed');\n throw new FactoryStartTransitionError(transition);\n }\n revision = transition.revision;\n }\n\n await storage.markPendingStart(prepared.binding.id, 'sent');\n prepared.pendingStart.status = 'sent';\n\n return {\n workItemId: prepared.item.id,\n bindingId: prepared.binding.id,\n threadId,\n resourceId: memoryResourceId,\n sessionId: sourceSession.sessionId,\n branch: sourceSession.branch,\n revision,\n kickoffStatus: prepared.pendingStart.status,\n replayed: prepared.replayed,\n };\n }\n}\n"],"mappings":";;;;;;;;;;;AAoDA,IAAa,8BAAb,cAAiD,MAAM;CAChC;CAArB,YAAY,WAA4B;EACtC,MACE,WA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W;IAAa;IAC7E,OAAO;GACT,CAAC;GACD,IAAI,WAAW,WAAW,YAAY;IACpC,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,QAAQ;IAC5D,MAAM,IAAI,4BAA4B,UAAU;GAClD;GACA,WAAW,WAAW;EACxB;EAEA,MAAM,QAAQ,iBAAiB,SAAS,QAAQ,IAAI,MAAM;EAC1D,SAAS,aAAa,SAAS;EAE/B,OAAO;GACL,YAAY,SAAS,KAAK;GAC1B,WAAW,SAAS,QAAQ;GAC5B;GACA,YAAY;GACZ,WAAW,cAAc;GACzB,QAAQ,cAAc;GACtB;GACA,eAAe,SAAS,aAAa;GACrC,UAAU,SAAS;EACrB;CACF;AACF"}
@@ -1,6 +1,7 @@
1
1
  import "../boards/index.js";
2
2
  import { toBoardSource } from "../boards/project-boards.js";
3
- import { boardFlow, boardForWorkItem, cardBoardFlow, hasPullRequest, isPullRequestCard, reviewedChangeRequest, workItemPhaseSemantics } from "../boards/semantics.js";
3
+ import { isPullRequestCard } from "../work-items/change-requests.js";
4
+ import { boardFlow, boardForWorkItem, cardBoardFlow, hasPullRequest, reviewedChangeRequest, workItemPhaseSemantics } from "../boards/semantics.js";
4
5
  import { WorkItemUpdateConflictError } from "../storage/domains/work-items/base.js";
5
6
  import { resolveFactorySessionAddress } from "./binding-context.js";
6
7
  import { phaseGrantsTool } from "./phase-tools.js";
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","names":[],"sources":["../../src/rules/tools.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport {\n boardFlow,\n boardForWorkItem,\n cardBoardFlow,\n hasPullRequest,\n isPullRequestCard,\n reviewedChangeRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactorySessionSourceLookup } from './binding-context.js';\nimport { resolveFactorySessionAddress } from './binding-context.js';\nimport { phaseGrantsTool } from './phase-tools.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { SELF_REVIEW_ROUND_LIMIT, workItemSource } from './types.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from './validation.js';\n\nconst MAX_RATIONALE_LENGTH = 1_000;\n\nconst transitionInputSchema = z\n .object({\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n expectedRevision: z.number().int().positive(),\n // Providers strip maxLength from the JSON schema and models can't count characters, so a\n // hard cap invites overshoot-retry loops at the end of every run. Accept and clamp instead.\n rationale: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_RATIONALE_LENGTH ? value : `${value.slice(0, MAX_RATIONALE_LENGTH - 1)}…`,\n ),\n // Triage used to report a classification here, and sessions keep that call in their history\n // across role rotations and restarts. Accept the stale key and ignore it, rather than fail a\n // call an agent copied from that history and send it into a retry loop.\n triageType: z.unknown().optional().describe('Ignored. Factory no longer records a triage classification.'),\n })\n .strict();\n\nexport async function createFactoryTransitionTools(options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n boards?: BoardRegistry | ProjectBoardSource;\n}): Promise<IntegrationTools> {\n const resolution = await resolveFactorySessionAddress({\n requestContext: options.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n if (!resolution) return {};\n const availableBinding = resolution.binding ?? (await options.storage.findActiveRunBinding(resolution.address));\n if (!availableBinding) {\n // No live binding for this session. A resumed session whose binding was\n // revoked when its work item reached a terminal stage was retired out from\n // under the model: rather than silently drop the tool — which leaves the\n // resumed run to rationalize a false blocked state — surface a tool that\n // fails with the concrete reason. Threads that were never bound (or whose\n // binding was rotated to a peer role, leaving the item still in flight) get\n // no tool as before.\n const retired = await options.storage.findRunBindingBySession(resolution.address);\n if (retired && retired.status === 'revoked' && options.boards) {\n const item = await options.storage.get({ orgId: retired.orgId, id: retired.workItemId });\n if (\n item &&\n workItemPhaseSemantics(await toBoardSource(options.boards).load(retired), item)?.kind === 'terminal'\n ) {\n return { factory_transition_work_item: createRetiredSessionTool(retired.workItemId, item.stages[0]) };\n }\n }\n return {};\n }\n // Tools are built for every turn, so a card that moves on takes its phase's tools with it.\n // A failed lookup grants no phase tools but keeps the move tool.\n const recordsVerdict = await options.storage\n .get({ orgId: availableBinding.orgId, id: availableBinding.workItemId })\n .then(item =>\n item ? phaseGrantsTool(options.boards, availableBinding, item, 'factory_record_review_verdict') : false,\n )\n .catch(() => false);\n\n return {\n ...(recordsVerdict ? createReviewVerdictTool(options, availableBinding.workItemId) : {}),\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n 'Request a governed stage transition for the Factory work item exactly bound to this thread. Use the current revision from the factory-phase signal and explain why the transition is appropriate.',\n inputSchema: transitionInputSchema,\n requireApproval: true,\n execute: async ({ stage, expectedRevision, rationale }, execution) => {\n const currentResolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const currentAddress = currentResolution?.address ?? null;\n const toolCallId = execution.agent?.toolCallId;\n if (!currentAddress || !toolCallId) {\n throw new Error('Factory transitions require an authenticated bound agent tool call.');\n }\n const binding = await options.storage.findActiveRunBinding(currentAddress);\n // Authority is the work item this session is bound to, not the individual\n // binding row. Handing the next role its turn in an existing session\n // rotates the binding, and tools built for the previous role stay live\n // across that rotation; keying on row identity would strand the run that\n // the rotation exists to start. Re-pointing a session at a different item\n // is the hijack this guards against.\n if (!binding || binding.workItemId !== availableBinding.workItemId) {\n throw new Error('Factory agent binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n const board = boardForWorkItem(item);\n\n const result = await options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board,\n stage,\n expectedRevision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${toolCallId}` },\n cause: rationale,\n });\n\n return result;\n },\n }),\n };\n}\n\nexport const REVIEW_VERDICTS = ['approve', 'request changes'] as const;\n\nconst MAX_SELF_REVIEW_FINDINGS_LENGTH = 20_000;\n\nconst reviewVerdictInputSchema = z.object({\n verdict: z.enum(REVIEW_VERDICTS),\n reviewedHeadSha: z\n .string()\n .regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i, 'Use the full commit SHA of the reviewed head.'),\n findings: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_SELF_REVIEW_FINDINGS_LENGTH\n ? value\n : `${value.slice(0, MAX_SELF_REVIEW_FINDINGS_LENGTH - 1)}…`,\n )\n .optional()\n .describe(\n 'Self-review only: the findings and test report, in Markdown. On request changes the builder receives them; on approve they go in the change request body.',\n ),\n});\n\n/**\n * A review pass ends by recording its verdict on the card, which stays in\n * Reviewing: Done is reserved for the merge, and a verdict is not a lane. The\n * next push re-reviews from the recorded verdict.\n */\nfunction createReviewVerdictTool(\n options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n boards?: BoardRegistry | ProjectBoardSource;\n },\n boundWorkItemId: string,\n): IntegrationTools {\n return {\n factory_record_review_verdict: createTool({\n id: 'factory_record_review_verdict',\n description:\n 'Record the review verdict and the head SHA it covers on the card bound to this thread, ending the review pass. In the phase that reviews pull requests it records the published PR verdict and the card stays put. In a self-review phase with no change request open yet, approve keeps the card in place for you to open the change request from the approved head; once a GitHub pull request opens from that head, Factory moves the card to pull request review itself (elsewhere, move it with factory_transition_work_item). Request changes sends it back to the build phase with your findings.',\n inputSchema: reviewVerdictInputSchema,\n requireApproval: false,\n execute: async ({ verdict, reviewedHeadSha, findings }, execution) => {\n const resolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const binding = resolution ? await options.storage.findActiveRunBinding(resolution.address) : null;\n if (!binding || binding.workItemId !== boundWorkItemId) {\n throw new Error('Factory review binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n // The card may have moved since the tools were built for this turn.\n if (!(await phaseGrantsTool(options.boards, binding, item, 'factory_record_review_verdict'))) {\n throw new Error(\n `This session does not review the card in its current phase (${item.stages.join(', ')}); it cannot record a verdict.`,\n );\n }\n const boards = await toBoardSource(options.boards).load(binding);\n const boardId = boardForWorkItem(item);\n const board = boards.get(boardId);\n const flow = boardFlow(board);\n const stage = item.stages[0];\n const source = workItemSource(item.externalSource);\n const pullRequestCard = isPullRequestCard({ source });\n if (\n board &&\n stage === flow.selfReview &&\n !pullRequestCard &&\n typeof item.metadata?.openPullRequestNumber !== 'number'\n ) {\n return recordSelfReviewVerdict({\n storage: options.storage,\n transitionService: options.transitionService,\n binding,\n item,\n board: boardId,\n // Requested changes go back to the builder; a board without a build phase rests the card.\n buildPhase: flow.build ?? board.initialPhase,\n parkPhase: board.initialPhase,\n verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n findings,\n toolCallId: execution.agent?.toolCallId,\n });\n }\n if (\n stage === undefined ||\n stage !== flow.pullRequestReview ||\n !hasPullRequest({ source, workItem: item.workItem })\n ) {\n const where = flow.pullRequestReview\n ? (board?.phases[flow.pullRequestReview]?.name ?? flow.pullRequestReview)\n : undefined;\n throw new Error(\n where\n ? `Only a card with a pull request in ${where} records a verdict; this one is in ${item.stages.join(', ')}.`\n : `The ${board?.name ?? boardId} board reviews no pull requests, so this card in ${item.stages.join(', ')} records no verdict.`,\n );\n }\n // An issue card can carry several pull requests; the verdict names the one it covers.\n const reviewedNumber = reviewedChangeRequest({ ...item, source })?.number;\n const reviewedAt = new Date().toISOString();\n // Revision-checked, so a merge that moves the card between the stage\n // check and this write fails the call instead of stamping a Done card.\n try {\n await options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n ...(item.metadata ?? {}),\n reviewVerdict: verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n reviewedAt,\n ...(reviewedNumber !== undefined ? { reviewedPullRequestNumber: reviewedNumber } : {}),\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error(\n 'The Review card changed while recording the verdict; call again to record it on the current card.',\n );\n }\n // Mirror the verdict onto the card that authored the PR, so its\n // builder cannot close the work while changes are still requested.\n const parent = item.parentWorkItemId\n ? await options.storage.get({ orgId: binding.orgId, id: item.parentWorkItemId })\n : null;\n if (parent && cardBoardFlow(boards, parent).build !== undefined) {\n await options.storage.update({\n orgId: binding.orgId,\n id: parent.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n reviewVerdict: verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n reviewedAt,\n ...(reviewedNumber !== undefined ? { reviewedPullRequestNumber: reviewedNumber } : {}),\n },\n },\n });\n }\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt };\n },\n }),\n };\n}\n\n/**\n * Self-review ends the same way a PR review does, but on the authoring card before\n * any change request exists, and it moves the card itself: the verdict is the\n * only thing that decides where the work goes next.\n */\nasync function recordSelfReviewVerdict(input: {\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n binding: { id: string; orgId: string; factoryProjectId: string; workItemId: string; role: string };\n item: Card;\n board: string;\n buildPhase: string;\n parkPhase: string;\n verdict: (typeof REVIEW_VERDICTS)[number];\n reviewedHeadSha: string;\n findings: string | undefined;\n toolCallId: string | undefined;\n}) {\n const { storage, binding, item, verdict, reviewedHeadSha, findings } = input;\n if (!input.toolCallId) throw new Error('Self-review verdicts require an authenticated bound agent tool call.');\n const reviewedAt = new Date().toISOString();\n const previousRounds = typeof item.metadata?.selfReviewRounds === 'number' ? item.metadata.selfReviewRounds : 0;\n const rounds = verdict === 'request changes' ? previousRounds + 1 : previousRounds;\n // Every SELF_REVIEW_ROUND_LIMIT rounds the card rests in its board's initial phase for a person\n // instead of looping; moving it back to the build phase grants another full set of rounds.\n const parked = verdict === 'request changes' && rounds % SELF_REVIEW_ROUND_LIMIT === 0;\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n selfReviewVerdict: verdict,\n selfReviewedHeadSha: reviewedHeadSha,\n selfReviewedAt: reviewedAt,\n selfReviewFindings: findings ?? null,\n selfReviewRounds: rounds,\n selfReviewNeedsHuman: parked,\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error('The card changed while recording the verdict; call again to record it on the current card.');\n }\n if (!updated) throw new Error('Bound Factory work item not found.');\n if (verdict === 'approve')\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt, selfReviewRounds: rounds };\n const transition = await input.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board: input.board,\n stage: parked ? input.parkPhase : input.buildPhase,\n expectedRevision: updated.item.revision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${input.toolCallId}` },\n cause: parked\n ? `Self-review requested changes ${rounds} times; parked for a person to decide how to proceed.`\n : `Self-review requested changes on ${reviewedHeadSha} (round ${rounds}).`,\n });\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt, selfReviewRounds: rounds, transition };\n}\n\n/**\n * A retired session's transition tool: it exists only to fail loudly. The run's\n * binding was revoked when its work item settled at a terminal stage, so there\n * is nothing to transition. Registering it (instead of dropping the tool) stops\n * a resumed model from inventing a false \"blocked\" state when the affordance it\n * expects has silently vanished.\n */\nfunction createRetiredSessionTool(workItemId: string, stage: string | undefined): IntegrationTools[string] {\n return createTool({\n id: 'factory_transition_work_item',\n description:\n 'This Factory session has been retired: its work item already reached a terminal stage and the run binding was revoked. No further transitions can be requested from this session.',\n inputSchema: transitionInputSchema,\n requireApproval: false,\n execute: async () => {\n throw new Error(\n `This Factory session has been retired: work item ${workItemId} reached a terminal stage${\n stage ? ` (${stage})` : ''\n } and its run binding was revoked. No transition can be requested from this session.`,\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;AA0BA,MAAM,uBAAuB;AAE7B,MAAM,wBAAwB,EAC3B,OAAO;CACN,OAAO,EAAE,OAAO,CAAC,CAAC,IAAA,GAA+B,CAAC,CAAC,MAAM,mBAAmB;CAC5E,kBAAkB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CAG5C,WAAW,EACR,OAAO,CAAC,CACR,KAAK,CAAC,CACN,IAAI,CAAC,CAAC,CACN,WAAU,UACT,MAAM,UAAU,uBAAuB,QAAQ,GAAG,MAAM,MAAM,GAAG,GAAwB,EAAE,EAC7F;CAIF,YAAY,EAAE,QAAQ,CAAC,CAAC,SAAS,CAAC,CAAC,SAAS,6DAA6D;AAC3G,CAAC,CAAC,CACD,OAAO;AAEV,eAAsB,6BAA6B,SAMrB;CAC5B,MAAM,aAAa,MAAM,6BAA6B;EACpD,gBAAgB,QAAQ;EACxB,SAAS,QAAQ;EACjB,UAAU,QAAQ;CACpB,CAAC;CACD,IAAI,CAAC,YAAY,OAAO,CAAC;CACzB,MAAM,mBAAmB,WAAW,WAAY,MAAM,QAAQ,QAAQ,qBAAqB,WAAW,OAAO;CAC7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B,MAAM,IAAI,MACR,oDAAoD,WAAW,2BAC7D,QAAQ,KAAK,MAAM,KAAK,GACzB,oFACH;EACF;CACF,CAAC;AACH"}
1
+ {"version":3,"file":"tools.js","names":[],"sources":["../../src/rules/tools.ts"],"sourcesContent":["import type { RequestContext } from '@mastra/core/request-context';\nimport { createTool } from '@mastra/core/tools';\nimport { z } from 'zod';\n\nimport {\n boardFlow,\n boardForWorkItem,\n cardBoardFlow,\n hasPullRequest,\n isPullRequestCard,\n reviewedChangeRequest,\n workItemPhaseSemantics,\n} from '../boards/index.js';\nimport type { BoardRegistry } from '../boards/index.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../boards/project-boards.js';\nimport type { IntegrationTools } from '../integrations/base.js';\nimport { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport type { FactorySessionSourceLookup } from './binding-context.js';\nimport { resolveFactorySessionAddress } from './binding-context.js';\nimport { phaseGrantsTool } from './phase-tools.js';\nimport type { FactoryTransitionService } from './transition-service.js';\nimport { SELF_REVIEW_ROUND_LIMIT, workItemSource } from './types.js';\nimport { BOARD_IDENTIFIER_RE, MAX_BOARD_IDENTIFIER_LENGTH } from './validation.js';\n\nconst MAX_RATIONALE_LENGTH = 1_000;\n\nconst transitionInputSchema = z\n .object({\n stage: z.string().max(MAX_BOARD_IDENTIFIER_LENGTH).regex(BOARD_IDENTIFIER_RE),\n expectedRevision: z.number().int().positive(),\n // Providers strip maxLength from the JSON schema and models can't count characters, so a\n // hard cap invites overshoot-retry loops at the end of every run. Accept and clamp instead.\n rationale: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_RATIONALE_LENGTH ? value : `${value.slice(0, MAX_RATIONALE_LENGTH - 1)}…`,\n ),\n // Triage used to report a classification here, and sessions keep that call in their history\n // across role rotations and restarts. Accept the stale key and ignore it, rather than fail a\n // call an agent copied from that history and send it into a retry loop.\n triageType: z.unknown().optional().describe('Ignored. Factory no longer records a triage classification.'),\n })\n .strict();\n\nexport async function createFactoryTransitionTools(options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n boards?: BoardRegistry | ProjectBoardSource;\n}): Promise<IntegrationTools> {\n const resolution = await resolveFactorySessionAddress({\n requestContext: options.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n if (!resolution) return {};\n const availableBinding = resolution.binding ?? (await options.storage.findActiveRunBinding(resolution.address));\n if (!availableBinding) {\n // No live binding for this session. A resumed session whose binding was\n // revoked when its work item reached a terminal stage was retired out from\n // under the model: rather than silently drop the tool — which leaves the\n // resumed run to rationalize a false blocked state — surface a tool that\n // fails with the concrete reason. Threads that were never bound (or whose\n // binding was rotated to a peer role, leaving the item still in flight) get\n // no tool as before.\n const retired = await options.storage.findRunBindingBySession(resolution.address);\n if (retired && retired.status === 'revoked' && options.boards) {\n const item = await options.storage.get({ orgId: retired.orgId, id: retired.workItemId });\n if (\n item &&\n workItemPhaseSemantics(await toBoardSource(options.boards).load(retired), item)?.kind === 'terminal'\n ) {\n return { factory_transition_work_item: createRetiredSessionTool(retired.workItemId, item.stages[0]) };\n }\n }\n return {};\n }\n // Tools are built for every turn, so a card that moves on takes its phase's tools with it.\n // A failed lookup grants no phase tools but keeps the move tool.\n const recordsVerdict = await options.storage\n .get({ orgId: availableBinding.orgId, id: availableBinding.workItemId })\n .then(item =>\n item ? phaseGrantsTool(options.boards, availableBinding, item, 'factory_record_review_verdict') : false,\n )\n .catch(() => false);\n\n return {\n ...(recordsVerdict ? createReviewVerdictTool(options, availableBinding.workItemId) : {}),\n factory_transition_work_item: createTool({\n id: 'factory_transition_work_item',\n description:\n 'Request a governed stage transition for the Factory work item exactly bound to this thread. Use the current revision from the factory-phase signal and explain why the transition is appropriate.',\n inputSchema: transitionInputSchema,\n requireApproval: true,\n execute: async ({ stage, expectedRevision, rationale }, execution) => {\n const currentResolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const currentAddress = currentResolution?.address ?? null;\n const toolCallId = execution.agent?.toolCallId;\n if (!currentAddress || !toolCallId) {\n throw new Error('Factory transitions require an authenticated bound agent tool call.');\n }\n const binding = await options.storage.findActiveRunBinding(currentAddress);\n // Authority is the work item this session is bound to, not the individual\n // binding row. Handing the next role its turn in an existing session\n // rotates the binding, and tools built for the previous role stay live\n // across that rotation; keying on row identity would strand the run that\n // the rotation exists to start. Re-pointing a session at a different item\n // is the hijack this guards against.\n if (!binding || binding.workItemId !== availableBinding.workItemId) {\n throw new Error('Factory agent binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n const board = boardForWorkItem(item);\n\n const result = await options.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board,\n stage,\n expectedRevision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${toolCallId}` },\n cause: rationale,\n });\n\n return result;\n },\n }),\n };\n}\n\nexport const REVIEW_VERDICTS = ['approve', 'request changes'] as const;\n\nconst MAX_SELF_REVIEW_FINDINGS_LENGTH = 20_000;\n\nconst reviewVerdictInputSchema = z.object({\n verdict: z.enum(REVIEW_VERDICTS),\n reviewedHeadSha: z\n .string()\n .regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i, 'Use the full commit SHA of the reviewed head.'),\n findings: z\n .string()\n .trim()\n .min(1)\n .transform(value =>\n value.length <= MAX_SELF_REVIEW_FINDINGS_LENGTH\n ? value\n : `${value.slice(0, MAX_SELF_REVIEW_FINDINGS_LENGTH - 1)}…`,\n )\n .optional()\n .describe(\n 'Self-review only: the findings and test report, in Markdown. On request changes the builder receives them; on approve they go in the change request body.',\n ),\n});\n\n/**\n * A review pass ends by recording its verdict on the card, which stays in\n * Reviewing: Done is reserved for the merge, and a verdict is not a lane. The\n * next push re-reviews from the recorded verdict.\n */\nfunction createReviewVerdictTool(\n options: {\n requestContext: RequestContext;\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n sessions?: FactorySessionSourceLookup;\n boards?: BoardRegistry | ProjectBoardSource;\n },\n boundWorkItemId: string,\n): IntegrationTools {\n return {\n factory_record_review_verdict: createTool({\n id: 'factory_record_review_verdict',\n description:\n 'Record the review verdict and the head SHA it covers on the card bound to this thread, ending the review pass. In the phase that reviews pull requests it records the published PR verdict and the card stays put. In a self-review phase with no change request open yet, approve keeps the card in place for you to open the change request from the approved head; once a GitHub pull request opens from that head, Factory moves the card to pull request review itself (elsewhere, move it with factory_transition_work_item). Request changes sends it back to the build phase with your findings.',\n inputSchema: reviewVerdictInputSchema,\n requireApproval: false,\n execute: async ({ verdict, reviewedHeadSha, findings }, execution) => {\n const resolution = await resolveFactorySessionAddress({\n requestContext: execution.requestContext,\n storage: options.storage,\n sessions: options.sessions,\n });\n const binding = resolution ? await options.storage.findActiveRunBinding(resolution.address) : null;\n if (!binding || binding.workItemId !== boundWorkItemId) {\n throw new Error('Factory review binding is unavailable, revoked, or no longer matches this session.');\n }\n const item = await options.storage.get({ orgId: binding.orgId, id: binding.workItemId });\n if (!item) throw new Error('Bound Factory work item not found.');\n // The card may have moved since the tools were built for this turn.\n if (!(await phaseGrantsTool(options.boards, binding, item, 'factory_record_review_verdict'))) {\n throw new Error(\n `This session does not review the card in its current phase (${item.stages.join(', ')}); it cannot record a verdict.`,\n );\n }\n const boards = await toBoardSource(options.boards).load(binding);\n const boardId = boardForWorkItem(item);\n const board = boards.get(boardId);\n const flow = boardFlow(board);\n const stage = item.stages[0];\n const source = workItemSource(item.externalSource);\n const pullRequestCard = isPullRequestCard({ source });\n if (\n board &&\n stage === flow.selfReview &&\n !pullRequestCard &&\n typeof item.metadata?.openPullRequestNumber !== 'number'\n ) {\n return recordSelfReviewVerdict({\n storage: options.storage,\n transitionService: options.transitionService,\n binding,\n item,\n board: boardId,\n // Requested changes go back to the builder; a board without a build phase rests the card.\n buildPhase: flow.build ?? board.initialPhase,\n parkPhase: board.initialPhase,\n verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n findings,\n toolCallId: execution.agent?.toolCallId,\n });\n }\n if (\n stage === undefined ||\n stage !== flow.pullRequestReview ||\n !hasPullRequest({ source, workItem: item.workItem })\n ) {\n const where = flow.pullRequestReview\n ? (board?.phases[flow.pullRequestReview]?.name ?? flow.pullRequestReview)\n : undefined;\n throw new Error(\n where\n ? `Only a card with a pull request in ${where} records a verdict; this one is in ${item.stages.join(', ')}.`\n : `The ${board?.name ?? boardId} board reviews no pull requests, so this card in ${item.stages.join(', ')} records no verdict.`,\n );\n }\n // An issue card can carry several pull requests; the verdict names the one it covers.\n const reviewedNumber = reviewedChangeRequest({ ...item, source })?.number;\n const reviewedAt = new Date().toISOString();\n // Revision-checked, so a merge that moves the card between the stage\n // check and this write fails the call instead of stamping a Done card.\n try {\n await options.storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n ...(item.metadata ?? {}),\n reviewVerdict: verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n reviewedAt,\n ...(reviewedNumber !== undefined ? { reviewedPullRequestNumber: reviewedNumber } : {}),\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error(\n 'The Review card changed while recording the verdict; call again to record it on the current card.',\n );\n }\n // Mirror the verdict onto the card that authored the PR, so its\n // builder cannot close the work while changes are still requested.\n const parent = item.parentWorkItemId\n ? await options.storage.get({ orgId: binding.orgId, id: item.parentWorkItemId })\n : null;\n if (parent && cardBoardFlow(boards, parent).build !== undefined) {\n await options.storage.update({\n orgId: binding.orgId,\n id: parent.id,\n userId: `agent:${binding.id}`,\n patch: {\n metadata: {\n reviewVerdict: verdict,\n reviewedHeadSha: reviewedHeadSha.toLowerCase(),\n reviewedAt,\n ...(reviewedNumber !== undefined ? { reviewedPullRequestNumber: reviewedNumber } : {}),\n },\n },\n });\n }\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt };\n },\n }),\n };\n}\n\n/**\n * Self-review ends the same way a PR review does, but on the authoring card before\n * any change request exists, and it moves the card itself: the verdict is the\n * only thing that decides where the work goes next.\n */\nasync function recordSelfReviewVerdict(input: {\n storage: WorkItemsStorage;\n transitionService: Pick<FactoryTransitionService, 'transition'>;\n binding: { id: string; orgId: string; factoryProjectId: string; workItemId: string; role: string };\n item: Card;\n board: string;\n buildPhase: string;\n parkPhase: string;\n verdict: (typeof REVIEW_VERDICTS)[number];\n reviewedHeadSha: string;\n findings: string | undefined;\n toolCallId: string | undefined;\n}) {\n const { storage, binding, item, verdict, reviewedHeadSha, findings } = input;\n if (!input.toolCallId) throw new Error('Self-review verdicts require an authenticated bound agent tool call.');\n const reviewedAt = new Date().toISOString();\n const previousRounds = typeof item.metadata?.selfReviewRounds === 'number' ? item.metadata.selfReviewRounds : 0;\n const rounds = verdict === 'request changes' ? previousRounds + 1 : previousRounds;\n // Every SELF_REVIEW_ROUND_LIMIT rounds the card rests in its board's initial phase for a person\n // instead of looping; moving it back to the build phase grants another full set of rounds.\n const parked = verdict === 'request changes' && rounds % SELF_REVIEW_ROUND_LIMIT === 0;\n let updated: Awaited<ReturnType<WorkItemsStorage['update']>>;\n try {\n updated = await storage.update({\n orgId: binding.orgId,\n id: item.id,\n userId: `agent:${binding.id}`,\n expectedRevision: item.revision,\n patch: {\n metadata: {\n selfReviewVerdict: verdict,\n selfReviewedHeadSha: reviewedHeadSha,\n selfReviewedAt: reviewedAt,\n selfReviewFindings: findings ?? null,\n selfReviewRounds: rounds,\n selfReviewNeedsHuman: parked,\n },\n },\n });\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n throw new Error('The card changed while recording the verdict; call again to record it on the current card.');\n }\n if (!updated) throw new Error('Bound Factory work item not found.');\n if (verdict === 'approve')\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt, selfReviewRounds: rounds };\n const transition = await input.transitionService.transition({\n orgId: binding.orgId,\n factoryProjectId: binding.factoryProjectId,\n workItemId: binding.workItemId,\n board: input.board,\n stage: parked ? input.parkPhase : input.buildPhase,\n expectedRevision: updated.item.revision,\n actor: { type: 'agent', bindingId: binding.id, role: binding.role },\n ingress: { type: 'agent', identity: `${binding.id}:${input.toolCallId}` },\n cause: parked\n ? `Self-review requested changes ${rounds} times; parked for a person to decide how to proceed.`\n : `Self-review requested changes on ${reviewedHeadSha} (round ${rounds}).`,\n });\n return { status: 'recorded', verdict, reviewedHeadSha, reviewedAt, selfReviewRounds: rounds, transition };\n}\n\n/**\n * A retired session's transition tool: it exists only to fail loudly. The run's\n * binding was revoked when its work item settled at a terminal stage, so there\n * is nothing to transition. Registering it (instead of dropping the tool) stops\n * a resumed model from inventing a false \"blocked\" state when the affordance it\n * expects has silently vanished.\n */\nfunction createRetiredSessionTool(workItemId: string, stage: string | undefined): IntegrationTools[string] {\n return createTool({\n id: 'factory_transition_work_item',\n description:\n 'This Factory session has been retired: its work item already reached a terminal stage and the run binding was revoked. No further transitions can be requested from this session.',\n inputSchema: transitionInputSchema,\n requireApproval: false,\n execute: async () => {\n throw new Error(\n `This Factory session has been retired: work item ${workItemId} reached a terminal stage${\n stage ? ` (${stage})` : ''\n } and its run binding was revoked. No transition can be requested from this session.`,\n );\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;AA0BA,MAAM,uBAAuB;AAE7B,MAAM,wBAAwB,EAC3B,OAAO;CACN,OAAO,EAAE,OAAO,CAAC,CAAC,IAAA,GAA+B,CAAC,CAAC,MAAM,mBAAmB;CAC5E,kBAAkB,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC,CAAC,SAAS;CAG5C,WAAW,EACR,OAAO,CAAC,CACR,KA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;GAC1B,YAAY,QAAQ;GACpB,OAAO,MAAM;GACb,OAAO,SAAS,MAAM,YAAY,MAAM;GACxC,kBAAkB,QAAQ,KAAK;GAC/B,OAAO;IAAE,MAAM;IAAS,WAAW,QAAQ;IAAI,MAAM,QAAQ;GAAK;GAClE,SAAS;IAAE,MAAM;IAAS,UAAU,GAAG,QAAQ,GAAG,GAAG,MAAM;GAAa;GACxE,OAAO,SACH,iCAAiC,OAAO,yDACxC,oCAAoC,gBAAgB,UAAU,OAAO;EAC3E,CAAC;CACuG;AAC1G;;;;;;;;AASA,SAAS,yBAAyB,YAAoB,OAAqD;CACzG,OAAO,WAAW;EAChB,IAAI;EACJ,aACE;EACF,aAAa;EACb,iBAAiB;EACjB,SAAS,YAAY;GACnB,MAAM,IAAI,MACR,oDAAoD,WAAW,2BAC7D,QAAQ,KAAK,MAAM,KAAK,GACzB,oFACH;EACF;CACF,CAAC;AACH"}
@@ -39,6 +39,12 @@ export interface FactoryTransitionRequest {
39
39
  eventRoute?: {
40
40
  routeId: string;
41
41
  };
42
+ /**
43
+ * Internal, with `eventRoute` only: the installed board the route moves the card to, at `stage`.
44
+ * `board` stays the card's current board. The target board's next phases don't restrict the
45
+ * move; its phase, card shape and policy checks still apply, and its phase's runner starts.
46
+ */
47
+ toBoard?: string;
42
48
  }
43
49
  export interface FactoryTransitionServiceOptions {
44
50
  configVersion: string;
@@ -99,6 +105,16 @@ export interface FactoryTransitionServiceOptions {
99
105
  * `onTerminalStage` or `onContextLeft` before returning (default 30s). The
100
106
  * cleanup continues in the background past the bound. */
101
107
  terminalCleanupTimeoutMs?: number;
108
+ /**
109
+ * Whether a run is in flight on the card's sessions. With a run queued for the card, it makes the
110
+ * card busy, and a person's move into a phase that may start a run is refused while it is.
111
+ * Without it only a queued run counts.
112
+ */
113
+ runInFlight?: (card: {
114
+ orgId: string;
115
+ factoryProjectId: string;
116
+ workItemId: string;
117
+ }) => Promise<boolean>;
102
118
  /**
103
119
  * Called after a person moves a Work card from Intake or Triage into Planning or
104
120
  * Building, which approves the work. Fire-and-forget: failures are swallowed, the committed transition never
@@ -1 +1 @@
1
- {"version":3,"file":"transition-service.d.ts","sourceRoot":"","sources":["../../src/rules/transition-service.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAkB,MAAM,oBAAoB,CAAC;AAIxE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAGtE,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,kCAAkC,CAAC;AAC7G,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAGxE,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AACpF,OAAO,KAAK,EAEV,gBAAgB,EAEhB,sBAAsB,EAEtB,gBAAgB,EAEhB,uBAAuB,EAExB,MAAM,YAAY,CAAC;AAiBpB,MAAM,WAAW,wBAAwB;IACvC,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;IACzB,UAAU,EAAE,MAAM,CAAC;IACnB,6EAA6E;IAC7E,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,gBAAgB,CAAC;IACxB,gBAAgB,EAAE,MAAM,CAAC;IACzB,KAAK,EAAE,gBAAgB,CAAC;IACxB,YAAY,CAAC,EAAE,sBAAsB,CAAC;IACtC,sEAAsE;IACtE,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,OAAO,EAAE;QAAE,IAAI,EAAE,OAAO,GAAG,OAAO,GAAG,YAAY,GAAG,QAAQ,GAAG,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,YAAY,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACjH,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,SAAS,sBAAsB,EAAE,CAAC;IAChD,2GAA2G;IAC3G,YAAY,CAAC,EAAE,O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C,EAAE,CAAC,IAAI,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,gBAAgB,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAA;KAAE,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IAC1G;;;;OAIG;IACH,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE;QAClB,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;QACnB,IAAI,EAAE,IAAI,CAAC;KACZ,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;CAC5B;AA0BD,wBAAgB,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,cAAc,CAAA;CAAE,CAWpG;AAiBD,wBAAgB,YAAY,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,GAAG,gBAAgB,GAAG,SAAS,CAEpF;AAyFD,qBAAa,wBAAwB;;IAanC,YAAY,OAAO,EAAE,+BAA+B,EAYnD;IAED,IAAI,aAAa,IAAI,MAAM,CAE1B;IAEK,UAAU,CAAC,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,uBAAuB,CAAC,CA4BpF;CA0cF"}
@@ -1,13 +1,15 @@
1
+ import { BUSY_CARD_MOVE_REFUSAL, phaseMayStartRun } from "../boards/busy-card.js";
1
2
  import "../boards/index.js";
2
- import { autoApprovedExitTool, exitToolSucceeded } from "../boards/phase-automation.js";
3
3
  import "../boards/define-board.js";
4
4
  import "../boards/default-board.js";
5
+ import { autoApprovedExitTool, exitToolSucceeded } from "../boards/phase-automation.js";
5
6
  import { phaseRunDecision } from "../boards/phase-runner.js";
6
7
  import { toBoardSource } from "../boards/project-boards.js";
7
8
  import { boardFlow, boardForWorkItem, hasPullRequest, pullRequestCardRejection } from "../boards/semantics.js";
8
9
  import { boardTransitionPolicyResultSchema, immutablePolicySnapshot } from "../boards/transition-policy.js";
9
10
  import { isFactoryPrincipalId } from "../storage/domains/projects/base.js";
10
11
  import { isAgentActor } from "../storage/domains/work-items/base.js";
12
+ import { isRunBearingDecision } from "./run-bearing.js";
11
13
  import { factoryRuleSourceForWorkItem, workItemSource } from "./types.js";
12
14
  import { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from "./validation.js";
13
15
  // src/rules/transition-service.ts
@@ -136,6 +138,7 @@ var FactoryTransitionService = class {
136
138
  #onAccepted;
137
139
  #onTransitionCommitted;
138
140
  #audit;
141
+ #runInFlight;
139
142
  constructor(options) {
140
143
  this.#configVersion = options.configVersion;
141
144
  this.#boards = toBoardSource(options.boards);
@@ -146,6 +149,7 @@ var FactoryTransitionService = class {
146
149
  this.#onContextLeft = options.onContextLeft;
147
150
  this.#onAccepted = options.onAccepted;
148
151
  this.#onTransitionCommitted = options.onTransitionCommitted;
152
+ this.#runInFlight = options.runInFlight;
149
153
  this.#terminalCleanupTimeoutMs = options.terminalCleanupTimeoutMs ?? TERMINAL_CLEANUP_TIMEOUT_MS;
150
154
  }
151
155
  get configVersion() {
@@ -241,10 +245,14 @@ var FactoryTransitionService = class {
241
245
  if (item.board === null && !boards.has("work")) return this.#commitRejection(request, transitionId, "invalid_transition", "This legacy work item has no assigned board. Assign an installed board and phase through the work-item PATCH endpoint before transitioning it.");
242
246
  const itemBoard = boardForWorkItem(item);
243
247
  if (request.board !== itemBoard) return this.#commitRejection(request, transitionId, "invalid_transition", `The work item belongs to board "${itemBoard}", not "${request.board}".`);
244
- const board = boards.get(request.board);
245
- if (!board) return this.#commitRejection(request, transitionId, "invalid_transition", `Board "${request.board}" is not installed.`);
248
+ const fromBoard = boards.get(request.board);
249
+ if (!fromBoard) return this.#commitRejection(request, transitionId, "invalid_transition", `Board "${request.board}" is not installed.`);
250
+ if (request.toBoard !== void 0 && !request.eventRoute) return this.#commitRejection(request, transitionId, "invalid_transition", "Only a card-move rule can move a card to another board.");
251
+ const targetBoard = request.toBoard ?? request.board;
252
+ const board = targetBoard === request.board ? fromBoard : boards.get(targetBoard);
253
+ if (!board) return this.#commitRejection(request, transitionId, "invalid_transition", `Board "${targetBoard}" is not installed.`);
246
254
  const fromStage = item.stages.length === 1 ? item.stages[0] : void 0;
247
- if (!fromStage || !Object.prototype.hasOwnProperty.call(board.phases, fromStage)) return this.#commitRejection(request, transitionId, "invalid_transition", "The work item does not have one canonical phase on the requested board.");
255
+ if (!fromStage || !Object.prototype.hasOwnProperty.call(fromBoard.phases, fromStage)) return this.#commitRejection(request, transitionId, "invalid_transition", "The work item does not have one canonical phase on the requested board.");
248
256
  const cardShapeRejection = pullRequestCardRejection(board, {
249
257
  standalonePullRequest: isPullRequest,
250
258
  hasPullRequest: hasPullRequest({
@@ -254,10 +262,12 @@ var FactoryTransitionService = class {
254
262
  }, request.stage);
255
263
  if (cardShapeRejection) return this.#commitRejection(request, transitionId, "invalid_transition", cardShapeRejection);
256
264
  if (!Object.prototype.hasOwnProperty.call(board.phases, request.stage) || !request.eventRoute && !board.allowsTransition(fromStage, request.stage)) {
265
+ if (board !== fromBoard) return this.#commitRejection(request, transitionId, "invalid_transition", `The ${board.name} board has no phase ${request.stage}.`);
257
266
  const nextStages = [...new Set((board.transitions[fromStage] ?? []).map((transition) => transition.to))];
258
267
  const nextStagesReason = nextStages.length > 0 ? `Next stages declared from ${fromStage}: ${nextStages.join(", ")}.` : `No next stage is declared from ${fromStage}.`;
259
268
  return this.#commitRejection(request, transitionId, "invalid_transition", `The ${board.name} board does not allow moving from ${fromStage} to ${request.stage}. ${nextStagesReason}`);
260
269
  }
270
+ if (isHumanTransition(request) && request.cause !== "run_start" && !request.initialEntry && (fromStage !== request.stage || request.reenter === true) && phaseMayStartRun(board.phaseKind(request.stage)) && await this.#cardBusy(request)) return this.#commitRejection(request, transitionId, "card_busy", BUSY_CARD_MOVE_REFUSAL);
261
271
  const humanMove = request.actor.type === "human" && fromStage !== request.stage && request.cause !== "run_start";
262
272
  const entersWorking = board.isWorking(request.stage);
263
273
  const seatRole = board.roleForPhase(request.stage);
@@ -286,7 +296,7 @@ var FactoryTransitionService = class {
286
296
  acceptedAt: item.acceptedAt,
287
297
  metadata: item.metadata
288
298
  },
289
- board: request.board,
299
+ board: board.id,
290
300
  itemRevision: item.revision,
291
301
  source,
292
302
  fromStage,
@@ -296,7 +306,7 @@ var FactoryTransitionService = class {
296
306
  try {
297
307
  evaluation = await withRuleTimeout((async () => {
298
308
  const plansAutoApproved = autoApprovedExitTool(boards, item) === "submit_plan";
299
- const fromPhase = board.phases[fromStage];
309
+ const fromPhase = fromBoard.phases[fromStage];
300
310
  const exitTool = fromPhase?.kind === "working" ? fromPhase.exitTool : void 0;
301
311
  if (request.actor.type !== "human" && request.cause !== "run_start" && !request.eventRoute && exitTool && fromStage !== request.stage && entersWorking && !(exitTool.id === "submit_plan" ? request.planApproved === true : request.completedTool === exitTool.id) && !exitToolSucceeded(item, fromStage, exitTool.id)) return {
302
312
  outcome: "rejected",
@@ -326,7 +336,7 @@ var FactoryTransitionService = class {
326
336
  reenter: request.reenter
327
337
  });
328
338
  const validated = validateFactoryRuleDecisions(run ? [run] : [], contextBase.causalChain.length).filter((decision) => {
329
- assertFactoryDecisionTarget(decision, boards, itemBoard);
339
+ assertFactoryDecisionTarget(decision, boards, board.id);
330
340
  return !(startsRun(decision) && runAlreadyUnderway(request, decision));
331
341
  });
332
342
  if (humanMove) {
@@ -365,6 +375,18 @@ var FactoryTransitionService = class {
365
375
  ...evaluation.intents
366
376
  } : {}, boards, fromStage);
367
377
  }
378
+ /** A run in flight on the card's sessions, or one queued for it: what the board shows as busy. */
379
+ async #cardBusy(request) {
380
+ if ((await this.#storage.listDeferredDecisions(request.orgId, request.factoryProjectId, {
381
+ statuses: [
382
+ "pending",
383
+ "retry",
384
+ "leased"
385
+ ],
386
+ workItemId: request.workItemId
387
+ })).some((decision) => isRunBearingDecision(decision.decision))) return true;
388
+ return await this.#runInFlight?.(request) ?? false;
389
+ }
368
390
  async #commitRejection(request, transitionId, code, reason) {
369
391
  return this.#commit(request, transitionId, {
370
392
  outcome: "rejected",
@@ -381,6 +403,7 @@ var FactoryTransitionService = class {
381
403
  workItemId: request.workItemId,
382
404
  expectedRevision: request.expectedRevision,
383
405
  destinationStage: request.stage,
406
+ ...request.toBoard !== void 0 && request.toBoard !== request.board ? { destinationBoard: request.toBoard } : {},
384
407
  actorId: actorId(request.actor),
385
408
  ingress: {
386
409
  identity: request.ingress.identity,
@@ -403,8 +426,9 @@ var FactoryTransitionService = class {
403
426
  console.warn(`[factory] acceptance hook failed for work item ${request.workItemId}:`, error);
404
427
  });
405
428
  }
406
- const board = result.status === "accepted" ? boards?.get(request.board) : void 0;
429
+ const board = result.status === "accepted" ? boards?.get(request.toBoard ?? request.board) : void 0;
407
430
  if (board && result.status === "accepted") {
431
+ const crossesBoards = request.toBoard !== void 0 && request.toBoard !== request.board;
408
432
  const hooks = {
409
433
  orgId: request.orgId,
410
434
  factoryProjectId: request.factoryProjectId,
@@ -419,10 +443,10 @@ var FactoryTransitionService = class {
419
443
  stage: result.stage
420
444
  }));
421
445
  } else if (fromStage !== void 0 && this.#onContextLeft) {
422
- const context = board.roleForPhase(fromStage);
446
+ const context = boards?.get(request.board)?.roleForPhase(fromStage);
423
447
  const toContext = board.roleForPhase(result.stage);
424
448
  const onContextLeft = this.#onContextLeft;
425
- if (context !== void 0 && context !== toContext) await this.#bounded(() => onContextLeft({
449
+ if (context !== void 0 && (crossesBoards || context !== toContext)) await this.#bounded(() => onContextLeft({
426
450
  ...hooks,
427
451
  context,
428
452
  toContext