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

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 (335) hide show
  1. package/README.md +210 -42
  2. package/dist/boards/board-events.d.ts +34 -0
  3. package/dist/boards/board-events.d.ts.map +1 -0
  4. package/dist/boards/board-events.js +50 -0
  5. package/dist/boards/board-events.js.map +1 -0
  6. package/dist/boards/board-writes.d.ts +86 -0
  7. package/dist/boards/board-writes.d.ts.map +1 -0
  8. package/dist/boards/board-writes.js +252 -0
  9. package/dist/boards/board-writes.js.map +1 -0
  10. package/dist/boards/define-board.d.ts +16 -5
  11. package/dist/boards/define-board.d.ts.map +1 -1
  12. package/dist/boards/define-board.js +30 -8
  13. package/dist/boards/define-board.js.map +1 -1
  14. package/dist/boards/intake-routing.d.ts +30 -6
  15. package/dist/boards/intake-routing.d.ts.map +1 -1
  16. package/dist/boards/intake-routing.js +43 -5
  17. package/dist/boards/intake-routing.js.map +1 -1
  18. package/dist/boards/legacy-plan-role.d.ts.map +1 -1
  19. package/dist/boards/legacy-plan-role.js +8 -4
  20. package/dist/boards/legacy-plan-role.js.map +1 -1
  21. package/dist/boards/phase-automation.d.ts.map +1 -1
  22. package/dist/boards/phase-automation.js +7 -2
  23. package/dist/boards/phase-automation.js.map +1 -1
  24. package/dist/boards/project-boards.d.ts +18 -7
  25. package/dist/boards/project-boards.d.ts.map +1 -1
  26. package/dist/boards/project-boards.js +78 -14
  27. package/dist/boards/project-boards.js.map +1 -1
  28. package/dist/boards/stored-board.d.ts +59 -1
  29. package/dist/boards/stored-board.d.ts.map +1 -1
  30. package/dist/boards/stored-board.js +219 -7
  31. package/dist/boards/stored-board.js.map +1 -1
  32. package/dist/factory.d.ts +63 -9
  33. package/dist/factory.d.ts.map +1 -1
  34. package/dist/factory.js +187 -22
  35. package/dist/factory.js.map +1 -1
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +4 -3
  39. package/dist/integrations/base.d.ts +6 -0
  40. package/dist/integrations/base.d.ts.map +1 -1
  41. package/dist/integrations/github/acceptance-labels.d.ts +4 -0
  42. package/dist/integrations/github/acceptance-labels.d.ts.map +1 -1
  43. package/dist/integrations/github/acceptance-labels.js +1 -1
  44. package/dist/integrations/github/acceptance-labels.js.map +1 -1
  45. package/dist/integrations/github/default-rules.d.ts +2 -9
  46. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  47. package/dist/integrations/github/default-rules.js +7 -6
  48. package/dist/integrations/github/default-rules.js.map +1 -1
  49. package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
  50. package/dist/integrations/github/issue-reconciler.js +17 -1
  51. package/dist/integrations/github/issue-reconciler.js.map +1 -1
  52. package/dist/integrations/github/review-status-comment.d.ts +61 -0
  53. package/dist/integrations/github/review-status-comment.d.ts.map +1 -0
  54. package/dist/integrations/github/review-status-comment.js +217 -0
  55. package/dist/integrations/github/review-status-comment.js.map +1 -0
  56. package/dist/integrations/github/review-status-reporter.d.ts +42 -0
  57. package/dist/integrations/github/review-status-reporter.d.ts.map +1 -0
  58. package/dist/integrations/github/review-status-reporter.js +100 -0
  59. package/dist/integrations/github/review-status-reporter.js.map +1 -0
  60. package/dist/integrations/github/review-status.d.ts +28 -0
  61. package/dist/integrations/github/review-status.d.ts.map +1 -0
  62. package/dist/integrations/github/review-status.js +95 -0
  63. package/dist/integrations/github/review-status.js.map +1 -0
  64. package/dist/integrations/github/routes.d.ts.map +1 -1
  65. package/dist/integrations/github/routes.js +2 -5
  66. package/dist/integrations/github/routes.js.map +1 -1
  67. package/dist/integrations/github/rules.d.ts +13 -1
  68. package/dist/integrations/github/rules.d.ts.map +1 -1
  69. package/dist/integrations/github/rules.js +77 -6
  70. package/dist/integrations/github/rules.js.map +1 -1
  71. package/dist/integrations/gitlab/default-rules.d.ts +24 -9
  72. package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
  73. package/dist/integrations/gitlab/default-rules.js +4 -4
  74. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  75. package/dist/integrations/gitlab/merge-request-reconciler.js +1 -1
  76. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  77. package/dist/integrations/gitlab/routes.js +1 -3
  78. package/dist/integrations/gitlab/routes.js.map +1 -1
  79. package/dist/integrations/gitlab/rules.d.ts +16 -0
  80. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  81. package/dist/integrations/gitlab/rules.js +69 -4
  82. package/dist/integrations/gitlab/rules.js.map +1 -1
  83. package/dist/integrations/incidentio/default-rules.d.ts +1 -9
  84. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  85. package/dist/integrations/incidentio/default-rules.js +3 -4
  86. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  87. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  88. package/dist/integrations/incidentio/routes.js +1 -4
  89. package/dist/integrations/incidentio/routes.js.map +1 -1
  90. package/dist/integrations/incidentio/rules.d.ts +7 -0
  91. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  92. package/dist/integrations/incidentio/rules.js +35 -3
  93. package/dist/integrations/incidentio/rules.js.map +1 -1
  94. package/dist/integrations/jira/default-rules.d.ts +1 -9
  95. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  96. package/dist/integrations/jira/default-rules.js +3 -4
  97. package/dist/integrations/jira/default-rules.js.map +1 -1
  98. package/dist/integrations/jira/routes.d.ts.map +1 -1
  99. package/dist/integrations/jira/routes.js +1 -4
  100. package/dist/integrations/jira/routes.js.map +1 -1
  101. package/dist/integrations/jira/rules.d.ts +7 -0
  102. package/dist/integrations/jira/rules.d.ts.map +1 -1
  103. package/dist/integrations/jira/rules.js +35 -3
  104. package/dist/integrations/jira/rules.js.map +1 -1
  105. package/dist/integrations/linear/default-rules.d.ts +1 -9
  106. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  107. package/dist/integrations/linear/default-rules.js +3 -4
  108. package/dist/integrations/linear/default-rules.js.map +1 -1
  109. package/dist/integrations/linear/routes.d.ts.map +1 -1
  110. package/dist/integrations/linear/routes.js +1 -4
  111. package/dist/integrations/linear/routes.js.map +1 -1
  112. package/dist/integrations/linear/rules.d.ts +7 -0
  113. package/dist/integrations/linear/rules.d.ts.map +1 -1
  114. package/dist/integrations/linear/rules.js +35 -3
  115. package/dist/integrations/linear/rules.js.map +1 -1
  116. package/dist/integrations/platform/connect/routes.d.ts +7 -1
  117. package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
  118. package/dist/integrations/platform/connect/routes.js +42 -5
  119. package/dist/integrations/platform/connect/routes.js.map +1 -1
  120. package/dist/integrations/platform/connect/session-tools.d.ts +7 -0
  121. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -0
  122. package/dist/integrations/platform/connect/session-tools.js +30 -0
  123. package/dist/integrations/platform/connect/session-tools.js.map +1 -0
  124. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  125. package/dist/integrations/platform/github/integration.js +1 -3
  126. package/dist/integrations/platform/github/integration.js.map +1 -1
  127. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  128. package/dist/integrations/platform/jira/routes.js +1 -4
  129. package/dist/integrations/platform/jira/routes.js.map +1 -1
  130. package/dist/integrations/platform/linear/event-worker.d.ts +1 -1
  131. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  132. package/dist/integrations/platform/linear/event-worker.js +9 -0
  133. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  134. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  135. package/dist/integrations/platform/linear/integration.js +1 -3
  136. package/dist/integrations/platform/linear/integration.js.map +1 -1
  137. package/dist/integrations/slack/channel-reply-processor.d.ts +2 -0
  138. package/dist/integrations/slack/channel-reply-processor.d.ts.map +1 -1
  139. package/dist/integrations/slack/channel-reply-processor.js +6 -1
  140. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  141. package/dist/integrations/slack/connect-route.d.ts.map +1 -1
  142. package/dist/integrations/slack/connect-route.js +1 -1
  143. package/dist/integrations/slack/connect-route.js.map +1 -1
  144. package/dist/integrations/slack/integration.d.ts.map +1 -1
  145. package/dist/integrations/slack/integration.js +2 -0
  146. package/dist/integrations/slack/integration.js.map +1 -1
  147. package/dist/integrations/slack/slack.d.ts +12 -10
  148. package/dist/integrations/slack/slack.d.ts.map +1 -1
  149. package/dist/integrations/slack/slack.js +110 -43
  150. package/dist/integrations/slack/slack.js.map +1 -1
  151. package/dist/integrations/slack/voice-clips.d.ts +32 -0
  152. package/dist/integrations/slack/voice-clips.d.ts.map +1 -0
  153. package/dist/integrations/slack/voice-clips.js +201 -0
  154. package/dist/integrations/slack/voice-clips.js.map +1 -0
  155. package/dist/integrations/workos/integration.d.ts.map +1 -1
  156. package/dist/integrations/workos/integration.js +1 -3
  157. package/dist/integrations/workos/integration.js.map +1 -1
  158. package/dist/mcp/routes.js +1 -1
  159. package/dist/packages/_internals/workspace/dist/index.js +1 -1
  160. package/dist/routes/attention-activity.js +1 -1
  161. package/dist/routes/attention-providers.js +1 -1
  162. package/dist/routes/automation-runs.d.ts.map +1 -1
  163. package/dist/routes/automation-runs.js +1 -4
  164. package/dist/routes/automation-runs.js.map +1 -1
  165. package/dist/routes/boards.d.ts +8 -6
  166. package/dist/routes/boards.d.ts.map +1 -1
  167. package/dist/routes/boards.js +73 -143
  168. package/dist/routes/boards.js.map +1 -1
  169. package/dist/routes/config.d.ts.map +1 -1
  170. package/dist/routes/config.js +3 -8
  171. package/dist/routes/config.js.map +1 -1
  172. package/dist/routes/contracts.d.ts +132 -0
  173. package/dist/routes/contracts.d.ts.map +1 -1
  174. package/dist/routes/contracts.js +77 -29
  175. package/dist/routes/contracts.js.map +1 -1
  176. package/dist/routes/fs.d.ts.map +1 -1
  177. package/dist/routes/fs.js +1 -4
  178. package/dist/routes/fs.js.map +1 -1
  179. package/dist/routes/intake-routes.d.ts.map +1 -1
  180. package/dist/routes/intake-routes.js +19 -12
  181. package/dist/routes/intake-routes.js.map +1 -1
  182. package/dist/routes/intake.d.ts.map +1 -1
  183. package/dist/routes/intake.js +3 -5
  184. package/dist/routes/intake.js.map +1 -1
  185. package/dist/routes/knowledge.d.ts.map +1 -1
  186. package/dist/routes/knowledge.js +1 -4
  187. package/dist/routes/knowledge.js.map +1 -1
  188. package/dist/routes/oauth.d.ts.map +1 -1
  189. package/dist/routes/oauth.js +1 -4
  190. package/dist/routes/oauth.js.map +1 -1
  191. package/dist/routes/projects.d.ts +3 -0
  192. package/dist/routes/projects.d.ts.map +1 -1
  193. package/dist/routes/projects.js +7 -4
  194. package/dist/routes/projects.js.map +1 -1
  195. package/dist/routes/provider-credentials.d.ts.map +1 -1
  196. package/dist/routes/provider-credentials.js +6 -0
  197. package/dist/routes/provider-credentials.js.map +1 -1
  198. package/dist/routes/route.d.ts +2 -0
  199. package/dist/routes/route.d.ts.map +1 -1
  200. package/dist/routes/route.js +5 -1
  201. package/dist/routes/route.js.map +1 -1
  202. package/dist/routes/skills.d.ts.map +1 -1
  203. package/dist/routes/skills.js +1 -4
  204. package/dist/routes/skills.js.map +1 -1
  205. package/dist/routes/source-control-sessions.d.ts.map +1 -1
  206. package/dist/routes/source-control-sessions.js +1 -3
  207. package/dist/routes/source-control-sessions.js.map +1 -1
  208. package/dist/routes/source-control-settings.d.ts.map +1 -1
  209. package/dist/routes/source-control-settings.js +3 -2
  210. package/dist/routes/source-control-settings.js.map +1 -1
  211. package/dist/routes/surface.d.ts +3 -1
  212. package/dist/routes/surface.d.ts.map +1 -1
  213. package/dist/routes/surface.js +11 -1
  214. package/dist/routes/surface.js.map +1 -1
  215. package/dist/routes/voice.d.ts +48 -0
  216. package/dist/routes/voice.d.ts.map +1 -0
  217. package/dist/routes/voice.js +248 -0
  218. package/dist/routes/voice.js.map +1 -0
  219. package/dist/routes/work-items.d.ts.map +1 -1
  220. package/dist/routes/work-items.js +1 -4
  221. package/dist/routes/work-items.js.map +1 -1
  222. package/dist/rules/decision-applicability.js +1 -1
  223. package/dist/rules/dispatcher.d.ts +28 -0
  224. package/dist/rules/dispatcher.d.ts.map +1 -1
  225. package/dist/rules/dispatcher.js +391 -93
  226. package/dist/rules/dispatcher.js.map +1 -1
  227. package/dist/rules/event-rules.d.ts +40 -1
  228. package/dist/rules/event-rules.d.ts.map +1 -1
  229. package/dist/rules/event-rules.js +59 -1
  230. package/dist/rules/event-rules.js.map +1 -1
  231. package/dist/rules/processor.js +1 -1
  232. package/dist/rules/processor.js.map +1 -1
  233. package/dist/rules/transition-service.d.ts +9 -0
  234. package/dist/rules/transition-service.d.ts.map +1 -1
  235. package/dist/rules/transition-service.js +4 -2
  236. package/dist/rules/transition-service.js.map +1 -1
  237. package/dist/rules/types.d.ts +54 -3
  238. package/dist/rules/types.d.ts.map +1 -1
  239. package/dist/rules/types.js +2 -0
  240. package/dist/rules/types.js.map +1 -1
  241. package/dist/rules/validation.d.ts.map +1 -1
  242. package/dist/rules/validation.js +57 -2
  243. package/dist/rules/validation.js.map +1 -1
  244. package/dist/session/credential-policy.d.ts +2 -2
  245. package/dist/session/credential-policy.d.ts.map +1 -1
  246. package/dist/session/credential-policy.js +3 -3
  247. package/dist/session/credential-policy.js.map +1 -1
  248. package/dist/session/default-model-hydration.d.ts +2 -2
  249. package/dist/session/default-model-hydration.d.ts.map +1 -1
  250. package/dist/session/default-model-hydration.js +4 -4
  251. package/dist/session/default-model-hydration.js.map +1 -1
  252. package/dist/session/session-threads.d.ts +8 -0
  253. package/dist/session/session-threads.d.ts.map +1 -1
  254. package/dist/session/session-threads.js +11 -1
  255. package/dist/session/session-threads.js.map +1 -1
  256. package/dist/skills/catalog.js +1 -1
  257. package/dist/storage/domains/audit/actions.d.ts +1 -1
  258. package/dist/storage/domains/audit/actions.d.ts.map +1 -1
  259. package/dist/storage/domains/audit/actions.js +2 -1
  260. package/dist/storage/domains/audit/actions.js.map +1 -1
  261. package/dist/storage/domains/audit/domain.d.ts.map +1 -1
  262. package/dist/storage/domains/audit/domain.js +1 -3
  263. package/dist/storage/domains/audit/domain.js.map +1 -1
  264. package/dist/storage/domains/boards/base.d.ts +32 -1
  265. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  266. package/dist/storage/domains/boards/base.js +155 -8
  267. package/dist/storage/domains/boards/base.js.map +1 -1
  268. package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
  269. package/dist/storage/domains/boards/schemas.js +13 -1
  270. package/dist/storage/domains/boards/schemas.js.map +1 -1
  271. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  272. package/dist/storage/domains/comments/routes.js +1 -3
  273. package/dist/storage/domains/comments/routes.js.map +1 -1
  274. package/dist/storage/domains/memory-settings/base.d.ts +0 -8
  275. package/dist/storage/domains/memory-settings/base.d.ts.map +1 -1
  276. package/dist/storage/domains/memory-settings/base.js +1 -11
  277. package/dist/storage/domains/memory-settings/base.js.map +1 -1
  278. package/dist/storage/domains/projects/base.d.ts +6 -0
  279. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  280. package/dist/storage/domains/projects/base.js +9 -1
  281. package/dist/storage/domains/projects/base.js.map +1 -1
  282. package/dist/storage/domains/voice-settings/base.d.ts +31 -0
  283. package/dist/storage/domains/voice-settings/base.d.ts.map +1 -0
  284. package/dist/storage/domains/voice-settings/base.js +81 -0
  285. package/dist/storage/domains/voice-settings/base.js.map +1 -0
  286. package/dist/storage/domains/work-items/base.d.ts +31 -2
  287. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  288. package/dist/storage/domains/work-items/base.js +197 -44
  289. package/dist/storage/domains/work-items/base.js.map +1 -1
  290. package/dist/storage/domains/work-items/cards.d.ts +6 -1
  291. package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
  292. package/dist/storage/domains/work-items/cards.js +54 -4
  293. package/dist/storage/domains/work-items/cards.js.map +1 -1
  294. package/dist/storage/domains/work-items/work-item-schema.d.ts +2 -0
  295. package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
  296. package/dist/storage/domains/work-items/work-item-schema.js +24 -1
  297. package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
  298. package/dist/timing.d.ts +1 -0
  299. package/dist/timing.d.ts.map +1 -1
  300. package/dist/timing.js +1 -1
  301. package/dist/timing.js.map +1 -1
  302. package/dist/tools/read-tools.d.ts +2 -2
  303. package/dist/tools/read-tools.d.ts.map +1 -1
  304. package/dist/tools/read-tools.js +7 -6
  305. package/dist/tools/read-tools.js.map +1 -1
  306. package/dist/tools/session-tools.d.ts +1 -1
  307. package/dist/tools/session-tools.d.ts.map +1 -1
  308. package/dist/tools/session-tools.js.map +1 -1
  309. package/dist/tools/sessions-state-processor.d.ts +1 -1
  310. package/dist/tools/sessions-state-processor.d.ts.map +1 -1
  311. package/dist/tools/sessions-state-processor.js +9 -2
  312. package/dist/tools/sessions-state-processor.js.map +1 -1
  313. package/dist/tools/work-item-tools.js +2 -2
  314. package/dist/voice/rate-limit.d.ts +13 -0
  315. package/dist/voice/rate-limit.d.ts.map +1 -0
  316. package/dist/voice/rate-limit.js +36 -0
  317. package/dist/voice/rate-limit.js.map +1 -0
  318. package/dist/voice/realtime.d.ts +13 -0
  319. package/dist/voice/realtime.d.ts.map +1 -0
  320. package/dist/voice/realtime.js +56 -0
  321. package/dist/voice/realtime.js.map +1 -0
  322. package/dist/voice/transcription.d.ts +51 -0
  323. package/dist/voice/transcription.d.ts.map +1 -0
  324. package/dist/voice/transcription.js +112 -0
  325. package/dist/voice/transcription.js.map +1 -0
  326. package/dist/work-items/split-backfill.d.ts +13 -0
  327. package/dist/work-items/split-backfill.d.ts.map +1 -0
  328. package/dist/work-items/split-backfill.js +32 -0
  329. package/dist/work-items/split-backfill.js.map +1 -0
  330. package/dist/work-items/split-migration.d.ts +39 -2
  331. package/dist/work-items/split-migration.d.ts.map +1 -1
  332. package/dist/work-items/split-migration.js +170 -62
  333. package/dist/work-items/split-migration.js.map +1 -1
  334. package/dist/workspace.js +2 -2
  335. package/package.json +12 -11
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/boards/base.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport type { RuleGroup } from '../../../rules/rule-group.js';\nimport {\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARDS_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n} from './schemas.js';\n\n/** The project a board belongs to. */\nexport interface StoredBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport type StoredPhaseKind = 'resting' | 'working' | 'terminal';\n\n/** Who runs a working phase. Factory runs every phase with its code agent. */\nexport interface StoredPhaseRunner {\n skill?: string;\n context?: string;\n instructions?: string;\n}\n\nexport interface StoredPhaseExitTool {\n id: string;\n autoApprove?: boolean;\n autoApproveWhen?: RuleGroup;\n}\n\n/** A phase as it is written. `key` is the stage id cards sit in. */\nexport interface StoredPhaseInput {\n key: string;\n name: string;\n description?: string | null;\n kind: StoredPhaseKind;\n runner?: StoredPhaseRunner | null;\n /** Unset or `null` on a resting or working phase means every other phase; `[]` means none. */\n nextPhases?: string[] | null;\n autoStart?: boolean;\n autoStartWhen?: RuleGroup | null;\n exitTool?: StoredPhaseExitTool | null;\n}\n\n/** A board as it is written. Phase order is significant: the first phase is where cards start. */\nexport interface StoredBoardInput {\n key: string;\n name: string;\n description?: string | null;\n phases: StoredPhaseInput[];\n}\n\nexport interface StoredPhaseRecord {\n key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n nextPhases: string[] | null;\n autoStart: boolean;\n autoStartWhen: RuleGroup | null;\n exitTool: StoredPhaseExitTool | null;\n}\n\nexport interface StoredBoardRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n phases: StoredPhaseRecord[];\n}\n\nexport interface StoredBoardSnapshot {\n version: string | null;\n boards: StoredBoardRecord[];\n}\n\nexport interface IntakeRouteTarget {\n boardKey: string;\n /** Unset lands the card in the board's first phase. */\n phaseKey?: string | null;\n}\n\n/** An intake route as it is written. */\nexport interface StoredIntakeRouteInput {\n name: string;\n enabled?: boolean;\n /** Null matches every card. */\n when?: RuleGroup | null;\n target: IntakeRouteTarget;\n}\n\nexport interface StoredIntakeRouteRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n name: string;\n enabled: boolean;\n position: number;\n when: RuleGroup | null;\n target: { boardKey: string; phaseKey: string | null };\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n}\n\nexport type StoredBoardErrorCode =\n | 'board_exists'\n | 'board_not_found'\n | 'revision_mismatch'\n | 'intake_route_not_found'\n | 'intake_route_set_mismatch'\n | 'intake_route_limit';\n\n/** A project's most intake routes; a reorder names every one of them. */\nexport const MAX_INTAKE_ROUTES = 100;\n\n/**\n * The route every project starts with: a GitHub or GitLab card whose author is outside the\n * write-access circle lands in Work › Intake, where nothing starts until a person moves it.\n * It is a stored route like any other, so admins can see, edit, disable or delete it.\n */\nexport const DEFAULT_INTAKE_ROUTE: StoredIntakeRouteInput = {\n name: 'Outside authors wait in Intake',\n when: {\n operator: 'AND',\n conditions: [\n { field: 'source.integration', operator: 'in', value: ['github', 'gitlab'] },\n { field: 'author.trusted', operator: 'equals', value: false },\n ],\n },\n target: { boardKey: 'work', phaseKey: 'intake' },\n};\n\n/**\n * Pull requests are reviewed in Work › PR review. It comes after `DEFAULT_INTAKE_ROUTE`, so a\n * pull request from outside the write-access circle still waits in Intake for a person.\n */\nexport const PULL_REQUEST_INTAKE_ROUTE: StoredIntakeRouteInput = {\n name: 'Pull requests go to PR review',\n when: { operator: 'AND', conditions: [{ field: 'source.kind', operator: 'equals', value: 'pull_request' }] },\n target: { boardKey: 'work', phaseKey: 'pr-review' },\n};\n\n/**\n * The routes Factory adds to a project, in order, each under a key that never changes. A project\n * gets each one once: a new project gets them all, a project set up earlier gets a route added\n * since at the end of its list, and a route an admin deleted stays deleted.\n */\nexport const DEFAULT_INTAKE_ROUTES: readonly { key: string; route: StoredIntakeRouteInput }[] = [\n { key: 'outside-authors', route: DEFAULT_INTAKE_ROUTE },\n { key: 'pull-requests', route: PULL_REQUEST_INTAKE_ROUTE },\n];\n\n/** The defaults a project whose lock row predates `seeded_defaults` was set up with. */\nconst ORIGINAL_DEFAULT_KEYS = ['outside-authors'];\n\n/** Who the default intake routes are created and last updated by. */\nexport const DEFAULT_INTAKE_ROUTE_ACTOR = 'factory';\n\nexport class StoredBoardError extends Error {\n override name = 'StoredBoardError';\n constructor(\n readonly code: StoredBoardErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface BoardRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface PhaseRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n phase_key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n next_phases: string[] | null;\n auto_start: boolean;\n auto_start_when: RuleGroup | null;\n exit_tool: StoredPhaseExitTool | null;\n}\n\ninterface IntakeRouteRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n name: string;\n enabled: boolean;\n position: number;\n when_condition: RuleGroup | null;\n board_key: string;\n phase_key: string | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface IntakeRouteLockRow extends Record<string, unknown> {\n /** Keys of the `DEFAULT_INTAKE_ROUTES` added to the project; null on rows written before the list. */\n seeded_defaults: string[] | null;\n}\n\nfunction seededDefaults(lock: IntakeRouteLockRow): string[] {\n return lock.seeded_defaults ?? ORIGINAL_DEFAULT_KEYS;\n}\n\nfunction missingDefaults(lock: IntakeRouteLockRow): (typeof DEFAULT_INTAKE_ROUTES)[number][] {\n const seeded = new Set(seededDefaults(lock));\n return DEFAULT_INTAKE_ROUTES.filter(({ key }) => !seeded.has(key));\n}\n\nconst BOARDS = 'factory_boards';\nconst PHASES = 'factory_board_phases';\nconst VERSIONS = 'factory_board_definition_versions';\nconst INTAKE_ROUTES = 'factory_intake_routes';\nconst INTAKE_ROUTE_LOCKS = 'factory_intake_route_locks';\nconst MAX_WRITE_ATTEMPTS = 3;\n\nfunction scopeWhere({ orgId, factoryProjectId }: StoredBoardScope) {\n return { org_id: orgId, factory_project_id: factoryProjectId };\n}\n\nfunction toPhaseRecord(row: PhaseRow): StoredPhaseRecord {\n return {\n key: row.phase_key,\n position: row.position,\n name: row.name,\n description: row.description,\n kind: row.kind,\n runner: row.runner,\n nextPhases: row.next_phases,\n autoStart: row.auto_start,\n autoStartWhen: row.auto_start_when,\n exitTool: row.exit_tool,\n };\n}\n\nfunction toRecord(row: BoardRow, phases: PhaseRow[]): StoredBoardRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n key: row.board_key,\n name: row.name,\n description: row.description,\n position: row.position,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n phases: phases.sort((left, right) => left.position - right.position).map(toPhaseRecord),\n };\n}\n\n/** A compare-and-set inside a write lost to a concurrent writer; the write is retried from fresh reads. */\nclass ConcurrentBoardWrite extends Error {}\n\n/**\n * Each project's boards and their ordered phases. Every write runs in one transaction that also\n * replaces the project's row in `factory_board_definition_versions`, so caches on other\n * replicas can detect it.\n */\nexport class StoredBoardsStorage extends FactoryStorageDomain {\n constructor() {\n super('boards');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n FACTORY_BOARDS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany(PHASES, {});\n await this.ops.deleteMany(BOARDS, {});\n await this.ops.deleteMany(VERSIONS, {});\n await this.ops.deleteMany(INTAKE_ROUTES, {});\n await this.ops.deleteMany(INTAKE_ROUTE_LOCKS, {});\n }\n\n /** The project's current definition version; null before its first board write. */\n async readVersion(scope: StoredBoardScope): Promise<string | null> {\n return readVersion(this.ops, scope);\n }\n\n /** The project's boards in order. */\n async list(scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n return readBoards(this.ops, scope);\n }\n\n /**\n * The version and the boards, read in that order: a write landing between the two reads leaves a\n * version older than the rows, so a cache keyed on it rereads on its next check instead of\n * keeping the stale rows.\n */\n async snapshot(scope: StoredBoardScope): Promise<StoredBoardSnapshot> {\n const version = await readVersion(this.ops, scope);\n return { version, boards: await this.list(scope) };\n }\n\n async get(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord | null> {\n const row = await this.ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) return null;\n const phases = await this.ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: key });\n return toRecord(row, phases);\n }\n\n /** Creates a board through the API. */\n async create(scope: StoredBoardScope, input: StoredBoardInput, actor: string): Promise<StoredBoardRecord> {\n await ensureVersionRow(this.ops, scope);\n try {\n return await this.#write(scope, async ops => {\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n if (rows.some(row => row.board_key === input.key)) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n await insertBoard(ops, scope, input, { position: nextPosition(rows), actor });\n return { result: undefined, changed: true };\n }).then(async () => (await this.get(scope, input.key))!);\n } catch (error) {\n // Only the board key's index means the board exists; a lost race on another table is not that.\n if (error instanceof UniqueViolationError && error.collection === BOARDS) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n throw error;\n }\n }\n\n /** Replaces a board's name, description and phases. The board key never changes. */\n async replace(\n scope: StoredBoardScope,\n key: string,\n input: Omit<StoredBoardInput, 'key'>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { key, ...input }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /** Deletes a board and its phases. */\n async delete(scope: StoredBoardScope, key: string, options: { expectedRevision: number }): Promise<void> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n if ((await ops.deleteMany(BOARDS, { id: row.id, revision: row.revision })) === 0)\n throw new ConcurrentBoardWrite();\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: key });\n return { result: undefined, changed: true };\n });\n }\n\n /** The project's intake routes in the order they are tried; Factory's `DEFAULT_INTAKE_ROUTES` are added once each. */\n async listIntakeRoutes(scope: StoredBoardScope): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n return (await readIntakeRoutes(this.ops, scope)).map(toIntakeRouteRecord);\n }\n\n async getIntakeRoute(scope: StoredBoardScope, id: string): Promise<StoredIntakeRouteRecord | null> {\n const row = await this.ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n return row ? toIntakeRouteRecord(row) : null;\n }\n\n /** Adds a route after the project's last one. */\n async createIntakeRoute(\n scope: StoredBoardScope,\n input: StoredIntakeRouteInput,\n actor: string,\n ): Promise<StoredIntakeRouteRecord> {\n const id = randomUUID();\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n if (rows.length >= MAX_INTAKE_ROUTES) {\n throw new StoredBoardError(\n 'intake_route_limit',\n `A project can have at most ${MAX_INTAKE_ROUTES} intake routes; delete one first.`,\n );\n }\n await insertIntakeRoute(ops, scope, {\n id,\n input,\n position: rows.reduce((max, row) => Math.max(max, row.position), -1) + 1,\n actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Changes the fields `patch` names; the route keeps its place in the order. */\n async updateIntakeRoute(\n scope: StoredBoardScope,\n id: string,\n patch: Partial<StoredIntakeRouteInput>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredIntakeRouteRecord> {\n await this.#transact(async ops => {\n const row = await findIntakeRoute(ops, scope, id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n await updateIntakeRouteRow(ops, row, {\n ...(patch.name !== undefined && { name: patch.name }),\n ...(patch.enabled !== undefined && { enabled: patch.enabled }),\n ...(patch.when !== undefined && { when_condition: patch.when }),\n ...(patch.target !== undefined && {\n board_key: patch.target.boardKey,\n phase_key: patch.target.phaseKey ?? null,\n }),\n updated_by: options.actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Deletes a route; the routes after it move up one place. */\n async deleteIntakeRoute(scope: StoredBoardScope, id: string, options: { expectedRevision: number }): Promise<void> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const row = rows.find(route => route.id === id);\n if (!row) throw intakeRouteNotFound(id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n if ((await ops.deleteMany(INTAKE_ROUTES, { id: row.id, revision: row.revision })) === 0) {\n throw new ConcurrentBoardWrite();\n }\n await placeIntakeRoutes(\n ops,\n rows.filter(route => route.id !== row.id),\n );\n });\n }\n\n /** Puts the project's routes in the order of `ids`, which must name every route exactly once. */\n async reorderIntakeRoutes(scope: StoredBoardScope, ids: string[], actor: string): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const byId = new Map(rows.map(row => [row.id, row]));\n if (ids.length !== rows.length || new Set(ids).size !== ids.length || ids.some(id => !byId.has(id))) {\n throw new StoredBoardError(\n 'intake_route_set_mismatch',\n 'The order must list every intake route of the project exactly once; reload the routes and try again.',\n );\n }\n await placeIntakeRoutes(\n ops,\n ids.map(id => byId.get(id)!),\n actor,\n );\n });\n return this.listIntakeRoutes(scope);\n }\n\n /**\n * Creates the project's route lock row (see `FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA`) and adds each of\n * `DEFAULT_INTAKE_ROUTES` the row doesn't list as added yet, after the project's routes. The row\n * records every default it added, so a project whose admin deleted one doesn't get it back. Runs\n * before, never inside, a write's transaction: the lock taken there must always be an update.\n */\n async #ensureIntakeRoutes(scope: StoredBoardScope): Promise<void> {\n const lock = await this.ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope));\n if (lock && missingDefaults(lock).length === 0) return;\n await this.#transact(async ops => {\n if (await ops.findOne(INTAKE_ROUTE_LOCKS, scopeWhere(scope))) await lockIntakeRoutes(ops, scope);\n // A racing first read inserted the lock row first: this one fails on the unique index and\n // retries, taking the lock above.\n else\n await ops.insertOne(INTAKE_ROUTE_LOCKS, { ...scopeWhere(scope), locked_at: new Date(), seeded_defaults: [] });\n // Read under the lock: a racing seeder that committed first already added what it listed.\n const current = (await ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope)))!;\n const missing = missingDefaults(current);\n if (missing.length === 0) return;\n const rows = await readIntakeRoutes(ops, scope);\n let position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n for (const { route } of missing) {\n // A project at the limit keeps its own routes; the default counts as added all the same.\n if (position >= MAX_INTAKE_ROUTES) break;\n await insertIntakeRoute(ops, scope, {\n id: randomUUID(),\n input: route,\n position: position++,\n actor: DEFAULT_INTAKE_ROUTE_ACTOR,\n });\n }\n await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), {\n seeded_defaults: [...seededDefaults(current), ...missing.map(({ key }) => key)],\n });\n });\n }\n\n /**\n * Runs `fn` in a transaction and replaces the project's version when it changed anything.\n * Lost races (a compare-and-set miss, or a concurrent write that inserted the same board or the\n * project's first version row) retry from fresh reads.\n */\n async #write<T>(\n scope: StoredBoardScope,\n fn: (ops: FactoryStorageOps) => Promise<{ result: T; changed: boolean }>,\n ): Promise<T> {\n return this.#transact(async ops => {\n const { result, changed } = await fn(ops);\n if (changed) await bumpVersion(ops, scope);\n return result;\n });\n }\n\n /**\n * Runs `fn` in a transaction, retrying lost races from fresh reads. Intake route writes use it\n * directly: routes are read uncached, so they leave the board definition version alone.\n */\n async #transact<T>(fn: (ops: FactoryStorageOps) => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n // Read committed is enough: every row change is a compare-and-set on `revision` and every\n // insert meets the unique index. Serializable isolation would also fail writes to\n // unrelated projects that replicas run side by side.\n return await this.storage.withTransaction(fn);\n } catch (error) {\n const retryable = error instanceof ConcurrentBoardWrite || error instanceof UniqueViolationError;\n if (!retryable || attempt >= MAX_WRITE_ATTEMPTS) throw error;\n }\n }\n }\n}\n\nasync function readVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<string | null> {\n const row = await ops.findOne<{ version: string }>(VERSIONS, scopeWhere(scope));\n return row?.version ?? null;\n}\n\nasync function readBoards(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n const [rows, phases] = await Promise.all([\n ops.findMany<BoardRow>(BOARDS, scopeWhere(scope)),\n ops.findMany<PhaseRow>(PHASES, scopeWhere(scope)),\n ]);\n const byBoard = new Map<string, PhaseRow[]>();\n for (const phase of phases) {\n const list = byBoard.get(phase.board_key) ?? [];\n list.push(phase);\n byBoard.set(phase.board_key, list);\n }\n return rows\n .sort((left, right) => left.position - right.position || left.board_key.localeCompare(right.board_key))\n .map(row => toRecord(row, byBoard.get(row.board_key) ?? []));\n}\n\n/**\n * Inserts the project's version row if it has none. This runs outside the write transaction: on\n * Postgres, two transactions racing to insert it would leave the loser's transaction aborted, so\n * the version bump inside a write must always be an update.\n */\nasync function ensureVersionRow(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n if (await ops.findOne(VERSIONS, scopeWhere(scope))) return;\n try {\n await ops.insertOne(VERSIONS, { ...scopeWhere(scope), version: randomUUID(), updated_at: new Date() });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n}\n\nasync function bumpVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n await ops.upsertOne(VERSIONS, ['org_id', 'factory_project_id'], {\n ...scopeWhere(scope),\n version: randomUUID(),\n updated_at: new Date(),\n });\n}\n\nasync function findBoard(ops: FactoryStorageOps, scope: StoredBoardScope, key: string): Promise<BoardRow> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) {\n throw new StoredBoardError('board_not_found', `Board \"${key}\" does not exist in this project.`);\n }\n return row;\n}\n\nfunction checkRevision(row: BoardRow, key: string, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Board \"${key}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\nfunction nextPosition(rows: BoardRow[]): number {\n return rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n}\n\n/** Sets columns on a board row and raises its revision, unless another writer changed it first. */\nasync function updateRow(ops: FactoryStorageOps, row: BoardRow, set: Partial<BoardRow>): Promise<void> {\n const updated = await ops.updateMany(\n BOARDS,\n { id: row.id, revision: row.revision },\n { ...set, revision: row.revision + 1, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n}\n\nasync function insertPhases(ops: FactoryStorageOps, scope: StoredBoardScope, input: StoredBoardInput): Promise<void> {\n for (const [position, phase] of input.phases.entries()) {\n await ops.insertOne<PhaseRow>(PHASES, {\n ...scopeWhere(scope),\n board_key: input.key,\n phase_key: phase.key,\n position,\n name: phase.name,\n description: phase.description ?? null,\n kind: phase.kind,\n runner: phase.runner ?? null,\n next_phases: phase.nextPhases ?? null,\n auto_start: phase.autoStart ?? false,\n auto_start_when: phase.autoStartWhen ?? null,\n exit_tool: phase.exitTool ?? null,\n });\n }\n}\n\nasync function insertBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n input: StoredBoardInput,\n options: { position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<BoardRow>(BOARDS, {\n ...scopeWhere(scope),\n board_key: input.key,\n name: input.name,\n description: input.description ?? null,\n position: options.position,\n revision: 1,\n created_by: options.actor,\n created_at: now,\n updated_by: options.actor,\n updated_at: now,\n });\n await insertPhases(ops, scope, input);\n}\n\n/** Replaces a board's definition and phases in place, keeping its key, position and history. */\nasync function writeBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n row: BoardRow,\n input: StoredBoardInput,\n actor: string,\n): Promise<void> {\n await updateRow(ops, row, { name: input.name, description: input.description ?? null, updated_by: actor });\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n await insertPhases(ops, scope, { ...input, key: row.board_key });\n}\n\nfunction toIntakeRouteRecord(row: IntakeRouteRow): StoredIntakeRouteRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n name: row.name,\n enabled: row.enabled,\n position: row.position,\n when: row.when_condition,\n target: { boardKey: row.board_key, phaseKey: row.phase_key },\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n };\n}\n\nasync function readIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n const rows = await ops.findMany<IntakeRouteRow>(INTAKE_ROUTES, scopeWhere(scope));\n return rows.sort((left, right) => left.position - right.position);\n}\n\nasync function findIntakeRoute(ops: FactoryStorageOps, scope: StoredBoardScope, id: string): Promise<IntakeRouteRow> {\n const row = await ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n if (!row) throw intakeRouteNotFound(id);\n return row;\n}\n\nfunction intakeRouteNotFound(id: string): StoredBoardError {\n return new StoredBoardError('intake_route_not_found', `Intake route \"${id}\" does not exist in this project.`);\n}\n\nfunction checkIntakeRouteRevision(row: IntakeRouteRow, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Intake route \"${row.name}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\n/** Sets columns on a route row and raises its revision, unless another writer changed it first. */\nasync function updateIntakeRouteRow(\n ops: FactoryStorageOps,\n row: IntakeRouteRow,\n set: Partial<IntakeRouteRow>,\n): Promise<number> {\n const revision = row.revision + 1;\n const updated = await ops.updateMany(\n INTAKE_ROUTES,\n { id: row.id, revision: row.revision },\n { ...set, revision, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return revision;\n}\n\nasync function insertIntakeRoute(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n route: { id: string; input: StoredIntakeRouteInput; position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<IntakeRouteRow>(INTAKE_ROUTES, {\n id: route.id,\n ...scopeWhere(scope),\n name: route.input.name,\n enabled: route.input.enabled ?? true,\n position: route.position,\n when_condition: route.input.when ?? null,\n board_key: route.input.target.boardKey,\n phase_key: route.input.target.phaseKey ?? null,\n revision: 1,\n created_by: route.actor,\n created_at: now,\n updated_by: route.actor,\n updated_at: now,\n });\n}\n\n/**\n * Takes the project's route lock and reads the routes. Writes that add, delete or move routes\n * call this first, so they run one after another and each reads what the one before committed.\n */\nasync function lockIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n if ((await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), { locked_at: new Date() })) !== 1) {\n throw new ConcurrentBoardWrite();\n }\n return readIntakeRoutes(ops, scope);\n}\n\n/** Moves routes, read under the project's route lock, to the positions of their order in `rows`. */\nasync function placeIntakeRoutes(ops: FactoryStorageOps, rows: IntakeRouteRow[], actor?: string): Promise<void> {\n const moving = rows.flatMap((row, position) => (row.position === position ? [] : [{ row, position }]));\n const parked = [];\n for (const [index, { row, position }] of moving.entries()) {\n const revision = await updateIntakeRouteRow(ops, row, {\n position: -(index + 1),\n ...(actor !== undefined && { updated_by: actor }),\n });\n parked.push({ id: row.id, revision, position });\n }\n for (const { id, revision, position } of parked) {\n if ((await ops.updateMany(INTAKE_ROUTES, { id, revision }, { position })) !== 1) throw new ConcurrentBoardWrite();\n }\n}\n"],"mappings":";;;;;AAmIA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,uBAA+C;CAC1D,MAAM;CACN,MAAM;EACJ,UAAU;EACV,YAAY,CACV;GAAE,OAAO;GAAsB,UAAU;GAAM,OAAO,CAAC,UAAU,QAAQ;EAAE,GAC3E;GAAE,OAAO;GAAkB,UAAU;GAAU,OAAO;EAAM,CAC9D;CACF;CACA,QAAQ;EAAE,UAAU;EAAQ,UAAU;CAAS;AACjD;;;;;AAMA,MAAa,4BAAoD;CAC/D,MAAM;CACN,MAAM;EAAE,UAAU;EAAO,YAAY,CAAC;GAAE,OAAO;GAAe,UAAU;GAAU,OAAO;EAAe,CAAC;CAAE;CAC3G,QAAQ;EAAE,UAAU;EAAQ,UAAU;CAAY;AACpD;;;;;;AAOA,MAAa,wBAAmF,CAC9F;CAAE,KAAK;CAAmB,OAAO;AAAqB,GACtD;CAAE,KAAK;CAAiB,OAAO;AAA0B,CAC3D;;AAGA,MAAM,wBAAwB,CAAC,iBAAiB;;AAGhD,MAAa,6BAA6B;AAE1C,IAAa,mBAAb,cAAsC,MAAM;CA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,QAAQ;GACpB,GAAI,UAAU,KAAA,KAAa,EAAE,YAAY,MAAM;EACjD,CAAC;EACD,OAAO,KAAK;GAAE,IAAI,IAAI;GAAI;GAAU;EAAS,CAAC;CAChD;CACA,KAAK,MAAM,EAAE,IAAI,UAAU,cAAc,QACvC,IAAK,MAAM,IAAI,WAAW,eAAe;EAAE;EAAI;CAAS,GAAG,EAAE,SAAS,CAAC,MAAO,GAAG,MAAM,IAAI,qBAAqB;AAEpH"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/boards/base.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_ROUTE_EVENTS, routeEventsProblem } from '../../../boards/board-events.js';\nimport type { StatusEvent } from '../../../boards/board-events.js';\nimport type { RuleGroup } from '../../../rules/rule-group.js';\nimport {\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARDS_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n} from './schemas.js';\n\n/** The project a board belongs to. */\nexport interface StoredBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport type StoredPhaseKind = 'resting' | 'working' | 'terminal';\n\n/** Who runs a working phase. Factory runs every phase with its code agent. */\nexport interface StoredPhaseRunner {\n skill?: string;\n context?: string;\n instructions?: string;\n}\n\nexport interface StoredPhaseExitTool {\n id: string;\n autoApprove?: boolean;\n autoApproveWhen?: RuleGroup;\n}\n\n/** A phase as it is written. `key` is the stage id cards sit in. */\nexport interface StoredPhaseInput {\n key: string;\n name: string;\n description?: string | null;\n kind: StoredPhaseKind;\n runner?: StoredPhaseRunner | null;\n /** Unset or `null` on a resting or working phase means every other phase; `[]` means none. */\n nextPhases?: string[] | null;\n autoStart?: boolean;\n autoStartWhen?: RuleGroup | null;\n exitTool?: StoredPhaseExitTool | null;\n}\n\n/** A board as it is written. Phase order is significant: the first phase is where cards start. */\nexport interface StoredBoardInput {\n key: string;\n name: string;\n description?: string | null;\n phases: StoredPhaseInput[];\n}\n\nexport interface StoredPhaseRecord {\n key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n nextPhases: string[] | null;\n autoStart: boolean;\n autoStartWhen: RuleGroup | null;\n exitTool: StoredPhaseExitTool | null;\n}\n\nexport interface StoredBoardRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n phases: StoredPhaseRecord[];\n}\n\nexport interface StoredBoardSnapshot {\n version: string | null;\n boards: StoredBoardRecord[];\n}\n\nexport interface IntakeRouteTarget {\n boardKey: string;\n /** Unset lands the card in the board's first phase. */\n phaseKey?: string | null;\n}\n\n/** An intake route as it is written. */\nexport interface StoredIntakeRouteInput {\n name: string;\n enabled?: boolean;\n /** Null matches every card. */\n when?: RuleGroup | null;\n target: IntakeRouteTarget;\n /** The status events the route handles; unset handles new cards (`work_item.created`). */\n on?: StatusEvent[];\n /** Lets an event move an existing card into a working phase, such as Triage. Off by default. */\n allowWorkingPhase?: boolean;\n}\n\nexport interface StoredIntakeRouteRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n name: string;\n enabled: boolean;\n position: number;\n when: RuleGroup | null;\n target: { boardKey: string; phaseKey: string | null };\n on: StatusEvent[];\n allowWorkingPhase: boolean;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n}\n\nexport type StoredBoardErrorCode =\n | 'board_exists'\n | 'board_not_found'\n | 'revision_mismatch'\n | 'intake_route_not_found'\n | 'intake_route_set_mismatch'\n | 'intake_route_limit'\n | 'invalid_intake_route';\n\n/** A project's most intake routes; a reorder names every one of them. */\nexport const MAX_INTAKE_ROUTES = 100;\n\n/**\n * The route every project starts with: a GitHub or GitLab card whose author is outside the\n * write-access circle lands in Work › Intake, where nothing starts until a person moves it.\n * It is a stored route like any other, so admins can see, edit, disable or delete it.\n */\nexport const DEFAULT_INTAKE_ROUTE: StoredIntakeRouteInput = {\n name: 'Outside authors wait in Intake',\n when: {\n operator: 'AND',\n conditions: [\n { field: 'source.integration', operator: 'in', value: ['github', 'gitlab'] },\n { field: 'author.trusted', operator: 'equals', value: false },\n ],\n },\n target: { boardKey: 'work', phaseKey: 'intake' },\n};\n\n/**\n * Pull requests are reviewed in Work › PR review. It comes after `DEFAULT_INTAKE_ROUTE`, so a\n * pull request from outside the write-access circle still waits in Intake for a person.\n */\nexport const PULL_REQUEST_INTAKE_ROUTE: StoredIntakeRouteInput = {\n name: 'Pull requests go to PR review',\n when: { operator: 'AND', conditions: [{ field: 'source.kind', operator: 'equals', value: 'pull_request' }] },\n target: { boardKey: 'work', phaseKey: 'pr-review' },\n};\n\n/** A Work card whose issue was closed as done goes to Done. */\nexport const CLOSED_COMPLETED_ROUTE: StoredIntakeRouteInput = {\n name: 'Closed issues go to Done',\n on: ['work_item.closed'],\n when: { operator: 'AND', conditions: [{ field: 'event.reason', operator: 'equals', value: 'completed' }] },\n target: { boardKey: 'work', phaseKey: 'done' },\n};\n\n/** A Work card whose issue was closed as not planned, or as a duplicate, goes to Canceled. */\nexport const CLOSED_CANCELED_ROUTE: StoredIntakeRouteInput = {\n name: 'Issues closed as not planned go to Canceled',\n on: ['work_item.closed'],\n when: { operator: 'AND', conditions: [{ field: 'event.reason', operator: 'equals', value: 'canceled' }] },\n target: { boardKey: 'work', phaseKey: 'canceled' },\n};\n\n/** A finished Work card whose issue was reopened goes back to Intake, where a person picks it up again. */\nexport const REOPENED_ROUTE: StoredIntakeRouteInput = {\n name: 'Reopened issues go back to Intake',\n on: ['work_item.reopened'],\n target: { boardKey: 'work', phaseKey: 'intake' },\n};\n\n/**\n * The routes Factory adds to a project, in order, each under a key that never changes. A project\n * gets each one once: a new project gets them all, a project set up earlier gets a route added\n * since at the end of its list, and a route an admin deleted stays deleted.\n */\nexport const DEFAULT_INTAKE_ROUTES: readonly { key: string; route: StoredIntakeRouteInput }[] = [\n { key: 'outside-authors', route: DEFAULT_INTAKE_ROUTE },\n { key: 'pull-requests', route: PULL_REQUEST_INTAKE_ROUTE },\n { key: 'closed-completed', route: CLOSED_COMPLETED_ROUTE },\n { key: 'closed-canceled', route: CLOSED_CANCELED_ROUTE },\n { key: 'reopened', route: REOPENED_ROUTE },\n];\n\n/** The defaults a project whose lock row predates `seeded_defaults` was set up with. */\nconst ORIGINAL_DEFAULT_KEYS = ['outside-authors'];\n\n/** Who the default intake routes are created and last updated by. */\nexport const DEFAULT_INTAKE_ROUTE_ACTOR = 'factory';\n\nexport class StoredBoardError extends Error {\n override name = 'StoredBoardError';\n constructor(\n readonly code: StoredBoardErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface BoardRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface VersionRow extends Record<string, unknown> {\n version: string;\n /** Keys of the boards Factory stored in the project; null on rows written before the list. */\n seeded_boards: string[] | null;\n}\n\ninterface PhaseRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n phase_key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n next_phases: string[] | null;\n auto_start: boolean;\n auto_start_when: RuleGroup | null;\n exit_tool: StoredPhaseExitTool | null;\n}\n\ninterface IntakeRouteRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n name: string;\n enabled: boolean;\n position: number;\n when_condition: RuleGroup | null;\n board_key: string;\n phase_key: string | null;\n /** Null on rows written before routes named events: they place new cards. */\n on_events: StatusEvent[] | null;\n allow_working_phase: boolean | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface IntakeRouteLockRow extends Record<string, unknown> {\n /** Keys of the `DEFAULT_INTAKE_ROUTES` added to the project; null on rows written before the list. */\n seeded_defaults: string[] | null;\n}\n\nfunction seededDefaults(lock: IntakeRouteLockRow): string[] {\n return lock.seeded_defaults ?? ORIGINAL_DEFAULT_KEYS;\n}\n\nfunction missingDefaults(lock: IntakeRouteLockRow): (typeof DEFAULT_INTAKE_ROUTES)[number][] {\n const seeded = new Set(seededDefaults(lock));\n return DEFAULT_INTAKE_ROUTES.filter(({ key }) => !seeded.has(key));\n}\n\nconst BOARDS = 'factory_boards';\nconst PHASES = 'factory_board_phases';\nconst VERSIONS = 'factory_board_definition_versions';\nconst INTAKE_ROUTES = 'factory_intake_routes';\nconst INTAKE_ROUTE_LOCKS = 'factory_intake_route_locks';\nconst MAX_WRITE_ATTEMPTS = 3;\n\nfunction scopeWhere({ orgId, factoryProjectId }: StoredBoardScope) {\n return { org_id: orgId, factory_project_id: factoryProjectId };\n}\n\nfunction toPhaseRecord(row: PhaseRow): StoredPhaseRecord {\n return {\n key: row.phase_key,\n position: row.position,\n name: row.name,\n description: row.description,\n kind: row.kind,\n runner: row.runner,\n nextPhases: row.next_phases,\n autoStart: row.auto_start,\n autoStartWhen: row.auto_start_when,\n exitTool: row.exit_tool,\n };\n}\n\nfunction toRecord(row: BoardRow, phases: PhaseRow[]): StoredBoardRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n key: row.board_key,\n name: row.name,\n description: row.description,\n position: row.position,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n phases: phases.sort((left, right) => left.position - right.position).map(toPhaseRecord),\n };\n}\n\n/** A compare-and-set inside a write lost to a concurrent writer; the write is retried from fresh reads. */\nclass ConcurrentBoardWrite extends Error {}\n\n/**\n * Each project's boards and their ordered phases. Every write runs in one transaction that also\n * replaces the project's row in `factory_board_definition_versions`, so caches on other\n * replicas can detect it.\n */\nexport class StoredBoardsStorage extends FactoryStorageDomain {\n constructor() {\n super('boards');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n FACTORY_BOARDS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany(PHASES, {});\n await this.ops.deleteMany(BOARDS, {});\n await this.ops.deleteMany(VERSIONS, {});\n await this.ops.deleteMany(INTAKE_ROUTES, {});\n await this.ops.deleteMany(INTAKE_ROUTE_LOCKS, {});\n }\n\n /** The project's current definition version; null before its first board write. */\n async readVersion(scope: StoredBoardScope): Promise<string | null> {\n return readVersion(this.ops, scope);\n }\n\n /** The project's boards in order. */\n async list(scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n return readBoards(this.ops, scope);\n }\n\n /**\n * The version and the boards, read in that order: a write landing between the two reads leaves a\n * version older than the rows, so a cache keyed on it rereads on its next check instead of\n * keeping the stale rows.\n */\n async snapshot(scope: StoredBoardScope): Promise<StoredBoardSnapshot> {\n const version = await readVersion(this.ops, scope);\n return { version, boards: await this.list(scope) };\n }\n\n async get(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord | null> {\n const row = await this.ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) return null;\n const phases = await this.ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: key });\n return toRecord(row, phases);\n }\n\n /** Creates a board through the API. */\n async create(scope: StoredBoardScope, input: StoredBoardInput, actor: string): Promise<StoredBoardRecord> {\n await ensureVersionRow(this.ops, scope);\n try {\n return await this.#write(scope, async ops => {\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n if (rows.some(row => row.board_key === input.key)) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n await insertBoard(ops, scope, input, { position: nextPosition(rows), actor });\n return { result: undefined, changed: true };\n }).then(async () => (await this.get(scope, input.key))!);\n } catch (error) {\n // Only the board key's index means the board exists; a lost race on another table is not that.\n if (error instanceof UniqueViolationError && error.collection === BOARDS) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n throw error;\n }\n }\n\n /** Replaces a board's name, description and phases. The board key never changes. */\n async replace(\n scope: StoredBoardScope,\n key: string,\n input: Omit<StoredBoardInput, 'key'>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { key, ...input }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /**\n * Stores Factory's boards (Work, app and seed boards) in the project, each key once: a key the\n * project has had before is skipped even if its board was deleted since, and a stored board is\n * never rewritten. A project stored before the list was kept counts the boards it has as stored.\n * Reads one row when every key was stored before. Returns the keys it inserted.\n */\n async seedBoards(scope: StoredBoardScope, boards: readonly StoredBoardInput[]): Promise<string[]> {\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.seeded_boards && boards.every(board => marker.seeded_boards!.includes(board.key))) return [];\n return this.#insertOnce(scope, boards, { actor: DEFAULT_INTAKE_ROUTE_ACTOR, skipSeeded: true });\n }\n\n /**\n * Inserts a board into the project unless one is stored under its key, and records the key as\n * stored, so seeding never adds it again. Unlike seeding, it inserts a key the project deleted.\n * Returns whether it inserted the board.\n */\n async insertIfMissing(scope: StoredBoardScope, board: StoredBoardInput, actor: string): Promise<boolean> {\n return (await this.#insertOnce(scope, [board], { actor, skipSeeded: false })).length > 0;\n }\n\n async #insertOnce(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: { actor: string; skipSeeded: boolean },\n ): Promise<string[]> {\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const marker = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n const present = new Set(rows.map(row => row.board_key));\n const seeded = new Set(marker.seeded_boards ?? present);\n let position = nextPosition(rows);\n const inserted: string[] = [];\n for (const board of boards) {\n if (present.has(board.key) || (options.skipSeeded && seeded.has(board.key))) continue;\n await insertBoard(ops, scope, board, { position: position++, actor: options.actor });\n present.add(board.key);\n inserted.push(board.key);\n }\n const next = [...new Set([...seeded, ...boards.map(board => board.key)])];\n const unchanged = marker.seeded_boards !== null && next.length === marker.seeded_boards.length;\n if (inserted.length === 0 && unchanged) return inserted;\n // Compare-and-set on the version, and every marker write takes a new one: two replicas\n // recording different keys can't both match the version they read, so neither key is lost.\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: marker.version },\n {\n seeded_boards: next,\n version: randomUUID(),\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return inserted;\n });\n }\n\n /** Rewrites a board to `definition` (Factory's current one for its key), raising its revision. */\n async resetTo(\n scope: StoredBoardScope,\n key: string,\n definition: StoredBoardInput,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { ...definition, key }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /** Deletes a board and its phases. */\n async delete(scope: StoredBoardScope, key: string, options: { expectedRevision: number }): Promise<void> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n if ((await ops.deleteMany(BOARDS, { id: row.id, revision: row.revision })) === 0)\n throw new ConcurrentBoardWrite();\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: key });\n return { result: undefined, changed: true };\n });\n }\n\n /** The project's intake routes in the order they are tried; Factory's `DEFAULT_INTAKE_ROUTES` are added once each. */\n async listIntakeRoutes(scope: StoredBoardScope): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n return (await readIntakeRoutes(this.ops, scope)).map(toIntakeRouteRecord);\n }\n\n async getIntakeRoute(scope: StoredBoardScope, id: string): Promise<StoredIntakeRouteRecord | null> {\n const row = await this.ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n return row ? toIntakeRouteRecord(row) : null;\n }\n\n /** Adds a route after the project's last one. */\n async createIntakeRoute(\n scope: StoredBoardScope,\n input: StoredIntakeRouteInput,\n actor: string,\n ): Promise<StoredIntakeRouteRecord> {\n const id = randomUUID();\n checkRouteEvents(input.on ?? DEFAULT_ROUTE_EVENTS, input.when ?? null);\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n if (rows.length >= MAX_INTAKE_ROUTES) {\n throw new StoredBoardError(\n 'intake_route_limit',\n `A project can have at most ${MAX_INTAKE_ROUTES} intake routes; delete one first.`,\n );\n }\n await insertIntakeRoute(ops, scope, {\n id,\n input,\n position: rows.reduce((max, row) => Math.max(max, row.position), -1) + 1,\n actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Changes the fields `patch` names; the route keeps its place in the order. */\n async updateIntakeRoute(\n scope: StoredBoardScope,\n id: string,\n patch: Partial<StoredIntakeRouteInput>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredIntakeRouteRecord> {\n await this.#transact(async ops => {\n const row = await findIntakeRoute(ops, scope, id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n checkRouteEvents(patch.on ?? routeEvents(row), patch.when !== undefined ? patch.when : row.when_condition);\n await updateIntakeRouteRow(ops, row, {\n ...(patch.on !== undefined && { on_events: patch.on }),\n ...(patch.allowWorkingPhase !== undefined && { allow_working_phase: patch.allowWorkingPhase }),\n ...(patch.name !== undefined && { name: patch.name }),\n ...(patch.enabled !== undefined && { enabled: patch.enabled }),\n ...(patch.when !== undefined && { when_condition: patch.when }),\n ...(patch.target !== undefined && {\n board_key: patch.target.boardKey,\n phase_key: patch.target.phaseKey ?? null,\n }),\n updated_by: options.actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Deletes a route; the routes after it move up one place. */\n async deleteIntakeRoute(scope: StoredBoardScope, id: string, options: { expectedRevision: number }): Promise<void> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const row = rows.find(route => route.id === id);\n if (!row) throw intakeRouteNotFound(id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n if ((await ops.deleteMany(INTAKE_ROUTES, { id: row.id, revision: row.revision })) === 0) {\n throw new ConcurrentBoardWrite();\n }\n await placeIntakeRoutes(\n ops,\n rows.filter(route => route.id !== row.id),\n );\n });\n }\n\n /** Puts the project's routes in the order of `ids`, which must name every route exactly once. */\n async reorderIntakeRoutes(scope: StoredBoardScope, ids: string[], actor: string): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const byId = new Map(rows.map(row => [row.id, row]));\n if (ids.length !== rows.length || new Set(ids).size !== ids.length || ids.some(id => !byId.has(id))) {\n throw new StoredBoardError(\n 'intake_route_set_mismatch',\n 'The order must list every intake route of the project exactly once; reload the routes and try again.',\n );\n }\n await placeIntakeRoutes(\n ops,\n ids.map(id => byId.get(id)!),\n actor,\n );\n });\n return this.listIntakeRoutes(scope);\n }\n\n /**\n * Creates the project's route lock row (see `FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA`) and adds each of\n * `DEFAULT_INTAKE_ROUTES` the row doesn't list as added yet, after the project's routes. The row\n * records every default it added, so a project whose admin deleted one doesn't get it back. Runs\n * before, never inside, a write's transaction: the lock taken there must always be an update.\n */\n async #ensureIntakeRoutes(scope: StoredBoardScope): Promise<void> {\n const lock = await this.ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope));\n if (lock && missingDefaults(lock).length === 0) return;\n await this.#transact(async ops => {\n if (await ops.findOne(INTAKE_ROUTE_LOCKS, scopeWhere(scope))) await lockIntakeRoutes(ops, scope);\n // A racing first read inserted the lock row first: this one fails on the unique index and\n // retries, taking the lock above.\n else\n await ops.insertOne(INTAKE_ROUTE_LOCKS, { ...scopeWhere(scope), locked_at: new Date(), seeded_defaults: [] });\n // Read under the lock: a racing seeder that committed first already added what it listed.\n const current = (await ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope)))!;\n const missing = missingDefaults(current);\n if (missing.length === 0) return;\n const rows = await readIntakeRoutes(ops, scope);\n let position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n for (const { route } of missing) {\n // A project at the limit keeps its own routes; the default counts as added all the same.\n if (position >= MAX_INTAKE_ROUTES) break;\n await insertIntakeRoute(ops, scope, {\n id: randomUUID(),\n input: route,\n position: position++,\n actor: DEFAULT_INTAKE_ROUTE_ACTOR,\n });\n }\n await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), {\n seeded_defaults: [...seededDefaults(current), ...missing.map(({ key }) => key)],\n });\n });\n }\n\n /**\n * Runs `fn` in a transaction and replaces the project's version when it changed anything.\n * Lost races (a compare-and-set miss, or a concurrent write that inserted the same board or the\n * project's first version row) retry from fresh reads.\n */\n async #write<T>(\n scope: StoredBoardScope,\n fn: (ops: FactoryStorageOps) => Promise<{ result: T; changed: boolean }>,\n ): Promise<T> {\n return this.#transact(async ops => {\n const { result, changed } = await fn(ops);\n if (changed) await bumpVersion(ops, scope);\n return result;\n });\n }\n\n /**\n * Runs `fn` in a transaction, retrying lost races from fresh reads. Intake route writes use it\n * directly: routes are read uncached, so they leave the board definition version alone.\n */\n async #transact<T>(fn: (ops: FactoryStorageOps) => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n // Read committed is enough: every row change is a compare-and-set on `revision` and every\n // insert meets the unique index. Serializable isolation would also fail writes to\n // unrelated projects that replicas run side by side.\n return await this.storage.withTransaction(fn);\n } catch (error) {\n const retryable = error instanceof ConcurrentBoardWrite || error instanceof UniqueViolationError;\n if (!retryable || attempt >= MAX_WRITE_ATTEMPTS) throw error;\n }\n }\n }\n}\n\nasync function readVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<string | null> {\n const row = await ops.findOne<{ version: string }>(VERSIONS, scopeWhere(scope));\n return row?.version ?? null;\n}\n\nasync function readBoards(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n const [rows, phases] = await Promise.all([\n ops.findMany<BoardRow>(BOARDS, scopeWhere(scope)),\n ops.findMany<PhaseRow>(PHASES, scopeWhere(scope)),\n ]);\n const byBoard = new Map<string, PhaseRow[]>();\n for (const phase of phases) {\n const list = byBoard.get(phase.board_key) ?? [];\n list.push(phase);\n byBoard.set(phase.board_key, list);\n }\n return rows\n .sort((left, right) => left.position - right.position || left.board_key.localeCompare(right.board_key))\n .map(row => toRecord(row, byBoard.get(row.board_key) ?? []));\n}\n\n/**\n * Inserts the project's version row if it has none. This runs outside the write transaction: on\n * Postgres, two transactions racing to insert it would leave the loser's transaction aborted, so\n * the version bump inside a write must always be an update.\n */\nasync function ensureVersionRow(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n if (await ops.findOne(VERSIONS, scopeWhere(scope))) return;\n try {\n await ops.insertOne(VERSIONS, { ...scopeWhere(scope), version: randomUUID(), updated_at: new Date() });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n}\n\nasync function bumpVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n await ops.upsertOne(VERSIONS, ['org_id', 'factory_project_id'], {\n ...scopeWhere(scope),\n version: randomUUID(),\n updated_at: new Date(),\n });\n}\n\nasync function findBoard(ops: FactoryStorageOps, scope: StoredBoardScope, key: string): Promise<BoardRow> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) {\n throw new StoredBoardError('board_not_found', `Board \"${key}\" does not exist in this project.`);\n }\n return row;\n}\n\nfunction checkRevision(row: BoardRow, key: string, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Board \"${key}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\nfunction nextPosition(rows: BoardRow[]): number {\n return rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n}\n\n/** Sets columns on a board row and raises its revision, unless another writer changed it first. */\nasync function updateRow(ops: FactoryStorageOps, row: BoardRow, set: Partial<BoardRow>): Promise<void> {\n const updated = await ops.updateMany(\n BOARDS,\n { id: row.id, revision: row.revision },\n { ...set, revision: row.revision + 1, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n}\n\nasync function insertPhases(ops: FactoryStorageOps, scope: StoredBoardScope, input: StoredBoardInput): Promise<void> {\n for (const [position, phase] of input.phases.entries()) {\n await ops.insertOne<PhaseRow>(PHASES, {\n ...scopeWhere(scope),\n board_key: input.key,\n phase_key: phase.key,\n position,\n name: phase.name,\n description: phase.description ?? null,\n kind: phase.kind,\n runner: phase.runner ?? null,\n next_phases: phase.nextPhases ?? null,\n auto_start: phase.autoStart ?? false,\n auto_start_when: phase.autoStartWhen ?? null,\n exit_tool: phase.exitTool ?? null,\n });\n }\n}\n\nasync function insertBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n input: StoredBoardInput,\n options: { position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<BoardRow>(BOARDS, {\n ...scopeWhere(scope),\n board_key: input.key,\n name: input.name,\n description: input.description ?? null,\n position: options.position,\n revision: 1,\n created_by: options.actor,\n created_at: now,\n updated_by: options.actor,\n updated_at: now,\n });\n await insertPhases(ops, scope, input);\n}\n\n/** Replaces a board's definition and phases in place, keeping its key, position and history. */\nasync function writeBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n row: BoardRow,\n input: StoredBoardInput,\n actor: string,\n): Promise<void> {\n await updateRow(ops, row, { name: input.name, description: input.description ?? null, updated_by: actor });\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n await insertPhases(ops, scope, { ...input, key: row.board_key });\n}\n\nfunction routeEvents(row: IntakeRouteRow): StatusEvent[] {\n return row.on_events ?? [...DEFAULT_ROUTE_EVENTS];\n}\n\nfunction checkRouteEvents(on: readonly string[], when: RuleGroup | null): void {\n const problem = routeEventsProblem(on, when);\n if (problem) throw new StoredBoardError('invalid_intake_route', problem);\n}\n\nfunction toIntakeRouteRecord(row: IntakeRouteRow): StoredIntakeRouteRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n name: row.name,\n enabled: row.enabled,\n position: row.position,\n when: row.when_condition,\n target: { boardKey: row.board_key, phaseKey: row.phase_key },\n on: routeEvents(row),\n allowWorkingPhase: row.allow_working_phase ?? false,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n };\n}\n\nasync function readIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n const rows = await ops.findMany<IntakeRouteRow>(INTAKE_ROUTES, scopeWhere(scope));\n return rows.sort((left, right) => left.position - right.position);\n}\n\nasync function findIntakeRoute(ops: FactoryStorageOps, scope: StoredBoardScope, id: string): Promise<IntakeRouteRow> {\n const row = await ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n if (!row) throw intakeRouteNotFound(id);\n return row;\n}\n\nfunction intakeRouteNotFound(id: string): StoredBoardError {\n return new StoredBoardError('intake_route_not_found', `Intake route \"${id}\" does not exist in this project.`);\n}\n\nfunction checkIntakeRouteRevision(row: IntakeRouteRow, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Intake route \"${row.name}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\n/** Sets columns on a route row and raises its revision, unless another writer changed it first. */\nasync function updateIntakeRouteRow(\n ops: FactoryStorageOps,\n row: IntakeRouteRow,\n set: Partial<IntakeRouteRow>,\n): Promise<number> {\n const revision = row.revision + 1;\n const updated = await ops.updateMany(\n INTAKE_ROUTES,\n { id: row.id, revision: row.revision },\n { ...set, revision, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return revision;\n}\n\nasync function insertIntakeRoute(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n route: { id: string; input: StoredIntakeRouteInput; position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<IntakeRouteRow>(INTAKE_ROUTES, {\n id: route.id,\n ...scopeWhere(scope),\n name: route.input.name,\n enabled: route.input.enabled ?? true,\n position: route.position,\n when_condition: route.input.when ?? null,\n board_key: route.input.target.boardKey,\n phase_key: route.input.target.phaseKey ?? null,\n on_events: route.input.on ?? null,\n allow_working_phase: route.input.allowWorkingPhase ?? false,\n revision: 1,\n created_by: route.actor,\n created_at: now,\n updated_by: route.actor,\n updated_at: now,\n });\n}\n\n/**\n * Takes the project's route lock and reads the routes. Writes that add, delete or move routes\n * call this first, so they run one after another and each reads what the one before committed.\n */\nasync function lockIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n if ((await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), { locked_at: new Date() })) !== 1) {\n throw new ConcurrentBoardWrite();\n }\n return readIntakeRoutes(ops, scope);\n}\n\n/** Moves routes, read under the project's route lock, to the positions of their order in `rows`. */\nasync function placeIntakeRoutes(ops: FactoryStorageOps, rows: IntakeRouteRow[], actor?: string): Promise<void> {\n const moving = rows.flatMap((row, position) => (row.position === position ? [] : [{ row, position }]));\n const parked = [];\n for (const [index, { row, position }] of moving.entries()) {\n const revision = await updateIntakeRouteRow(ops, row, {\n position: -(index + 1),\n ...(actor !== undefined && { updated_by: actor }),\n });\n parked.push({ id: row.id, revision, position });\n }\n for (const { id, revision, position } of parked) {\n if ((await ops.updateMany(INTAKE_ROUTES, { id, revision }, { position })) !== 1) throw new ConcurrentBoardWrite();\n }\n}\n"],"mappings":";;;;;;AA4IA,MAAa,oBAAoB;;;;;;AAOjC,MAAa,uBAA+C;CAC1D,MAAM;CACN,MAAM;EACJ,UAAU;EACV,YAAY,CACV;GAAE,OAAO;GAAsB,UAAU;GAAM,OAAO,CAAC,UAAU,QAAQ;EAAE,GAC3E;GAAE,OAAO;GAAkB,UAAU;GAAU,OAAO;EAAM,CAC9D;CACF;CACA,QAAQ;EAAE,UAAU;EAAQ,UAAU;CAAS;AACjD;;;;;AAMA,MAAa,4BAAoD;CAC/D,MAAM;CACN,MAAM;EAAE,UAAU;EAAO,YAAY,CAAC;GAAE,OAAO;GAAe,UAAU;GAAU,OAAO;EAAe,CAAC;CAAE;CAC3G,QAAQ;EAAE,UAAU;EAAQ,UAAU;CAAY;AACpD;;AAGA,MAAa,yBAAiD;CAC5D,MAAM;CACN,IAAI,CAAC,kBAAkB;CACvB,MAAM;EAAE,UAAU;EAAO,YAAY,CAAC;GAAE,OAAO;GAAgB,UAAU;GAAU,OAAO;EAAY,CAAC;CAAE;CACzG,QAAQ;EAAE,UAAU;EAAQ,UAAU;CAAO;AAC/C;;AAGA,MAAa,wBAAgD;CAC3D,MAAM;CACN,IAAI,CAAC,kBAAkB;CACvB,MAAM;EAAE,UAAU;EAAO,YAAY,CAAC;GAAE,OAAO;GAAgB,UAAU;GAAU,O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MAAM,iCAAiC,EAAE,gBAY/C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wCAAwC,EAAE,gBAUtD,CAAC"}
1
+ {"version":3,"file":"schemas.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/boards/schemas.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAE7D,sFAAsF;AACtF,eAAO,MAAM,qBAAqB,EAAE,gBAmBnC,CAAC;AAEF,0EAA0E;AAC1E,eAAO,MAAM,2BAA2B,EAAE,gBA0BzC,CAAC;AAEF,yFAAyF;AACzF,eAAO,MAAM,4BAA4B,EAAE,gBA8B1C,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,EAAE,gBAY/C,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,wCAAwC,EAAE,gBAatD,CAAC"}
@@ -105,6 +105,14 @@ const FACTORY_INTAKE_ROUTES_SCHEMA = {
105
105
  type: "text",
106
106
  nullable: true
107
107
  },
108
+ on_events: {
109
+ type: "json",
110
+ nullable: true
111
+ },
112
+ allow_working_phase: {
113
+ type: "boolean",
114
+ nullable: true
115
+ },
108
116
  revision: { type: "integer" },
109
117
  created_by: { type: "text" },
110
118
  created_at: { type: "timestamp" },
@@ -157,7 +165,11 @@ const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA = {
157
165
  org_id: { type: "text" },
158
166
  factory_project_id: { type: "text" },
159
167
  version: { type: "text" },
160
- updated_at: { type: "timestamp" }
168
+ updated_at: { type: "timestamp" },
169
+ seeded_boards: {
170
+ type: "json",
171
+ nullable: true
172
+ }
161
173
  },
162
174
  uniqueIndexes: [{
163
175
  name: "factory_board_definition_versions_project",
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.js","names":[],"sources":["../../../../src/storage/domains/boards/schemas.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\n/** A project's boards. `board_key` is the id cards reference (`work_items.board`). */\nexport const FACTORY_BOARDS_SCHEMA: CollectionSchema = {\n name: 'factory_boards',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n position: { type: 'integer' },\n // Rises on every write to the board or its phases; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_boards_project_key', columns: ['org_id', 'factory_project_id', 'board_key'] }],\n indexes: [{ name: 'factory_boards_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A board's ordered phases. `phase_key` is the stage id cards sit in. */\nexport const FACTORY_BOARD_PHASES_SCHEMA: CollectionSchema = {\n name: 'factory_board_phases',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n phase_key: { type: 'text' },\n position: { type: 'integer' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n kind: { type: 'text' },\n // { skill?, context?, instructions? }; room for other runner types later.\n runner: { type: 'json', nullable: true },\n next_phases: { type: 'json', nullable: true },\n auto_start: { type: 'boolean', default: false },\n auto_start_when: { type: 'json', nullable: true },\n exit_tool: { type: 'json', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_board_phases_project_board_phase',\n columns: ['org_id', 'factory_project_id', 'board_key', 'phase_key'],\n },\n ],\n indexes: [{ name: 'factory_board_phases_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project's ordered intake routes: where new cards matching `when_condition` land. */\nexport const FACTORY_INTAKE_ROUTES_SCHEMA: CollectionSchema = {\n name: 'factory_intake_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n name: { type: 'text' },\n enabled: { type: 'boolean', default: true },\n position: { type: 'integer' },\n // A card RuleGroup; null matches every card. Not named `when`, which is an SQL keyword.\n when_condition: { type: 'json', nullable: true },\n board_key: { type: 'text' },\n // Null lands the card in the board's first phase.\n phase_key: { type: 'text', nullable: true },\n // Rises on every write to the route, including a move; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_intake_routes_project_position', columns: ['org_id', 'factory_project_id', 'position'] },\n ],\n indexes: [{ name: 'factory_intake_routes_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project that every write adding, deleting or moving intake routes upserts first,\n * inside its transaction. The upsert holds the row until commit, so those writes on one project\n * run one after another and positions stay 0..n-1 with no gaps.\n */\nexport const FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_intake_route_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n locked_at: { type: 'timestamp' },\n // Keys of the default routes Factory added to the project (`DEFAULT_INTAKE_ROUTES`), so each is\n // added once. Null on rows written before the list: those projects got `outside-authors`.\n seeded_defaults: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_intake_route_locks_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project whose `version` is replaced inside every board write, so other replicas\n * can tell their cached boards are stale with one indexed read.\n */\nexport const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_definition_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_board_definition_versions_project', columns: ['org_id', 'factory_project_id'] }],\n};\n"],"mappings":";;AAGA,MAAa,wBAA0C;CACrD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAA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AAe,CAAC;EAAE,MAAM;EAA6C,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AAClH"}
1
+ {"version":3,"file":"schemas.js","names":[],"sources":["../../../../src/storage/domains/boards/schemas.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\n/** A project's boards. `board_key` is the id cards reference (`work_items.board`). */\nexport const FACTORY_BOARDS_SCHEMA: CollectionSchema = {\n name: 'factory_boards',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n position: { type: 'integer' },\n // Rises on every write to the board or its phases; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_boards_project_key', columns: ['org_id', 'factory_project_id', 'board_key'] }],\n indexes: [{ name: 'factory_boards_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A board's ordered phases. `phase_key` is the stage id cards sit in. */\nexport const FACTORY_BOARD_PHASES_SCHEMA: CollectionSchema = {\n name: 'factory_board_phases',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n phase_key: { type: 'text' },\n position: { type: 'integer' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n kind: { type: 'text' },\n // { skill?, context?, instructions? }; room for other runner types later.\n runner: { type: 'json', nullable: true },\n next_phases: { type: 'json', nullable: true },\n auto_start: { type: 'boolean', default: false },\n auto_start_when: { type: 'json', nullable: true },\n exit_tool: { type: 'json', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_board_phases_project_board_phase',\n columns: ['org_id', 'factory_project_id', 'board_key', 'phase_key'],\n },\n ],\n indexes: [{ name: 'factory_board_phases_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project's ordered intake routes: where new cards matching `when_condition` land. */\nexport const FACTORY_INTAKE_ROUTES_SCHEMA: CollectionSchema = {\n name: 'factory_intake_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n name: { type: 'text' },\n enabled: { type: 'boolean', default: true },\n position: { type: 'integer' },\n // A card RuleGroup; null matches every card. Not named `when`, which is an SQL keyword.\n when_condition: { type: 'json', nullable: true },\n board_key: { type: 'text' },\n // Null lands the card in the board's first phase.\n phase_key: { type: 'text', nullable: true },\n // The status events the route handles (`StatusEvent`s). Null on rows written before routes named\n // events: those place new cards, as `['work_item.created']`.\n on_events: { type: 'json', nullable: true },\n // Lets an event move an existing card into a working phase. Null on older rows: off.\n allow_working_phase: { type: 'boolean', nullable: true },\n // Rises on every write to the route, including a move; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_intake_routes_project_position', columns: ['org_id', 'factory_project_id', 'position'] },\n ],\n indexes: [{ name: 'factory_intake_routes_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project that every write adding, deleting or moving intake routes upserts first,\n * inside its transaction. The upsert holds the row until commit, so those writes on one project\n * run one after another and positions stay 0..n-1 with no gaps.\n */\nexport const FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_intake_route_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n locked_at: { type: 'timestamp' },\n // Keys of the default routes Factory added to the project (`DEFAULT_INTAKE_ROUTES`), so each is\n // added once. Null on rows written before the list: those projects got `outside-authors`.\n seeded_defaults: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_intake_route_locks_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project whose `version` is replaced inside every board write, so other replicas\n * can tell their cached boards are stale with one indexed read.\n */\nexport const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_definition_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n // Keys of the boards Factory stored in the project (Work, app and seed boards); each is stored\n // once, so one the project deleted stays deleted. Null on projects stored before the list.\n seeded_boards: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_definition_versions_project', columns: ['org_id', 'factory_project_id'] }],\n};\n"],"mappings":";;AAGA,MAAa,wBAA0C;CACrD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAAW,EAAE,MAAM,OAAO;EAC1B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,UAAU,EAAE,MAAM,UAAU;EAE5B,UAAU,EAAE,MAAM,UAAU;EAC5B,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;CAClC;CACA,eAAe,CAAC;EAAE,MAAM;EAA8B,SAAS;GAAC;GAAU;GAAsB;EAAW;CAAE,CAAC;CAC9G,SAAS,CAAC;EAAE,MAAM;EAA0B,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AACzF;;AAGA,MAAa,8BAAgD;CAC3D,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAAW,EAAE,MAAM,OAAO;EAC1B,WAAW,EAAE,MAAM,OAAO;EAC1B,UAAU,EAAE,MAAM,U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AwB,GAAG,QAAQ,EAAE,CAqSrF"}
@@ -1,5 +1,6 @@
1
1
  import { getFactoryAuthUser } from "../../../auth.js";
2
2
  import { feedTopic } from "../../../feed-events.js";
3
+ import { loose } from "../../../routes/route.js";
3
4
  import { actorFromAuthUser } from "./actor.js";
4
5
  import { decodeCommentCursor } from "./base.js";
5
6
  import { UUID_RE, isRecord, parseCreateCommentBody, parseEditCommentBody, readJson } from "./parse.js";
@@ -16,9 +17,6 @@ import { streamSSE } from "hono/streaming";
16
17
  const MAX_AUDIT_BODY_SNAPSHOT = 1024;
17
18
  /** Comment frames only — proxies drop an idle stream, and `write` can't detect a dead peer. */
18
19
  const FEED_KEEPALIVE_MS = 25e3;
19
- function loose(c) {
20
- return c;
21
- }
22
20
  function buildCommentRoutes(dependencies) {
23
21
  const { domain, auth, comments, workItems, projects, pubsub, audit } = dependencies;
24
22
  async function resolveTenant(c) {
@@ -1 +1 @@
1
- {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/storage/domains/comments/routes.ts"],"sourcesContent":["/**\n * HTTP for the item feed. Every handler is the same shape: resolve the tenant,\n * validate the path ids, delegate to a `CommentsDomain` service method, map its\n * result status to a status code, then emit audit.\n */\n\nimport { withAck } from '@mastra/core/events';\nimport type { EventCallback, PubSub } from '@mastra/core/events';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { streamSSE } from 'hono/streaming';\n\nimport { getFactoryAuthUser } from '../../../auth.js';\nimport { feedTopic } from '../../../feed-events.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { AuditEmitter } from '../audit/domain.js';\nimport type { FactoryProjectsStorage } from '../projects/base.js';\nimport type { WorkItemsStorage } from '../work-items/base.js';\nimport { actorFromAuthUser } from './actor.js';\nimport type { WorkItemCommentsStorage } from './base.js';\nimport { decodeCommentCursor } from './base.js';\nimport type { CommentEditor, CommentsDomain } from './domain.js';\nimport { isRecord, parseCreateCommentBody, parseEditCommentBody, readJson, UUID_RE } from './parse.js';\nimport { toWireComment } from './wire.js';\nimport type { WireCommentPage } from './wire.js';\n\nconst MAX_AUDIT_BODY_SNAPSHOT = 1024;\n/** Comment frames only — proxies drop an idle stream, and `write` can't detect a dead peer. */\nconst FEED_KEEPALIVE_MS = 25_000;\n// Ceiling: one broker subscription per open tab, not per project. A per-replica\n// topic multiplexer is the upgrade path if tab counts ever make that hurt.\n\nexport interface CommentRouteDependencies {\n domain: CommentsDomain;\n auth: RouteAuth;\n comments: WorkItemCommentsStorage;\n workItems: WorkItemsStorage;\n projects: FactoryProjectsStorage;\n pubsub: PubSub;\n audit?: AuditEmitter;\n}\n\ninterface Tenant {\n orgId: string;\n userId: string;\n}\n\nfunction loose(c: unknown): Context {\n return c as Context;\n}\n\nexport function buildCommentRoutes(dependencies: CommentRouteDependencies): ApiRoute[] {\n const { domain, auth, comments, workItems, projects, pubsub, audit } = dependencies;\n\n async function resolveTenant(c: Context): Promise<Tenant | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json({ error: 'organization_required', message: 'The item feed requires an organization.' }, 403),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n function editorFor(c: Context, tenant: Tenant): CommentEditor {\n return {\n userId: tenant.userId,\n canModerate: () => auth.isOrganizationAdmin(c, tenant.orgId),\n };\n }\n\n async function emitMentionAudit(\n c: Context,\n target: { factoryProjectId: string; workItemId: string; title?: string },\n commentId: string,\n mentionedIds: string[],\n ): Promise<void> {\n if (mentionedIds.length === 0) return;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_mentioned',\n factoryProjectId: target.factoryProjectId,\n targets: [{ type: 'work_item', id: target.workItemId, ...(target.title ? { name: target.title } : {}) }],\n metadata: { commentId, mentionedIds },\n },\n });\n }\n\n return [\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n await workItems.ensureReady();\n const workItem = await workItems.get({ orgId: tenant.orgId, id: workItemId });\n if (!workItem) return c.json({ error: 'Work item not found' }, 404);\n\n await comments.ensureReady();\n const limitRaw = c.req.query('limit');\n const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;\n const before = c.req.query('before') || undefined;\n if (before && !decodeCommentCursor(before)) return c.json({ error: 'invalid_cursor' }, 422);\n const around = c.req.query('around') || undefined;\n if (around && !UUID_RE.test(around)) return c.json({ error: 'invalid_comment_id' }, 422);\n const page = await comments.list({\n orgId: tenant.orgId,\n factoryProjectId: workItem.factoryProjectId,\n workItemId,\n before,\n ...(around ? { around } : {}),\n ...(limit !== undefined && Number.isFinite(limit) ? { limit } : {}),\n });\n const wirePage: WireCommentPage = {\n comments: page.comments.map(comment => toWireComment(comment, tenant.userId)),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n };\n return c.json(wirePage);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'POST',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n\n const parsed = parseCreateCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.createComment({\n orgId: tenant.orgId,\n workItemId,\n author: actorFromAuthUser(tenant.userId, getFactoryAuthUser(c)),\n body: parsed.body,\n ...(parsed.replyTo ? { replyTo: parsed.replyTo } : {}),\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.clientToken ? { clientToken: parsed.clientToken } : {}),\n });\n if (result.status === 'work_item_not_found') return c.json({ error: 'Work item not found' }, 404);\n if (result.status === 'token_conflict') return c.json({ error: 'comment_token_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment, workItem } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_created',\n factoryProjectId: workItem.factoryProjectId,\n targets: [{ type: 'work_item', id: workItem.id, name: workItem.title }],\n metadata: { commentId: comment.id },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: workItem.factoryProjectId, workItemId: workItem.id, title: workItem.title },\n comment.id,\n comment.mentions.map(mention => mention.id).filter(id => id !== comment.author.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) }, 201);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'PATCH',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const parsed = parseEditCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.editComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n body: parsed.body,\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.expectedRevision !== undefined ? { expectedRevision: parsed.expectedRevision } : {}),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n if (result.status === 'conflict') return c.json({ error: 'comment_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_edited',\n factoryProjectId: comment.factoryProjectId,\n targets: [{ type: 'work_item', id: comment.workItemId }],\n metadata: {\n commentId: comment.id,\n previousBody: result.previousBody.slice(0, MAX_AUDIT_BODY_SNAPSHOT),\n },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: comment.factoryProjectId, workItemId: comment.workItemId },\n comment.id,\n result.addedMentions.map(mention => mention.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'DELETE',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const result = await domain.deleteComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_deleted',\n factoryProjectId: result.comment.factoryProjectId,\n targets: [{ type: 'work_item', id: result.comment.workItemId }],\n metadata: { commentId: result.comment.id },\n },\n });\n return c.json({ comment: toWireComment(result.comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/mention-roster', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n await comments.ensureReady();\n const roster = await domain.mentionRoster({ orgId: tenant.orgId, factoryProjectId: projectId });\n const query = c.req.query('q')?.trim().toLowerCase();\n const members = query\n ? roster.filter(member => (member.name ?? member.id).toLowerCase().startsWith(query))\n : roster;\n return c.json({ members });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/feed-events', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n const topic = feedTopic(tenant.orgId, projectId);\n return streamSSE(c, async stream => {\n // `withAck` settles every delivery: on a durable broker (Redis\n // Streams) an unacked event stays in the subscription's pending set\n // and in the broker client's in-flight bookkeeping for the life of\n // this connection — a leak that grows with every feed touch on\n // long-lived dashboard tabs. Feed frames are fire-and-forget\n // invalidations, so a delivery is acked even when the tab is gone.\n const onEvent: EventCallback = withAck(async event => {\n if (stream.aborted) return;\n const data = event.data;\n const workItemId = isRecord(data) && typeof data.workItemId === 'string' ? data.workItemId : undefined;\n try {\n await stream.writeSSE({ event: 'feed', data: JSON.stringify(workItemId ? { workItemId } : {}) });\n } catch {\n // A write to a half-closed socket must not reach `withAck` as a\n // rejection: the nack would republish the event to the shared\n // feed topic, duplicating the invalidation for every tab.\n }\n });\n // Claimed before any await: `onAbort` handlers registered after the\n // reader is gone never run, and a broker subscribe is a round trip.\n const closed = new Promise<void>(resolve => stream.onAbort(resolve));\n let keepalive: ReturnType<typeof setInterval> | undefined;\n try {\n // Without `latest`, a retaining broker replays its whole backlog into\n // every new connection as spurious invalidations.\n await pubsub.subscribe(topic, onEvent, { startFrom: 'latest' });\n if (!stream.aborted) {\n keepalive = setInterval(() => {\n if (stream.aborted) return;\n void stream.write(': ping\\n\\n');\n }, FEED_KEEPALIVE_MS);\n // `streamSSE` closes the stream the moment this callback returns.\n await closed;\n }\n } finally {\n clearInterval(keepalive);\n await pubsub.unsubscribe(topic, onEvent);\n }\n });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;AA2BA,MAAM,0BAA0B;;AAEhC,MAAM,oBAAoB;AAmB1B,SAAS,MAAM,GAAqB;CAClC,OAAO;AACT;AAEA,SAAgB,mBAAmB,cAAoD;CACrF,MAAM,EAAE,QAAQ,MAAM,UAAU,WAAW,UAAU,QAAQ,UAAU;CAEvE,eAAe,cAAc,GAAsD;EACjF,MAAM,KAAK,WAAW,CAAC;EACvB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;EACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KAAK;GAAE,OAAO;GAAyB,SAAS;EAA0C,GAAG,GAAG,EAC9G;EAEF,OAAO;GAAE,OAAO,OAAO;GAAO,QAAQ,OAAO;EAAO;CACtD;CAEA,SAAS,UAAU,GAAY,QAA+B;EAC5D,OAAO;GACL,QAAQ,OAAO;GACf,mBAAmB,KAAK,oBAAoB,GAAG,OAAO,KAAK;EAC7D;CACF;CAEA,eAAe,iBACb,GACA,QACA,WACA,cACe;EACf,IAAI,aAAa,WAAW,GAAG;EAC/B,MAAM,OAAO,KAAK;GAChB,SAAS;GACT,OAAO;IACL,QAAQ;IACR,kBAAkB,OAAO;IACzB,SAAS,CAAC;KAAE,MAAM;KAAa,IAAI,OAAO;KAAY,GAAI,OAAO,QAAQ,EAAE,MAAM,OAAO,MAAM,IAAI,CAAC;IAAG,CAAC;IACvG,UAAU;KAAE;KAAW;IAAa;GACtC;EACF,CAAC;CACH;CAEA,OAAO;EACL,iBAAiB,gDAAgD;GAC/D,QAAQ;GACR,SAAS,OAAM,OAAM;IACnB,MAAM,IAAI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F,MAAM,OAAO,UAAU,OAAO,SAAS,EAAE,WAAW,SAAS,CAAC;MAC9D,IAAI,CAAC,OAAO,SAAS;OACnB,YAAY,kBAAkB;QAC5B,IAAI,OAAO,SAAS;QACpB,OAAY,MAAM,YAAY;OAChC,GAAG,iBAAiB;OAEpB,MAAM;MACR;KACF,UAAU;MACR,cAAc,SAAS;MACvB,MAAM,OAAO,YAAY,OAAO,OAAO;KACzC;IACF,CAAC;GACH;EACF,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"routes.js","names":[],"sources":["../../../../src/storage/domains/comments/routes.ts"],"sourcesContent":["/**\n * HTTP for the item feed. Every handler is the same shape: resolve the tenant,\n * validate the path ids, delegate to a `CommentsDomain` service method, map its\n * result status to a status code, then emit audit.\n */\n\nimport { withAck } from '@mastra/core/events';\nimport type { EventCallback, PubSub } from '@mastra/core/events';\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { streamSSE } from 'hono/streaming';\n\nimport { getFactoryAuthUser } from '../../../auth.js';\nimport { feedTopic } from '../../../feed-events.js';\nimport { loose } from '../../../routes/route.js';\nimport type { RouteAuth } from '../../../routes/route.js';\nimport type { AuditEmitter } from '../audit/domain.js';\nimport type { FactoryProjectsStorage } from '../projects/base.js';\nimport type { WorkItemsStorage } from '../work-items/base.js';\nimport { actorFromAuthUser } from './actor.js';\nimport type { WorkItemCommentsStorage } from './base.js';\nimport { decodeCommentCursor } from './base.js';\nimport type { CommentEditor, CommentsDomain } from './domain.js';\nimport { isRecord, parseCreateCommentBody, parseEditCommentBody, readJson, UUID_RE } from './parse.js';\nimport { toWireComment } from './wire.js';\nimport type { WireCommentPage } from './wire.js';\n\nconst MAX_AUDIT_BODY_SNAPSHOT = 1024;\n/** Comment frames only — proxies drop an idle stream, and `write` can't detect a dead peer. */\nconst FEED_KEEPALIVE_MS = 25_000;\n// Ceiling: one broker subscription per open tab, not per project. A per-replica\n// topic multiplexer is the upgrade path if tab counts ever make that hurt.\n\nexport interface CommentRouteDependencies {\n domain: CommentsDomain;\n auth: RouteAuth;\n comments: WorkItemCommentsStorage;\n workItems: WorkItemsStorage;\n projects: FactoryProjectsStorage;\n pubsub: PubSub;\n audit?: AuditEmitter;\n}\n\ninterface Tenant {\n orgId: string;\n userId: string;\n}\n\nexport function buildCommentRoutes(dependencies: CommentRouteDependencies): ApiRoute[] {\n const { domain, auth, comments, workItems, projects, pubsub, audit } = dependencies;\n\n async function resolveTenant(c: Context): Promise<Tenant | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json({ error: 'organization_required', message: 'The item feed requires an organization.' }, 403),\n };\n }\n return { orgId: tenant.orgId, userId: tenant.userId };\n }\n\n function editorFor(c: Context, tenant: Tenant): CommentEditor {\n return {\n userId: tenant.userId,\n canModerate: () => auth.isOrganizationAdmin(c, tenant.orgId),\n };\n }\n\n async function emitMentionAudit(\n c: Context,\n target: { factoryProjectId: string; workItemId: string; title?: string },\n commentId: string,\n mentionedIds: string[],\n ): Promise<void> {\n if (mentionedIds.length === 0) return;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_mentioned',\n factoryProjectId: target.factoryProjectId,\n targets: [{ type: 'work_item', id: target.workItemId, ...(target.title ? { name: target.title } : {}) }],\n metadata: { commentId, mentionedIds },\n },\n });\n }\n\n return [\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n await workItems.ensureReady();\n const workItem = await workItems.get({ orgId: tenant.orgId, id: workItemId });\n if (!workItem) return c.json({ error: 'Work item not found' }, 404);\n\n await comments.ensureReady();\n const limitRaw = c.req.query('limit');\n const limit = limitRaw ? Number.parseInt(limitRaw, 10) : undefined;\n const before = c.req.query('before') || undefined;\n if (before && !decodeCommentCursor(before)) return c.json({ error: 'invalid_cursor' }, 422);\n const around = c.req.query('around') || undefined;\n if (around && !UUID_RE.test(around)) return c.json({ error: 'invalid_comment_id' }, 422);\n const page = await comments.list({\n orgId: tenant.orgId,\n factoryProjectId: workItem.factoryProjectId,\n workItemId,\n before,\n ...(around ? { around } : {}),\n ...(limit !== undefined && Number.isFinite(limit) ? { limit } : {}),\n });\n const wirePage: WireCommentPage = {\n comments: page.comments.map(comment => toWireComment(comment, tenant.userId)),\n ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}),\n };\n return c.json(wirePage);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments', {\n method: 'POST',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n if (!workItemId || !UUID_RE.test(workItemId)) return c.json({ error: 'Work item not found' }, 404);\n\n const parsed = parseCreateCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.createComment({\n orgId: tenant.orgId,\n workItemId,\n author: actorFromAuthUser(tenant.userId, getFactoryAuthUser(c)),\n body: parsed.body,\n ...(parsed.replyTo ? { replyTo: parsed.replyTo } : {}),\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.clientToken ? { clientToken: parsed.clientToken } : {}),\n });\n if (result.status === 'work_item_not_found') return c.json({ error: 'Work item not found' }, 404);\n if (result.status === 'token_conflict') return c.json({ error: 'comment_token_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment, workItem } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_created',\n factoryProjectId: workItem.factoryProjectId,\n targets: [{ type: 'work_item', id: workItem.id, name: workItem.title }],\n metadata: { commentId: comment.id },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: workItem.factoryProjectId, workItemId: workItem.id, title: workItem.title },\n comment.id,\n comment.mentions.map(mention => mention.id).filter(id => id !== comment.author.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) }, 201);\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'PATCH',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const parsed = parseEditCommentBody(await readJson(c));\n if (!parsed) return c.json({ error: 'invalid_comment' }, 422);\n\n const result = await domain.editComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n body: parsed.body,\n ...(parsed.mentions ? { mentions: parsed.mentions } : {}),\n ...(parsed.expectedRevision !== undefined ? { expectedRevision: parsed.expectedRevision } : {}),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n if (result.status === 'conflict') return c.json({ error: 'comment_conflict' }, 409);\n if (result.status === 'invalid') return c.json({ error: 'invalid_comment', message: result.message }, 422);\n\n const { comment } = result;\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_edited',\n factoryProjectId: comment.factoryProjectId,\n targets: [{ type: 'work_item', id: comment.workItemId }],\n metadata: {\n commentId: comment.id,\n previousBody: result.previousBody.slice(0, MAX_AUDIT_BODY_SNAPSHOT),\n },\n },\n });\n await emitMentionAudit(\n c,\n { factoryProjectId: comment.factoryProjectId, workItemId: comment.workItemId },\n comment.id,\n result.addedMentions.map(mention => mention.id),\n );\n return c.json({ comment: toWireComment(comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/work-items/:workItemId/comments/:commentId', {\n method: 'DELETE',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const workItemId = c.req.param('workItemId');\n const commentId = c.req.param('commentId');\n if (!workItemId || !UUID_RE.test(workItemId) || !commentId || !UUID_RE.test(commentId)) {\n return c.json({ error: 'Comment not found' }, 404);\n }\n\n const result = await domain.deleteComment({\n orgId: tenant.orgId,\n workItemId,\n commentId,\n editor: editorFor(c, tenant),\n });\n if (result.status === 'not_found') return c.json({ error: 'Comment not found' }, 404);\n if (result.status === 'forbidden') return c.json({ error: 'not_comment_author' }, 403);\n if (result.status === 'not_editable') return c.json({ error: 'comment_not_editable' }, 409);\n\n await audit?.emit({\n context: c,\n input: {\n action: 'factory.work_item.comment_deleted',\n factoryProjectId: result.comment.factoryProjectId,\n targets: [{ type: 'work_item', id: result.comment.workItemId }],\n metadata: { commentId: result.comment.id },\n },\n });\n return c.json({ comment: toWireComment(result.comment, tenant.userId) });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/mention-roster', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n await comments.ensureReady();\n const roster = await domain.mentionRoster({ orgId: tenant.orgId, factoryProjectId: projectId });\n const query = c.req.query('q')?.trim().toLowerCase();\n const members = query\n ? roster.filter(member => (member.name ?? member.id).toLowerCase().startsWith(query))\n : roster;\n return c.json({ members });\n },\n }),\n\n registerApiRoute('/web/factory/projects/:id/feed-events', {\n method: 'GET',\n handler: async cc => {\n const c = loose(cc);\n const tenant = await resolveTenant(c);\n if ('response' in tenant) return tenant.response;\n\n const projectId = c.req.param('id');\n if (!projectId || !UUID_RE.test(projectId)) return c.json({ error: 'Project not found' }, 404);\n await projects.ensureReady();\n const project = await projects.get({ orgId: tenant.orgId, id: projectId });\n if (!project) return c.json({ error: 'Project not found' }, 404);\n\n const topic = feedTopic(tenant.orgId, projectId);\n return streamSSE(c, async stream => {\n // `withAck` settles every delivery: on a durable broker (Redis\n // Streams) an unacked event stays in the subscription's pending set\n // and in the broker client's in-flight bookkeeping for the life of\n // this connection — a leak that grows with every feed touch on\n // long-lived dashboard tabs. Feed frames are fire-and-forget\n // invalidations, so a delivery is acked even when the tab is gone.\n const onEvent: EventCallback = withAck(async event => {\n if (stream.aborted) return;\n const data = event.data;\n const workItemId = isRecord(data) && typeof data.workItemId === 'string' ? data.workItemId : undefined;\n try {\n await stream.writeSSE({ event: 'feed', data: JSON.stringify(workItemId ? { workItemId } : {}) });\n } catch {\n // A write to a half-closed socket must not reach `withAck` as a\n // rejection: the nack would republish the event to the shared\n // feed topic, duplicating the invalidation for every tab.\n }\n });\n // Claimed before any await: `onAbort` handlers registered after the\n // reader is gone never run, and a broker subscribe is a round trip.\n const closed = new Promise<void>(resolve => stream.onAbort(resolve));\n let keepalive: ReturnType<typeof setInterval> | undefined;\n try {\n // Without `latest`, a retaining broker replays its whole backlog into\n // every new connection as spurious invalidations.\n await pubsub.subscribe(topic, onEvent, { startFrom: 'latest' });\n if (!stream.aborted) {\n keepalive = setInterval(() => {\n if (stream.aborted) return;\n void stream.write(': ping\\n\\n');\n }, FEED_KEEPALIVE_MS);\n // `streamSSE` closes the stream the moment this callback returns.\n await closed;\n }\n } finally {\n clearInterval(keepalive);\n await pubsub.unsubscribe(topic, onEvent);\n }\n });\n },\n }),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA4BA,MAAM,0BAA0B;;AAEhC,MAAM,oBAAoB;AAmB1B,SAAgB,mBAAmB,cAAoD;CACrF,MAAM,EAAE,QAAQ,MAAM,UAA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@ export interface MemorySettingsPatch {
26
26
  reflectionThreshold?: number;
27
27
  observeAttachments?: 'auto' | boolean;
28
28
  }
29
- /**
30
- * Sentinel `user_id` for a factory project's shared memory settings. Factory
31
- * runs are org-shared, so their OM configuration lives on the project — this
32
- * key reuses the same `(org, user)` table without a schema change. Real user
33
- * ids are WorkOS ids (`user_…`) or the `local` sentinel, so the prefix cannot
34
- * collide.
35
- */
36
- export declare function factoryMemorySettingsUserId(factoryProjectId: string): string;
37
29
  export declare const MEMORY_SETTINGS_SCHEMA: CollectionSchema;
38
30
  export declare class MemorySettingsStorage extends FactoryStorageDomain {
39
31
  #private;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/memory-settings/base.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAClF,OAAO,KAAK,EAAE,gBAAgB,EAAqB,MAAM,sBAAsB,CAAC;AAEhF;;;;;;GAMG;AACH,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,eAAe,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,oBAAoB,EAAE,MAAM,GAAG,IAAI,CAAC;IACpC,mBAAmB,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,kBAAkB,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC;IAC5C,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,gGAAgG;AAChG,MAAM,WAAW,mBAAmB;IAClC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,kBA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AAO,GAAG,IAAI,CAAC;IAC5C,SAAS,EAAE,IAAI,CAAC;IAChB,SAAS,EAAE,IAAI,CAAC;CACjB;AAED,gGAAgG;AAChG,MAAM,WAAW,mBAAmB;IAClC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,gBAAgB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACjC,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,kBAAkB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;CACvC;AAED,eAAO,MAAM,sBAAsB,EAAE,gBAgBpC,CAAC;AAuCF,qBAAa,qBAAsB,SAAQ,oBAAoB;;IAC7D,cAEC;IAEK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAE1B;IAEK,mBAAmB,IAAI,OAAO,CAAC,IAAI,CAAC,CAEzC;IAMK,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CAGpG;IAED;;;;OAIG;IACG,KAAK,CAAC,EACV,KAAK,EACL,MAAM,EACN,KAAK,GACN,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,MAAM,EAAE,MAAM,CAAC;QACf,KAAK,EAAE,mBAAmB,CAAC;KAC5B,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAgChC;CACF"}
@@ -1,15 +1,5 @@
1
1
  import { FactoryStorageDomain, UniqueViolationError } from "@mastra/core/storage";
2
2
  // src/storage/domains/memory-settings/base.ts
3
- /**
4
- * Sentinel `user_id` for a factory project's shared memory settings. Factory
5
- * runs are org-shared, so their OM configuration lives on the project — this
6
- * key reuses the same `(org, user)` table without a schema change. Real user
7
- * ids are WorkOS ids (`user_…`) or the `local` sentinel, so the prefix cannot
8
- * collide.
9
- */
10
- function factoryMemorySettingsUserId(factoryProjectId) {
11
- return `factory-project:${factoryProjectId}`;
12
- }
13
3
  const MEMORY_SETTINGS_SCHEMA = {
14
4
  name: "memory_settings",
15
5
  columns: {
@@ -123,6 +113,6 @@ var MemorySettingsStorage = class extends FactoryStorageDomain {
123
113
  }
124
114
  }
125
115
  };
126
- export { MEMORY_SETTINGS_SCHEMA, MemorySettingsStorage, factoryMemorySettingsUserId };
116
+ export { MEMORY_SETTINGS_SCHEMA, MemorySettingsStorage };
127
117
 
128
118
  //# sourceMappingURL=base.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/memory-settings/base.ts"],"sourcesContent":["import { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\n/**\n * A user's persisted memory (observational-memory) configuration. The\n * DB-backed tenant counterpart of the local `settings.json` OM fields\n * (`observerModelOverride`, `reflectorModelOverride`, `omObservationThreshold`,\n * `omReflectionThreshold`, `omObserveAttachments`): one row per `(org, user)`,\n * every knob nullable so only explicitly-changed values are stored.\n */\nexport interface MemorySettingsRecord {\n orgId: string;\n userId: string;\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Partial update — only the provided knobs are written. `null` resets a model role to auto. */\nexport interface MemorySettingsPatch {\n observerModelId?: string | null;\n reflectorModelId?: string | null;\n observationThreshold?: number;\n reflectionThreshold?: number;\n observeAttachments?: 'auto' | boolean;\n}\n\n/**\n * Sentinel `user_id` for a factory project's shared memory settings. Factory\n * runs are org-shared, so their OM configuration lives on the project — this\n * key reuses the same `(org, user)` table without a schema change. Real user\n * ids are WorkOS ids (`user_…`) or the `local` sentinel, so the prefix cannot\n * collide.\n */\nexport function factoryMemorySettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\nexport const MEMORY_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'memory_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n observer_model_id: { type: 'text', nullable: true },\n reflector_model_id: { type: 'text', nullable: true },\n observation_threshold: { type: 'integer', nullable: true },\n reflection_threshold: { type: 'integer', nullable: true },\n // 'auto' | true | false — json keeps the tri-state without string encoding.\n observe_attachments: { type: 'json', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'memory_settings_org_user_key', columns: ['org_id', 'user_id'] }],\n};\n\ninterface MemorySettingsDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n user_id: string;\n observer_model_id: string | null;\n reflector_model_id: string | null;\n observation_threshold: number | null;\n reflection_threshold: number | null;\n observe_attachments: 'auto' | boolean | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toRecord(row: MemorySettingsDbRow): MemorySettingsRecord {\n return {\n orgId: row.org_id,\n userId: row.user_id,\n observerModelId: row.observer_model_id,\n reflectorModelId: row.reflector_model_id,\n observationThreshold: row.observation_threshold,\n reflectionThreshold: row.reflection_threshold,\n observeAttachments: row.observe_attachments,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction patchToColumns(patch: MemorySettingsPatch): Partial<MemorySettingsDbRow> {\n const columns: Partial<MemorySettingsDbRow> = {};\n if (patch.observerModelId !== undefined) columns.observer_model_id = patch.observerModelId;\n if (patch.reflectorModelId !== undefined) columns.reflector_model_id = patch.reflectorModelId;\n if (patch.observationThreshold !== undefined) columns.observation_threshold = patch.observationThreshold;\n if (patch.reflectionThreshold !== undefined) columns.reflection_threshold = patch.reflectionThreshold;\n if (patch.observeAttachments !== undefined) columns.observe_attachments = patch.observeAttachments;\n return columns;\n}\n\nexport class MemorySettingsStorage extends FactoryStorageDomain {\n constructor() {\n super('memory-settings');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([MEMORY_SETTINGS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('memory_settings', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async get({ orgId, userId }: { orgId: string; userId: string }): Promise<MemorySettingsRecord | null> {\n const row = await this.#db.findOne<MemorySettingsDbRow>('memory_settings', { org_id: orgId, user_id: userId });\n return row ? toRecord(row) : null;\n }\n\n /**\n * Upsert the user's row, writing only the knobs present in `patch`.\n * Concurrent first writes are resolved via the shared\n * insert-then-catch-unique-violation pattern (see `queue_health`).\n */\n async patch({\n orgId,\n userId,\n patch,\n }: {\n orgId: string;\n userId: string;\n patch: MemorySettingsPatch;\n }): Promise<MemorySettingsRecord> {\n const now = new Date();\n const updateExisting = () =>\n this.#db.updateAtomic<MemorySettingsDbRow>('memory_settings', { org_id: orgId, user_id: userId }, () => ({\n ...patchToColumns(patch),\n updated_at: now,\n }));\n\n const updated = await updateExisting();\n if (updated) return toRecord(updated);\n\n try {\n const row = await this.#db.insertOne<MemorySettingsDbRow>('memory_settings', {\n org_id: orgId,\n user_id: userId,\n observer_model_id: null,\n reflector_model_id: null,\n observation_threshold: null,\n reflection_threshold: null,\n observe_attachments: null,\n ...patchToColumns(patch),\n created_at: now,\n updated_at: now,\n });\n return toRecord(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n // Lost the first-write race — apply the patch to the winning row.\n const row = await updateExisting();\n if (!row) throw error;\n return toRecord(row);\n }\n }\n}\n"],"mappings":";;;;;;;;;AAsCA,SAAgB,4BAA4B,kBAAkC;CAC5E,OAAO,mBAAmB;AAC5B;AAEA,MAAa,yBAA2C;CACtD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,SAAS,EAAE,MAAM,OAAO;EACxB,mBAAmB;GAAE,MAAM;GAAQ,UAAU;EAAK;EAClD,oBAAoB;GAAE,MAAM;GAA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AA6B,mBAAmB;GAAE,QAAQ;GAAO,SAAS;EAAO,CAAC;EAC7G,OAAO,MAAM,SAAS,GAAG,IAAI;CAC/B;;;;;;CAOA,MAAM,MAAM,EACV,OACA,QACA,SAKgC;EAChC,MAAM,sBAAM,IAAI,KAAK;EACrB,MAAM,uBACJ,KAAK,IAAI,aAAkC,mBAAmB;GAAE,QAAQ;GAAO,SAAS;EAAO,UAAU;GACvG,GAAG,eAAe,KAAK;GACvB,YAAY;EACd,EAAE;EAEJ,MAAM,UAAU,MAAM,eAAe;EACrC,IAAI,SAAS,OAAO,SAAS,OAAO;EAEpC,IAAI;GAaF,OAAO,SAAS,MAZE,KAAK,IAAI,UAA+B,mBAAmB;IAC3E,QAAQ;IACR,SAAS;IACT,mBAAmB;IACnB,oBAAoB;IACpB,uBAAuB;IACvB,sBAAsB;IACtB,qBAAqB;IACrB,GAAG,eAAe,KAAK;IACvB,YAAY;IACZ,YAAY;GACd,CAAC,CACkB;EACrB,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;GAEpD,MAAM,MAAM,MAAM,eAAe;GACjC,IAAI,CAAC,KAAK,MAAM;GAChB,OAAO,SAAS,GAAG;EACrB;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/memory-settings/base.ts"],"sourcesContent":["import { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\n/**\n * A user's persisted memory (observational-memory) configuration. The\n * DB-backed tenant counterpart of the local `settings.json` OM fields\n * (`observerModelOverride`, `reflectorModelOverride`, `omObservationThreshold`,\n * `omReflectionThreshold`, `omObserveAttachments`): one row per `(org, user)`,\n * every knob nullable so only explicitly-changed values are stored.\n */\nexport interface MemorySettingsRecord {\n orgId: string;\n userId: string;\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Partial update — only the provided knobs are written. `null` resets a model role to auto. */\nexport interface MemorySettingsPatch {\n observerModelId?: string | null;\n reflectorModelId?: string | null;\n observationThreshold?: number;\n reflectionThreshold?: number;\n observeAttachments?: 'auto' | boolean;\n}\n\nexport const MEMORY_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'memory_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n observer_model_id: { type: 'text', nullable: true },\n reflector_model_id: { type: 'text', nullable: true },\n observation_threshold: { type: 'integer', nullable: true },\n reflection_threshold: { type: 'integer', nullable: true },\n // 'auto' | true | false — json keeps the tri-state without string encoding.\n observe_attachments: { type: 'json', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'memory_settings_org_user_key', columns: ['org_id', 'user_id'] }],\n};\n\ninterface MemorySettingsDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n user_id: string;\n observer_model_id: string | null;\n reflector_model_id: string | null;\n observation_threshold: number | null;\n reflection_threshold: number | null;\n observe_attachments: 'auto' | boolean | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toRecord(row: MemorySettingsDbRow): MemorySettingsRecord {\n return {\n orgId: row.org_id,\n userId: row.user_id,\n observerModelId: row.observer_model_id,\n reflectorModelId: row.reflector_model_id,\n observationThreshold: row.observation_threshold,\n reflectionThreshold: row.reflection_threshold,\n observeAttachments: row.observe_attachments,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction patchToColumns(patch: MemorySettingsPatch): Partial<MemorySettingsDbRow> {\n const columns: Partial<MemorySettingsDbRow> = {};\n if (patch.observerModelId !== undefined) columns.observer_model_id = patch.observerModelId;\n if (patch.reflectorModelId !== undefined) columns.reflector_model_id = patch.reflectorModelId;\n if (patch.observationThreshold !== undefined) columns.observation_threshold = patch.observationThreshold;\n if (patch.reflectionThreshold !== undefined) columns.reflection_threshold = patch.reflectionThreshold;\n if (patch.observeAttachments !== undefined) columns.observe_attachments = patch.observeAttachments;\n return columns;\n}\n\nexport class MemorySettingsStorage extends FactoryStorageDomain {\n constructor() {\n super('memory-settings');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([MEMORY_SETTINGS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('memory_settings', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async get({ orgId, userId }: { orgId: string; userId: string }): Promise<MemorySettingsRecord | null> {\n const row = await this.#db.findOne<MemorySettingsDbRow>('memory_settings', { org_id: orgId, user_id: userId });\n return row ? toRecord(row) : null;\n }\n\n /**\n * Upsert the user's row, writing only the knobs present in `patch`.\n * Concurrent first writes are resolved via the shared\n * insert-then-catch-unique-violation pattern (see `queue_health`).\n */\n async patch({\n orgId,\n userId,\n patch,\n }: {\n orgId: string;\n userId: string;\n patch: MemorySettingsPatch;\n }): Promise<MemorySettingsRecord> {\n const now = new Date();\n const updateExisting = () =>\n this.#db.updateAtomic<MemorySettingsDbRow>('memory_settings', { org_id: orgId, user_id: userId }, () => ({\n ...patchToColumns(patch),\n updated_at: now,\n }));\n\n const updated = await updateExisting();\n if (updated) return toRecord(updated);\n\n try {\n const row = await this.#db.insertOne<MemorySettingsDbRow>('memory_settings', {\n org_id: orgId,\n user_id: userId,\n observer_model_id: null,\n reflector_model_id: null,\n observation_threshold: null,\n reflection_threshold: null,\n observe_attachments: null,\n ...patchToColumns(patch),\n created_at: now,\n updated_at: now,\n });\n return toRecord(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n // Lost the first-write race — apply the patch to the winning row.\n const row = await updateExisting();\n if (!row) throw error;\n return toRecord(row);\n }\n }\n}\n"],"mappings":";;AA+BA,MAAa,yBAA2C;CACtD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,O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AAI,MAAyB;EAC3B,OAAO,KAAK;CACd;CAEA,MAAM,IAAI,EAAE,OAAO,UAAmF;EACpG,MAAM,MAAM,MAAM,KAAK,IAAI,QAA6B,mBAAmB;GAAE,QAAQ;GAAO,SAAS;EAAO,CAAC;EAC7G,OAAO,MAAM,SAAS,GAAG,IAAI;CAC/B;;;;;;CAOA,MAAM,MAAM,EACV,OACA,QACA,SAKgC;EAChC,MAAM,sBAAM,IAAI,KAAK;EACrB,MAAM,uBACJ,KAAK,IAAI,aAAkC,mBAAmB;GAAE,QAAQ;GAAO,SAAS;EAAO,UAAU;GACvG,GAAG,eAAe,KAAK;GACvB,YAAY;EACd,EAAE;EAEJ,MAAM,UAAU,MAAM,eAAe;EACrC,IAAI,SAAS,OAAO,SAAS,OAAO;EAEpC,IAAI;GAaF,OAAO,SAAS,MAZE,KAAK,IAAI,UAA+B,mBAAmB;IAC3E,QAAQ;IACR,SAAS;IACT,mBAAmB;IACnB,oBAAoB;IACpB,uBAAuB;IACvB,sBAAsB;IACtB,qBAAqB;IACrB,GAAG,eAAe,KAAK;IACvB,YAAY;IACZ,YAAY;GACd,CAAC,CACkB;EACrB,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;GAEpD,MAAM,MAAM,MAAM,eAAe;GACjC,IAAI,CAAC,KAAK,MAAM;GAChB,OAAO,SAAS,GAAG;EACrB;CACF;AACF"}
@@ -11,6 +11,12 @@ export type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;
11
11
  * Factory's model and credentials, interactive sessions use the session owner's.
12
12
  */
13
13
  export declare function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope;
14
+ /**
15
+ * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the
16
+ * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or
17
+ * the `local` sentinel, so the prefix cannot collide.
18
+ */
19
+ export declare function factoryProjectSettingsUserId(factoryProjectId: string): string;
14
20
  export interface FactoryProject {
15
21
  id: string;
16
22
  orgId: 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,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,2FAA2F;IAC3F,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B;;;OAGG;IACH,UAAU,EAAE,iBAAiB,CAAC;IAC9B,0FAA0F;IAC1F,oBAAoB,EAAE,oBAAoB,CAAC;IAC3C,kGAAkG;IAClG,cAAc,EAAE,OAAO,CAAC;IACxB,qFAAqF;IACrF,uBAAuB,EAAE,MAAM,GAAG,IAAI,CAAC;IACvC,qGAAqG;IACrG,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OA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,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"}
@@ -16,6 +16,14 @@ function effectiveModelScope(scope, context) {
16
16
  if (scope === "hybrid") return context === "run" ? "factory" : "user";
17
17
  return scope;
18
18
  }
19
+ /**
20
+ * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the
21
+ * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or
22
+ * the `local` sentinel, so the prefix cannot collide.
23
+ */
24
+ function factoryProjectSettingsUserId(factoryProjectId) {
25
+ return `factory-project:${factoryProjectId}`;
26
+ }
19
27
  const FACTORY_PROJECTS_SCHEMA = {
20
28
  name: "factory_projects",
21
29
  columns: {
@@ -368,6 +376,6 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
368
376
  }, { isolationLevel: "serializable" });
369
377
  }
370
378
  };
371
- export { DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES, FACTORY_MODEL_SCOPES, FACTORY_PROJECTS_SCHEMA, FactoryProjectsStorage, effectiveModelScope };
379
+ export { DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES, FACTORY_MODEL_SCOPES, FACTORY_PROJECTS_SCHEMA, FactoryProjectsStorage, effectiveModelScope, factoryProjectSettingsUserId };
372
380
 
373
381
  //# sourceMappingURL=base.js.map