@mastra/factory 0.28.0-alpha.5 → 0.28.0-alpha.7

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 (289) hide show
  1. package/README.md +52 -28
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +5 -5
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/board-writes.d.ts +1 -1
  6. package/dist/boards/board-writes.d.ts.map +1 -1
  7. package/dist/boards/board-writes.js +7 -8
  8. package/dist/boards/board-writes.js.map +1 -1
  9. package/dist/boards/index.d.ts +1 -1
  10. package/dist/boards/index.d.ts.map +1 -1
  11. package/dist/boards/index.js +2 -2
  12. package/dist/boards/project-boards.d.ts +30 -4
  13. package/dist/boards/project-boards.d.ts.map +1 -1
  14. package/dist/boards/project-boards.js +71 -19
  15. package/dist/boards/project-boards.js.map +1 -1
  16. package/dist/boards/registry.d.ts +7 -1
  17. package/dist/boards/registry.d.ts.map +1 -1
  18. package/dist/boards/registry.js +16 -3
  19. package/dist/boards/registry.js.map +1 -1
  20. package/dist/boards/semantics.d.ts +5 -4
  21. package/dist/boards/semantics.d.ts.map +1 -1
  22. package/dist/boards/semantics.js +5 -4
  23. package/dist/boards/semantics.js.map +1 -1
  24. package/dist/boards/work-migrations.d.ts +4 -3
  25. package/dist/boards/work-migrations.d.ts.map +1 -1
  26. package/dist/boards/work-migrations.js +6 -5
  27. package/dist/boards/work-migrations.js.map +1 -1
  28. package/dist/boards/work-seeds.d.ts +9 -0
  29. package/dist/boards/work-seeds.d.ts.map +1 -0
  30. package/dist/boards/work-seeds.js +56 -0
  31. package/dist/boards/work-seeds.js.map +1 -0
  32. package/dist/boards/work.d.ts +2 -2
  33. package/dist/boards/work.d.ts.map +1 -1
  34. package/dist/boards/work.js +0 -16
  35. package/dist/boards/work.js.map +1 -1
  36. package/dist/environment/build-runner.d.ts.map +1 -1
  37. package/dist/environment/build-runner.js +2 -2
  38. package/dist/environment/build-runner.js.map +1 -1
  39. package/dist/environment/build-workflow.d.ts.map +1 -1
  40. package/dist/environment/build-workflow.js +6 -5
  41. package/dist/environment/build-workflow.js.map +1 -1
  42. package/dist/environment/build.d.ts +15 -2
  43. package/dist/environment/build.d.ts.map +1 -1
  44. package/dist/environment/build.js +32 -9
  45. package/dist/environment/build.js.map +1 -1
  46. package/dist/factory.d.ts +8 -4
  47. package/dist/factory.d.ts.map +1 -1
  48. package/dist/factory.js +57 -59
  49. package/dist/factory.js.map +1 -1
  50. package/dist/feed-events.d.ts +2 -3
  51. package/dist/feed-events.d.ts.map +1 -1
  52. package/dist/feed-events.js +4 -5
  53. package/dist/feed-events.js.map +1 -1
  54. package/dist/index.d.ts +2 -0
  55. package/dist/index.d.ts.map +1 -1
  56. package/dist/index.js +3 -1
  57. package/dist/integrations/base.d.ts +0 -11
  58. package/dist/integrations/base.d.ts.map +1 -1
  59. package/dist/integrations/github/integration.d.ts.map +1 -1
  60. package/dist/integrations/github/integration.js +7 -3
  61. package/dist/integrations/github/integration.js.map +1 -1
  62. package/dist/integrations/github/issue-reconciler.js +2 -2
  63. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  64. package/dist/integrations/github/provenance.js +1 -1
  65. package/dist/integrations/github/provenance.js.map +1 -1
  66. package/dist/integrations/github/reconcile-worker.d.ts +5 -1
  67. package/dist/integrations/github/reconcile-worker.d.ts.map +1 -1
  68. package/dist/integrations/github/reconcile-worker.js +39 -6
  69. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  70. package/dist/integrations/github/routes.d.ts +4 -3
  71. package/dist/integrations/github/routes.d.ts.map +1 -1
  72. package/dist/integrations/github/routes.js +9 -86
  73. package/dist/integrations/github/routes.js.map +1 -1
  74. package/dist/integrations/github/rules.d.ts +67 -0
  75. package/dist/integrations/github/rules.d.ts.map +1 -1
  76. package/dist/integrations/github/rules.js +215 -12
  77. package/dist/integrations/github/rules.js.map +1 -1
  78. package/dist/integrations/github/sandbox.d.ts +10 -2
  79. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  80. package/dist/integrations/github/sandbox.js +20 -4
  81. package/dist/integrations/github/sandbox.js.map +1 -1
  82. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  83. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  84. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  85. package/dist/integrations/gitlab/rules.js +6 -5
  86. package/dist/integrations/gitlab/rules.js.map +1 -1
  87. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/rules.js +5 -2
  89. package/dist/integrations/incidentio/rules.js.map +1 -1
  90. package/dist/integrations/issue-reconciler.js +1 -1
  91. package/dist/integrations/issue-reconciler.js.map +1 -1
  92. package/dist/integrations/jira/rules.d.ts.map +1 -1
  93. package/dist/integrations/jira/rules.js +5 -2
  94. package/dist/integrations/jira/rules.js.map +1 -1
  95. package/dist/integrations/linear/agent-tools.d.ts.map +1 -1
  96. package/dist/integrations/linear/agent-tools.js +1 -1
  97. package/dist/integrations/linear/agent-tools.js.map +1 -1
  98. package/dist/integrations/linear/rules.d.ts.map +1 -1
  99. package/dist/integrations/linear/rules.js +2 -2
  100. package/dist/integrations/linear/rules.js.map +1 -1
  101. package/dist/integrations/platform/github/event-worker.d.ts +4 -1
  102. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  103. package/dist/integrations/platform/github/event-worker.js +39 -3
  104. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  105. package/dist/integrations/platform/github/integration.d.ts +8 -0
  106. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  107. package/dist/integrations/platform/github/integration.js +21 -3
  108. package/dist/integrations/platform/github/integration.js.map +1 -1
  109. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  110. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  111. package/dist/integrations/platform/linear/event-worker.js +1 -1
  112. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  113. package/dist/integrations/slack/integration.d.ts +0 -2
  114. package/dist/integrations/slack/integration.d.ts.map +1 -1
  115. package/dist/integrations/slack/integration.js +0 -5
  116. package/dist/integrations/slack/integration.js.map +1 -1
  117. package/dist/integrations/slack/slack.d.ts +3 -18
  118. package/dist/integrations/slack/slack.d.ts.map +1 -1
  119. package/dist/integrations/slack/slack.js +3 -74
  120. package/dist/integrations/slack/slack.js.map +1 -1
  121. package/dist/links.d.ts +1 -2
  122. package/dist/links.d.ts.map +1 -1
  123. package/dist/links.js +1 -2
  124. package/dist/links.js.map +1 -1
  125. package/dist/mcp/routes.js +1 -1
  126. package/dist/mcp/routes.js.map +1 -1
  127. package/dist/routes/attention-parked.js +1 -1
  128. package/dist/routes/attention-parked.js.map +1 -1
  129. package/dist/routes/attention-providers.d.ts +0 -25
  130. package/dist/routes/attention-providers.d.ts.map +1 -1
  131. package/dist/routes/attention-providers.js +2 -150
  132. package/dist/routes/attention-providers.js.map +1 -1
  133. package/dist/routes/attention.d.ts +0 -2
  134. package/dist/routes/attention.d.ts.map +1 -1
  135. package/dist/routes/attention.js +2 -13
  136. package/dist/routes/attention.js.map +1 -1
  137. package/dist/routes/boards.d.ts +1 -1
  138. package/dist/routes/boards.d.ts.map +1 -1
  139. package/dist/routes/boards.js.map +1 -1
  140. package/dist/routes/contracts.d.ts +121 -14
  141. package/dist/routes/contracts.d.ts.map +1 -1
  142. package/dist/routes/contracts.js +73 -3
  143. package/dist/routes/contracts.js.map +1 -1
  144. package/dist/routes/feed-events.d.ts +15 -0
  145. package/dist/routes/feed-events.d.ts.map +1 -0
  146. package/dist/routes/feed-events.js +68 -0
  147. package/dist/routes/feed-events.js.map +1 -0
  148. package/dist/routes/knowledge.js +1 -1
  149. package/dist/routes/projects.d.ts +1 -1
  150. package/dist/routes/projects.d.ts.map +1 -1
  151. package/dist/routes/projects.js +13 -7
  152. package/dist/routes/projects.js.map +1 -1
  153. package/dist/routes/sandbox-envs.d.ts +26 -0
  154. package/dist/routes/sandbox-envs.d.ts.map +1 -0
  155. package/dist/routes/sandbox-envs.js +180 -0
  156. package/dist/routes/sandbox-envs.js.map +1 -0
  157. package/dist/routes/surface.d.ts +0 -7
  158. package/dist/routes/surface.d.ts.map +1 -1
  159. package/dist/routes/surface.js +1 -5
  160. package/dist/routes/surface.js.map +1 -1
  161. package/dist/routes/work-items.d.ts +0 -3
  162. package/dist/routes/work-items.d.ts.map +1 -1
  163. package/dist/routes/work-items.js +1 -2
  164. package/dist/routes/work-items.js.map +1 -1
  165. package/dist/rules/dispatcher.d.ts +0 -3
  166. package/dist/rules/dispatcher.d.ts.map +1 -1
  167. package/dist/rules/dispatcher.js +8 -9
  168. package/dist/rules/dispatcher.js.map +1 -1
  169. package/dist/sandbox/sandbox-env-cache.d.ts +33 -0
  170. package/dist/sandbox/sandbox-env-cache.d.ts.map +1 -0
  171. package/dist/sandbox/sandbox-env-cache.js +140 -0
  172. package/dist/sandbox/sandbox-env-cache.js.map +1 -0
  173. package/dist/sandbox/sandbox-env.d.ts +77 -0
  174. package/dist/sandbox/sandbox-env.d.ts.map +1 -0
  175. package/dist/sandbox/sandbox-env.js +130 -0
  176. package/dist/sandbox/sandbox-env.js.map +1 -0
  177. package/dist/storage/domains/audit/actions.d.ts +2 -1
  178. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  179. package/dist/storage/domains/audit/actions.js +5 -4
  180. package/dist/storage/domains/audit/actions.js.map +1 -1
  181. package/dist/storage/domains/boards/base.d.ts +15 -1
  182. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  183. package/dist/storage/domains/boards/base.js +21 -5
  184. package/dist/storage/domains/boards/base.js.map +1 -1
  185. package/dist/storage/domains/channel-identity/base.d.ts +0 -4
  186. package/dist/storage/domains/channel-identity/base.d.ts.map +1 -1
  187. package/dist/storage/domains/channel-identity/base.js +0 -7
  188. package/dist/storage/domains/channel-identity/base.js.map +1 -1
  189. package/dist/storage/domains/sandbox-envs/base.d.ts +70 -0
  190. package/dist/storage/domains/sandbox-envs/base.d.ts.map +1 -0
  191. package/dist/storage/domains/sandbox-envs/base.js +227 -0
  192. package/dist/storage/domains/sandbox-envs/base.js.map +1 -0
  193. package/dist/storage/domains/work-items/base.d.ts +8 -9
  194. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  195. package/dist/storage/domains/work-items/base.js +20 -86
  196. package/dist/storage/domains/work-items/base.js.map +1 -1
  197. package/dist/storage/domains/work-items/cards.d.ts +3 -3
  198. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  199. package/dist/storage/domains/work-items/cards.js +10 -10
  200. package/dist/storage/domains/work-items/cards.js.map +1 -1
  201. package/dist/storage/domains/work-items/metrics.d.ts +1 -1
  202. package/dist/storage/domains/work-items/metrics.d.ts.map +1 -1
  203. package/dist/storage/domains/work-items/metrics.js.map +1 -1
  204. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -2
  205. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  206. package/dist/storage/domains/work-items/work-item-schema.js +8 -8
  207. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  208. package/dist/tools/read-tools.d.ts +0 -2
  209. package/dist/tools/read-tools.d.ts.map +1 -1
  210. package/dist/tools/read-tools.js +3 -14
  211. package/dist/tools/read-tools.js.map +1 -1
  212. package/dist/tools/work-item-tools.d.ts +0 -3
  213. package/dist/tools/work-item-tools.d.ts.map +1 -1
  214. package/dist/tools/work-item-tools.js +8 -18
  215. package/dist/tools/work-item-tools.js.map +1 -1
  216. package/dist/work-items/create-work-item.d.ts.map +1 -1
  217. package/dist/work-items/create-work-item.js +3 -2
  218. package/dist/work-items/create-work-item.js.map +1 -1
  219. package/dist/work-items/description-context.d.ts +5 -0
  220. package/dist/work-items/description-context.d.ts.map +1 -0
  221. package/dist/work-items/description-context.js +17 -0
  222. package/dist/work-items/description-context.js.map +1 -0
  223. package/dist/work-items/split-migration.d.ts.map +1 -1
  224. package/dist/work-items/split-migration.js +1 -6
  225. package/dist/work-items/split-migration.js.map +1 -1
  226. package/dist/workspace.d.ts +3 -0
  227. package/dist/workspace.d.ts.map +1 -1
  228. package/dist/workspace.js +21 -4
  229. package/dist/workspace.js.map +1 -1
  230. package/factory-skills/configure-factory-rules/SKILL.md +3 -3
  231. package/factory-skills/factory-rereview/SKILL.md +2 -2
  232. package/factory-skills/factory-review/SKILL.md +2 -2
  233. package/factory-skills/factory-triage/SKILL.md +3 -2
  234. package/package.json +7 -7
  235. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts +0 -8
  236. package/dist/integrations/slack/emoji-shortcodes.generated.d.ts.map +0 -1
  237. package/dist/integrations/slack/emoji-shortcodes.generated.js +0 -1984
  238. package/dist/integrations/slack/emoji-shortcodes.generated.js.map +0 -1
  239. package/dist/integrations/slack/emoji.d.ts +0 -3
  240. package/dist/integrations/slack/emoji.d.ts.map +0 -1
  241. package/dist/integrations/slack/emoji.js +0 -11
  242. package/dist/integrations/slack/emoji.js.map +0 -1
  243. package/dist/integrations/slack/feed-publisher.d.ts +0 -26
  244. package/dist/integrations/slack/feed-publisher.d.ts.map +0 -1
  245. package/dist/integrations/slack/feed-publisher.js +0 -43
  246. package/dist/integrations/slack/feed-publisher.js.map +0 -1
  247. package/dist/routes/attention-activity.d.ts +0 -23
  248. package/dist/routes/attention-activity.d.ts.map +0 -1
  249. package/dist/routes/attention-activity.js +0 -154
  250. package/dist/routes/attention-activity.js.map +0 -1
  251. package/dist/storage/domains/comments/activity.d.ts +0 -40
  252. package/dist/storage/domains/comments/activity.d.ts.map +0 -1
  253. package/dist/storage/domains/comments/activity.js +0 -93
  254. package/dist/storage/domains/comments/activity.js.map +0 -1
  255. package/dist/storage/domains/comments/actor.d.ts +0 -51
  256. package/dist/storage/domains/comments/actor.d.ts.map +0 -1
  257. package/dist/storage/domains/comments/actor.js +0 -37
  258. package/dist/storage/domains/comments/actor.js.map +0 -1
  259. package/dist/storage/domains/comments/base.d.ts +0 -245
  260. package/dist/storage/domains/comments/base.d.ts.map +0 -1
  261. package/dist/storage/domains/comments/base.js +0 -539
  262. package/dist/storage/domains/comments/base.js.map +0 -1
  263. package/dist/storage/domains/comments/domain.d.ts +0 -135
  264. package/dist/storage/domains/comments/domain.d.ts.map +0 -1
  265. package/dist/storage/domains/comments/domain.js +0 -284
  266. package/dist/storage/domains/comments/domain.js.map +0 -1
  267. package/dist/storage/domains/comments/feed-context.d.ts +0 -22
  268. package/dist/storage/domains/comments/feed-context.d.ts.map +0 -1
  269. package/dist/storage/domains/comments/feed-context.js +0 -88
  270. package/dist/storage/domains/comments/feed-context.js.map +0 -1
  271. package/dist/storage/domains/comments/feed-sync.d.ts +0 -21
  272. package/dist/storage/domains/comments/feed-sync.d.ts.map +0 -1
  273. package/dist/storage/domains/comments/feed-sync.js +0 -1
  274. package/dist/storage/domains/comments/parse.d.ts +0 -23
  275. package/dist/storage/domains/comments/parse.d.ts.map +0 -1
  276. package/dist/storage/domains/comments/parse.js +0 -89
  277. package/dist/storage/domains/comments/parse.js.map +0 -1
  278. package/dist/storage/domains/comments/routes.d.ts +0 -24
  279. package/dist/storage/domains/comments/routes.d.ts.map +0 -1
  280. package/dist/storage/domains/comments/routes.js +0 -301
  281. package/dist/storage/domains/comments/routes.js.map +0 -1
  282. package/dist/storage/domains/comments/schema.d.ts +0 -5
  283. package/dist/storage/domains/comments/schema.d.ts.map +0 -1
  284. package/dist/storage/domains/comments/schema.js +0 -178
  285. package/dist/storage/domains/comments/schema.js.map +0 -1
  286. package/dist/storage/domains/comments/wire.d.ts +0 -40
  287. package/dist/storage/domains/comments/wire.d.ts.map +0 -1
  288. package/dist/storage/domains/comments/wire.js +0 -36
  289. package/dist/storage/domains/comments/wire.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"work.js","names":[],"sources":["../../src/boards/work.ts"],"sourcesContent":["import { DEFAULT_BOARD_ID } from './default-board.js';\nimport { compileBoardDefinition } from './define-board.js';\nimport type { BoardPhaseDefinition } from './define-board.js';\n\n/**\n * A change request tracked on its own card never attaches to this one, so Review refuses the card and\n * the builder leaves it in Building: the goal counts that hand-off as done rather than looping on it.\n */\nexport const OWN_CARD_HAND_OFF =\n 'Also done, with the card left in Building, when the change request was opened but is tracked on its own card ' +\n \"and the builder's latest message posts its link and says a person should confirm it is reviewed there.\";\n\n/**\n * The goal Building pursues. The goal judge sees only this text and the latest messages, so it\n * spells out when the build is done and when it waits for a person.\n */\nexport const BUILD_OBJECTIVE =\n 'Build the plan approved in Planning for this work item. Done when every step of that plan is implemented on ' +\n \"the work branch; the plan's verification gates (the tests, typecheck and lint it names, else the narrowest \" +\n 'relevant ones) were run on the final head and passed; the branch is pushed; and the card was moved on with ' +\n 'factory_transition_work_item out of Building (to Review after opening the change request, or back to ' +\n \"Planning if the plan proved wrong); the builder's latest message names the move and the pushed head. \" +\n OWN_CARD_HAND_OFF +\n ' Continue while any of that is missing. Waiting only when the agent asked a person a question it cannot ' +\n 'answer from the repository.';\n\nexport type WorkBoardPhase = 'intake' | 'triage' | 'planning' | 'execute' | 'pr-review' | 'done' | 'canceled';\n\nexport const workBoard = compileBoardDefinition<'work', Record<WorkBoardPhase, BoardPhaseDefinition<WorkBoardPhase>>>({\n id: DEFAULT_BOARD_ID,\n name: 'Work',\n initialPhase: 'intake',\n sourceClosed: { completed: 'done', canceled: 'canceled' },\n phases: {\n intake: {\n name: 'Intake',\n kind: 'resting',\n // Never straight to Building: a plan comes first. Review takes a pull request's own card;\n // Done is where a completed source closes it.\n nextPhases: ['triage', 'planning', 'pr-review', 'done', 'canceled'],\n },\n triage: {\n name: 'Triage',\n kind: 'working',\n runner: { skill: 'factory-triage', context: 'triage' },\n // A confirmed bug goes to Planning; any other open issue waits in Intake for a person.\n nextPhases: ['intake', 'planning', 'done', 'canceled'],\n },\n planning: {\n name: 'Planning',\n kind: 'working',\n // Planning and Building share one session, so the builder keeps the plan's context.\n runner: { skill: 'factory-plan', context: 'work' },\n nextPhases: ['execute', 'triage', 'intake', 'done', 'canceled'],\n // The card stays in Planning until submit_plan comes back approved; then factory-plan moves it.\n exitTool: { id: 'submit_plan', autoApprove: false },\n },\n execute: {\n name: 'Building',\n kind: 'working',\n runner: { skill: 'factory-build', context: 'work', goal: { objective: BUILD_OBJECTIVE, maxRuns: 20 } },\n // Review once the builder opened the change request; Planning again when the build shows\n // the plan was wrong.\n nextPhases: ['pr-review', 'planning', 'done', 'canceled'],\n },\n 'pr-review': {\n // Keyed `pr-review`: projects stored before Work dropped its self-review phase hold a\n // `review` phase for it, and the retired Review board's cards read as `pr-review`.\n name: 'Review',\n // A card's pull request is reviewed here by the independent reviewer, in its own\n // review seat on the pull request's branch. Work has no self-review phase; a board that\n // wants one adds a review-context phase granting only factory_record_review_verdict.\n kind: 'working',\n runner: { skill: 'factory-review', context: 'review' },\n tools: ['factory_record_review_verdict', 'factory_review_source'],\n // Merged, closed, or set aside in Intake. An issue card can go back to its builder for a\n // fix; a pull request's own card never reaches the builder's lanes (workPullRequestCardRejection).\n nextPhases: ['intake', 'planning', 'execute', 'done', 'canceled'],\n },\n done: {\n name: 'Done',\n kind: 'terminal',\n // A review request on a finished pull request reopens its review.\n nextPhases: ['pr-review'],\n },\n canceled: {\n name: 'Canceled',\n kind: 'terminal',\n // Revived into Intake; a pull request closed without merging and then reopened goes back to Review.\n nextPhases: ['intake', 'pr-review'],\n },\n },\n});\n"],"mappings":";;;;;;;AAQA,MAAa,oBACX;;;;;AAOF,MAAa,kBACX;AAWF,MAAa,YAAY,uBAA6F;CACpH,IAAI;CACJ,MAAM;CACN,cAAc;CACd,cAAc;EAAE,WAAW;EAAQ,UAAU;CAAW;CACxD,QAAQ;EACN,QAAQ;GACN,MAAM;GACN,MAAM;GAGN,YAAY;IAAC;IAAU;IAAY;IAAa;IAAQ;GAAU;EACpE;EACA,QAAQ;GACN,MAAM;GACN,MAAM;GACN,QAAQ;IAAE,OAAO;IAAkB,SAAS;GAAS;GAErD,YAAY;IAAC;IAAU;IAAY;IAAQ;GAAU;EACvD;EACA,UAAU;GACR,MAAM;GACN,MAAM;GAEN,QAAQ;IAAE,OAAO;IAAgB,SAAS;GAAO;GACjD,YAAY;IAAC;IAAW;IAAU;IAAU;IAAQ;GAAU;GAE9D,UAAU;IAAE,IAAI;IAAe,aAAa;GAAM;EACpD;EACA,SAAS;GACP,MAAM;GACN,MAAM;GACN,QAAQ;IAAE,OAAO;IAAiB,SAAS;IAAQ,MAAM;KAAE,WAAW;KAAiB,SAAS;IAAG;GAAE;GAGrG,YAAY;IAAC;IAAa;IAAY;IAAQ;GAAU;EAC1D;EACA,aAAa;GAGX,MAAM;GAIN,MAAM;GACN,QAAQ;IAAE,OAAO;IAAkB,SAAS;GAAS;GACrD,OAAO,CAAC,iCAAiC,uBAAuB;GAGhE,YAAY;IAAC;IAAU;IAAY;IAAW;IAAQ;GAAU;EAClE;EACA,MAAM;GACJ,MAAM;GACN,MAAM;GAEN,YAAY,CAAC,WAAW;EAC1B;EACA,UAAU;GACR,MAAM;GACN,MAAM;GAEN,YAAY,CAAC,UAAU,WAAW;EACpC;CACF;AACF,CAAC"}
1
+ {"version":3,"file":"work.js","names":[],"sources":["../../src/boards/work.ts"],"sourcesContent":["import { DEFAULT_BOARD_ID } from './default-board.js';\nimport { compileBoardDefinition } from './define-board.js';\nimport type { BoardPhaseDefinition } from './define-board.js';\n\n/**\n * A change request tracked on its own card never attaches to this one, so Review refuses the card and\n * the builder leaves it in Building: the goal counts that hand-off as done rather than looping on it.\n */\nexport const OWN_CARD_HAND_OFF =\n 'Also done, with the card left in Building, when the change request was opened but is tracked on its own card ' +\n \"and the builder's latest message posts its link and says a person should confirm it is reviewed there.\";\n\n/**\n * The goal Building pursues. The goal judge sees only this text and the latest messages, so it\n * spells out when the build is done and when it waits for a person.\n */\nexport const BUILD_OBJECTIVE =\n 'Build the plan approved in Planning for this work item. Done when every step of that plan is implemented on ' +\n \"the work branch; the plan's verification gates (the tests, typecheck and lint it names, else the narrowest \" +\n 'relevant ones) were run on the final head and passed; the branch is pushed; and the card was moved on with ' +\n 'factory_transition_work_item out of Building (to Review after opening the change request, or back to ' +\n \"Planning if the plan proved wrong); the builder's latest message names the move and the pushed head. \" +\n OWN_CARD_HAND_OFF +\n ' Continue while any of that is missing. Waiting only when the agent asked a person a question it cannot ' +\n 'answer from the repository.';\n\nexport type WorkBoardPhase = 'intake' | 'planning' | 'execute' | 'pr-review' | 'done' | 'canceled';\n\nexport const workBoard = compileBoardDefinition<'work', Record<WorkBoardPhase, BoardPhaseDefinition<WorkBoardPhase>>>({\n id: DEFAULT_BOARD_ID,\n name: 'Work',\n initialPhase: 'intake',\n sourceClosed: { completed: 'done', canceled: 'canceled' },\n phases: {\n intake: {\n name: 'Intake',\n kind: 'resting',\n // Never straight to Building: a plan comes first. Review takes a pull request's own card;\n // Done is where a completed source closes it. New projects' Work has no Triage; projects\n // stored before keep theirs (workSeedWithTriage).\n nextPhases: ['planning', 'pr-review', 'done', 'canceled'],\n },\n planning: {\n name: 'Planning',\n kind: 'working',\n // Planning and Building share one session, so the builder keeps the plan's context.\n runner: { skill: 'factory-plan', context: 'work' },\n nextPhases: ['execute', 'intake', 'done', 'canceled'],\n // The card stays in Planning until submit_plan comes back approved; then factory-plan moves it.\n exitTool: { id: 'submit_plan', autoApprove: false },\n },\n execute: {\n name: 'Building',\n kind: 'working',\n runner: { skill: 'factory-build', context: 'work', goal: { objective: BUILD_OBJECTIVE, maxRuns: 20 } },\n // Review once the builder opened the change request; Planning again when the build shows\n // the plan was wrong.\n nextPhases: ['pr-review', 'planning', 'done', 'canceled'],\n },\n 'pr-review': {\n // Keyed `pr-review`: projects stored before Work dropped its self-review phase hold a\n // `review` phase for it, and the retired Review board's cards read as `pr-review`.\n name: 'Review',\n // A card's pull request is reviewed here by the independent reviewer, in its own\n // review seat on the pull request's branch. Work has no self-review phase; a board that\n // wants one adds a review-context phase granting only factory_record_review_verdict.\n kind: 'working',\n runner: { skill: 'factory-review', context: 'review' },\n tools: ['factory_record_review_verdict', 'factory_review_source'],\n // Merged, closed, or set aside in Intake. An issue card can go back to its builder for a\n // fix; a pull request's own card never reaches the builder's lanes (workPullRequestCardRejection).\n nextPhases: ['intake', 'planning', 'execute', 'done', 'canceled'],\n },\n done: {\n name: 'Done',\n kind: 'terminal',\n // A review request on a finished pull request reopens its review.\n nextPhases: ['pr-review'],\n },\n canceled: {\n name: 'Canceled',\n kind: 'terminal',\n // Revived into Intake; a pull request closed without merging and then reopened goes back to Review.\n nextPhases: ['intake', 'pr-review'],\n },\n },\n});\n"],"mappings":";;;;;;;AAQA,MAAa,oBACX;;;;;AAOF,MAAa,kBACX;AAWF,MAAa,YAAY,uBAA6F;CACpH,IAAI;CACJ,MAAM;CACN,cAAc;CACd,cAAc;EAAE,WAAW;EAAQ,UAAU;CAAW;CACxD,QAAQ;EACN,QAAQ;GACN,MAAM;GACN,MAAM;GAIN,YAAY;IAAC;IAAY;IAAa;IAAQ;GAAU;EAC1D;EACA,UAAU;GACR,MAAM;GACN,MAAM;GAEN,QAAQ;IAAE,OAAO;IAAgB,SAAS;GAAO;GACjD,YAAY;IAAC;IAAW;IAAU;IAAQ;GAAU;GAEpD,UAAU;IAAE,IAAI;IAAe,aAAa;GAAM;EACpD;EACA,SAAS;GACP,MAAM;GACN,MAAM;GACN,QAAQ;IAAE,OAAO;IAAiB,SAAS;IAAQ,MAAM;KAAE,WAAW;KAAiB,SAAS;IAAG;GAAE;GAGrG,YAAY;IAAC;IAAa;IAAY;IAAQ;GAAU;EAC1D;EACA,aAAa;GAGX,MAAM;GAIN,MAAM;GACN,QAAQ;IAAE,OAAO;IAAkB,SAAS;GAAS;GACrD,OAAO,CAAC,iCAAiC,uBAAuB;GAGhE,YAAY;IAAC;IAAU;IAAY;IAAW;IAAQ;GAAU;EAClE;EACA,MAAM;GACJ,MAAM;GACN,MAAM;GAEN,YAAY,CAAC,WAAW;EAC1B;EACA,UAAU;GACR,MAAM;GACN,MAAM;GAEN,YAAY,CAAC,UAAU,WAAW;EACpC;CACF;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"build-runner.d.ts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AC1E;AAED,qEAAqE;AACrE,MAAM,WAAW,2BAA2B;IAC1C,GAAG,EAAE,qBAAqB,CAAC;IAC3B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACnC;AAED,qBAAa,sBAAsB;;IACjC,QAAQ,CAAC,QAAQ;;;;;;;;;;;;;;;mBAAC;IAOlB,YAAY,IAAI,EAAE,oBAAoB,EAAE,OAAO,EAAE,6BAA6B,EAY7E;IAED,wEAAwE;IACxE,SAAS,IAAI,eAAe,GAAG,SAAS,CAEvC;IAED,2FAA2F;IAC3F,IAAI,iBAAiB,IAAI,OAAO,CAE/B;IAED,gGAAgG;IAC1F,cAAc,IAAI,OAAO,CAAC,OAAO,CAAC,CAIvC;IAED;;;;;OAKG;IACG,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,2BAA2B,GAAG,SAAS,CAAC,CAsBrF;IAED;;;;OAIG;IACH,QAAQ,CAAC,gBAAgB,UAAW,mBAAmB,KAAG,IAAI,CAa5D;IAEF;;;;;;OAMG;IACH,QAAQ,CAAC,KAAK,EAAE,qBAAqB,CAqCnC;CACH"}
@@ -1,7 +1,7 @@
1
1
  import { resolveProjectEnvironment } from "../workspace.js";
2
2
  import { probeSchedulesAvailable } from "./build-schedule.js";
3
3
  import { ENVIRONMENT_BUILD_WORKFLOW_ID, createEnvironmentBuildWorkflow } from "./build-workflow.js";
4
- import { environmentBuildContext, errorReason, resolveEnvironmentHeads } from "./build.js";
4
+ import { environmentBuildContextWithEnv, errorReason, resolveEnvironmentHeads } from "./build.js";
5
5
  // src/environment/build-runner.ts
6
6
  var EnvironmentBuildRunner = class {
7
7
  workflow;
@@ -51,7 +51,7 @@ var EnvironmentBuildRunner = class {
51
51
  const environment = await resolveProjectEnvironment(sourceControl.storage, project);
52
52
  const heads = project.lastBuildHeads ?? project.activeTemplateHeads ?? await resolveEnvironmentHeads(sourceControl, project, environment);
53
53
  return {
54
- ctx: environmentBuildContext(project, environment, heads, sourceControl.versionControl),
54
+ ctx: (await environmentBuildContextWithEnv(project, environment, heads, sourceControl.versionControl, this.#deps.sandboxEnvs)).ctx,
55
55
  settings: environment.settings
56
56
  };
57
57
  }
@@ -1 +1 @@
1
- {"version":3,"file":"build-runner.js","names":[],"sources":["../../src/environment/build-runner.ts"],"sourcesContent":["/**\n * Starts `factory-environment-build` runs on the booted `Mastra`. Every\n * trigger goes through a workflow run so the start decision and the poll are\n * recorded the same way whether a route, the scheduler or a webhook asked.\n */\n\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { FactorySandboxContext } from '@mastra/core/workspace';\nimport type { RepositoryPushEvent } from '../integrations/base.js';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport { probeSchedulesAvailable } from './build-schedule.js';\nimport type { ScheduleService } from './build-schedule.js';\nimport { createEnvironmentBuildWorkflow, ENVIRONMENT_BUILD_WORKFLOW_ID } from './build-workflow.js';\nimport type { EnvironmentBuildWorkflowOptions } from './build-workflow.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome, EnvironmentBuildTrigger } from './build.js';\nimport { environmentBuildContext, errorReason, resolveEnvironmentHeads } from './build.js';\n\nexport type StartEnvironmentBuild = (\n projectId: string,\n trigger: EnvironmentBuildTrigger,\n) => Promise<EnvironmentBuildOutcome>;\n\nexport interface EnvironmentBuildRunnerOptions extends Omit<EnvironmentBuildWorkflowOptions, 'onStart'> {\n /** The booted instance; `undefined` until the host finished `finalize()`. */\n getMastra: () => Mastra | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n}\n\n/** What a read of a build's status or history hands the provider. */\nexport interface EnvironmentBuildReadContext {\n ctx: FactorySandboxContext;\n settings: Record<string, unknown>;\n}\n\nexport class EnvironmentBuildRunner {\n readonly workflow;\n readonly #deps: EnvironmentBuildDeps;\n readonly #getMastra: () => Mastra | undefined;\n readonly #logger: EnvironmentBuildRunnerOptions['logger'];\n readonly #pending = new Map<string, (outcome: EnvironmentBuildOutcome) => void>();\n #scheduleAvailable = false;\n\n constructor(deps: EnvironmentBuildDeps, options: EnvironmentBuildRunnerOptions) {\n const { getMastra, logger, ...workflowOptions } = options;\n this.#deps = deps;\n this.#getMastra = getMastra;\n this.#logger = logger;\n this.workflow = createEnvironmentBuildWorkflow(deps, {\n ...workflowOptions,\n onStart: (runId, outcome) => {\n this.#pending.get(runId)?.(outcome);\n this.#pending.delete(runId);\n },\n });\n }\n\n /** The schedule service of the booted host, `undefined` before boot. */\n schedules(): ScheduleService | undefined {\n return this.#getMastra()?.schedules;\n }\n\n /** Whether the host's storage implements schedules; false until `probeSchedules()` ran. */\n get scheduleAvailable(): boolean {\n return this.#scheduleAvailable;\n }\n\n /** Probe once after the host booted; a storage without the domain disables the cron trigger. */\n async probeSchedules(): Promise<boolean> {\n const schedules = this.schedules();\n this.#scheduleAvailable = schedules ? await probeSchedulesAvailable(schedules) : false;\n return this.#scheduleAvailable;\n }\n\n /**\n * The context a status or history read hands the provider. Heads come from\n * the stored last attempt (the build being read was pinned to them), else\n * the active template, so a read never calls GitHub; before the first build\n * they are resolved live once.\n */\n async readContext(projectId: string): Promise<EnvironmentBuildReadContext | undefined> {\n const sourceControl = this.#deps.sourceControl;\n if (!sourceControl) return undefined;\n const project = await this.#deps.projects.getById({ id: projectId });\n if (!project) return undefined;\n const environment = await resolveProjectEnvironment(sourceControl.storage, project);\n const heads =\n project.lastBuildHeads ??\n project.activeTemplateHeads ??\n (await resolveEnvironmentHeads(sourceControl, project, environment));\n return {\n ctx: environmentBuildContext(project, environment, heads, sourceControl.versionControl),\n settings: environment.settings,\n };\n }\n\n /**\n * A push to an environment repository's default branch starts a `push` run\n * when the project opted in; the run's debounce claim decides whether it\n * builds. Fire and forget: the webhook never waits on it.\n */\n readonly onRepositoryPush = (event: RepositoryPushEvent): void => {\n if (!event.projectRepository.inEnvironment) return;\n const branch = event.defaultBranch;\n if (event.ref !== `refs/heads/${branch}`) return;\n void this.#deps.projects\n .getById({ id: event.factoryProjectId })\n .then(project => (project?.buildOnPushEnabled ? this.start(project.id, 'push') : undefined))\n .catch((error: unknown) => {\n this.#logger?.info('environment build push hand-off failed', {\n factoryProjectId: event.factoryProjectId,\n reason: errorReason(error),\n });\n });\n };\n\n /**\n * Start a run and resolve with the first step's answer; the poll step keeps\n * running in the background. Resolves `unavailable` before the host booted\n * or when the host never registered the workflow, and `failed` when the run\n * could not be created; a caller that already saved its own change must not\n * fail on the build it merely requested.\n */\n readonly start: StartEnvironmentBuild = async (projectId, trigger) => {\n const mastra = this.#getMastra();\n if (!mastra) return { outcome: 'unavailable', reason: 'not_ready' };\n let run: Awaited<ReturnType<typeof this.workflow.createRun>>;\n try {\n run = await mastra.getWorkflow(ENVIRONMENT_BUILD_WORKFLOW_ID).createRun();\n } catch (error) {\n const reason = errorReason(error);\n this.#logger?.info('environment build run could not be created', { factoryProjectId: projectId, reason });\n return mastra.listWorkflows()[ENVIRONMENT_BUILD_WORKFLOW_ID]\n ? { outcome: 'failed', reason }\n : { outcome: 'unavailable', reason: 'no_workflow' };\n }\n const outcome = new Promise<EnvironmentBuildOutcome>(resolve => this.#pending.set(run.runId, resolve));\n run\n .start({ inputData: { projectId, trigger } })\n .then(result => {\n if (result.status !== 'success') {\n this.#logger?.info('environment build run did not succeed', {\n factoryProjectId: projectId,\n runId: run.runId,\n });\n }\n })\n .catch((error: unknown) => {\n this.#logger?.info('environment build run threw', {\n factoryProjectId: projectId,\n runId: run.runId,\n reason: errorReason(error),\n });\n })\n .finally(() => {\n // A run that failed before its first step answered must not hang the caller.\n this.#pending.get(run.runId)?.({ outcome: 'failed', reason: 'The build run ended before it started a build.' });\n this.#pending.delete(run.runId);\n });\n return outcome;\n };\n}\n"],"mappings":";;;;;AAkCA,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA,2BAAoB,IAAI,IAAwD;CAChF,qBAAqB;CAErB,YAAY,MAA4B,SAAwC;EAC9E,MAAM,EAAE,WAAW,QAAQ,GAAG,oBAAoB;EAClD,KA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AM;IACxB,QAAQ,YAAY,KAAK;GAC3B,CAAC;EACH,CAAC;CACL;;;;;;;;CASA,QAAwC,OAAO,WAAW,YAAY;EACpE,MAAM,SAAS,KAAK,WAAW;EAC/B,IAAI,CAAC,QAAQ,OAAO;GAAE,SAAS;GAAe,QAAQ;EAAY;EAClE,IAAI;EACJ,IAAI;GACF,MAAM,MAAM,OAAO,YAAY,6BAA6B,CAAC,CAAC,UAAU;EAC1E,SAAS,OAAO;GACd,MAAM,SAAS,YAAY,KAAK;GAChC,KAAK,SAAS,KAAK,8CAA8C;IAAE,kBAAkB;IAAW;GAAO,CAAC;GACxG,OAAO,OAAO,cAAc,CAAC,CAAA,+BACzB;IAAE,SAAS;IAAU;GAAO,IAC5B;IAAE,SAAS;IAAe,QAAQ;GAAc;EACtD;EACA,MAAM,UAAU,IAAI,SAAiC,YAAW,KAAK,SAAS,IAAI,IAAI,OAAO,OAAO,CAAC;EACrG,IACG,MAAM,EAAE,WAAW;GAAE;GAAW;EAAQ,EAAE,CAAC,CAAC,CAC5C,MAAK,WAAU;GACd,IAAI,OAAO,WAAW,WACpB,KAAK,SAAS,KAAK,yCAAyC;IAC1D,kBAAkB;IAClB,OAAO,IAAI;GACb,CAAC;EAEL,CAAC,CAAC,CACD,OAAO,UAAmB;GACzB,KAAK,SAAS,KAAK,+BAA+B;IAChD,kBAAkB;IAClB,OAAO,IAAI;IACX,QAAQ,YAAY,KAAK;GAC3B,CAAC;EACH,CAAC,CAAC,CACD,cAAc;GAEb,KAAK,SAAS,IAAI,IAAI,KAAK,CAAC,GAAG;IAAE,SAAS;IAAU,QAAQ;GAAiD,CAAC;GAC9G,KAAK,SAAS,OAAO,IAAI,KAAK;EAChC,CAAC;EACH,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"build-runner.js","names":[],"sources":["../../src/environment/build-runner.ts"],"sourcesContent":["/**\n * Starts `factory-environment-build` runs on the booted `Mastra`. Every\n * trigger goes through a workflow run so the start decision and the poll are\n * recorded the same way whether a route, the scheduler or a webhook asked.\n */\n\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { FactorySandboxContext } from '@mastra/core/workspace';\nimport type { RepositoryPushEvent } from '../integrations/base.js';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport { probeSchedulesAvailable } from './build-schedule.js';\nimport type { ScheduleService } from './build-schedule.js';\nimport { createEnvironmentBuildWorkflow, ENVIRONMENT_BUILD_WORKFLOW_ID } from './build-workflow.js';\nimport type { EnvironmentBuildWorkflowOptions } from './build-workflow.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome, EnvironmentBuildTrigger } from './build.js';\nimport { environmentBuildContextWithEnv, errorReason, resolveEnvironmentHeads } from './build.js';\n\nexport type StartEnvironmentBuild = (\n projectId: string,\n trigger: EnvironmentBuildTrigger,\n) => Promise<EnvironmentBuildOutcome>;\n\nexport interface EnvironmentBuildRunnerOptions extends Omit<EnvironmentBuildWorkflowOptions, 'onStart'> {\n /** The booted instance; `undefined` until the host finished `finalize()`. */\n getMastra: () => Mastra | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n}\n\n/** What a read of a build's status or history hands the provider. */\nexport interface EnvironmentBuildReadContext {\n ctx: FactorySandboxContext;\n settings: Record<string, unknown>;\n}\n\nexport class EnvironmentBuildRunner {\n readonly workflow;\n readonly #deps: EnvironmentBuildDeps;\n readonly #getMastra: () => Mastra | undefined;\n readonly #logger: EnvironmentBuildRunnerOptions['logger'];\n readonly #pending = new Map<string, (outcome: EnvironmentBuildOutcome) => void>();\n #scheduleAvailable = false;\n\n constructor(deps: EnvironmentBuildDeps, options: EnvironmentBuildRunnerOptions) {\n const { getMastra, logger, ...workflowOptions } = options;\n this.#deps = deps;\n this.#getMastra = getMastra;\n this.#logger = logger;\n this.workflow = createEnvironmentBuildWorkflow(deps, {\n ...workflowOptions,\n onStart: (runId, outcome) => {\n this.#pending.get(runId)?.(outcome);\n this.#pending.delete(runId);\n },\n });\n }\n\n /** The schedule service of the booted host, `undefined` before boot. */\n schedules(): ScheduleService | undefined {\n return this.#getMastra()?.schedules;\n }\n\n /** Whether the host's storage implements schedules; false until `probeSchedules()` ran. */\n get scheduleAvailable(): boolean {\n return this.#scheduleAvailable;\n }\n\n /** Probe once after the host booted; a storage without the domain disables the cron trigger. */\n async probeSchedules(): Promise<boolean> {\n const schedules = this.schedules();\n this.#scheduleAvailable = schedules ? await probeSchedulesAvailable(schedules) : false;\n return this.#scheduleAvailable;\n }\n\n /**\n * The context a status or history read hands the provider. Heads come from\n * the stored last attempt (the build being read was pinned to them), else\n * the active template, so a read never calls GitHub; before the first build\n * they are resolved live once.\n */\n async readContext(projectId: string): Promise<EnvironmentBuildReadContext | undefined> {\n const sourceControl = this.#deps.sourceControl;\n if (!sourceControl) return undefined;\n const project = await this.#deps.projects.getById({ id: projectId });\n if (!project) return undefined;\n const environment = await resolveProjectEnvironment(sourceControl.storage, project);\n const heads =\n project.lastBuildHeads ??\n project.activeTemplateHeads ??\n (await resolveEnvironmentHeads(sourceControl, project, environment));\n return {\n ctx: (\n await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n sourceControl.versionControl,\n this.#deps.sandboxEnvs,\n )\n ).ctx,\n settings: environment.settings,\n };\n }\n\n /**\n * A push to an environment repository's default branch starts a `push` run\n * when the project opted in; the run's debounce claim decides whether it\n * builds. Fire and forget: the webhook never waits on it.\n */\n readonly onRepositoryPush = (event: RepositoryPushEvent): void => {\n if (!event.projectRepository.inEnvironment) return;\n const branch = event.defaultBranch;\n if (event.ref !== `refs/heads/${branch}`) return;\n void this.#deps.projects\n .getById({ id: event.factoryProjectId })\n .then(project => (project?.buildOnPushEnabled ? this.start(project.id, 'push') : undefined))\n .catch((error: unknown) => {\n this.#logger?.info('environment build push hand-off failed', {\n factoryProjectId: event.factoryProjectId,\n reason: errorReason(error),\n });\n });\n };\n\n /**\n * Start a run and resolve with the first step's answer; the poll step keeps\n * running in the background. Resolves `unavailable` before the host booted\n * or when the host never registered the workflow, and `failed` when the run\n * could not be created; a caller that already saved its own change must not\n * fail on the build it merely requested.\n */\n readonly start: StartEnvironmentBuild = async (projectId, trigger) => {\n const mastra = this.#getMastra();\n if (!mastra) return { outcome: 'unavailable', reason: 'not_ready' };\n let run: Awaited<ReturnType<typeof this.workflow.createRun>>;\n try {\n run = await mastra.getWorkflow(ENVIRONMENT_BUILD_WORKFLOW_ID).createRun();\n } catch (error) {\n const reason = errorReason(error);\n this.#logger?.info('environment build run could not be created', { factoryProjectId: projectId, reason });\n return mastra.listWorkflows()[ENVIRONMENT_BUILD_WORKFLOW_ID]\n ? { outcome: 'failed', reason }\n : { outcome: 'unavailable', reason: 'no_workflow' };\n }\n const outcome = new Promise<EnvironmentBuildOutcome>(resolve => this.#pending.set(run.runId, resolve));\n run\n .start({ inputData: { projectId, trigger } })\n .then(result => {\n if (result.status !== 'success') {\n this.#logger?.info('environment build run did not succeed', {\n factoryProjectId: projectId,\n runId: run.runId,\n });\n }\n })\n .catch((error: unknown) => {\n this.#logger?.info('environment build run threw', {\n factoryProjectId: projectId,\n runId: run.runId,\n reason: errorReason(error),\n });\n })\n .finally(() => {\n // A run that failed before its first step answered must not hang the caller.\n this.#pending.get(run.runId)?.({ outcome: 'failed', reason: 'The build run ended before it started a build.' });\n this.#pending.delete(run.runId);\n });\n return outcome;\n };\n}\n"],"mappings":";;;;;AAkCA,IAAa,yBAAb,MAAoC;CAClC;CACA;CACA;CACA;CACA,2BAAoB,IAAI,IAAwD;CAChF,qBAAqB;CAErB,YAAY,MAA4B,SAAwC;EAC9E,MAAM,EAAE,WAAW,QAAQ,GAAG,oBAAoB;EAClD,KAAK,QAAQ;EACb,KAAK,aAAa;EAClB,KAAK,UAAU;EACf,KAAK,WAAW,+BAA+B,MAAM;GACnD,GAAG;GACH,UAAU,OAAO,YAAY;IAC3B,KAAK,SAAS,IAAI,KAAK,CAAC,GAAG,OAAO;IAClC,KAAK,SAAS,OAAO,KAAK;GAC5B;EACF,CAAC;CACH;;CAGA,YAAyC;EAC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;IACtC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kGAAkG;IAClG,OAAO,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,uBAAuB,KAAK,IAAI,CAAC;CACrE;AAED,wBAAgB,8BAA8B,CAC5C,IAAI,EAAE,oBAAoB,EAC1B,OAAO,GAAE,+BAAoC;;;;;;;;;;;;;;;eA0F9C"}
@@ -1,5 +1,6 @@
1
+ import { maskSandboxEnvValues } from "../sandbox/sandbox-env.js";
1
2
  import { resolveProjectEnvironment } from "../workspace.js";
2
- import { ENVIRONMENT_BUILD_TRIGGERS, environmentBuildContext, errorReason, redactCredentials, runEnvironmentBuild } from "./build.js";
3
+ import { ENVIRONMENT_BUILD_TRIGGERS, environmentBuildContextWithEnv, errorReason, redactCredentials, runEnvironmentBuild } from "./build.js";
3
4
  import { z } from "zod";
4
5
  import { createStep, createWorkflow } from "@mastra/core/workflows";
5
6
  // src/environment/build-workflow.ts
@@ -80,7 +81,7 @@ function createEnvironmentBuildWorkflow(deps, options = {}) {
80
81
  status: "unknown"
81
82
  };
82
83
  const environment = await resolveProjectEnvironment(deps.sourceControl.storage, project);
83
- const ctx = environmentBuildContext(project, environment, heads, deps.sourceControl.versionControl);
84
+ const { ctx } = await environmentBuildContextWithEnv(project, environment, heads, deps.sourceControl.versionControl, deps.sandboxEnvs);
84
85
  const startedAt = now().getTime();
85
86
  try {
86
87
  for (;;) {
@@ -108,12 +109,12 @@ function createEnvironmentBuildWorkflow(deps, options = {}) {
108
109
  factoryProjectId: project.id,
109
110
  buildId: result.buildId,
110
111
  status: build.status,
111
- ...build.error ? { reason: redactCredentials(build.error) } : {}
112
+ ...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
112
113
  });
113
114
  return {
114
115
  ...result,
115
116
  status: build.status,
116
- ...build.error ? { reason: redactCredentials(build.error) } : {}
117
+ ...build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}
117
118
  };
118
119
  }
119
120
  if (now().getTime() - startedAt >= maxWaitMs) return {
@@ -124,7 +125,7 @@ function createEnvironmentBuildWorkflow(deps, options = {}) {
124
125
  await sleep(pollMs);
125
126
  }
126
127
  } catch (error) {
127
- const reason = errorReason(error);
128
+ const reason = maskSandboxEnvValues(errorReason(error), ctx.buildEnv);
128
129
  deps.logger?.info("environment build status read failed", {
129
130
  factoryProjectId: project.id,
130
131
  reason
@@ -1 +1 @@
1
- {"version":3,"file":"build-workflow.js","names":[],"sources":["../../src/environment/build-workflow.ts"],"sourcesContent":["/**\n * The `factory-environment-build` workflow: step one decides and starts a\n * build (`runEnvironmentBuild`), step two polls the provider until the build\n * settles and pins the active template on the project row. Registered by\n * `MastraFactory.prepare()` only when the sandbox has `builds`, and driven by\n * the Build now route, the per-project cron schedule and the GitHub push\n * hand-off. Saving settings never starts it.\n */\n\nimport { createStep, createWorkflow } from '@mastra/core/workflows';\nimport { z } from 'zod';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport {\n ENVIRONMENT_BUILD_TRIGGERS,\n environmentBuildContext,\n errorReason,\n redactCredentials,\n runEnvironmentBuild,\n} from './build.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome } from './build.js';\n\nexport const ENVIRONMENT_BUILD_WORKFLOW_ID = 'factory-environment-build';\nexport const DEFAULT_BUILD_POLL_MS = 15_000;\nexport const MAX_BUILD_WAIT_MS = 30 * 60_000;\n\nexport const environmentBuildInputSchema = z.object({\n projectId: z.string().min(1),\n trigger: z.enum(ENVIRONMENT_BUILD_TRIGGERS),\n});\n\nconst startOutputSchema = z.object({\n projectId: z.string(),\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n heads: z.record(z.string(), z.string()).optional(),\n});\n\nexport const environmentBuildOutputSchema = z.object({\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n /** Where the started build ended: `ready`, `failed`, or `unknown` when the provider lost it or the wait ran out. */\n status: z.enum(['ready', 'failed', 'unknown']).optional(),\n});\n\nexport type EnvironmentBuildWorkflowResult = z.infer<typeof environmentBuildOutputSchema>;\n\nexport interface EnvironmentBuildWorkflowOptions {\n sleep?: (ms: number) => Promise<void>;\n pollMs?: number;\n maxWaitMs?: number;\n /** Called with the first step's answer so a caller can return it without waiting for the poll. */\n onStart?: (runId: string, outcome: EnvironmentBuildOutcome) => void;\n}\n\nexport function createEnvironmentBuildWorkflow(\n deps: EnvironmentBuildDeps,\n options: EnvironmentBuildWorkflowOptions = {},\n) {\n const sleep = options.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));\n const pollMs = options.pollMs ?? DEFAULT_BUILD_POLL_MS;\n const maxWaitMs = options.maxWaitMs ?? MAX_BUILD_WAIT_MS;\n const now = deps.now ?? (() => new Date());\n\n const start = createStep({\n id: 'start',\n inputSchema: environmentBuildInputSchema,\n outputSchema: startOutputSchema,\n execute: async ({ inputData, runId }) => {\n const outcome = await runEnvironmentBuild(deps, inputData);\n options.onStart?.(runId, outcome);\n return { projectId: inputData.projectId, ...outcome };\n },\n });\n\n const awaitBuild = createStep({\n id: 'await-build',\n inputSchema: startOutputSchema,\n outputSchema: environmentBuildOutputSchema,\n execute: async ({ inputData }): Promise<EnvironmentBuildWorkflowResult> => {\n const { projectId, heads, ...result } = inputData;\n if (result.outcome !== 'started' || !result.buildId || !heads) return result;\n const builds = deps.sandbox?.builds;\n const project = await deps.projects.getById({ id: projectId });\n if (!builds || !deps.sourceControl || !project) return { ...result, status: 'unknown' };\n const environment = await resolveProjectEnvironment(deps.sourceControl.storage, project);\n const ctx = environmentBuildContext(project, environment, heads, deps.sourceControl.versionControl);\n const startedAt = now().getTime();\n try {\n for (;;) {\n const build = await builds.get(ctx, environment.settings, result.buildId);\n if (build.status === 'ready') {\n const templateId = build.templateId ?? result.templateId ?? result.buildId;\n // A newer run may have replaced `last_build_id` while this one\n // polled; the pin is skipped then so the stale image never wins.\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: result.buildId,\n templateId,\n heads,\n });\n deps.logger?.info(pinned ? 'environment build ready' : 'environment build ready but superseded', {\n factoryProjectId: project.id,\n templateId,\n });\n return { ...result, templateId, status: 'ready' };\n }\n if (build.status === 'failed' || build.status === 'unknown') {\n deps.logger?.info('environment build did not complete', {\n factoryProjectId: project.id,\n buildId: result.buildId,\n status: build.status,\n ...(build.error ? { reason: redactCredentials(build.error) } : {}),\n });\n return {\n ...result,\n status: build.status,\n ...(build.error ? { reason: redactCredentials(build.error) } : {}),\n };\n }\n if (now().getTime() - startedAt >= maxWaitMs) {\n return { ...result, status: 'unknown', reason: 'Build wait timed out.' };\n }\n await sleep(pollMs);\n }\n } catch (error) {\n const reason = errorReason(error);\n deps.logger?.info('environment build status read failed', { factoryProjectId: project.id, reason });\n return { ...result, status: 'unknown', reason };\n }\n },\n });\n\n return createWorkflow({\n id: ENVIRONMENT_BUILD_WORKFLOW_ID,\n inputSchema: environmentBuildInputSchema,\n outputSchema: environmentBuildOutputSchema,\n })\n .then(start)\n .then(awaitBuild)\n .commit();\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,MAAa,gCAAgC;AAC7C,MAAa,wBAAwB;AACrC,MAAa,oBAAoB;AAEjC,MAAa,8BAA8B,EAAE,OAAO;CAClD,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC3B,SAAS,EAAE,KAAK,0BAA0B;AAC5C,CAAC;AAED,MAAM,oBAAoB,EAAE,OAAO;CACjC,WAAW,EAAE,OAAO;CACpB,SAAS,EAAE,KAAK;EAAC;EAAW;EAAW;EAAe;CAAQ,CAAC;CAC/D,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,QAA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kB,QAAQ;KAAI;IAAO,CAAC;IAClG,OAAO;KAAE,GAAG;KAAQ,QAAQ;KAAW;IAAO;GAChD;EACF;CACF,CAAC;CAED,OAAO,eAAe;EACpB,IAAI;EACJ,aAAa;EACb,cAAc;CAChB,CAAC,CAAC,CACC,KAAK,KAAK,CAAC,CACX,KAAK,UAAU,CAAC,CAChB,OAAO;AACZ"}
1
+ {"version":3,"file":"build-workflow.js","names":[],"sources":["../../src/environment/build-workflow.ts"],"sourcesContent":["/**\n * The `factory-environment-build` workflow: step one decides and starts a\n * build (`runEnvironmentBuild`), step two polls the provider until the build\n * settles and pins the active template on the project row. Registered by\n * `MastraFactory.prepare()` only when the sandbox has `builds`, and driven by\n * the Build now route, the per-project cron schedule and the GitHub push\n * hand-off. Saving settings never starts it.\n */\n\nimport { createStep, createWorkflow } from '@mastra/core/workflows';\nimport { z } from 'zod';\nimport { maskSandboxEnvValues } from '../sandbox/sandbox-env.js';\nimport { resolveProjectEnvironment } from '../workspace.js';\nimport {\n ENVIRONMENT_BUILD_TRIGGERS,\n environmentBuildContextWithEnv,\n errorReason,\n redactCredentials,\n runEnvironmentBuild,\n} from './build.js';\nimport type { EnvironmentBuildDeps, EnvironmentBuildOutcome } from './build.js';\n\nexport const ENVIRONMENT_BUILD_WORKFLOW_ID = 'factory-environment-build';\nexport const DEFAULT_BUILD_POLL_MS = 15_000;\nexport const MAX_BUILD_WAIT_MS = 30 * 60_000;\n\nexport const environmentBuildInputSchema = z.object({\n projectId: z.string().min(1),\n trigger: z.enum(ENVIRONMENT_BUILD_TRIGGERS),\n});\n\nconst startOutputSchema = z.object({\n projectId: z.string(),\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n heads: z.record(z.string(), z.string()).optional(),\n});\n\nexport const environmentBuildOutputSchema = z.object({\n outcome: z.enum(['started', 'skipped', 'unavailable', 'failed']),\n buildId: z.string().optional(),\n templateId: z.string().optional(),\n reason: z.string().optional(),\n /** Where the started build ended: `ready`, `failed`, or `unknown` when the provider lost it or the wait ran out. */\n status: z.enum(['ready', 'failed', 'unknown']).optional(),\n});\n\nexport type EnvironmentBuildWorkflowResult = z.infer<typeof environmentBuildOutputSchema>;\n\nexport interface EnvironmentBuildWorkflowOptions {\n sleep?: (ms: number) => Promise<void>;\n pollMs?: number;\n maxWaitMs?: number;\n /** Called with the first step's answer so a caller can return it without waiting for the poll. */\n onStart?: (runId: string, outcome: EnvironmentBuildOutcome) => void;\n}\n\nexport function createEnvironmentBuildWorkflow(\n deps: EnvironmentBuildDeps,\n options: EnvironmentBuildWorkflowOptions = {},\n) {\n const sleep = options.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)));\n const pollMs = options.pollMs ?? DEFAULT_BUILD_POLL_MS;\n const maxWaitMs = options.maxWaitMs ?? MAX_BUILD_WAIT_MS;\n const now = deps.now ?? (() => new Date());\n\n const start = createStep({\n id: 'start',\n inputSchema: environmentBuildInputSchema,\n outputSchema: startOutputSchema,\n execute: async ({ inputData, runId }) => {\n const outcome = await runEnvironmentBuild(deps, inputData);\n options.onStart?.(runId, outcome);\n return { projectId: inputData.projectId, ...outcome };\n },\n });\n\n const awaitBuild = createStep({\n id: 'await-build',\n inputSchema: startOutputSchema,\n outputSchema: environmentBuildOutputSchema,\n execute: async ({ inputData }): Promise<EnvironmentBuildWorkflowResult> => {\n const { projectId, heads, ...result } = inputData;\n if (result.outcome !== 'started' || !result.buildId || !heads) return result;\n const builds = deps.sandbox?.builds;\n const project = await deps.projects.getById({ id: projectId });\n if (!builds || !deps.sourceControl || !project) return { ...result, status: 'unknown' };\n const environment = await resolveProjectEnvironment(deps.sourceControl.storage, project);\n const { ctx } = await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n deps.sourceControl.versionControl,\n deps.sandboxEnvs,\n );\n const startedAt = now().getTime();\n try {\n for (;;) {\n const build = await builds.get(ctx, environment.settings, result.buildId);\n if (build.status === 'ready') {\n const templateId = build.templateId ?? result.templateId ?? result.buildId;\n // A newer run may have replaced `last_build_id` while this one\n // polled; the pin is skipped then so the stale image never wins.\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: result.buildId,\n templateId,\n heads,\n });\n deps.logger?.info(pinned ? 'environment build ready' : 'environment build ready but superseded', {\n factoryProjectId: project.id,\n templateId,\n });\n return { ...result, templateId, status: 'ready' };\n }\n if (build.status === 'failed' || build.status === 'unknown') {\n deps.logger?.info('environment build did not complete', {\n factoryProjectId: project.id,\n buildId: result.buildId,\n status: build.status,\n ...(build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}),\n });\n return {\n ...result,\n status: build.status,\n ...(build.error ? { reason: maskSandboxEnvValues(redactCredentials(build.error), ctx.buildEnv) } : {}),\n };\n }\n if (now().getTime() - startedAt >= maxWaitMs) {\n return { ...result, status: 'unknown', reason: 'Build wait timed out.' };\n }\n await sleep(pollMs);\n }\n } catch (error) {\n const reason = maskSandboxEnvValues(errorReason(error), ctx.buildEnv);\n deps.logger?.info('environment build status read failed', { factoryProjectId: project.id, reason });\n return { ...result, status: 'unknown', reason };\n }\n },\n });\n\n return createWorkflow({\n id: ENVIRONMENT_BUILD_WORKFLOW_ID,\n inputSchema: environmentBuildInputSchema,\n outputSchema: environmentBuildOutputSchema,\n })\n .then(start)\n .then(awaitBuild)\n .commit();\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,gCAAgC;AAC7C,MAAa,wBAAwB;AACrC,MAAa,oBAAoB;AAEjC,MAAa,8BAA8B,EAAE,OAAO;CAClD,WAAW,EAAE,OAAO,CAAC,CAAC,IAAI,CAAC;CAC3B,SAAS,EAAE,KAAK,0BAA0B;AAC5C,CAAC;AAED,MAAM,oBAAoB,EAAE,OAAO;CACjC,WAAW,EAAE,OAAO;CACpB,SAAS,EAAE,KAAK;EAAC;EAAW;EAAW;EAAe;CAAQ,CAAC;CAC/D,SAAS,EAAE,OAAO,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Q;MAAW,QAAQ;KAAwB;KAEzE,MAAM,MAAM,MAAM;IACpB;GACF,SAAS,OAAO;IACd,MAAM,SAAS,qBAAqB,YAAY,KAAK,GAAG,IAAI,QAAQ;IACpE,KAAK,QAAQ,KAAK,wCAAwC;KAAE,kBAAkB,QAAQ;KAAI;IAAO,CAAC;IAClG,OAAO;KAAE,GAAG;KAAQ,QAAQ;KAAW;IAAO;GAChD;EACF;CACF,CAAC;CAED,OAAO,eAAe;EACpB,IAAI;EACJ,aAAa;EACb,cAAc;CAChB,CAAC,CAAC,CACC,KAAK,KAAK,CAAC,CACX,KAAK,UAAU,CAAC,CAChB,OAAO;AACZ"}
@@ -9,6 +9,7 @@
9
9
  import type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';
10
10
  import type { VersionControl } from '../capabilities/version-control.js';
11
11
  import type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';
12
+ import type { SandboxEnvStore } from '../storage/domains/sandbox-envs/base.js';
12
13
  import type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';
13
14
  import type { SessionEnvironment } from '../workspace.js';
14
15
  import type { EnvironmentHeads } from './heads.js';
@@ -24,6 +25,8 @@ export interface EnvironmentBuildDeps {
24
25
  projects: Pick<FactoryProjectsStorage, 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'>;
25
26
  /** Absent when the factory has no source-control integration to resolve heads with. */
26
27
  sourceControl: EnvironmentBuildSourceControl | undefined;
28
+ /** The Factory's sandbox environment variables; Build ones reach the template build. */
29
+ sandboxEnvs?: Pick<SandboxEnvStore, 'resolve'>;
27
30
  logger?: {
28
31
  info: (msg: string, meta?: Record<string, unknown>) => void;
29
32
  };
@@ -58,13 +61,23 @@ export declare function errorReason(error: unknown): string;
58
61
  * them itself.
59
62
  */
60
63
  export declare function environmentBuildContext(project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>, environment: SessionEnvironment, heads: EnvironmentHeads, versionControl: Pick<VersionControl, 'getRepositoryAccess'>): FactorySandboxContext;
64
+ /**
65
+ * {@link environmentBuildContext} with the Factory's Build variables, plus the
66
+ * build revision for {@link environmentBuildInputs}. Every build path (start,
67
+ * status read, poll) goes through this so all of them name the same template.
68
+ */
69
+ export declare function environmentBuildContextWithEnv(project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>, environment: SessionEnvironment, heads: EnvironmentHeads, versionControl: Pick<VersionControl, 'getRepositoryAccess'>, sandboxEnvs: Pick<SandboxEnvStore, 'resolve'> | undefined): Promise<{
70
+ ctx: FactorySandboxContext;
71
+ buildEnvRevision: string | undefined;
72
+ }>;
61
73
  /**
62
74
  * Fingerprint of everything a build bakes into the template besides the
63
75
  * repository heads: provider settings, the repositories and their order,
64
76
  * their setup commands, the workspace setup command and the working
65
- * directory. A schedule or push skips a ready build only while this matches.
77
+ * directory, and the Build variables' revision (a random id, never a value).
78
+ * A schedule or push skips a ready build only while this matches.
66
79
  */
67
- export declare function environmentBuildInputs(environment: SessionEnvironment): string;
80
+ export declare function environmentBuildInputs(environment: SessionEnvironment, buildEnvRevision?: string): string;
68
81
  /**
69
82
  * The current head of every environment repository's template branch, keyed
70
83
  * by slug. The template clones the repository default branch (a link's own
@@ -1 +1 @@
1
- {"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../src/environment/build.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAIH,OAAO,KAAK,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACpF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClG,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,CAAC;AAE5F,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,KAAK,EAAE,gBAAgB,EA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CAAC;IAAE,GAAG,EAAE,qBAAqB,CAAC;IAAC,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,CAAC,CAS/E;AAED;;;;;;GAMG;AACH,wBAAgB,sBAAsB,CAAC,WAAW,EAAE,kBAAkB,EAAE,gBAAgB,CAAC,EAAE,MAAM,GAAG,MAAM,CAczG;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAC3C,aAAa,EAAE,6BAA6B,EAC5C,OAAO,EAAE,IAAI,CAAC,cAAc,EAAE,OAAO,CAAC,EACtC,WAAW,EAAE,kBAAkB,GAC9B,OAAO,CAAC,gBAAgB,CAAC,CAS3B;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,QAAc,CAAC;AAKhD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,oBAAoB,EAC1B,KAAK,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,uBAAuB,CAAA;CAAE,GAC7D,OAAO,CAAC,uBAAuB,CAAC,CAuMlC"}
@@ -1,3 +1,4 @@
1
+ import { maskSandboxEnvValues, resolveSandboxEnv, sandboxBuildContext } from "../sandbox/sandbox-env.js";
1
2
  import { environmentSandboxContext, resolveProjectEnvironment } from "../workspace.js";
2
3
  import { headsChanged, recordedHeadResolver, resolveCurrentHeads } from "./heads.js";
3
4
  import { createHash, randomUUID } from "crypto";
@@ -49,12 +50,32 @@ function environmentBuildContext(project, environment, heads, versionControl) {
49
50
  };
50
51
  }
51
52
  /**
53
+ * {@link environmentBuildContext} with the Factory's Build variables, plus the
54
+ * build revision for {@link environmentBuildInputs}. Every build path (start,
55
+ * status read, poll) goes through this so all of them name the same template.
56
+ */
57
+ async function environmentBuildContextWithEnv(project, environment, heads, versionControl, sandboxEnvs) {
58
+ const env = sandboxEnvs ? await resolveSandboxEnv(sandboxEnvs, {
59
+ orgId: project.orgId,
60
+ projectId: project.id
61
+ }) : void 0;
62
+ const build = sandboxBuildContext(env);
63
+ return {
64
+ ctx: {
65
+ ...environmentBuildContext(project, environment, heads, versionControl),
66
+ ...build
67
+ },
68
+ buildEnvRevision: build.buildEnvRevision
69
+ };
70
+ }
71
+ /**
52
72
  * Fingerprint of everything a build bakes into the template besides the
53
73
  * repository heads: provider settings, the repositories and their order,
54
74
  * their setup commands, the workspace setup command and the working
55
- * directory. A schedule or push skips a ready build only while this matches.
75
+ * directory, and the Build variables' revision (a random id, never a value).
76
+ * A schedule or push skips a ready build only while this matches.
56
77
  */
57
- function environmentBuildInputs(environment) {
78
+ function environmentBuildInputs(environment, buildEnvRevision) {
58
79
  const inputs = {
59
80
  settings: environment.settings,
60
81
  workspaceSetupCommand: environment.workspaceSetupCommand ?? null,
@@ -63,7 +84,8 @@ function environmentBuildInputs(environment) {
63
84
  repositoryId: repo.repositoryId,
64
85
  templateBranch: repo.templateBranch,
65
86
  setupCommand: repo.setupCommand ?? null
66
- }))
87
+ })),
88
+ ...buildEnvRevision ? { buildEnvRevision } : {}
67
89
  };
68
90
  return createHash("sha256").update(JSON.stringify(inputs)).digest("hex");
69
91
  }
@@ -173,8 +195,8 @@ async function runEnvironmentBuild(deps, input) {
173
195
  resolved,
174
196
  now: now()
175
197
  });
176
- const failed = async (error, changes) => {
177
- const reason = errorReason(error);
198
+ const failed = async (error, changes, buildEnv) => {
199
+ const reason = maskSandboxEnvValues(errorReason(error), buildEnv);
178
200
  await release(changes);
179
201
  deps.logger?.info("environment build failed", {
180
202
  factoryProjectId: initial.id,
@@ -203,8 +225,9 @@ async function runEnvironmentBuild(deps, input) {
203
225
  };
204
226
  }
205
227
  heads = await resolveEnvironmentHeads(sourceControl, project, environment);
206
- ctx = environmentBuildContext(project, environment, heads, sourceControl.versionControl);
207
- buildInputs = environmentBuildInputs(environment);
228
+ const built = await environmentBuildContextWithEnv(project, environment, heads, sourceControl.versionControl, deps.sandboxEnvs);
229
+ ctx = built.ctx;
230
+ buildInputs = environmentBuildInputs(environment, built.buildEnvRevision);
208
231
  if (claim.uncertain) {
209
232
  if (builds.list) {
210
233
  const running = (await builds.list(ctx, environment.settings)).find((build) => build.status === "pending" || build.status === "building");
@@ -288,7 +311,7 @@ async function runEnvironmentBuild(deps, input) {
288
311
  lastBuildHeads: null,
289
312
  lastBuildInputs: null,
290
313
  ...attempted
291
- });
314
+ }, ctx.buildEnv);
292
315
  }
293
316
  const log = {
294
317
  factoryProjectId: project.id,
@@ -342,6 +365,6 @@ async function runEnvironmentBuild(deps, input) {
342
365
  clearInterval(renewal);
343
366
  }
344
367
  }
345
- export { BUILD_START_LEASE_MS, ENVIRONMENT_BUILD_TRIGGERS, environmentBuildContext, environmentBuildInputs, environmentBuildSessionId, errorReason, redactCredentials, resolveEnvironmentHeads, runEnvironmentBuild };
368
+ export { BUILD_START_LEASE_MS, ENVIRONMENT_BUILD_TRIGGERS, environmentBuildContext, environmentBuildContextWithEnv, environmentBuildInputs, environmentBuildSessionId, errorReason, redactCredentials, resolveEnvironmentHeads, runEnvironmentBuild };
346
369
 
347
370
  //# sourceMappingURL=build.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"build.js","names":[],"sources":["../../src/environment/build.ts"],"sourcesContent":["/**\n * One proactive environment build: decide whether a trigger should build,\n * hand the sandbox's `builds` capability a context identical to a session's,\n * and record the started build on the project row. Polling the build to its\n * end and pinning the active template is the workflow's second step\n * (`build-workflow.ts`), so a request that only needs the start answer never\n * waits on the provider.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\n\nimport type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { environmentSandboxContext, resolveProjectEnvironment } from '../workspace.js';\nimport type { SessionEnvironment } from '../workspace.js';\nimport { headsChanged, recordedHeadResolver, resolveCurrentHeads } from './heads.js';\nimport type { EnvironmentHeads } from './heads.js';\n\nexport const ENVIRONMENT_BUILD_TRIGGERS = ['manual', 'schedule', 'push'] as const;\nexport type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];\n\nexport interface EnvironmentBuildSourceControl {\n storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>;\n}\n\nexport interface EnvironmentBuildDeps {\n /** The factory's normalized sandbox; builds are unavailable without its `builds`. */\n sandbox: FactorySandbox | undefined;\n projects: Pick<\n FactoryProjectsStorage,\n 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'\n >;\n /** Absent when the factory has no source-control integration to resolve heads with. */\n sourceControl: EnvironmentBuildSourceControl | undefined;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n now?: () => Date;\n /** How often a run renews its build-start lease; a third of `BUILD_START_LEASE_MS` by default. */\n leaseRenewMs?: number;\n /** Waits between tries at recording a started build. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface EnvironmentBuildOutcome {\n outcome: 'started' | 'skipped' | 'unavailable' | 'failed';\n buildId?: string;\n templateId?: string;\n /** Why nothing started: `debounced`, `starting` (another run is starting a build), `in_progress`, `unchanged`, `unresolved` (a lapsed run may have started a build the provider cannot list), `no_environment`, `no_builds`, `no_source_control`; why a run failed: `not_recorded`, `superseded`, or an error. */\n reason?: string;\n /** The heads the started build pins; the workflow stores them once the build is ready. */\n heads?: EnvironmentHeads;\n}\n\n/** The synthetic session id a project's build runs under; never a session. */\nexport function environmentBuildSessionId(projectId: string): string {\n return `environment-build:${projectId}`;\n}\n\n/**\n * A build or setup error may echo a clone URL or a token; strip URL userinfo\n * and GitHub token shapes before the message is stored, logged or shown.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(/\\/\\/[^/\\s@]+@/g, '//***@').replace(/\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]+/g, '***');\n}\n\n/** An error's message with credentials redacted, safe to log, store or return. */\nexport function errorReason(error: unknown): string {\n return redactCredentials(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * The context an environment build (or a read of its status) hands the\n * provider: the same list form a session boots with, under the build's own\n * session id, with heads served from `heads` so the provider never resolves\n * them itself.\n */\nexport function environmentBuildContext(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n): FactorySandboxContext {\n return {\n sessionId: environmentBuildSessionId(project.id),\n factoryId: project.id,\n factoryName: project.name,\n ...environmentSandboxContext(environment, {\n orgId: project.orgId,\n getRepositoryAccess: args => versionControl.getRepositoryAccess(args),\n resolveHead: recordedHeadResolver(heads),\n }),\n };\n}\n\n/**\n * Fingerprint of everything a build bakes into the template besides the\n * repository heads: provider settings, the repositories and their order,\n * their setup commands, the workspace setup command and the working\n * directory. A schedule or push skips a ready build only while this matches.\n */\nexport function environmentBuildInputs(environment: SessionEnvironment): string {\n const inputs = {\n settings: environment.settings,\n workspaceSetupCommand: environment.workspaceSetupCommand ?? null,\n workingDirectory: environment.workingDirectory ?? null,\n repos: environment.repos.map(repo => ({\n repositoryId: repo.repositoryId,\n templateBranch: repo.templateBranch,\n setupCommand: repo.setupCommand ?? null,\n })),\n };\n return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');\n}\n\n/**\n * The current head of every environment repository's template branch, keyed\n * by slug. The template clones the repository default branch (a link's own\n * branch is the session's base, checked out after boot), so that is the\n * branch a build pins; sessions let the provider resolve the same head.\n */\nexport async function resolveEnvironmentHeads(\n sourceControl: EnvironmentBuildSourceControl,\n project: Pick<FactoryProject, 'orgId'>,\n environment: SessionEnvironment,\n): Promise<EnvironmentHeads> {\n return resolveCurrentHeads(sourceControl, {\n orgId: project.orgId,\n repositories: environment.repos.map(repo => ({\n id: repo.repositoryId,\n slug: repo.slug,\n branch: repo.templateBranch,\n })),\n });\n}\n\n/**\n * How long a build-start lease lasts without renewal. The run holding it\n * renews it every third of that while it works, so a lease lapses only when\n * its run died or stalled.\n */\nexport const BUILD_START_LEASE_MS = 10 * 60_000;\n\n/** Tries at recording a started build before the run leaves its lease to lapse. */\nconst RECORD_ATTEMPTS = 5;\n\n/**\n * Start a build for `projectId` when `trigger` calls for one. Every trigger\n * takes the project's build-start lease before reading build state and renews\n * it until the started build is recorded, so overlapping manual, scheduled and\n * push runs never both start a build, however long the provider takes; a run\n * that finds the lease held skips as `starting`. Every trigger skips while the\n * last build is still running; `schedule` and `push` also skip when the last\n * build is ready and neither a head nor any other template input changed;\n * `manual` otherwise always builds. A `push` that would build then takes the\n * leading-edge debounce claim, so only a push that starts a build opens the\n * window. Saving settings never builds.\n *\n * Taking over a lapsed lease leaves the start uncertain: the lapsed run may\n * have started a build it never recorded. The mark persists until resolved.\n * While it stands, a provider that lists builds is asked for a running one\n * (and every trigger skips as `in_progress` on it); with a provider that\n * cannot list, every trigger skips as `unresolved`.\n *\n * The result is written as the lease is released, and only while this run\n * still holds it. A failed `builds.start` clears the last build id, so a later\n * `schedule` or `push` cannot mistake the previous ready build for the current\n * template; any other error keeps a running build's id. A started build whose\n * recording keeps failing yields `failed` (`not_recorded`) with the lease left\n * to lapse rather than released, and a run that lost its lease while the\n * provider started yields `failed` (`superseded`); neither is polled or pinned.\n */\nexport async function runEnvironmentBuild(\n deps: EnvironmentBuildDeps,\n input: { projectId: string; trigger: EnvironmentBuildTrigger },\n): Promise<EnvironmentBuildOutcome> {\n const builds = deps.sandbox?.builds;\n if (!builds) return { outcome: 'unavailable', reason: 'no_builds' };\n if (!deps.sourceControl) return { outcome: 'unavailable', reason: 'no_source_control' };\n const sourceControl = deps.sourceControl;\n const initial = await deps.projects.getById({ id: input.projectId });\n if (!initial) return { outcome: 'skipped', reason: 'no_environment' };\n const now = deps.now ?? (() => new Date());\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n const pushDebounced = (project: FactoryProject, at: Date) =>\n project.lastPushBuildAt !== null &&\n at.getTime() - project.lastPushBuildAt.getTime() < project.buildPushDebounceMinutes * 60_000;\n if (input.trigger === 'push' && pushDebounced(initial, now())) return { outcome: 'skipped', reason: 'debounced' };\n\n const token = randomUUID();\n const lease = { id: initial.id, token, leaseMs: BUILD_START_LEASE_MS };\n const claim = await deps.projects.claimBuildStart({ ...lease, now: now() });\n if (!claim.claimed) return { outcome: 'skipped', reason: 'starting' };\n let held = true;\n const renewal = setInterval(\n () => {\n deps.projects.renewBuildStart({ ...lease, now: now() }).then(\n renewed => {\n if (!renewed) held = false;\n },\n // A failed renewal is retried on the next tick; the lease outlasts two misses.\n () => {},\n );\n },\n deps.leaseRenewMs ?? BUILD_START_LEASE_MS / 3,\n );\n renewal.unref?.();\n\n const attempted = { lastBuildAttemptedAt: now() };\n // Set once this run has reconciled an uncertain start, or builds past it.\n let resolved = false;\n const release = (changes: Parameters<EnvironmentBuildDeps['projects']['releaseBuildStart']>[0]['changes'] = {}) =>\n deps.projects.releaseBuildStart({ id: initial.id, token, changes, resolved, now: now() });\n const failed = async (error: unknown, changes: Parameters<typeof release>[0]) => {\n const reason = errorReason(error);\n await release(changes);\n deps.logger?.info('environment build failed', { factoryProjectId: initial.id, trigger: input.trigger, reason });\n return { outcome: 'failed', reason } satisfies EnvironmentBuildOutcome;\n };\n\n try {\n let project: FactoryProject;\n let environment: SessionEnvironment;\n let heads: EnvironmentHeads;\n let ctx: FactorySandboxContext;\n let buildInputs: string;\n try {\n // Read build state only once this run holds the lease, so a run that\n // finished while this one waited has already recorded its build.\n project = (await deps.projects.getById({ id: initial.id })) ?? initial;\n environment = await resolveProjectEnvironment(sourceControl.storage, project);\n if (environment.repos.length === 0) {\n await release();\n return { outcome: 'skipped', reason: 'no_environment' };\n }\n heads = await resolveEnvironmentHeads(sourceControl, project, environment);\n ctx = environmentBuildContext(project, environment, heads, sourceControl.versionControl);\n buildInputs = environmentBuildInputs(environment);\n\n if (claim.uncertain) {\n // A run whose lease lapsed may have reached the provider before it\n // died; a build it left running is never raced by a second one. The\n // mark stays until that build is gone, since its inputs are unknown.\n if (builds.list) {\n const listed = await builds.list(ctx, environment.settings);\n const running = listed.find(build => build.status === 'pending' || build.status === 'building');\n if (running) {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: running.buildId };\n }\n resolved = true;\n } else {\n // Without history the earlier start can never be reconciled, so no\n // trigger starts another build beside it.\n await release();\n return { outcome: 'skipped', reason: 'unresolved' };\n }\n }\n\n if (project.lastBuildId) {\n const last = await builds.get(ctx, environment.settings, project.lastBuildId);\n // Two runs polling one template fight over it (each poll resubmits its\n // own definition and the provider cancels the other), so a running\n // build is never joined by a second one, whatever asked.\n if (last.status === 'pending' || last.status === 'building') {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: project.lastBuildId };\n }\n // A ready build whose poll ran out or died with its host was never\n // pinned; pin it now so the skip below compares against what it built.\n let pinnedHeads = project.activeTemplateHeads;\n const lastTemplateId = last.templateId ?? project.lastBuildId;\n if (last.status === 'ready' && project.lastBuildHeads && project.activeTemplateId !== lastTemplateId) {\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: project.lastBuildId,\n templateId: lastTemplateId,\n heads: project.lastBuildHeads,\n });\n if (pinned) pinnedHeads = project.lastBuildHeads;\n }\n if (\n (input.trigger === 'schedule' || input.trigger === 'push') &&\n last.status === 'ready' &&\n !headsChanged(pinnedHeads, heads) &&\n project.lastBuildInputs === buildInputs\n ) {\n await release();\n return { outcome: 'skipped', reason: 'unchanged' };\n }\n }\n } catch (error) {\n return await failed(error, attempted);\n }\n\n // A run that lost its lease while reading must not start beside its successor.\n if (!held) return { outcome: 'skipped', reason: 'starting' };\n\n if (input.trigger === 'push') {\n // Claimed only now, so a push that skipped above never closes the window.\n let claimed: boolean;\n try {\n claimed = await deps.projects.claimBuildAttempt({\n id: project.id,\n debounceMinutes: project.buildPushDebounceMinutes,\n now: now(),\n });\n } catch (error) {\n return await failed(error, {});\n }\n if (!claimed) {\n await release();\n return { outcome: 'skipped', reason: 'debounced' };\n }\n }\n\n let started: Awaited<ReturnType<typeof builds.start>>;\n try {\n started = await builds.start(ctx, environment.settings);\n } catch (error) {\n // Only a failed start clears the last build: the previous one no longer\n // describes the template this project wants.\n return await failed(error, { lastBuildId: null, lastBuildHeads: null, lastBuildInputs: null, ...attempted });\n }\n\n // The provider has started the build: from here on, no error clears it.\n const log = { factoryProjectId: project.id, trigger: input.trigger, buildId: started.buildId };\n const changes = { lastBuildId: started.buildId, lastBuildHeads: heads, lastBuildInputs: buildInputs, ...attempted };\n let recorded: boolean | undefined;\n for (let attempt = 1; recorded === undefined; attempt++) {\n try {\n recorded = await release(changes);\n } catch (error) {\n if (attempt >= RECORD_ATTEMPTS) {\n // Keep the lease: it lapses once renewal stops, and the run that\n // takes it over looks for this build at the provider first.\n deps.logger?.info('environment build started but not recorded', { ...log, reason: errorReason(error) });\n return { outcome: 'failed', reason: 'not_recorded', buildId: started.buildId };\n }\n await sleep(1000 * 2 ** (attempt - 1));\n }\n }\n if (!recorded) {\n // A newer run took the lease while the provider started this build; the\n // project tracks that run's build, so this one is never polled or pinned.\n deps.logger?.info('environment build superseded', log);\n return { outcome: 'failed', reason: 'superseded', buildId: started.buildId };\n }\n try {\n deps.logger?.info('environment build started', { ...log, templateId: started.templateId });\n } catch {\n // Logging never turns a recorded build into a failure.\n }\n return {\n outcome: 'started',\n buildId: started.buildId,\n ...(started.templateId ? { templateId: started.templateId } : {}),\n heads,\n };\n } finally {\n clearInterval(renewal);\n }\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;AAAM;;AAoCvE,SAAgB,0BAA0B,WAA2B;CACnE,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,CAAC,CAAC,QAAQ,6CA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AI;EACJ,KAAK,IAAI,UAAU,GAAG,aAAa,KAAA,GAAW,WAC5C,IAAI;GACF,WAAW,MAAM,QAAQ,OAAO;EAClC,SAAS,OAAO;GACd,IAAI,WAAW,iBAAiB;IAG9B,KAAK,QAAQ,KAAK,8CAA8C;KAAE,GAAG;KAAK,QAAQ,YAAY,KAAK;IAAE,CAAC;IACtG,OAAO;KAAE,SAAS;KAAU,QAAQ;KAAgB,SAAS,QAAQ;IAAQ;GAC/E;GACA,MAAM,MAAM,MAAO,MAAM,UAAU,EAAE;EACvC;EAEF,IAAI,CAAC,UAAU;GAGb,KAAK,QAAQ,KAAK,gCAAgC,GAAG;GACrD,OAAO;IAAE,SAAS;IAAU,QAAQ;IAAc,SAAS,QAAQ;GAAQ;EAC7E;EACA,IAAI;GACF,KAAK,QAAQ,KAAK,6BAA6B;IAAE,GAAG;IAAK,YAAY,QAAQ;GAAW,CAAC;EAC3F,QAAQ,CAER;EACA,OAAO;GACL,SAAS;GACT,SAAS,QAAQ;GACjB,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D;EACF;CACF,UAAU;EACR,cAAc,OAAO;CACvB;AACF"}
1
+ {"version":3,"file":"build.js","names":[],"sources":["../../src/environment/build.ts"],"sourcesContent":["/**\n * One proactive environment build: decide whether a trigger should build,\n * hand the sandbox's `builds` capability a context identical to a session's,\n * and record the started build on the project row. Polling the build to its\n * end and pinning the active template is the workflow's second step\n * (`build-workflow.ts`), so a request that only needs the start answer never\n * waits on the provider.\n */\n\nimport { createHash, randomUUID } from 'node:crypto';\n\nimport type { FactorySandbox, FactorySandboxContext } from '@mastra/core/workspace';\nimport type { VersionControl } from '../capabilities/version-control.js';\nimport { maskSandboxEnvValues, resolveSandboxEnv, sandboxBuildContext } from '../sandbox/sandbox-env.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { SandboxEnvStore } from '../storage/domains/sandbox-envs/base.js';\nimport type { SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport { environmentSandboxContext, resolveProjectEnvironment } from '../workspace.js';\nimport type { SessionEnvironment } from '../workspace.js';\nimport { headsChanged, recordedHeadResolver, resolveCurrentHeads } from './heads.js';\nimport type { EnvironmentHeads } from './heads.js';\n\nexport const ENVIRONMENT_BUILD_TRIGGERS = ['manual', 'schedule', 'push'] as const;\nexport type EnvironmentBuildTrigger = (typeof ENVIRONMENT_BUILD_TRIGGERS)[number];\n\nexport interface EnvironmentBuildSourceControl {\n storage: Pick<SourceControlStorageHandle, 'projectRepositories' | 'repositories'>;\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>;\n}\n\nexport interface EnvironmentBuildDeps {\n /** The factory's normalized sandbox; builds are unavailable without its `builds`. */\n sandbox: FactorySandbox | undefined;\n projects: Pick<\n FactoryProjectsStorage,\n 'getById' | 'claimBuildAttempt' | 'claimBuildStart' | 'renewBuildStart' | 'releaseBuildStart' | 'pinActiveTemplate'\n >;\n /** Absent when the factory has no source-control integration to resolve heads with. */\n sourceControl: EnvironmentBuildSourceControl | undefined;\n /** The Factory's sandbox environment variables; Build ones reach the template build. */\n sandboxEnvs?: Pick<SandboxEnvStore, 'resolve'>;\n logger?: { info: (msg: string, meta?: Record<string, unknown>) => void };\n now?: () => Date;\n /** How often a run renews its build-start lease; a third of `BUILD_START_LEASE_MS` by default. */\n leaseRenewMs?: number;\n /** Waits between tries at recording a started build. */\n sleep?: (ms: number) => Promise<void>;\n}\n\nexport interface EnvironmentBuildOutcome {\n outcome: 'started' | 'skipped' | 'unavailable' | 'failed';\n buildId?: string;\n templateId?: string;\n /** Why nothing started: `debounced`, `starting` (another run is starting a build), `in_progress`, `unchanged`, `unresolved` (a lapsed run may have started a build the provider cannot list), `no_environment`, `no_builds`, `no_source_control`; why a run failed: `not_recorded`, `superseded`, or an error. */\n reason?: string;\n /** The heads the started build pins; the workflow stores them once the build is ready. */\n heads?: EnvironmentHeads;\n}\n\n/** The synthetic session id a project's build runs under; never a session. */\nexport function environmentBuildSessionId(projectId: string): string {\n return `environment-build:${projectId}`;\n}\n\n/**\n * A build or setup error may echo a clone URL or a token; strip URL userinfo\n * and GitHub token shapes before the message is stored, logged or shown.\n */\nexport function redactCredentials(message: string): string {\n return message.replace(/\\/\\/[^/\\s@]+@/g, '//***@').replace(/\\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]+/g, '***');\n}\n\n/** An error's message with credentials redacted, safe to log, store or return. */\nexport function errorReason(error: unknown): string {\n return redactCredentials(error instanceof Error ? error.message : String(error));\n}\n\n/**\n * The context an environment build (or a read of its status) hands the\n * provider: the same list form a session boots with, under the build's own\n * session id, with heads served from `heads` so the provider never resolves\n * them itself.\n */\nexport function environmentBuildContext(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n): FactorySandboxContext {\n return {\n sessionId: environmentBuildSessionId(project.id),\n factoryId: project.id,\n factoryName: project.name,\n ...environmentSandboxContext(environment, {\n orgId: project.orgId,\n getRepositoryAccess: args => versionControl.getRepositoryAccess(args),\n resolveHead: recordedHeadResolver(heads),\n }),\n };\n}\n\n/**\n * {@link environmentBuildContext} with the Factory's Build variables, plus the\n * build revision for {@link environmentBuildInputs}. Every build path (start,\n * status read, poll) goes through this so all of them name the same template.\n */\nexport async function environmentBuildContextWithEnv(\n project: Pick<FactoryProject, 'id' | 'orgId' | 'name'>,\n environment: SessionEnvironment,\n heads: EnvironmentHeads,\n versionControl: Pick<VersionControl, 'getRepositoryAccess'>,\n sandboxEnvs: Pick<SandboxEnvStore, 'resolve'> | undefined,\n): Promise<{ ctx: FactorySandboxContext; buildEnvRevision: string | undefined }> {\n const env = sandboxEnvs\n ? await resolveSandboxEnv(sandboxEnvs, { orgId: project.orgId, projectId: project.id })\n : undefined;\n const build = sandboxBuildContext(env);\n return {\n ctx: { ...environmentBuildContext(project, environment, heads, versionControl), ...build },\n buildEnvRevision: build.buildEnvRevision,\n };\n}\n\n/**\n * Fingerprint of everything a build bakes into the template besides the\n * repository heads: provider settings, the repositories and their order,\n * their setup commands, the workspace setup command and the working\n * directory, and the Build variables' revision (a random id, never a value).\n * A schedule or push skips a ready build only while this matches.\n */\nexport function environmentBuildInputs(environment: SessionEnvironment, buildEnvRevision?: string): string {\n const inputs = {\n settings: environment.settings,\n workspaceSetupCommand: environment.workspaceSetupCommand ?? null,\n workingDirectory: environment.workingDirectory ?? null,\n repos: environment.repos.map(repo => ({\n repositoryId: repo.repositoryId,\n templateBranch: repo.templateBranch,\n setupCommand: repo.setupCommand ?? null,\n })),\n // Only when set, so fingerprints recorded before Build variables existed still match.\n ...(buildEnvRevision ? { buildEnvRevision } : {}),\n };\n return createHash('sha256').update(JSON.stringify(inputs)).digest('hex');\n}\n\n/**\n * The current head of every environment repository's template branch, keyed\n * by slug. The template clones the repository default branch (a link's own\n * branch is the session's base, checked out after boot), so that is the\n * branch a build pins; sessions let the provider resolve the same head.\n */\nexport async function resolveEnvironmentHeads(\n sourceControl: EnvironmentBuildSourceControl,\n project: Pick<FactoryProject, 'orgId'>,\n environment: SessionEnvironment,\n): Promise<EnvironmentHeads> {\n return resolveCurrentHeads(sourceControl, {\n orgId: project.orgId,\n repositories: environment.repos.map(repo => ({\n id: repo.repositoryId,\n slug: repo.slug,\n branch: repo.templateBranch,\n })),\n });\n}\n\n/**\n * How long a build-start lease lasts without renewal. The run holding it\n * renews it every third of that while it works, so a lease lapses only when\n * its run died or stalled.\n */\nexport const BUILD_START_LEASE_MS = 10 * 60_000;\n\n/** Tries at recording a started build before the run leaves its lease to lapse. */\nconst RECORD_ATTEMPTS = 5;\n\n/**\n * Start a build for `projectId` when `trigger` calls for one. Every trigger\n * takes the project's build-start lease before reading build state and renews\n * it until the started build is recorded, so overlapping manual, scheduled and\n * push runs never both start a build, however long the provider takes; a run\n * that finds the lease held skips as `starting`. Every trigger skips while the\n * last build is still running; `schedule` and `push` also skip when the last\n * build is ready and neither a head nor any other template input changed;\n * `manual` otherwise always builds. A `push` that would build then takes the\n * leading-edge debounce claim, so only a push that starts a build opens the\n * window. Saving settings never builds.\n *\n * Taking over a lapsed lease leaves the start uncertain: the lapsed run may\n * have started a build it never recorded. The mark persists until resolved.\n * While it stands, a provider that lists builds is asked for a running one\n * (and every trigger skips as `in_progress` on it); with a provider that\n * cannot list, every trigger skips as `unresolved`.\n *\n * The result is written as the lease is released, and only while this run\n * still holds it. A failed `builds.start` clears the last build id, so a later\n * `schedule` or `push` cannot mistake the previous ready build for the current\n * template; any other error keeps a running build's id. A started build whose\n * recording keeps failing yields `failed` (`not_recorded`) with the lease left\n * to lapse rather than released, and a run that lost its lease while the\n * provider started yields `failed` (`superseded`); neither is polled or pinned.\n */\nexport async function runEnvironmentBuild(\n deps: EnvironmentBuildDeps,\n input: { projectId: string; trigger: EnvironmentBuildTrigger },\n): Promise<EnvironmentBuildOutcome> {\n const builds = deps.sandbox?.builds;\n if (!builds) return { outcome: 'unavailable', reason: 'no_builds' };\n if (!deps.sourceControl) return { outcome: 'unavailable', reason: 'no_source_control' };\n const sourceControl = deps.sourceControl;\n const initial = await deps.projects.getById({ id: input.projectId });\n if (!initial) return { outcome: 'skipped', reason: 'no_environment' };\n const now = deps.now ?? (() => new Date());\n const sleep = deps.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)));\n\n const pushDebounced = (project: FactoryProject, at: Date) =>\n project.lastPushBuildAt !== null &&\n at.getTime() - project.lastPushBuildAt.getTime() < project.buildPushDebounceMinutes * 60_000;\n if (input.trigger === 'push' && pushDebounced(initial, now())) return { outcome: 'skipped', reason: 'debounced' };\n\n const token = randomUUID();\n const lease = { id: initial.id, token, leaseMs: BUILD_START_LEASE_MS };\n const claim = await deps.projects.claimBuildStart({ ...lease, now: now() });\n if (!claim.claimed) return { outcome: 'skipped', reason: 'starting' };\n let held = true;\n const renewal = setInterval(\n () => {\n deps.projects.renewBuildStart({ ...lease, now: now() }).then(\n renewed => {\n if (!renewed) held = false;\n },\n // A failed renewal is retried on the next tick; the lease outlasts two misses.\n () => {},\n );\n },\n deps.leaseRenewMs ?? BUILD_START_LEASE_MS / 3,\n );\n renewal.unref?.();\n\n const attempted = { lastBuildAttemptedAt: now() };\n // Set once this run has reconciled an uncertain start, or builds past it.\n let resolved = false;\n const release = (changes: Parameters<EnvironmentBuildDeps['projects']['releaseBuildStart']>[0]['changes'] = {}) =>\n deps.projects.releaseBuildStart({ id: initial.id, token, changes, resolved, now: now() });\n const failed = async (error: unknown, changes: Parameters<typeof release>[0], buildEnv?: Record<string, string>) => {\n const reason = maskSandboxEnvValues(errorReason(error), buildEnv);\n await release(changes);\n deps.logger?.info('environment build failed', { factoryProjectId: initial.id, trigger: input.trigger, reason });\n return { outcome: 'failed', reason } satisfies EnvironmentBuildOutcome;\n };\n\n try {\n let project: FactoryProject;\n let environment: SessionEnvironment;\n let heads: EnvironmentHeads;\n let ctx: FactorySandboxContext;\n let buildInputs: string;\n try {\n // Read build state only once this run holds the lease, so a run that\n // finished while this one waited has already recorded its build.\n project = (await deps.projects.getById({ id: initial.id })) ?? initial;\n environment = await resolveProjectEnvironment(sourceControl.storage, project);\n if (environment.repos.length === 0) {\n await release();\n return { outcome: 'skipped', reason: 'no_environment' };\n }\n heads = await resolveEnvironmentHeads(sourceControl, project, environment);\n const built = await environmentBuildContextWithEnv(\n project,\n environment,\n heads,\n sourceControl.versionControl,\n deps.sandboxEnvs,\n );\n ctx = built.ctx;\n buildInputs = environmentBuildInputs(environment, built.buildEnvRevision);\n\n if (claim.uncertain) {\n // A run whose lease lapsed may have reached the provider before it\n // died; a build it left running is never raced by a second one. The\n // mark stays until that build is gone, since its inputs are unknown.\n if (builds.list) {\n const listed = await builds.list(ctx, environment.settings);\n const running = listed.find(build => build.status === 'pending' || build.status === 'building');\n if (running) {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: running.buildId };\n }\n resolved = true;\n } else {\n // Without history the earlier start can never be reconciled, so no\n // trigger starts another build beside it.\n await release();\n return { outcome: 'skipped', reason: 'unresolved' };\n }\n }\n\n if (project.lastBuildId) {\n const last = await builds.get(ctx, environment.settings, project.lastBuildId);\n // Two runs polling one template fight over it (each poll resubmits its\n // own definition and the provider cancels the other), so a running\n // build is never joined by a second one, whatever asked.\n if (last.status === 'pending' || last.status === 'building') {\n await release();\n return { outcome: 'skipped', reason: 'in_progress', buildId: project.lastBuildId };\n }\n // A ready build whose poll ran out or died with its host was never\n // pinned; pin it now so the skip below compares against what it built.\n let pinnedHeads = project.activeTemplateHeads;\n const lastTemplateId = last.templateId ?? project.lastBuildId;\n if (last.status === 'ready' && project.lastBuildHeads && project.activeTemplateId !== lastTemplateId) {\n const pinned = await deps.projects.pinActiveTemplate({\n id: project.id,\n buildId: project.lastBuildId,\n templateId: lastTemplateId,\n heads: project.lastBuildHeads,\n });\n if (pinned) pinnedHeads = project.lastBuildHeads;\n }\n if (\n (input.trigger === 'schedule' || input.trigger === 'push') &&\n last.status === 'ready' &&\n !headsChanged(pinnedHeads, heads) &&\n project.lastBuildInputs === buildInputs\n ) {\n await release();\n return { outcome: 'skipped', reason: 'unchanged' };\n }\n }\n } catch (error) {\n return await failed(error, attempted);\n }\n\n // A run that lost its lease while reading must not start beside its successor.\n if (!held) return { outcome: 'skipped', reason: 'starting' };\n\n if (input.trigger === 'push') {\n // Claimed only now, so a push that skipped above never closes the window.\n let claimed: boolean;\n try {\n claimed = await deps.projects.claimBuildAttempt({\n id: project.id,\n debounceMinutes: project.buildPushDebounceMinutes,\n now: now(),\n });\n } catch (error) {\n return await failed(error, {});\n }\n if (!claimed) {\n await release();\n return { outcome: 'skipped', reason: 'debounced' };\n }\n }\n\n let started: Awaited<ReturnType<typeof builds.start>>;\n try {\n started = await builds.start(ctx, environment.settings);\n } catch (error) {\n // Only a failed start clears the last build: the previous one no longer\n // describes the template this project wants.\n return await failed(\n error,\n { lastBuildId: null, lastBuildHeads: null, lastBuildInputs: null, ...attempted },\n ctx.buildEnv,\n );\n }\n\n // The provider has started the build: from here on, no error clears it.\n const log = { factoryProjectId: project.id, trigger: input.trigger, buildId: started.buildId };\n const changes = { lastBuildId: started.buildId, lastBuildHeads: heads, lastBuildInputs: buildInputs, ...attempted };\n let recorded: boolean | undefined;\n for (let attempt = 1; recorded === undefined; attempt++) {\n try {\n recorded = await release(changes);\n } catch (error) {\n if (attempt >= RECORD_ATTEMPTS) {\n // Keep the lease: it lapses once renewal stops, and the run that\n // takes it over looks for this build at the provider first.\n deps.logger?.info('environment build started but not recorded', { ...log, reason: errorReason(error) });\n return { outcome: 'failed', reason: 'not_recorded', buildId: started.buildId };\n }\n await sleep(1000 * 2 ** (attempt - 1));\n }\n }\n if (!recorded) {\n // A newer run took the lease while the provider started this build; the\n // project tracks that run's build, so this one is never polled or pinned.\n deps.logger?.info('environment build superseded', log);\n return { outcome: 'failed', reason: 'superseded', buildId: started.buildId };\n }\n try {\n deps.logger?.info('environment build started', { ...log, templateId: started.templateId });\n } catch {\n // Logging never turns a recorded build into a failure.\n }\n return {\n outcome: 'started',\n buildId: started.buildId,\n ...(started.templateId ? { templateId: started.templateId } : {}),\n heads,\n };\n } finally {\n clearInterval(renewal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAsBA,MAAa,6BAA6B;CAAC;CAAU;CAAY;AAAM;;AAsCvE,SAAgB,0BAA0B,WAA2B;CACnE,OAAO,qBAAqB;AAC9B;;;;;AAMA,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,QAAQ,QAAQ,kBAAkB,QAAQ,CAAC,CAAC,QAAQ,6CAA6C,KAAK;AAC/G;;AAGA,SAAgB,YAAY,OAAwB;CAClD,OAAO,kBAAkB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACjF;;;;;;;AAQA,SAAgB,wBACd,SACA,aACA,OACA,gBACuB;CACvB,OAAO;EACL,WAAW,0BAA0B,QAAQ,EAAE;EAC/C,WAAW,QAAQ;EACnB,aAAa,QAAQ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U,GAC/E,IAAI,QACN;EACF;EAGA,MAAM,MAAM;GAAE,kBAAkB,QAAQ;GAAI,SAAS,MAAM;GAAS,SAAS,QAAQ;EAAQ;EAC7F,MAAM,UAAU;GAAE,aAAa,QAAQ;GAAS,gBAAgB;GAAO,iBAAiB;GAAa,GAAG;EAAU;EAClH,IAAI;EACJ,KAAK,IAAI,UAAU,GAAG,aAAa,KAAA,GAAW,WAC5C,IAAI;GACF,WAAW,MAAM,QAAQ,OAAO;EAClC,SAAS,OAAO;GACd,IAAI,WAAW,iBAAiB;IAG9B,KAAK,QAAQ,KAAK,8CAA8C;KAAE,GAAG;KAAK,QAAQ,YAAY,KAAK;IAAE,CAAC;IACtG,OAAO;KAAE,SAAS;KAAU,QAAQ;KAAgB,SAAS,QAAQ;IAAQ;GAC/E;GACA,MAAM,MAAM,MAAO,MAAM,UAAU,EAAE;EACvC;EAEF,IAAI,CAAC,UAAU;GAGb,KAAK,QAAQ,KAAK,gCAAgC,GAAG;GACrD,OAAO;IAAE,SAAS;IAAU,QAAQ;IAAc,SAAS,QAAQ;GAAQ;EAC7E;EACA,IAAI;GACF,KAAK,QAAQ,KAAK,6BAA6B;IAAE,GAAG;IAAK,YAAY,QAAQ;GAAW,CAAC;EAC3F,QAAQ,CAER;EACA,OAAO;GACL,SAAS;GACT,SAAS,QAAQ;GACjB,GAAI,QAAQ,aAAa,EAAE,YAAY,QAAQ,WAAW,IAAI,CAAC;GAC/D;EACF;CACF,UAAU;EACR,cAAc,OAAO;CACvB;AACF"}
package/dist/factory.d.ts CHANGED
@@ -216,8 +216,9 @@ export interface MastraFactoryConfig {
216
216
  */
217
217
  skills?: readonly InlineSkill[];
218
218
  /**
219
- * Whether projects get the built-in Work board, stored in each project once, and the legacy
220
- * read-only Review board. Default: true.
219
+ * @deprecated Ignored, and removed in a future release. Every project gets Factory's Work board
220
+ * when it has no boards yet; one that has any keeps what it has. To run your own Work board,
221
+ * store it under the `work` key with `factory.upsertBoard(board, { projects: 'all' })`.
221
222
  */
222
223
  includeDefaultBoards?: boolean;
223
224
  /**
@@ -266,8 +267,11 @@ export declare class MastraFactory {
266
267
  /**
267
268
  * Writes a board definition into projects: each project that has no board under its key gets
268
269
  * it, and each one that has it, edited or not, has it replaced at the next revision. Use it to
269
- * push a board from code into projects; it isn't run for you, and projects created later don't
270
- * get it until you run it again. A Work or app board's key keeps that board's code behaviour,
270
+ * push a board from code into projects, at startup. With `projects: 'all'`, a project that has
271
+ * no boards yet on its first load (one created later, during onboarding) gets it too, before
272
+ * Factory's own boards; Factory adds its default Work only to a project with no boards, so that
273
+ * project gets none. This lasts for the process, so run it at every startup. A Work or app
274
+ * board's key keeps that board's code behaviour,
271
275
  * so the definition is checked as an edit is; a new key gets none (no tool, source-closed or
272
276
  * event rules). The board is validated once, as the boards API does, and each write is audited
273
277
  * as `factory.board.created` or `factory.board.updated` by `system:factory`. Refusals throw a
@@ -1 +1 @@
1
- {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AASH,OAAO,KAAK,EAAiC,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAClG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAG1D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CA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