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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (348) hide show
  1. package/README.md +67 -46
  2. package/dist/boards/board-writes.d.ts +3 -3
  3. package/dist/boards/board-writes.d.ts.map +1 -1
  4. package/dist/boards/board-writes.js +24 -20
  5. package/dist/boards/board-writes.js.map +1 -1
  6. package/dist/boards/project-boards.d.ts +20 -0
  7. package/dist/boards/project-boards.d.ts.map +1 -1
  8. package/dist/boards/project-boards.js +35 -11
  9. package/dist/boards/project-boards.js.map +1 -1
  10. package/dist/boards/registry.d.ts.map +1 -1
  11. package/dist/boards/registry.js +0 -3
  12. package/dist/boards/registry.js.map +1 -1
  13. package/dist/boards/reroute.d.ts +31 -0
  14. package/dist/boards/reroute.d.ts.map +1 -0
  15. package/dist/boards/reroute.js +71 -0
  16. package/dist/boards/reroute.js.map +1 -0
  17. package/dist/capabilities/version-control.d.ts +6 -1
  18. package/dist/capabilities/version-control.d.ts.map +1 -1
  19. package/dist/environment/build-runner.d.ts +13 -2
  20. package/dist/environment/build-runner.d.ts.map +1 -1
  21. package/dist/environment/build-runner.js +42 -0
  22. package/dist/environment/build-runner.js.map +1 -1
  23. package/dist/environment/build-schedule.js +1 -1
  24. package/dist/environment/build-schedule.js.map +1 -1
  25. package/dist/environment/build-workflow.d.ts +6 -4
  26. package/dist/environment/build-workflow.d.ts.map +1 -1
  27. package/dist/environment/build-workflow.js +70 -66
  28. package/dist/environment/build-workflow.js.map +1 -1
  29. package/dist/environment/build.d.ts +22 -7
  30. package/dist/environment/build.d.ts.map +1 -1
  31. package/dist/environment/build.js +73 -15
  32. package/dist/environment/build.js.map +1 -1
  33. package/dist/environment/heads.d.ts +1 -1
  34. package/dist/environment/heads.d.ts.map +1 -1
  35. package/dist/environment/heads.js +4 -1
  36. package/dist/environment/heads.js.map +1 -1
  37. package/dist/environment/repository-access.d.ts +15 -0
  38. package/dist/environment/repository-access.d.ts.map +1 -0
  39. package/dist/environment/repository-access.js +60 -0
  40. package/dist/environment/repository-access.js.map +1 -0
  41. package/dist/factory.d.ts +5 -2
  42. package/dist/factory.d.ts.map +1 -1
  43. package/dist/factory.js +40 -30
  44. package/dist/factory.js.map +1 -1
  45. package/dist/integrations/base.d.ts +8 -0
  46. package/dist/integrations/base.d.ts.map +1 -1
  47. package/dist/integrations/dependabot/default-rules.d.ts +38 -0
  48. package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
  49. package/dist/integrations/dependabot/default-rules.js +63 -0
  50. package/dist/integrations/dependabot/default-rules.js.map +1 -0
  51. package/dist/integrations/dependabot/rules.d.ts +42 -0
  52. package/dist/integrations/dependabot/rules.d.ts.map +1 -0
  53. package/dist/integrations/dependabot/rules.js +187 -0
  54. package/dist/integrations/dependabot/rules.js.map +1 -0
  55. package/dist/integrations/dependabot/sync.d.ts +76 -0
  56. package/dist/integrations/dependabot/sync.d.ts.map +1 -0
  57. package/dist/integrations/dependabot/sync.js +111 -0
  58. package/dist/integrations/dependabot/sync.js.map +1 -0
  59. package/dist/integrations/github/routes.d.ts.map +1 -1
  60. package/dist/integrations/github/routes.js +7 -2
  61. package/dist/integrations/github/routes.js.map +1 -1
  62. package/dist/integrations/github/sandbox-release.d.ts +12 -0
  63. package/dist/integrations/github/sandbox-release.d.ts.map +1 -1
  64. package/dist/integrations/github/sandbox-release.js +16 -1
  65. package/dist/integrations/github/sandbox-release.js.map +1 -1
  66. package/dist/integrations/github/sandbox.d.ts +12 -0
  67. package/dist/integrations/github/sandbox.d.ts.map +1 -1
  68. package/dist/integrations/github/sandbox.js +22 -1
  69. package/dist/integrations/github/sandbox.js.map +1 -1
  70. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  71. package/dist/integrations/platform/connect/routes.js +4 -0
  72. package/dist/integrations/platform/connect/routes.js.map +1 -1
  73. package/dist/integrations/platform/github/event-worker.d.ts +5 -0
  74. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  75. package/dist/integrations/platform/github/event-worker.js +33 -2
  76. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  77. package/dist/integrations/platform/github/integration.d.ts +19 -1
  78. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  79. package/dist/integrations/platform/github/integration.js +183 -105
  80. package/dist/integrations/platform/github/integration.js.map +1 -1
  81. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  82. package/dist/integrations/platform/jira/integration.js +5 -1
  83. package/dist/integrations/platform/jira/integration.js.map +1 -1
  84. package/dist/integrations/platform/vanta/integration.d.ts +33 -0
  85. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
  86. package/dist/integrations/platform/vanta/integration.js +133 -0
  87. package/dist/integrations/platform/vanta/integration.js.map +1 -0
  88. package/dist/integrations/slack/integration.d.ts.map +1 -1
  89. package/dist/integrations/slack/integration.js +7 -4
  90. package/dist/integrations/slack/integration.js.map +1 -1
  91. package/dist/integrations/vanta/default-rules.d.ts +34 -0
  92. package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
  93. package/dist/integrations/vanta/default-rules.js +61 -0
  94. package/dist/integrations/vanta/default-rules.js.map +1 -0
  95. package/dist/integrations/vanta/rules.d.ts +40 -0
  96. package/dist/integrations/vanta/rules.d.ts.map +1 -0
  97. package/dist/integrations/vanta/rules.js +208 -0
  98. package/dist/integrations/vanta/rules.js.map +1 -0
  99. package/dist/integrations/vanta/sync.d.ts +36 -0
  100. package/dist/integrations/vanta/sync.d.ts.map +1 -0
  101. package/dist/integrations/vanta/sync.js +73 -0
  102. package/dist/integrations/vanta/sync.js.map +1 -0
  103. package/dist/mcp/routes.d.ts.map +1 -1
  104. package/dist/mcp/routes.js +3 -5
  105. package/dist/mcp/routes.js.map +1 -1
  106. package/dist/routes/board-snapshot.d.ts +24 -1
  107. package/dist/routes/board-snapshot.d.ts.map +1 -1
  108. package/dist/routes/board-snapshot.js +75 -7
  109. package/dist/routes/board-snapshot.js.map +1 -1
  110. package/dist/routes/boards.d.ts +2 -3
  111. package/dist/routes/boards.d.ts.map +1 -1
  112. package/dist/routes/boards.js.map +1 -1
  113. package/dist/routes/contracts.d.ts +307 -0
  114. package/dist/routes/contracts.d.ts.map +1 -1
  115. package/dist/routes/contracts.js +253 -9
  116. package/dist/routes/contracts.js.map +1 -1
  117. package/dist/routes/intake-routes.d.ts +3 -0
  118. package/dist/routes/intake-routes.d.ts.map +1 -1
  119. package/dist/routes/intake-routes.js +44 -0
  120. package/dist/routes/intake-routes.js.map +1 -1
  121. package/dist/routes/knowledge.d.ts.map +1 -1
  122. package/dist/routes/knowledge.js +3 -2
  123. package/dist/routes/knowledge.js.map +1 -1
  124. package/dist/routes/projects.d.ts.map +1 -1
  125. package/dist/routes/projects.js +5 -0
  126. package/dist/routes/projects.js.map +1 -1
  127. package/dist/routes/sandbox-envs.d.ts +2 -0
  128. package/dist/routes/sandbox-envs.d.ts.map +1 -1
  129. package/dist/routes/sandbox-envs.js +3 -0
  130. package/dist/routes/sandbox-envs.js.map +1 -1
  131. package/dist/routes/source-control-sessions.d.ts +1 -1
  132. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  133. package/dist/routes/source-control-sessions.js +109 -3
  134. package/dist/routes/source-control-sessions.js.map +1 -1
  135. package/dist/routes/source-control-settings.d.ts +2 -0
  136. package/dist/routes/source-control-settings.d.ts.map +1 -1
  137. package/dist/routes/source-control-settings.js +5 -0
  138. package/dist/routes/source-control-settings.js.map +1 -1
  139. package/dist/routes/surface.d.ts +8 -1
  140. package/dist/routes/surface.d.ts.map +1 -1
  141. package/dist/routes/surface.js +74 -10
  142. package/dist/routes/surface.js.map +1 -1
  143. package/dist/routes/work-item-activity.d.ts +11 -0
  144. package/dist/routes/work-item-activity.d.ts.map +1 -0
  145. package/dist/routes/work-item-activity.js +25 -0
  146. package/dist/routes/work-item-activity.js.map +1 -0
  147. package/dist/routes/work-item-selection.d.ts +14 -0
  148. package/dist/routes/work-item-selection.d.ts.map +1 -0
  149. package/dist/routes/work-item-selection.js +44 -0
  150. package/dist/routes/work-item-selection.js.map +1 -0
  151. package/dist/routes/work-item-starters.d.ts +29 -0
  152. package/dist/routes/work-item-starters.d.ts.map +1 -0
  153. package/dist/routes/work-item-starters.js +152 -0
  154. package/dist/routes/work-item-starters.js.map +1 -0
  155. package/dist/routes/work-items.d.ts.map +1 -1
  156. package/dist/routes/work-items.js +239 -16
  157. package/dist/routes/work-items.js.map +1 -1
  158. package/dist/rules/dispatch-errors.d.ts +3 -0
  159. package/dist/rules/dispatch-errors.d.ts.map +1 -1
  160. package/dist/rules/dispatch-errors.js +9 -0
  161. package/dist/rules/dispatch-errors.js.map +1 -1
  162. package/dist/rules/dispatcher.d.ts +4 -1
  163. package/dist/rules/dispatcher.d.ts.map +1 -1
  164. package/dist/rules/dispatcher.js +122 -33
  165. package/dist/rules/dispatcher.js.map +1 -1
  166. package/dist/rules/index.d.ts +2 -2
  167. package/dist/rules/index.d.ts.map +1 -1
  168. package/dist/rules/index.js +2 -2
  169. package/dist/rules/processor.d.ts +2 -0
  170. package/dist/rules/processor.d.ts.map +1 -1
  171. package/dist/rules/processor.js +18 -4
  172. package/dist/rules/processor.js.map +1 -1
  173. package/dist/rules/start-coordinator.d.ts +6 -1
  174. package/dist/rules/start-coordinator.d.ts.map +1 -1
  175. package/dist/rules/start-coordinator.js +6 -2
  176. package/dist/rules/start-coordinator.js.map +1 -1
  177. package/dist/rules/transition-service.d.ts +20 -2
  178. package/dist/rules/transition-service.d.ts.map +1 -1
  179. package/dist/rules/transition-service.js +43 -20
  180. package/dist/rules/transition-service.js.map +1 -1
  181. package/dist/rules/types.d.ts +71 -3
  182. package/dist/rules/types.d.ts.map +1 -1
  183. package/dist/rules/types.js +10 -2
  184. package/dist/rules/types.js.map +1 -1
  185. package/dist/rules/validation.d.ts.map +1 -1
  186. package/dist/rules/validation.js +5 -0
  187. package/dist/rules/validation.js.map +1 -1
  188. package/dist/sandbox/context-sandboxes.d.ts +70 -0
  189. package/dist/sandbox/context-sandboxes.d.ts.map +1 -0
  190. package/dist/sandbox/context-sandboxes.js +120 -0
  191. package/dist/sandbox/context-sandboxes.js.map +1 -0
  192. package/dist/sandbox/session-retirement.d.ts +11 -4
  193. package/dist/sandbox/session-retirement.d.ts.map +1 -1
  194. package/dist/sandbox/session-retirement.js +39 -13
  195. package/dist/sandbox/session-retirement.js.map +1 -1
  196. package/dist/session/factory-session.d.ts +20 -5
  197. package/dist/session/factory-session.d.ts.map +1 -1
  198. package/dist/session/factory-session.js +20 -6
  199. package/dist/session/factory-session.js.map +1 -1
  200. package/dist/session/live-sessions.d.ts +1 -1
  201. package/dist/session/live-sessions.d.ts.map +1 -1
  202. package/dist/session/live-sessions.js +12 -2
  203. package/dist/session/live-sessions.js.map +1 -1
  204. package/dist/storage/domains/audit/actions.d.ts +1 -1
  205. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  206. package/dist/storage/domains/audit/actions.js +2 -1
  207. package/dist/storage/domains/audit/actions.js.map +1 -1
  208. package/dist/storage/domains/audit/actors.d.ts.map +1 -1
  209. package/dist/storage/domains/audit/actors.js +1 -1
  210. package/dist/storage/domains/audit/actors.js.map +1 -1
  211. package/dist/storage/domains/boards/base.d.ts +25 -5
  212. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  213. package/dist/storage/domains/boards/base.js +57 -20
  214. package/dist/storage/domains/boards/base.js.map +1 -1
  215. package/dist/storage/domains/intake/base.d.ts +1 -1
  216. package/dist/storage/domains/intake/base.js +2 -2
  217. package/dist/storage/domains/intake/base.js.map +1 -1
  218. package/dist/storage/domains/projects/base.d.ts +16 -2
  219. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  220. package/dist/storage/domains/projects/base.js +32 -5
  221. package/dist/storage/domains/projects/base.js.map +1 -1
  222. package/dist/storage/domains/work-items/base.d.ts +60 -8
  223. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  224. package/dist/storage/domains/work-items/base.js +180 -18
  225. package/dist/storage/domains/work-items/base.js.map +1 -1
  226. package/dist/storage/domains/work-items/cards.d.ts +1 -0
  227. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  228. package/dist/storage/domains/work-items/cards.js +32 -8
  229. package/dist/storage/domains/work-items/cards.js.map +1 -1
  230. package/dist/storage/domains/work-items/legacy-review.d.ts +19 -1
  231. package/dist/storage/domains/work-items/legacy-review.d.ts.map +1 -1
  232. package/dist/storage/domains/work-items/legacy-review.js +62 -3
  233. package/dist/storage/domains/work-items/legacy-review.js.map +1 -1
  234. package/dist/storage/domains/work-items/work-item-schema.d.ts +1 -0
  235. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  236. package/dist/storage/domains/work-items/work-item-schema.js +46 -18
  237. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  238. package/dist/tools/annotations.d.ts.map +1 -1
  239. package/dist/tools/annotations.js +4 -0
  240. package/dist/tools/annotations.js.map +1 -1
  241. package/dist/tools/approval-tools.d.ts +20 -0
  242. package/dist/tools/approval-tools.d.ts.map +1 -1
  243. package/dist/tools/approval-tools.js +79 -30
  244. package/dist/tools/approval-tools.js.map +1 -1
  245. package/dist/tools/audit-events-tool.d.ts +29 -0
  246. package/dist/tools/audit-events-tool.d.ts.map +1 -0
  247. package/dist/tools/audit-events-tool.js +180 -0
  248. package/dist/tools/audit-events-tool.js.map +1 -0
  249. package/dist/tools/index.d.ts +2 -1
  250. package/dist/tools/index.d.ts.map +1 -1
  251. package/dist/tools/index.js +2 -0
  252. package/dist/tools/index.js.map +1 -1
  253. package/dist/tools/messaging-tools.d.ts.map +1 -1
  254. package/dist/tools/messaging-tools.js +1 -1
  255. package/dist/tools/messaging-tools.js.map +1 -1
  256. package/dist/tools/permissions.d.ts.map +1 -1
  257. package/dist/tools/permissions.js +1 -0
  258. package/dist/tools/permissions.js.map +1 -1
  259. package/dist/tools/read-tools.d.ts +0 -2
  260. package/dist/tools/read-tools.d.ts.map +1 -1
  261. package/dist/tools/read-tools.js +2 -7
  262. package/dist/tools/read-tools.js.map +1 -1
  263. package/dist/tools/reports.d.ts +3 -0
  264. package/dist/tools/reports.d.ts.map +1 -1
  265. package/dist/tools/reports.js +3 -3
  266. package/dist/tools/reports.js.map +1 -1
  267. package/dist/tools/run-watch.d.ts +14 -2
  268. package/dist/tools/run-watch.d.ts.map +1 -1
  269. package/dist/tools/run-watch.js +24 -4
  270. package/dist/tools/run-watch.js.map +1 -1
  271. package/dist/tools/session-tools.d.ts.map +1 -1
  272. package/dist/tools/session-tools.js +17 -6
  273. package/dist/tools/session-tools.js.map +1 -1
  274. package/dist/tools/sessions-state-processor.js +1 -1
  275. package/dist/tools/sessions-state-processor.js.map +1 -1
  276. package/dist/tools/side-sessions.d.ts.map +1 -1
  277. package/dist/tools/side-sessions.js +1 -1
  278. package/dist/tools/side-sessions.js.map +1 -1
  279. package/dist/tools/work-item-tools.d.ts.map +1 -1
  280. package/dist/tools/work-item-tools.js +12 -2
  281. package/dist/tools/work-item-tools.js.map +1 -1
  282. package/dist/work-item-branch.d.ts +1 -1
  283. package/dist/work-item-branch.d.ts.map +1 -1
  284. package/dist/work-item-branch.js +2 -0
  285. package/dist/work-item-branch.js.map +1 -1
  286. package/dist/work-items/board-check.d.ts +11 -0
  287. package/dist/work-items/board-check.d.ts.map +1 -0
  288. package/dist/work-items/board-check.js +20 -0
  289. package/dist/work-items/board-check.js.map +1 -0
  290. package/dist/work-items/board-filter-options.d.ts +5 -0
  291. package/dist/work-items/board-filter-options.d.ts.map +1 -0
  292. package/dist/work-items/board-filter-options.js +27 -0
  293. package/dist/work-items/board-filter-options.js.map +1 -0
  294. package/dist/work-items/board-phases.d.ts +28 -0
  295. package/dist/work-items/board-phases.d.ts.map +1 -0
  296. package/dist/work-items/board-phases.js +165 -0
  297. package/dist/work-items/board-phases.js.map +1 -0
  298. package/dist/work-items/card-facts.d.ts +24 -0
  299. package/dist/work-items/card-facts.d.ts.map +1 -0
  300. package/dist/work-items/card-facts.js +75 -0
  301. package/dist/work-items/card-facts.js.map +1 -0
  302. package/dist/work-items/card-labels.d.ts +5 -0
  303. package/dist/work-items/card-labels.d.ts.map +1 -0
  304. package/dist/work-items/card-labels.js +13 -0
  305. package/dist/work-items/card-labels.js.map +1 -0
  306. package/dist/work-items/card-number.d.ts +10 -0
  307. package/dist/work-items/card-number.d.ts.map +1 -0
  308. package/dist/work-items/card-number.js +15 -0
  309. package/dist/work-items/card-number.js.map +1 -0
  310. package/dist/work-items/card-people.d.ts +25 -0
  311. package/dist/work-items/card-people.d.ts.map +1 -0
  312. package/dist/work-items/card-people.js +100 -0
  313. package/dist/work-items/card-people.js.map +1 -0
  314. package/dist/work-items/card-search-text.d.ts +4 -0
  315. package/dist/work-items/card-search-text.d.ts.map +1 -0
  316. package/dist/work-items/card-search-text.js +15 -0
  317. package/dist/work-items/card-search-text.js.map +1 -0
  318. package/dist/work-items/card-source-filters.d.ts +23 -0
  319. package/dist/work-items/card-source-filters.d.ts.map +1 -0
  320. package/dist/work-items/card-source-filters.js +25 -0
  321. package/dist/work-items/card-source-filters.js.map +1 -0
  322. package/dist/work-items/create-work-item.d.ts +0 -6
  323. package/dist/work-items/create-work-item.d.ts.map +1 -1
  324. package/dist/work-items/create-work-item.js +2 -7
  325. package/dist/work-items/create-work-item.js.map +1 -1
  326. package/dist/work-items/list-related-cards.d.ts +4 -0
  327. package/dist/work-items/list-related-cards.d.ts.map +1 -0
  328. package/dist/work-items/list-related-cards.js +24 -0
  329. package/dist/work-items/list-related-cards.js.map +1 -0
  330. package/dist/work-items/related-cards.d.ts +21 -0
  331. package/dist/work-items/related-cards.d.ts.map +1 -0
  332. package/dist/work-items/related-cards.js +45 -0
  333. package/dist/work-items/related-cards.js.map +1 -0
  334. package/dist/work-items/search-words.d.ts +5 -0
  335. package/dist/work-items/search-words.d.ts.map +1 -0
  336. package/dist/work-items/search-words.js +12 -0
  337. package/dist/work-items/search-words.js.map +1 -0
  338. package/dist/work-items/split-migration.d.ts.map +1 -1
  339. package/dist/work-items/split-migration.js +6 -2
  340. package/dist/work-items/split-migration.js.map +1 -1
  341. package/dist/workspace.d.ts +0 -1
  342. package/dist/workspace.d.ts.map +1 -1
  343. package/dist/workspace.js +140 -78
  344. package/dist/workspace.js.map +1 -1
  345. package/factory-skills/factory-build/SKILL.md +1 -1
  346. package/factory-skills/factory-self-review/SKILL.md +1 -1
  347. package/factory-skills/factory-triage/SKILL.md +4 -4
  348. package/package.json +17 -16
@@ -371,7 +371,7 @@ var IntakeStorage = class extends FactoryStorageDomain {
371
371
  const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);
372
372
  if (!integrationIds) return saved;
373
373
  return Object.fromEntries(integrationIds.map((integrationId) => [integrationId, saved[integrationId] ?? {
374
- enabled: true,
374
+ enabled: false,
375
375
  sourceIds: null
376
376
  }]));
377
377
  }
@@ -579,7 +579,7 @@ var IntakeStorage = class extends FactoryStorageDomain {
579
579
  if (nextSelected.length !== selected.length || nextSelected.some((sourceId, index) => sourceId !== selected[index])) {
580
580
  const config = structuredClone(configRow.config);
581
581
  config[integrationId] = {
582
- ...config[integrationId] ?? { enabled: true },
582
+ ...config[integrationId] ?? { enabled: false },
583
583
  sourceIds: nextSelected.length > 0 ? nextSelected : null
584
584
  };
585
585
  await ops.updateMany("intake_org_settings", { org_id: orgId }, {
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Org-wide intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the organization selected. The selection feeds shared boards, so\n * every member reads the same one.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport class FactoryProjectNotFoundError extends Error {\n constructor() {\n super('Factory project not found for this organization.');\n this.name = 'FactoryProjectNotFoundError';\n }\n}\n\nasync function assertFactoryProject(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<void> {\n if (!(await ops.findOne('factory_projects', { org_id: orgId, id: factoryProjectId }))) {\n throw new FactoryProjectNotFoundError();\n }\n}\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n repositoryByLinearProject?: Record<string, string>;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_org_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_org_settings_org_unique', columns: ['org_id'] }],\n};\n\n/** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */\nexport const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */\nexport function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig {\n const merged: IntakeConfig = Object.create(null);\n for (const config of configs) {\n for (const [integrationId, selection] of Object.entries(config)) {\n const current = merged[integrationId] ?? { enabled: false, sourceIds: null };\n const syncing = selection.enabled ? (selection.sourceIds ?? []) : [];\n const sourceIds = [...new Set([...(current.sourceIds ?? []), ...syncing])];\n merged[integrationId] = {\n enabled: current.enabled || selection.enabled,\n sourceIds: sourceIds.length ? sourceIds : null,\n };\n }\n }\n return merged;\n}\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n *\n * Frozen: its unique index allows one binding per source, and indexes cannot be\n * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows\n * are copied once at boot and never written again; the collection stays\n * registered so an earlier build that is rolled back to still finds them.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\n/**\n * Binds an intake source to a Factory project, one row per (source, Factory\n * project). Most integrations keep one binding per source and rebinding moves\n * it; integrations with `Intake.bindingLabelFilters` let several Factory\n * projects share a source, each taking the issues carrying its own labels.\n */\nexport const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'intake_source_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */\n labels: { type: 'json', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_subscriptions_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_subscriptions_org_integration_source_project_unique',\n columns: ['org_id', 'integration_id', 'source_id', 'factory_project_id'],\n },\n ],\n};\n\n/** One-time data migrations that have run, so none re-runs over rows users have changed since. */\nexport const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema = {\n name: 'intake_data_migrations',\n columns: {\n name: { type: 'text', primaryKey: true },\n completed_at: { type: 'timestamp' },\n },\n};\n\nconst COPY_LEGACY_BINDINGS_MIGRATION = 'copy_intake_source_bindings_to_subscriptions';\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n /** Labels whose issues this binding takes; `null` takes every issue no other binding's labels claim. */\n labels: string[] | null;\n createdAt: Date;\n}\n\n/** Another Factory project's binding that already takes some of the requested issues. */\nexport interface IntakeBindingConflict {\n factoryProjectId: string;\n /** The overlapping labels, or `null` when both bindings take all unclaimed issues. */\n labels: string[] | null;\n}\n\n/** Bindings on one source in precedence order: the oldest binding wins an issue two of them match. */\nfunction inPrecedenceOrder<T extends Pick<IntakeSourceBinding, 'createdAt' | 'factoryProjectId'>>(\n bindings: readonly T[],\n): T[] {\n return [...bindings].sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() ||\n left.factoryProjectId.localeCompare(right.factoryProjectId),\n );\n}\n\n/**\n * The slice of a shared source's issues `binding` takes, given every binding\n * on that source (`siblings` may include `binding` itself). Label bindings beat\n * the all-issues binding, and an issue carrying labels of two label bindings\n * goes to the older one.\n */\nexport function bindingLabelSlice(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n): { include: string[] | null; exclude: string[] } {\n const labelled = inPrecedenceOrder(\n siblings.filter(sibling => sibling.labels !== null && sibling.factoryProjectId !== binding.factoryProjectId),\n );\n if (binding.labels === null) {\n return { include: null, exclude: labelled.flatMap(sibling => sibling.labels ?? []) };\n }\n const older = labelled.filter(sibling => inPrecedenceOrder([sibling, binding])[0] === sibling);\n return { include: binding.labels, exclude: older.flatMap(sibling => sibling.labels ?? []) };\n}\n\n/** Whether an issue carrying `labels` falls in `binding`'s slice of its source. */\nexport function bindingTakesIssue(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n labels: readonly string[],\n): boolean {\n const carried = new Set(labels.map(normalizeIntakeLabel));\n const { include, exclude } = bindingLabelSlice(binding, siblings);\n if (exclude.some(label => carried.has(normalizeIntakeLabel(label)))) return false;\n return include === null || include.some(label => carried.has(normalizeIntakeLabel(label)));\n}\n\n/** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */\nexport function normalizeBindingLabels(labels: readonly string[]): string[] {\n const seen = new Set<string>();\n const kept: string[] = [];\n for (const label of labels) {\n const trimmed = label.trim();\n const key = normalizeIntakeLabel(trimmed);\n if (!key || seen.has(key)) continue;\n seen.add(key);\n kept.push(trimmed);\n }\n return kept;\n}\n\n/**\n * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection\n * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or\n * writes it.\n */\nexport const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema = {\n name: 'intake_label_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n integration_id: { type: 'text' },\n /** Label as the provider reports it; matched case-insensitively. */\n label: { type: 'text' },\n board: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_label_routes_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_label_routes_org_project_integration_label_unique',\n columns: ['org_id', 'factory_project_id', 'integration_id', 'label'],\n },\n ],\n};\n\n/** Labels are matched the way GitHub treats them: case-insensitively. */\nexport function normalizeIntakeLabel(label: string): string {\n return label.trim().toLowerCase();\n}\n\ntype IntakeSourceBindingRow = {\n org_id: string;\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n labels?: string[] | null;\n created_by_user_id?: string | null;\n created_at: Date;\n};\nfunction toIntakeSourceBinding(row: IntakeSourceBindingRow): IntakeSourceBinding {\n return {\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n labels: row.labels ?? null,\n createdAt: row.created_at,\n };\n}\n\n/** Overlap between a requested binding and the other Factory projects' bindings on the same source. */\nfunction bindingConflicts(\n factoryProjectId: string,\n labels: string[] | null,\n rows: readonly IntakeSourceBindingRow[],\n): IntakeBindingConflict[] {\n const requested = new Set(labels?.map(normalizeIntakeLabel));\n return rows.flatMap((row): IntakeBindingConflict[] => {\n if (row.factory_project_id === factoryProjectId) return [];\n const theirs = row.labels ?? null;\n if (labels === null || theirs === null) {\n return labels === null && theirs === null ? [{ factoryProjectId: row.factory_project_id, labels: null }] : [];\n }\n const overlap = theirs.filter(label => requested.has(normalizeIntakeLabel(label)));\n return overlap.length > 0 ? [{ factoryProjectId: row.factory_project_id, labels: overlap }] : [];\n });\n}\n\n/** Update one (source, Factory project) binding in place, keeping its age, or insert it. */\nasync function upsertBinding(\n ops: FactoryStorageOps,\n key: { org_id: string; integration_id: string; source_id: string; factory_project_id: string },\n patch: { labels: string[] | null },\n userId: string | undefined,\n): Promise<void> {\n const now = new Date();\n const updated = await ops.updateMany('intake_source_subscriptions', key, { ...patch, updated_at: now });\n if (updated > 0) return;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n ...patch,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n}\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTAKE_ORG_SETTINGS_SCHEMA,\n LEGACY_INTAKE_USER_SETTINGS_SCHEMA,\n INTAKE_SOURCE_BINDINGS_SCHEMA,\n INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,\n INTAKE_DATA_MIGRATIONS_SCHEMA,\n INTAKE_LABEL_ROUTES_SCHEMA,\n ]);\n await this.#foldLegacyUserSelections();\n await this.#copyLegacyBindings();\n }\n\n /**\n * Copy `intake_source_bindings` into `intake_source_subscriptions` as\n * all-issues bindings, once. The marker and the copy commit together, so a\n * boot racing another cannot re-copy a binding removed after the first\n * boot finished.\n */\n async #copyLegacyBindings(): Promise<void> {\n try {\n await this.storage.withTransaction(\n async ops => {\n if (await ops.findOne('intake_data_migrations', { name: COPY_LEGACY_BINDINGS_MIGRATION })) return;\n const legacyRows = await ops.findMany<IntakeSourceBindingRow & { updated_at: Date }>(\n 'intake_source_bindings',\n {},\n );\n for (const row of legacyRows) {\n const key = {\n org_id: row.org_id,\n integration_id: row.integration_id,\n source_id: row.source_id,\n factory_project_id: row.factory_project_id,\n };\n if (await ops.findOne('intake_source_subscriptions', key)) continue;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n labels: null,\n created_by_user_id: row.created_by_user_id ?? null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n });\n }\n await ops.insertOne('intake_data_migrations', {\n name: COPY_LEGACY_BINDINGS_MIGRATION,\n completed_at: new Date(),\n });\n },\n { isolationLevel: 'serializable' },\n );\n } catch (error) {\n // Postgres can report the boot that lost the race as a unique violation instead of a serialization failure.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n }\n\n async #foldLegacyUserSelections(): Promise<void> {\n const legacyRows = await this.ops.findMany<{ org_id: string; config: IntakeConfig }>('intake_settings', {});\n const byOrg = new Map<string, IntakeConfig[]>();\n for (const row of legacyRows) {\n byOrg.set(row.org_id, [...(byOrg.get(row.org_id) ?? []), row.config]);\n }\n for (const [orgId, configs] of byOrg) {\n const folded = await this.ops.findOne('intake_org_settings', { org_id: orgId });\n if (folded) continue;\n await this.#insertConfigIfAbsent(orgId, mergeIntakeSelections(configs));\n }\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_org_settings', {});\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n await this.ops.deleteMany('intake_source_subscriptions', {});\n await this.ops.deleteMany('intake_data_migrations', {});\n await this.ops.deleteMany('intake_label_routes', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n integrationIds,\n }: {\n orgId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: true, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: true, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId };\n const updated = await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n if (await this.#insertConfigIfAbsent(orgId, config)) return;\n await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n }\n\n /** Overlay `config` onto the stored selections; integrations it omits keep their stored value. */\n async mergeConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<IntakeConfig> {\n const merged: IntakeConfig = Object.assign(Object.create(null), await this.getConfig({ orgId }), config);\n await this.saveConfig({ orgId, config: merged });\n return merged;\n }\n\n async #insertConfigIfAbsent(orgId: string, config: IntakeConfig): Promise<boolean> {\n const now = new Date();\n try {\n await this.#db.insertOne('intake_org_settings', { org_id: orgId, config, created_at: now, updated_at: now });\n return true;\n } catch (error) {\n if (error instanceof UniqueViolationError) return false;\n throw error;\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration, oldest first. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * One Factory project's binding of a source, or `null` when it has none.\n * Without `factoryProjectId`, the source's oldest binding — for integrations\n * that keep one binding per source.\n */\n async getBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0] ?? null;\n }\n\n /**\n * Remove one Factory project's binding of a source, or — without\n * `factoryProjectId` — every binding of it. Returns the (oldest) removed\n * binding, or `null` when there was none.\n */\n async clearBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const where = {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n };\n return this.storage.withTransaction(\n async ops => {\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', where);\n if (rows.length === 0) return null;\n await ops.deleteMany('intake_source_subscriptions', where);\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0]!;\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Release every source a Factory project was bound to, so the others can take\n * them. Pass the transaction deleting the project, so no binding lands in between.\n */\n async clearProjectBindings(\n { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string },\n ops: FactoryStorageOps = this.#db,\n ): Promise<void> {\n await ops.deleteMany('intake_source_subscriptions', { org_id: orgId, factory_project_id: factoryProjectId });\n }\n\n /**\n * Bind a source to one Factory project, moving it away from any other: the\n * source keeps a single binding, which takes all of its issues.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n userId?: string;\n }): Promise<void> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n await this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n for (const row of rows) {\n if (row.factory_project_id === factoryProjectId) continue;\n await ops.deleteMany('intake_source_subscriptions', {\n ...source,\n factory_project_id: row.factory_project_id,\n });\n }\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: null }, userId);\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Bind a source to one Factory project alongside other Factory projects'\n * bindings of it, taking the issues carrying one of `labels` — or, with\n * `labels: null`, every issue no label binding claims. Rejected with the\n * overlapping bindings when another Factory project already takes some of\n * those labels, or already takes all unclaimed issues.\n */\n async setSharedBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n labels,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n labels: string[] | null;\n userId?: string;\n }): Promise<{ conflicts: IntakeBindingConflict[] }> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n const kept = labels === null ? null : normalizeBindingLabels(labels);\n return this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n const conflicts = bindingConflicts(factoryProjectId, kept, rows);\n if (conflicts.length > 0) return { conflicts };\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: kept }, userId);\n return { conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Atomically replace legacy provider source ids in both selection and routing state. */\n async migrateSourceIds({\n orgId,\n integrationId,\n migrations,\n }: {\n orgId: string;\n integrationId: string;\n migrations: Array<{ from: string; to: string }>;\n }): Promise<{ migrations: Array<{ from: string; to: string }>; conflicts: Array<{ from: string; to: string }> }> {\n if (migrations.length === 0) return { migrations: [], conflicts: [] };\n return this.storage.withTransaction(\n async ops => {\n const bindings = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n });\n const bindingsBySource = new Map<string, IntakeSourceBindingRow[]>();\n for (const binding of bindings) {\n bindingsBySource.set(binding.source_id, [...(bindingsBySource.get(binding.source_id) ?? []), binding]);\n }\n // Where a source's issues land: every Factory project and label slice bound to it.\n const destination = (rows: IntakeSourceBindingRow[]) =>\n rows\n .map(row => `${row.factory_project_id}\\0${JSON.stringify(row.labels ?? null)}`)\n .sort()\n .join('\\n');\n const grouped = new Map<string, Array<{ from: string; to: string }>>();\n for (const migration of migrations) {\n grouped.set(migration.to, [...(grouped.get(migration.to) ?? []), migration]);\n }\n const conflicts: Array<{ from: string; to: string }> = [];\n for (const [to, group] of grouped) {\n const candidates = [bindingsBySource.get(to), ...group.map(({ from }) => bindingsBySource.get(from))].filter(\n (rows): rows is IntakeSourceBindingRow[] => rows !== undefined,\n );\n if (new Set(candidates.map(destination)).size > 1) conflicts.push(...group);\n }\n if (conflicts.length > 0) return { migrations: [], conflicts };\n\n const now = new Date();\n for (const [to, group] of grouped) {\n const legacy = group.filter(({ from }) => bindingsBySource.has(from));\n const scope = { org_id: orgId, integration_id: integrationId };\n if (!bindingsBySource.has(to) && legacy.length > 0) {\n const [first, ...duplicates] = legacy;\n await ops.updateMany(\n 'intake_source_subscriptions',\n { ...scope, source_id: first!.from },\n { source_id: to, updated_at: now },\n );\n for (const duplicate of duplicates) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: duplicate.from });\n }\n } else {\n for (const entry of legacy) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: entry.from });\n }\n }\n }\n\n const configRow = await ops.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n if (configRow) {\n const replacements = new Map(migrations.map(({ from, to }) => [from, to] as const));\n const selected = configRow.config[integrationId]?.sourceIds ?? [];\n const nextSelected = [...new Set(selected.map(sourceId => replacements.get(sourceId) ?? sourceId))];\n if (\n nextSelected.length !== selected.length ||\n nextSelected.some((sourceId, index) => sourceId !== selected[index])\n ) {\n const config = structuredClone(configRow.config);\n config[integrationId] = {\n ...(config[integrationId] ?? { enabled: true }),\n sourceIds: nextSelected.length > 0 ? nextSelected : null,\n };\n await ops.updateMany('intake_org_settings', { org_id: orgId }, { config, updated_at: now });\n }\n }\n return { migrations, conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,8BAAb,cAAiD,MAAM;CACrD,cAAc;EACZ,MAAM,kDAAkD;EACxD,KAAK,OAAO;CACd;AACF;AAEA,eAAe,qBAAqB,KAAwB,OAAe,kBAAyC;CAClH,IAAI,CAAE,MAAM,IAAI,QAAQ,oBAAoB;EAAE,QAAQ;EAAO,IAAI;CAAiB,CAAC,GACjF,MAAM,IAAI,4BAA4B;AAE1C;AAWA,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UAAU,OAAO,cAAc,EAAE,aAAa,CAAC;IAChE,MAAM,eAAe,CAAC,GAAG,IAAI,IAAI,SAAS,KAAI,aAAY,aAAa,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAClG,IACE,aAAa,WAAW,SAAS,UACjC,aAAa,MAAM,UAAU,UAAU,aAAa,SAAS,MAAM,GACnE;KACA,MAAM,SAAS,gBAAgB,UAAU,MAAM;KAC/C,OAAO,iBAAiB;MACtB,GAAI,OAAO,kBAAkB,EAAE,SAAS,KAAK;MAC7C,WAAW,aAAa,SAAS,IAAI,eAAe;KACtD;KACA,MAAM,IAAI,WAAW,uBAAuB,EAAE,QAAQ,MAAM,GAAG;MAAE;MAAQ,YAAY;KAAI,CAAC;IAC5F;GACF;GACA,OAAO;IAAE;IAAY,WAAW,CAAC;GAAE;EACrC,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Org-wide intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the organization selected. The selection feeds shared boards, so\n * every member reads the same one.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport class FactoryProjectNotFoundError extends Error {\n constructor() {\n super('Factory project not found for this organization.');\n this.name = 'FactoryProjectNotFoundError';\n }\n}\n\nasync function assertFactoryProject(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<void> {\n if (!(await ops.findOne('factory_projects', { org_id: orgId, id: factoryProjectId }))) {\n throw new FactoryProjectNotFoundError();\n }\n}\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n repositoryByLinearProject?: Record<string, string>;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_org_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_org_settings_org_unique', columns: ['org_id'] }],\n};\n\n/** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */\nexport const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */\nexport function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig {\n const merged: IntakeConfig = Object.create(null);\n for (const config of configs) {\n for (const [integrationId, selection] of Object.entries(config)) {\n const current = merged[integrationId] ?? { enabled: false, sourceIds: null };\n const syncing = selection.enabled ? (selection.sourceIds ?? []) : [];\n const sourceIds = [...new Set([...(current.sourceIds ?? []), ...syncing])];\n merged[integrationId] = {\n enabled: current.enabled || selection.enabled,\n sourceIds: sourceIds.length ? sourceIds : null,\n };\n }\n }\n return merged;\n}\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n *\n * Frozen: its unique index allows one binding per source, and indexes cannot be\n * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows\n * are copied once at boot and never written again; the collection stays\n * registered so an earlier build that is rolled back to still finds them.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\n/**\n * Binds an intake source to a Factory project, one row per (source, Factory\n * project). Most integrations keep one binding per source and rebinding moves\n * it; integrations with `Intake.bindingLabelFilters` let several Factory\n * projects share a source, each taking the issues carrying its own labels.\n */\nexport const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'intake_source_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */\n labels: { type: 'json', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_subscriptions_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_subscriptions_org_integration_source_project_unique',\n columns: ['org_id', 'integration_id', 'source_id', 'factory_project_id'],\n },\n ],\n};\n\n/** One-time data migrations that have run, so none re-runs over rows users have changed since. */\nexport const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema = {\n name: 'intake_data_migrations',\n columns: {\n name: { type: 'text', primaryKey: true },\n completed_at: { type: 'timestamp' },\n },\n};\n\nconst COPY_LEGACY_BINDINGS_MIGRATION = 'copy_intake_source_bindings_to_subscriptions';\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n /** Labels whose issues this binding takes; `null` takes every issue no other binding's labels claim. */\n labels: string[] | null;\n createdAt: Date;\n}\n\n/** Another Factory project's binding that already takes some of the requested issues. */\nexport interface IntakeBindingConflict {\n factoryProjectId: string;\n /** The overlapping labels, or `null` when both bindings take all unclaimed issues. */\n labels: string[] | null;\n}\n\n/** Bindings on one source in precedence order: the oldest binding wins an issue two of them match. */\nfunction inPrecedenceOrder<T extends Pick<IntakeSourceBinding, 'createdAt' | 'factoryProjectId'>>(\n bindings: readonly T[],\n): T[] {\n return [...bindings].sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() ||\n left.factoryProjectId.localeCompare(right.factoryProjectId),\n );\n}\n\n/**\n * The slice of a shared source's issues `binding` takes, given every binding\n * on that source (`siblings` may include `binding` itself). Label bindings beat\n * the all-issues binding, and an issue carrying labels of two label bindings\n * goes to the older one.\n */\nexport function bindingLabelSlice(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n): { include: string[] | null; exclude: string[] } {\n const labelled = inPrecedenceOrder(\n siblings.filter(sibling => sibling.labels !== null && sibling.factoryProjectId !== binding.factoryProjectId),\n );\n if (binding.labels === null) {\n return { include: null, exclude: labelled.flatMap(sibling => sibling.labels ?? []) };\n }\n const older = labelled.filter(sibling => inPrecedenceOrder([sibling, binding])[0] === sibling);\n return { include: binding.labels, exclude: older.flatMap(sibling => sibling.labels ?? []) };\n}\n\n/** Whether an issue carrying `labels` falls in `binding`'s slice of its source. */\nexport function bindingTakesIssue(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n labels: readonly string[],\n): boolean {\n const carried = new Set(labels.map(normalizeIntakeLabel));\n const { include, exclude } = bindingLabelSlice(binding, siblings);\n if (exclude.some(label => carried.has(normalizeIntakeLabel(label)))) return false;\n return include === null || include.some(label => carried.has(normalizeIntakeLabel(label)));\n}\n\n/** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */\nexport function normalizeBindingLabels(labels: readonly string[]): string[] {\n const seen = new Set<string>();\n const kept: string[] = [];\n for (const label of labels) {\n const trimmed = label.trim();\n const key = normalizeIntakeLabel(trimmed);\n if (!key || seen.has(key)) continue;\n seen.add(key);\n kept.push(trimmed);\n }\n return kept;\n}\n\n/**\n * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection\n * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or\n * writes it.\n */\nexport const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema = {\n name: 'intake_label_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n integration_id: { type: 'text' },\n /** Label as the provider reports it; matched case-insensitively. */\n label: { type: 'text' },\n board: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_label_routes_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_label_routes_org_project_integration_label_unique',\n columns: ['org_id', 'factory_project_id', 'integration_id', 'label'],\n },\n ],\n};\n\n/** Labels are matched the way GitHub treats them: case-insensitively. */\nexport function normalizeIntakeLabel(label: string): string {\n return label.trim().toLowerCase();\n}\n\ntype IntakeSourceBindingRow = {\n org_id: string;\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n labels?: string[] | null;\n created_by_user_id?: string | null;\n created_at: Date;\n};\nfunction toIntakeSourceBinding(row: IntakeSourceBindingRow): IntakeSourceBinding {\n return {\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n labels: row.labels ?? null,\n createdAt: row.created_at,\n };\n}\n\n/** Overlap between a requested binding and the other Factory projects' bindings on the same source. */\nfunction bindingConflicts(\n factoryProjectId: string,\n labels: string[] | null,\n rows: readonly IntakeSourceBindingRow[],\n): IntakeBindingConflict[] {\n const requested = new Set(labels?.map(normalizeIntakeLabel));\n return rows.flatMap((row): IntakeBindingConflict[] => {\n if (row.factory_project_id === factoryProjectId) return [];\n const theirs = row.labels ?? null;\n if (labels === null || theirs === null) {\n return labels === null && theirs === null ? [{ factoryProjectId: row.factory_project_id, labels: null }] : [];\n }\n const overlap = theirs.filter(label => requested.has(normalizeIntakeLabel(label)));\n return overlap.length > 0 ? [{ factoryProjectId: row.factory_project_id, labels: overlap }] : [];\n });\n}\n\n/** Update one (source, Factory project) binding in place, keeping its age, or insert it. */\nasync function upsertBinding(\n ops: FactoryStorageOps,\n key: { org_id: string; integration_id: string; source_id: string; factory_project_id: string },\n patch: { labels: string[] | null },\n userId: string | undefined,\n): Promise<void> {\n const now = new Date();\n const updated = await ops.updateMany('intake_source_subscriptions', key, { ...patch, updated_at: now });\n if (updated > 0) return;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n ...patch,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n}\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTAKE_ORG_SETTINGS_SCHEMA,\n LEGACY_INTAKE_USER_SETTINGS_SCHEMA,\n INTAKE_SOURCE_BINDINGS_SCHEMA,\n INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,\n INTAKE_DATA_MIGRATIONS_SCHEMA,\n INTAKE_LABEL_ROUTES_SCHEMA,\n ]);\n await this.#foldLegacyUserSelections();\n await this.#copyLegacyBindings();\n }\n\n /**\n * Copy `intake_source_bindings` into `intake_source_subscriptions` as\n * all-issues bindings, once. The marker and the copy commit together, so a\n * boot racing another cannot re-copy a binding removed after the first\n * boot finished.\n */\n async #copyLegacyBindings(): Promise<void> {\n try {\n await this.storage.withTransaction(\n async ops => {\n if (await ops.findOne('intake_data_migrations', { name: COPY_LEGACY_BINDINGS_MIGRATION })) return;\n const legacyRows = await ops.findMany<IntakeSourceBindingRow & { updated_at: Date }>(\n 'intake_source_bindings',\n {},\n );\n for (const row of legacyRows) {\n const key = {\n org_id: row.org_id,\n integration_id: row.integration_id,\n source_id: row.source_id,\n factory_project_id: row.factory_project_id,\n };\n if (await ops.findOne('intake_source_subscriptions', key)) continue;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n labels: null,\n created_by_user_id: row.created_by_user_id ?? null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n });\n }\n await ops.insertOne('intake_data_migrations', {\n name: COPY_LEGACY_BINDINGS_MIGRATION,\n completed_at: new Date(),\n });\n },\n { isolationLevel: 'serializable' },\n );\n } catch (error) {\n // Postgres can report the boot that lost the race as a unique violation instead of a serialization failure.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n }\n\n async #foldLegacyUserSelections(): Promise<void> {\n const legacyRows = await this.ops.findMany<{ org_id: string; config: IntakeConfig }>('intake_settings', {});\n const byOrg = new Map<string, IntakeConfig[]>();\n for (const row of legacyRows) {\n byOrg.set(row.org_id, [...(byOrg.get(row.org_id) ?? []), row.config]);\n }\n for (const [orgId, configs] of byOrg) {\n const folded = await this.ops.findOne('intake_org_settings', { org_id: orgId });\n if (folded) continue;\n await this.#insertConfigIfAbsent(orgId, mergeIntakeSelections(configs));\n }\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_org_settings', {});\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n await this.ops.deleteMany('intake_source_subscriptions', {});\n await this.ops.deleteMany('intake_data_migrations', {});\n await this.ops.deleteMany('intake_label_routes', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n integrationIds,\n }: {\n orgId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: false, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: false, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId };\n const updated = await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n if (await this.#insertConfigIfAbsent(orgId, config)) return;\n await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n }\n\n /** Overlay `config` onto the stored selections; integrations it omits keep their stored value. */\n async mergeConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<IntakeConfig> {\n const merged: IntakeConfig = Object.assign(Object.create(null), await this.getConfig({ orgId }), config);\n await this.saveConfig({ orgId, config: merged });\n return merged;\n }\n\n async #insertConfigIfAbsent(orgId: string, config: IntakeConfig): Promise<boolean> {\n const now = new Date();\n try {\n await this.#db.insertOne('intake_org_settings', { org_id: orgId, config, created_at: now, updated_at: now });\n return true;\n } catch (error) {\n if (error instanceof UniqueViolationError) return false;\n throw error;\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration, oldest first. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * One Factory project's binding of a source, or `null` when it has none.\n * Without `factoryProjectId`, the source's oldest binding — for integrations\n * that keep one binding per source.\n */\n async getBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0] ?? null;\n }\n\n /**\n * Remove one Factory project's binding of a source, or — without\n * `factoryProjectId` — every binding of it. Returns the (oldest) removed\n * binding, or `null` when there was none.\n */\n async clearBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const where = {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n };\n return this.storage.withTransaction(\n async ops => {\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', where);\n if (rows.length === 0) return null;\n await ops.deleteMany('intake_source_subscriptions', where);\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0]!;\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Release every source a Factory project was bound to, so the others can take\n * them. Pass the transaction deleting the project, so no binding lands in between.\n */\n async clearProjectBindings(\n { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string },\n ops: FactoryStorageOps = this.#db,\n ): Promise<void> {\n await ops.deleteMany('intake_source_subscriptions', { org_id: orgId, factory_project_id: factoryProjectId });\n }\n\n /**\n * Bind a source to one Factory project, moving it away from any other: the\n * source keeps a single binding, which takes all of its issues.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n userId?: string;\n }): Promise<void> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n await this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n for (const row of rows) {\n if (row.factory_project_id === factoryProjectId) continue;\n await ops.deleteMany('intake_source_subscriptions', {\n ...source,\n factory_project_id: row.factory_project_id,\n });\n }\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: null }, userId);\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Bind a source to one Factory project alongside other Factory projects'\n * bindings of it, taking the issues carrying one of `labels` — or, with\n * `labels: null`, every issue no label binding claims. Rejected with the\n * overlapping bindings when another Factory project already takes some of\n * those labels, or already takes all unclaimed issues.\n */\n async setSharedBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n labels,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n labels: string[] | null;\n userId?: string;\n }): Promise<{ conflicts: IntakeBindingConflict[] }> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n const kept = labels === null ? null : normalizeBindingLabels(labels);\n return this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n const conflicts = bindingConflicts(factoryProjectId, kept, rows);\n if (conflicts.length > 0) return { conflicts };\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: kept }, userId);\n return { conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Atomically replace legacy provider source ids in both selection and routing state. */\n async migrateSourceIds({\n orgId,\n integrationId,\n migrations,\n }: {\n orgId: string;\n integrationId: string;\n migrations: Array<{ from: string; to: string }>;\n }): Promise<{ migrations: Array<{ from: string; to: string }>; conflicts: Array<{ from: string; to: string }> }> {\n if (migrations.length === 0) return { migrations: [], conflicts: [] };\n return this.storage.withTransaction(\n async ops => {\n const bindings = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n });\n const bindingsBySource = new Map<string, IntakeSourceBindingRow[]>();\n for (const binding of bindings) {\n bindingsBySource.set(binding.source_id, [...(bindingsBySource.get(binding.source_id) ?? []), binding]);\n }\n // Where a source's issues land: every Factory project and label slice bound to it.\n const destination = (rows: IntakeSourceBindingRow[]) =>\n rows\n .map(row => `${row.factory_project_id}\\0${JSON.stringify(row.labels ?? null)}`)\n .sort()\n .join('\\n');\n const grouped = new Map<string, Array<{ from: string; to: string }>>();\n for (const migration of migrations) {\n grouped.set(migration.to, [...(grouped.get(migration.to) ?? []), migration]);\n }\n const conflicts: Array<{ from: string; to: string }> = [];\n for (const [to, group] of grouped) {\n const candidates = [bindingsBySource.get(to), ...group.map(({ from }) => bindingsBySource.get(from))].filter(\n (rows): rows is IntakeSourceBindingRow[] => rows !== undefined,\n );\n if (new Set(candidates.map(destination)).size > 1) conflicts.push(...group);\n }\n if (conflicts.length > 0) return { migrations: [], conflicts };\n\n const now = new Date();\n for (const [to, group] of grouped) {\n const legacy = group.filter(({ from }) => bindingsBySource.has(from));\n const scope = { org_id: orgId, integration_id: integrationId };\n if (!bindingsBySource.has(to) && legacy.length > 0) {\n const [first, ...duplicates] = legacy;\n await ops.updateMany(\n 'intake_source_subscriptions',\n { ...scope, source_id: first!.from },\n { source_id: to, updated_at: now },\n );\n for (const duplicate of duplicates) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: duplicate.from });\n }\n } else {\n for (const entry of legacy) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: entry.from });\n }\n }\n }\n\n const configRow = await ops.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n if (configRow) {\n const replacements = new Map(migrations.map(({ from, to }) => [from, to] as const));\n const selected = configRow.config[integrationId]?.sourceIds ?? [];\n const nextSelected = [...new Set(selected.map(sourceId => replacements.get(sourceId) ?? sourceId))];\n if (\n nextSelected.length !== selected.length ||\n nextSelected.some((sourceId, index) => sourceId !== selected[index])\n ) {\n const config = structuredClone(configRow.config);\n config[integrationId] = {\n ...(config[integrationId] ?? { enabled: false }),\n sourceIds: nextSelected.length > 0 ? nextSelected : null,\n };\n await ops.updateMany('intake_org_settings', { org_id: orgId }, { config, updated_at: now });\n }\n }\n return { migrations, conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,8BAAb,cAAiD,MAAM;CACrD,cAAc;EACZ,MAAM,kDAAkD;EACxD,KAAK,OAAO;CACd;AACF;AAEA,eAAe,qBAAqB,KAAwB,OAAe,kBAAyC;CAClH,IAAI,CAAE,MAAM,IAAI,QAAQ,oBAAoB;EAAE,QAAQ;EAAO,IAAI;CAAiB,CAAC,GACjF,MAAM,IAAI,4BAA4B;AAE1C;AAWA,MAAa,wBAAsC,CAAC;AAEpD,MAAa,6BAA+C;CAC1D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAAkC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M;KAC/C,OAAO,iBAAiB;MACtB,GAAI,OAAO,kBAAkB,EAAE,SAAS,MAAM;MAC9C,WAAW,aAAa,SAAS,IAAI,eAAe;KACtD;KACA,MAAM,IAAI,WAAW,uBAAuB,EAAE,QAAQ,MAAM,GAAG;MAAE;MAAQ,YAAY;KAAI,CAAC;IAC5F;GACF;GACA,OAAO;IAAE;IAAY,WAAW,CAAC;GAAE;EACrC,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
@@ -17,6 +17,14 @@ export declare function effectiveModelScope(scope: FactoryModelScope, context: '
17
17
  * the `local` sentinel, so the prefix cannot collide.
18
18
  */
19
19
  export declare function factoryProjectSettingsUserId(factoryProjectId: string): string;
20
+ /**
21
+ * The Factory as the owner of work nobody started: the `user_id` of a phase session a
22
+ * webhook, an automatic phase or a rule opened, and the user its runs authenticate as.
23
+ * It is the settings sentinel, so such a run reads the Factory's own settings rows and,
24
+ * having no personal rows, only ever resolves the organization's model keys.
25
+ */
26
+ export declare const factoryPrincipalId: typeof factoryProjectSettingsUserId;
27
+ export declare function isFactoryPrincipalId(userId: string | null | undefined): boolean;
20
28
  export interface FactoryProject {
21
29
  id: string;
22
30
  orgId: string;
@@ -54,9 +62,12 @@ export interface FactoryProject {
54
62
  lastPushBuildAt: Date | null;
55
63
  /**
56
64
  * A run's build-start lease lapsed, so a build it may have started is not
57
- * on record. Cleared once a run reconciles it with a provider that lists builds.
65
+ * on record. Cleared once a run reconciles it with a provider that lists
66
+ * builds, or gives up on it after `UNRESOLVED_BUILD_START_TIMEOUT_MS`.
58
67
  */
59
68
  buildStartUncertain: boolean;
69
+ /** The latest moment the unrecorded build behind `buildStartUncertain` may have started. */
70
+ buildStartUncertainSince: Date | null;
60
71
  /** Whether a push to an environment repository's default branch starts a build. */
61
72
  buildOnPushEnabled: boolean;
62
73
  /** Minutes after a push-triggered attempt during which further pushes do not build. */
@@ -155,7 +166,10 @@ export declare class FactoryProjectsStorage extends FactoryStorageDomain {
155
166
  * only expires when its run died or stalled. Taking over an expired lease
156
167
  * marks the start uncertain (that run's build may have reached the provider
157
168
  * unrecorded), and the mark stays until a release resolves it; `uncertain`
158
- * reports it. Only the claim is transactional; provider calls run outside it.
169
+ * reports it. The mark's `build_start_uncertain_since` is the lapsed lease's
170
+ * expiry, the latest that run could have started a build; a mark written
171
+ * before that column existed is dated by the first claim that reads it.
172
+ * Only the claim is transactional; provider calls run outside it.
159
173
  */
160
174
  claimBuildStart({ id, token, leaseMs, now, }: {
161
175
  id: string;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/projects/base.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAIhF,eAAO,MAAM,mCAAmC,KAAK,CAAC;AACtD,eAAO,MAAM,oBAAoB,YAAI,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAU,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AACtE,iGAAiG;AACjG,MAAM,MAAM,mBAAmB,GAAG,OAAO,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;AAEvE;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,KAAK,GAAG,SAAS,GAAG,mBAAmB,CAG7G;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAA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AI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAUnB;IAED;;;;;;OAMG;IACG,iBAAiB,CAAC,EACtB,EAAE,EACF,KAAK,EACL,OAAY,EACZ,QAAgB,EAChB,GAAgB,GACjB,EAAE;QACD,EAAE,EAAE,MAAM,CAAC;QACX,KAAK,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,OAAO,CAAC,EAAE,IAAI,CACZ,yBAAyB,EACzB,aAAa,GAAG,gBAAgB,GAAG,iBAAiB,GAAG,sBAAsB,CAC9E,CAAC;QACF,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAqBnB;IAED;;;;;;OAMG;IACG,iBAAiB,CAAC,EACtB,EAAE,EACF,OAAO,EACP,UAAU,EACV,KAAK,EACL,GAAgB,GACjB,EAAE;QACD,EAAE,EAAE,MAAM,CAAC;QACX,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9B,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAUnB;IAED,2GAA2G;IACrG,MAAM,CACV,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,EAC5C,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GAClD,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAWhC;CACF"}
@@ -24,6 +24,16 @@ function effectiveModelScope(scope, context) {
24
24
  function factoryProjectSettingsUserId(factoryProjectId) {
25
25
  return `factory-project:${factoryProjectId}`;
26
26
  }
27
+ /**
28
+ * The Factory as the owner of work nobody started: the `user_id` of a phase session a
29
+ * webhook, an automatic phase or a rule opened, and the user its runs authenticate as.
30
+ * It is the settings sentinel, so such a run reads the Factory's own settings rows and,
31
+ * having no personal rows, only ever resolves the organization's model keys.
32
+ */
33
+ const factoryPrincipalId = factoryProjectSettingsUserId;
34
+ function isFactoryPrincipalId(userId) {
35
+ return userId?.startsWith("factory-project:") === true;
36
+ }
27
37
  const FACTORY_PROJECTS_SCHEMA = {
28
38
  name: "factory_projects",
29
39
  columns: {
@@ -103,6 +113,10 @@ const FACTORY_PROJECTS_SCHEMA = {
103
113
  type: "boolean",
104
114
  default: false
105
115
  },
116
+ build_start_uncertain_since: {
117
+ type: "timestamp",
118
+ nullable: true
119
+ },
106
120
  build_start_claim: {
107
121
  type: "text",
108
122
  nullable: true
@@ -161,6 +175,7 @@ function toFactoryProject(row) {
161
175
  lastBuildAttemptedAt: row.last_build_attempted_at ?? null,
162
176
  lastPushBuildAt: row.last_push_build_at ?? null,
163
177
  buildStartUncertain: row.build_start_uncertain ?? false,
178
+ buildStartUncertainSince: row.build_start_uncertain_since ?? null,
164
179
  buildOnPushEnabled: row.build_on_push_enabled ?? false,
165
180
  buildPushDebounceMinutes: row.build_push_debounce_minutes ?? 10,
166
181
  createdAt: row.created_at,
@@ -285,7 +300,10 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
285
300
  * only expires when its run died or stalled. Taking over an expired lease
286
301
  * marks the start uncertain (that run's build may have reached the provider
287
302
  * unrecorded), and the mark stays until a release resolves it; `uncertain`
288
- * reports it. Only the claim is transactional; provider calls run outside it.
303
+ * reports it. The mark's `build_start_uncertain_since` is the lapsed lease's
304
+ * expiry, the latest that run could have started a build; a mark written
305
+ * before that column existed is dated by the first claim that reads it.
306
+ * Only the claim is transactional; provider calls run outside it.
289
307
  */
290
308
  async claimBuildStart({ id, token, leaseMs, now = /* @__PURE__ */ new Date() }) {
291
309
  const result = {
@@ -296,11 +314,17 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
296
314
  const expiresAt = current.build_start_claim_expires_at;
297
315
  if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;
298
316
  result.claimed = true;
299
- result.uncertain = Boolean(current.build_start_claim) || current.build_start_uncertain === true;
317
+ const lapsedAt = current.build_start_claim ? expiresAt ?? now : null;
318
+ const markedAt = current.build_start_uncertain === true ? current.build_start_uncertain_since ?? now : null;
319
+ result.uncertain = lapsedAt !== null || markedAt !== null;
320
+ const since = lapsedAt && markedAt ? lapsedAt.getTime() > markedAt.getTime() ? lapsedAt : markedAt : lapsedAt ?? markedAt;
300
321
  return {
301
322
  build_start_claim: token,
302
323
  build_start_claim_expires_at: new Date(now.getTime() + leaseMs),
303
- ...result.uncertain ? { build_start_uncertain: true } : {},
324
+ ...since ? {
325
+ build_start_uncertain: true,
326
+ build_start_uncertain_since: since
327
+ } : {},
304
328
  updated_at: now
305
329
  };
306
330
  }));
@@ -339,7 +363,10 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
339
363
  ...changes.lastBuildHeads !== void 0 ? { last_build_heads: changes.lastBuildHeads } : {},
340
364
  ...changes.lastBuildInputs !== void 0 ? { last_build_inputs: changes.lastBuildInputs } : {},
341
365
  ...changes.lastBuildAttemptedAt !== void 0 ? { last_build_attempted_at: changes.lastBuildAttemptedAt } : {},
342
- ...resolved ? { build_start_uncertain: false } : {},
366
+ ...resolved ? {
367
+ build_start_uncertain: false,
368
+ build_start_uncertain_since: null
369
+ } : {},
343
370
  build_start_claim: null,
344
371
  build_start_claim_expires_at: null,
345
372
  updated_at: now
@@ -384,6 +411,6 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
384
411
  }, { isolationLevel: "serializable" });
385
412
  }
386
413
  };
387
- export { DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES, FACTORY_MODEL_SCOPES, FACTORY_PROJECTS_SCHEMA, FactoryProjectsStorage, effectiveModelScope, factoryProjectSettingsUserId };
414
+ export { DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES, FACTORY_MODEL_SCOPES, FACTORY_PROJECTS_SCHEMA, FactoryProjectsStorage, effectiveModelScope, factoryPrincipalId, factoryProjectSettingsUserId, isFactoryPrincipalId };
388
415
 
389
416
  //# sourceMappingURL=base.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/projects/base.ts"],"sourcesContent":["import { isThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { FactoryStorageDomain } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_THINKING_LEVEL } from '../../../default-thinking-level.js';\n\nexport const DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES = 10;\nexport const FACTORY_MODEL_SCOPES = ['factory', 'user', 'hybrid'] as const;\nexport type FactoryModelScope = (typeof FACTORY_MODEL_SCOPES)[number];\n/** The single credential scope one session or run resolves from; `hybrid` is never effective. */\nexport type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;\n\n/**\n * Resolve the scope one context runs under. `hybrid` splits by context: work-item runs use the\n * Factory's model and credentials, interactive sessions use the session owner's.\n */\nexport function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope {\n if (scope === 'hybrid') return context === 'run' ? 'factory' : 'user';\n return scope;\n}\n\n/**\n * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the\n * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or\n * the `local` sentinel, so the prefix cannot collide.\n */\nexport function factoryProjectSettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\nexport interface FactoryProject {\n id: string;\n orgId: string;\n createdBy: string;\n name: string;\n description: string | null;\n /** Default model for sessions/runs started under this Factory (null = harness default). */\n defaultModelId: string | null;\n /**\n * Whose model and credentials sessions and runs use: the Factory's, the session owner's, or\n * `hybrid` (owner's for interactive sessions, the Factory's for work-item runs).\n */\n modelScope: FactoryModelScope;\n /** Thinking level for this Factory's sessions and runs that have not picked their own. */\n defaultThinkingLevel: ThinkingLevelSetting;\n /** Workspace root in the sandbox; linked repositories are checked out beneath it. */\n sandboxWorkingDirectory: string | null;\n /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */\n sandboxSettings: Record<string, unknown> | null;\n /** Command run once in the workspace root after every repository's own setup. */\n workspaceSetupCommand: string | null;\n /** Template id of the environment's current build, written by the build path. */\n activeTemplateId: string | null;\n /** Repository slug → commit the active template was built at. */\n activeTemplateHeads: Record<string, string> | null;\n /** Provider build id of the most recent build attempt; its status is read live from the provider. */\n lastBuildId: string | null;\n /** Repository slug → commit the most recent build attempt pinned, so its status can be read back. */\n lastBuildHeads: Record<string, string> | null;\n /** Fingerprint of the settings, repositories and setup commands the most recent build attempt used. */\n lastBuildInputs: string | null;\n /** When the most recent build attempt started, whatever triggered it. */\n lastBuildAttemptedAt: Date | null;\n /** When a push last started a build: the leading edge of the push debounce window. */\n lastPushBuildAt: Date | null;\n /**\n * A run's build-start lease lapsed, so a build it may have started is not\n * on record. Cleared once a run reconciles it with a provider that lists builds.\n */\n buildStartUncertain: boolean;\n /** Whether a push to an environment repository's default branch starts a build. */\n buildOnPushEnabled: boolean;\n /** Minutes after a push-triggered attempt during which further pushes do not build. */\n buildPushDebounceMinutes: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Project switches the board replaced, as last stored. */\nexport interface RetiredAutomationSettings {\n /** Runs started without a person on every phase. */\n autoRunEnabled: boolean;\n /** Cards on a board with a self-review phase went through it. */\n selfReviewEnabled: boolean;\n}\n\nexport interface CreateFactoryProjectInput {\n name: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n}\n\nexport interface UpdateFactoryProjectInput {\n name?: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n defaultThinkingLevel?: ThinkingLevelSetting;\n sandboxWorkingDirectory?: string | null;\n sandboxSettings?: Record<string, unknown> | null;\n workspaceSetupCommand?: string | null;\n activeTemplateId?: string | null;\n activeTemplateHeads?: Record<string, string> | null;\n lastBuildId?: string | null;\n lastBuildHeads?: Record<string, string> | null;\n lastBuildInputs?: string | null;\n lastBuildAttemptedAt?: Date | null;\n buildOnPushEnabled?: boolean;\n buildPushDebounceMinutes?: number;\n}\n\nexport const FACTORY_PROJECTS_SCHEMA: CollectionSchema = {\n name: 'factory_projects',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n default_model_id: { type: 'text', nullable: true },\n model_scope: { type: 'text', default: 'hybrid' },\n default_thinking_level: { type: 'text', default: DEFAULT_THINKING_LEVEL },\n // Deprecated: no longer read or written. Kept so existing databases need no\n // migration. Old rows may still hold `true`, so never read it to bring Slack\n // work items back. Drop it in a later migration.\n slack_work_items_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A phase starts on its own with `autoStart`; the\n // `auto-run-switch-v1` board migration reads it once to carry it into the project's boards.\n auto_run_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer read or written. Plans are approved per board (`exitTool.autoApprove`).\n auto_approve_plans: { type: 'boolean', default: false },\n sandbox_working_directory: { type: 'text', nullable: true },\n sandbox_settings: { type: 'json', nullable: true },\n workspace_setup_command: { type: 'text', nullable: true },\n active_template_id: { type: 'text', nullable: true },\n active_template_heads: { type: 'json', nullable: true },\n last_build_id: { type: 'text', nullable: true },\n last_build_heads: { type: 'json', nullable: true },\n last_build_inputs: { type: 'text', nullable: true },\n last_build_attempted_at: { type: 'timestamp', nullable: true },\n last_push_build_at: { type: 'timestamp', nullable: true },\n build_start_uncertain: { type: 'boolean', default: false },\n build_start_claim: { type: 'text', nullable: true },\n build_start_claim_expires_at: { type: 'timestamp', nullable: true },\n build_on_push_enabled: { type: 'boolean', default: false },\n build_push_debounce_minutes: { type: 'integer', default: DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES },\n // Retired project switch: no longer read or written. The review skill decides whether to publish its test check.\n review_test_checks_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A board self-reviews when it has a self-review\n // phase; the `self-review-switch-v1` board migration reads it once to carry it into its boards.\n self_review_enabled: { type: 'boolean', default: false },\n /** Set once the source-control domain has backfilled repository positions and environment membership. */\n environment_backfilled_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_projects_org_updated_at_idx', columns: ['org_id', 'updated_at'] }],\n};\n\ninterface FactoryProjectDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n name: string;\n description: string | null;\n default_model_id: string | null;\n model_scope: string;\n default_thinking_level: string | null;\n auto_run_enabled: boolean;\n auto_approve_plans: boolean;\n sandbox_working_directory: string | null;\n sandbox_settings: Record<string, unknown> | null;\n workspace_setup_command: string | null;\n active_template_id: string | null;\n active_template_heads: Record<string, string> | null;\n last_build_id: string | null;\n last_build_heads: Record<string, string> | null;\n last_build_inputs: string | null;\n last_build_attempted_at: Date | null;\n last_push_build_at: Date | null;\n build_start_uncertain: boolean | null;\n build_start_claim: string | null;\n build_start_claim_expires_at: Date | null;\n build_on_push_enabled: boolean | null;\n build_push_debounce_minutes: number | null;\n self_review_enabled: boolean | null;\n environment_backfilled_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toFactoryProject(row: FactoryProjectDbRow): FactoryProject {\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n name: row.name,\n description: row.description,\n defaultModelId: row.default_model_id,\n modelScope: row.model_scope === 'factory' || row.model_scope === 'user' ? row.model_scope : 'hybrid',\n defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level)\n ? row.default_thinking_level\n : DEFAULT_THINKING_LEVEL,\n sandboxWorkingDirectory: row.sandbox_working_directory ?? null,\n sandboxSettings: row.sandbox_settings ?? null,\n workspaceSetupCommand: row.workspace_setup_command ?? null,\n activeTemplateId: row.active_template_id ?? null,\n activeTemplateHeads: row.active_template_heads ?? null,\n lastBuildId: row.last_build_id ?? null,\n lastBuildHeads: row.last_build_heads ?? null,\n lastBuildInputs: row.last_build_inputs ?? null,\n lastBuildAttemptedAt: row.last_build_attempted_at ?? null,\n lastPushBuildAt: row.last_push_build_at ?? null,\n buildStartUncertain: row.build_start_uncertain ?? false,\n buildOnPushEnabled: row.build_on_push_enabled ?? false,\n buildPushDebounceMinutes: row.build_push_debounce_minutes ?? DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class FactoryProjectsStorage extends FactoryStorageDomain {\n constructor() {\n super('projects');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([FACTORY_PROJECTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('factory_projects', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async create({\n orgId,\n userId,\n input,\n }: {\n orgId: string;\n userId: string;\n input: CreateFactoryProjectInput;\n }): Promise<FactoryProject> {\n const now = new Date();\n const row = await this.#db.insertOne<FactoryProjectDbRow>('factory_projects', {\n org_id: orgId,\n created_by: userId,\n name: input.name,\n description: input.description ?? null,\n default_model_id: input.defaultModelId ?? null,\n model_scope: input.modelScope ?? 'hybrid',\n created_at: now,\n updated_at: now,\n });\n return toFactoryProject(row);\n }\n\n async list({ orgId }: { orgId: string }): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n { org_id: orgId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async listAll(): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n {},\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * The retired automation switches as the project last stored them, read only by the one-time\n * board migrations that carry them into its boards. Null when the project doesn't exist.\n */\n async retiredAutomationSettings(\n { orgId, id }: { orgId: string; id: string },\n /** A transaction's ops, to read it inside that transaction. */\n ops: FactoryStorageOps = this.#db,\n ): Promise<RetiredAutomationSettings | null> {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n return { autoRunEnabled: Boolean(row.auto_run_enabled), selfReviewEnabled: Boolean(row.self_review_enabled) };\n }\n\n async getById({ id }: { id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { id });\n return row ? toFactoryProject(row) : null;\n }\n\n async update({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n /** A function input runs in a transaction; writes through its `ops` commit or roll back with the project. */\n input:\n | UpdateFactoryProjectInput\n | ((current: FactoryProject, ops: FactoryStorageOps) => Promise<UpdateFactoryProjectInput | null>);\n }): Promise<FactoryProject | null> {\n const update = (ops: FactoryStorageOps) =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id }, async current => {\n const changes = typeof input === 'function' ? await input(toFactoryProject(current), ops) : input;\n if (changes === null) return null;\n return {\n ...(changes.name !== undefined ? { name: changes.name } : {}),\n ...(changes.description !== undefined ? { description: changes.description } : {}),\n ...(changes.defaultModelId !== undefined ? { default_model_id: changes.defaultModelId } : {}),\n ...(changes.modelScope !== undefined ? { model_scope: changes.modelScope } : {}),\n ...(changes.defaultThinkingLevel !== undefined\n ? { default_thinking_level: changes.defaultThinkingLevel }\n : {}),\n ...(changes.sandboxWorkingDirectory !== undefined\n ? { sandbox_working_directory: changes.sandboxWorkingDirectory }\n : {}),\n ...(changes.sandboxSettings !== undefined ? { sandbox_settings: changes.sandboxSettings } : {}),\n ...(changes.workspaceSetupCommand !== undefined\n ? { workspace_setup_command: changes.workspaceSetupCommand }\n : {}),\n ...(changes.activeTemplateId !== undefined ? { active_template_id: changes.activeTemplateId } : {}),\n ...(changes.activeTemplateHeads !== undefined ? { active_template_heads: changes.activeTemplateHeads } : {}),\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(changes.buildOnPushEnabled !== undefined ? { build_on_push_enabled: changes.buildOnPushEnabled } : {}),\n ...(changes.buildPushDebounceMinutes !== undefined\n ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes }\n : {}),\n updated_at: new Date(),\n };\n });\n // LibSQL's standalone updateAtomic only serializes one client; a transaction\n // also protects a read-dependent update against other database connections.\n const row = typeof input === 'function' ? await this.storage.withTransaction(update) : await update(this.#db);\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * Leading-edge debounce for push-triggered builds: stamps\n * `last_push_build_at = now` and resolves true when no push started a build\n * within the last `debounceMinutes`, else writes nothing and resolves\n * false. Taken right before the provider start, so a push that skips\n * (another run starting, a build in progress) never closes the window. The read and the write run in one transaction, so two concurrent\n * webhooks never both win, even on different database connections.\n */\n async claimBuildAttempt({\n id,\n debounceMinutes,\n now = new Date(),\n }: {\n id: string;\n debounceMinutes: number;\n now?: Date;\n }): Promise<boolean> {\n let claimed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const last = current.last_push_build_at;\n if (last && now.getTime() - last.getTime() < debounceMinutes * 60_000) return null;\n claimed = true;\n return { last_push_build_at: now, updated_at: now };\n }),\n );\n return claimed;\n }\n\n /**\n * Takes the project's build-start lease for `token`. Every trigger (manual,\n * schedule, push) takes it before reading build state and holds it through\n * `builds.start` and recording the result, so two runs never both start a\n * build. `claimed` is false while another run holds an unexpired lease. The\n * holder renews the lease while it works (`renewBuildStart`), so a lease\n * only expires when its run died or stalled. Taking over an expired lease\n * marks the start uncertain (that run's build may have reached the provider\n * unrecorded), and the mark stays until a release resolves it; `uncertain`\n * reports it. Only the claim is transactional; provider calls run outside it.\n */\n async claimBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<{ claimed: boolean; uncertain: boolean }> {\n const result = { claimed: false, uncertain: false };\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const expiresAt = current.build_start_claim_expires_at;\n if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;\n result.claimed = true;\n result.uncertain = Boolean(current.build_start_claim) || current.build_start_uncertain === true;\n return {\n build_start_claim: token,\n build_start_claim_expires_at: new Date(now.getTime() + leaseMs),\n ...(result.uncertain ? { build_start_uncertain: true } : {}),\n updated_at: now,\n };\n }),\n );\n return result;\n }\n\n /**\n * Extends the build-start lease held by `token` to `now + leaseMs`. Resolves\n * false, writing nothing, when `token` no longer holds it.\n */\n async renewBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<boolean> {\n let renewed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n renewed = true;\n return { build_start_claim_expires_at: new Date(now.getTime() + leaseMs), updated_at: now };\n }),\n );\n return renewed;\n }\n\n /**\n * Releases the build-start lease taken with `token` and writes `changes` in\n * the same transaction, but only while `token` still holds the lease. A run\n * whose lease expired and was taken by a newer run writes nothing, so it\n * never clears or overwrites that run's build. `resolved` clears an\n * uncertain start. Resolves false when skipped.\n */\n async releaseBuildStart({\n id,\n token,\n changes = {},\n resolved = false,\n now = new Date(),\n }: {\n id: string;\n token: string;\n resolved?: boolean;\n changes?: Pick<\n UpdateFactoryProjectInput,\n 'lastBuildId' | 'lastBuildHeads' | 'lastBuildInputs' | 'lastBuildAttemptedAt'\n >;\n now?: Date;\n }): Promise<boolean> {\n let released = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n released = true;\n return {\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(resolved ? { build_start_uncertain: false } : {}),\n build_start_claim: null,\n build_start_claim_expires_at: null,\n updated_at: now,\n };\n }),\n );\n return released;\n }\n\n /**\n * Pins the active template to a finished build, but only while that build is\n * still the project's last one. Overlapping runs (Build now during a push\n * build) can finish out of order; the write and the `last_build_id` check\n * run in one transaction so a stale run never overwrites a newer build's\n * pin. Resolves false when the pin was skipped.\n */\n async pinActiveTemplate({\n id,\n buildId,\n templateId,\n heads,\n now = new Date(),\n }: {\n id: string;\n buildId: string;\n templateId: string;\n heads: Record<string, string>;\n now?: Date;\n }): Promise<boolean> {\n let pinned = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.last_build_id !== buildId) return null;\n pinned = true;\n return { active_template_id: templateId, active_template_heads: heads, updated_at: now };\n }),\n );\n return pinned;\n }\n\n /** `release` runs in the deleting transaction, so nothing can be routed to the project between the two. */\n async delete(\n { orgId, id }: { orgId: string; id: string },\n release?: (ops: FactoryStorageOps) => Promise<void>,\n ): Promise<FactoryProject | null> {\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n await release?.(ops);\n await ops.deleteMany('factory_projects', { org_id: orgId, id });\n return toFactoryProject(row);\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;AAOA,MAAa,sCAAsC;AACnD,MAAa,uBAAuB;CAAC;CAAW;CAAQ;AAAQ;;;;;AAShE,SAAgB,oBAAoB,OAA0B,SAAiD;CAC7G,IAAI,UAAU,UAAU,OAAO,YAAY,QAAQ,YAAY;CAC/D,OAAO;AACT;;;;;;AAOA,SAAgB,6BAA6B,kBAAkC;CAC7E,OAAO,mBAAmB;AAC5B;AAoFA,MAAa,0BAA4C;CACvD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,OAAO;EAC3B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,kBAAkB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACjD,aAAa;GAAE,MAAM;GAAQ,SAAS;EAAS;EAC/C,wBAAwB;GAAE,MAAM;GAAQ,SAAS;EAAuB;EAIxE,0BAA0B;GAAE,MAAM;GAAW,SAAS;EAAM;EAG5D,kBAAkB;GAAE,MAAM;GAAW,SAAS;EAAM;EAEpD,oBAAoB;GAAE,MAAM;GAAW,SAAS;EAAM;EACtD,2BAA2B;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1D,kBAAkB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACjD,yBAAyB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxD,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACnD,uBAAuB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACtD,eAAe;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC9C,kBAAkB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACjD,mBA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IAAI,CAAC;IAClF,GAAI,QAAQ,mBAAmB,KAAA,IAAY,EAAE,kBAAkB,QAAQ,eAAe,IAAI,CAAC;IAC3F,GAAI,QAAQ,oBAAoB,KAAA,IAAY,EAAE,mBAAmB,QAAQ,gBAAgB,IAAI,CAAC;IAC9F,GAAI,QAAQ,yBAAyB,KAAA,IACjC,EAAE,yBAAyB,QAAQ,qBAAqB,IACxD,CAAC;IACL,GAAI,WAAW,EAAE,uBAAuB,MAAM,IAAI,CAAC;IACnD,mBAAmB;IACnB,8BAA8B;IAC9B,YAAY;GACd;EACF,CAAC,CACH;EACA,OAAO;CACT;;;;;;;;CASA,MAAM,kBAAkB,EACtB,IACA,SACA,YACA,OACA,sBAAM,IAAI,KAAK,KAOI;EACnB,IAAI,SAAS;EACb,MAAM,KAAK,QAAQ,iBAAgB,QACjC,IAAI,aAAkC,oBAAoB,EAAE,GAAG,IAAG,YAAW;GAC3E,IAAI,QAAQ,kBAAkB,SAAS,OAAO;GAC9C,SAAS;GACT,OAAO;IAAE,oBAAoB;IAAY,uBAAuB;IAAO,YAAY;GAAI;EACzF,CAAC,CACH;EACA,OAAO;CACT;;CAGA,MAAM,OACJ,EAAE,OAAO,MACT,SACgC;EAChC,OAAO,KAAK,QAAQ,gBAClB,OAAM,QAAO;GACX,MAAM,MAAM,MAAM,IAAI,QAA6B,oBAAoB;IAAE,QAAQ;IAAO;GAAG,CAAC;GAC5F,IAAI,CAAC,KAAK,OAAO;GACjB,MAAM,UAAU,GAAG;GACnB,MAAM,IAAI,WAAW,oBAAoB;IAAE,QAAQ;IAAO;GAAG,CAAC;GAC9D,OAAO,iBAAiB,GAAG;EAC7B,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/projects/base.ts"],"sourcesContent":["import { isThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { FactoryStorageDomain } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_THINKING_LEVEL } from '../../../default-thinking-level.js';\n\nexport const DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES = 10;\nexport const FACTORY_MODEL_SCOPES = ['factory', 'user', 'hybrid'] as const;\nexport type FactoryModelScope = (typeof FACTORY_MODEL_SCOPES)[number];\n/** The single credential scope one session or run resolves from; `hybrid` is never effective. */\nexport type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;\n\n/**\n * Resolve the scope one context runs under. `hybrid` splits by context: work-item runs use the\n * Factory's model and credentials, interactive sessions use the session owner's.\n */\nexport function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope {\n if (scope === 'hybrid') return context === 'run' ? 'factory' : 'user';\n return scope;\n}\n\n/**\n * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the\n * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or\n * the `local` sentinel, so the prefix cannot collide.\n */\nexport function factoryProjectSettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\n/**\n * The Factory as the owner of work nobody started: the `user_id` of a phase session a\n * webhook, an automatic phase or a rule opened, and the user its runs authenticate as.\n * It is the settings sentinel, so such a run reads the Factory's own settings rows and,\n * having no personal rows, only ever resolves the organization's model keys.\n */\nexport const factoryPrincipalId = factoryProjectSettingsUserId;\n\nexport function isFactoryPrincipalId(userId: string | null | undefined): boolean {\n return userId?.startsWith('factory-project:') === true;\n}\n\nexport interface FactoryProject {\n id: string;\n orgId: string;\n createdBy: string;\n name: string;\n description: string | null;\n /** Default model for sessions/runs started under this Factory (null = harness default). */\n defaultModelId: string | null;\n /**\n * Whose model and credentials sessions and runs use: the Factory's, the session owner's, or\n * `hybrid` (owner's for interactive sessions, the Factory's for work-item runs).\n */\n modelScope: FactoryModelScope;\n /** Thinking level for this Factory's sessions and runs that have not picked their own. */\n defaultThinkingLevel: ThinkingLevelSetting;\n /** Workspace root in the sandbox; linked repositories are checked out beneath it. */\n sandboxWorkingDirectory: string | null;\n /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */\n sandboxSettings: Record<string, unknown> | null;\n /** Command run once in the workspace root after every repository's own setup. */\n workspaceSetupCommand: string | null;\n /** Template id of the environment's current build, written by the build path. */\n activeTemplateId: string | null;\n /** Repository slug → commit the active template was built at. */\n activeTemplateHeads: Record<string, string> | null;\n /** Provider build id of the most recent build attempt; its status is read live from the provider. */\n lastBuildId: string | null;\n /** Repository slug → commit the most recent build attempt pinned, so its status can be read back. */\n lastBuildHeads: Record<string, string> | null;\n /** Fingerprint of the settings, repositories and setup commands the most recent build attempt used. */\n lastBuildInputs: string | null;\n /** When the most recent build attempt started, whatever triggered it. */\n lastBuildAttemptedAt: Date | null;\n /** When a push last started a build: the leading edge of the push debounce window. */\n lastPushBuildAt: Date | null;\n /**\n * A run's build-start lease lapsed, so a build it may have started is not\n * on record. Cleared once a run reconciles it with a provider that lists\n * builds, or gives up on it after `UNRESOLVED_BUILD_START_TIMEOUT_MS`.\n */\n buildStartUncertain: boolean;\n /** The latest moment the unrecorded build behind `buildStartUncertain` may have started. */\n buildStartUncertainSince: Date | null;\n /** Whether a push to an environment repository's default branch starts a build. */\n buildOnPushEnabled: boolean;\n /** Minutes after a push-triggered attempt during which further pushes do not build. */\n buildPushDebounceMinutes: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Project switches the board replaced, as last stored. */\nexport interface RetiredAutomationSettings {\n /** Runs started without a person on every phase. */\n autoRunEnabled: boolean;\n /** Cards on a board with a self-review phase went through it. */\n selfReviewEnabled: boolean;\n}\n\nexport interface CreateFactoryProjectInput {\n name: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n}\n\nexport interface UpdateFactoryProjectInput {\n name?: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n defaultThinkingLevel?: ThinkingLevelSetting;\n sandboxWorkingDirectory?: string | null;\n sandboxSettings?: Record<string, unknown> | null;\n workspaceSetupCommand?: string | null;\n activeTemplateId?: string | null;\n activeTemplateHeads?: Record<string, string> | null;\n lastBuildId?: string | null;\n lastBuildHeads?: Record<string, string> | null;\n lastBuildInputs?: string | null;\n lastBuildAttemptedAt?: Date | null;\n buildOnPushEnabled?: boolean;\n buildPushDebounceMinutes?: number;\n}\n\nexport const FACTORY_PROJECTS_SCHEMA: CollectionSchema = {\n name: 'factory_projects',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n default_model_id: { type: 'text', nullable: true },\n model_scope: { type: 'text', default: 'hybrid' },\n default_thinking_level: { type: 'text', default: DEFAULT_THINKING_LEVEL },\n // Deprecated: no longer read or written. Kept so existing databases need no\n // migration. Old rows may still hold `true`, so never read it to bring Slack\n // work items back. Drop it in a later migration.\n slack_work_items_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A phase starts on its own with `autoStart`; the\n // `auto-run-switch-v1` board migration reads it once to carry it into the project's boards.\n auto_run_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer read or written. Plans are approved per board (`exitTool.autoApprove`).\n auto_approve_plans: { type: 'boolean', default: false },\n sandbox_working_directory: { type: 'text', nullable: true },\n sandbox_settings: { type: 'json', nullable: true },\n workspace_setup_command: { type: 'text', nullable: true },\n active_template_id: { type: 'text', nullable: true },\n active_template_heads: { type: 'json', nullable: true },\n last_build_id: { type: 'text', nullable: true },\n last_build_heads: { type: 'json', nullable: true },\n last_build_inputs: { type: 'text', nullable: true },\n last_build_attempted_at: { type: 'timestamp', nullable: true },\n last_push_build_at: { type: 'timestamp', nullable: true },\n build_start_uncertain: { type: 'boolean', default: false },\n build_start_uncertain_since: { type: 'timestamp', nullable: true },\n build_start_claim: { type: 'text', nullable: true },\n build_start_claim_expires_at: { type: 'timestamp', nullable: true },\n build_on_push_enabled: { type: 'boolean', default: false },\n build_push_debounce_minutes: { type: 'integer', default: DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES },\n // Retired project switch: no longer read or written. The review skill decides whether to publish its test check.\n review_test_checks_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A board self-reviews when it has a self-review\n // phase; the `self-review-switch-v1` board migration reads it once to carry it into its boards.\n self_review_enabled: { type: 'boolean', default: false },\n /** Set once the source-control domain has backfilled repository positions and environment membership. */\n environment_backfilled_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_projects_org_updated_at_idx', columns: ['org_id', 'updated_at'] }],\n};\n\ninterface FactoryProjectDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n name: string;\n description: string | null;\n default_model_id: string | null;\n model_scope: string;\n default_thinking_level: string | null;\n auto_run_enabled: boolean;\n auto_approve_plans: boolean;\n sandbox_working_directory: string | null;\n sandbox_settings: Record<string, unknown> | null;\n workspace_setup_command: string | null;\n active_template_id: string | null;\n active_template_heads: Record<string, string> | null;\n last_build_id: string | null;\n last_build_heads: Record<string, string> | null;\n last_build_inputs: string | null;\n last_build_attempted_at: Date | null;\n last_push_build_at: Date | null;\n build_start_uncertain: boolean | null;\n build_start_uncertain_since: Date | null;\n build_start_claim: string | null;\n build_start_claim_expires_at: Date | null;\n build_on_push_enabled: boolean | null;\n build_push_debounce_minutes: number | null;\n self_review_enabled: boolean | null;\n environment_backfilled_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toFactoryProject(row: FactoryProjectDbRow): FactoryProject {\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n name: row.name,\n description: row.description,\n defaultModelId: row.default_model_id,\n modelScope: row.model_scope === 'factory' || row.model_scope === 'user' ? row.model_scope : 'hybrid',\n defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level)\n ? row.default_thinking_level\n : DEFAULT_THINKING_LEVEL,\n sandboxWorkingDirectory: row.sandbox_working_directory ?? null,\n sandboxSettings: row.sandbox_settings ?? null,\n workspaceSetupCommand: row.workspace_setup_command ?? null,\n activeTemplateId: row.active_template_id ?? null,\n activeTemplateHeads: row.active_template_heads ?? null,\n lastBuildId: row.last_build_id ?? null,\n lastBuildHeads: row.last_build_heads ?? null,\n lastBuildInputs: row.last_build_inputs ?? null,\n lastBuildAttemptedAt: row.last_build_attempted_at ?? null,\n lastPushBuildAt: row.last_push_build_at ?? null,\n buildStartUncertain: row.build_start_uncertain ?? false,\n buildStartUncertainSince: row.build_start_uncertain_since ?? null,\n buildOnPushEnabled: row.build_on_push_enabled ?? false,\n buildPushDebounceMinutes: row.build_push_debounce_minutes ?? DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class FactoryProjectsStorage extends FactoryStorageDomain {\n constructor() {\n super('projects');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([FACTORY_PROJECTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('factory_projects', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async create({\n orgId,\n userId,\n input,\n }: {\n orgId: string;\n userId: string;\n input: CreateFactoryProjectInput;\n }): Promise<FactoryProject> {\n const now = new Date();\n const row = await this.#db.insertOne<FactoryProjectDbRow>('factory_projects', {\n org_id: orgId,\n created_by: userId,\n name: input.name,\n description: input.description ?? null,\n default_model_id: input.defaultModelId ?? null,\n model_scope: input.modelScope ?? 'hybrid',\n created_at: now,\n updated_at: now,\n });\n return toFactoryProject(row);\n }\n\n async list({ orgId }: { orgId: string }): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n { org_id: orgId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async listAll(): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n {},\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * The retired automation switches as the project last stored them, read only by the one-time\n * board migrations that carry them into its boards. Null when the project doesn't exist.\n */\n async retiredAutomationSettings(\n { orgId, id }: { orgId: string; id: string },\n /** A transaction's ops, to read it inside that transaction. */\n ops: FactoryStorageOps = this.#db,\n ): Promise<RetiredAutomationSettings | null> {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n return { autoRunEnabled: Boolean(row.auto_run_enabled), selfReviewEnabled: Boolean(row.self_review_enabled) };\n }\n\n async getById({ id }: { id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { id });\n return row ? toFactoryProject(row) : null;\n }\n\n async update({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n /** A function input runs in a transaction; writes through its `ops` commit or roll back with the project. */\n input:\n | UpdateFactoryProjectInput\n | ((current: FactoryProject, ops: FactoryStorageOps) => Promise<UpdateFactoryProjectInput | null>);\n }): Promise<FactoryProject | null> {\n const update = (ops: FactoryStorageOps) =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id }, async current => {\n const changes = typeof input === 'function' ? await input(toFactoryProject(current), ops) : input;\n if (changes === null) return null;\n return {\n ...(changes.name !== undefined ? { name: changes.name } : {}),\n ...(changes.description !== undefined ? { description: changes.description } : {}),\n ...(changes.defaultModelId !== undefined ? { default_model_id: changes.defaultModelId } : {}),\n ...(changes.modelScope !== undefined ? { model_scope: changes.modelScope } : {}),\n ...(changes.defaultThinkingLevel !== undefined\n ? { default_thinking_level: changes.defaultThinkingLevel }\n : {}),\n ...(changes.sandboxWorkingDirectory !== undefined\n ? { sandbox_working_directory: changes.sandboxWorkingDirectory }\n : {}),\n ...(changes.sandboxSettings !== undefined ? { sandbox_settings: changes.sandboxSettings } : {}),\n ...(changes.workspaceSetupCommand !== undefined\n ? { workspace_setup_command: changes.workspaceSetupCommand }\n : {}),\n ...(changes.activeTemplateId !== undefined ? { active_template_id: changes.activeTemplateId } : {}),\n ...(changes.activeTemplateHeads !== undefined ? { active_template_heads: changes.activeTemplateHeads } : {}),\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(changes.buildOnPushEnabled !== undefined ? { build_on_push_enabled: changes.buildOnPushEnabled } : {}),\n ...(changes.buildPushDebounceMinutes !== undefined\n ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes }\n : {}),\n updated_at: new Date(),\n };\n });\n // LibSQL's standalone updateAtomic only serializes one client; a transaction\n // also protects a read-dependent update against other database connections.\n const row = typeof input === 'function' ? await this.storage.withTransaction(update) : await update(this.#db);\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * Leading-edge debounce for push-triggered builds: stamps\n * `last_push_build_at = now` and resolves true when no push started a build\n * within the last `debounceMinutes`, else writes nothing and resolves\n * false. Taken right before the provider start, so a push that skips\n * (another run starting, a build in progress) never closes the window. The read and the write run in one transaction, so two concurrent\n * webhooks never both win, even on different database connections.\n */\n async claimBuildAttempt({\n id,\n debounceMinutes,\n now = new Date(),\n }: {\n id: string;\n debounceMinutes: number;\n now?: Date;\n }): Promise<boolean> {\n let claimed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const last = current.last_push_build_at;\n if (last && now.getTime() - last.getTime() < debounceMinutes * 60_000) return null;\n claimed = true;\n return { last_push_build_at: now, updated_at: now };\n }),\n );\n return claimed;\n }\n\n /**\n * Takes the project's build-start lease for `token`. Every trigger (manual,\n * schedule, push) takes it before reading build state and holds it through\n * `builds.start` and recording the result, so two runs never both start a\n * build. `claimed` is false while another run holds an unexpired lease. The\n * holder renews the lease while it works (`renewBuildStart`), so a lease\n * only expires when its run died or stalled. Taking over an expired lease\n * marks the start uncertain (that run's build may have reached the provider\n * unrecorded), and the mark stays until a release resolves it; `uncertain`\n * reports it. The mark's `build_start_uncertain_since` is the lapsed lease's\n * expiry, the latest that run could have started a build; a mark written\n * before that column existed is dated by the first claim that reads it.\n * Only the claim is transactional; provider calls run outside it.\n */\n async claimBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<{ claimed: boolean; uncertain: boolean }> {\n const result = { claimed: false, uncertain: false };\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const expiresAt = current.build_start_claim_expires_at;\n if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;\n result.claimed = true;\n const lapsedAt = current.build_start_claim ? (expiresAt ?? now) : null;\n const markedAt = current.build_start_uncertain === true ? (current.build_start_uncertain_since ?? now) : null;\n result.uncertain = lapsedAt !== null || markedAt !== null;\n const since =\n lapsedAt && markedAt\n ? lapsedAt.getTime() > markedAt.getTime()\n ? lapsedAt\n : markedAt\n : (lapsedAt ?? markedAt);\n return {\n build_start_claim: token,\n build_start_claim_expires_at: new Date(now.getTime() + leaseMs),\n ...(since ? { build_start_uncertain: true, build_start_uncertain_since: since } : {}),\n updated_at: now,\n };\n }),\n );\n return result;\n }\n\n /**\n * Extends the build-start lease held by `token` to `now + leaseMs`. Resolves\n * false, writing nothing, when `token` no longer holds it.\n */\n async renewBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<boolean> {\n let renewed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n renewed = true;\n return { build_start_claim_expires_at: new Date(now.getTime() + leaseMs), updated_at: now };\n }),\n );\n return renewed;\n }\n\n /**\n * Releases the build-start lease taken with `token` and writes `changes` in\n * the same transaction, but only while `token` still holds the lease. A run\n * whose lease expired and was taken by a newer run writes nothing, so it\n * never clears or overwrites that run's build. `resolved` clears an\n * uncertain start. Resolves false when skipped.\n */\n async releaseBuildStart({\n id,\n token,\n changes = {},\n resolved = false,\n now = new Date(),\n }: {\n id: string;\n token: string;\n resolved?: boolean;\n changes?: Pick<\n UpdateFactoryProjectInput,\n 'lastBuildId' | 'lastBuildHeads' | 'lastBuildInputs' | 'lastBuildAttemptedAt'\n >;\n now?: Date;\n }): Promise<boolean> {\n let released = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n released = true;\n return {\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(resolved ? { build_start_uncertain: false, build_start_uncertain_since: null } : {}),\n build_start_claim: null,\n build_start_claim_expires_at: null,\n updated_at: now,\n };\n }),\n );\n return released;\n }\n\n /**\n * Pins the active template to a finished build, but only while that build is\n * still the project's last one. Overlapping runs (Build now during a push\n * build) can finish out of order; the write and the `last_build_id` check\n * run in one transaction so a stale run never overwrites a newer build's\n * pin. Resolves false when the pin was skipped.\n */\n async pinActiveTemplate({\n id,\n buildId,\n templateId,\n heads,\n now = new Date(),\n }: {\n id: string;\n buildId: string;\n templateId: string;\n heads: Record<string, string>;\n now?: Date;\n }): Promise<boolean> {\n let pinned = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.last_build_id !== buildId) return null;\n pinned = true;\n return { active_template_id: templateId, active_template_heads: heads, updated_at: now };\n }),\n );\n return pinned;\n }\n\n /** `release` runs in the deleting transaction, so nothing can be routed to the project between the two. */\n async delete(\n { orgId, id }: { orgId: string; id: string },\n release?: (ops: FactoryStorageOps) => Promise<void>,\n ): Promise<FactoryProject | null> {\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n await release?.(ops);\n await ops.deleteMany('factory_projects', { org_id: orgId, id });\n return toFactoryProject(row);\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;AAOA,MAAa,sCAAsC;AACnD,MAAa,uBAAuB;CAAC;CAAW;CAAQ;AAAQ;;;;;AAShE,SAAgB,oBAAoB,OAA0B,SAAiD;CAC7G,IAAI,UAAU,UAAU,OAAO,YAAY,QAAQ,YAAY;CAC/D,OAAO;AACT;;;;;;AAOA,SAAgB,6BAA6B,kBAAkC;CAC7E,OAAO,mBAAmB;AAC5B;;;;;;;AAQA,MAAa,qBAAqB;AAElC,SAAgB,qBAAqB,QAA4C;CAC/E,OAAO,QAAQ,WAAW,kBAAkB,MAAM;AACpD;AAuFA,MAAa,0BAA4C;CACvD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,OAAO;EAC3B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,kBAAkB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACjD,a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