@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/boards/base.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_ROUTE_EVENTS, routeEventsProblem } from '../../../boards/board-events.js';\nimport type { StatusEvent } from '../../../boards/board-events.js';\nimport type { FactoryPhaseTool } from '../../../boards/define-board.js';\nimport { DEFAULT_INTAKE_ROUTES } from '../../../boards/work-routes.js';\nimport type { RuleGroup } from '../../../rules/rule-group.js';\nimport {\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARDS_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n} from './schemas.js';\n\n/** The project a board belongs to. */\nexport interface StoredBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport type StoredPhaseKind = 'resting' | 'working' | 'terminal';\n\n/** Who runs a working phase. Factory runs every phase with its code agent. */\nexport interface StoredPhaseRunner {\n skill?: string;\n context?: string;\n instructions?: string;\n /** The objective the phase's runs pursue as a goal. */\n goal?: { objective: string; maxRuns?: number };\n}\n\nexport interface StoredPhaseExitTool {\n id: string;\n autoApprove?: boolean;\n autoApproveWhen?: RuleGroup;\n}\n\n/** A phase as it is written. `key` is the stage id cards sit in. */\nexport interface StoredPhaseInput {\n key: string;\n name: string;\n description?: string | null;\n kind: StoredPhaseKind;\n runner?: StoredPhaseRunner | null;\n /** Unset or `null` on a resting or working phase means every other phase; `[]` means none. */\n nextPhases?: string[] | null;\n autoStart?: boolean;\n autoStartWhen?: RuleGroup | null;\n exitTool?: StoredPhaseExitTool | null;\n /** Factory tools the phase grants the session working the card there. */\n tools?: FactoryPhaseTool[] | null;\n}\n\n/** A board as it is written. Phase order is significant: the first phase is where cards start. */\nexport interface StoredBoardInput {\n key: string;\n name: string;\n description?: string | null;\n phases: StoredPhaseInput[];\n}\n\nexport interface StoredPhaseRecord {\n key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n nextPhases: string[] | null;\n autoStart: boolean;\n autoStartWhen: RuleGroup | null;\n exitTool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\nexport interface StoredBoardRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n phases: StoredPhaseRecord[];\n}\n\n/** A one-time rewrite of a stored board, keyed so each project gets it once. */\nexport interface StoredBoardMigration {\n key: string;\n boardKey: string;\n /** The board to write instead, with what changed; undefined leaves it as it is. */\n migrate(board: StoredBoardRecord): { board: Omit<StoredBoardInput, 'key'>; filled: string[] } | undefined;\n}\n\nexport interface AppliedBoardMigration {\n key: string;\n boardKey: string;\n filled: string[];\n}\n\nexport interface StoredBoardSnapshot {\n version: string | null;\n boards: StoredBoardRecord[];\n}\n\nexport interface IntakeRouteTarget {\n boardKey: string;\n /**\n * Unset lands the card in the board's first phase. On a route that joins a closed issue's\n * card, the phase that card moves to when its board allows it; unset leaves it where it is.\n */\n phaseKey?: string | null;\n /**\n * Files a pull request on the card of the issue it closes, which must be on `boardKey`, as one\n * more source instead of a card of its own. The route doesn't match any other arrival.\n */\n joinClosedIssue?: boolean;\n}\n\n/** An intake route as it is written. */\nexport interface StoredIntakeRouteInput {\n name: string;\n enabled?: boolean;\n /** Null matches every card. */\n when?: RuleGroup | null;\n target: IntakeRouteTarget;\n /** The status events the route handles; unset handles new cards (`work_item.created`). */\n on?: StatusEvent[];\n /** Lets an event move an existing card into a working phase, such as Triage. Off by default. */\n allowWorkingPhase?: boolean;\n}\n\nexport interface StoredIntakeRouteRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n name: string;\n enabled: boolean;\n position: number;\n when: RuleGroup | null;\n target: { boardKey: string; phaseKey: string | null; joinClosedIssue: boolean };\n on: StatusEvent[];\n allowWorkingPhase: boolean;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n}\n\nexport type StoredBoardErrorCode =\n | 'board_exists'\n | 'board_not_found'\n | 'revision_mismatch'\n | 'intake_route_not_found'\n | 'intake_route_set_mismatch'\n | 'intake_route_limit'\n | 'invalid_intake_route';\n\n/** A project's most intake routes; a reorder names every one of them. */\nexport const MAX_INTAKE_ROUTES = 100;\n\n// Work's routes are its seed data, kept with the board they target.\nexport {\n DEFAULT_INTAKE_ROUTE,\n PULL_REQUEST_INTAKE_ROUTE,\n CLOSED_COMPLETED_ROUTE,\n CLOSED_CANCELED_ROUTE,\n REOPENED_ROUTE,\n PULL_REQUEST_MERGED_ROUTE,\n PULL_REQUEST_CLOSED_ROUTE,\n PULL_REQUEST_CLOSED_ISSUE_ROUTE,\n PULL_REQUEST_UPDATED_ROUTE,\n PULL_REQUEST_REVIEW_REQUESTED_ROUTE,\n CLOSES_ISSUE_INTAKE_ROUTE,\n DEFAULT_INTAKE_ROUTES,\n} from '../../../boards/work-routes.js';\n\n/** The defaults a project whose lock row predates `seeded_defaults` was set up with. */\nconst ORIGINAL_DEFAULT_KEYS = ['outside-authors'];\n\n/** Who the default intake routes are created and last updated by. */\nexport const DEFAULT_INTAKE_ROUTE_ACTOR = 'factory';\n\nexport class StoredBoardError extends Error {\n override name = 'StoredBoardError';\n constructor(\n readonly code: StoredBoardErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface BoardRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface VersionRow extends Record<string, unknown> {\n version: string;\n /** Keys of the boards Factory stored in the project; null on rows written before the list. */\n seeded_boards: string[] | null;\n /** Keys of the board migrations applied to the project; null before the first one. */\n applied_migrations: string[] | null;\n}\n\ninterface PhaseRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n phase_key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n next_phases: string[] | null;\n auto_start: boolean;\n auto_start_when: RuleGroup | null;\n exit_tool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\ninterface IntakeRouteRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n name: string;\n enabled: boolean;\n position: number;\n when_condition: RuleGroup | null;\n board_key: string;\n phase_key: string | null;\n /** Null on rows written before routes named events: they place new cards. */\n on_events: StatusEvent[] | null;\n allow_working_phase: boolean | null;\n join_closed_issue: boolean | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface IntakeRouteLockRow extends Record<string, unknown> {\n /** Keys of the `DEFAULT_INTAKE_ROUTES` added to the project; null on rows written before the list. */\n seeded_defaults: string[] | null;\n}\n\nfunction seededDefaults(lock: IntakeRouteLockRow): string[] {\n return lock.seeded_defaults ?? ORIGINAL_DEFAULT_KEYS;\n}\n\nfunction missingDefaults(lock: IntakeRouteLockRow): (typeof DEFAULT_INTAKE_ROUTES)[number][] {\n const seeded = new Set(seededDefaults(lock));\n return DEFAULT_INTAKE_ROUTES.filter(({ key }) => !seeded.has(key));\n}\n\nconst BOARDS = 'factory_boards';\nconst PHASES = 'factory_board_phases';\nconst VERSIONS = 'factory_board_definition_versions';\nconst INTAKE_ROUTES = 'factory_intake_routes';\nconst INTAKE_ROUTE_LOCKS = 'factory_intake_route_locks';\nconst MAX_WRITE_ATTEMPTS = 3;\nconst MIGRATION_ACTOR = 'factory';\n\nfunction scopeWhere({ orgId, factoryProjectId }: StoredBoardScope) {\n return { org_id: orgId, factory_project_id: factoryProjectId };\n}\n\nfunction toPhaseRecord(row: PhaseRow): StoredPhaseRecord {\n return {\n key: row.phase_key,\n position: row.position,\n name: row.name,\n description: row.description,\n kind: row.kind,\n runner: row.runner,\n nextPhases: row.next_phases,\n autoStart: row.auto_start,\n autoStartWhen: row.auto_start_when,\n exitTool: row.exit_tool,\n tools: row.tools ?? null,\n };\n}\n\nfunction toRecord(row: BoardRow, phases: PhaseRow[]): StoredBoardRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n key: row.board_key,\n name: row.name,\n description: row.description,\n position: row.position,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n phases: phases.sort((left, right) => left.position - right.position).map(toPhaseRecord),\n };\n}\n\n/** A compare-and-set inside a write lost to a concurrent writer; the write is retried from fresh reads. */\nclass ConcurrentBoardWrite extends Error {}\n\n/**\n * Each project's boards and their ordered phases. Every write runs in one transaction that also\n * replaces the project's row in `factory_board_definition_versions`, so caches on other\n * replicas can detect it.\n */\nexport class StoredBoardsStorage extends FactoryStorageDomain {\n constructor() {\n super('boards');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n FACTORY_BOARDS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany(PHASES, {});\n await this.ops.deleteMany(BOARDS, {});\n await this.ops.deleteMany(VERSIONS, {});\n await this.ops.deleteMany(INTAKE_ROUTES, {});\n await this.ops.deleteMany(INTAKE_ROUTE_LOCKS, {});\n }\n\n /** The project's current definition version; null before its first board write. */\n async readVersion(scope: StoredBoardScope): Promise<string | null> {\n return readVersion(this.ops, scope);\n }\n\n /** The project's boards in order. */\n async list(scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n return readBoards(this.ops, scope);\n }\n\n /**\n * The version and the boards, read in that order: a write landing between the two reads leaves a\n * version older than the rows, so a cache keyed on it rereads on its next check instead of\n * keeping the stale rows.\n */\n async snapshot(scope: StoredBoardScope): Promise<StoredBoardSnapshot> {\n const version = await readVersion(this.ops, scope);\n return { version, boards: await this.list(scope) };\n }\n\n async get(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord | null> {\n const row = await this.ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) return null;\n const phases = await this.ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: key });\n return toRecord(row, phases);\n }\n\n /** Creates a board through the API. */\n async create(scope: StoredBoardScope, input: StoredBoardInput, actor: string): Promise<StoredBoardRecord> {\n await ensureVersionRow(this.ops, scope);\n try {\n return await this.#write(scope, async ops => {\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n if (rows.some(row => row.board_key === input.key)) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n await insertBoard(ops, scope, input, { position: nextPosition(rows), actor });\n return { result: undefined, changed: true };\n }).then(async () => (await this.get(scope, input.key))!);\n } catch (error) {\n // Only the board key's index means the board exists; a lost race on another table is not that.\n if (error instanceof UniqueViolationError && error.collection === BOARDS) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n throw error;\n }\n }\n\n /** Replaces a board's name, description and phases. The board key never changes. */\n async replace(\n scope: StoredBoardScope,\n key: string,\n input: Omit<StoredBoardInput, 'key'>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { key, ...input }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /**\n * Stores Factory's boards (Work, app and seed boards) in the project, each key once: a key the\n * project has had before is skipped even if its board was deleted since, and a stored board is\n * never rewritten. A project stored before the list was kept counts the boards it has as stored.\n * Reads one row when every key was stored before. Returns the keys it inserted.\n */\n async seedBoards(scope: StoredBoardScope, boards: readonly StoredBoardInput[]): Promise<string[]> {\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.seeded_boards && boards.every(board => marker.seeded_boards!.includes(board.key))) return [];\n return this.#insertOnce(scope, boards, { actor: DEFAULT_INTAKE_ROUTE_ACTOR, skipSeeded: true });\n }\n\n /**\n * Inserts a board into the project unless one is stored under its key, and records the key as\n * stored, so seeding never adds it again. Unlike seeding, it inserts a key the project deleted.\n * Returns whether it inserted the board.\n */\n async insertIfMissing(scope: StoredBoardScope, board: StoredBoardInput, actor: string): Promise<boolean> {\n return (await this.#insertOnce(scope, [board], { actor, skipSeeded: false })).length > 0;\n }\n\n async #insertOnce(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: { actor: string; skipSeeded: boolean },\n ): Promise<string[]> {\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const marker = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n const present = new Set(rows.map(row => row.board_key));\n const seeded = new Set(marker.seeded_boards ?? present);\n let position = nextPosition(rows);\n const inserted: string[] = [];\n for (const board of boards) {\n if (present.has(board.key) || (options.skipSeeded && seeded.has(board.key))) continue;\n await insertBoard(ops, scope, board, { position: position++, actor: options.actor });\n present.add(board.key);\n inserted.push(board.key);\n }\n const next = [...new Set([...seeded, ...boards.map(board => board.key)])];\n const unchanged = marker.seeded_boards !== null && next.length === marker.seeded_boards.length;\n if (inserted.length === 0 && unchanged) return inserted;\n // Compare-and-set on the version, and every marker write takes a new one: two replicas\n // recording different keys can't both match the version they read, so neither key is lost.\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: marker.version },\n {\n seeded_boards: next,\n version: randomUUID(),\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return inserted;\n });\n }\n\n /**\n * Runs each migration the project hasn't had yet, once: the keys applied are recorded on the\n * project's version row in the same transaction as the board writes, and the compare-and-set on\n * its version makes a concurrent first load retry from fresh reads, where it finds them applied.\n * A migration whose board the project doesn't have is recorded without running, and the version\n * only changes when a board was rewritten. Reads one row\n * when every key was applied before. Returns what each migration that rewrote a board filled.\n */\n async applyBoardMigrations(\n scope: StoredBoardScope,\n migrations: readonly StoredBoardMigration[],\n ): Promise<AppliedBoardMigration[]> {\n if (migrations.length === 0) return [];\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.applied_migrations && migrations.every(({ key }) => marker.applied_migrations!.includes(key))) {\n return [];\n }\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const current = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const applied = current.applied_migrations ?? [];\n const pending = migrations.filter(({ key }) => !applied.includes(key));\n if (pending.length === 0) return [];\n const changed: AppliedBoardMigration[] = [];\n for (const migration of pending) {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: migration.boardKey });\n if (!row) continue;\n const phases = await ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n const result = migration.migrate(toRecord(row, phases));\n if (!result) continue;\n await writeBoard(ops, scope, row, { ...result.board, key: row.board_key }, MIGRATION_ACTOR);\n changed.push({ key: migration.key, boardKey: row.board_key, filled: result.filled });\n }\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: current.version },\n {\n applied_migrations: [...applied, ...pending.map(({ key }) => key)],\n // Only a rewritten board is news to the other replicas' caches.\n version: changed.length > 0 ? randomUUID() : current.version,\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return changed;\n });\n }\n\n /** Rewrites a board to `definition` (Factory's current one for its key), raising its revision. */\n async resetTo(\n scope: StoredBoardScope,\n key: string,\n definition: StoredBoardInput,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { ...definition, key }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /** Deletes a board and its phases. */\n async delete(scope: StoredBoardScope, key: string, options: { expectedRevision: number }): Promise<void> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n if ((await ops.deleteMany(BOARDS, { id: row.id, revision: row.revision })) === 0)\n throw new ConcurrentBoardWrite();\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: key });\n return { result: undefined, changed: true };\n });\n }\n\n /** The project's intake routes in the order they are tried; Factory's `DEFAULT_INTAKE_ROUTES` are added once each. */\n async listIntakeRoutes(scope: StoredBoardScope): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n return (await readIntakeRoutes(this.ops, scope)).map(toIntakeRouteRecord);\n }\n\n async getIntakeRoute(scope: StoredBoardScope, id: string): Promise<StoredIntakeRouteRecord | null> {\n const row = await this.ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n return row ? toIntakeRouteRecord(row) : null;\n }\n\n /** Adds a route after the project's last one. */\n async createIntakeRoute(\n scope: StoredBoardScope,\n input: StoredIntakeRouteInput,\n actor: string,\n ): Promise<StoredIntakeRouteRecord> {\n const id = randomUUID();\n checkRouteEvents(input.on ?? DEFAULT_ROUTE_EVENTS, input.when ?? null);\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n if (rows.length >= MAX_INTAKE_ROUTES) {\n throw new StoredBoardError(\n 'intake_route_limit',\n `A project can have at most ${MAX_INTAKE_ROUTES} intake routes; delete one first.`,\n );\n }\n await insertIntakeRoute(ops, scope, {\n id,\n input,\n position: rows.reduce((max, row) => Math.max(max, row.position), -1) + 1,\n actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Changes the fields `patch` names; the route keeps its place in the order. */\n async updateIntakeRoute(\n scope: StoredBoardScope,\n id: string,\n patch: Partial<StoredIntakeRouteInput>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredIntakeRouteRecord> {\n await this.#transact(async ops => {\n const row = await findIntakeRoute(ops, scope, id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n checkRouteEvents(patch.on ?? routeEvents(row), patch.when !== undefined ? patch.when : row.when_condition);\n await updateIntakeRouteRow(ops, row, {\n ...(patch.on !== undefined && { on_events: patch.on }),\n ...(patch.allowWorkingPhase !== undefined && { allow_working_phase: patch.allowWorkingPhase }),\n ...(patch.name !== undefined && { name: patch.name }),\n ...(patch.enabled !== undefined && { enabled: patch.enabled }),\n ...(patch.when !== undefined && { when_condition: patch.when }),\n ...(patch.target !== undefined && {\n board_key: patch.target.boardKey,\n phase_key: patch.target.phaseKey ?? null,\n join_closed_issue: patch.target.joinClosedIssue ?? false,\n }),\n updated_by: options.actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Deletes a route; the routes after it move up one place. */\n async deleteIntakeRoute(scope: StoredBoardScope, id: string, options: { expectedRevision: number }): Promise<void> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const row = rows.find(route => route.id === id);\n if (!row) throw intakeRouteNotFound(id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n if ((await ops.deleteMany(INTAKE_ROUTES, { id: row.id, revision: row.revision })) === 0) {\n throw new ConcurrentBoardWrite();\n }\n await placeIntakeRoutes(\n ops,\n rows.filter(route => route.id !== row.id),\n );\n });\n }\n\n /** Puts the project's routes in the order of `ids`, which must name every route exactly once. */\n async reorderIntakeRoutes(scope: StoredBoardScope, ids: string[], actor: string): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const byId = new Map(rows.map(row => [row.id, row]));\n if (ids.length !== rows.length || new Set(ids).size !== ids.length || ids.some(id => !byId.has(id))) {\n throw new StoredBoardError(\n 'intake_route_set_mismatch',\n 'The order must list every intake route of the project exactly once; reload the routes and try again.',\n );\n }\n await placeIntakeRoutes(\n ops,\n ids.map(id => byId.get(id)!),\n actor,\n );\n });\n return this.listIntakeRoutes(scope);\n }\n\n /**\n * Creates the project's route lock row (see `FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA`) and adds each of\n * `DEFAULT_INTAKE_ROUTES` the row doesn't list as added yet, after the project's routes. The row\n * records every default it added, so a project whose admin deleted one doesn't get it back. Runs\n * before, never inside, a write's transaction: the lock taken there must always be an update.\n */\n async #ensureIntakeRoutes(scope: StoredBoardScope): Promise<void> {\n const lock = await this.ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope));\n if (lock && missingDefaults(lock).length === 0) return;\n await this.#transact(async ops => {\n if (await ops.findOne(INTAKE_ROUTE_LOCKS, scopeWhere(scope))) await lockIntakeRoutes(ops, scope);\n // A racing first read inserted the lock row first: this one fails on the unique index and\n // retries, taking the lock above.\n else\n await ops.insertOne(INTAKE_ROUTE_LOCKS, { ...scopeWhere(scope), locked_at: new Date(), seeded_defaults: [] });\n // Read under the lock: a racing seeder that committed first already added what it listed.\n const current = (await ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope)))!;\n const missing = missingDefaults(current);\n if (missing.length === 0) return;\n const rows = await readIntakeRoutes(ops, scope);\n let position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n const first: string[] = [];\n for (const { route, first: leads } of missing) {\n // A project at the limit keeps its own routes; the default counts as added all the same.\n if (position >= MAX_INTAKE_ROUTES) break;\n const id = randomUUID();\n await insertIntakeRoute(ops, scope, {\n id,\n input: route,\n position: position++,\n actor: DEFAULT_INTAKE_ROUTE_ACTOR,\n });\n if (leads) first.push(id);\n }\n // A project that had routes before gets a leading default ahead of them.\n if (first.length > 0 && rows.length > 0) {\n const placed = await readIntakeRoutes(ops, scope);\n const leading = new Set(first);\n await placeIntakeRoutes(ops, [\n ...first.map(id => placed.find(row => row.id === id)!),\n ...placed.filter(row => !leading.has(row.id)),\n ]);\n }\n await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), {\n seeded_defaults: [...seededDefaults(current), ...missing.map(({ key }) => key)],\n });\n });\n }\n\n /**\n * Runs `fn` in a transaction and replaces the project's version when it changed anything.\n * Lost races (a compare-and-set miss, or a concurrent write that inserted the same board or the\n * project's first version row) retry from fresh reads.\n */\n async #write<T>(\n scope: StoredBoardScope,\n fn: (ops: FactoryStorageOps) => Promise<{ result: T; changed: boolean }>,\n ): Promise<T> {\n return this.#transact(async ops => {\n const { result, changed } = await fn(ops);\n if (changed) await bumpVersion(ops, scope);\n return result;\n });\n }\n\n /**\n * Runs `fn` in a transaction, retrying lost races from fresh reads. Intake route writes use it\n * directly: routes are read uncached, so they leave the board definition version alone.\n */\n async #transact<T>(fn: (ops: FactoryStorageOps) => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n // Read committed is enough: every row change is a compare-and-set on `revision` and every\n // insert meets the unique index. Serializable isolation would also fail writes to\n // unrelated projects that replicas run side by side.\n return await this.storage.withTransaction(fn);\n } catch (error) {\n const retryable = error instanceof ConcurrentBoardWrite || error instanceof UniqueViolationError;\n if (!retryable || attempt >= MAX_WRITE_ATTEMPTS) throw error;\n }\n }\n }\n}\n\nasync function readVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<string | null> {\n const row = await ops.findOne<{ version: string }>(VERSIONS, scopeWhere(scope));\n return row?.version ?? null;\n}\n\nasync function readBoards(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n const [rows, phases] = await Promise.all([\n ops.findMany<BoardRow>(BOARDS, scopeWhere(scope)),\n ops.findMany<PhaseRow>(PHASES, scopeWhere(scope)),\n ]);\n const byBoard = new Map<string, PhaseRow[]>();\n for (const phase of phases) {\n const list = byBoard.get(phase.board_key) ?? [];\n list.push(phase);\n byBoard.set(phase.board_key, list);\n }\n return rows\n .sort((left, right) => left.position - right.position || left.board_key.localeCompare(right.board_key))\n .map(row => toRecord(row, byBoard.get(row.board_key) ?? []));\n}\n\n/**\n * Inserts the project's version row if it has none. This runs outside the write transaction: on\n * Postgres, two transactions racing to insert it would leave the loser's transaction aborted, so\n * the version bump inside a write must always be an update.\n */\nasync function ensureVersionRow(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n if (await ops.findOne(VERSIONS, scopeWhere(scope))) return;\n try {\n await ops.insertOne(VERSIONS, { ...scopeWhere(scope), version: randomUUID(), updated_at: new Date() });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n}\n\nasync function bumpVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n await ops.upsertOne(VERSIONS, ['org_id', 'factory_project_id'], {\n ...scopeWhere(scope),\n version: randomUUID(),\n updated_at: new Date(),\n });\n}\n\nasync function findBoard(ops: FactoryStorageOps, scope: StoredBoardScope, key: string): Promise<BoardRow> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) {\n throw new StoredBoardError('board_not_found', `Board \"${key}\" does not exist in this project.`);\n }\n return row;\n}\n\nfunction checkRevision(row: BoardRow, key: string, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Board \"${key}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\nfunction nextPosition(rows: BoardRow[]): number {\n return rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n}\n\n/** Sets columns on a board row and raises its revision, unless another writer changed it first. */\nasync function updateRow(ops: FactoryStorageOps, row: BoardRow, set: Partial<BoardRow>): Promise<void> {\n const updated = await ops.updateMany(\n BOARDS,\n { id: row.id, revision: row.revision },\n { ...set, revision: row.revision + 1, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n}\n\nasync function insertPhases(ops: FactoryStorageOps, scope: StoredBoardScope, input: StoredBoardInput): Promise<void> {\n for (const [position, phase] of input.phases.entries()) {\n await ops.insertOne<PhaseRow>(PHASES, {\n ...scopeWhere(scope),\n board_key: input.key,\n phase_key: phase.key,\n position,\n name: phase.name,\n description: phase.description ?? null,\n kind: phase.kind,\n runner: phase.runner ?? null,\n next_phases: phase.nextPhases ?? null,\n auto_start: phase.autoStart ?? false,\n auto_start_when: phase.autoStartWhen ?? null,\n exit_tool: phase.exitTool ?? null,\n tools: phase.tools?.length ? phase.tools : null,\n });\n }\n}\n\nasync function insertBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n input: StoredBoardInput,\n options: { position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<BoardRow>(BOARDS, {\n ...scopeWhere(scope),\n board_key: input.key,\n name: input.name,\n description: input.description ?? null,\n position: options.position,\n revision: 1,\n created_by: options.actor,\n created_at: now,\n updated_by: options.actor,\n updated_at: now,\n });\n await insertPhases(ops, scope, input);\n}\n\n/** Replaces a board's definition and phases in place, keeping its key, position and history. */\nasync function writeBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n row: BoardRow,\n input: StoredBoardInput,\n actor: string,\n): Promise<void> {\n await updateRow(ops, row, { name: input.name, description: input.description ?? null, updated_by: actor });\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n await insertPhases(ops, scope, { ...input, key: row.board_key });\n}\n\nfunction routeEvents(row: IntakeRouteRow): StatusEvent[] {\n return row.on_events ?? [...DEFAULT_ROUTE_EVENTS];\n}\n\nfunction checkRouteEvents(on: readonly string[], when: RuleGroup | null): void {\n const problem = routeEventsProblem(on, when);\n if (problem) throw new StoredBoardError('invalid_intake_route', problem);\n}\n\nfunction toIntakeRouteRecord(row: IntakeRouteRow): StoredIntakeRouteRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n name: row.name,\n enabled: row.enabled,\n position: row.position,\n when: row.when_condition,\n target: { boardKey: row.board_key, phaseKey: row.phase_key, joinClosedIssue: row.join_closed_issue === true },\n on: routeEvents(row),\n allowWorkingPhase: row.allow_working_phase ?? false,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n };\n}\n\nasync function readIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n const rows = await ops.findMany<IntakeRouteRow>(INTAKE_ROUTES, scopeWhere(scope));\n return rows.sort((left, right) => left.position - right.position);\n}\n\nasync function findIntakeRoute(ops: FactoryStorageOps, scope: StoredBoardScope, id: string): Promise<IntakeRouteRow> {\n const row = await ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n if (!row) throw intakeRouteNotFound(id);\n return row;\n}\n\nfunction intakeRouteNotFound(id: string): StoredBoardError {\n return new StoredBoardError('intake_route_not_found', `Intake route \"${id}\" does not exist in this project.`);\n}\n\nfunction checkIntakeRouteRevision(row: IntakeRouteRow, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Intake route \"${row.name}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\n/** Sets columns on a route row and raises its revision, unless another writer changed it first. */\nasync function updateIntakeRouteRow(\n ops: FactoryStorageOps,\n row: IntakeRouteRow,\n set: Partial<IntakeRouteRow>,\n): Promise<number> {\n const revision = row.revision + 1;\n const updated = await ops.updateMany(\n INTAKE_ROUTES,\n { id: row.id, revision: row.revision },\n { ...set, revision, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return revision;\n}\n\nasync function insertIntakeRoute(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n route: { id: string; input: StoredIntakeRouteInput; position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<IntakeRouteRow>(INTAKE_ROUTES, {\n id: route.id,\n ...scopeWhere(scope),\n name: route.input.name,\n enabled: route.input.enabled ?? true,\n position: route.position,\n when_condition: route.input.when ?? null,\n board_key: route.input.target.boardKey,\n phase_key: route.input.target.phaseKey ?? null,\n on_events: route.input.on ?? null,\n allow_working_phase: route.input.allowWorkingPhase ?? false,\n join_closed_issue: route.input.target.joinClosedIssue ?? false,\n revision: 1,\n created_by: route.actor,\n created_at: now,\n updated_by: route.actor,\n updated_at: now,\n });\n}\n\n/**\n * Takes the project's route lock and reads the routes. Writes that add, delete or move routes\n * call this first, so they run one after another and each reads what the one before committed.\n */\nasync function lockIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n if ((await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), { locked_at: new Date() })) !== 1) {\n throw new ConcurrentBoardWrite();\n }\n return readIntakeRoutes(ops, scope);\n}\n\n/** Moves routes, read under the project's route lock, to the positions of their order in `rows`. */\nasync function placeIntakeRoutes(ops: FactoryStorageOps, rows: IntakeRouteRow[], actor?: string): Promise<void> {\n const moving = rows.flatMap((row, position) => (row.position === position ? [] : [{ row, position }]));\n const parked = [];\n for (const [index, { row, position }] of moving.entries()) {\n const revision = await updateIntakeRouteRow(ops, row, {\n position: -(index + 1),\n ...(actor !== undefined && { updated_by: actor }),\n });\n parked.push({ id: row.id, revision, position });\n }\n for (const { id, revision, position } of parked) {\n if ((await ops.updateMany(INTAKE_ROUTES, { id, revision }, { position })) !== 1) throw new ConcurrentBoardWrite();\n }\n}\n"],"mappings":";;;;;;;AAyKA,MAAa,oBAAoB;;AAmBjC,MAAM,wBAAwB,CAAC,iBAAiB;;AAGhD,MAAa,6BAA6B;AAE1C,IAAa,mBAAb,cAAsC,MAAM;CAG/B;CAFX,OAAgB;CAChB,YACE,MACA,SACA;EACA,MAAM,OAAO;EAHJ,KAAA,OAAA;CAIX;AACF;AAqEA,SAAS,eAAe,MAAoC;CAC1D,OAAO,KAAK,mBAAmB;AACjC;AAEA,SAAS,gBAAgB,MAAoE;CAC3F,MAAM,SAAS,IAAI,IAAI,eAAe,IAAI,CAAC;CAC3C,OAAO,sBAAsB,QAAQ,EAAE,UAAU,CAAC,OAAO,IAAI,GAAG,CAAC;AACnE;AAEA,MAAM,SAAS;AACf,MAAM,SAAS;AACf,MAAM,WAAW;AACjB,MAAM,gBAAgB;AACtB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;AAC3B,MAAM,kBAAkB;AAExB,SAAS,WAAW,EAAE,OAAO,oBAAsC;CACjE,OAAO;EAAE,QAAQ;EAAO,oBAAoB;CAAiB;AAC/D;AAEA,SAAS,cAAc,KAAkC;CACvD,OAAO;EACL,KAAK,IAAI;EACT,UAAU,IAAI;EACd,MAAM,IAAI;EACV,aAAa,IAAI;EACjB,MAAM,IAAI;EACV,QAAQ,IAAI;EACZ,YAAY,IAAI;EAChB,WAAW,IAAI;EACf,eAAe,IAAI;EACnB,UAAU,IAAI;EACd,OAAO,IAAI,SAAS;CACtB;AACF;AAEA,SAAS,SAAS,KAAe,QAAuC;CACtE,OAAO;EACL,IAAI,IAAI;EACR,OAAO,IAAI;EACX,kBAAkB,IAAI;EACtB,KAAK,IAAI;EACT,MAAM,IAAI;EACV,aAAa,IAAI;EACjB,UAAU,IAAI;EACd,U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GAAI;GAAU;EAAS,CAAC;CAChD;CACA,KAAK,MAAM,EAAE,IAAI,UAAU,cAAc,QACvC,IAAK,MAAM,IAAI,WAAW,eAAe;EAAE;EAAI;CAAS,GAAG,EAAE,SAAS,CAAC,MAAO,GAAG,MAAM,IAAI,qBAAqB;AAEpH"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/boards/base.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { DEFAULT_ROUTE_EVENTS, routeEventsProblem } from '../../../boards/board-events.js';\nimport type { StatusEvent } from '../../../boards/board-events.js';\nimport type { FactoryPhaseTool } from '../../../boards/define-board.js';\nimport { DEFAULT_INTAKE_ROUTES } from '../../../boards/work-routes.js';\nimport type { RuleGroup } from '../../../rules/rule-group.js';\nimport type { RetiredAutomationSettings } from '../projects/base.js';\nimport {\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARDS_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n} from './schemas.js';\n\n/** The project a board belongs to. */\nexport interface StoredBoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\nexport type StoredPhaseKind = 'resting' | 'working' | 'terminal';\n\n/** Who runs a working phase. Factory runs every phase with its code agent. */\nexport interface StoredPhaseRunner {\n skill?: string;\n context?: string;\n instructions?: string;\n /** The objective the phase's runs pursue as a goal. */\n goal?: { objective: string; maxRuns?: number };\n}\n\nexport interface StoredPhaseExitTool {\n id: string;\n autoApprove?: boolean;\n autoApproveWhen?: RuleGroup;\n}\n\n/** A phase as it is written. `key` is the stage id cards sit in. */\nexport interface StoredPhaseInput {\n key: string;\n name: string;\n description?: string | null;\n kind: StoredPhaseKind;\n runner?: StoredPhaseRunner | null;\n /** Unset or `null` on a resting or working phase means every other phase; `[]` means none. */\n nextPhases?: string[] | null;\n autoStart?: boolean;\n autoStartWhen?: RuleGroup | null;\n exitTool?: StoredPhaseExitTool | null;\n /** Factory tools the phase grants the session working the card there. */\n tools?: FactoryPhaseTool[] | null;\n}\n\n/** A board as it is written. Phase order is significant: the first phase is where cards start. */\nexport interface StoredBoardInput {\n key: string;\n name: string;\n description?: string | null;\n phases: StoredPhaseInput[];\n}\n\nexport interface StoredPhaseRecord {\n key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n nextPhases: string[] | null;\n autoStart: boolean;\n autoStartWhen: RuleGroup | null;\n exitTool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\nexport interface StoredBoardRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n phases: StoredPhaseRecord[];\n}\n\n/** What a board migration may know about the project besides the board it rewrites. */\nexport interface BoardMigrationContext {\n /** The project switches the boards replaced, as the project last stored them; null when unknown. */\n readonly retiredSettings: RetiredAutomationSettings | null;\n /** The phases of each board that cards sit in, by board key; null when the cards can't be read. */\n readonly occupiedPhases: ReadonlyMap<string, ReadonlySet<string>> | null;\n /**\n * The phases the code board under this key declares; undefined for a board only the project\n * stores. A row that drops one runs without its code rules (`mergeCodeBehaviour`).\n */\n codePhases(boardKey: string): ReadonlySet<string> | undefined;\n /** Tells the operator about a board a migration left as it is. */\n warn(message: string): void;\n}\n\n/** A one-time rewrite of a stored board, keyed so each project gets it once. */\nexport interface StoredBoardMigration {\n key: string;\n /** The board it rewrites; `null` rewrites every board the project stores. */\n boardKey: string | null;\n /** The board to write instead, with what changed; undefined leaves it as it is. */\n migrate(\n board: StoredBoardRecord,\n context: BoardMigrationContext,\n ): { board: Omit<StoredBoardInput, 'key'>; filled: string[] } | undefined;\n}\n\nconst EMPTY_MIGRATION_CONTEXT: BoardMigrationContext = {\n retiredSettings: null,\n occupiedPhases: new Map(),\n codePhases: () => undefined,\n warn: () => {},\n};\n\nexport interface AppliedBoardMigration {\n key: string;\n boardKey: string;\n filled: string[];\n}\n\nexport interface StoredBoardSnapshot {\n version: string | null;\n boards: StoredBoardRecord[];\n}\n\nexport interface IntakeRouteTarget {\n boardKey: string;\n /**\n * Unset lands the card in the board's first phase. On a route that joins a closed issue's\n * card, the phase that card moves to when its board allows it; unset leaves it where it is.\n */\n phaseKey?: string | null;\n /**\n * Files a pull request on the card of the issue it closes, which must be on `boardKey`, as one\n * more source instead of a card of its own. The route doesn't match any other arrival.\n */\n joinClosedIssue?: boolean;\n}\n\n/** An intake route as it is written. */\nexport interface StoredIntakeRouteInput {\n name: string;\n enabled?: boolean;\n /** Null matches every card. */\n when?: RuleGroup | null;\n target: IntakeRouteTarget;\n /** The status events the route handles; unset handles new cards (`work_item.created`). */\n on?: StatusEvent[];\n}\n\nexport interface StoredIntakeRouteRecord {\n id: string;\n orgId: string;\n factoryProjectId: string;\n name: string;\n enabled: boolean;\n position: number;\n when: RuleGroup | null;\n target: { boardKey: string; phaseKey: string | null; joinClosedIssue: boolean };\n on: StatusEvent[];\n revision: number;\n createdBy: string;\n createdAt: Date;\n updatedBy: string;\n updatedAt: Date;\n}\n\nexport type StoredBoardErrorCode =\n | 'board_exists'\n | 'board_not_found'\n | 'revision_mismatch'\n | 'intake_route_not_found'\n | 'intake_route_set_mismatch'\n | 'intake_route_limit'\n | 'invalid_intake_route';\n\n/** A project's most intake routes; a reorder names every one of them. */\nexport const MAX_INTAKE_ROUTES = 100;\n\n// Work's routes are its seed data, kept with the board they target.\nexport {\n DEFAULT_INTAKE_ROUTE,\n PULL_REQUEST_INTAKE_ROUTE,\n CLOSED_COMPLETED_ROUTE,\n CLOSED_CANCELED_ROUTE,\n REOPENED_ROUTE,\n PULL_REQUEST_MERGED_ROUTE,\n PULL_REQUEST_CLOSED_ROUTE,\n PULL_REQUEST_CLOSED_ISSUE_ROUTE,\n PULL_REQUEST_UPDATED_ROUTE,\n PULL_REQUEST_REVIEW_REQUESTED_ROUTE,\n CLOSES_ISSUE_INTAKE_ROUTE,\n CATCH_ALL_INTAKE_ROUTE,\n DEFAULT_INTAKE_ROUTES,\n} from '../../../boards/work-routes.js';\n\n/** The defaults a project whose lock row predates `seeded_defaults` was set up with. */\nconst ORIGINAL_DEFAULT_KEYS = ['outside-authors'];\n\n/** Who the default intake routes are created and last updated by. */\nexport const DEFAULT_INTAKE_ROUTE_ACTOR = 'factory';\n\nexport class StoredBoardError extends Error {\n override name = 'StoredBoardError';\n constructor(\n readonly code: StoredBoardErrorCode,\n message: string,\n ) {\n super(message);\n }\n}\n\ninterface BoardRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n name: string;\n description: string | null;\n position: number;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface VersionRow extends Record<string, unknown> {\n version: string;\n /** Keys of the boards Factory stored in the project; null on rows written before the list. */\n seeded_boards: string[] | null;\n /** Keys of the board migrations applied to the project; null before the first one. */\n applied_migrations: string[] | null;\n}\n\ninterface PhaseRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n board_key: string;\n phase_key: string;\n position: number;\n name: string;\n description: string | null;\n kind: StoredPhaseKind;\n runner: StoredPhaseRunner | null;\n next_phases: string[] | null;\n auto_start: boolean;\n auto_start_when: RuleGroup | null;\n exit_tool: StoredPhaseExitTool | null;\n tools: FactoryPhaseTool[] | null;\n}\n\ninterface IntakeRouteRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n name: string;\n enabled: boolean;\n position: number;\n when_condition: RuleGroup | null;\n board_key: string;\n phase_key: string | null;\n /** Null on rows written before routes named events: they place new cards. */\n on_events: StatusEvent[] | null;\n join_closed_issue: boolean | null;\n revision: number;\n created_by: string;\n created_at: Date;\n updated_by: string;\n updated_at: Date;\n}\n\ninterface IntakeRouteLockRow extends Record<string, unknown> {\n /** Keys of the `DEFAULT_INTAKE_ROUTES` added to the project; null on rows written before the list. */\n seeded_defaults: string[] | null;\n}\n\nfunction seededDefaults(lock: IntakeRouteLockRow): string[] {\n return lock.seeded_defaults ?? ORIGINAL_DEFAULT_KEYS;\n}\n\nfunction missingDefaults(lock: IntakeRouteLockRow): (typeof DEFAULT_INTAKE_ROUTES)[number][] {\n const seeded = new Set(seededDefaults(lock));\n return DEFAULT_INTAKE_ROUTES.filter(({ key }) => !seeded.has(key));\n}\n\nconst BOARDS = 'factory_boards';\nconst PHASES = 'factory_board_phases';\nconst VERSIONS = 'factory_board_definition_versions';\nconst INTAKE_ROUTES = 'factory_intake_routes';\nconst INTAKE_ROUTE_LOCKS = 'factory_intake_route_locks';\nconst MAX_WRITE_ATTEMPTS = 3;\nconst MIGRATION_ACTOR = 'factory';\n\nfunction scopeWhere({ orgId, factoryProjectId }: StoredBoardScope) {\n return { org_id: orgId, factory_project_id: factoryProjectId };\n}\n\nfunction toPhaseRecord(row: PhaseRow): StoredPhaseRecord {\n return {\n key: row.phase_key,\n position: row.position,\n name: row.name,\n description: row.description,\n kind: row.kind,\n runner: row.runner,\n nextPhases: row.next_phases,\n autoStart: row.auto_start,\n autoStartWhen: row.auto_start_when,\n exitTool: row.exit_tool,\n tools: row.tools ?? null,\n };\n}\n\nfunction toRecord(row: BoardRow, phases: PhaseRow[]): StoredBoardRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n key: row.board_key,\n name: row.name,\n description: row.description,\n position: row.position,\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n phases: phases.sort((left, right) => left.position - right.position).map(toPhaseRecord),\n };\n}\n\n/** A compare-and-set inside a write lost to a concurrent writer; the write is retried from fresh reads. */\nclass ConcurrentBoardWrite extends Error {}\n\n/**\n * Each project's boards and their ordered phases. Every write runs in one transaction that also\n * replaces the project's row in `factory_board_definition_versions`, so caches on other\n * replicas can detect it.\n */\nexport class StoredBoardsStorage extends FactoryStorageDomain {\n constructor() {\n super('boards');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n FACTORY_BOARDS_SCHEMA,\n FACTORY_BOARD_PHASES_SCHEMA,\n FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA,\n FACTORY_INTAKE_ROUTES_SCHEMA,\n FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA,\n ]);\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany(PHASES, {});\n await this.ops.deleteMany(BOARDS, {});\n await this.ops.deleteMany(VERSIONS, {});\n await this.ops.deleteMany(INTAKE_ROUTES, {});\n await this.ops.deleteMany(INTAKE_ROUTE_LOCKS, {});\n }\n\n /** The project's current definition version; null before its first board write. */\n async readVersion(scope: StoredBoardScope): Promise<string | null> {\n return readVersion(this.ops, scope);\n }\n\n /** The project's boards in order. */\n async list(scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n return readBoards(this.ops, scope);\n }\n\n /**\n * The version and the boards, read in that order: a write landing between the two reads leaves a\n * version older than the rows, so a cache keyed on it rereads on its next check instead of\n * keeping the stale rows.\n */\n async snapshot(scope: StoredBoardScope): Promise<StoredBoardSnapshot> {\n const version = await readVersion(this.ops, scope);\n return { version, boards: await this.list(scope) };\n }\n\n async get(scope: StoredBoardScope, key: string): Promise<StoredBoardRecord | null> {\n const row = await this.ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) return null;\n const phases = await this.ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: key });\n return toRecord(row, phases);\n }\n\n /** Creates a board through the API. */\n async create(scope: StoredBoardScope, input: StoredBoardInput, actor: string): Promise<StoredBoardRecord> {\n await ensureVersionRow(this.ops, scope);\n try {\n return await this.#write(scope, async ops => {\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n if (rows.some(row => row.board_key === input.key)) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n await insertBoard(ops, scope, input, { position: nextPosition(rows), actor });\n return { result: undefined, changed: true };\n }).then(async () => (await this.get(scope, input.key))!);\n } catch (error) {\n // Only the board key's index means the board exists; a lost race on another table is not that.\n if (error instanceof UniqueViolationError && error.collection === BOARDS) {\n throw new StoredBoardError('board_exists', `Board \"${input.key}\" already exists in this project.`);\n }\n throw error;\n }\n }\n\n /** Replaces a board's name, description and phases. The board key never changes. */\n async replace(\n scope: StoredBoardScope,\n key: string,\n input: Omit<StoredBoardInput, 'key'>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { key, ...input }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /**\n * Stores Factory's boards (Work, app and seed boards) in the project, each key once: a key the\n * project has had before is skipped even if its board was deleted since, and a stored board is\n * never rewritten. A project stored before the list was kept counts the boards it has as stored.\n * Reads one row when every key was stored before. Returns the keys it inserted.\n */\n async seedBoards(scope: StoredBoardScope, boards: readonly StoredBoardInput[]): Promise<string[]> {\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.seeded_boards && boards.every(board => marker.seeded_boards!.includes(board.key))) return [];\n return this.#insertOnce(scope, boards, { actor: DEFAULT_INTAKE_ROUTE_ACTOR, skipSeeded: true });\n }\n\n /**\n * Inserts a board into the project unless one is stored under its key, and records the key as\n * stored, so seeding never adds it again. Unlike seeding, it inserts a key the project deleted.\n * Returns whether it inserted the board.\n */\n async insertIfMissing(scope: StoredBoardScope, board: StoredBoardInput, actor: string): Promise<boolean> {\n return (await this.#insertOnce(scope, [board], { actor, skipSeeded: false })).length > 0;\n }\n\n async #insertOnce(\n scope: StoredBoardScope,\n boards: readonly StoredBoardInput[],\n options: { actor: string; skipSeeded: boolean },\n ): Promise<string[]> {\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const marker = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const rows = await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope));\n const present = new Set(rows.map(row => row.board_key));\n const seeded = new Set(marker.seeded_boards ?? present);\n let position = nextPosition(rows);\n const inserted: string[] = [];\n for (const board of boards) {\n if (present.has(board.key) || (options.skipSeeded && seeded.has(board.key))) continue;\n await insertBoard(ops, scope, board, { position: position++, actor: options.actor });\n present.add(board.key);\n inserted.push(board.key);\n }\n const next = [...new Set([...seeded, ...boards.map(board => board.key)])];\n const unchanged = marker.seeded_boards !== null && next.length === marker.seeded_boards.length;\n if (inserted.length === 0 && unchanged) return inserted;\n // Compare-and-set on the version, and every marker write takes a new one: two replicas\n // recording different keys can't both match the version they read, so neither key is lost.\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: marker.version },\n {\n seeded_boards: next,\n version: randomUUID(),\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return inserted;\n });\n }\n\n /**\n * Runs each migration the project hasn't had yet, once: the keys applied are recorded on the\n * project's version row in the same transaction as the board writes, and the compare-and-set on\n * its version makes a concurrent first load retry from fresh reads, where it finds them applied.\n * A migration whose board the project doesn't have is recorded without running, and the version\n * only changes when a board was rewritten. Reads one row\n * when every key was applied before. Returns what each migration that rewrote a board filled.\n */\n async applyBoardMigrations(\n scope: StoredBoardScope,\n migrations: readonly StoredBoardMigration[],\n /**\n * Read through the transaction's `ops`, again on every retry, and only when a migration is still\n * pending, so what it reports is as fresh as the boards the migrations rewrite.\n */\n context: (ops: FactoryStorageOps) => Promise<BoardMigrationContext> = async () => EMPTY_MIGRATION_CONTEXT,\n ): Promise<AppliedBoardMigration[]> {\n if (migrations.length === 0) return [];\n const marker = await this.ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope));\n if (marker?.applied_migrations && migrations.every(({ key }) => marker.applied_migrations!.includes(key))) {\n return [];\n }\n await ensureVersionRow(this.ops, scope);\n return this.#transact(async ops => {\n const current = (await ops.findOne<VersionRow>(VERSIONS, scopeWhere(scope)))!;\n const applied = current.applied_migrations ?? [];\n const pending = migrations.filter(({ key }) => !applied.includes(key));\n if (pending.length === 0) return [];\n const project = await context(ops);\n const changed: AppliedBoardMigration[] = [];\n for (const migration of pending) {\n const rows =\n migration.boardKey === null\n ? await ops.findMany<BoardRow>(BOARDS, scopeWhere(scope))\n : await ops.findMany<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: migration.boardKey });\n for (const row of rows) {\n const phases = await ops.findMany<PhaseRow>(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n const result = migration.migrate(toRecord(row, phases), project);\n if (!result) continue;\n await writeBoard(ops, scope, row, { ...result.board, key: row.board_key }, MIGRATION_ACTOR);\n changed.push({ key: migration.key, boardKey: row.board_key, filled: result.filled });\n }\n }\n const updated = await ops.updateMany(\n VERSIONS,\n { ...scopeWhere(scope), version: current.version },\n {\n applied_migrations: [...applied, ...pending.map(({ key }) => key)],\n // Only a rewritten board is news to the other replicas' caches.\n version: changed.length > 0 ? randomUUID() : current.version,\n updated_at: new Date(),\n },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return changed;\n });\n }\n\n /** Rewrites a board to `definition` (Factory's current one for its key), raising its revision. */\n async resetTo(\n scope: StoredBoardScope,\n key: string,\n definition: StoredBoardInput,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredBoardRecord> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n await writeBoard(ops, scope, row, { ...definition, key }, options.actor);\n return { result: undefined, changed: true };\n });\n return (await this.get(scope, key))!;\n }\n\n /** Deletes a board and its phases. */\n async delete(scope: StoredBoardScope, key: string, options: { expectedRevision: number }): Promise<void> {\n await this.#write(scope, async ops => {\n const row = await findBoard(ops, scope, key);\n checkRevision(row, key, options.expectedRevision);\n if ((await ops.deleteMany(BOARDS, { id: row.id, revision: row.revision })) === 0)\n throw new ConcurrentBoardWrite();\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: key });\n return { result: undefined, changed: true };\n });\n }\n\n /** The project's intake routes in the order they are tried; Factory's `DEFAULT_INTAKE_ROUTES` are added once each. */\n async listIntakeRoutes(scope: StoredBoardScope): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n return (await readIntakeRoutes(this.ops, scope)).map(toIntakeRouteRecord);\n }\n\n async getIntakeRoute(scope: StoredBoardScope, id: string): Promise<StoredIntakeRouteRecord | null> {\n const row = await this.ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n return row ? toIntakeRouteRecord(row) : null;\n }\n\n /**\n * Adds a route after the project's last one. A route that places new cards goes just ahead of the\n * first route that takes every new card instead, since after it it would never place one.\n */\n async createIntakeRoute(\n scope: StoredBoardScope,\n input: StoredIntakeRouteInput,\n actor: string,\n ): Promise<StoredIntakeRouteRecord> {\n const id = randomUUID();\n checkRouteEvents(input.on ?? DEFAULT_ROUTE_EVENTS, input.when ?? null);\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n if (rows.length >= MAX_INTAKE_ROUTES) {\n throw new StoredBoardError(\n 'intake_route_limit',\n `A project can have at most ${MAX_INTAKE_ROUTES} intake routes; delete one first.`,\n );\n }\n const position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n await insertIntakeRoute(ops, scope, { id, input, position, actor });\n const ahead = (input.on ?? DEFAULT_ROUTE_EVENTS).includes('work_item.created')\n ? rows.findIndex(catchesEveryNewCard)\n : -1;\n if (ahead >= 0) {\n const added = (await readIntakeRoutes(ops, scope)).find(row => row.id === id)!;\n await placeIntakeRoutes(ops, rows.toSpliced(ahead, 0, added), actor);\n }\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Changes the fields `patch` names; the route keeps its place in the order. */\n async updateIntakeRoute(\n scope: StoredBoardScope,\n id: string,\n patch: Partial<StoredIntakeRouteInput>,\n options: { expectedRevision: number; actor: string },\n ): Promise<StoredIntakeRouteRecord> {\n await this.#transact(async ops => {\n const row = await findIntakeRoute(ops, scope, id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n checkRouteEvents(patch.on ?? routeEvents(row), patch.when !== undefined ? patch.when : row.when_condition);\n await updateIntakeRouteRow(ops, row, {\n ...(patch.on !== undefined && { on_events: patch.on }),\n ...(patch.name !== undefined && { name: patch.name }),\n ...(patch.enabled !== undefined && { enabled: patch.enabled }),\n ...(patch.when !== undefined && { when_condition: patch.when }),\n ...(patch.target !== undefined && {\n board_key: patch.target.boardKey,\n phase_key: patch.target.phaseKey ?? null,\n join_closed_issue: patch.target.joinClosedIssue ?? false,\n }),\n updated_by: options.actor,\n });\n });\n return (await this.getIntakeRoute(scope, id))!;\n }\n\n /** Deletes a route; the routes after it move up one place. */\n async deleteIntakeRoute(scope: StoredBoardScope, id: string, options: { expectedRevision: number }): Promise<void> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const row = rows.find(route => route.id === id);\n if (!row) throw intakeRouteNotFound(id);\n checkIntakeRouteRevision(row, options.expectedRevision);\n if ((await ops.deleteMany(INTAKE_ROUTES, { id: row.id, revision: row.revision })) === 0) {\n throw new ConcurrentBoardWrite();\n }\n await placeIntakeRoutes(\n ops,\n rows.filter(route => route.id !== row.id),\n );\n });\n }\n\n /** Puts the project's routes in the order of `ids`, which must name every route exactly once. */\n async reorderIntakeRoutes(scope: StoredBoardScope, ids: string[], actor: string): Promise<StoredIntakeRouteRecord[]> {\n await this.#ensureIntakeRoutes(scope);\n await this.#transact(async ops => {\n const rows = await lockIntakeRoutes(ops, scope);\n const byId = new Map(rows.map(row => [row.id, row]));\n if (ids.length !== rows.length || new Set(ids).size !== ids.length || ids.some(id => !byId.has(id))) {\n throw new StoredBoardError(\n 'intake_route_set_mismatch',\n 'The order must list every intake route of the project exactly once; reload the routes and try again.',\n );\n }\n await placeIntakeRoutes(\n ops,\n ids.map(id => byId.get(id)!),\n actor,\n );\n });\n return this.listIntakeRoutes(scope);\n }\n\n /**\n * Creates the project's route lock row (see `FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA`) and adds each of\n * `DEFAULT_INTAKE_ROUTES` the row doesn't list as added yet, after the project's routes. The row\n * records every default it added, so a project whose admin deleted one doesn't get it back. Runs\n * before, never inside, a write's transaction: the lock taken there must always be an update.\n */\n async #ensureIntakeRoutes(scope: StoredBoardScope): Promise<void> {\n const lock = await this.ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope));\n if (lock && missingDefaults(lock).length === 0) return;\n await this.#transact(async ops => {\n if (await ops.findOne(INTAKE_ROUTE_LOCKS, scopeWhere(scope))) await lockIntakeRoutes(ops, scope);\n // A racing first read inserted the lock row first: this one fails on the unique index and\n // retries, taking the lock above.\n else\n await ops.insertOne(INTAKE_ROUTE_LOCKS, { ...scopeWhere(scope), locked_at: new Date(), seeded_defaults: [] });\n // Read under the lock: a racing seeder that committed first already added what it listed.\n const current = (await ops.findOne<IntakeRouteLockRow>(INTAKE_ROUTE_LOCKS, scopeWhere(scope)))!;\n const missing = missingDefaults(current);\n if (missing.length === 0) return;\n const rows = await readIntakeRoutes(ops, scope);\n let position = rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n const first: string[] = [];\n for (const { route, first: leads } of missing) {\n // A project at the limit keeps its own routes; the default counts as added all the same.\n if (position >= MAX_INTAKE_ROUTES) break;\n const id = randomUUID();\n await insertIntakeRoute(ops, scope, {\n id,\n input: route,\n position: position++,\n actor: DEFAULT_INTAKE_ROUTE_ACTOR,\n });\n if (leads) first.push(id);\n }\n // A project that had routes before gets a leading default ahead of them.\n if (first.length > 0 && rows.length > 0) {\n const placed = await readIntakeRoutes(ops, scope);\n const leading = new Set(first);\n await placeIntakeRoutes(ops, [\n ...first.map(id => placed.find(row => row.id === id)!),\n ...placed.filter(row => !leading.has(row.id)),\n ]);\n }\n await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), {\n seeded_defaults: [...seededDefaults(current), ...missing.map(({ key }) => key)],\n });\n });\n }\n\n /**\n * Runs `fn` in a transaction and replaces the project's version when it changed anything.\n * Lost races (a compare-and-set miss, or a concurrent write that inserted the same board or the\n * project's first version row) retry from fresh reads.\n */\n async #write<T>(\n scope: StoredBoardScope,\n fn: (ops: FactoryStorageOps) => Promise<{ result: T; changed: boolean }>,\n ): Promise<T> {\n return this.#transact(async ops => {\n const { result, changed } = await fn(ops);\n if (changed) await bumpVersion(ops, scope);\n return result;\n });\n }\n\n /**\n * Runs `fn` in a transaction, retrying lost races from fresh reads. Intake route writes use it\n * directly: routes are read uncached, so they leave the board definition version alone.\n */\n async #transact<T>(fn: (ops: FactoryStorageOps) => Promise<T>): Promise<T> {\n for (let attempt = 1; ; attempt++) {\n try {\n // Read committed is enough: every row change is a compare-and-set on `revision` and every\n // insert meets the unique index. Serializable isolation would also fail writes to\n // unrelated projects that replicas run side by side.\n return await this.storage.withTransaction(fn);\n } catch (error) {\n const retryable = error instanceof ConcurrentBoardWrite || error instanceof UniqueViolationError;\n if (!retryable || attempt >= MAX_WRITE_ATTEMPTS) throw error;\n }\n }\n }\n}\n\nasync function readVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<string | null> {\n const row = await ops.findOne<{ version: string }>(VERSIONS, scopeWhere(scope));\n return row?.version ?? null;\n}\n\nasync function readBoards(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<StoredBoardRecord[]> {\n const [rows, phases] = await Promise.all([\n ops.findMany<BoardRow>(BOARDS, scopeWhere(scope)),\n ops.findMany<PhaseRow>(PHASES, scopeWhere(scope)),\n ]);\n const byBoard = new Map<string, PhaseRow[]>();\n for (const phase of phases) {\n const list = byBoard.get(phase.board_key) ?? [];\n list.push(phase);\n byBoard.set(phase.board_key, list);\n }\n return rows\n .sort((left, right) => left.position - right.position || left.board_key.localeCompare(right.board_key))\n .map(row => toRecord(row, byBoard.get(row.board_key) ?? []));\n}\n\n/**\n * Inserts the project's version row if it has none. This runs outside the write transaction: on\n * Postgres, two transactions racing to insert it would leave the loser's transaction aborted, so\n * the version bump inside a write must always be an update.\n */\nasync function ensureVersionRow(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n if (await ops.findOne(VERSIONS, scopeWhere(scope))) return;\n try {\n await ops.insertOne(VERSIONS, { ...scopeWhere(scope), version: randomUUID(), updated_at: new Date() });\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n }\n}\n\nasync function bumpVersion(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<void> {\n await ops.upsertOne(VERSIONS, ['org_id', 'factory_project_id'], {\n ...scopeWhere(scope),\n version: randomUUID(),\n updated_at: new Date(),\n });\n}\n\nasync function findBoard(ops: FactoryStorageOps, scope: StoredBoardScope, key: string): Promise<BoardRow> {\n const row = await ops.findOne<BoardRow>(BOARDS, { ...scopeWhere(scope), board_key: key });\n if (!row) {\n throw new StoredBoardError('board_not_found', `Board \"${key}\" does not exist in this project.`);\n }\n return row;\n}\n\nfunction checkRevision(row: BoardRow, key: string, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Board \"${key}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\nfunction nextPosition(rows: BoardRow[]): number {\n return rows.reduce((max, row) => Math.max(max, row.position), -1) + 1;\n}\n\n/** Sets columns on a board row and raises its revision, unless another writer changed it first. */\nasync function updateRow(ops: FactoryStorageOps, row: BoardRow, set: Partial<BoardRow>): Promise<void> {\n const updated = await ops.updateMany(\n BOARDS,\n { id: row.id, revision: row.revision },\n { ...set, revision: row.revision + 1, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n}\n\nasync function insertPhases(ops: FactoryStorageOps, scope: StoredBoardScope, input: StoredBoardInput): Promise<void> {\n for (const [position, phase] of input.phases.entries()) {\n await ops.insertOne<PhaseRow>(PHASES, {\n ...scopeWhere(scope),\n board_key: input.key,\n phase_key: phase.key,\n position,\n name: phase.name,\n description: phase.description ?? null,\n kind: phase.kind,\n runner: phase.runner ?? null,\n next_phases: phase.nextPhases ?? null,\n auto_start: phase.autoStart ?? false,\n auto_start_when: phase.autoStartWhen ?? null,\n exit_tool: phase.exitTool ?? null,\n tools: phase.tools?.length ? phase.tools : null,\n });\n }\n}\n\nasync function insertBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n input: StoredBoardInput,\n options: { position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<BoardRow>(BOARDS, {\n ...scopeWhere(scope),\n board_key: input.key,\n name: input.name,\n description: input.description ?? null,\n position: options.position,\n revision: 1,\n created_by: options.actor,\n created_at: now,\n updated_by: options.actor,\n updated_at: now,\n });\n await insertPhases(ops, scope, input);\n}\n\n/** Replaces a board's definition and phases in place, keeping its key, position and history. */\nasync function writeBoard(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n row: BoardRow,\n input: StoredBoardInput,\n actor: string,\n): Promise<void> {\n await updateRow(ops, row, { name: input.name, description: input.description ?? null, updated_by: actor });\n await ops.deleteMany(PHASES, { ...scopeWhere(scope), board_key: row.board_key });\n await insertPhases(ops, scope, { ...input, key: row.board_key });\n}\n\nfunction routeEvents(row: IntakeRouteRow): StatusEvent[] {\n return row.on_events ?? [...DEFAULT_ROUTE_EVENTS];\n}\n\nfunction checkRouteEvents(on: readonly string[], when: RuleGroup | null): void {\n const problem = routeEventsProblem(on, when);\n if (problem) throw new StoredBoardError('invalid_intake_route', problem);\n}\n\nfunction toIntakeRouteRecord(row: IntakeRouteRow): StoredIntakeRouteRecord {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n name: row.name,\n enabled: row.enabled,\n position: row.position,\n when: row.when_condition,\n target: { boardKey: row.board_key, phaseKey: row.phase_key, joinClosedIssue: row.join_closed_issue === true },\n on: routeEvents(row),\n revision: row.revision,\n createdBy: row.created_by,\n createdAt: row.created_at,\n updatedBy: row.updated_by,\n updatedAt: row.updated_at,\n };\n}\n\n/** Whether `row` places every new card that reaches it, as the seeded \"Everything else\" route does. */\nfunction catchesEveryNewCard(row: IntakeRouteRow): boolean {\n return (\n row.enabled &&\n row.when_condition === null &&\n (row.on_events ?? DEFAULT_ROUTE_EVENTS).includes('work_item.created') &&\n !row.join_closed_issue\n );\n}\n\nasync function readIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n const rows = await ops.findMany<IntakeRouteRow>(INTAKE_ROUTES, scopeWhere(scope));\n return rows.sort((left, right) => left.position - right.position);\n}\n\nasync function findIntakeRoute(ops: FactoryStorageOps, scope: StoredBoardScope, id: string): Promise<IntakeRouteRow> {\n const row = await ops.findOne<IntakeRouteRow>(INTAKE_ROUTES, { ...scopeWhere(scope), id });\n if (!row) throw intakeRouteNotFound(id);\n return row;\n}\n\nfunction intakeRouteNotFound(id: string): StoredBoardError {\n return new StoredBoardError('intake_route_not_found', `Intake route \"${id}\" does not exist in this project.`);\n}\n\nfunction checkIntakeRouteRevision(row: IntakeRouteRow, expectedRevision: number): void {\n if (row.revision !== expectedRevision) {\n throw new StoredBoardError(\n 'revision_mismatch',\n `Intake route \"${row.name}\" is at revision ${row.revision}, not ${expectedRevision}; reload it and try again.`,\n );\n }\n}\n\n/** Sets columns on a route row and raises its revision, unless another writer changed it first. */\nasync function updateIntakeRouteRow(\n ops: FactoryStorageOps,\n row: IntakeRouteRow,\n set: Partial<IntakeRouteRow>,\n): Promise<number> {\n const revision = row.revision + 1;\n const updated = await ops.updateMany(\n INTAKE_ROUTES,\n { id: row.id, revision: row.revision },\n { ...set, revision, updated_at: new Date() },\n );\n if (updated !== 1) throw new ConcurrentBoardWrite();\n return revision;\n}\n\nasync function insertIntakeRoute(\n ops: FactoryStorageOps,\n scope: StoredBoardScope,\n route: { id: string; input: StoredIntakeRouteInput; position: number; actor: string },\n): Promise<void> {\n const now = new Date();\n await ops.insertOne<IntakeRouteRow>(INTAKE_ROUTES, {\n id: route.id,\n ...scopeWhere(scope),\n name: route.input.name,\n enabled: route.input.enabled ?? true,\n position: route.position,\n when_condition: route.input.when ?? null,\n board_key: route.input.target.boardKey,\n phase_key: route.input.target.phaseKey ?? null,\n on_events: route.input.on ?? null,\n join_closed_issue: route.input.target.joinClosedIssue ?? false,\n revision: 1,\n created_by: route.actor,\n created_at: now,\n updated_by: route.actor,\n updated_at: now,\n });\n}\n\n/**\n * Takes the project's route lock and reads the routes. Writes that add, delete or move routes\n * call this first, so they run one after another and each reads what the one before committed.\n */\nasync function lockIntakeRoutes(ops: FactoryStorageOps, scope: StoredBoardScope): Promise<IntakeRouteRow[]> {\n if ((await ops.updateMany(INTAKE_ROUTE_LOCKS, scopeWhere(scope), { locked_at: new Date() })) !== 1) {\n throw new ConcurrentBoardWrite();\n }\n return readIntakeRoutes(ops, scope);\n}\n\n/** Moves routes, read under the project's route lock, to the positions of their order in `rows`. */\nasync function placeIntakeRoutes(ops: FactoryStorageOps, rows: IntakeRouteRow[], actor?: string): Promise<void> {\n const moving = rows.flatMap((row, position) => (row.position === position ? [] : [{ row, position }]));\n const parked = [];\n for (const [index, { row, position }] of moving.entries()) {\n const revision = await updateIntakeRouteRow(ops, row, {\n position: -(index + 1),\n ...(actor !== undefined && { updated_by: actor }),\n });\n parked.push({ id: row.id, revision, position });\n }\n for (const { id, revision, position } of parked) {\n if ((await ops.updateMany(INTAKE_ROUTES, { id, revision }, { position })) !== 1) throw new ConcurrentBoardWrite();\n }\n}\n"],"mappings":";;;;;;AA2HA,MAAM,0BAAiD;CACrD,iBAAiB;CACjB,gCAAgB,IAAI,IAAI;CACxB,k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AAa,WAAW,CAAC,IAAI,CAAC;EAAE;EAAK;CAAS,CAAC,CAAE;CACrG,MAAM,SAAS,CAAC;CAChB,KAAK,MAAM,CAAC,OAAO,EAAE,KAAK,eAAe,OAAO,QAAQ,GAAG;EACzD,MAAM,WAAW,MAAM,qBAAqB,KAAK,KAAK;GACpD,UAAU,EAAE,QAAQ;GACpB,GAAI,UAAU,KAAA,KAAa,EAAE,YAAY,MAAM;EACjD,CAAC;EACD,OAAO,KAAK;GAAE,IAAI,IAAI;GAAI;GAAU;EAAS,CAAC;CAChD;CACA,KAAK,MAAM,EAAE,IAAI,UAAU,cAAc,QACvC,IAAK,MAAM,IAAI,WAAW,eAAe;EAAE;EAAI;CAAS,GAAG,EAAE,SAAS,CAAC,MAAO,GAAG,MAAM,IAAI,qBAAqB;AAEpH"}
@@ -1 +1 @@
1
- {"version":3,"file":"schemas.js","names":[],"sources":["../../../../src/storage/domains/boards/schemas.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\n/** A project's boards. `board_key` is the id cards reference (`work_items.board`). */\nexport const FACTORY_BOARDS_SCHEMA: CollectionSchema = {\n name: 'factory_boards',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n position: { type: 'integer' },\n // Rises on every write to the board or its phases; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_boards_project_key', columns: ['org_id', 'factory_project_id', 'board_key'] }],\n indexes: [{ name: 'factory_boards_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A board's ordered phases. `phase_key` is the stage id cards sit in. */\nexport const FACTORY_BOARD_PHASES_SCHEMA: CollectionSchema = {\n name: 'factory_board_phases',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n phase_key: { type: 'text' },\n position: { type: 'integer' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n kind: { type: 'text' },\n // { skill?, context?, instructions? }; room for other runner types later.\n runner: { type: 'json', nullable: true },\n next_phases: { type: 'json', nullable: true },\n auto_start: { type: 'boolean', default: false },\n auto_start_when: { type: 'json', nullable: true },\n exit_tool: { type: 'json', nullable: true },\n // Factory tools the phase grants the session working the card there, e.g. [\"factory_record_review_verdict\"].\n tools: { type: 'json', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_board_phases_project_board_phase',\n columns: ['org_id', 'factory_project_id', 'board_key', 'phase_key'],\n },\n ],\n indexes: [{ name: 'factory_board_phases_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project's ordered intake routes: where new cards matching `when_condition` land. */\nexport const FACTORY_INTAKE_ROUTES_SCHEMA: CollectionSchema = {\n name: 'factory_intake_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n name: { type: 'text' },\n enabled: { type: 'boolean', default: true },\n position: { type: 'integer' },\n // A card RuleGroup; null matches every card. Not named `when`, which is an SQL keyword.\n when_condition: { type: 'json', nullable: true },\n board_key: { type: 'text' },\n // Null lands the card in the board's first phase.\n phase_key: { type: 'text', nullable: true },\n // The status events the route handles (`StatusEvent`s). Null on rows written before routes named\n // events: those place new cards, as `['work_item.created']`.\n on_events: { type: 'json', nullable: true },\n // Lets an event move an existing card into a working phase. Null on older rows: off.\n allow_working_phase: { type: 'boolean', nullable: true },\n // True files a pull request on the card of the issue it closes instead of a new card. Null on rows written before it.\n join_closed_issue: { type: 'boolean', nullable: true },\n // Rises on every write to the route, including a move; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_intake_routes_project_position', columns: ['org_id', 'factory_project_id', 'position'] },\n ],\n indexes: [{ name: 'factory_intake_routes_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project that every write adding, deleting or moving intake routes upserts first,\n * inside its transaction. The upsert holds the row until commit, so those writes on one project\n * run one after another and positions stay 0..n-1 with no gaps.\n */\nexport const FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_intake_route_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n locked_at: { type: 'timestamp' },\n // Keys of the default routes Factory added to the project (`DEFAULT_INTAKE_ROUTES`), so each is\n // added once. Null on rows written before the list: those projects got `outside-authors`.\n seeded_defaults: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_intake_route_locks_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project whose `version` is replaced inside every board write, so other replicas\n * can tell their cached boards are stale with one indexed read.\n */\nexport const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_definition_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n // Keys of the boards Factory stored in the project (Work, app and seed boards); each is stored\n // once, so one the project deleted stays deleted. Null on projects stored before the list.\n seeded_boards: { type: 'json', nullable: true },\n // Keys of the board migrations applied to the project, so each runs once: a field a user\n // later sets back to an old default is never rewritten again. Null before the first one.\n applied_migrations: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_definition_versions_project', columns: ['org_id', 'factory_project_id'] }],\n};\n"],"mappings":";;AAGA,MAAa,wBAA0C;CACrD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAA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AAoB,EAAE,MAAM,OAAO;EACnC,SAAS,EAAE,MAAM,OAAO;EACxB,YAAY,EAAE,MAAM,YAAY;EAGhC,eAAe;GAAE,MAAM;GAAQ,UAAU;EAAK;EAG9C,oBAAoB;GAAE,MAAM;GAAQ,UAAU;EAAK;CACrD;CACA,eAAe,CAAC;EAAE,MAAM;EAA6C,SAAS,CAAC,UAAU,oBAAoB;CAAE,CAAC;AAClH"}
1
+ {"version":3,"file":"schemas.js","names":[],"sources":["../../../../src/storage/domains/boards/schemas.ts"],"sourcesContent":["import type { CollectionSchema } from '@mastra/core/storage';\n\n/** A project's boards. `board_key` is the id cards reference (`work_items.board`). */\nexport const FACTORY_BOARDS_SCHEMA: CollectionSchema = {\n name: 'factory_boards',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n position: { type: 'integer' },\n // Rises on every write to the board or its phases; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [{ name: 'factory_boards_project_key', columns: ['org_id', 'factory_project_id', 'board_key'] }],\n indexes: [{ name: 'factory_boards_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A board's ordered phases. `phase_key` is the stage id cards sit in. */\nexport const FACTORY_BOARD_PHASES_SCHEMA: CollectionSchema = {\n name: 'factory_board_phases',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n board_key: { type: 'text' },\n phase_key: { type: 'text' },\n position: { type: 'integer' },\n name: { type: 'text' },\n description: { type: 'text', nullable: true },\n kind: { type: 'text' },\n // { skill?, context?, instructions? }; room for other runner types later.\n runner: { type: 'json', nullable: true },\n next_phases: { type: 'json', nullable: true },\n auto_start: { type: 'boolean', default: false },\n auto_start_when: { type: 'json', nullable: true },\n exit_tool: { type: 'json', nullable: true },\n // Factory tools the phase grants the session working the card there, e.g. [\"factory_record_review_verdict\"].\n tools: { type: 'json', nullable: true },\n },\n uniqueIndexes: [\n {\n name: 'factory_board_phases_project_board_phase',\n columns: ['org_id', 'factory_project_id', 'board_key', 'phase_key'],\n },\n ],\n indexes: [{ name: 'factory_board_phases_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/** A project's ordered intake routes: where new cards matching `when_condition` land. */\nexport const FACTORY_INTAKE_ROUTES_SCHEMA: CollectionSchema = {\n name: 'factory_intake_routes',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n name: { type: 'text' },\n enabled: { type: 'boolean', default: true },\n position: { type: 'integer' },\n // A card RuleGroup; null matches every card. Not named `when`, which is an SQL keyword.\n when_condition: { type: 'json', nullable: true },\n board_key: { type: 'text' },\n // Null lands the card in the board's first phase.\n phase_key: { type: 'text', nullable: true },\n // The status events the route handles (`StatusEvent`s). Null on rows written before routes named\n // events: those place new cards, as `['work_item.created']`.\n on_events: { type: 'json', nullable: true },\n // No longer read or written: a route moves a card into any phase. Kept so existing tables match.\n allow_working_phase: { type: 'boolean', nullable: true },\n // True files a pull request on the card of the issue it closes instead of a new card. Null on rows written before it.\n join_closed_issue: { type: 'boolean', nullable: true },\n // Rises on every write to the route, including a move; the compare-and-set token for edits.\n revision: { type: 'integer' },\n created_by: { type: 'text' },\n created_at: { type: 'timestamp' },\n updated_by: { type: 'text' },\n updated_at: { type: 'timestamp' },\n },\n uniqueIndexes: [\n { name: 'factory_intake_routes_project_position', columns: ['org_id', 'factory_project_id', 'position'] },\n ],\n indexes: [{ name: 'factory_intake_routes_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project that every write adding, deleting or moving intake routes upserts first,\n * inside its transaction. The upsert holds the row until commit, so those writes on one project\n * run one after another and positions stay 0..n-1 with no gaps.\n */\nexport const FACTORY_INTAKE_ROUTE_LOCKS_SCHEMA: CollectionSchema = {\n name: 'factory_intake_route_locks',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n locked_at: { type: 'timestamp' },\n // Keys of the default routes Factory added to the project (`DEFAULT_INTAKE_ROUTES`), so each is\n // added once. Null on rows written before the list: those projects got `outside-authors`.\n seeded_defaults: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_intake_route_locks_project', columns: ['org_id', 'factory_project_id'] }],\n};\n\n/**\n * One row per project whose `version` is replaced inside every board write, so other replicas\n * can tell their cached boards are stale with one indexed read.\n */\nexport const FACTORY_BOARD_DEFINITION_VERSIONS_SCHEMA: CollectionSchema = {\n name: 'factory_board_definition_versions',\n columns: {\n id: { type: 'uuid-pk' },\n org_id: { type: 'text' },\n factory_project_id: { type: 'text' },\n version: { type: 'text' },\n updated_at: { type: 'timestamp' },\n // Keys of the boards Factory stored in the project (Work, app and seed boards); each is stored\n // once, so one the project deleted stays deleted. Null on projects stored before the list.\n seeded_boards: { type: 'json', nullable: true },\n // Keys of the board migrations applied to the project, so each runs once: a field a user\n // later sets back to an old default is never rewritten again. Null before the first one.\n applied_migrations: { type: 'json', nullable: true },\n },\n uniqueIndexes: [{ name: 'factory_board_definition_versions_project', columns: ['org_id', 'factory_project_id'] }],\n};\n"],"mappings":";;AAGA,MAAa,wBAA0C;CACrD,MAAM;CACN,SAAS;EACP,IAAI,EAAE,MAAM,UAAU;EACtB,QAAQ,EAAE,MAAM,OAAO;EACvB,oBAAoB,EAAE,MAAM,OAAO;EACnC,WAAW,EAAE,MAAM,OAAO;EAC1B,MAAM,EAAE,MAAM,OAAO;EACrB,aAAa;GAAE,MAAM;GAAQ,UAAU;EAAK;EAC5C,UAAU,EAAE,MAAM,UAAU;EAE5B,UAAU,EAAE,MAAM,UAAU;EAC5B,YAAY,EAAE,MAAM,OAAO;EAC3B,YAAY,EAAE,MAAM,YAAY;EAChC,YAAY,EAAE,MAAM,OAAO;E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CAcrC;IAEK,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAE7E;IAED,0EAA0E;IACpE,mBAAmB,CAAC,EACxB,KAAK,EACL,gBAAgB,EAChB,MAAM,EACN,MAAM,EACN,KAAK,GACN,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,MAAM,EAAE,MAAM,CAAC;QACf,MAAM,CAAC,EAAE;YAAE,UAAU,EAAE,IAAI,CAAC;YAAC,EAAE,EAAE,MAAM,CAAA;SAAE,CAAC;QAC1C,KAAK,EAAE,MAAM,CAAC;KACf,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAkBhC;IAEK,gBAAgB,CAAC,EACrB,KAAK,EACL,gBAAgB,EAChB,UAAU,GACX,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,MAAM,CAAC,CAUlB;IAED,6EAA6E;IACvE,iBAAiB,CAAC,EACtB,KAAK,EACL,gBAAgB,EAChB,KAAW,GACZ,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC,CAkB7B;CAqCF"}
1
+ {"version":3,"file":"base.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/base.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAAE,oBAAoB,EAAwB,MAAM,sBAAsB,CAAC;AAClF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAG9D,OAAO,KAAK,EAAE,sBAAsB,EAAoB,MAAM,uBAAuB,CAAC;AAStF,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,eAAe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E,MAAM,CAAA;SAAE,CAAC;QAC1C,KAAK,EAAE,MAAM,CAAC;KACf,GAAG,OAAO,CAAC,kBAAkB,EAAE,CAAC,CAkBhC;IAEK,gBAAgB,CAAC,EACrB,KAAK,EACL,gBAAgB,EAChB,UAAU,GACX,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,UAAU,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,MAAM,CAAC,CAUlB;IAED,6EAA6E;IACvE,iBAAiB,CAAC,EACtB,KAAK,EACL,gBAAgB,EAChB,KAAW,GACZ,EAAE;QACD,KAAK,EAAE,MAAM,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,KAAK,CAAC,EAAE,MAAM,CAAC;KAChB,GAAG,OAAO,CAAC,eAAe,EAAE,CAAC,CAkB7B;CAqCF"}
@@ -1,5 +1,5 @@
1
1
  import { externalSourceKey } from "../work-items/base.js";
2
- import { FACTORY_BOARD_VERSIONS_SCHEMA, bumpBoardVersions, trackBoardWrites } from "../work-items/board-version.js";
2
+ import { CARD_TABLES, FACTORY_BOARD_VERSIONS_SCHEMA, bumpBoardVersions, trackBoardWrites } from "../work-items/board-version.js";
3
3
  import { FACTORY_BOARD_ITEMS_SCHEMA } from "../work-items/work-item-schema.js";
4
4
  import { fanOutWorkItemActivity, listActivityForUser } from "./activity.js";
5
5
  import { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA } from "./schema.js";
@@ -152,7 +152,7 @@ var WorkItemCommentsStorage = class extends FactoryStorageDomain {
152
152
  /** Comment counts live on the card, so these writes change the board too. */
153
153
  get ops() {
154
154
  const ops = super.ops;
155
- return trackBoardWrites(ops, (scope) => bumpBoardVersions(ops, [scope]));
155
+ return trackBoardWrites(ops, CARD_TABLES, (scope) => bumpBoardVersions(ops, [scope]));
156
156
  }
157
157
  async dangerouslyClearAll() {
158
158
  await this.ops.deleteMany("work_item_activity", {});
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/comments/base.ts"],"sourcesContent":["/**\n * Work-item comments domain — one message list per work item, materialized\n * from every source. Local creates and platform mirrors (Slack, Linear,\n * GitHub) share one idempotency story: `external_source` json + derived\n * `source_key` under a partial unique index, a local retry token being just\n * another source (`local:comment:<uuid>`).\n *\n * Ordering is caller-settable `occurred_at`, never insert time — ingest\n * backdates to the platform timestamp and retries arrive out of order.\n * Deletes are soft: the tombstone holds the ordering and its kept\n * `source_key` stops a redelivery from resurrecting the row.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { externalSourceKey } from '../work-items/base.js';\nimport type { ExternalWorkItemSource, WorkItemsStorage } from '../work-items/base.js';\nimport { bumpBoardVersions, FACTORY_BOARD_VERSIONS_SCHEMA, trackBoardWrites } from '../work-items/board-version.js';\nimport { FACTORY_BOARD_ITEMS_SCHEMA } from '../work-items/work-item-schema.js';\nimport { fanOutWorkItemActivity, listActivityForUser, PARTICIPANT_SCAN_LIMIT } from './activity.js';\nimport type { WorkItemActivityRow } from './activity.js';\nimport type { FactoryActorExternalIdentity, FactoryActorRef } from './actor.js';\nimport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type { WorkItemActivityRow } from './activity.js';\nexport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type WorkItemCommentKind = 'comment';\n\nexport interface FactoryMentionRef {\n kind: 'user';\n id: string;\n}\n\nexport interface WorkItemCommentReplyRef {\n commentId: string;\n quote?: string;\n authorId?: string;\n authorName?: string;\n}\n\nexport interface WorkItemCommentRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n kind: WorkItemCommentKind;\n body: string;\n bodyFormat: string;\n author: FactoryActorRef;\n replyTo: WorkItemCommentReplyRef | null;\n mentions: FactoryMentionRef[];\n externalSource: ExternalWorkItemSource | null;\n sourceKey: string | null;\n occurredAt: Date;\n editedAt: Date | null;\n deletedAt: Date | null;\n deletedBy: string | null;\n revision: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemCommentInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n author: FactoryActorRef;\n body: string;\n bodyFormat?: string;\n replyTo?: WorkItemCommentReplyRef;\n mentions?: FactoryMentionRef[];\n externalSource?: ExternalWorkItemSource;\n /** Local idempotent-retry token; mutually exclusive with `externalSource`. */\n clientToken?: string;\n occurredAt?: Date;\n}\n\nexport interface EditWorkItemCommentInput {\n orgId: string;\n commentId: string;\n body: string;\n mentions?: FactoryMentionRef[];\n /** The acting user; their own handle never becomes a mention row. */\n editorId?: string;\n /** When set, the edit only lands if the row is still at this revision. */\n expectedRevision?: number;\n now?: Date;\n}\n\nexport interface EditWorkItemCommentResult {\n comment: WorkItemCommentRow;\n addedMentions: FactoryMentionRef[];\n removedMentions: FactoryMentionRef[];\n}\n\nexport interface ListWorkItemCommentsInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n before?: string;\n limit?: number;\n /**\n * Anchor the first page on this comment: it and every comment newer than it,\n * so a deep link opens on the target instead of paging back to find it.\n * Ignored when the comment is gone, or sits further back than one page holds.\n */\n around?: string;\n}\n\n/** The only two work-item columns the feed refresh reads or writes. */\ninterface WorkItemFeedColumns extends Record<string, unknown> {\n comment_count: number;\n feed_activity_at: Date | null;\n}\n\n/** A feed snapshot: how many comments the item had, and when it last moved. */\nexport interface FeedActivitySnapshot {\n commentCount: number;\n feedActivityAt: Date;\n}\n\n/**\n * The refresh reads its snapshot outside the write transaction, so two of them\n * can interleave and the loser can write last. This is the one rule that keeps\n * that from undoing a newer refresh: feed activity never moves backwards, and\n * on the same stamp the fuller count wins.\n *\n * Known ceiling: a soft delete sharing a millisecond with a create leaves the\n * count one high until the next feed mutation recounts. Closing that needs the\n * aggregate read inside the write transaction, which the ops layer cannot do\n * without checking out a second pool connection per open transaction.\n */\nexport function supersedesFeedActivity(next: FeedActivitySnapshot, stored: FeedActivitySnapshot): boolean {\n const drift = next.feedActivityAt.getTime() - stored.feedActivityAt.getTime();\n return drift > 0 || (drift === 0 && next.commentCount >= stored.commentCount);\n}\n\nexport interface WorkItemCommentPage {\n comments: WorkItemCommentRow[];\n nextCursor?: string;\n}\n\nexport interface WorkItemMentionRow {\n id: string;\n commentId: string;\n mentionedKind: 'user';\n mentionedId: string;\n authorId: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n occurredAt: Date;\n}\n\nexport const MAX_COMMENT_BODY_LENGTH = 16_000;\nexport const MAX_COMMENT_QUOTE_LENGTH = 500;\nexport const MAX_COMMENT_MENTIONS = 20;\n\n/** The one body policy: HTTP parsing and the service both reject on it. */\nexport function commentBodyError(body: string): string | undefined {\n if (!body.trim()) return 'Comment body must not be empty.';\n if (body.length > MAX_COMMENT_BODY_LENGTH)\n return `Comment body must be at most ${MAX_COMMENT_BODY_LENGTH} characters.`;\n return undefined;\n}\n\nconst DEFAULT_PAGE_SIZE = 30;\nconst MAX_PAGE_SIZE = 100;\n\nexport function clampCommentLimit(limit: number | undefined): number {\n const normalized = typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : DEFAULT_PAGE_SIZE;\n return Math.min(Math.max(normalized, 1), MAX_PAGE_SIZE);\n}\n\nexport function encodeCommentCursor(row: WorkItemCommentRow): string {\n return `${row.occurredAt.toISOString()}_${row.id}`;\n}\n\nexport function decodeCommentCursor(cursor: string): { occurredAt: Date; id: string } | undefined {\n const sep = cursor.lastIndexOf('_');\n if (sep <= 0) return undefined;\n const occurredAt = new Date(cursor.slice(0, sep));\n const id = cursor.slice(sep + 1);\n if (Number.isNaN(occurredAt.getTime()) || !id) return undefined;\n return { occurredAt, id };\n}\n\nexport function commentSourceKey(input: {\n externalSource?: ExternalWorkItemSource;\n clientToken?: string;\n}): string | null {\n if (input.externalSource) return externalSourceKey(input.externalSource);\n if (input.clientToken) return `local:comment:${input.clientToken}`;\n return null;\n}\n\n/** A `clientToken` replay that resolved to a different work item or author. */\nexport class CommentTokenConflictError extends Error {\n constructor() {\n super('Client token already used by a different comment.');\n this.name = 'CommentTokenConflictError';\n }\n}\n\ninterface WorkItemCommentDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n kind: WorkItemCommentKind;\n body: string;\n body_format: string;\n author_kind: FactoryActorRef['kind'];\n author_id: string;\n author_display_name: string | null;\n author_avatar_url: string | null;\n author_external: FactoryActorExternalIdentity | null;\n reply_to_comment_id: string | null;\n reply_quote: string | null;\n reply_to_author_id: string | null;\n reply_to_author_name: string | null;\n mentions: FactoryMentionRef[];\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n occurred_at: Date;\n edited_at: Date | null;\n deleted_at: Date | null;\n deleted_by: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface WorkItemMentionDbRow extends Record<string, unknown> {\n id: string;\n comment_id: string;\n mentioned_kind: 'user';\n mentioned_id: string;\n author_id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n occurred_at: Date;\n}\n\nfunction toComment(row: WorkItemCommentDbRow): WorkItemCommentRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n kind: row.kind,\n body: row.body,\n bodyFormat: row.body_format,\n author: {\n kind: row.author_kind,\n id: row.author_id,\n ...(row.author_display_name ? { displayName: row.author_display_name } : {}),\n ...(row.author_avatar_url ? { avatarUrl: row.author_avatar_url } : {}),\n ...(row.author_external ? { external: row.author_external } : {}),\n },\n replyTo: row.reply_to_comment_id\n ? {\n commentId: row.reply_to_comment_id,\n ...(row.reply_quote ? { quote: row.reply_quote } : {}),\n ...(row.reply_to_author_id ? { authorId: row.reply_to_author_id } : {}),\n ...(row.reply_to_author_name ? { authorName: row.reply_to_author_name } : {}),\n }\n : null,\n mentions: row.mentions,\n externalSource: row.external_source,\n sourceKey: row.source_key,\n occurredAt: row.occurred_at,\n editedAt: row.edited_at,\n deletedAt: row.deleted_at,\n deletedBy: row.deleted_by,\n revision: row.revision,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toMention(row: WorkItemMentionDbRow): WorkItemMentionRow {\n return {\n id: row.id,\n commentId: row.comment_id,\n mentionedKind: row.mentioned_kind,\n mentionedId: row.mentioned_id,\n authorId: row.author_id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n occurredAt: row.occurred_at,\n };\n}\n\nfunction toMentionRef(row: WorkItemMentionRow): FactoryMentionRef {\n return { kind: row.mentionedKind, id: row.mentionedId };\n}\n\nfunction mentionKey(mention: { kind: string; id: string }): string {\n return `${mention.kind}\\0${mention.id}`;\n}\n\nfunction dedupeMentions(mentions: FactoryMentionRef[] | undefined): FactoryMentionRef[] {\n if (!mentions?.length) return [];\n return [...new Map(mentions.map(mention => [mentionKey(mention), mention])).values()];\n}\n\nexport class WorkItemCommentsStorage extends FactoryStorageDomain {\n get #legacyMode(): boolean {\n return this.storage.hasDomain('work-items') && this.storage.getDomain<WorkItemsStorage>('work-items').legacyMode;\n }\n\n get #boardItemsTable(): string {\n return this.#legacyMode ? 'work_items' : FACTORY_BOARD_ITEMS_SCHEMA.name;\n }\n\n constructor() {\n super('work-item-comments');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n WORK_ITEM_COMMENTS_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_ACTIVITY_SCHEMA,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n ]);\n }\n\n /** Comment counts live on the card, so these writes change the board too. */\n protected override get ops(): FactoryStorageOps {\n const ops = super.ops;\n return trackBoardWrites(ops, scope => bumpBoardVersions(ops, [scope]));\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_item_activity', {});\n await this.ops.deleteMany('work_item_comment_mentions', {});\n await this.ops.deleteMany('work_item_comments', {});\n }\n\n async create(input: CreateWorkItemCommentInput): Promise<WorkItemCommentRow> {\n const now = new Date();\n const occurredAt = input.occurredAt ?? now;\n const sourceKey = commentSourceKey(input);\n const author = input.author;\n const row: Partial<WorkItemCommentDbRow> = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n kind: 'comment',\n body: input.body,\n body_format: input.bodyFormat ?? 'markdown',\n author_kind: author.kind,\n author_id: author.id,\n author_display_name: author.displayName ?? null,\n author_avatar_url: author.avatarUrl ?? null,\n author_external: author.external ?? null,\n reply_to_comment_id: input.replyTo?.commentId ?? null,\n reply_quote: input.replyTo?.quote ?? null,\n reply_to_author_id: input.replyTo?.authorId ?? null,\n reply_to_author_name: input.replyTo?.authorName ?? null,\n mentions: dedupeMentions(input.mentions),\n external_source: input.externalSource ?? null,\n source_key: sourceKey,\n occurred_at: occurredAt,\n edited_at: null,\n deleted_at: null,\n deleted_by: null,\n revision: 1,\n created_at: now,\n updated_at: now,\n };\n\n // Insert-or-recover, never upsert: a replayed create must return the\n // existing row untouched (an upsert would clobber a later edit's body).\n // A local token resolving to another item or author is a conflict, not a\n // recovery. External keys stay lenient: a redelivery after a thread\n // re-link maps to a new item id and must still no-op.\n if (sourceKey) {\n const sourceWhere = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: sourceKey,\n };\n const recover = (found: WorkItemCommentDbRow): WorkItemCommentRow => {\n if (!input.externalSource && (found.work_item_id !== input.workItemId || found.author_id !== author.id)) {\n throw new CommentTokenConflictError();\n }\n return toComment(found);\n };\n const existing = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (existing) return recover(existing);\n try {\n return await this.#insertWithMentions(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const raced = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (!raced) throw error;\n return recover(raced);\n }\n }\n\n return this.#insertWithMentions(row);\n }\n\n /**\n * The one insert path a genuinely new comment takes — `create()`'s recover\n * branches never reach it, so a replay writes no mention or activity rows.\n */\n async #insertWithMentions(row: Partial<WorkItemCommentDbRow>): Promise<WorkItemCommentRow> {\n const comment = toComment(await this.ops.insertOne<WorkItemCommentDbRow>('work_item_comments', row));\n await this.#writeMentionRows(comment, comment.mentions);\n await this.#fanOutActivity(comment);\n return comment;\n }\n\n /**\n * Participants come off the item's recent authors, so the scan happens here\n * rather than in the fan-out, which must stay free of its own queries.\n */\n async #fanOutActivity(comment: WorkItemCommentRow): Promise<void> {\n const item = await this.ops.findOne<{ created_by: string } & Record<string, unknown>>(this.#boardItemsTable, {\n id: comment.workItemId,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n });\n if (!item) return;\n const recent = await this.listRecent({\n orgId: comment.orgId,\n factoryProjectId: comment.factoryProjectId,\n workItemId: comment.workItemId,\n limit: PARTICIPANT_SCAN_LIMIT,\n });\n await fanOutWorkItemActivity(this.ops, {\n comment,\n recentAuthors: recent.filter(row => row.author.kind === 'user').map(row => row.author.id),\n createdBy: item.created_by,\n mentions: comment.mentions,\n });\n }\n\n async listActivityForUser(args: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemActivityRow[]> {\n return listActivityForUser(this.ops, args);\n }\n\n /**\n * Idempotent counter refresh on the parent work item: both columns are read\n * back off the comments (never incremented or stamped with the wall clock —\n * replays and races double an increment, and a replayed create would move a\n * work item in the feed without adding a comment; a read-back can't drift).\n * Read BEFORE `updateAtomic`: its mutator runs inside an open transaction\n * holding a pool connection, and a query in there checks out a second one —\n * concurrent posts would exhaust the pool. Reading outside means two\n * refreshes can interleave, so the write goes through\n * {@link supersedesFeedActivity} rather than landing whatever it read.\n * Touches ONLY the counter columns: `revision`/`updated_at` are the\n * stage-transition concurrency token.\n */\n async refreshWorkItemFeedActivity({\n orgId,\n factoryProjectId,\n workItemId,\n now = new Date(),\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n now?: Date;\n }): Promise<void> {\n // Every feed mutation stamps `updated_at`, edits and tombstones included,\n // so the newest one is when this feed last moved.\n const [latest] = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n { orderBy: [['updated_at', 'desc']], limit: 1 },\n );\n const feedActivityAt = latest?.updated_at ?? now;\n // Capture the clock before counting: a paused old count must not borrow a\n // later deletion's clock and supersede its newer, smaller recount.\n const commentCount = await this.countForWorkItem({ orgId, factoryProjectId, workItemId });\n await this.ops.updateAtomic<WorkItemFeedColumns>(\n this.#boardItemsTable,\n { id: workItemId, org_id: orgId, factory_project_id: factoryProjectId },\n row => {\n const next = { commentCount, feedActivityAt };\n const stored = row.feed_activity_at;\n if (stored && !supersedesFeedActivity(next, { commentCount: row.comment_count, feedActivityAt: stored })) {\n return null;\n }\n return { comment_count: commentCount, feed_activity_at: feedActivityAt };\n },\n );\n }\n\n async get({ orgId, commentId }: { orgId: string; commentId: string }): Promise<WorkItemCommentRow | null> {\n const row = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', {\n id: commentId,\n org_id: orgId,\n });\n return row ? toComment(row) : null;\n }\n\n async listByIds({ orgId, ids }: { orgId: string; ids: string[] }): Promise<WorkItemCommentRow[]> {\n if (ids.length === 0) return [];\n const rows = await this.ops.findMany<WorkItemCommentDbRow>('work_item_comments', {\n org_id: orgId,\n id: { in: ids },\n });\n return rows.map(toComment);\n }\n\n async list(input: ListWorkItemCommentsInput): Promise<WorkItemCommentPage> {\n const anchored = input.around ? await this.#listAround(input, input.around) : undefined;\n if (anchored) return anchored;\n const limit = clampCommentLimit(input.limit);\n const cursor = input.before ? decodeCommentCursor(input.before) : undefined;\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: limit + 1,\n ...(cursor ? { cursor: { values: [cursor.occurredAt, cursor.id] } } : {}),\n },\n );\n const comments = rows.slice(0, limit).map(toComment);\n const hasMore = rows.length > limit;\n const last = comments[comments.length - 1];\n return {\n comments,\n ...(hasMore && last ? { nextCursor: encodeCommentCursor(last) } : {}),\n };\n }\n\n async #listAround(\n { orgId, factoryProjectId, workItemId }: ListWorkItemCommentsInput,\n commentId: string,\n ): Promise<WorkItemCommentPage | undefined> {\n const target = await this.get({ orgId, commentId });\n if (!target || target.factoryProjectId !== factoryProjectId || target.workItemId !== workItemId) return undefined;\n\n const newer = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n {\n orderBy: [\n ['occurred_at', 'asc'],\n ['id', 'asc'],\n ],\n limit: MAX_PAGE_SIZE + 1,\n cursor: { values: [target.occurredAt, target.id] },\n },\n );\n if (newer.length > MAX_PAGE_SIZE) return undefined;\n\n const before = encodeCommentCursor(target);\n const older = await this.list({ orgId, factoryProjectId, workItemId, before, limit: 1 });\n return {\n comments: [...newer.map(toComment).reverse(), target],\n ...(older.comments.length > 0 ? { nextCursor: before } : {}),\n };\n }\n\n /**\n * Newest non-deleted comments for run-context injection, newest-first (the\n * caller reverses for display order).\n */\n async listRecent({\n orgId,\n factoryProjectId,\n workItemId,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n limit: number;\n }): Promise<WorkItemCommentRow[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n return rows.map(toComment);\n }\n\n async edit(input: EditWorkItemCommentInput): Promise<EditWorkItemCommentResult | 'conflict' | null> {\n const now = input.now ?? new Date();\n let rejection: 'deleted' | 'conflict' | undefined;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: input.commentId, org_id: input.orgId },\n current => {\n if (current.deleted_at) {\n rejection = 'deleted';\n return null;\n }\n if (input.expectedRevision !== undefined && Number(current.revision) !== input.expectedRevision) {\n rejection = 'conflict';\n return null;\n }\n return {\n body: input.body,\n mentions: dedupeMentions(input.mentions ?? current.mentions),\n edited_at: now,\n revision: Number(current.revision) + 1,\n updated_at: now,\n };\n },\n );\n if (rejection === 'conflict') return 'conflict';\n if (!updated || rejection) return null;\n const comment = toComment(updated);\n\n const existing = await this.#listMentionRows(comment.id);\n const existingKeys = new Set(existing.map(mention => mentionKey(toMentionRef(mention))));\n const nextKeys = new Set(comment.mentions.map(mentionKey));\n // Self-mentions (author, or the acting editor) never become rows, so they\n // must not report as \"added\" either — they would re-report on every edit.\n const skippedIds = new Set([comment.author.id, ...(input.editorId ? [input.editorId] : [])]);\n const addedMentions = comment.mentions.filter(\n mention => !existingKeys.has(mentionKey(mention)) && !skippedIds.has(mention.id),\n );\n const removedMentions = existing.map(toMentionRef).filter(mention => !nextKeys.has(mentionKey(mention)));\n\n // Stamped with the edit time, not the comment's creation time: the inbox\n // is a keyset on `occurred_at`, and a backdated row lands buried under\n // everything the user already saw.\n await this.#writeMentionRows(comment, addedMentions, now);\n for (const mention of removedMentions) {\n await this.ops.deleteMany('work_item_comment_mentions', {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n });\n }\n return { comment, addedMentions, removedMentions };\n }\n\n async softDelete({\n orgId,\n commentId,\n deletedBy,\n now = new Date(),\n }: {\n orgId: string;\n commentId: string;\n deletedBy: string;\n now?: Date;\n }): Promise<WorkItemCommentRow | null> {\n let alreadyDeleted = false;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.deleted_at) {\n alreadyDeleted = true;\n return null;\n }\n return {\n body: '',\n mentions: [],\n deleted_at: now,\n deleted_by: deletedBy,\n updated_at: now,\n };\n },\n );\n if (!updated || alreadyDeleted) return null;\n await this.ops.deleteMany('work_item_comment_mentions', { comment_id: commentId });\n return toComment(updated);\n }\n\n /**\n * Provenance write-back after an outbound publish. First platform wins, and\n * an existing `source_key` is kept: replacing a `local:comment:<token>` one\n * would let a client retry duplicate the row. So a web-born comment is never\n * key-deduped against its own platform echo — the host's bot-sender check is\n * the only echo layer for those rows (COR-1174).\n */\n async attachExternalSource({\n orgId,\n commentId,\n source,\n }: {\n orgId: string;\n commentId: string;\n source: ExternalWorkItemSource;\n }): Promise<WorkItemCommentRow | null> {\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.external_source) return null;\n return {\n external_source: source,\n source_key: current.source_key ?? commentSourceKey({ externalSource: source }),\n updated_at: new Date(),\n };\n },\n );\n return updated ? toComment(updated) : null;\n }\n\n async listMentionsForComment(commentId: string): Promise<WorkItemMentionRow[]> {\n return this.#listMentionRows(commentId);\n }\n\n /** Keyset inbox read for the mention attention provider, newest-first. */\n async listMentionsForUser({\n orgId,\n factoryProjectId,\n userId,\n before,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n mentioned_id: userId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n ...(before ? { cursor: { values: [before.occurredAt, before.id] } } : {}),\n },\n );\n return rows.map(toMention);\n }\n\n async countForWorkItem({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n }): Promise<number> {\n if (!this.ops.count) {\n throw new Error('[WorkItemCommentsStorage] storage backend does not support collection counts.');\n }\n return this.ops.count('work_item_comments', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n });\n }\n\n /** Recent distinct comment authors of a project, for the roster fallback. */\n async listRecentAuthors({\n orgId,\n factoryProjectId,\n limit = 200,\n }: {\n orgId: string;\n factoryProjectId: string;\n limit?: number;\n }): Promise<FactoryActorRef[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n const authors = new Map<string, FactoryActorRef>();\n for (const row of rows) {\n if (authors.has(row.author_id)) continue;\n authors.set(row.author_id, toComment(row).author);\n }\n return [...authors.values()];\n }\n\n async #listMentionRows(commentId: string): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>('work_item_comment_mentions', {\n comment_id: commentId,\n });\n return rows.map(toMention);\n }\n\n /**\n * Self-mentions never get rows: the join exists solely for the attention\n * inbox, and `CollectionWhere` cannot express `author_id != userId` at read\n * time, so the filter happens at write time.\n */\n async #writeMentionRows(\n comment: WorkItemCommentRow,\n mentions: FactoryMentionRef[],\n occurredAt = comment.occurredAt,\n ): Promise<void> {\n for (const mention of mentions) {\n if (mention.id === comment.author.id) continue;\n await this.ops.upsertOne<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n ['comment_id', 'mentioned_kind', 'mentioned_id'],\n {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n author_id: comment.author.id,\n org_id: comment.orgId,\n factory_project_id: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tB,OACA,kBACA,QAAQ,OAKqB;EAC7B,MAAM,OAAO,MAAM,KAAK,IAAI,SAC1B,sBACA;GAAE,QAAQ;GAAO,oBAAoB;EAAiB,GACtD;GACE,SAAS,CACP,CAAC,eAAe,MAAM,GACtB,CAAC,MAAM,MAAM,CACf;GACA;EACF,CACF;EACA,MAAM,0BAAU,IAAI,IAA6B;EACjD,KAAK,MAAM,OAAO,MAAM;GACtB,IAAI,QAAQ,IAAI,IAAI,SAAS,GAAG;GAChC,QAAQ,IAAI,IAAI,WAAW,UAAU,GAAG,CAAC,CAAC,MAAM;EAClD;EACA,OAAO,CAAC,GAAG,QAAQ,OAAO,CAAC;CAC7B;CAEA,MAAM,iBAAiB,WAAkD;EAIvE,QAAO,MAHY,KAAK,IAAI,SAA+B,8BAA8B,EACvF,YAAY,UACd,CAAC,EAAA,CACW,IAAI,SAAS;CAC3B;;;;;;CAOA,MAAM,kBACJ,SACA,UACA,aAAa,QAAQ,YACN;EACf,KAAK,MAAM,WAAW,UAAU;GAC9B,IAAI,QAAQ,OAAO,QAAQ,OAAO,IAAI;GACtC,MAAM,KAAK,IAAI,UACb,8BACA;IAAC;IAAc;IAAkB;GAAc,GAC/C;IACE,YAAY,QAAQ;IACpB,gBAAgB,QAAQ;IACxB,cAAc,QAAQ;IACtB,WAAW,QAAQ,OAAO;IAC1B,QAAQ,QAAQ;IAChB,oBAAoB,QAAQ;IAC5B,cAAc,QAAQ;IACtB,aAAa;GACf,CACF;EACF;CACF;AACF"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../../../src/storage/domains/comments/base.ts"],"sourcesContent":["/**\n * Work-item comments domain — one message list per work item, materialized\n * from every source. Local creates and platform mirrors (Slack, Linear,\n * GitHub) share one idempotency story: `external_source` json + derived\n * `source_key` under a partial unique index, a local retry token being just\n * another source (`local:comment:<uuid>`).\n *\n * Ordering is caller-settable `occurred_at`, never insert time — ingest\n * backdates to the platform timestamp and retries arrive out of order.\n * Deletes are soft: the tombstone holds the ordering and its kept\n * `source_key` stops a redelivery from resurrecting the row.\n */\n\nimport { FactoryStorageDomain, UniqueViolationError } from '@mastra/core/storage';\nimport type { FactoryStorageOps } from '@mastra/core/storage';\n\nimport { externalSourceKey } from '../work-items/base.js';\nimport type { ExternalWorkItemSource, WorkItemsStorage } from '../work-items/base.js';\nimport {\n bumpBoardVersions,\n CARD_TABLES,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n trackBoardWrites,\n} from '../work-items/board-version.js';\nimport { FACTORY_BOARD_ITEMS_SCHEMA } from '../work-items/work-item-schema.js';\nimport { fanOutWorkItemActivity, listActivityForUser, PARTICIPANT_SCAN_LIMIT } from './activity.js';\nimport type { WorkItemActivityRow } from './activity.js';\nimport type { FactoryActorExternalIdentity, FactoryActorRef } from './actor.js';\nimport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type { WorkItemActivityRow } from './activity.js';\nexport { WORK_ITEM_ACTIVITY_SCHEMA, WORK_ITEM_COMMENT_MENTIONS_SCHEMA, WORK_ITEM_COMMENTS_SCHEMA } from './schema.js';\n\nexport type WorkItemCommentKind = 'comment';\n\nexport interface FactoryMentionRef {\n kind: 'user';\n id: string;\n}\n\nexport interface WorkItemCommentReplyRef {\n commentId: string;\n quote?: string;\n authorId?: string;\n authorName?: string;\n}\n\nexport interface WorkItemCommentRow {\n id: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n kind: WorkItemCommentKind;\n body: string;\n bodyFormat: string;\n author: FactoryActorRef;\n replyTo: WorkItemCommentReplyRef | null;\n mentions: FactoryMentionRef[];\n externalSource: ExternalWorkItemSource | null;\n sourceKey: string | null;\n occurredAt: Date;\n editedAt: Date | null;\n deletedAt: Date | null;\n deletedBy: string | null;\n revision: number;\n createdAt: Date;\n updatedAt: Date;\n}\n\nexport interface CreateWorkItemCommentInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n author: FactoryActorRef;\n body: string;\n bodyFormat?: string;\n replyTo?: WorkItemCommentReplyRef;\n mentions?: FactoryMentionRef[];\n externalSource?: ExternalWorkItemSource;\n /** Local idempotent-retry token; mutually exclusive with `externalSource`. */\n clientToken?: string;\n occurredAt?: Date;\n}\n\nexport interface EditWorkItemCommentInput {\n orgId: string;\n commentId: string;\n body: string;\n mentions?: FactoryMentionRef[];\n /** The acting user; their own handle never becomes a mention row. */\n editorId?: string;\n /** When set, the edit only lands if the row is still at this revision. */\n expectedRevision?: number;\n now?: Date;\n}\n\nexport interface EditWorkItemCommentResult {\n comment: WorkItemCommentRow;\n addedMentions: FactoryMentionRef[];\n removedMentions: FactoryMentionRef[];\n}\n\nexport interface ListWorkItemCommentsInput {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n before?: string;\n limit?: number;\n /**\n * Anchor the first page on this comment: it and every comment newer than it,\n * so a deep link opens on the target instead of paging back to find it.\n * Ignored when the comment is gone, or sits further back than one page holds.\n */\n around?: string;\n}\n\n/** The only two work-item columns the feed refresh reads or writes. */\ninterface WorkItemFeedColumns extends Record<string, unknown> {\n comment_count: number;\n feed_activity_at: Date | null;\n}\n\n/** A feed snapshot: how many comments the item had, and when it last moved. */\nexport interface FeedActivitySnapshot {\n commentCount: number;\n feedActivityAt: Date;\n}\n\n/**\n * The refresh reads its snapshot outside the write transaction, so two of them\n * can interleave and the loser can write last. This is the one rule that keeps\n * that from undoing a newer refresh: feed activity never moves backwards, and\n * on the same stamp the fuller count wins.\n *\n * Known ceiling: a soft delete sharing a millisecond with a create leaves the\n * count one high until the next feed mutation recounts. Closing that needs the\n * aggregate read inside the write transaction, which the ops layer cannot do\n * without checking out a second pool connection per open transaction.\n */\nexport function supersedesFeedActivity(next: FeedActivitySnapshot, stored: FeedActivitySnapshot): boolean {\n const drift = next.feedActivityAt.getTime() - stored.feedActivityAt.getTime();\n return drift > 0 || (drift === 0 && next.commentCount >= stored.commentCount);\n}\n\nexport interface WorkItemCommentPage {\n comments: WorkItemCommentRow[];\n nextCursor?: string;\n}\n\nexport interface WorkItemMentionRow {\n id: string;\n commentId: string;\n mentionedKind: 'user';\n mentionedId: string;\n authorId: string;\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n occurredAt: Date;\n}\n\nexport const MAX_COMMENT_BODY_LENGTH = 16_000;\nexport const MAX_COMMENT_QUOTE_LENGTH = 500;\nexport const MAX_COMMENT_MENTIONS = 20;\n\n/** The one body policy: HTTP parsing and the service both reject on it. */\nexport function commentBodyError(body: string): string | undefined {\n if (!body.trim()) return 'Comment body must not be empty.';\n if (body.length > MAX_COMMENT_BODY_LENGTH)\n return `Comment body must be at most ${MAX_COMMENT_BODY_LENGTH} characters.`;\n return undefined;\n}\n\nconst DEFAULT_PAGE_SIZE = 30;\nconst MAX_PAGE_SIZE = 100;\n\nexport function clampCommentLimit(limit: number | undefined): number {\n const normalized = typeof limit === 'number' && Number.isFinite(limit) ? Math.trunc(limit) : DEFAULT_PAGE_SIZE;\n return Math.min(Math.max(normalized, 1), MAX_PAGE_SIZE);\n}\n\nexport function encodeCommentCursor(row: WorkItemCommentRow): string {\n return `${row.occurredAt.toISOString()}_${row.id}`;\n}\n\nexport function decodeCommentCursor(cursor: string): { occurredAt: Date; id: string } | undefined {\n const sep = cursor.lastIndexOf('_');\n if (sep <= 0) return undefined;\n const occurredAt = new Date(cursor.slice(0, sep));\n const id = cursor.slice(sep + 1);\n if (Number.isNaN(occurredAt.getTime()) || !id) return undefined;\n return { occurredAt, id };\n}\n\nexport function commentSourceKey(input: {\n externalSource?: ExternalWorkItemSource;\n clientToken?: string;\n}): string | null {\n if (input.externalSource) return externalSourceKey(input.externalSource);\n if (input.clientToken) return `local:comment:${input.clientToken}`;\n return null;\n}\n\n/** A `clientToken` replay that resolved to a different work item or author. */\nexport class CommentTokenConflictError extends Error {\n constructor() {\n super('Client token already used by a different comment.');\n this.name = 'CommentTokenConflictError';\n }\n}\n\ninterface WorkItemCommentDbRow extends Record<string, unknown> {\n id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n kind: WorkItemCommentKind;\n body: string;\n body_format: string;\n author_kind: FactoryActorRef['kind'];\n author_id: string;\n author_display_name: string | null;\n author_avatar_url: string | null;\n author_external: FactoryActorExternalIdentity | null;\n reply_to_comment_id: string | null;\n reply_quote: string | null;\n reply_to_author_id: string | null;\n reply_to_author_name: string | null;\n mentions: FactoryMentionRef[];\n external_source: ExternalWorkItemSource | null;\n source_key: string | null;\n occurred_at: Date;\n edited_at: Date | null;\n deleted_at: Date | null;\n deleted_by: string | null;\n revision: number;\n created_at: Date;\n updated_at: Date;\n}\n\ninterface WorkItemMentionDbRow extends Record<string, unknown> {\n id: string;\n comment_id: string;\n mentioned_kind: 'user';\n mentioned_id: string;\n author_id: string;\n org_id: string;\n factory_project_id: string;\n work_item_id: string;\n occurred_at: Date;\n}\n\nfunction toComment(row: WorkItemCommentDbRow): WorkItemCommentRow {\n return {\n id: row.id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n kind: row.kind,\n body: row.body,\n bodyFormat: row.body_format,\n author: {\n kind: row.author_kind,\n id: row.author_id,\n ...(row.author_display_name ? { displayName: row.author_display_name } : {}),\n ...(row.author_avatar_url ? { avatarUrl: row.author_avatar_url } : {}),\n ...(row.author_external ? { external: row.author_external } : {}),\n },\n replyTo: row.reply_to_comment_id\n ? {\n commentId: row.reply_to_comment_id,\n ...(row.reply_quote ? { quote: row.reply_quote } : {}),\n ...(row.reply_to_author_id ? { authorId: row.reply_to_author_id } : {}),\n ...(row.reply_to_author_name ? { authorName: row.reply_to_author_name } : {}),\n }\n : null,\n mentions: row.mentions,\n externalSource: row.external_source,\n sourceKey: row.source_key,\n occurredAt: row.occurred_at,\n editedAt: row.edited_at,\n deletedAt: row.deleted_at,\n deletedBy: row.deleted_by,\n revision: row.revision,\n createdAt: row.created_at,\n updatedAt: row.updated_at,\n };\n}\n\nfunction toMention(row: WorkItemMentionDbRow): WorkItemMentionRow {\n return {\n id: row.id,\n commentId: row.comment_id,\n mentionedKind: row.mentioned_kind,\n mentionedId: row.mentioned_id,\n authorId: row.author_id,\n orgId: row.org_id,\n factoryProjectId: row.factory_project_id,\n workItemId: row.work_item_id,\n occurredAt: row.occurred_at,\n };\n}\n\nfunction toMentionRef(row: WorkItemMentionRow): FactoryMentionRef {\n return { kind: row.mentionedKind, id: row.mentionedId };\n}\n\nfunction mentionKey(mention: { kind: string; id: string }): string {\n return `${mention.kind}\\0${mention.id}`;\n}\n\nfunction dedupeMentions(mentions: FactoryMentionRef[] | undefined): FactoryMentionRef[] {\n if (!mentions?.length) return [];\n return [...new Map(mentions.map(mention => [mentionKey(mention), mention])).values()];\n}\n\nexport class WorkItemCommentsStorage extends FactoryStorageDomain {\n get #legacyMode(): boolean {\n return this.storage.hasDomain('work-items') && this.storage.getDomain<WorkItemsStorage>('work-items').legacyMode;\n }\n\n get #boardItemsTable(): string {\n return this.#legacyMode ? 'work_items' : FACTORY_BOARD_ITEMS_SCHEMA.name;\n }\n\n constructor() {\n super('work-item-comments');\n }\n\n async init(): Promise<void> {\n await this.ensureCollections([\n WORK_ITEM_COMMENTS_SCHEMA,\n WORK_ITEM_COMMENT_MENTIONS_SCHEMA,\n WORK_ITEM_ACTIVITY_SCHEMA,\n FACTORY_BOARD_VERSIONS_SCHEMA,\n ]);\n }\n\n /** Comment counts live on the card, so these writes change the board too. */\n protected override get ops(): FactoryStorageOps {\n const ops = super.ops;\n return trackBoardWrites(ops, CARD_TABLES, scope => bumpBoardVersions(ops, [scope]));\n }\n\n async dangerouslyClearAll(): Promise<void> {\n await this.ops.deleteMany('work_item_activity', {});\n await this.ops.deleteMany('work_item_comment_mentions', {});\n await this.ops.deleteMany('work_item_comments', {});\n }\n\n async create(input: CreateWorkItemCommentInput): Promise<WorkItemCommentRow> {\n const now = new Date();\n const occurredAt = input.occurredAt ?? now;\n const sourceKey = commentSourceKey(input);\n const author = input.author;\n const row: Partial<WorkItemCommentDbRow> = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n kind: 'comment',\n body: input.body,\n body_format: input.bodyFormat ?? 'markdown',\n author_kind: author.kind,\n author_id: author.id,\n author_display_name: author.displayName ?? null,\n author_avatar_url: author.avatarUrl ?? null,\n author_external: author.external ?? null,\n reply_to_comment_id: input.replyTo?.commentId ?? null,\n reply_quote: input.replyTo?.quote ?? null,\n reply_to_author_id: input.replyTo?.authorId ?? null,\n reply_to_author_name: input.replyTo?.authorName ?? null,\n mentions: dedupeMentions(input.mentions),\n external_source: input.externalSource ?? null,\n source_key: sourceKey,\n occurred_at: occurredAt,\n edited_at: null,\n deleted_at: null,\n deleted_by: null,\n revision: 1,\n created_at: now,\n updated_at: now,\n };\n\n // Insert-or-recover, never upsert: a replayed create must return the\n // existing row untouched (an upsert would clobber a later edit's body).\n // A local token resolving to another item or author is a conflict, not a\n // recovery. External keys stay lenient: a redelivery after a thread\n // re-link maps to a new item id and must still no-op.\n if (sourceKey) {\n const sourceWhere = {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n source_key: sourceKey,\n };\n const recover = (found: WorkItemCommentDbRow): WorkItemCommentRow => {\n if (!input.externalSource && (found.work_item_id !== input.workItemId || found.author_id !== author.id)) {\n throw new CommentTokenConflictError();\n }\n return toComment(found);\n };\n const existing = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (existing) return recover(existing);\n try {\n return await this.#insertWithMentions(row);\n } catch (error) {\n if (!(error instanceof UniqueViolationError)) throw error;\n const raced = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', sourceWhere);\n if (!raced) throw error;\n return recover(raced);\n }\n }\n\n return this.#insertWithMentions(row);\n }\n\n /**\n * The one insert path a genuinely new comment takes — `create()`'s recover\n * branches never reach it, so a replay writes no mention or activity rows.\n */\n async #insertWithMentions(row: Partial<WorkItemCommentDbRow>): Promise<WorkItemCommentRow> {\n const comment = toComment(await this.ops.insertOne<WorkItemCommentDbRow>('work_item_comments', row));\n await this.#writeMentionRows(comment, comment.mentions);\n await this.#fanOutActivity(comment);\n return comment;\n }\n\n /**\n * Participants come off the item's recent authors, so the scan happens here\n * rather than in the fan-out, which must stay free of its own queries.\n */\n async #fanOutActivity(comment: WorkItemCommentRow): Promise<void> {\n const item = await this.ops.findOne<{ created_by: string } & Record<string, unknown>>(this.#boardItemsTable, {\n id: comment.workItemId,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n });\n if (!item) return;\n const recent = await this.listRecent({\n orgId: comment.orgId,\n factoryProjectId: comment.factoryProjectId,\n workItemId: comment.workItemId,\n limit: PARTICIPANT_SCAN_LIMIT,\n });\n await fanOutWorkItemActivity(this.ops, {\n comment,\n recentAuthors: recent.filter(row => row.author.kind === 'user').map(row => row.author.id),\n createdBy: item.created_by,\n mentions: comment.mentions,\n });\n }\n\n async listActivityForUser(args: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemActivityRow[]> {\n return listActivityForUser(this.ops, args);\n }\n\n /**\n * Idempotent counter refresh on the parent work item: both columns are read\n * back off the comments (never incremented or stamped with the wall clock —\n * replays and races double an increment, and a replayed create would move a\n * work item in the feed without adding a comment; a read-back can't drift).\n * Read BEFORE `updateAtomic`: its mutator runs inside an open transaction\n * holding a pool connection, and a query in there checks out a second one —\n * concurrent posts would exhaust the pool. Reading outside means two\n * refreshes can interleave, so the write goes through\n * {@link supersedesFeedActivity} rather than landing whatever it read.\n * Touches ONLY the counter columns: `revision`/`updated_at` are the\n * stage-transition concurrency token.\n */\n async refreshWorkItemFeedActivity({\n orgId,\n factoryProjectId,\n workItemId,\n now = new Date(),\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n now?: Date;\n }): Promise<void> {\n // Every feed mutation stamps `updated_at`, edits and tombstones included,\n // so the newest one is when this feed last moved.\n const [latest] = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n { orderBy: [['updated_at', 'desc']], limit: 1 },\n );\n const feedActivityAt = latest?.updated_at ?? now;\n // Capture the clock before counting: a paused old count must not borrow a\n // later deletion's clock and supersede its newer, smaller recount.\n const commentCount = await this.countForWorkItem({ orgId, factoryProjectId, workItemId });\n await this.ops.updateAtomic<WorkItemFeedColumns>(\n this.#boardItemsTable,\n { id: workItemId, org_id: orgId, factory_project_id: factoryProjectId },\n row => {\n const next = { commentCount, feedActivityAt };\n const stored = row.feed_activity_at;\n if (stored && !supersedesFeedActivity(next, { commentCount: row.comment_count, feedActivityAt: stored })) {\n return null;\n }\n return { comment_count: commentCount, feed_activity_at: feedActivityAt };\n },\n );\n }\n\n async get({ orgId, commentId }: { orgId: string; commentId: string }): Promise<WorkItemCommentRow | null> {\n const row = await this.ops.findOne<WorkItemCommentDbRow>('work_item_comments', {\n id: commentId,\n org_id: orgId,\n });\n return row ? toComment(row) : null;\n }\n\n async listByIds({ orgId, ids }: { orgId: string; ids: string[] }): Promise<WorkItemCommentRow[]> {\n if (ids.length === 0) return [];\n const rows = await this.ops.findMany<WorkItemCommentDbRow>('work_item_comments', {\n org_id: orgId,\n id: { in: ids },\n });\n return rows.map(toComment);\n }\n\n async list(input: ListWorkItemCommentsInput): Promise<WorkItemCommentPage> {\n const anchored = input.around ? await this.#listAround(input, input.around) : undefined;\n if (anchored) return anchored;\n const limit = clampCommentLimit(input.limit);\n const cursor = input.before ? decodeCommentCursor(input.before) : undefined;\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: input.orgId,\n factory_project_id: input.factoryProjectId,\n work_item_id: input.workItemId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit: limit + 1,\n ...(cursor ? { cursor: { values: [cursor.occurredAt, cursor.id] } } : {}),\n },\n );\n const comments = rows.slice(0, limit).map(toComment);\n const hasMore = rows.length > limit;\n const last = comments[comments.length - 1];\n return {\n comments,\n ...(hasMore && last ? { nextCursor: encodeCommentCursor(last) } : {}),\n };\n }\n\n async #listAround(\n { orgId, factoryProjectId, workItemId }: ListWorkItemCommentsInput,\n commentId: string,\n ): Promise<WorkItemCommentPage | undefined> {\n const target = await this.get({ orgId, commentId });\n if (!target || target.factoryProjectId !== factoryProjectId || target.workItemId !== workItemId) return undefined;\n\n const newer = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId, work_item_id: workItemId },\n {\n orderBy: [\n ['occurred_at', 'asc'],\n ['id', 'asc'],\n ],\n limit: MAX_PAGE_SIZE + 1,\n cursor: { values: [target.occurredAt, target.id] },\n },\n );\n if (newer.length > MAX_PAGE_SIZE) return undefined;\n\n const before = encodeCommentCursor(target);\n const older = await this.list({ orgId, factoryProjectId, workItemId, before, limit: 1 });\n return {\n comments: [...newer.map(toComment).reverse(), target],\n ...(older.comments.length > 0 ? { nextCursor: before } : {}),\n };\n }\n\n /**\n * Newest non-deleted comments for run-context injection, newest-first (the\n * caller reverses for display order).\n */\n async listRecent({\n orgId,\n factoryProjectId,\n workItemId,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n limit: number;\n }): Promise<WorkItemCommentRow[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n return rows.map(toComment);\n }\n\n async edit(input: EditWorkItemCommentInput): Promise<EditWorkItemCommentResult | 'conflict' | null> {\n const now = input.now ?? new Date();\n let rejection: 'deleted' | 'conflict' | undefined;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: input.commentId, org_id: input.orgId },\n current => {\n if (current.deleted_at) {\n rejection = 'deleted';\n return null;\n }\n if (input.expectedRevision !== undefined && Number(current.revision) !== input.expectedRevision) {\n rejection = 'conflict';\n return null;\n }\n return {\n body: input.body,\n mentions: dedupeMentions(input.mentions ?? current.mentions),\n edited_at: now,\n revision: Number(current.revision) + 1,\n updated_at: now,\n };\n },\n );\n if (rejection === 'conflict') return 'conflict';\n if (!updated || rejection) return null;\n const comment = toComment(updated);\n\n const existing = await this.#listMentionRows(comment.id);\n const existingKeys = new Set(existing.map(mention => mentionKey(toMentionRef(mention))));\n const nextKeys = new Set(comment.mentions.map(mentionKey));\n // Self-mentions (author, or the acting editor) never become rows, so they\n // must not report as \"added\" either — they would re-report on every edit.\n const skippedIds = new Set([comment.author.id, ...(input.editorId ? [input.editorId] : [])]);\n const addedMentions = comment.mentions.filter(\n mention => !existingKeys.has(mentionKey(mention)) && !skippedIds.has(mention.id),\n );\n const removedMentions = existing.map(toMentionRef).filter(mention => !nextKeys.has(mentionKey(mention)));\n\n // Stamped with the edit time, not the comment's creation time: the inbox\n // is a keyset on `occurred_at`, and a backdated row lands buried under\n // everything the user already saw.\n await this.#writeMentionRows(comment, addedMentions, now);\n for (const mention of removedMentions) {\n await this.ops.deleteMany('work_item_comment_mentions', {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n });\n }\n return { comment, addedMentions, removedMentions };\n }\n\n async softDelete({\n orgId,\n commentId,\n deletedBy,\n now = new Date(),\n }: {\n orgId: string;\n commentId: string;\n deletedBy: string;\n now?: Date;\n }): Promise<WorkItemCommentRow | null> {\n let alreadyDeleted = false;\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.deleted_at) {\n alreadyDeleted = true;\n return null;\n }\n return {\n body: '',\n mentions: [],\n deleted_at: now,\n deleted_by: deletedBy,\n updated_at: now,\n };\n },\n );\n if (!updated || alreadyDeleted) return null;\n await this.ops.deleteMany('work_item_comment_mentions', { comment_id: commentId });\n return toComment(updated);\n }\n\n /**\n * Provenance write-back after an outbound publish. First platform wins, and\n * an existing `source_key` is kept: replacing a `local:comment:<token>` one\n * would let a client retry duplicate the row. So a web-born comment is never\n * key-deduped against its own platform echo — the host's bot-sender check is\n * the only echo layer for those rows (COR-1174).\n */\n async attachExternalSource({\n orgId,\n commentId,\n source,\n }: {\n orgId: string;\n commentId: string;\n source: ExternalWorkItemSource;\n }): Promise<WorkItemCommentRow | null> {\n const updated = await this.ops.updateAtomic<WorkItemCommentDbRow>(\n 'work_item_comments',\n { id: commentId, org_id: orgId },\n current => {\n if (current.external_source) return null;\n return {\n external_source: source,\n source_key: current.source_key ?? commentSourceKey({ externalSource: source }),\n updated_at: new Date(),\n };\n },\n );\n return updated ? toComment(updated) : null;\n }\n\n async listMentionsForComment(commentId: string): Promise<WorkItemMentionRow[]> {\n return this.#listMentionRows(commentId);\n }\n\n /** Keyset inbox read for the mention attention provider, newest-first. */\n async listMentionsForUser({\n orgId,\n factoryProjectId,\n userId,\n before,\n limit,\n }: {\n orgId: string;\n factoryProjectId: string;\n userId: string;\n before?: { occurredAt: Date; id: string };\n limit: number;\n }): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n mentioned_id: userId,\n },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n ...(before ? { cursor: { values: [before.occurredAt, before.id] } } : {}),\n },\n );\n return rows.map(toMention);\n }\n\n async countForWorkItem({\n orgId,\n factoryProjectId,\n workItemId,\n }: {\n orgId: string;\n factoryProjectId: string;\n workItemId: string;\n }): Promise<number> {\n if (!this.ops.count) {\n throw new Error('[WorkItemCommentsStorage] storage backend does not support collection counts.');\n }\n return this.ops.count('work_item_comments', {\n org_id: orgId,\n factory_project_id: factoryProjectId,\n work_item_id: workItemId,\n deleted_at: null,\n });\n }\n\n /** Recent distinct comment authors of a project, for the roster fallback. */\n async listRecentAuthors({\n orgId,\n factoryProjectId,\n limit = 200,\n }: {\n orgId: string;\n factoryProjectId: string;\n limit?: number;\n }): Promise<FactoryActorRef[]> {\n const rows = await this.ops.findMany<WorkItemCommentDbRow>(\n 'work_item_comments',\n { org_id: orgId, factory_project_id: factoryProjectId },\n {\n orderBy: [\n ['occurred_at', 'desc'],\n ['id', 'desc'],\n ],\n limit,\n },\n );\n const authors = new Map<string, FactoryActorRef>();\n for (const row of rows) {\n if (authors.has(row.author_id)) continue;\n authors.set(row.author_id, toComment(row).author);\n }\n return [...authors.values()];\n }\n\n async #listMentionRows(commentId: string): Promise<WorkItemMentionRow[]> {\n const rows = await this.ops.findMany<WorkItemMentionDbRow>('work_item_comment_mentions', {\n comment_id: commentId,\n });\n return rows.map(toMention);\n }\n\n /**\n * Self-mentions never get rows: the join exists solely for the attention\n * inbox, and `CollectionWhere` cannot express `author_id != userId` at read\n * time, so the filter happens at write time.\n */\n async #writeMentionRows(\n comment: WorkItemCommentRow,\n mentions: FactoryMentionRef[],\n occurredAt = comment.occurredAt,\n ): Promise<void> {\n for (const mention of mentions) {\n if (mention.id === comment.author.id) continue;\n await this.ops.upsertOne<WorkItemMentionDbRow>(\n 'work_item_comment_mentions',\n ['comment_id', 'mentioned_kind', 'mentioned_id'],\n {\n comment_id: comment.id,\n mentioned_kind: mention.kind,\n mentioned_id: mention.id,\n author_id: comment.author.id,\n org_id: comment.orgId,\n factory_project_id: comment.factoryProjectId,\n work_item_id: comment.workItemId,\n occurred_at: occurredAt,\n },\n );\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2IA,SAAgB,uBAAuB,MAA4B,QAAuC;CACxG,MAAM,QAAQ,KAAK,eAAe,QAAQ,IAAI,OAAO,eAAe,QAAQ;CAC5E,OAAO,QAAQ,KAAM,UAAU,KAAK,KAAK,gBAAgB,OAAO;AAClE;AAmBA,MAAa,0BAA0B;AACvC,MAAa,2BAA2B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cAAc,CAAC;IACvB,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,uBAAuB,CAAC;IAClC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,EAAE,sBAAsB,CAAC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,YAAY,CAAC;CACtB;AAOD,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CAqSrF"}
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../../../src/storage/domains/comments/routes.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAiB,MAAM,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAQpD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AACvD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAClE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAE9D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAC;AAEzD,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,aAAa,CAAC;AAWjE,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,cAAc,CAAC;IACvB,IAAI,EAAE,SAAS,CAAC;IAChB,QAAQ,EAAE,uBAAuB,CAAC;IAClC,SAAS,EAAE,gBAAgB,CAAC;IAC5B,QAAQ,EAAE,sBAAsB,CAAC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,YAAY,CAAC;CACtB;AAOD,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,wBAAwB,GAAG,QAAQ,EAAE,CAwSrF"}
@@ -279,10 +279,12 @@ function buildCommentRoutes(dependencies) {
279
279
  try {
280
280
  await pubsub.subscribe(topic, onEvent, { startFrom: "latest" });
281
281
  if (!stream.aborted) {
282
- keepalive = setInterval(() => {
282
+ const ping = () => {
283
283
  if (stream.aborted) return;
284
284
  stream.write(": ping\n\n");
285
- }, FEED_KEEPALIVE_MS);
285
+ };
286
+ ping();
287
+ keepalive = setInterval(ping, FEED_KEEPALIVE_MS);
286
288
  await closed;
287
289
  }
288
290
  } finally {