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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +110 -56
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +7 -1
  4. package/dist/auth.js.map +1 -1
  5. package/dist/boards/board-events.d.ts +1 -1
  6. package/dist/boards/board-events.d.ts.map +1 -1
  7. package/dist/boards/card-facts.d.ts +3 -1
  8. package/dist/boards/card-facts.d.ts.map +1 -1
  9. package/dist/boards/card-facts.js +26 -4
  10. package/dist/boards/card-facts.js.map +1 -1
  11. package/dist/boards/default-board.d.ts +2 -2
  12. package/dist/boards/default-board.js +2 -2
  13. package/dist/boards/default-board.js.map +1 -1
  14. package/dist/boards/define-board.d.ts +1 -1
  15. package/dist/boards/define-board.d.ts.map +1 -1
  16. package/dist/boards/define-board.js.map +1 -1
  17. package/dist/boards/intake-routing.d.ts +3 -5
  18. package/dist/boards/intake-routing.d.ts.map +1 -1
  19. package/dist/boards/intake-routing.js +3 -4
  20. package/dist/boards/intake-routing.js.map +1 -1
  21. package/dist/boards/project-boards.d.ts +18 -1
  22. package/dist/boards/project-boards.d.ts.map +1 -1
  23. package/dist/boards/project-boards.js +40 -3
  24. package/dist/boards/project-boards.js.map +1 -1
  25. package/dist/boards/semantics.d.ts +4 -4
  26. package/dist/boards/semantics.d.ts.map +1 -1
  27. package/dist/boards/semantics.js +8 -10
  28. package/dist/boards/semantics.js.map +1 -1
  29. package/dist/boards/work-migrations.d.ts +24 -1
  30. package/dist/boards/work-migrations.d.ts.map +1 -1
  31. package/dist/boards/work-migrations.js +97 -2
  32. package/dist/boards/work-migrations.js.map +1 -1
  33. package/dist/boards/work-routes.d.ts +6 -1
  34. package/dist/boards/work-routes.d.ts.map +1 -1
  35. package/dist/boards/work-routes.js +20 -6
  36. package/dist/boards/work-routes.js.map +1 -1
  37. package/dist/factory.d.ts +23 -0
  38. package/dist/factory.d.ts.map +1 -1
  39. package/dist/factory.js +62 -59
  40. package/dist/factory.js.map +1 -1
  41. package/dist/feed-events.d.ts +3 -2
  42. package/dist/feed-events.d.ts.map +1 -1
  43. package/dist/feed-events.js +3 -2
  44. package/dist/feed-events.js.map +1 -1
  45. package/dist/index.d.ts +3 -0
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +2 -1
  48. package/dist/integrations/github/default-rules.d.ts.map +1 -1
  49. package/dist/integrations/github/default-rules.js +3 -5
  50. package/dist/integrations/github/default-rules.js.map +1 -1
  51. package/dist/integrations/github/rules.d.ts +0 -6
  52. package/dist/integrations/github/rules.d.ts.map +1 -1
  53. package/dist/integrations/github/rules.js +23 -70
  54. package/dist/integrations/github/rules.js.map +1 -1
  55. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  56. package/dist/integrations/gitlab/routes.js +1 -3
  57. package/dist/integrations/gitlab/routes.js.map +1 -1
  58. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  59. package/dist/integrations/gitlab/rules.js +4 -9
  60. package/dist/integrations/gitlab/rules.js.map +1 -1
  61. package/dist/integrations/incidentio/agent-tools.js +5 -5
  62. package/dist/integrations/incidentio/agent-tools.js.map +1 -1
  63. package/dist/integrations/incidentio/default-rules.d.ts.map +1 -1
  64. package/dist/integrations/incidentio/default-rules.js.map +1 -1
  65. package/dist/integrations/incidentio/routes.d.ts +2 -2
  66. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  67. package/dist/integrations/incidentio/routes.js +10 -13
  68. package/dist/integrations/incidentio/routes.js.map +1 -1
  69. package/dist/integrations/incidentio/rules.d.ts +1 -3
  70. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  71. package/dist/integrations/incidentio/rules.js +1 -3
  72. package/dist/integrations/incidentio/rules.js.map +1 -1
  73. package/dist/integrations/jira/binding-scope.d.ts +5 -6
  74. package/dist/integrations/jira/binding-scope.d.ts.map +1 -1
  75. package/dist/integrations/jira/binding-scope.js +9 -11
  76. package/dist/integrations/jira/binding-scope.js.map +1 -1
  77. package/dist/integrations/jira/default-rules.d.ts.map +1 -1
  78. package/dist/integrations/jira/default-rules.js.map +1 -1
  79. package/dist/integrations/jira/routes.d.ts.map +1 -1
  80. package/dist/integrations/jira/routes.js +3 -5
  81. package/dist/integrations/jira/routes.js.map +1 -1
  82. package/dist/integrations/jira/rules.d.ts +1 -3
  83. package/dist/integrations/jira/rules.d.ts.map +1 -1
  84. package/dist/integrations/jira/rules.js +1 -3
  85. package/dist/integrations/jira/rules.js.map +1 -1
  86. package/dist/integrations/linear/default-rules.d.ts.map +1 -1
  87. package/dist/integrations/linear/default-rules.js.map +1 -1
  88. package/dist/integrations/linear/routes.d.ts.map +1 -1
  89. package/dist/integrations/linear/routes.js +11 -14
  90. package/dist/integrations/linear/routes.js.map +1 -1
  91. package/dist/integrations/linear/rules.d.ts +1 -3
  92. package/dist/integrations/linear/rules.d.ts.map +1 -1
  93. package/dist/integrations/linear/rules.js +1 -3
  94. package/dist/integrations/linear/rules.js.map +1 -1
  95. package/dist/integrations/platform/connect/session-tools.d.ts +5 -0
  96. package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
  97. package/dist/integrations/platform/connect/session-tools.js +5 -0
  98. package/dist/integrations/platform/connect/session-tools.js.map +1 -1
  99. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  100. package/dist/integrations/platform/jira/routes.js +3 -5
  101. package/dist/integrations/platform/jira/routes.js.map +1 -1
  102. package/dist/integrations/slack/run-error-card.js +1 -0
  103. package/dist/integrations/slack/run-error-card.js.map +1 -1
  104. package/dist/provider-display-name.d.ts.map +1 -1
  105. package/dist/provider-display-name.js +1 -0
  106. package/dist/provider-display-name.js.map +1 -1
  107. package/dist/routes/automation-runs.d.ts +1 -1
  108. package/dist/routes/automation-runs.js.map +1 -1
  109. package/dist/routes/config.d.ts +7 -1
  110. package/dist/routes/config.d.ts.map +1 -1
  111. package/dist/routes/config.js +105 -22
  112. package/dist/routes/config.js.map +1 -1
  113. package/dist/routes/contracts.d.ts +3 -10
  114. package/dist/routes/contracts.d.ts.map +1 -1
  115. package/dist/routes/contracts.js +11 -9
  116. package/dist/routes/contracts.js.map +1 -1
  117. package/dist/routes/intake-routes.d.ts.map +1 -1
  118. package/dist/routes/intake-routes.js +6 -1
  119. package/dist/routes/intake-routes.js.map +1 -1
  120. package/dist/routes/intake.d.ts +0 -23
  121. package/dist/routes/intake.d.ts.map +1 -1
  122. package/dist/routes/intake.js +13 -310
  123. package/dist/routes/intake.js.map +1 -1
  124. package/dist/routes/mastra-gateway.d.ts +19 -0
  125. package/dist/routes/mastra-gateway.d.ts.map +1 -0
  126. package/dist/routes/mastra-gateway.js +120 -0
  127. package/dist/routes/mastra-gateway.js.map +1 -0
  128. package/dist/routes/projects.d.ts.map +1 -1
  129. package/dist/routes/projects.js +1 -1
  130. package/dist/routes/projects.js.map +1 -1
  131. package/dist/routes/provider-credentials.d.ts +6 -1
  132. package/dist/routes/provider-credentials.d.ts.map +1 -1
  133. package/dist/routes/provider-credentials.js +32 -2
  134. package/dist/routes/provider-credentials.js.map +1 -1
  135. package/dist/routes/route.d.ts +6 -0
  136. package/dist/routes/route.d.ts.map +1 -1
  137. package/dist/routes/route.js.map +1 -1
  138. package/dist/routes/surface.d.ts.map +1 -1
  139. package/dist/routes/surface.js +0 -2
  140. package/dist/routes/surface.js.map +1 -1
  141. package/dist/routes/tenant-credentials.d.ts.map +1 -1
  142. package/dist/routes/tenant-credentials.js +5 -1
  143. package/dist/routes/tenant-credentials.js.map +1 -1
  144. package/dist/rules/dispatcher.d.ts +0 -5
  145. package/dist/rules/dispatcher.d.ts.map +1 -1
  146. package/dist/rules/dispatcher.js +18 -22
  147. package/dist/rules/dispatcher.js.map +1 -1
  148. package/dist/rules/rule-group.d.ts +1 -1
  149. package/dist/rules/rule-group.d.ts.map +1 -1
  150. package/dist/rules/rule-group.js +13 -5
  151. package/dist/rules/rule-group.js.map +1 -1
  152. package/dist/rules/transition-service.d.ts +2 -3
  153. package/dist/rules/transition-service.d.ts.map +1 -1
  154. package/dist/rules/transition-service.js +0 -1
  155. package/dist/rules/transition-service.js.map +1 -1
  156. package/dist/rules/types.d.ts +7 -11
  157. package/dist/rules/types.d.ts.map +1 -1
  158. package/dist/rules/types.js.map +1 -1
  159. package/dist/run-error.d.ts +1 -1
  160. package/dist/run-error.d.ts.map +1 -1
  161. package/dist/run-error.js +38 -5
  162. package/dist/run-error.js.map +1 -1
  163. package/dist/session/live-sessions.d.ts +11 -4
  164. package/dist/session/live-sessions.d.ts.map +1 -1
  165. package/dist/session/live-sessions.js +31 -10
  166. package/dist/session/live-sessions.js.map +1 -1
  167. package/dist/session/self-review-gate.d.ts +0 -2
  168. package/dist/session/self-review-gate.d.ts.map +1 -1
  169. package/dist/session/self-review-gate.js +1 -8
  170. package/dist/session/self-review-gate.js.map +1 -1
  171. package/dist/session/source-control-tools.d.ts +39 -13
  172. package/dist/session/source-control-tools.d.ts.map +1 -1
  173. package/dist/session/source-control-tools.js +54 -60
  174. package/dist/session/source-control-tools.js.map +1 -1
  175. package/dist/session/work-item-state-processor.d.ts +1 -4
  176. package/dist/session/work-item-state-processor.d.ts.map +1 -1
  177. package/dist/session/work-item-state-processor.js +5 -18
  178. package/dist/session/work-item-state-processor.js.map +1 -1
  179. package/dist/storage/domains/boards/base.d.ts +30 -8
  180. package/dist/storage/domains/boards/base.d.ts.map +1 -1
  181. package/dist/storage/domains/boards/base.js +43 -25
  182. package/dist/storage/domains/boards/base.js.map +1 -1
  183. package/dist/storage/domains/boards/schemas.js.map +1 -1
  184. package/dist/storage/domains/comments/base.d.ts.map +1 -1
  185. package/dist/storage/domains/comments/base.js +2 -2
  186. package/dist/storage/domains/comments/base.js.map +1 -1
  187. package/dist/storage/domains/comments/routes.d.ts.map +1 -1
  188. package/dist/storage/domains/comments/routes.js +4 -2
  189. package/dist/storage/domains/comments/routes.js.map +1 -1
  190. package/dist/storage/domains/intake/base.d.ts +5 -45
  191. package/dist/storage/domains/intake/base.d.ts.map +1 -1
  192. package/dist/storage/domains/intake/base.js +11 -89
  193. package/dist/storage/domains/intake/base.js.map +1 -1
  194. package/dist/storage/domains/projects/base.d.ts +17 -9
  195. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  196. package/dist/storage/domains/projects/base.js +15 -7
  197. package/dist/storage/domains/projects/base.js.map +1 -1
  198. package/dist/storage/domains/work-items/base.d.ts +13 -11
  199. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  200. package/dist/storage/domains/work-items/base.js +37 -33
  201. package/dist/storage/domains/work-items/base.js.map +1 -1
  202. package/dist/storage/domains/work-items/board-version.d.ts +6 -2
  203. package/dist/storage/domains/work-items/board-version.d.ts.map +1 -1
  204. package/dist/storage/domains/work-items/board-version.js +20 -9
  205. package/dist/storage/domains/work-items/board-version.js.map +1 -1
  206. package/dist/work-items/providers/base.d.ts +4 -1
  207. package/dist/work-items/providers/base.d.ts.map +1 -1
  208. package/dist/work-items/providers/base.js +6 -1
  209. package/dist/work-items/providers/base.js.map +1 -1
  210. package/dist/work-items/providers/github.d.ts.map +1 -1
  211. package/dist/work-items/providers/github.js +2 -1
  212. package/dist/work-items/providers/github.js.map +1 -1
  213. package/dist/work-items/providers/gitlab.d.ts.map +1 -1
  214. package/dist/work-items/providers/gitlab.js +2 -1
  215. package/dist/work-items/providers/gitlab.js.map +1 -1
  216. package/dist/work-items/providers/jira.d.ts.map +1 -1
  217. package/dist/work-items/providers/jira.js +3 -2
  218. package/dist/work-items/providers/jira.js.map +1 -1
  219. package/dist/work-items/providers/linear.d.ts.map +1 -1
  220. package/dist/work-items/providers/linear.js +3 -2
  221. package/dist/work-items/providers/linear.js.map +1 -1
  222. package/dist/work-items/providers/types.d.ts +6 -0
  223. package/dist/work-items/providers/types.d.ts.map +1 -1
  224. package/factory-skills/configure-factory-rules/SKILL.md +2 -2
  225. package/factory-skills/factory-build/SKILL.md +5 -5
  226. package/factory-skills/factory-gitlab-rereview/SKILL.md +4 -4
  227. package/factory-skills/factory-gitlab-review/SKILL.md +5 -5
  228. package/factory-skills/factory-rereview/SKILL.md +69 -23
  229. package/factory-skills/factory-review/SKILL.md +69 -23
  230. package/factory-skills/factory-self-review/SKILL.md +5 -6
  231. package/factory-skills/factory-triage/SKILL.md +8 -20
  232. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Org-wide intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the organization selected. The selection feeds shared boards, so\n * every member reads the same one.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport class FactoryProjectNotFoundError extends Error {\n constructor() {\n super('Factory project not found for this organization.');\n this.name = 'FactoryProjectNotFoundError';\n }\n}\n\nasync function assertFactoryProject(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<void> {\n if (!(await ops.findOne('factory_projects', { org_id: orgId, id: factoryProjectId }))) {\n throw new FactoryProjectNotFoundError();\n }\n}\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n repositoryByLinearProject?: Record<string, string>;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_org_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_org_settings_org_unique', columns: ['org_id'] }],\n};\n\n/** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */\nexport const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */\nexport function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig {\n const merged: IntakeConfig = Object.create(null);\n for (const config of configs) {\n for (const [integrationId, selection] of Object.entries(config)) {\n const current = merged[integrationId] ?? { enabled: false, sourceIds: null };\n const syncing = selection.enabled ? (selection.sourceIds ?? []) : [];\n const sourceIds = [...new Set([...(current.sourceIds ?? []), ...syncing])];\n merged[integrationId] = {\n enabled: current.enabled || selection.enabled,\n sourceIds: sourceIds.length ? sourceIds : null,\n };\n }\n }\n return merged;\n}\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n *\n * Frozen: its unique index allows one binding per source, and indexes cannot be\n * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows\n * are copied once at boot and never written again; the collection stays\n * registered so an earlier build that is rolled back to still finds them.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Installed board the source feeds; `null` keeps the legacy source-type routing (issues → work, PRs → review). */\n board: { type: 'text', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\n/**\n * Binds an intake source to a Factory project, one row per (source, Factory\n * project). Most integrations keep one binding per source and rebinding moves\n * it; integrations with `Intake.bindingLabelFilters` let several Factory\n * projects share a source, each taking the issues carrying its own labels.\n */\nexport const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'intake_source_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Installed board the source feeds; `null` keeps the legacy source-type routing (issues → work, PRs → review). */\n board: { type: 'text', nullable: true },\n /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */\n labels: { type: 'json', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_subscriptions_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_subscriptions_org_integration_source_project_unique',\n columns: ['org_id', 'integration_id', 'source_id', 'factory_project_id'],\n },\n ],\n};\n\n/** One-time data migrations that have run, so none re-runs over rows users have changed since. */\nexport const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema = {\n name: 'intake_data_migrations',\n columns: {\n name: { type: 'text', primaryKey: true },\n completed_at: { type: 'timestamp' },\n },\n};\n\nconst COPY_LEGACY_BINDINGS_MIGRATION = 'copy_intake_source_bindings_to_subscriptions';\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n /** Installed board the source feeds, or `null` for legacy source-type routing. */\n board: string | null;\n /** Labels whose issues this binding takes; `null` takes every issue no other binding's labels claim. */\n labels: string[] | null;\n createdAt: Date;\n}\n\n/** Another Factory project's binding that already takes some of the requested issues. */\nexport interface IntakeBindingConflict {\n factoryProjectId: string;\n /** The overlapping labels, or `null` when both bindings take all unclaimed issues. */\n labels: string[] | null;\n}\n\n/** Bindings on one source in precedence order: the oldest binding wins an issue two of them match. */\nfunction inPrecedenceOrder<T extends Pick<IntakeSourceBinding, 'createdAt' | 'factoryProjectId'>>(\n bindings: readonly T[],\n): T[] {\n return [...bindings].sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() ||\n left.factoryProjectId.localeCompare(right.factoryProjectId),\n );\n}\n\n/**\n * The slice of a shared source's issues `binding` takes, given every binding\n * on that source (`siblings` may include `binding` itself). Label bindings beat\n * the all-issues binding, and an issue carrying labels of two label bindings\n * goes to the older one.\n */\nexport function bindingLabelSlice(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n): { include: string[] | null; exclude: string[] } {\n const labelled = inPrecedenceOrder(\n siblings.filter(sibling => sibling.labels !== null && sibling.factoryProjectId !== binding.factoryProjectId),\n );\n if (binding.labels === null) {\n return { include: null, exclude: labelled.flatMap(sibling => sibling.labels ?? []) };\n }\n const older = labelled.filter(sibling => inPrecedenceOrder([sibling, binding])[0] === sibling);\n return { include: binding.labels, exclude: older.flatMap(sibling => sibling.labels ?? []) };\n}\n\n/** Whether an issue carrying `labels` falls in `binding`'s slice of its source. */\nexport function bindingTakesIssue(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n labels: readonly string[],\n): boolean {\n const carried = new Set(labels.map(normalizeIntakeLabel));\n const { include, exclude } = bindingLabelSlice(binding, siblings);\n if (exclude.some(label => carried.has(normalizeIntakeLabel(label)))) return false;\n return include === null || include.some(label => carried.has(normalizeIntakeLabel(label)));\n}\n\n/** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */\nexport function normalizeBindingLabels(labels: readonly string[]): string[] {\n const seen = new Set<string>();\n const kept: string[] = [];\n for (const label of labels) {\n const trimmed = label.trim();\n const key = normalizeIntakeLabel(trimmed);\n if (!key || seen.has(key)) continue;\n seen.add(key);\n kept.push(trimmed);\n }\n return kept;\n}\n\n/**\n * Routes items carrying a label to an installed board, per Factory project.\n *\n * Repository-scoped providers (GitHub) already know which project an item\n * belongs to, but one repository can feed several boards: an issue labelled\n * `release` belongs on a release board while the rest stay on Work. Labels\n * without a route fall back to the provider's built-in board.\n */\nexport const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema = {\n name: 'intake_label_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n integration_id: { type: 'text' },\n /** Label as the provider reports it; matched case-insensitively. */\n label: { type: 'text' },\n board: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_label_routes_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_label_routes_org_project_integration_label_unique',\n columns: ['org_id', 'factory_project_id', 'integration_id', 'label'],\n },\n ],\n};\n\nexport interface IntakeLabelRoute {\n factoryProjectId: string;\n integrationId: string;\n label: string;\n board: string;\n}\n\ntype IntakeLabelRouteRow = {\n factory_project_id: string;\n integration_id: string;\n label: string;\n board: string;\n};\nfunction toIntakeLabelRoute(row: IntakeLabelRouteRow): IntakeLabelRoute {\n return {\n factoryProjectId: row.factory_project_id,\n integrationId: row.integration_id,\n label: row.label,\n board: row.board,\n };\n}\n\n/** Labels are matched the way GitHub treats them: case-insensitively. */\nexport function normalizeIntakeLabel(label: string): string {\n return label.trim().toLowerCase();\n}\n\n/**\n * The board a labelled item should land on under `routes`, or `undefined` when\n * none of its labels is routed. Ties resolve to the first route in `routes`\n * order, so callers should pass a deterministically ordered list.\n */\nexport function resolveIntakeLabelRoute(\n routes: readonly IntakeLabelRoute[],\n labels: readonly string[] | undefined,\n): IntakeLabelRoute | undefined {\n if (!labels?.length) return undefined;\n const normalized = new Set(labels.map(normalizeIntakeLabel));\n return routes.find(route => normalized.has(normalizeIntakeLabel(route.label)));\n}\n\ntype IntakeSourceBindingRow = {\n org_id: string;\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n board?: string | null;\n labels?: string[] | null;\n created_by_user_id?: string | null;\n created_at: Date;\n};\nfunction toIntakeSourceBinding(row: IntakeSourceBindingRow): IntakeSourceBinding {\n return {\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n board: row.board ?? null,\n labels: row.labels ?? null,\n createdAt: row.created_at,\n };\n}\n\n/** Overlap between a requested binding and the other Factory projects' bindings on the same source. */\nfunction bindingConflicts(\n factoryProjectId: string,\n labels: string[] | null,\n rows: readonly IntakeSourceBindingRow[],\n): IntakeBindingConflict[] {\n const requested = new Set(labels?.map(normalizeIntakeLabel));\n return rows.flatMap((row): IntakeBindingConflict[] => {\n if (row.factory_project_id === factoryProjectId) return [];\n const theirs = row.labels ?? null;\n if (labels === null || theirs === null) {\n return labels === null && theirs === null ? [{ factoryProjectId: row.factory_project_id, labels: null }] : [];\n }\n const overlap = theirs.filter(label => requested.has(normalizeIntakeLabel(label)));\n return overlap.length > 0 ? [{ factoryProjectId: row.factory_project_id, labels: overlap }] : [];\n });\n}\n\n/** Update one (source, Factory project) binding in place, keeping its age, or insert it. */\nasync function upsertBinding(\n ops: FactoryStorageOps,\n key: { org_id: string; integration_id: string; source_id: string; factory_project_id: string },\n patch: { board: string | null; labels: string[] | null },\n userId: string | undefined,\n): Promise<void> {\n const now = new Date();\n const updated = await ops.updateMany('intake_source_subscriptions', key, { ...patch, updated_at: now });\n if (updated > 0) return;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n ...patch,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n}\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTAKE_ORG_SETTINGS_SCHEMA,\n LEGACY_INTAKE_USER_SETTINGS_SCHEMA,\n INTAKE_SOURCE_BINDINGS_SCHEMA,\n INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,\n INTAKE_DATA_MIGRATIONS_SCHEMA,\n INTAKE_LABEL_ROUTES_SCHEMA,\n ]);\n await this.#foldLegacyUserSelections();\n await this.#copyLegacyBindings();\n }\n\n /**\n * Copy `intake_source_bindings` into `intake_source_subscriptions` as\n * all-issues bindings, once. The marker and the copy commit together, so a\n * boot racing another cannot re-copy a binding removed after the first\n * boot finished.\n */\n async #copyLegacyBindings(): Promise<void> {\n try {\n await this.storage.withTransaction(\n async ops => {\n if (await ops.findOne('intake_data_migrations', { name: COPY_LEGACY_BINDINGS_MIGRATION })) return;\n const legacyRows = await ops.findMany<IntakeSourceBindingRow & { updated_at: Date }>(\n 'intake_source_bindings',\n {},\n );\n for (const row of legacyRows) {\n const key = {\n org_id: row.org_id,\n integration_id: row.integration_id,\n source_id: row.source_id,\n factory_project_id: row.factory_project_id,\n };\n if (await ops.findOne('intake_source_subscriptions', key)) continue;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n board: row.board ?? null,\n labels: null,\n created_by_user_id: row.created_by_user_id ?? null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n });\n }\n await ops.insertOne('intake_data_migrations', {\n name: COPY_LEGACY_BINDINGS_MIGRATION,\n completed_at: new Date(),\n });\n },\n { isolationLevel: 'serializable' },\n );\n } catch (error) {\n // Postgres can report the boot that lost the race as a unique violation instead of a serialization failure.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n }\n\n async #foldLegacyUserSelections(): Promise<void> {\n const legacyRows = await this.ops.findMany<{ org_id: string; config: IntakeConfig }>('intake_settings', {});\n const byOrg = new Map<string, IntakeConfig[]>();\n for (const row of legacyRows) {\n byOrg.set(row.org_id, [...(byOrg.get(row.org_id) ?? []), row.config]);\n }\n for (const [orgId, configs] of byOrg) {\n const folded = await this.ops.findOne('intake_org_settings', { org_id: orgId });\n if (folded) continue;\n await this.#insertConfigIfAbsent(orgId, mergeIntakeSelections(configs));\n }\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_org_settings', {});\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n await this.ops.deleteMany('intake_source_subscriptions', {});\n await this.ops.deleteMany('intake_data_migrations', {});\n await this.ops.deleteMany('intake_label_routes', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n integrationIds,\n }: {\n orgId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: true, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: true, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId };\n const updated = await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n if (await this.#insertConfigIfAbsent(orgId, config)) return;\n await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n }\n\n /** Overlay `config` onto the stored selections; integrations it omits keep their stored value. */\n async mergeConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<IntakeConfig> {\n const merged: IntakeConfig = Object.assign(Object.create(null), await this.getConfig({ orgId }), config);\n await this.saveConfig({ orgId, config: merged });\n return merged;\n }\n\n async #insertConfigIfAbsent(orgId: string, config: IntakeConfig): Promise<boolean> {\n const now = new Date();\n try {\n await this.#db.insertOne('intake_org_settings', { org_id: orgId, config, created_at: now, updated_at: now });\n return true;\n } catch (error) {\n if (error instanceof UniqueViolationError) return false;\n throw error;\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration, oldest first. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * One Factory project's binding of a source, or `null` when it has none.\n * Without `factoryProjectId`, the source's oldest binding — for integrations\n * that keep one binding per source.\n */\n async getBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0] ?? null;\n }\n\n /**\n * Remove one Factory project's binding of a source, or — without\n * `factoryProjectId` — every binding of it. Returns the (oldest) removed\n * binding, or `null` when there was none.\n */\n async clearBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const where = {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n };\n return this.storage.withTransaction(\n async ops => {\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', where);\n if (rows.length === 0) return null;\n await ops.deleteMany('intake_source_subscriptions', where);\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0]!;\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Release every source a Factory project was bound to, so the others can take\n * them. Pass the transaction deleting the project, so no binding lands in between.\n */\n async clearProjectBindings(\n { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string },\n ops: FactoryStorageOps = this.#db,\n ): Promise<void> {\n await ops.deleteMany('intake_source_subscriptions', { org_id: orgId, factory_project_id: factoryProjectId });\n }\n\n /**\n * Bind a source to one Factory project, moving it away from any other: the\n * source keeps a single binding, which takes all of its issues.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n board = null,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n board?: string | null;\n userId?: string;\n }): Promise<void> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n await this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n for (const row of rows) {\n if (row.factory_project_id === factoryProjectId) continue;\n await ops.deleteMany('intake_source_subscriptions', {\n ...source,\n factory_project_id: row.factory_project_id,\n });\n }\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { board, labels: null }, userId);\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Bind a source to one Factory project alongside other Factory projects'\n * bindings of it, taking the issues carrying one of `labels` — or, with\n * `labels: null`, every issue no label binding claims. Rejected with the\n * overlapping bindings when another Factory project already takes some of\n * those labels, or already takes all unclaimed issues.\n */\n async setSharedBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n board = null,\n labels,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n board?: string | null;\n labels: string[] | null;\n userId?: string;\n }): Promise<{ conflicts: IntakeBindingConflict[] }> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n const kept = labels === null ? null : normalizeBindingLabels(labels);\n return this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n const conflicts = bindingConflicts(factoryProjectId, kept, rows);\n if (conflicts.length > 0) return { conflicts };\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { board, labels: kept }, userId);\n return { conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Atomically replace legacy provider source ids in both selection and routing state. */\n async migrateSourceIds({\n orgId,\n integrationId,\n migrations,\n }: {\n orgId: string;\n integrationId: string;\n migrations: Array<{ from: string; to: string }>;\n }): Promise<{ migrations: Array<{ from: string; to: string }>; conflicts: Array<{ from: string; to: string }> }> {\n if (migrations.length === 0) return { migrations: [], conflicts: [] };\n return this.storage.withTransaction(\n async ops => {\n const bindings = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n });\n const bindingsBySource = new Map<string, IntakeSourceBindingRow[]>();\n for (const binding of bindings) {\n bindingsBySource.set(binding.source_id, [...(bindingsBySource.get(binding.source_id) ?? []), binding]);\n }\n // Where a source's issues land: every Factory project, board and label slice bound to it.\n const destination = (rows: IntakeSourceBindingRow[]) =>\n rows\n .map(row => `${row.factory_project_id}\\0${row.board ?? ''}\\0${JSON.stringify(row.labels ?? null)}`)\n .sort()\n .join('\\n');\n const grouped = new Map<string, Array<{ from: string; to: string }>>();\n for (const migration of migrations) {\n grouped.set(migration.to, [...(grouped.get(migration.to) ?? []), migration]);\n }\n const conflicts: Array<{ from: string; to: string }> = [];\n for (const [to, group] of grouped) {\n const candidates = [bindingsBySource.get(to), ...group.map(({ from }) => bindingsBySource.get(from))].filter(\n (rows): rows is IntakeSourceBindingRow[] => rows !== undefined,\n );\n if (new Set(candidates.map(destination)).size > 1) conflicts.push(...group);\n }\n if (conflicts.length > 0) return { migrations: [], conflicts };\n\n const now = new Date();\n for (const [to, group] of grouped) {\n const legacy = group.filter(({ from }) => bindingsBySource.has(from));\n const scope = { org_id: orgId, integration_id: integrationId };\n if (!bindingsBySource.has(to) && legacy.length > 0) {\n const [first, ...duplicates] = legacy;\n await ops.updateMany(\n 'intake_source_subscriptions',\n { ...scope, source_id: first!.from },\n { source_id: to, updated_at: now },\n );\n for (const duplicate of duplicates) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: duplicate.from });\n }\n } else {\n for (const entry of legacy) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: entry.from });\n }\n }\n }\n\n const configRow = await ops.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n if (configRow) {\n const replacements = new Map(migrations.map(({ from, to }) => [from, to] as const));\n const selected = configRow.config[integrationId]?.sourceIds ?? [];\n const nextSelected = [...new Set(selected.map(sourceId => replacements.get(sourceId) ?? sourceId))];\n if (\n nextSelected.length !== selected.length ||\n nextSelected.some((sourceId, index) => sourceId !== selected[index])\n ) {\n const config = structuredClone(configRow.config);\n config[integrationId] = {\n ...(config[integrationId] ?? { enabled: true }),\n sourceIds: nextSelected.length > 0 ? nextSelected : null,\n };\n await ops.updateMany('intake_org_settings', { org_id: orgId }, { config, updated_at: now });\n }\n }\n return { migrations, conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Label routes in the org, optionally narrowed to one project and/or integration. Sorted by label. */\n async listLabelRoutes({\n orgId,\n factoryProjectId,\n integrationId,\n }: {\n orgId: string;\n factoryProjectId?: string;\n integrationId?: string;\n }): Promise<IntakeLabelRoute[]> {\n const rows = await this.#db.findMany<IntakeLabelRouteRow>('intake_label_routes', {\n org_id: orgId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return rows.map(toIntakeLabelRoute).sort((a, b) => a.label.localeCompare(b.label));\n }\n\n async setLabelRoute({\n orgId,\n factoryProjectId,\n integrationId,\n label,\n board,\n userId,\n }: {\n orgId: string;\n factoryProjectId: string;\n integrationId: string;\n label: string;\n board: string;\n userId?: string;\n }): Promise<void> {\n const where = {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n integration_id: integrationId,\n label: normalizeIntakeLabel(label),\n };\n const now = new Date();\n const patch = { board, updated_at: now };\n const updated = await this.#db.updateMany('intake_label_routes', where, patch);\n if (updated > 0) return;\n try {\n await this.#db.insertOne('intake_label_routes', {\n ...where,\n board,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n await this.#db.updateMany('intake_label_routes', where, patch);\n }\n }\n\n /** Remove a label route; returns the route that was removed, or `null` when none existed. */\n async clearLabelRoute({\n orgId,\n factoryProjectId,\n integrationId,\n label,\n }: {\n orgId: string;\n factoryProjectId: string;\n integrationId: string;\n label: string;\n }): Promise<IntakeLabelRoute | null> {\n const where = {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n integration_id: integrationId,\n label: normalizeIntakeLabel(label),\n };\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<IntakeLabelRouteRow>('intake_label_routes', where);\n if (!row) return null;\n await ops.deleteMany('intake_label_routes', where);\n return toIntakeLabelRoute(row);\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,8BAAb,cAAiD,MAAM;CACrD,cAAc;EACZ,MAAM,kDAAkD;EACxD,KAAK,OAAO;CACd;AACF;AAEA,eAAe,qBAAqB,KA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AA8B,uBAAuB;GAC/E,QAAQ;GACR,GAAI,mBAAmB,EAAE,oBAAoB,iBAAiB,IAAI,CAAC;GACnE,GAAI,gBAAgB,EAAE,gBAAgB,cAAc,IAAI,CAAC;EAC3D,CAAC,EAAA,CACW,IAAI,kBAAkB,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,MAAM,cAAc,EAAE,KAAK,CAAC;CACnF;CAEA,MAAM,cAAc,EAClB,OACA,kBACA,eACA,OACA,OACA,UAQgB;EAChB,MAAM,QAAQ;GACZ,QAAQ;GACR,oBAAoB;GACpB,gBAAgB;GAChB,OAAO,qBAAqB,KAAK;EACnC;EACA,MAAM,sBAAM,IAAI,KAAK;EACrB,MAAM,QAAQ;GAAE;GAAO,YAAY;EAAI;EAEvC,IAAI,MADkB,KAAK,IAAI,WAAW,uBAAuB,OAAO,KAAK,IAC/D,GAAG;EACjB,IAAI;GACF,MAAM,KAAK,IAAI,UAAU,uBAAuB;IAC9C,GAAG;IACH;IACA,oBAAoB,UAAU;IAC9B,YAAY;IACZ,YAAY;GACd,CAAC;EACH,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,uBAAuB,MAAM;GACpD,MAAM,KAAK,IAAI,WAAW,uBAAuB,OAAO,KAAK;EAC/D;CACF;;CAGA,MAAM,gBAAgB,EACpB,OACA,kBACA,eACA,SAMmC;EACnC,MAAM,QAAQ;GACZ,QAAQ;GACR,oBAAoB;GACpB,gBAAgB;GAChB,OAAO,qBAAqB,KAAK;EACnC;EACA,OAAO,KAAK,QAAQ,gBAClB,OAAM,QAAO;GACX,MAAM,MAAM,MAAM,IAAI,QAA6B,uBAAuB,KAAK;GAC/E,IAAI,CAAC,KAAK,OAAO;GACjB,MAAM,IAAI,WAAW,uBAAuB,KAAK;GACjD,OAAO,mBAAmB,GAAG;EAC/B,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/intake/base.ts"],"sourcesContent":["/**\n * Org-wide intake selections for every configured intake integration.\n *\n * Integration ids are dynamic. Each integration contributes provider-neutral\n * sources through `FactoryIntegration.intake`; this domain only persists which\n * source ids the organization selected. The selection feeds shared boards, so\n * every member reads the same one.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nexport class FactoryProjectNotFoundError extends Error {\n constructor() {\n super('Factory project not found for this organization.');\n this.name = 'FactoryProjectNotFoundError';\n }\n}\n\nasync function assertFactoryProject(ops: FactoryStorageOps, orgId: string, factoryProjectId: string): Promise<void> {\n if (!(await ops.findOne('factory_projects', { org_id: orgId, id: factoryProjectId }))) {\n throw new FactoryProjectNotFoundError();\n }\n}\n\nexport interface IntakeSelection {\n enabled: boolean;\n /** Provider-owned source ids; `null` means nothing is selected. */\n sourceIds: string[] | null;\n repositoryByLinearProject?: Record<string, string>;\n}\n\nexport type IntakeConfig = Record<string, IntakeSelection>;\n\nexport const DEFAULT_INTAKE_CONFIG: IntakeConfig = {};\n\nexport const INTAKE_ORG_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_org_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_org_settings_org_unique', columns: ['org_id'] }],\n};\n\n/** Collection evolution is additive, so the per-member unique index cannot be narrowed: rows stay and are folded at boot. */\nexport const LEGACY_INTAKE_USER_SETTINGS_SCHEMA: CollectionSchema = {\n name: 'intake_settings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n user_id: { type: 'text' },\n config: { type: 'json' },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'intake_settings_org_user_unique', columns: ['org_id', 'user_id'] }],\n};\n\n/** What the org effectively saw while selections were personal: a member's sources fed the shared board only while their switch was on. */\nexport function mergeIntakeSelections(configs: readonly IntakeConfig[]): IntakeConfig {\n const merged: IntakeConfig = Object.create(null);\n for (const config of configs) {\n for (const [integrationId, selection] of Object.entries(config)) {\n const current = merged[integrationId] ?? { enabled: false, sourceIds: null };\n const syncing = selection.enabled ? (selection.sourceIds ?? []) : [];\n const sourceIds = [...new Set([...(current.sourceIds ?? []), ...syncing])];\n merged[integrationId] = {\n enabled: current.enabled || selection.enabled,\n sourceIds: sourceIds.length ? sourceIds : null,\n };\n }\n }\n return merged;\n}\n\n/**\n * Binds an intake source to the Factory project its items belong to.\n *\n * Intake selections are org-wide, so they cannot say *where* an\n * ingested item should land. GitHub items are naturally scoped by their linked\n * repository; providers without that link (Linear) need this explicit binding\n * so viewing one project's board cannot materialize another project's items.\n *\n * Frozen: its unique index allows one binding per source, and indexes cannot be\n * narrowed, so bindings moved to {@link INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA}. Rows\n * are copied once at boot and never written again; the collection stays\n * registered so an earlier build that is rolled back to still finds them.\n */\nexport const INTAKE_SOURCE_BINDINGS_SCHEMA: CollectionSchema = {\n name: 'intake_source_bindings',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_bindings_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_bindings_org_integration_source_unique',\n columns: ['org_id', 'integration_id', 'source_id'],\n },\n ],\n};\n\n/**\n * Binds an intake source to a Factory project, one row per (source, Factory\n * project). Most integrations keep one binding per source and rebinding moves\n * it; integrations with `Intake.bindingLabelFilters` let several Factory\n * projects share a source, each taking the issues carrying its own labels.\n */\nexport const INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA: CollectionSchema = {\n name: 'intake_source_subscriptions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n integration_id: { type: 'text' },\n source_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n /** Retired: intake routes decide where a source's cards land. Nothing reads or writes it. */\n board: { type: 'text', nullable: true },\n /** Labels whose issues this binding takes, as the user typed them; `null` takes every unclaimed issue. */\n labels: { type: 'json', nullable: true },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_source_subscriptions_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_source_subscriptions_org_integration_source_project_unique',\n columns: ['org_id', 'integration_id', 'source_id', 'factory_project_id'],\n },\n ],\n};\n\n/** One-time data migrations that have run, so none re-runs over rows users have changed since. */\nexport const INTAKE_DATA_MIGRATIONS_SCHEMA: CollectionSchema = {\n name: 'intake_data_migrations',\n columns: {\n name: { type: 'text', primaryKey: true },\n completed_at: { type: 'timestamp' },\n },\n};\n\nconst COPY_LEGACY_BINDINGS_MIGRATION = 'copy_intake_source_bindings_to_subscriptions';\n\nexport interface IntakeSourceBinding {\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n /** Labels whose issues this binding takes; `null` takes every issue no other binding's labels claim. */\n labels: string[] | null;\n createdAt: Date;\n}\n\n/** Another Factory project's binding that already takes some of the requested issues. */\nexport interface IntakeBindingConflict {\n factoryProjectId: string;\n /** The overlapping labels, or `null` when both bindings take all unclaimed issues. */\n labels: string[] | null;\n}\n\n/** Bindings on one source in precedence order: the oldest binding wins an issue two of them match. */\nfunction inPrecedenceOrder<T extends Pick<IntakeSourceBinding, 'createdAt' | 'factoryProjectId'>>(\n bindings: readonly T[],\n): T[] {\n return [...bindings].sort(\n (left, right) =>\n left.createdAt.getTime() - right.createdAt.getTime() ||\n left.factoryProjectId.localeCompare(right.factoryProjectId),\n );\n}\n\n/**\n * The slice of a shared source's issues `binding` takes, given every binding\n * on that source (`siblings` may include `binding` itself). Label bindings beat\n * the all-issues binding, and an issue carrying labels of two label bindings\n * goes to the older one.\n */\nexport function bindingLabelSlice(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n): { include: string[] | null; exclude: string[] } {\n const labelled = inPrecedenceOrder(\n siblings.filter(sibling => sibling.labels !== null && sibling.factoryProjectId !== binding.factoryProjectId),\n );\n if (binding.labels === null) {\n return { include: null, exclude: labelled.flatMap(sibling => sibling.labels ?? []) };\n }\n const older = labelled.filter(sibling => inPrecedenceOrder([sibling, binding])[0] === sibling);\n return { include: binding.labels, exclude: older.flatMap(sibling => sibling.labels ?? []) };\n}\n\n/** Whether an issue carrying `labels` falls in `binding`'s slice of its source. */\nexport function bindingTakesIssue(\n binding: Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>,\n siblings: readonly Pick<IntakeSourceBinding, 'factoryProjectId' | 'labels' | 'createdAt'>[],\n labels: readonly string[],\n): boolean {\n const carried = new Set(labels.map(normalizeIntakeLabel));\n const { include, exclude } = bindingLabelSlice(binding, siblings);\n if (exclude.some(label => carried.has(normalizeIntakeLabel(label)))) return false;\n return include === null || include.some(label => carried.has(normalizeIntakeLabel(label)));\n}\n\n/** Trim and de-duplicate case-insensitively, keeping the first spelling the user typed. */\nexport function normalizeBindingLabels(labels: readonly string[]): string[] {\n const seen = new Set<string>();\n const kept: string[] = [];\n for (const label of labels) {\n const trimmed = label.trim();\n const key = normalizeIntakeLabel(trimmed);\n if (!key || seen.has(key)) continue;\n seen.add(key);\n kept.push(trimmed);\n }\n return kept;\n}\n\n/**\n * Retired: label routes sent labelled items to a board. Intake routes replaced them; the collection\n * stays registered so an earlier build that is rolled back to still finds it, but nothing reads or\n * writes it.\n */\nexport const INTAKE_LABEL_ROUTES_SCHEMA: CollectionSchema = {\n name: 'intake_label_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n integration_id: { type: 'text' },\n /** Label as the provider reports it; matched case-insensitively. */\n label: { type: 'text' },\n board: { type: 'text' },\n created_by_user_id: { type: 'text', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'intake_label_routes_project_idx', columns: ['org_id', 'factory_project_id'] }],\n uniqueIndexes: [\n {\n name: 'intake_label_routes_org_project_integration_label_unique',\n columns: ['org_id', 'factory_project_id', 'integration_id', 'label'],\n },\n ],\n};\n\n/** Labels are matched the way GitHub treats them: case-insensitively. */\nexport function normalizeIntakeLabel(label: string): string {\n return label.trim().toLowerCase();\n}\n\ntype IntakeSourceBindingRow = {\n org_id: string;\n integration_id: string;\n source_id: string;\n factory_project_id: string;\n labels?: string[] | null;\n created_by_user_id?: string | null;\n created_at: Date;\n};\nfunction toIntakeSourceBinding(row: IntakeSourceBindingRow): IntakeSourceBinding {\n return {\n integrationId: row.integration_id,\n sourceId: row.source_id,\n factoryProjectId: row.factory_project_id,\n labels: row.labels ?? null,\n createdAt: row.created_at,\n };\n}\n\n/** Overlap between a requested binding and the other Factory projects' bindings on the same source. */\nfunction bindingConflicts(\n factoryProjectId: string,\n labels: string[] | null,\n rows: readonly IntakeSourceBindingRow[],\n): IntakeBindingConflict[] {\n const requested = new Set(labels?.map(normalizeIntakeLabel));\n return rows.flatMap((row): IntakeBindingConflict[] => {\n if (row.factory_project_id === factoryProjectId) return [];\n const theirs = row.labels ?? null;\n if (labels === null || theirs === null) {\n return labels === null && theirs === null ? [{ factoryProjectId: row.factory_project_id, labels: null }] : [];\n }\n const overlap = theirs.filter(label => requested.has(normalizeIntakeLabel(label)));\n return overlap.length > 0 ? [{ factoryProjectId: row.factory_project_id, labels: overlap }] : [];\n });\n}\n\n/** Update one (source, Factory project) binding in place, keeping its age, or insert it. */\nasync function upsertBinding(\n ops: FactoryStorageOps,\n key: { org_id: string; integration_id: string; source_id: string; factory_project_id: string },\n patch: { labels: string[] | null },\n userId: string | undefined,\n): Promise<void> {\n const now = new Date();\n const updated = await ops.updateMany('intake_source_subscriptions', key, { ...patch, updated_at: now });\n if (updated > 0) return;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n ...patch,\n created_by_user_id: userId ?? null,\n created_at: now,\n updated_at: now,\n });\n}\n\nexport class IntakeStorage extends FactoryStorageDomain {\n constructor() {\n super('intake');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n INTAKE_ORG_SETTINGS_SCHEMA,\n LEGACY_INTAKE_USER_SETTINGS_SCHEMA,\n INTAKE_SOURCE_BINDINGS_SCHEMA,\n INTAKE_SOURCE_SUBSCRIPTIONS_SCHEMA,\n INTAKE_DATA_MIGRATIONS_SCHEMA,\n INTAKE_LABEL_ROUTES_SCHEMA,\n ]);\n await this.#foldLegacyUserSelections();\n await this.#copyLegacyBindings();\n }\n\n /**\n * Copy `intake_source_bindings` into `intake_source_subscriptions` as\n * all-issues bindings, once. The marker and the copy commit together, so a\n * boot racing another cannot re-copy a binding removed after the first\n * boot finished.\n */\n async #copyLegacyBindings(): Promise<void> {\n try {\n await this.storage.withTransaction(\n async ops => {\n if (await ops.findOne('intake_data_migrations', { name: COPY_LEGACY_BINDINGS_MIGRATION })) return;\n const legacyRows = await ops.findMany<IntakeSourceBindingRow & { updated_at: Date }>(\n 'intake_source_bindings',\n {},\n );\n for (const row of legacyRows) {\n const key = {\n org_id: row.org_id,\n integration_id: row.integration_id,\n source_id: row.source_id,\n factory_project_id: row.factory_project_id,\n };\n if (await ops.findOne('intake_source_subscriptions', key)) continue;\n await ops.insertOne('intake_source_subscriptions', {\n ...key,\n labels: null,\n created_by_user_id: row.created_by_user_id ?? null,\n created_at: row.created_at,\n updated_at: row.updated_at,\n });\n }\n await ops.insertOne('intake_data_migrations', {\n name: COPY_LEGACY_BINDINGS_MIGRATION,\n completed_at: new Date(),\n });\n },\n { isolationLevel: 'serializable' },\n );\n } catch (error) {\n // Postgres can report the boot that lost the race as a unique violation instead of a serialization failure.\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n }\n\n async #foldLegacyUserSelections(): Promise<void> {\n const legacyRows = await this.ops.findMany<{ org_id: string; config: IntakeConfig }>('intake_settings', {});\n const byOrg = new Map<string, IntakeConfig[]>();\n for (const row of legacyRows) {\n byOrg.set(row.org_id, [...(byOrg.get(row.org_id) ?? []), row.config]);\n }\n for (const [orgId, configs] of byOrg) {\n const folded = await this.ops.findOne('intake_org_settings', { org_id: orgId });\n if (folded) continue;\n await this.#insertConfigIfAbsent(orgId, mergeIntakeSelections(configs));\n }\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('intake_org_settings', {});\n await this.ops.deleteMany('intake_settings', {});\n await this.ops.deleteMany('intake_source_bindings', {});\n await this.ops.deleteMany('intake_source_subscriptions', {});\n await this.ops.deleteMany('intake_data_migrations', {});\n await this.ops.deleteMany('intake_label_routes', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async getConfig({\n orgId,\n integrationIds,\n }: {\n orgId: string;\n /**\n * When provided, the result contains exactly these integration ids, with\n * unset integrations defaulting to `{ enabled: true, sourceIds: null }`.\n */\n integrationIds?: string[];\n }): Promise<IntakeConfig> {\n const row = await this.#db.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n const saved = structuredClone(row?.config ?? DEFAULT_INTAKE_CONFIG);\n if (!integrationIds) return saved;\n return Object.fromEntries(\n integrationIds.map(integrationId => [integrationId, saved[integrationId] ?? { enabled: true, sourceIds: null }]),\n );\n }\n\n async saveConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<void> {\n const now = new Date();\n const where = { org_id: orgId };\n const updated = await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n if (updated > 0) return;\n if (await this.#insertConfigIfAbsent(orgId, config)) return;\n await this.#db.updateMany('intake_org_settings', where, { config, updated_at: now });\n }\n\n /** Overlay `config` onto the stored selections; integrations it omits keep their stored value. */\n async mergeConfig({ orgId, config }: { orgId: string; config: IntakeConfig }): Promise<IntakeConfig> {\n const merged: IntakeConfig = Object.assign(Object.create(null), await this.getConfig({ orgId }), config);\n await this.saveConfig({ orgId, config: merged });\n return merged;\n }\n\n async #insertConfigIfAbsent(orgId: string, config: IntakeConfig): Promise<boolean> {\n const now = new Date();\n try {\n await this.#db.insertOne('intake_org_settings', { org_id: orgId, config, created_at: now, updated_at: now });\n return true;\n } catch (error) {\n if (error instanceof UniqueViolationError) return false;\n throw error;\n }\n }\n\n /** Every source binding in the org, optionally narrowed to one integration, oldest first. */\n async listBindings({\n orgId,\n integrationId,\n }: {\n orgId: string;\n integrationId?: string;\n }): Promise<IntakeSourceBinding[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n ...(integrationId ? { integration_id: integrationId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding));\n }\n\n /** Source ids bound to one Factory project. Empty means \"nothing bound\". */\n async listBoundSourceIds({\n orgId,\n integrationId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n factoryProjectId: string;\n }): Promise<string[]> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n factory_project_id: factoryProjectId,\n });\n return rows.map(row => row.source_id);\n }\n\n /**\n * One Factory project's binding of a source, or `null` when it has none.\n * Without `factoryProjectId`, the source's oldest binding — for integrations\n * that keep one binding per source.\n */\n async getBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const rows = await this.#db.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n });\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0] ?? null;\n }\n\n /**\n * Remove one Factory project's binding of a source, or — without\n * `factoryProjectId` — every binding of it. Returns the (oldest) removed\n * binding, or `null` when there was none.\n */\n async clearBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId?: string;\n }): Promise<IntakeSourceBinding | null> {\n const where = {\n org_id: orgId,\n integration_id: integrationId,\n source_id: sourceId,\n ...(factoryProjectId ? { factory_project_id: factoryProjectId } : {}),\n };\n return this.storage.withTransaction(\n async ops => {\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', where);\n if (rows.length === 0) return null;\n await ops.deleteMany('intake_source_subscriptions', where);\n return inPrecedenceOrder(rows.map(toIntakeSourceBinding))[0]!;\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Release every source a Factory project was bound to, so the others can take\n * them. Pass the transaction deleting the project, so no binding lands in between.\n */\n async clearProjectBindings(\n { orgId, factoryProjectId }: { orgId: string; factoryProjectId: string },\n ops: FactoryStorageOps = this.#db,\n ): Promise<void> {\n await ops.deleteMany('intake_source_subscriptions', { org_id: orgId, factory_project_id: factoryProjectId });\n }\n\n /**\n * Bind a source to one Factory project, moving it away from any other: the\n * source keeps a single binding, which takes all of its issues.\n */\n async setBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n userId?: string;\n }): Promise<void> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n await this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n for (const row of rows) {\n if (row.factory_project_id === factoryProjectId) continue;\n await ops.deleteMany('intake_source_subscriptions', {\n ...source,\n factory_project_id: row.factory_project_id,\n });\n }\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: null }, userId);\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /**\n * Bind a source to one Factory project alongside other Factory projects'\n * bindings of it, taking the issues carrying one of `labels` — or, with\n * `labels: null`, every issue no label binding claims. Rejected with the\n * overlapping bindings when another Factory project already takes some of\n * those labels, or already takes all unclaimed issues.\n */\n async setSharedBinding({\n orgId,\n integrationId,\n sourceId,\n factoryProjectId,\n labels,\n userId,\n }: {\n orgId: string;\n integrationId: string;\n sourceId: string;\n factoryProjectId: string;\n labels: string[] | null;\n userId?: string;\n }): Promise<{ conflicts: IntakeBindingConflict[] }> {\n const source = { org_id: orgId, integration_id: integrationId, source_id: sourceId };\n const kept = labels === null ? null : normalizeBindingLabels(labels);\n return this.storage.withTransaction(\n async ops => {\n await assertFactoryProject(ops, orgId, factoryProjectId);\n const rows = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', source);\n const conflicts = bindingConflicts(factoryProjectId, kept, rows);\n if (conflicts.length > 0) return { conflicts };\n await upsertBinding(ops, { ...source, factory_project_id: factoryProjectId }, { labels: kept }, userId);\n return { conflicts: [] };\n },\n { isolationLevel: 'serializable' },\n );\n }\n\n /** Atomically replace legacy provider source ids in both selection and routing state. */\n async migrateSourceIds({\n orgId,\n integrationId,\n migrations,\n }: {\n orgId: string;\n integrationId: string;\n migrations: Array<{ from: string; to: string }>;\n }): Promise<{ migrations: Array<{ from: string; to: string }>; conflicts: Array<{ from: string; to: string }> }> {\n if (migrations.length === 0) return { migrations: [], conflicts: [] };\n return this.storage.withTransaction(\n async ops => {\n const bindings = await ops.findMany<IntakeSourceBindingRow>('intake_source_subscriptions', {\n org_id: orgId,\n integration_id: integrationId,\n });\n const bindingsBySource = new Map<string, IntakeSourceBindingRow[]>();\n for (const binding of bindings) {\n bindingsBySource.set(binding.source_id, [...(bindingsBySource.get(binding.source_id) ?? []), binding]);\n }\n // Where a source's issues land: every Factory project and label slice bound to it.\n const destination = (rows: IntakeSourceBindingRow[]) =>\n rows\n .map(row => `${row.factory_project_id}\\0${JSON.stringify(row.labels ?? null)}`)\n .sort()\n .join('\\n');\n const grouped = new Map<string, Array<{ from: string; to: string }>>();\n for (const migration of migrations) {\n grouped.set(migration.to, [...(grouped.get(migration.to) ?? []), migration]);\n }\n const conflicts: Array<{ from: string; to: string }> = [];\n for (const [to, group] of grouped) {\n const candidates = [bindingsBySource.get(to), ...group.map(({ from }) => bindingsBySource.get(from))].filter(\n (rows): rows is IntakeSourceBindingRow[] => rows !== undefined,\n );\n if (new Set(candidates.map(destination)).size > 1) conflicts.push(...group);\n }\n if (conflicts.length > 0) return { migrations: [], conflicts };\n\n const now = new Date();\n for (const [to, group] of grouped) {\n const legacy = group.filter(({ from }) => bindingsBySource.has(from));\n const scope = { org_id: orgId, integration_id: integrationId };\n if (!bindingsBySource.has(to) && legacy.length > 0) {\n const [first, ...duplicates] = legacy;\n await ops.updateMany(\n 'intake_source_subscriptions',\n { ...scope, source_id: first!.from },\n { source_id: to, updated_at: now },\n );\n for (const duplicate of duplicates) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: duplicate.from });\n }\n } else {\n for (const entry of legacy) {\n await ops.deleteMany('intake_source_subscriptions', { ...scope, source_id: entry.from });\n }\n }\n }\n\n const configRow = await ops.findOne<{ config: IntakeConfig }>('intake_org_settings', { org_id: orgId });\n if (configRow) {\n const replacements = new Map(migrations.map(({ from, to }) => [from, to] as const));\n const selected = configRow.config[integrationId]?.sourceIds ?? [];\n const nextSelected = [...new Set(selected.map(sourceId => replacements.get(sourceId) ?? sourceId))];\n if (\n nextSelected.length !== selected.length ||\n nextSelected.some((sourceId, index) => sourceId !== selected[index])\n ) {\n const config = structuredClone(configRow.config);\n config[integrationId] = {\n ...(config[integrationId] ?? { enabled: true }),\n sourceIds: nextSelected.length > 0 ? nextSelected : null,\n };\n await ops.updateMany('intake_org_settings', { org_id: orgId }, { config, updated_at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E,GAAG;MAAO,WAAW,UAAU;KAAK,CAAC;IAE/F,OACE,KAAK,MAAM,SAAS,QAClB,MAAM,IAAI,WAAW,+BAA+B;KAAE,GAAG;KAAO,WAAW,MAAM;IAAK,CAAC;GAG7F;GAEA,MAAM,YAAY,MAAM,IAAI,QAAkC,uBAAuB,EAAE,QAAQ,MAAM,CAAC;GACtG,IAAI,WAAW;IACb,MAAM,eAAe,IAAI,IAAI,WAAW,KAAK,EAAE,MAAM,SAAS,CAAC,MAAM,EAAE,CAAU,CAAC;IAClF,MAAM,WAAW,UAAU,OAAO,cAAc,EAAE,aAAa,CAAC;IAChE,MAAM,eAAe,CAAC,GAAG,IAAI,IAAI,SAAS,KAAI,aAAY,aAAa,IAAI,QAAQ,KAAK,QAAQ,CAAC,CAAC;IAClG,IACE,aAAa,WAAW,SAAS,UACjC,aAAa,MAAM,UAAU,UAAU,aAAa,SAAS,MAAM,GACnE;KACA,MAAM,SAAS,gBAAgB,UAAU,MAAM;KAC/C,OAAO,iBAAiB;MACtB,GAAI,OAAO,kBAAkB,EAAE,SAAS,KAAK;MAC7C,WAAW,aAAa,SAAS,IAAI,eAAe;KACtD;KACA,MAAM,IAAI,WAAW,uBAAuB,EAAE,QAAQ,MAAM,GAAG;MAAE;MAAQ,YAAY;KAAI,CAAC;IAC5F;GACF;GACA,OAAO;IAAE;IAAY,WAAW,CAAC;GAAE;EACrC,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
@@ -32,8 +32,6 @@ export interface FactoryProject {
32
32
  modelScope: FactoryModelScope;
33
33
  /** Thinking level for this Factory's sessions and runs that have not picked their own. */
34
34
  defaultThinkingLevel: ThinkingLevelSetting;
35
- /** Whether rules may start agent runs on their own; off, a run waits for approval on its card. */
36
- autoRunEnabled: boolean;
37
35
  /** Workspace root in the sandbox; linked repositories are checked out beneath it. */
38
36
  sandboxWorkingDirectory: string | null;
39
37
  /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */
@@ -63,13 +61,16 @@ export interface FactoryProject {
63
61
  buildOnPushEnabled: boolean;
64
62
  /** Minutes after a push-triggered attempt during which further pushes do not build. */
65
63
  buildPushDebounceMinutes: number;
66
- /** Whether Review agents publish their test results as a commit check. Defaults to off. */
67
- reviewTestChecksEnabled: boolean;
68
- /** Whether Work items get an independent self-review before the change request opens. Defaults to off. */
69
- selfReviewEnabled: boolean;
70
64
  createdAt: Date;
71
65
  updatedAt: Date;
72
66
  }
67
+ /** Project switches the board replaced, as last stored. */
68
+ export interface RetiredAutomationSettings {
69
+ /** Runs started without a person on every phase. */
70
+ autoRunEnabled: boolean;
71
+ /** Cards on a board with a self-review phase went through it. */
72
+ selfReviewEnabled: boolean;
73
+ }
73
74
  export interface CreateFactoryProjectInput {
74
75
  name: string;
75
76
  description?: string | null;
@@ -82,7 +83,6 @@ export interface UpdateFactoryProjectInput {
82
83
  defaultModelId?: string | null;
83
84
  modelScope?: FactoryModelScope;
84
85
  defaultThinkingLevel?: ThinkingLevelSetting;
85
- autoRunEnabled?: boolean;
86
86
  sandboxWorkingDirectory?: string | null;
87
87
  sandboxSettings?: Record<string, unknown> | null;
88
88
  workspaceSetupCommand?: string | null;
@@ -94,8 +94,6 @@ export interface UpdateFactoryProjectInput {
94
94
  lastBuildAttemptedAt?: Date | null;
95
95
  buildOnPushEnabled?: boolean;
96
96
  buildPushDebounceMinutes?: number;
97
- reviewTestChecksEnabled?: boolean;
98
- selfReviewEnabled?: boolean;
99
97
  }
100
98
  export declare const FACTORY_PROJECTS_SCHEMA: CollectionSchema;
101
99
  export declare class FactoryProjectsStorage extends FactoryStorageDomain {
@@ -116,6 +114,16 @@ export declare class FactoryProjectsStorage extends FactoryStorageDomain {
116
114
  orgId: string;
117
115
  id: string;
118
116
  }): Promise<FactoryProject | null>;
117
+ /**
118
+ * The retired automation switches as the project last stored them, read only by the one-time
119
+ * board migrations that carry them into its boards. Null when the project doesn't exist.
120
+ */
121
+ retiredAutomationSettings({ orgId, id }: {
122
+ orgId: string;
123
+ id: string;
124
+ },
125
+ /** A transaction's ops, to read it inside that transaction. */
126
+ ops?: FactoryStorageOps): Promise<RetiredAutomationSettings | null>;
119
127
  getById({ id }: {
120
128
  id: string;
121
129
  }): Promise<FactoryProject | null>;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/projects/base.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAIhF,eAAO,MAAM,mCAAmC,KAAK,CAAC;AACtD,eAAO,MAAM,oBAAoB,YAAI,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAU,CAAC;AAC3E,MAAM,MAAM,iBAAiB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AACtE,iGAAiG;AACjG,MAAM,MAAM,mBAAmB,GAAG,OAAO,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;AAEvE;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,iBAAiB,EAAE,OAAO,EAAE,KAAK,GAAG,SAAS,GAAG,mBAAmB,CAG7G;AAED;;;;GAIG;AACH,wBAAgB,4BAA4B,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM,CAE7E;AAED,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,EAAE,MAAM,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,o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,OAAO,EACP,UAAU,EACV,KAAK,EACL,GAAgB,GACjB,EAAE;QACD,EAAE,EAAE,MAAM,CAAC;QACX,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC9B,GAAG,CAAC,EAAE,IAAI,CAAC;KACZ,GAAG,OAAO,CAAC,OAAO,CAAC,CAUnB;IAED,2GAA2G;IACrG,MAAM,CACV,EAAE,KAAK,EAAE,EAAE,EAAE,EAAE;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,EAC5C,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,KAAK,OAAO,CAAC,IAAI,CAAC,GAClD,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAWhC;CACF"}
@@ -150,7 +150,6 @@ function toFactoryProject(row) {
150
150
  defaultModelId: row.default_model_id,
151
151
  modelScope: row.model_scope === "factory" || row.model_scope === "user" ? row.model_scope : "hybrid",
152
152
  defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level) ? row.default_thinking_level : DEFAULT_THINKING_LEVEL,
153
- autoRunEnabled: row.auto_run_enabled,
154
153
  sandboxWorkingDirectory: row.sandbox_working_directory ?? null,
155
154
  sandboxSettings: row.sandbox_settings ?? null,
156
155
  workspaceSetupCommand: row.workspace_setup_command ?? null,
@@ -164,8 +163,6 @@ function toFactoryProject(row) {
164
163
  buildStartUncertain: row.build_start_uncertain ?? false,
165
164
  buildOnPushEnabled: row.build_on_push_enabled ?? false,
166
165
  buildPushDebounceMinutes: row.build_push_debounce_minutes ?? 10,
167
- reviewTestChecksEnabled: row.review_test_checks_enabled ?? false,
168
- selfReviewEnabled: row.self_review_enabled ?? false,
169
166
  createdAt: row.created_at,
170
167
  updatedAt: row.updated_at
171
168
  };
@@ -192,7 +189,6 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
192
189
  description: input.description ?? null,
193
190
  default_model_id: input.defaultModelId ?? null,
194
191
  model_scope: input.modelScope ?? "hybrid",
195
- auto_run_enabled: false,
196
192
  created_at: now,
197
193
  updated_at: now
198
194
  }));
@@ -210,6 +206,21 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
210
206
  });
211
207
  return row ? toFactoryProject(row) : null;
212
208
  }
209
+ /**
210
+ * The retired automation switches as the project last stored them, read only by the one-time
211
+ * board migrations that carry them into its boards. Null when the project doesn't exist.
212
+ */
213
+ async retiredAutomationSettings({ orgId, id }, ops = this.#db) {
214
+ const row = await ops.findOne("factory_projects", {
215
+ org_id: orgId,
216
+ id
217
+ });
218
+ if (!row) return null;
219
+ return {
220
+ autoRunEnabled: Boolean(row.auto_run_enabled),
221
+ selfReviewEnabled: Boolean(row.self_review_enabled)
222
+ };
223
+ }
213
224
  async getById({ id }) {
214
225
  const row = await this.#db.findOne("factory_projects", { id });
215
226
  return row ? toFactoryProject(row) : null;
@@ -227,7 +238,6 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
227
238
  ...changes.defaultModelId !== void 0 ? { default_model_id: changes.defaultModelId } : {},
228
239
  ...changes.modelScope !== void 0 ? { model_scope: changes.modelScope } : {},
229
240
  ...changes.defaultThinkingLevel !== void 0 ? { default_thinking_level: changes.defaultThinkingLevel } : {},
230
- ...changes.autoRunEnabled !== void 0 ? { auto_run_enabled: changes.autoRunEnabled } : {},
231
241
  ...changes.sandboxWorkingDirectory !== void 0 ? { sandbox_working_directory: changes.sandboxWorkingDirectory } : {},
232
242
  ...changes.sandboxSettings !== void 0 ? { sandbox_settings: changes.sandboxSettings } : {},
233
243
  ...changes.workspaceSetupCommand !== void 0 ? { workspace_setup_command: changes.workspaceSetupCommand } : {},
@@ -239,8 +249,6 @@ var FactoryProjectsStorage = class extends FactoryStorageDomain {
239
249
  ...changes.lastBuildAttemptedAt !== void 0 ? { last_build_attempted_at: changes.lastBuildAttemptedAt } : {},
240
250
  ...changes.buildOnPushEnabled !== void 0 ? { build_on_push_enabled: changes.buildOnPushEnabled } : {},
241
251
  ...changes.buildPushDebounceMinutes !== void 0 ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes } : {},
242
- ...changes.reviewTestChecksEnabled !== void 0 ? { review_test_checks_enabled: changes.reviewTestChecksEnabled } : {},
243
- ...changes.selfReviewEnabled !== void 0 ? { self_review_enabled: changes.selfReviewEnabled } : {},
244
252
  updated_at: /* @__PURE__ */ new Date()
245
253
  };
246
254
  });
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/projects/base.ts"],"sourcesContent":["import { isThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { FactoryStorageDomain } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_THINKING_LEVEL } from '../../../default-thinking-level.js';\n\nexport const DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES = 10;\nexport const FACTORY_MODEL_SCOPES = ['factory', 'user', 'hybrid'] as const;\nexport type FactoryModelScope = (typeof FACTORY_MODEL_SCOPES)[number];\n/** The single credential scope one session or run resolves from; `hybrid` is never effective. */\nexport type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;\n\n/**\n * Resolve the scope one context runs under. `hybrid` splits by context: work-item runs use the\n * Factory's model and credentials, interactive sessions use the session owner's.\n */\nexport function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope {\n if (scope === 'hybrid') return context === 'run' ? 'factory' : 'user';\n return scope;\n}\n\n/**\n * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the\n * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or\n * the `local` sentinel, so the prefix cannot collide.\n */\nexport function factoryProjectSettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\nexport interface FactoryProject {\n id: string;\n orgId: string;\n createdBy: string;\n name: string;\n description: string | null;\n /** Default model for sessions/runs started under this Factory (null = harness default). */\n defaultModelId: string | null;\n /**\n * Whose model and credentials sessions and runs use: the Factory's, the session owner's, or\n * `hybrid` (owner's for interactive sessions, the Factory's for work-item runs).\n */\n modelScope: FactoryModelScope;\n /** Thinking level for this Factory's sessions and runs that have not picked their own. */\n defaultThinkingLevel: ThinkingLevelSetting;\n /** Whether rules may start agent runs on their own; off, a run waits for approval on its card. */\n autoRunEnabled: boolean;\n /** Workspace root in the sandbox; linked repositories are checked out beneath it. */\n sandboxWorkingDirectory: string | null;\n /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */\n sandboxSettings: Record<string, unknown> | null;\n /** Command run once in the workspace root after every repository's own setup. */\n workspaceSetupCommand: string | null;\n /** Template id of the environment's current build, written by the build path. */\n activeTemplateId: string | null;\n /** Repository slug → commit the active template was built at. */\n activeTemplateHeads: Record<string, string> | null;\n /** Provider build id of the most recent build attempt; its status is read live from the provider. */\n lastBuildId: string | null;\n /** Repository slug → commit the most recent build attempt pinned, so its status can be read back. */\n lastBuildHeads: Record<string, string> | null;\n /** Fingerprint of the settings, repositories and setup commands the most recent build attempt used. */\n lastBuildInputs: string | null;\n /** When the most recent build attempt started, whatever triggered it. */\n lastBuildAttemptedAt: Date | null;\n /** When a push last started a build: the leading edge of the push debounce window. */\n lastPushBuildAt: Date | null;\n /**\n * A run's build-start lease lapsed, so a build it may have started is not\n * on record. Cleared once a run reconciles it with a provider that lists builds.\n */\n buildStartUncertain: boolean;\n /** Whether a push to an environment repository's default branch starts a build. */\n buildOnPushEnabled: boolean;\n /** Minutes after a push-triggered attempt during which further pushes do not build. */\n buildPushDebounceMinutes: number;\n /** Whether Review agents publish their test results as a commit check. Defaults to off. */\n reviewTestChecksEnabled: boolean;\n /** Whether Work items get an independent self-review before the change request opens. Defaults to off. */\n selfReviewEnabled: boolean;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateFactoryProjectInput {\n name: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n}\n\nexport interface UpdateFactoryProjectInput {\n name?: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n defaultThinkingLevel?: ThinkingLevelSetting;\n autoRunEnabled?: boolean;\n sandboxWorkingDirectory?: string | null;\n sandboxSettings?: Record<string, unknown> | null;\n workspaceSetupCommand?: string | null;\n activeTemplateId?: string | null;\n activeTemplateHeads?: Record<string, string> | null;\n lastBuildId?: string | null;\n lastBuildHeads?: Record<string, string> | null;\n lastBuildInputs?: string | null;\n lastBuildAttemptedAt?: Date | null;\n buildOnPushEnabled?: boolean;\n buildPushDebounceMinutes?: number;\n reviewTestChecksEnabled?: boolean;\n selfReviewEnabled?: boolean;\n}\n\nexport const FACTORY_PROJECTS_SCHEMA: CollectionSchema = {\n name: 'factory_projects',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n default_model_id: { type: 'text', nullable: true },\n model_scope: { type: 'text', default: 'hybrid' },\n default_thinking_level: { type: 'text', default: DEFAULT_THINKING_LEVEL },\n // Deprecated: no longer read or written. Kept so existing databases need no\n // migration. Old rows may still hold `true`, so never read it to bring Slack\n // work items back. Drop it in a later migration.\n slack_work_items_enabled: { type: 'boolean', default: false },\n auto_run_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer read or written. Plans are approved per board (`exitTool.autoApprove`).\n auto_approve_plans: { type: 'boolean', default: false },\n sandbox_working_directory: { type: 'text', nullable: true },\n sandbox_settings: { type: 'json', nullable: true },\n workspace_setup_command: { type: 'text', nullable: true },\n active_template_id: { type: 'text', nullable: true },\n active_template_heads: { type: 'json', nullable: true },\n last_build_id: { type: 'text', nullable: true },\n last_build_heads: { type: 'json', nullable: true },\n last_build_inputs: { type: 'text', nullable: true },\n last_build_attempted_at: { type: 'timestamp', nullable: true },\n last_push_build_at: { type: 'timestamp', nullable: true },\n build_start_uncertain: { type: 'boolean', default: false },\n build_start_claim: { type: 'text', nullable: true },\n build_start_claim_expires_at: { type: 'timestamp', nullable: true },\n build_on_push_enabled: { type: 'boolean', default: false },\n build_push_debounce_minutes: { type: 'integer', default: DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES },\n review_test_checks_enabled: { type: 'boolean', default: false },\n self_review_enabled: { type: 'boolean', default: false },\n /** Set once the source-control domain has backfilled repository positions and environment membership. */\n environment_backfilled_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_projects_org_updated_at_idx', columns: ['org_id', 'updated_at'] }],\n};\n\ninterface FactoryProjectDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n name: string;\n description: string | null;\n default_model_id: string | null;\n model_scope: string;\n default_thinking_level: string | null;\n auto_run_enabled: boolean;\n auto_approve_plans: boolean;\n sandbox_working_directory: string | null;\n sandbox_settings: Record<string, unknown> | null;\n workspace_setup_command: string | null;\n active_template_id: string | null;\n active_template_heads: Record<string, string> | null;\n last_build_id: string | null;\n last_build_heads: Record<string, string> | null;\n last_build_inputs: string | null;\n last_build_attempted_at: Date | null;\n last_push_build_at: Date | null;\n build_start_uncertain: boolean | null;\n build_start_claim: string | null;\n build_start_claim_expires_at: Date | null;\n build_on_push_enabled: boolean | null;\n build_push_debounce_minutes: number | null;\n review_test_checks_enabled: boolean | null;\n self_review_enabled: boolean | null;\n environment_backfilled_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toFactoryProject(row: FactoryProjectDbRow): FactoryProject {\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n name: row.name,\n description: row.description,\n defaultModelId: row.default_model_id,\n modelScope: row.model_scope === 'factory' || row.model_scope === 'user' ? row.model_scope : 'hybrid',\n defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level)\n ? row.default_thinking_level\n : DEFAULT_THINKING_LEVEL,\n autoRunEnabled: row.auto_run_enabled,\n sandboxWorkingDirectory: row.sandbox_working_directory ?? null,\n sandboxSettings: row.sandbox_settings ?? null,\n workspaceSetupCommand: row.workspace_setup_command ?? null,\n activeTemplateId: row.active_template_id ?? null,\n activeTemplateHeads: row.active_template_heads ?? null,\n lastBuildId: row.last_build_id ?? null,\n lastBuildHeads: row.last_build_heads ?? null,\n lastBuildInputs: row.last_build_inputs ?? null,\n lastBuildAttemptedAt: row.last_build_attempted_at ?? null,\n lastPushBuildAt: row.last_push_build_at ?? null,\n buildStartUncertain: row.build_start_uncertain ?? false,\n buildOnPushEnabled: row.build_on_push_enabled ?? false,\n buildPushDebounceMinutes: row.build_push_debounce_minutes ?? DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES,\n reviewTestChecksEnabled: row.review_test_checks_enabled ?? false,\n selfReviewEnabled: row.self_review_enabled ?? false,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class FactoryProjectsStorage extends FactoryStorageDomain {\n constructor() {\n super('projects');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([FACTORY_PROJECTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('factory_projects', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async create({\n orgId,\n userId,\n input,\n }: {\n orgId: string;\n userId: string;\n input: CreateFactoryProjectInput;\n }): Promise<FactoryProject> {\n const now = new Date();\n const row = await this.#db.insertOne<FactoryProjectDbRow>('factory_projects', {\n org_id: orgId,\n created_by: userId,\n name: input.name,\n description: input.description ?? null,\n default_model_id: input.defaultModelId ?? null,\n model_scope: input.modelScope ?? 'hybrid',\n auto_run_enabled: false,\n created_at: now,\n updated_at: now,\n });\n return toFactoryProject(row);\n }\n\n async list({ orgId }: { orgId: string }): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n { org_id: orgId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async listAll(): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n {},\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n return row ? toFactoryProject(row) : null;\n }\n\n async getById({ id }: { id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { id });\n return row ? toFactoryProject(row) : null;\n }\n\n async update({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n /** A function input runs in a transaction; writes through its `ops` commit or roll back with the project. */\n input:\n | UpdateFactoryProjectInput\n | ((current: FactoryProject, ops: FactoryStorageOps) => Promise<UpdateFactoryProjectInput | null>);\n }): Promise<FactoryProject | null> {\n const update = (ops: FactoryStorageOps) =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id }, async current => {\n const changes = typeof input === 'function' ? await input(toFactoryProject(current), ops) : input;\n if (changes === null) return null;\n return {\n ...(changes.name !== undefined ? { name: changes.name } : {}),\n ...(changes.description !== undefined ? { description: changes.description } : {}),\n ...(changes.defaultModelId !== undefined ? { default_model_id: changes.defaultModelId } : {}),\n ...(changes.modelScope !== undefined ? { model_scope: changes.modelScope } : {}),\n ...(changes.defaultThinkingLevel !== undefined\n ? { default_thinking_level: changes.defaultThinkingLevel }\n : {}),\n ...(changes.autoRunEnabled !== undefined ? { auto_run_enabled: changes.autoRunEnabled } : {}),\n ...(changes.sandboxWorkingDirectory !== undefined\n ? { sandbox_working_directory: changes.sandboxWorkingDirectory }\n : {}),\n ...(changes.sandboxSettings !== undefined ? { sandbox_settings: changes.sandboxSettings } : {}),\n ...(changes.workspaceSetupCommand !== undefined\n ? { workspace_setup_command: changes.workspaceSetupCommand }\n : {}),\n ...(changes.activeTemplateId !== undefined ? { active_template_id: changes.activeTemplateId } : {}),\n ...(changes.activeTemplateHeads !== undefined ? { active_template_heads: changes.activeTemplateHeads } : {}),\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(changes.buildOnPushEnabled !== undefined ? { build_on_push_enabled: changes.buildOnPushEnabled } : {}),\n ...(changes.buildPushDebounceMinutes !== undefined\n ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes }\n : {}),\n ...(changes.reviewTestChecksEnabled !== undefined\n ? { review_test_checks_enabled: changes.reviewTestChecksEnabled }\n : {}),\n ...(changes.selfReviewEnabled !== undefined ? { self_review_enabled: changes.selfReviewEnabled } : {}),\n updated_at: new Date(),\n };\n });\n // LibSQL's standalone updateAtomic only serializes one client; a transaction\n // also protects a read-dependent update against other database connections.\n const row = typeof input === 'function' ? await this.storage.withTransaction(update) : await update(this.#db);\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * Leading-edge debounce for push-triggered builds: stamps\n * `last_push_build_at = now` and resolves true when no push started a build\n * within the last `debounceMinutes`, else writes nothing and resolves\n * false. Taken right before the provider start, so a push that skips\n * (another run starting, a build in progress) never closes the window. The read and the write run in one transaction, so two concurrent\n * webhooks never both win, even on different database connections.\n */\n async claimBuildAttempt({\n id,\n debounceMinutes,\n now = new Date(),\n }: {\n id: string;\n debounceMinutes: number;\n now?: Date;\n }): Promise<boolean> {\n let claimed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const last = current.last_push_build_at;\n if (last && now.getTime() - last.getTime() < debounceMinutes * 60_000) return null;\n claimed = true;\n return { last_push_build_at: now, updated_at: now };\n }),\n );\n return claimed;\n }\n\n /**\n * Takes the project's build-start lease for `token`. Every trigger (manual,\n * schedule, push) takes it before reading build state and holds it through\n * `builds.start` and recording the result, so two runs never both start a\n * build. `claimed` is false while another run holds an unexpired lease. The\n * holder renews the lease while it works (`renewBuildStart`), so a lease\n * only expires when its run died or stalled. Taking over an expired lease\n * marks the start uncertain (that run's build may have reached the provider\n * unrecorded), and the mark stays until a release resolves it; `uncertain`\n * reports it. Only the claim is transactional; provider calls run outside it.\n */\n async claimBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<{ claimed: boolean; uncertain: boolean }> {\n const result = { claimed: false, uncertain: false };\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const expiresAt = current.build_start_claim_expires_at;\n if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;\n result.claimed = true;\n result.uncertain = Boolean(current.build_start_claim) || current.build_start_uncertain === true;\n return {\n build_start_claim: token,\n build_start_claim_expires_at: new Date(now.getTime() + leaseMs),\n ...(result.uncertain ? { build_start_uncertain: true } : {}),\n updated_at: now,\n };\n }),\n );\n return result;\n }\n\n /**\n * Extends the build-start lease held by `token` to `now + leaseMs`. Resolves\n * false, writing nothing, when `token` no longer holds it.\n */\n async renewBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<boolean> {\n let renewed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n renewed = true;\n return { build_start_claim_expires_at: new Date(now.getTime() + leaseMs), updated_at: now };\n }),\n );\n return renewed;\n }\n\n /**\n * Releases the build-start lease taken with `token` and writes `changes` in\n * the same transaction, but only while `token` still holds the lease. A run\n * whose lease expired and was taken by a newer run writes nothing, so it\n * never clears or overwrites that run's build. `resolved` clears an\n * uncertain start. Resolves false when skipped.\n */\n async releaseBuildStart({\n id,\n token,\n changes = {},\n resolved = false,\n now = new Date(),\n }: {\n id: string;\n token: string;\n resolved?: boolean;\n changes?: Pick<\n UpdateFactoryProjectInput,\n 'lastBuildId' | 'lastBuildHeads' | 'lastBuildInputs' | 'lastBuildAttemptedAt'\n >;\n now?: Date;\n }): Promise<boolean> {\n let released = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n released = true;\n return {\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(resolved ? { build_start_uncertain: false } : {}),\n build_start_claim: null,\n build_start_claim_expires_at: null,\n updated_at: now,\n };\n }),\n );\n return released;\n }\n\n /**\n * Pins the active template to a finished build, but only while that build is\n * still the project's last one. Overlapping runs (Build now during a push\n * build) can finish out of order; the write and the `last_build_id` check\n * run in one transaction so a stale run never overwrites a newer build's\n * pin. Resolves false when the pin was skipped.\n */\n async pinActiveTemplate({\n id,\n buildId,\n templateId,\n heads,\n now = new Date(),\n }: {\n id: string;\n buildId: string;\n templateId: string;\n heads: Record<string, string>;\n now?: Date;\n }): Promise<boolean> {\n let pinned = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.last_build_id !== buildId) return null;\n pinned = true;\n return { active_template_id: templateId, active_template_heads: heads, updated_at: now };\n }),\n );\n return pinned;\n }\n\n /** `release` runs in the deleting transaction, so nothing can be routed to the project between the two. */\n async delete(\n { orgId, id }: { orgId: string; id: string },\n release?: (ops: FactoryStorageOps) => Promise<void>,\n ): Promise<FactoryProject | null> {\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n await release?.(ops);\n await ops.deleteMany('factory_projects', { org_id: orgId, id });\n return toFactoryProject(row);\n },\n { isolationLevel: 'serializable' },\n );\n }\n}\n"],"mappings":";;;;AAOA,MAAa,sCAAsC;AACnD,MAAa,uBAAuB;CAAC;CAAW;CAAQ;AAAQ;;;;;AAShE,SAAgB,oBAAoB,OAA0B,SAAiD;CAC7G,IAAI,UAAU,UAAU,OAAO,YAAY,QAAQ,YAAY;CAC/D,OAAO;AACT;;;;;;AAOA,SAAgB,6BAA6B,kBAAkC;CAC7E,OAAO,mBAAmB;AAC5B;AAqFA,MAAa,0BAA4C;CACvD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,YAAY,EAAE,MAAM,OAAO;EAC3B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,kBAAkB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACjD,aAAa;GAAE,MAAM;GAAQ,SAAS;EAAS;EAC/C,wBAAwB;GAAE,MAAM;GAAQ,SAAS;EAAuB;EAIxE,0BAA0B;GAAE,MAAM;GAAW,SAAS;EAAM;EAC5D,kBAAkB;GAAE,MAAM;GAAW,SAAS;EAAM;EAEpD,oBAAoB;GAAE,MAAM;GAAW,SAAS;EAAM;EACtD,2BAA2B;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC1D,kBAAkB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACjD,yBAAyB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACxD,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;EACnD,uBAAuB;GAAE,MAAM;GAAQ,UAAU;EAAK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CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/projects/base.ts"],"sourcesContent":["import { isThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport type { ThinkingLevelSetting } from '@mastra/code-sdk/thinking';\nimport { FactoryStorageDomain } from '@mastra/core/storage';\nimport type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_THINKING_LEVEL } from '../../../default-thinking-level.js';\n\nexport const DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES = 10;\nexport const FACTORY_MODEL_SCOPES = ['factory', 'user', 'hybrid'] as const;\nexport type FactoryModelScope = (typeof FACTORY_MODEL_SCOPES)[number];\n/** The single credential scope one session or run resolves from; `hybrid` is never effective. */\nexport type EffectiveModelScope = Exclude<FactoryModelScope, 'hybrid'>;\n\n/**\n * Resolve the scope one context runs under. `hybrid` splits by context: work-item runs use the\n * Factory's model and credentials, interactive sessions use the session owner's.\n */\nexport function effectiveModelScope(scope: FactoryModelScope, context: 'run' | 'session'): EffectiveModelScope {\n if (scope === 'hybrid') return context === 'run' ? 'factory' : 'user';\n return scope;\n}\n\n/**\n * Sentinel `user_id` for a Factory's own settings rows (memory, voice) in the\n * per-`(org, user)` settings tables. Real user ids are WorkOS ids (`user_…`) or\n * the `local` sentinel, so the prefix cannot collide.\n */\nexport function factoryProjectSettingsUserId(factoryProjectId: string): string {\n return `factory-project:${factoryProjectId}`;\n}\n\nexport interface FactoryProject {\n id: string;\n orgId: string;\n createdBy: string;\n name: string;\n description: string | null;\n /** Default model for sessions/runs started under this Factory (null = harness default). */\n defaultModelId: string | null;\n /**\n * Whose model and credentials sessions and runs use: the Factory's, the session owner's, or\n * `hybrid` (owner's for interactive sessions, the Factory's for work-item runs).\n */\n modelScope: FactoryModelScope;\n /** Thinking level for this Factory's sessions and runs that have not picked their own. */\n defaultThinkingLevel: ThinkingLevelSetting;\n /** Workspace root in the sandbox; linked repositories are checked out beneath it. */\n sandboxWorkingDirectory: string | null;\n /** Provider settings document validated by the configured FactorySandbox. Only keys the user set. */\n sandboxSettings: Record<string, unknown> | null;\n /** Command run once in the workspace root after every repository's own setup. */\n workspaceSetupCommand: string | null;\n /** Template id of the environment's current build, written by the build path. */\n activeTemplateId: string | null;\n /** Repository slug → commit the active template was built at. */\n activeTemplateHeads: Record<string, string> | null;\n /** Provider build id of the most recent build attempt; its status is read live from the provider. */\n lastBuildId: string | null;\n /** Repository slug → commit the most recent build attempt pinned, so its status can be read back. */\n lastBuildHeads: Record<string, string> | null;\n /** Fingerprint of the settings, repositories and setup commands the most recent build attempt used. */\n lastBuildInputs: string | null;\n /** When the most recent build attempt started, whatever triggered it. */\n lastBuildAttemptedAt: Date | null;\n /** When a push last started a build: the leading edge of the push debounce window. */\n lastPushBuildAt: Date | null;\n /**\n * A run's build-start lease lapsed, so a build it may have started is not\n * on record. Cleared once a run reconciles it with a provider that lists builds.\n */\n buildStartUncertain: boolean;\n /** Whether a push to an environment repository's default branch starts a build. */\n buildOnPushEnabled: boolean;\n /** Minutes after a push-triggered attempt during which further pushes do not build. */\n buildPushDebounceMinutes: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\n/** Project switches the board replaced, as last stored. */\nexport interface RetiredAutomationSettings {\n /** Runs started without a person on every phase. */\n autoRunEnabled: boolean;\n /** Cards on a board with a self-review phase went through it. */\n selfReviewEnabled: boolean;\n}\n\nexport interface CreateFactoryProjectInput {\n name: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n}\n\nexport interface UpdateFactoryProjectInput {\n name?: string;\n description?: string | null;\n defaultModelId?: string | null;\n modelScope?: FactoryModelScope;\n defaultThinkingLevel?: ThinkingLevelSetting;\n sandboxWorkingDirectory?: string | null;\n sandboxSettings?: Record<string, unknown> | null;\n workspaceSetupCommand?: string | null;\n activeTemplateId?: string | null;\n activeTemplateHeads?: Record<string, string> | null;\n lastBuildId?: string | null;\n lastBuildHeads?: Record<string, string> | null;\n lastBuildInputs?: string | null;\n lastBuildAttemptedAt?: Date | null;\n buildOnPushEnabled?: boolean;\n buildPushDebounceMinutes?: number;\n}\n\nexport const FACTORY_PROJECTS_SCHEMA: CollectionSchema = {\n name: 'factory_projects',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n created_by: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n default_model_id: { type: 'text', nullable: true },\n model_scope: { type: 'text', default: 'hybrid' },\n default_thinking_level: { type: 'text', default: DEFAULT_THINKING_LEVEL },\n // Deprecated: no longer read or written. Kept so existing databases need no\n // migration. Old rows may still hold `true`, so never read it to bring Slack\n // work items back. Drop it in a later migration.\n slack_work_items_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A phase starts on its own with `autoStart`; the\n // `auto-run-switch-v1` board migration reads it once to carry it into the project's boards.\n auto_run_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer read or written. Plans are approved per board (`exitTool.autoApprove`).\n auto_approve_plans: { type: 'boolean', default: false },\n sandbox_working_directory: { type: 'text', nullable: true },\n sandbox_settings: { type: 'json', nullable: true },\n workspace_setup_command: { type: 'text', nullable: true },\n active_template_id: { type: 'text', nullable: true },\n active_template_heads: { type: 'json', nullable: true },\n last_build_id: { type: 'text', nullable: true },\n last_build_heads: { type: 'json', nullable: true },\n last_build_inputs: { type: 'text', nullable: true },\n last_build_attempted_at: { type: 'timestamp', nullable: true },\n last_push_build_at: { type: 'timestamp', nullable: true },\n build_start_uncertain: { type: 'boolean', default: false },\n build_start_claim: { type: 'text', nullable: true },\n build_start_claim_expires_at: { type: 'timestamp', nullable: true },\n build_on_push_enabled: { type: 'boolean', default: false },\n build_push_debounce_minutes: { type: 'integer', default: DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES },\n // Retired project switch: no longer read or written. The review skill decides whether to publish its test check.\n review_test_checks_enabled: { type: 'boolean', default: false },\n // Retired project switch: no longer written. A board self-reviews when it has a self-review\n // phase; the `self-review-switch-v1` board migration reads it once to carry it into its boards.\n self_review_enabled: { type: 'boolean', default: false },\n /** Set once the source-control domain has backfilled repository positions and environment membership. */\n environment_backfilled_at: { type: 'timestamp', nullable: true },\n created_at: { type: 'timestamp' },\n updated_at: { type: 'timestamp' },\n },\n indexes: [{ name: 'factory_projects_org_updated_at_idx', columns: ['org_id', 'updated_at'] }],\n};\n\ninterface FactoryProjectDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n created_by: string;\n name: string;\n description: string | null;\n default_model_id: string | null;\n model_scope: string;\n default_thinking_level: string | null;\n auto_run_enabled: boolean;\n auto_approve_plans: boolean;\n sandbox_working_directory: string | null;\n sandbox_settings: Record<string, unknown> | null;\n workspace_setup_command: string | null;\n active_template_id: string | null;\n active_template_heads: Record<string, string> | null;\n last_build_id: string | null;\n last_build_heads: Record<string, string> | null;\n last_build_inputs: string | null;\n last_build_attempted_at: Date | null;\n last_push_build_at: Date | null;\n build_start_uncertain: boolean | null;\n build_start_claim: string | null;\n build_start_claim_expires_at: Date | null;\n build_on_push_enabled: boolean | null;\n build_push_debounce_minutes: number | null;\n self_review_enabled: boolean | null;\n environment_backfilled_at: Date | null;\n created_at: Date;\n updated_at: Date;\n}\n\nfunction toFactoryProject(row: FactoryProjectDbRow): FactoryProject {\n return {\n id: row.id,\n orgId: row.org_id,\n createdBy: row.created_by,\n name: row.name,\n description: row.description,\n defaultModelId: row.default_model_id,\n modelScope: row.model_scope === 'factory' || row.model_scope === 'user' ? row.model_scope : 'hybrid',\n defaultThinkingLevel: isThinkingLevelSetting(row.default_thinking_level)\n ? row.default_thinking_level\n : DEFAULT_THINKING_LEVEL,\n sandboxWorkingDirectory: row.sandbox_working_directory ?? null,\n sandboxSettings: row.sandbox_settings ?? null,\n workspaceSetupCommand: row.workspace_setup_command ?? null,\n activeTemplateId: row.active_template_id ?? null,\n activeTemplateHeads: row.active_template_heads ?? null,\n lastBuildId: row.last_build_id ?? null,\n lastBuildHeads: row.last_build_heads ?? null,\n lastBuildInputs: row.last_build_inputs ?? null,\n lastBuildAttemptedAt: row.last_build_attempted_at ?? null,\n lastPushBuildAt: row.last_push_build_at ?? null,\n buildStartUncertain: row.build_start_uncertain ?? false,\n buildOnPushEnabled: row.build_on_push_enabled ?? false,\n buildPushDebounceMinutes: row.build_push_debounce_minutes ?? DEFAULT_BUILD_PUSH_DEBOUNCE_MINUTES,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nexport class FactoryProjectsStorage extends FactoryStorageDomain {\n constructor() {\n super('projects');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([FACTORY_PROJECTS_SCHEMA]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('factory_projects', {});\n }\n\n get #db(): FactoryStorageOps {\n return this.ops;\n }\n\n async create({\n orgId,\n userId,\n input,\n }: {\n orgId: string;\n userId: string;\n input: CreateFactoryProjectInput;\n }): Promise<FactoryProject> {\n const now = new Date();\n const row = await this.#db.insertOne<FactoryProjectDbRow>('factory_projects', {\n org_id: orgId,\n created_by: userId,\n name: input.name,\n description: input.description ?? null,\n default_model_id: input.defaultModelId ?? null,\n model_scope: input.modelScope ?? 'hybrid',\n created_at: now,\n updated_at: now,\n });\n return toFactoryProject(row);\n }\n\n async list({ orgId }: { orgId: string }): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n { org_id: orgId },\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async listAll(): Promise<FactoryProject[]> {\n const rows = await this.#db.findMany<FactoryProjectDbRow>(\n 'factory_projects',\n {},\n { orderBy: [['updated_at', 'desc']] },\n );\n return rows.map(toFactoryProject);\n }\n\n async get({ orgId, id }: { orgId: string; id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * The retired automation switches as the project last stored them, read only by the one-time\n * board migrations that carry them into its boards. Null when the project doesn't exist.\n */\n async retiredAutomationSettings(\n { orgId, id }: { orgId: string; id: string },\n /** A transaction's ops, to read it inside that transaction. */\n ops: FactoryStorageOps = this.#db,\n ): Promise<RetiredAutomationSettings | null> {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n return { autoRunEnabled: Boolean(row.auto_run_enabled), selfReviewEnabled: Boolean(row.self_review_enabled) };\n }\n\n async getById({ id }: { id: string }): Promise<FactoryProject | null> {\n const row = await this.#db.findOne<FactoryProjectDbRow>('factory_projects', { id });\n return row ? toFactoryProject(row) : null;\n }\n\n async update({\n orgId,\n id,\n input,\n }: {\n orgId: string;\n id: string;\n /** A function input runs in a transaction; writes through its `ops` commit or roll back with the project. */\n input:\n | UpdateFactoryProjectInput\n | ((current: FactoryProject, ops: FactoryStorageOps) => Promise<UpdateFactoryProjectInput | null>);\n }): Promise<FactoryProject | null> {\n const update = (ops: FactoryStorageOps) =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id }, async current => {\n const changes = typeof input === 'function' ? await input(toFactoryProject(current), ops) : input;\n if (changes === null) return null;\n return {\n ...(changes.name !== undefined ? { name: changes.name } : {}),\n ...(changes.description !== undefined ? { description: changes.description } : {}),\n ...(changes.defaultModelId !== undefined ? { default_model_id: changes.defaultModelId } : {}),\n ...(changes.modelScope !== undefined ? { model_scope: changes.modelScope } : {}),\n ...(changes.defaultThinkingLevel !== undefined\n ? { default_thinking_level: changes.defaultThinkingLevel }\n : {}),\n ...(changes.sandboxWorkingDirectory !== undefined\n ? { sandbox_working_directory: changes.sandboxWorkingDirectory }\n : {}),\n ...(changes.sandboxSettings !== undefined ? { sandbox_settings: changes.sandboxSettings } : {}),\n ...(changes.workspaceSetupCommand !== undefined\n ? { workspace_setup_command: changes.workspaceSetupCommand }\n : {}),\n ...(changes.activeTemplateId !== undefined ? { active_template_id: changes.activeTemplateId } : {}),\n ...(changes.activeTemplateHeads !== undefined ? { active_template_heads: changes.activeTemplateHeads } : {}),\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(changes.buildOnPushEnabled !== undefined ? { build_on_push_enabled: changes.buildOnPushEnabled } : {}),\n ...(changes.buildPushDebounceMinutes !== undefined\n ? { build_push_debounce_minutes: changes.buildPushDebounceMinutes }\n : {}),\n updated_at: new Date(),\n };\n });\n // LibSQL's standalone updateAtomic only serializes one client; a transaction\n // also protects a read-dependent update against other database connections.\n const row = typeof input === 'function' ? await this.storage.withTransaction(update) : await update(this.#db);\n return row ? toFactoryProject(row) : null;\n }\n\n /**\n * Leading-edge debounce for push-triggered builds: stamps\n * `last_push_build_at = now` and resolves true when no push started a build\n * within the last `debounceMinutes`, else writes nothing and resolves\n * false. Taken right before the provider start, so a push that skips\n * (another run starting, a build in progress) never closes the window. The read and the write run in one transaction, so two concurrent\n * webhooks never both win, even on different database connections.\n */\n async claimBuildAttempt({\n id,\n debounceMinutes,\n now = new Date(),\n }: {\n id: string;\n debounceMinutes: number;\n now?: Date;\n }): Promise<boolean> {\n let claimed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const last = current.last_push_build_at;\n if (last && now.getTime() - last.getTime() < debounceMinutes * 60_000) return null;\n claimed = true;\n return { last_push_build_at: now, updated_at: now };\n }),\n );\n return claimed;\n }\n\n /**\n * Takes the project's build-start lease for `token`. Every trigger (manual,\n * schedule, push) takes it before reading build state and holds it through\n * `builds.start` and recording the result, so two runs never both start a\n * build. `claimed` is false while another run holds an unexpired lease. The\n * holder renews the lease while it works (`renewBuildStart`), so a lease\n * only expires when its run died or stalled. Taking over an expired lease\n * marks the start uncertain (that run's build may have reached the provider\n * unrecorded), and the mark stays until a release resolves it; `uncertain`\n * reports it. Only the claim is transactional; provider calls run outside it.\n */\n async claimBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<{ claimed: boolean; uncertain: boolean }> {\n const result = { claimed: false, uncertain: false };\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n const expiresAt = current.build_start_claim_expires_at;\n if (current.build_start_claim && expiresAt && expiresAt.getTime() > now.getTime()) return null;\n result.claimed = true;\n result.uncertain = Boolean(current.build_start_claim) || current.build_start_uncertain === true;\n return {\n build_start_claim: token,\n build_start_claim_expires_at: new Date(now.getTime() + leaseMs),\n ...(result.uncertain ? { build_start_uncertain: true } : {}),\n updated_at: now,\n };\n }),\n );\n return result;\n }\n\n /**\n * Extends the build-start lease held by `token` to `now + leaseMs`. Resolves\n * false, writing nothing, when `token` no longer holds it.\n */\n async renewBuildStart({\n id,\n token,\n leaseMs,\n now = new Date(),\n }: {\n id: string;\n token: string;\n leaseMs: number;\n now?: Date;\n }): Promise<boolean> {\n let renewed = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n renewed = true;\n return { build_start_claim_expires_at: new Date(now.getTime() + leaseMs), updated_at: now };\n }),\n );\n return renewed;\n }\n\n /**\n * Releases the build-start lease taken with `token` and writes `changes` in\n * the same transaction, but only while `token` still holds the lease. A run\n * whose lease expired and was taken by a newer run writes nothing, so it\n * never clears or overwrites that run's build. `resolved` clears an\n * uncertain start. Resolves false when skipped.\n */\n async releaseBuildStart({\n id,\n token,\n changes = {},\n resolved = false,\n now = new Date(),\n }: {\n id: string;\n token: string;\n resolved?: boolean;\n changes?: Pick<\n UpdateFactoryProjectInput,\n 'lastBuildId' | 'lastBuildHeads' | 'lastBuildInputs' | 'lastBuildAttemptedAt'\n >;\n now?: Date;\n }): Promise<boolean> {\n let released = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.build_start_claim !== token) return null;\n released = true;\n return {\n ...(changes.lastBuildId !== undefined ? { last_build_id: changes.lastBuildId } : {}),\n ...(changes.lastBuildHeads !== undefined ? { last_build_heads: changes.lastBuildHeads } : {}),\n ...(changes.lastBuildInputs !== undefined ? { last_build_inputs: changes.lastBuildInputs } : {}),\n ...(changes.lastBuildAttemptedAt !== undefined\n ? { last_build_attempted_at: changes.lastBuildAttemptedAt }\n : {}),\n ...(resolved ? { build_start_uncertain: false } : {}),\n build_start_claim: null,\n build_start_claim_expires_at: null,\n updated_at: now,\n };\n }),\n );\n return released;\n }\n\n /**\n * Pins the active template to a finished build, but only while that build is\n * still the project's last one. Overlapping runs (Build now during a push\n * build) can finish out of order; the write and the `last_build_id` check\n * run in one transaction so a stale run never overwrites a newer build's\n * pin. Resolves false when the pin was skipped.\n */\n async pinActiveTemplate({\n id,\n buildId,\n templateId,\n heads,\n now = new Date(),\n }: {\n id: string;\n buildId: string;\n templateId: string;\n heads: Record<string, string>;\n now?: Date;\n }): Promise<boolean> {\n let pinned = false;\n await this.storage.withTransaction(ops =>\n ops.updateAtomic<FactoryProjectDbRow>('factory_projects', { id }, current => {\n if (current.last_build_id !== buildId) return null;\n pinned = true;\n return { active_template_id: templateId, active_template_heads: heads, updated_at: now };\n }),\n );\n return pinned;\n }\n\n /** `release` runs in the deleting transaction, so nothing can be routed to the project between the two. */\n async delete(\n { orgId, id }: { orgId: string; id: string },\n release?: (ops: FactoryStorageOps) => Promise<void>,\n ): Promise<FactoryProject | null> {\n return this.storage.withTransaction(\n async ops => {\n const row = await ops.findOne<FactoryProjectDbRow>('factory_projects', { org_id: orgId, id });\n if (!row) return null;\n await release?.(ops);\n await ops.deleteMany('factory_projects', { org_id: orgId, id });\n return toFactoryPro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KAAA,IAAY,EAAE,mBAAmB,QAAQ,gBAAgB,IAAI,CAAC;IAC9F,GAAI,QAAQ,yBAAyB,KAAA,IACjC,EAAE,yBAAyB,QAAQ,qBAAqB,IACxD,CAAC;IACL,GAAI,WAAW,EAAE,uBAAuB,MAAM,IAAI,CAAC;IACnD,mBAAmB;IACnB,8BAA8B;IAC9B,YAAY;GACd;EACF,CAAC,CACH;EACA,OAAO;CACT;;;;;;;;CASA,MAAM,kBAAkB,EACtB,IACA,SACA,YACA,OACA,sBAAM,IAAI,KAAK,KAOI;EACnB,IAAI,SAAS;EACb,MAAM,KAAK,QAAQ,iBAAgB,QACjC,IAAI,aAAkC,oBAAoB,EAAE,GAAG,IAAG,YAAW;GAC3E,IAAI,QAAQ,kBAAkB,SAAS,OAAO;GAC9C,SAAS;GACT,OAAO;IAAE,oBAAoB;IAAY,uBAAuB;IAAO,YAAY;GAAI;EACzF,CAAC,CACH;EACA,OAAO;CACT;;CAGA,MAAM,OACJ,EAAE,OAAO,MACT,SACgC;EAChC,OAAO,KAAK,QAAQ,gBAClB,OAAM,QAAO;GACX,MAAM,MAAM,MAAM,IAAI,QAA6B,oBAAoB;IAAE,QAAQ;IAAO;GAAG,CAAC;GAC5F,IAAI,CAAC,KAAK,OAAO;GACjB,MAAM,UAAU,GAAG;GACnB,MAAM,IAAI,WAAW,oBAAoB;IAAE,QAAQ;IAAO;GAAG,CAAC;GAC9D,OAAO,iBAAiB,GAAG;EAC7B,GACA,EAAE,gBAAgB,eAAe,CACnC;CACF;AACF"}
@@ -11,6 +11,7 @@ import { FactoryStorageDomain } from '@mastra/core/storage';
11
11
  import type { CollectionSchema, FactoryStorageOps } from '@mastra/core/storage';
12
12
  import type { FactoryTriageType } from '../../../rules/types.js';
13
13
  import type { WorkItemSplitReport } from '../../../work-items/split-migration.js';
14
+ import type { BoardScope } from './board-version.js';
14
15
  import type { FactoryClaimableWorkScope } from './claimable-work.js';
15
16
  import type { ReviewBoardScope } from './legacy-review.js';
16
17
  import type { WorkItemRow as ProviderWorkItemRow, WorkItemDbRecord, WorkItemSourceDbRecord, WorkItemSourceRow } from './work-item-schema.js';
@@ -405,8 +406,8 @@ export interface BoardItemRow {
405
406
  triageType: FactoryTriageType | null;
406
407
  /**
407
408
  * When a person first committed this item to the Factory, by starting a run
408
- * on it or releasing one that was proposed. Projects that withhold auto-run
409
- * are asking to decide what the Factory picks up, not to approve each step of
409
+ * on it or releasing one that was proposed. Boards whose phases don't start
410
+ * on their own are asking to decide what the Factory picks up, not to approve each step of
410
411
  * work they already asked for, so runs on an armed item skip the gate.
411
412
  */
412
413
  autonomyArmedAt: Date | null;
@@ -534,11 +535,8 @@ export declare function applyStageTransition(history: WorkItemStageEntry[], oldS
534
535
  export declare function stampSessions(sessions: Record<string, WorkItemSessionInput>, by: string): WorkItemSessions;
535
536
  /** Stage-history actor for the one-time move of cards held for triage acceptance. */
536
537
  export declare const HELD_CARD_SWEEP_ACTOR = "factory-held-card-sweep";
537
- /** The project whose attention list a write just changed. */
538
- export interface FactoryAttentionScope {
539
- orgId: string;
540
- factoryProjectId: string;
541
- }
538
+ /** The project whose board a committed card or decision write just changed. */
539
+ export type FactoryBoardScope = Required<BoardScope>;
542
540
  type WorkItemSourceSyncPatch = Partial<Pick<WorkItemSourceRow, 'state' | 'labels' | 'author' | 'url' | 'key' | 'metadata'>>;
543
541
  export declare class WorkItemsStorage extends FactoryStorageDomain {
544
542
  #private;
@@ -552,11 +550,10 @@ export declare class WorkItemsStorage extends FactoryStorageDomain {
552
550
  reviewBoardInUse(scope: ReviewBoardScope): Promise<boolean>;
553
551
  constructor();
554
552
  /**
555
- * Wired once at boot. Every write below that changes what this project's
556
- * attention list projects announces it here — the one place a new such write
557
- * has to remember, since clients stop polling while their stream is up.
553
+ * Wired once at boot. Fires after a committed write changes what a board shows of a card
554
+ * or a deferred decision, so open boards refetch instead of polling.
558
555
  */
559
- onAttentionChanged(listener: (scope: FactoryAttentionScope) => void): void;
556
+ onBoardChanged(listener: (scope: FactoryBoardScope) => void): void;
560
557
  /**
561
558
  * Fires after any committed write leaves a pending start or deferred decision
562
559
  * `pending` or `retry`, so an idle dispatcher can wake instead of polling.
@@ -642,6 +639,11 @@ export declare class WorkItemsStorage extends FactoryStorageDomain {
642
639
  } | null>;
643
640
  dangerouslyClearAll(): Promise<void>;
644
641
  protected get ops(): FactoryStorageOps;
642
+ /** The project's cards as {@link list} reads them, uncached, through `ops`: a transaction's, to read them in it. */
643
+ listWith(ops: FactoryStorageOps, { orgId, factoryProjectId }: {
644
+ orgId: string;
645
+ factoryProjectId: string;
646
+ }): Promise<Card[]>;
645
647
  /**
646
648
  * List the org's work items for a project, newest first. Ordered on `created_at` with an id
647
649
  * tiebreak so the order is stable: `updated_at` moves under every write, which makes it useless