@mastra/factory 0.29.0-alpha.0 → 0.29.0-alpha.1

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 (237) hide show
  1. package/README.md +20 -4
  2. package/dist/board-changes.d.ts +16 -0
  3. package/dist/board-changes.d.ts.map +1 -0
  4. package/dist/board-changes.js +40 -0
  5. package/dist/board-changes.js.map +1 -0
  6. package/dist/boards/index.js +2 -1
  7. package/dist/boards/semantics.d.ts +1 -3
  8. package/dist/boards/semantics.d.ts.map +1 -1
  9. package/dist/boards/semantics.js +1 -5
  10. package/dist/boards/semantics.js.map +1 -1
  11. package/dist/factory.d.ts +4 -0
  12. package/dist/factory.d.ts.map +1 -1
  13. package/dist/factory.js +51 -3
  14. package/dist/factory.js.map +1 -1
  15. package/dist/integrations/base.d.ts +9 -0
  16. package/dist/integrations/base.d.ts.map +1 -1
  17. package/dist/integrations/github/pull-request-source.js +2 -1
  18. package/dist/integrations/github/pull-request-source.js.map +1 -1
  19. package/dist/integrations/github/reconcile-worker.js +1 -1
  20. package/dist/integrations/github/reconcile-worker.js.map +1 -1
  21. package/dist/integrations/github/rules.d.ts +5 -2
  22. package/dist/integrations/github/rules.d.ts.map +1 -1
  23. package/dist/integrations/github/rules.js +16 -13
  24. package/dist/integrations/github/rules.js.map +1 -1
  25. package/dist/integrations/github/sandbox.js +2 -2
  26. package/dist/integrations/github/sandbox.js.map +1 -1
  27. package/dist/integrations/gitlab/default-rules.js +2 -1
  28. package/dist/integrations/gitlab/default-rules.js.map +1 -1
  29. package/dist/integrations/gitlab/discovery.d.ts +16 -0
  30. package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
  31. package/dist/integrations/gitlab/discovery.js +107 -0
  32. package/dist/integrations/gitlab/discovery.js.map +1 -0
  33. package/dist/integrations/gitlab/integration.d.ts.map +1 -1
  34. package/dist/integrations/gitlab/integration.js +1 -2
  35. package/dist/integrations/gitlab/integration.js.map +1 -1
  36. package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
  37. package/dist/integrations/gitlab/issue-reconciler.js +1 -0
  38. package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
  39. package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
  40. package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
  41. package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
  42. package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
  43. package/dist/integrations/gitlab/reconciler.js +4 -2
  44. package/dist/integrations/gitlab/reconciler.js.map +1 -1
  45. package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
  46. package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
  47. package/dist/integrations/gitlab/reconciliation-config.js +2 -8
  48. package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
  49. package/dist/integrations/gitlab/routes.d.ts +17 -0
  50. package/dist/integrations/gitlab/routes.d.ts.map +1 -1
  51. package/dist/integrations/gitlab/routes.js +28 -22
  52. package/dist/integrations/gitlab/routes.js.map +1 -1
  53. package/dist/integrations/gitlab/rules.d.ts +10 -4
  54. package/dist/integrations/gitlab/rules.d.ts.map +1 -1
  55. package/dist/integrations/gitlab/rules.js +32 -8
  56. package/dist/integrations/gitlab/rules.js.map +1 -1
  57. package/dist/integrations/incidentio/integration.d.ts +2 -1
  58. package/dist/integrations/incidentio/integration.d.ts.map +1 -1
  59. package/dist/integrations/incidentio/integration.js +7 -7
  60. package/dist/integrations/incidentio/integration.js.map +1 -1
  61. package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
  62. package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
  63. package/dist/integrations/incidentio/issue-reconciler.js +36 -1
  64. package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
  65. package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
  66. package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
  67. package/dist/integrations/incidentio/reconciliation-config.js +2 -5
  68. package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
  69. package/dist/integrations/incidentio/routes.d.ts +24 -8
  70. package/dist/integrations/incidentio/routes.d.ts.map +1 -1
  71. package/dist/integrations/incidentio/routes.js +33 -35
  72. package/dist/integrations/incidentio/routes.js.map +1 -1
  73. package/dist/integrations/incidentio/rules.d.ts +0 -4
  74. package/dist/integrations/incidentio/rules.d.ts.map +1 -1
  75. package/dist/integrations/incidentio/rules.js +17 -14
  76. package/dist/integrations/incidentio/rules.js.map +1 -1
  77. package/dist/integrations/intake-discovery.d.ts +44 -0
  78. package/dist/integrations/intake-discovery.d.ts.map +1 -0
  79. package/dist/integrations/intake-discovery.js +60 -0
  80. package/dist/integrations/intake-discovery.js.map +1 -0
  81. package/dist/integrations/issue-reconcile-worker.js +1 -1
  82. package/dist/integrations/issue-reconcile-worker.js.map +1 -1
  83. package/dist/integrations/issue-reconciler.d.ts +7 -0
  84. package/dist/integrations/issue-reconciler.d.ts.map +1 -1
  85. package/dist/integrations/issue-reconciler.js +47 -12
  86. package/dist/integrations/issue-reconciler.js.map +1 -1
  87. package/dist/integrations/jira/integration.d.ts +3 -2
  88. package/dist/integrations/jira/integration.d.ts.map +1 -1
  89. package/dist/integrations/jira/integration.js +5 -7
  90. package/dist/integrations/jira/integration.js.map +1 -1
  91. package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
  92. package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
  93. package/dist/integrations/jira/issue-reconciler.js +34 -1
  94. package/dist/integrations/jira/issue-reconciler.js.map +1 -1
  95. package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
  96. package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
  97. package/dist/integrations/jira/reconciliation-config.js +2 -5
  98. package/dist/integrations/jira/reconciliation-config.js.map +1 -1
  99. package/dist/integrations/jira/routes.d.ts +0 -7
  100. package/dist/integrations/jira/routes.d.ts.map +1 -1
  101. package/dist/integrations/jira/routes.js +2 -12
  102. package/dist/integrations/jira/routes.js.map +1 -1
  103. package/dist/integrations/jira/rules.d.ts +0 -4
  104. package/dist/integrations/jira/rules.d.ts.map +1 -1
  105. package/dist/integrations/jira/rules.js +3 -13
  106. package/dist/integrations/jira/rules.js.map +1 -1
  107. package/dist/integrations/kept-cards.d.ts +49 -0
  108. package/dist/integrations/kept-cards.d.ts.map +1 -0
  109. package/dist/integrations/kept-cards.js +97 -0
  110. package/dist/integrations/kept-cards.js.map +1 -0
  111. package/dist/integrations/linear/intake-discovery.d.ts +34 -0
  112. package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
  113. package/dist/integrations/linear/intake-discovery.js +112 -0
  114. package/dist/integrations/linear/intake-discovery.js.map +1 -0
  115. package/dist/integrations/linear/integration.d.ts.map +1 -1
  116. package/dist/integrations/linear/integration.js +1 -4
  117. package/dist/integrations/linear/integration.js.map +1 -1
  118. package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
  119. package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
  120. package/dist/integrations/linear/issue-reconciler.js +24 -20
  121. package/dist/integrations/linear/issue-reconciler.js.map +1 -1
  122. package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
  123. package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
  124. package/dist/integrations/linear/reconciliation-config.js +2 -8
  125. package/dist/integrations/linear/reconciliation-config.js.map +1 -1
  126. package/dist/integrations/linear/routes.d.ts +0 -2
  127. package/dist/integrations/linear/routes.d.ts.map +1 -1
  128. package/dist/integrations/linear/routes.js +3 -9
  129. package/dist/integrations/linear/routes.js.map +1 -1
  130. package/dist/integrations/platform/api-client.d.ts +2 -0
  131. package/dist/integrations/platform/api-client.d.ts.map +1 -1
  132. package/dist/integrations/platform/api-client.js +6 -1
  133. package/dist/integrations/platform/api-client.js.map +1 -1
  134. package/dist/integrations/platform/connect/routes.js +4 -1
  135. package/dist/integrations/platform/connect/routes.js.map +1 -1
  136. package/dist/integrations/platform/github/event-worker.d.ts +12 -0
  137. package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
  138. package/dist/integrations/platform/github/event-worker.js +56 -5
  139. package/dist/integrations/platform/github/event-worker.js.map +1 -1
  140. package/dist/integrations/platform/github/integration.d.ts +1 -0
  141. package/dist/integrations/platform/github/integration.d.ts.map +1 -1
  142. package/dist/integrations/platform/github/integration.js +8 -3
  143. package/dist/integrations/platform/github/integration.js.map +1 -1
  144. package/dist/integrations/platform/gitlab/event-worker.js +1 -1
  145. package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
  146. package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
  147. package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
  148. package/dist/integrations/platform/incidentio/integration.js +7 -7
  149. package/dist/integrations/platform/incidentio/integration.js.map +1 -1
  150. package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
  151. package/dist/integrations/platform/jira/integration.js +4 -7
  152. package/dist/integrations/platform/jira/integration.js.map +1 -1
  153. package/dist/integrations/platform/jira/routes.d.ts +0 -7
  154. package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
  155. package/dist/integrations/platform/jira/routes.js +2 -12
  156. package/dist/integrations/platform/jira/routes.js.map +1 -1
  157. package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
  158. package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
  159. package/dist/integrations/platform/linear/event-worker.js +1 -1
  160. package/dist/integrations/platform/linear/event-worker.js.map +1 -1
  161. package/dist/integrations/platform/linear/integration.d.ts +1 -0
  162. package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
  163. package/dist/integrations/platform/linear/integration.js +7 -7
  164. package/dist/integrations/platform/linear/integration.js.map +1 -1
  165. package/dist/integrations/platform/vanta/integration.d.ts +7 -2
  166. package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
  167. package/dist/integrations/platform/vanta/integration.js +22 -6
  168. package/dist/integrations/platform/vanta/integration.js.map +1 -1
  169. package/dist/integrations/reconciliation-config.d.ts +0 -1
  170. package/dist/integrations/reconciliation-config.d.ts.map +1 -1
  171. package/dist/integrations/reconciliation-config.js +1 -8
  172. package/dist/integrations/reconciliation-config.js.map +1 -1
  173. package/dist/integrations/slack/channel-reply-processor.js +1 -1
  174. package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
  175. package/dist/integrations/startup-summary.d.ts +8 -0
  176. package/dist/integrations/startup-summary.d.ts.map +1 -0
  177. package/dist/integrations/startup-summary.js +36 -0
  178. package/dist/integrations/startup-summary.js.map +1 -0
  179. package/dist/integrations/vanta/sync.d.ts +9 -5
  180. package/dist/integrations/vanta/sync.d.ts.map +1 -1
  181. package/dist/integrations/vanta/sync.js +16 -8
  182. package/dist/integrations/vanta/sync.js.map +1 -1
  183. package/dist/linked-repositories-changed.d.ts +14 -0
  184. package/dist/linked-repositories-changed.d.ts.map +1 -0
  185. package/dist/linked-repositories-changed.js +48 -0
  186. package/dist/linked-repositories-changed.js.map +1 -0
  187. package/dist/routes/contracts.d.ts +117 -0
  188. package/dist/routes/contracts.d.ts.map +1 -1
  189. package/dist/routes/contracts.js +44 -1
  190. package/dist/routes/contracts.js.map +1 -1
  191. package/dist/routes/run-queue.d.ts +17 -0
  192. package/dist/routes/run-queue.d.ts.map +1 -0
  193. package/dist/routes/run-queue.js +69 -0
  194. package/dist/routes/run-queue.js.map +1 -0
  195. package/dist/routes/surface.d.ts +8 -0
  196. package/dist/routes/surface.d.ts.map +1 -1
  197. package/dist/routes/surface.js +4 -2
  198. package/dist/routes/surface.js.map +1 -1
  199. package/dist/routes/work-item-selection.d.ts +4 -1
  200. package/dist/routes/work-item-selection.d.ts.map +1 -1
  201. package/dist/routes/work-item-selection.js +7 -2
  202. package/dist/routes/work-item-selection.js.map +1 -1
  203. package/dist/routes/work-items.d.ts +5 -0
  204. package/dist/routes/work-items.d.ts.map +1 -1
  205. package/dist/routes/work-items.js +17 -0
  206. package/dist/routes/work-items.js.map +1 -1
  207. package/dist/rules/dispatcher.d.ts +13 -1
  208. package/dist/rules/dispatcher.d.ts.map +1 -1
  209. package/dist/rules/dispatcher.js +9 -2
  210. package/dist/rules/dispatcher.js.map +1 -1
  211. package/dist/rules/review-source-tool.js +2 -1
  212. package/dist/rules/review-source-tool.js.map +1 -1
  213. package/dist/storage/domains/projects/base.d.ts +2 -0
  214. package/dist/storage/domains/projects/base.d.ts.map +1 -1
  215. package/dist/storage/domains/projects/base.js +13 -1
  216. package/dist/storage/domains/projects/base.js.map +1 -1
  217. package/dist/storage/domains/source-control/base.d.ts +32 -0
  218. package/dist/storage/domains/source-control/base.d.ts.map +1 -1
  219. package/dist/storage/domains/source-control/base.js +54 -4
  220. package/dist/storage/domains/source-control/base.js.map +1 -1
  221. package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
  222. package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
  223. package/dist/storage/domains/source-control/inmemory.js +17 -0
  224. package/dist/storage/domains/source-control/inmemory.js.map +1 -1
  225. package/dist/storage/domains/work-items/base.d.ts +1 -0
  226. package/dist/storage/domains/work-items/base.d.ts.map +1 -1
  227. package/dist/storage/domains/work-items/base.js +9 -0
  228. package/dist/storage/domains/work-items/base.js.map +1 -1
  229. package/dist/timing.d.ts +8 -1
  230. package/dist/timing.d.ts.map +1 -1
  231. package/dist/timing.js +10 -2
  232. package/dist/timing.js.map +1 -1
  233. package/dist/work-items/source-external-id.d.ts +4 -0
  234. package/dist/work-items/source-external-id.d.ts.map +1 -0
  235. package/dist/work-items/source-external-id.js +9 -0
  236. package/dist/work-items/source-external-id.js.map +1 -0
  237. package/package.json +8 -8
@@ -360,7 +360,8 @@ function buildIntegrationContext(deps, integrationId) {
360
360
  ...deps.factoryReady ? { runtime: {
361
361
  configVersion: deps.configVersion,
362
362
  workItems: deps.domains.workItems,
363
- boards: deps.boardRegistry
363
+ boards: deps.boardRegistry,
364
+ ...deps.keptCards ? { keptCards: deps.keptCards } : {}
364
365
  } } : {},
365
366
  ...deps.emitAudit || deps.onRepositoryPush ? { hooks: {
366
367
  ...deps.emitAudit ? { emitAudit: deps.emitAudit } : {},
@@ -662,7 +663,8 @@ function assembleFactoryApiRoutes(deps) {
662
663
  queueHealth: deps.domains.queueHealth,
663
664
  transitionService,
664
665
  startCoordinator,
665
- liveSessions: deps.liveSessions
666
+ liveSessions: deps.liveSessions,
667
+ runSlots: deps.runSlots
666
668
  }).routes() : [],
667
669
  ...deps.factoryReady && deps.storedBoards ? new BoardRoutes({
668
670
  auth: deps.auth,
@@ -1 +1 @@
1
- {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute, IUserProvider } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorage } from '@mastra/core/storage';\nimport type { FactorySandbox } from '@mastra/core/workspace';\n\nimport {\n boardFlow,\n boardForWorkItem,\n hasPullRequest,\n isPullRequestReviewPhase,\n REVIEW_CONTEXT,\n reviewedChangeRequest,\n} from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { legacyPlanRoleFor, workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardCache, ProjectBoardSource } from '../boards/project-boards.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationHooks } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport { MaterializeError } from '../integrations/github/sandbox.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport { workItemSource } from '../rules/types.js';\nimport type { FactoryRuleActor } from '../rules/types.js';\nimport { secretKeyMismatchHint, secretKeyProblem } from '../secret-encryption.js';\nimport {\n createSourceControlSessionLookup,\n ensureFactorySourceSession,\n FactorySourceSessionResolutionError,\n resolveFactorySourceControl,\n requireOrganizationModelKey,\n} from '../session/factory-session.js';\nimport type { EnsuredFactorySourceSession, OrganizationModelSources } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { StateSigner } from '../state-signing.js';\nimport { isHumanActorId } from '../storage/domains/audit/actors.js';\nimport type { AuditEmitter, AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { StoredBoardsStorage } from '../storage/domains/boards/base.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId, isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js';\nimport {\n SessionBranchHeldError,\n SessionOwnershipMismatchError,\n SourceControlConnectionNotFoundError,\n} from '../storage/domains/source-control/base.js';\nimport type { SourceControlStorage, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { VoiceSettingsStorage } from '../storage/domains/voice-settings/base.js';\nimport type { FactoryDispatchFailureCode, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport {\n legacyGithubWorkItemBranch,\n pullRequestBranch,\n workItemBranch,\n workItemBranchSource,\n workItemThreadTitle,\n} from '../work-item-branch.js';\nimport type { WorkItemBranchSource } from '../work-item-branch.js';\nimport { buildAutomationRunRoutes } from './automation-runs.js';\nimport { BoardRoutes } from './boards.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRouteRoutes } from './intake-routes.js';\nimport { IntakeRoutes } from './intake.js';\nimport { KnowledgeRoutes } from './knowledge.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { buildSourceControlSessionRoutes } from './source-control-sessions.js';\nimport { buildSourceControlSettingsRoutes } from './source-control-settings.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { VoiceRoutes } from './voice.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nconst MATERIALIZE_FAILURE_CODE = {\n 'git-missing': 'repository_git_missing',\n 'sandbox-unresponsive': 'repository_sandbox_unresponsive',\n 'egress-blocked': 'repository_egress_blocked',\n 'clone-failed': 'repository_clone_failed',\n 'pull-failed': 'repository_pull_failed',\n 'push-failed': 'repository_push_failed',\n 'commit-failed': 'repository_commit_failed',\n 'gh-missing': 'repository_cli_missing',\n 'pr-failed': 'repository_pr_failed',\n} satisfies Record<MaterializeError['code'], FactoryDispatchFailureCode>;\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Registry of the sessions this process holds, owned by the host so it can watch them too. */\n liveSessions: LiveSessions;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n /** Optional user directory for resolving persisted owners to display profiles. */\n users?: Pick<IUserProvider, 'getUser' | 'getUsers'>;\n authStorage: AuthStorage;\n audit: AuditEmitter & AuditRecorder;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox surface (enablement, provider label, create callback). */\n sandbox?: FactorySandbox;\n /** Push hand-off for environment builds, present when the sandbox can build templates. */\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n /** Saved-environment hand-off for environment builds, present when the sandbox can build templates. */\n onEnvironmentSaved?: (projectId: string) => void;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n filesystem: FilesystemStorage;\n modelDefaults: ModelDefaultsStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n skillOverrides: SkillOverridesStorage;\n voiceSettings: VoiceSettingsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n knowledgeEnabled: boolean;\n /** The Factory MCP endpoint is mounted; surfaced so the UI can show its URL. */\n mcpEnabled: boolean;\n /** Providers the operator opted in to run on the server process's own credentials. */\n deploymentModelProviders?: ReadonlySet<string>;\n /** App skills from `MastraFactory({ skills })`. */\n skills?: readonly InlineSkill[];\n knowledgeKey?: string;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n configVersion: string;\n /** Each project's boards; integrations use the code boards (`codeRegistry`). */\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Stored boards and their cache; mounts the board management routes when present. */\n storedBoards?: { storage: StoredBoardsStorage; cache: ProjectBoardCache };\n factoryTransitionService?: FactoryTransitionService;\n sessionRetirement?: import('../sandbox/session-retirement.js').SessionRetirementCoordinator;\n /** Moves a thread with its observation vectors onto another memory resource. */\n moveThread?: (input: { threadId: string; resourceId: string }) => Promise<unknown>;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n startCoordinator: FactoryStartCoordinator;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nconst REPEAT_UNAVAILABLE_LOG_MS = 5 * 60_000;\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n // Each retry throws a fresh error, so dedupe by message and repeat it periodically.\n let lastReported: { message: string; at: number } | undefined;\n const checkReady = async () => {\n try {\n await ensureReady();\n return undefined;\n } catch (error) {\n // The response only names a key mismatch, so this log is the only trace of any other cause.\n const message = String(error);\n const now = Date.now();\n if (lastReported?.message !== message || now - lastReported.at >= REPEAT_UNAVAILABLE_LOG_MS) {\n lastReported = { message, at: now };\n console.error(\n `[factory] ${integration.id} integration is unavailable: its storage failed to initialize:`,\n error,\n );\n }\n const cause =\n secretKeyMismatchHint(error) ??\n `Its storage failed to start. The server log line \"[factory] ${integration.id} integration is unavailable\" has the cause.`;\n return { error: 'integration_unavailable', message: `${integration.id} integration is unavailable. ${cause}` };\n }\n };\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context);\n };\n },\n };\n });\n}\n\n/**\n * Resolve the source-control session the work item already holds for this role,\n * when it still resolves to the item's org and factory project. Returns\n * `undefined` when there is no ref or the ref no longer resolves, so the caller\n * falls back to minting one.\n */\nasync function reuseBoundSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n role: string = input.role,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const ref = input.item.sessions[role];\n if (!ref) return undefined;\n // At least as strict as the coordinator's resolveSourceSession: a ref it\n // would reject must fall through to minting, not hard-fail the run.\n const session = await sourceControl.sessions.getBySessionId(ref.sessionId);\n if (\n !session?.projectRepositoryId ||\n session.orgId !== input.record.orgId ||\n session.factoryProjectId !== input.record.factoryProjectId\n ) {\n return undefined;\n }\n return {\n sessionId: session.sessionId,\n userId: session.userId,\n projectRepositoryId: session.projectRepositoryId,\n branch: session.branch,\n baseBranch: session.baseBranch,\n };\n}\n\n/**\n * Work cards planned before Planning moved into the `work` context hold the\n * plan's session under `plan`. Building continues in it, on the same branch and\n * repository a fresh session would use, so those cards keep the plan's context.\n */\nasync function legacyPlanSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n boardId: string,\n branch: string,\n projectRepositoryId: string,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const legacyRole = legacyPlanRoleFor(boardId, input.role);\n if (!legacyRole) return undefined;\n const session = await reuseBoundSession(sourceControl, input, legacyRole);\n if (\n session &&\n (session.branch === branch || session.branch === legacyGithubWorkItemBranch(branch)) &&\n session.projectRepositoryId === projectRepositoryId\n ) {\n return session;\n }\n return undefined;\n}\n\nfunction sameBranch(held: string, branch: string): boolean {\n return held === branch || held === legacyGithubWorkItemBranch(branch);\n}\n\n/** The branch a binding's session works on: the reviewed pull request's for PR review of an attached one. */\nfunction reviewBranch(\n input: FactoryBindingPreparationInput,\n board: InstalledBoard | undefined,\n stage: string,\n source: WorkItemBranchSource,\n): string {\n const metadata = input.item.workItem.metadata;\n if (input.role === REVIEW_CONTEXT && isPullRequestReviewPhase(board, stage)) {\n const change = reviewedChangeRequest({ ...input.item, source });\n if (change && !change.standalone && change.number !== undefined) {\n return pullRequestBranch({ id: input.item.id, provider: change.provider, number: change.number });\n }\n }\n return workItemBranch({ id: input.item.id, source, metadata });\n}\n\n/**\n * The lane a run started on a resting card moves it to: a review of a card with a pull request\n * goes to the board's pull request review; otherwise the first phase that runs in the role's\n * context. Work's phases share contexts, so its roles keep their own lanes: `work` builds and\n * the old `plan` role plans.\n */\nfunction restingExitLane(board: InstalledBoard | undefined, role: string, hasPullRequest: boolean): string | undefined {\n const pullRequestReview = boardFlow(board).pullRequestReview;\n if (hasPullRequest && role === REVIEW_CONTEXT && pullRequestReview) return pullRequestReview;\n return workLaneForRole(board, role) ?? board?.phaseForRole(role);\n}\n\n/** What the autonomous start reads to decide who a phase session runs as. */\nexport interface PhaseSessionOwnerSources extends OrganizationModelSources {\n workItems?: Pick<WorkItemsStorage, 'findRunBindingById'>;\n}\n\n/**\n * Who a newly minted phase session runs as. Wherever runs use the Factory's credentials\n * that is the Factory itself, whoever moved the card: the mover is the actor on the move,\n * not the owner of the run. A Factory whose runs use personal credentials has no keys of\n * its own, so there a person owns the run: whoever moved or approved the card, or the user\n * of the session whose agent moved it, else whoever created the Factory. `undefined`\n * leaves the last resort to the caller: whoever connected the repository.\n */\nasync function phaseSessionOwner(args: {\n sourceControl: SourceControlStorageHandle;\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined;\n project: FactoryProject;\n approver: string | undefined;\n}): Promise<string | undefined> {\n const { sourceControl, workItems, project, approver } = args;\n if (effectiveModelScope(project.modelScope, 'run') === 'factory') return factoryPrincipalId(project.id);\n if (approver?.startsWith('agent:')) {\n // `agent:session:<sessionId>` is a person's own session; `agent:<bindingId>` a phase run.\n const ref = approver.slice('agent:'.length);\n const sessionId = ref.startsWith('session:')\n ? ref.slice('session:'.length)\n : (await workItems?.findRunBindingById({ orgId: project.orgId, factoryProjectId: project.id, id: ref }))\n ?.sessionId;\n const session = sessionId ? await sourceControl.sessions.getBySessionId(sessionId) : null;\n if (session && session.orgId === project.orgId && isHumanActorId(session.userId)) return session.userId;\n } else if (isHumanActorId(approver)) {\n return approver;\n }\n return isHumanActorId(project.createdBy) ? project.createdBy : undefined;\n}\n\n/**\n * Who started the work, as the move that starts the run records them. An agent stays an\n * agent: recorded as a person, its move would count as a person accepting the work.\n */\nasync function starterOf(\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n approver: string,\n): Promise<FactoryRuleActor> {\n if (!approver.startsWith('agent:')) return { type: 'human', id: approver };\n const bindingId = approver.slice('agent:'.length);\n if (bindingId.startsWith('session:')) return { type: 'agent', bindingId, role: 'session' };\n const binding = await workItems?.findRunBindingById({\n orgId: project.orgId,\n factoryProjectId: project.id,\n id: bindingId,\n });\n return { type: 'agent', bindingId, role: binding?.role ?? 'agent' };\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n sourceControlProvider: SourceControlStorageHandle | Pick<GithubIntegration, 'sourceControlStorage'>,\n coordinator: Pick<FactoryStartCoordinator, 'prepare'>,\n projects: FactoryProjectsStorage,\n boards: BoardRegistry | ProjectBoardSource,\n input: FactoryBindingPreparationInput,\n intake?: Pick<IntakeStorage, 'getConfig'>,\n owner?: PhaseSessionOwnerSources,\n): Promise<void> {\n try {\n const sourceControl =\n 'sourceControlStorage' in sourceControlProvider\n ? sourceControlProvider.sourceControlStorage\n : sourceControlProvider;\n const source = workItemBranchSource(input.item.externalSource);\n // Only leaving a resting phase derives a lane from the role: roles don't own lanes,\n // and the Done close-out running in the triage seat must not drag the card back.\n // Both the current phase and the role's lane come from the installed board; an\n // unknown board or phase yields no destination rather than a guessed one.\n const boardId = boardForWorkItem(input.item);\n const board = (await toBoardSource(boards).load(input.record)).get(boardId);\n const currentStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n const currentKind = currentStage === undefined ? undefined : board?.phaseKind(currentStage);\n const destinationStage =\n currentKind === undefined\n ? undefined\n : currentKind === 'resting'\n ? restingExitLane(board, input.role, hasPullRequest({ ...input.item, source }))\n : currentStage;\n if (!destinationStage) {\n throw new FactoryDispatchError(\n 'unsupported_provider_item',\n `Factory skill invocation has no destination lane (role \"${input.role}\", stages [${input.item.stages.join(', ')}]).`,\n );\n }\n // A PR review on an issue card checks the pull request out on its own branch, apart from\n // the builder's issue branch; every other seat works on the card's own branch.\n const branch = reviewBranch(input, board, destinationStage, source);\n const connections = await sourceControl.connections.list({\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!connections.some(connection => connection.integrationId === sourceControl.integrationId)) {\n throw new FactoryDispatchError('source_control_missing', 'Factory source-control connection not found.');\n }\n const project = await projects.getById({ id: input.record.factoryProjectId });\n if (!project || project.orgId !== input.record.orgId) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory model policy is unavailable for project ${input.record.factoryProjectId}.`,\n );\n }\n // A retry may already own a role session. Check it before treating a\n // repository-less card as ambiguous, but never override an explicit signal.\n const reusable = await reuseBoundSession(sourceControl, input);\n // The review seat moves between branches on one card (self-review on the builder's branch,\n // PR review on each pull request's), so its session is reused only on the branch it holds.\n const boundSession =\n reusable && input.role === REVIEW_CONTEXT && !sameBranch(reusable.branch, branch) ? undefined : reusable;\n const intakeConfig = await intake?.getConfig({ orgId: input.record.orgId, integrationIds: ['linear'] });\n let repository = await resolveWorkItemRepository({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n item: input.item,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n });\n if (repository.status === 'ambiguous' && boundSession) {\n const link = await sourceControl.projectRepositories.get({\n orgId: input.record.orgId,\n id: boundSession.projectRepositoryId,\n });\n const linked =\n link && (await sourceControl.repositories.get({ orgId: input.record.orgId, id: link.repositoryId }));\n if (linked && repository.candidates.includes(linked.slug)) {\n repository = { status: 'resolved', slug: linked.slug, projectRepositoryId: link.id };\n }\n }\n if (repository.status !== 'resolved') {\n const detail =\n repository.status === 'ambiguous'\n ? `Choose one of the linked repositories: ${repository.candidates.join(', ')}.`\n : repository.hint;\n throw new FactoryDispatchError('source_repository_ambiguous', detail);\n }\n // Re-preparing a binding (server restart, retired controller session) must\n // land in the role's existing session: minting a replacement would repoint\n // the work item, flip the session's owner to the approver, and orphan the\n // previous sandbox.\n const approver = input.record.approvedBy ?? undefined;\n if (boundSession && boundSession.projectRepositoryId !== repository.projectRepositoryId) {\n throw new FactoryDispatchError(\n 'source_repository_ambiguous',\n `The existing session is bound to a different repository than ${repository.slug}. Choose the correct repository and retry.`,\n );\n }\n // The session is filed under the card's repository: the sandbox holds\n // every environment repository, but the coordinator, the PR tools and the\n // subscriptions follow the session's link, and the card names which one.\n const existingSession =\n boundSession ?? (await legacyPlanSession(sourceControl, input, boardId, branch, repository.projectRepositoryId));\n const ownerUserId =\n existingSession?.userId ??\n (await phaseSessionOwner({ sourceControl, workItems: owner?.workItems, project, approver }));\n if (isFactoryPrincipalId(ownerUserId)) await requireOrganizationModelKey(owner, project);\n const preparedSession =\n existingSession ??\n (await ensureFactorySourceSession({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n projectRepositoryId: repository.projectRepositoryId,\n branch,\n attributeToUserId: ownerUserId,\n }).catch(error => {\n if (error instanceof FactorySourceSessionResolutionError && error.reason === 'repository') {\n // The card resolved to a linked repository the sandbox will not check out.\n throw new FactoryDispatchError(\n 'source_repository_missing',\n `Repository ${repository.slug} is linked but not pre-cloned for this Factory. Turn on Pre-clone under Settings → Repositories, then retry.`,\n { cause: error },\n );\n }\n if (error instanceof SessionBranchHeldError) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `${error.message} The run cannot start until branch ${branch} is free for this repository.`,\n { cause: error },\n );\n }\n if (!(error instanceof SessionOwnershipMismatchError)) throw error;\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Session ${error.sessionId} on branch ${branch} predates factory ownership and cannot be reused. Delete that session, then retry.`,\n { cause: error },\n );\n }));\n\n const modelScope = effectiveModelScope(project.modelScope, 'run');\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n ...(approver ? { startedBy: await starterOf(owner?.workItems, project, approver) } : {}),\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n modelScope,\n defaultModelId: modelScope === 'factory' ? (project.defaultModelId ?? undefined) : undefined,\n threadTitle: workItemThreadTitle({ source, title: input.item.title, metadata: input.item.workItem.metadata }),\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: [...input.item.stages],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n if (error instanceof FactorySourceSessionResolutionError) {\n const code = error.reason === 'connection' ? 'source_control_missing' : 'source_repository_missing';\n throw new FactoryDispatchError(code, error.message, { cause: error });\n }\n if (error instanceof SourceControlConnectionNotFoundError) {\n throw new FactoryDispatchError('source_control_missing', error.message, { cause: error });\n }\n if (error instanceof MaterializeError) {\n throw new FactoryDispatchError(MATERIALIZE_FAILURE_CODE[error.code], error.message, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n | 'controller'\n | 'publicOrigin'\n | 'auth'\n | 'sandbox'\n | 'users'\n | 'factoryStorage'\n | 'integrationStorage'\n | 'sourceControlStorage'\n | 'integrations'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n configVersion: string;\n boardRegistry: BoardRegistry | ProjectBoardSource;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n | 'projects'\n | 'intake'\n | 'workItems'\n | 'channelIdentity'\n | 'memorySettings'\n | 'modelDefaults'\n | 'modelCredentials'\n | 'voiceSettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n sandbox: deps.sandbox,\n ...(deps.users ? { users: deps.users } : {}),\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n sourceControls: (deps.integrations ?? [])\n .filter(({ integration }) => integration.versionControl)\n .map(({ integration }) => deps.sourceControlStorage.forIntegration(integration.id)),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n modelDefaults: deps.domains.modelDefaults,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n },\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.factoryReady\n ? {\n runtime: { configVersion: deps.configVersion, workItems: deps.domains.workItems, boards: deps.boardRegistry },\n }\n : {}),\n ...(deps.emitAudit || deps.onRepositoryPush\n ? {\n hooks: {\n ...(deps.emitAudit ? { emitAudit: deps.emitAudit } : {}),\n ...(deps.onRepositoryPush ? { onRepositoryPush: deps.onRepositoryPush } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status`, `/web/linear/status`, and `/web/jira/status`\n * unconditionally, so when an integration is absent (or not ready) the status\n * contract must still hold. Unknown custom ids get no stub — the SPA doesn't\n * poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n sandbox: deps.sandbox,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n if (id === 'jira') {\n return [\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n configured,\n site: null,\n reason: 'missing_config',\n diagnostics: {\n jiraConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: deps.factoryStorage !== undefined,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\nexport interface FactoryStatusProblem {\n code: 'secret_key_mismatch';\n title: string;\n message: string;\n /** The one step that fixes it. Env var names are wrapped in backticks. */\n fix: string;\n /** Where an operator reads more, such as how to rotate keys. */\n docsUrl: string;\n}\n\n/** Domains that hold encrypted secrets; Factory can't run if they can't be read. */\nconst SECRET_DOMAINS = ['integrations', 'model-credentials', 'custom-providers'];\n\n/**\n * `GET /web/status`: problems that stop the whole Factory from working, so the\n * UI shows one alert banner instead of every page failing on its own. Only a\n * key problem counts, since only a redeploy with the right key clears it. Read\n * from the latest storage init result, so a key failure found by a later init\n * retry shows up too. Only client-safe copy goes out.\n */\nfunction factoryStatusRoutes(storage: FactoryStorage | undefined): ApiRoute[] {\n return [\n registerApiRoute('/web/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const problem = SECRET_DOMAINS.map(domain => secretKeyProblem(storage?.domainInitError(domain))).find(Boolean);\n const problems: FactoryStatusProblem[] = problem\n ? [\n {\n code: 'secret_key_mismatch',\n ...problem,\n docsUrl: 'https://factory.mastra.ai/troubleshooting#stored-credentials-stop-working',\n },\n ]\n : [];\n return c.json({ problems });\n },\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/default-model/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n const sourceControlRegistrations = registrations.filter(({ integration }) => integration.versionControl);\n const sourceControlIntegrationIds = [\n ...new Set(['github', ...sourceControlRegistrations.map(({ integration }) => integration.id)]),\n ];\n const sourceControls = sourceControlIntegrationIds.map(id => deps.sourceControlStorage.forIntegration(id));\n const sourceControlSessions = createSourceControlSessionLookup(sourceControls);\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n // Integrations evaluate code behaviors and place new cards with the code boards.\n boardRegistry: toBoardSource(deps.boardRegistry).codeRegistry,\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Session persistence belongs to the linked source-control provider, not to\n // GitHub. Replace legacy GitHub-owned handlers with one resolver spanning\n // the legacy GitHub partition and every registered source-control partition.\n const sharedSessionRouteKeys = new Set([\n 'GET /web/github/projects/:id/sessions',\n 'POST /web/github/projects/:id/sessions',\n 'GET /web/user-sessions/:sessionId',\n 'DELETE /web/user-sessions/:sessionId',\n 'POST /web/user-sessions/:sessionId/owner',\n 'POST /web/user-sessions/:sessionId/title',\n ]);\n const providerRoutes = integrationRoutes.filter(\n route => !sharedSessionRouteKeys.has(route.method + ' ' + route.path),\n );\n const sourceControlSessionRoutes =\n sourceControls.length === 0\n ? []\n : buildSourceControlSessionRoutes({\n auth: deps.auth,\n sourceControls,\n projects: deps.domains.projects,\n ...(deps.users ? { users: deps.users } : {}),\n controller: deps.controller,\n audit: deps.audit,\n memorySettings: deps.domains.memorySettings,\n sessionRetirement: deps.sessionRetirement,\n // A local sandbox's destroy keeps the session directory, so recreate\n // couldn't deliver the fresh checkout it promises there.\n sandboxRecreateSupported: deps.sandbox !== undefined && deps.sandbox.provider !== 'local',\n filesystem: deps.domains.filesystem,\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.moveThread ? { moveThread: deps.moveThread } : {}),\n ...(githubStorage ? { githubRepositories: githubStorage.repositories } : {}),\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear', 'jira']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({\n configVersion: deps.configVersion,\n boards: deps.boardRegistry,\n storage: deps.domains.workItems,\n audit: deps.audit,\n }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n request =>\n resolveFactorySourceControl({\n sourceControls,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n sessionId: request.sessionId,\n }),\n deps.domains.intake,\n { projects: deps.domains.projects, modelDefaults: deps.domains.modelDefaults },\n deps.boardRegistry,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n startCoordinator,\n ...(sourceControlRegistrations.length > 0\n ? {\n prepareBinding: async (input: FactoryBindingPreparationInput) => {\n const sourceControl = await resolveFactorySourceControl({\n sourceControls,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!sourceControl) {\n throw new FactoryDispatchError(\n 'source_control_missing',\n 'Factory project has no linked source-control repository.',\n );\n }\n return prepareFactoryRuleBinding(\n sourceControl,\n startCoordinator,\n deps.domains.projects,\n deps.boardRegistry,\n input,\n deps.domains.intake,\n {\n workItems: deps.domains.workItems,\n modelCredentials: deps.domains.modelCredentials,\n customProviders: deps.domains.customProviders,\n deploymentModelProviders: deps.deploymentModelProviders,\n },\n );\n },\n }\n : {}),\n });\n }\n\n return [\n ...factoryStatusRoutes(deps.factoryStorage),\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n sessions: sourceControlSessions,\n controller: deps.controller,\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelDefaults: deps.domains.modelDefaults,\n sourceControlSessions,\n sourceControls,\n workItems: deps.domains.workItems,\n memorySettings: deps.domains.memorySettings,\n factoryProjects: deps.domains.projects,\n customProviders: deps.domains.customProviders,\n features: { knowledge: deps.knowledgeEnabled, mcp: deps.mcpEnabled },\n deploymentProviders: deps.deploymentModelProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new VoiceRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n factoryProjects: deps.domains.projects,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n ...(deps.skills ? { skills: deps.skills } : {}),\n overrides: { projects: deps.domains.projects, storage: deps.domains.skillOverrides, audit: deps.audit },\n }).routes(),\n ...sourceControlSessionRoutes,\n ...(sourceControls.length === 0\n ? []\n : buildSourceControlSettingsRoutes({\n auth: deps.auth,\n sourceControls,\n ...(deps.onEnvironmentSaved ? { onEnvironmentSaved: deps.onEnvironmentSaved } : {}),\n })),\n ...providerRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n projects: deps.domains.projects,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) => [\n ...(integration.intake ? [{ id: integration.id, intake: integration.intake }] : []),\n ...(integration.additionalIntakes ?? []),\n ]),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.knowledgeEnabled\n ? new KnowledgeRoutes({\n auth: deps.auth,\n projects: deps.domains.projects,\n knowledge: async key => deps.controller.getMastra()?.getKnowledge(key),\n defaultKnowledgeKey: deps.knowledgeKey,\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n boardRegistry: deps.boardRegistry,\n intakeRoutes: deps.storedBoards?.storage,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: deps.liveSessions,\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new BoardRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new IntakeRouteRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n }).routes()\n : []),\n ...(deps.factoryReady\n ? buildAutomationRunRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n configVersion: deps.configVersion,\n boards: deps.boardRegistry,\n })\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FA,MAAM,2BAA2B;CAC/B,eAAe;CACf,wBAAwB;CACxB,kBAAkB;CAClB,gBAAgB;CAChB,eAAe;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W,KAAK,QAAQ;GACxB,eAAe,KAAK;GACpB,QAAQ,KAAK;EACf,CAAC,IACD,CAAC;CACP;AACF"}
1
+ {"version":3,"file":"surface.js","names":[],"sources":["../../src/routes/surface.ts"],"sourcesContent":["import type { AuthStorage } from '@mastra/code-sdk/auth/storage';\nimport type { MastraCodeState } from '@mastra/code-sdk/schema';\nimport type { AgentController } from '@mastra/core/agent-controller';\nimport type { ApiRoute, IUserProvider } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { InlineSkill } from '@mastra/core/skills';\nimport type { FactoryStorage } from '@mastra/core/storage';\nimport type { FactorySandbox } from '@mastra/core/workspace';\n\nimport {\n boardFlow,\n boardForWorkItem,\n hasPullRequest,\n isPullRequestReviewPhase,\n REVIEW_CONTEXT,\n reviewedChangeRequest,\n} from '../boards/index.js';\nimport type { BoardRegistry, InstalledBoard } from '../boards/index.js';\nimport { legacyPlanRoleFor, workLaneForRole } from '../boards/legacy-plan-role.js';\nimport { toBoardSource } from '../boards/project-boards.js';\nimport type { ProjectBoardCache, ProjectBoardSource } from '../boards/project-boards.js';\nimport type { FactoryIntegration, IntegrationContext, IntegrationHooks } from '../integrations/base.js';\nimport { getGithubFeatureDiagnostics } from '../integrations/github/config.js';\nimport type { GithubIntegration } from '../integrations/github/integration.js';\nimport { MaterializeError } from '../integrations/github/sandbox.js';\nimport type { CardSource } from '../integrations/kept-cards.js';\nimport { FactoryDispatchError } from '../rules/dispatch-errors.js';\nimport type { FactoryBindingPreparationInput } from '../rules/dispatcher.js';\nimport { FactoryStartCoordinator } from '../rules/start-coordinator.js';\nimport { FactoryTransitionService } from '../rules/transition-service.js';\nimport { workItemSource } from '../rules/types.js';\nimport type { FactoryRuleActor } from '../rules/types.js';\nimport { secretKeyMismatchHint, secretKeyProblem } from '../secret-encryption.js';\nimport {\n createSourceControlSessionLookup,\n ensureFactorySourceSession,\n FactorySourceSessionResolutionError,\n resolveFactorySourceControl,\n requireOrganizationModelKey,\n} from '../session/factory-session.js';\nimport type { EnsuredFactorySourceSession, OrganizationModelSources } from '../session/factory-session.js';\nimport type { LiveSessions } from '../session/live-sessions.js';\nimport { resolveWorkItemRepository } from '../session/work-item-repository.js';\nimport type { StateSigner } from '../state-signing.js';\nimport { isHumanActorId } from '../storage/domains/audit/actors.js';\nimport type { AuditEmitter, AuditRecorder } from '../storage/domains/audit/domain.js';\nimport type { StoredBoardsStorage } from '../storage/domains/boards/base.js';\nimport type { ChannelIdentityStorage } from '../storage/domains/channel-identity/base.js';\nimport type { ModelCredentialsStorage } from '../storage/domains/credentials/base.js';\nimport type { CustomProvidersStorage } from '../storage/domains/custom-providers/base.js';\nimport type { FilesystemStorage } from '../storage/domains/filesystem/base.js';\nimport type { IntakeStorage } from '../storage/domains/intake/base.js';\nimport type { IntegrationStorage } from '../storage/domains/integrations/base.js';\nimport type { MemorySettingsStorage } from '../storage/domains/memory-settings/base.js';\nimport type { ModelDefaultsStorage } from '../storage/domains/model-defaults/base.js';\nimport { effectiveModelScope, factoryPrincipalId, isFactoryPrincipalId } from '../storage/domains/projects/base.js';\nimport type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';\nimport type { SkillOverridesStorage } from '../storage/domains/skill-overrides/base.js';\nimport {\n SessionBranchHeldError,\n SessionOwnershipMismatchError,\n SourceControlConnectionNotFoundError,\n} from '../storage/domains/source-control/base.js';\nimport type { SourceControlStorage, SourceControlStorageHandle } from '../storage/domains/source-control/base.js';\nimport type { VoiceSettingsStorage } from '../storage/domains/voice-settings/base.js';\nimport type { FactoryDispatchFailureCode, WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport {\n legacyGithubWorkItemBranch,\n pullRequestBranch,\n workItemBranch,\n workItemBranchSource,\n workItemThreadTitle,\n} from '../work-item-branch.js';\nimport type { WorkItemBranchSource } from '../work-item-branch.js';\nimport { buildAutomationRunRoutes } from './automation-runs.js';\nimport { BoardRoutes } from './boards.js';\nimport { ConfigRoutes } from './config.js';\nimport { invalidateCustomProvidersSnapshots } from './custom-provider-source.js';\nimport { buildFsRoutes } from './fs.js';\nimport { IntakeRouteRoutes } from './intake-routes.js';\nimport { IntakeRoutes } from './intake.js';\nimport { KnowledgeRoutes } from './knowledge.js';\nimport { OAuthRoutes } from './oauth.js';\nimport type { RouteAuth } from './route.js';\nimport { SkillRoutes } from './skills.js';\nimport { buildSourceControlSessionRoutes } from './source-control-sessions.js';\nimport { buildSourceControlSettingsRoutes } from './source-control-settings.js';\nimport { invalidateTenantCredentialSnapshots } from './tenant-credentials.js';\nimport { VoiceRoutes } from './voice.js';\nimport { WorkItemRoutes } from './work-items.js';\n\nconst MATERIALIZE_FAILURE_CODE = {\n 'git-missing': 'repository_git_missing',\n 'sandbox-unresponsive': 'repository_sandbox_unresponsive',\n 'egress-blocked': 'repository_egress_blocked',\n 'clone-failed': 'repository_clone_failed',\n 'pull-failed': 'repository_pull_failed',\n 'push-failed': 'repository_push_failed',\n 'commit-failed': 'repository_commit_failed',\n 'gh-missing': 'repository_cli_missing',\n 'pr-failed': 'repository_pr_failed',\n} satisfies Record<MaterializeError['code'], FactoryDispatchFailureCode>;\nexport interface IntegrationRegistration {\n integration: FactoryIntegration;\n ready: boolean;\n ensureReady: () => Promise<void>;\n}\n\nexport interface FactoryApiRoutesDeps {\n controllerId: string;\n controller: AgentController<MastraCodeState>;\n /** Registry of the sessions this process holds, owned by the host so it can watch them too. */\n liveSessions: LiveSessions;\n /** Request-auth seam threaded from the host (no service locator). */\n auth: RouteAuth;\n /** Optional user directory for resolving persisted owners to display profiles. */\n users?: Pick<IUserProvider, 'getUser' | 'getUsers'>;\n authStorage: AuthStorage;\n audit: AuditEmitter & AuditRecorder;\n fsRoot?: string;\n publicOrigin: string;\n stateSigner?: StateSigner;\n /** Sandbox surface (enablement, provider label, create callback). */\n sandbox?: FactorySandbox;\n /** Push hand-off for environment builds, present when the sandbox can build templates. */\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n /** Saved-environment hand-off for environment builds, present when the sandbox can build templates. */\n onEnvironmentSaved?: (projectId: string) => void;\n /** Root factory storage backend (distributed locks, app-db diagnostics). */\n factoryStorage?: FactoryStorage;\n integrationStorage: IntegrationStorage;\n sourceControlStorage: SourceControlStorage;\n /** App-table domain handles, registered and owned by `MastraFactory.prepare()`. */\n domains: {\n intake: IntakeStorage;\n modelCredentials: ModelCredentialsStorage;\n memorySettings: MemorySettingsStorage;\n customProviders: CustomProvidersStorage;\n filesystem: FilesystemStorage;\n modelDefaults: ModelDefaultsStorage;\n projects: FactoryProjectsStorage;\n queueHealth: QueueHealthStorage;\n workItems: WorkItemsStorage;\n channelIdentity: ChannelIdentityStorage;\n skillOverrides: SkillOverridesStorage;\n voiceSettings: VoiceSettingsStorage;\n };\n integrations?: IntegrationRegistration[];\n intakeReady: boolean;\n factoryReady: boolean;\n knowledgeEnabled: boolean;\n /** The Factory MCP endpoint is mounted; surfaced so the UI can show its URL. */\n mcpEnabled: boolean;\n /** Providers the operator opted in to run on the server process's own credentials. */\n deploymentModelProviders?: ReadonlySet<string>;\n /** App skills from `MastraFactory({ skills })`. */\n skills?: readonly InlineSkill[];\n knowledgeKey?: string;\n /** Resolved Factory rule set, threaded from the host (no service locator). */\n configVersion: string;\n /** Each project's boards; integrations use the code boards (`codeRegistry`). */\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Stored boards and their cache; mounts the board management routes when present. */\n storedBoards?: { storage: StoredBoardsStorage; cache: ProjectBoardCache };\n factoryTransitionService?: FactoryTransitionService;\n sessionRetirement?: import('../sandbox/session-retirement.js').SessionRetirementCoordinator;\n /** Moves a thread with its observation vectors onto another memory resource. */\n moveThread?: (input: { threadId: string; resourceId: string }) => Promise<unknown>;\n /** This process's dispatcher run slots, for the run queue; `undefined` until the dispatcher exists. */\n runSlots?: () => { inUse: number; cap: number } | undefined;\n onFactoryRuntime?: (runtime: {\n transitionService: FactoryTransitionService;\n startCoordinator: FactoryStartCoordinator;\n prepareBinding?: (input: FactoryBindingPreparationInput) => Promise<void>;\n }) => void;\n}\n\nconst REPEAT_UNAVAILABLE_LOG_MS = 5 * 60_000;\n\nfunction guardIntegrationRoutes({\n integration,\n ready,\n ensureReady,\n routes,\n}: IntegrationRegistration & { routes: ApiRoute[] }): ApiRoute[] {\n if (ready) return routes;\n // Each retry throws a fresh error, so dedupe by message and repeat it periodically.\n let lastReported: { message: string; at: number } | undefined;\n const checkReady = async () => {\n try {\n await ensureReady();\n return undefined;\n } catch (error) {\n // The response only names a key mismatch, so this log is the only trace of any other cause.\n const message = String(error);\n const now = Date.now();\n if (lastReported?.message !== message || now - lastReported.at >= REPEAT_UNAVAILABLE_LOG_MS) {\n lastReported = { message, at: now };\n console.error(\n `[factory] ${integration.id} integration is unavailable: its storage failed to initialize:`,\n error,\n );\n }\n const cause =\n secretKeyMismatchHint(error) ??\n `Its storage failed to start. The server log line \"[factory] ${integration.id} integration is unavailable\" has the cause.`;\n return { error: 'integration_unavailable', message: `${integration.id} integration is unavailable. ${cause}` };\n }\n };\n return routes.map(route => {\n if ('handler' in route) {\n const handler = route.handler;\n return {\n ...route,\n handler: async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context, async () => {});\n },\n };\n }\n\n const createHandler = route.createHandler;\n return {\n ...route,\n createHandler: async (args: Parameters<typeof createHandler>[0]) => {\n const handler = await createHandler(args);\n return async (context: Parameters<typeof handler>[0]) => {\n const unavailable = await checkReady();\n if (unavailable) return context.json(unavailable, 503);\n return handler(context);\n };\n },\n };\n });\n}\n\n/**\n * Resolve the source-control session the work item already holds for this role,\n * when it still resolves to the item's org and factory project. Returns\n * `undefined` when there is no ref or the ref no longer resolves, so the caller\n * falls back to minting one.\n */\nasync function reuseBoundSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n role: string = input.role,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const ref = input.item.sessions[role];\n if (!ref) return undefined;\n // At least as strict as the coordinator's resolveSourceSession: a ref it\n // would reject must fall through to minting, not hard-fail the run.\n const session = await sourceControl.sessions.getBySessionId(ref.sessionId);\n if (\n !session?.projectRepositoryId ||\n session.orgId !== input.record.orgId ||\n session.factoryProjectId !== input.record.factoryProjectId\n ) {\n return undefined;\n }\n return {\n sessionId: session.sessionId,\n userId: session.userId,\n projectRepositoryId: session.projectRepositoryId,\n branch: session.branch,\n baseBranch: session.baseBranch,\n };\n}\n\n/**\n * Work cards planned before Planning moved into the `work` context hold the\n * plan's session under `plan`. Building continues in it, on the same branch and\n * repository a fresh session would use, so those cards keep the plan's context.\n */\nasync function legacyPlanSession(\n sourceControl: SourceControlStorageHandle,\n input: FactoryBindingPreparationInput,\n boardId: string,\n branch: string,\n projectRepositoryId: string,\n): Promise<EnsuredFactorySourceSession | undefined> {\n const legacyRole = legacyPlanRoleFor(boardId, input.role);\n if (!legacyRole) return undefined;\n const session = await reuseBoundSession(sourceControl, input, legacyRole);\n if (\n session &&\n (session.branch === branch || session.branch === legacyGithubWorkItemBranch(branch)) &&\n session.projectRepositoryId === projectRepositoryId\n ) {\n return session;\n }\n return undefined;\n}\n\nfunction sameBranch(held: string, branch: string): boolean {\n return held === branch || held === legacyGithubWorkItemBranch(branch);\n}\n\n/** The branch a binding's session works on: the reviewed pull request's for PR review of an attached one. */\nfunction reviewBranch(\n input: FactoryBindingPreparationInput,\n board: InstalledBoard | undefined,\n stage: string,\n source: WorkItemBranchSource,\n): string {\n const metadata = input.item.workItem.metadata;\n if (input.role === REVIEW_CONTEXT && isPullRequestReviewPhase(board, stage)) {\n const change = reviewedChangeRequest({ ...input.item, source });\n if (change && !change.standalone && change.number !== undefined) {\n return pullRequestBranch({ id: input.item.id, provider: change.provider, number: change.number });\n }\n }\n return workItemBranch({ id: input.item.id, source, metadata });\n}\n\n/**\n * The lane a run started on a resting card moves it to: a review of a card with a pull request\n * goes to the board's pull request review; otherwise the first phase that runs in the role's\n * context. Work's phases share contexts, so its roles keep their own lanes: `work` builds and\n * the old `plan` role plans.\n */\nfunction restingExitLane(board: InstalledBoard | undefined, role: string, hasPullRequest: boolean): string | undefined {\n const pullRequestReview = boardFlow(board).pullRequestReview;\n if (hasPullRequest && role === REVIEW_CONTEXT && pullRequestReview) return pullRequestReview;\n return workLaneForRole(board, role) ?? board?.phaseForRole(role);\n}\n\n/** What the autonomous start reads to decide who a phase session runs as. */\nexport interface PhaseSessionOwnerSources extends OrganizationModelSources {\n workItems?: Pick<WorkItemsStorage, 'findRunBindingById'>;\n}\n\n/**\n * Who a newly minted phase session runs as. Wherever runs use the Factory's credentials\n * that is the Factory itself, whoever moved the card: the mover is the actor on the move,\n * not the owner of the run. A Factory whose runs use personal credentials has no keys of\n * its own, so there a person owns the run: whoever moved or approved the card, or the user\n * of the session whose agent moved it, else whoever created the Factory. `undefined`\n * leaves the last resort to the caller: whoever connected the repository.\n */\nasync function phaseSessionOwner(args: {\n sourceControl: SourceControlStorageHandle;\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined;\n project: FactoryProject;\n approver: string | undefined;\n}): Promise<string | undefined> {\n const { sourceControl, workItems, project, approver } = args;\n if (effectiveModelScope(project.modelScope, 'run') === 'factory') return factoryPrincipalId(project.id);\n if (approver?.startsWith('agent:')) {\n // `agent:session:<sessionId>` is a person's own session; `agent:<bindingId>` a phase run.\n const ref = approver.slice('agent:'.length);\n const sessionId = ref.startsWith('session:')\n ? ref.slice('session:'.length)\n : (await workItems?.findRunBindingById({ orgId: project.orgId, factoryProjectId: project.id, id: ref }))\n ?.sessionId;\n const session = sessionId ? await sourceControl.sessions.getBySessionId(sessionId) : null;\n if (session && session.orgId === project.orgId && isHumanActorId(session.userId)) return session.userId;\n } else if (isHumanActorId(approver)) {\n return approver;\n }\n return isHumanActorId(project.createdBy) ? project.createdBy : undefined;\n}\n\n/**\n * Who started the work, as the move that starts the run records them. An agent stays an\n * agent: recorded as a person, its move would count as a person accepting the work.\n */\nasync function starterOf(\n workItems: Pick<WorkItemsStorage, 'findRunBindingById'> | undefined,\n project: Pick<FactoryProject, 'id' | 'orgId'>,\n approver: string,\n): Promise<FactoryRuleActor> {\n if (!approver.startsWith('agent:')) return { type: 'human', id: approver };\n const bindingId = approver.slice('agent:'.length);\n if (bindingId.startsWith('session:')) return { type: 'agent', bindingId, role: 'session' };\n const binding = await workItems?.findRunBindingById({\n orgId: project.orgId,\n factoryProjectId: project.id,\n id: bindingId,\n });\n return { type: 'agent', bindingId, role: binding?.role ?? 'agent' };\n}\n\n/**\n * Start a factory run for a rule binding: ensure the source-control session the\n * coordinator requires, then hand it to `prepare` along with the factory's\n * default model. Exported for tests — this is the autonomous entry point with no\n * browser and no interactive user, so nothing else would catch a regression in\n * what it forwards.\n */\nexport async function prepareFactoryRuleBinding(\n sourceControlProvider: SourceControlStorageHandle | Pick<GithubIntegration, 'sourceControlStorage'>,\n coordinator: Pick<FactoryStartCoordinator, 'prepare'>,\n projects: FactoryProjectsStorage,\n boards: BoardRegistry | ProjectBoardSource,\n input: FactoryBindingPreparationInput,\n intake?: Pick<IntakeStorage, 'getConfig'>,\n owner?: PhaseSessionOwnerSources,\n): Promise<void> {\n try {\n const sourceControl =\n 'sourceControlStorage' in sourceControlProvider\n ? sourceControlProvider.sourceControlStorage\n : sourceControlProvider;\n const source = workItemBranchSource(input.item.externalSource);\n // Only leaving a resting phase derives a lane from the role: roles don't own lanes,\n // and the Done close-out running in the triage seat must not drag the card back.\n // Both the current phase and the role's lane come from the installed board; an\n // unknown board or phase yields no destination rather than a guessed one.\n const boardId = boardForWorkItem(input.item);\n const board = (await toBoardSource(boards).load(input.record)).get(boardId);\n const currentStage = input.item.stages.length === 1 ? input.item.stages[0] : undefined;\n const currentKind = currentStage === undefined ? undefined : board?.phaseKind(currentStage);\n const destinationStage =\n currentKind === undefined\n ? undefined\n : currentKind === 'resting'\n ? restingExitLane(board, input.role, hasPullRequest({ ...input.item, source }))\n : currentStage;\n if (!destinationStage) {\n throw new FactoryDispatchError(\n 'unsupported_provider_item',\n `Factory skill invocation has no destination lane (role \"${input.role}\", stages [${input.item.stages.join(', ')}]).`,\n );\n }\n // A PR review on an issue card checks the pull request out on its own branch, apart from\n // the builder's issue branch; every other seat works on the card's own branch.\n const branch = reviewBranch(input, board, destinationStage, source);\n const connections = await sourceControl.connections.list({\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!connections.some(connection => connection.integrationId === sourceControl.integrationId)) {\n throw new FactoryDispatchError('source_control_missing', 'Factory source-control connection not found.');\n }\n const project = await projects.getById({ id: input.record.factoryProjectId });\n if (!project || project.orgId !== input.record.orgId) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Factory model policy is unavailable for project ${input.record.factoryProjectId}.`,\n );\n }\n // A retry may already own a role session. Check it before treating a\n // repository-less card as ambiguous, but never override an explicit signal.\n const reusable = await reuseBoundSession(sourceControl, input);\n // The review seat moves between branches on one card (self-review on the builder's branch,\n // PR review on each pull request's), so its session is reused only on the branch it holds.\n const boundSession =\n reusable && input.role === REVIEW_CONTEXT && !sameBranch(reusable.branch, branch) ? undefined : reusable;\n const intakeConfig = await intake?.getConfig({ orgId: input.record.orgId, integrationIds: ['linear'] });\n let repository = await resolveWorkItemRepository({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n item: input.item,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n });\n if (repository.status === 'ambiguous' && boundSession) {\n const link = await sourceControl.projectRepositories.get({\n orgId: input.record.orgId,\n id: boundSession.projectRepositoryId,\n });\n const linked =\n link && (await sourceControl.repositories.get({ orgId: input.record.orgId, id: link.repositoryId }));\n if (linked && repository.candidates.includes(linked.slug)) {\n repository = { status: 'resolved', slug: linked.slug, projectRepositoryId: link.id };\n }\n }\n if (repository.status !== 'resolved') {\n const detail =\n repository.status === 'ambiguous'\n ? `Choose one of the linked repositories: ${repository.candidates.join(', ')}.`\n : repository.hint;\n throw new FactoryDispatchError('source_repository_ambiguous', detail);\n }\n // Re-preparing a binding (server restart, retired controller session) must\n // land in the role's existing session: minting a replacement would repoint\n // the work item, flip the session's owner to the approver, and orphan the\n // previous sandbox.\n const approver = input.record.approvedBy ?? undefined;\n if (boundSession && boundSession.projectRepositoryId !== repository.projectRepositoryId) {\n throw new FactoryDispatchError(\n 'source_repository_ambiguous',\n `The existing session is bound to a different repository than ${repository.slug}. Choose the correct repository and retry.`,\n );\n }\n // The session is filed under the card's repository: the sandbox holds\n // every environment repository, but the coordinator, the PR tools and the\n // subscriptions follow the session's link, and the card names which one.\n const existingSession =\n boundSession ?? (await legacyPlanSession(sourceControl, input, boardId, branch, repository.projectRepositoryId));\n const ownerUserId =\n existingSession?.userId ??\n (await phaseSessionOwner({ sourceControl, workItems: owner?.workItems, project, approver }));\n if (isFactoryPrincipalId(ownerUserId)) await requireOrganizationModelKey(owner, project);\n const preparedSession =\n existingSession ??\n (await ensureFactorySourceSession({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n projectRepositoryId: repository.projectRepositoryId,\n branch,\n attributeToUserId: ownerUserId,\n }).catch(error => {\n if (error instanceof FactorySourceSessionResolutionError && error.reason === 'repository') {\n // The card resolved to a linked repository the sandbox will not check out.\n throw new FactoryDispatchError(\n 'source_repository_missing',\n `Repository ${repository.slug} is linked but not pre-cloned for this Factory. Turn on Pre-clone under Settings → Repositories, then retry.`,\n { cause: error },\n );\n }\n if (error instanceof SessionBranchHeldError) {\n throw new FactoryDispatchError(\n 'session_unavailable',\n `${error.message} The run cannot start until branch ${branch} is free for this repository.`,\n { cause: error },\n );\n }\n if (!(error instanceof SessionOwnershipMismatchError)) throw error;\n throw new FactoryDispatchError(\n 'session_unavailable',\n `Session ${error.sessionId} on branch ${branch} predates factory ownership and cannot be reused. Delete that session, then retry.`,\n { cause: error },\n );\n }));\n\n const modelScope = effectiveModelScope(project.modelScope, 'run');\n await coordinator.prepare({\n orgId: input.record.orgId,\n userId: preparedSession.userId,\n ...(approver ? { startedBy: await starterOf(owner?.workItems, project, approver) } : {}),\n factoryProjectId: input.record.factoryProjectId,\n sessionId: preparedSession.sessionId,\n modelScope,\n defaultModelId: modelScope === 'factory' ? (project.defaultModelId ?? undefined) : undefined,\n threadTitle: workItemThreadTitle({ source, title: input.item.title, metadata: input.item.workItem.metadata }),\n kickoffKey: input.record.id,\n destinationStage,\n workItem: {\n id: input.item.id,\n role: input.role,\n input: {\n externalSource: input.item.externalSource,\n parentWorkItemId: input.item.parentWorkItemId,\n title: input.item.title,\n stages: [...input.item.stages],\n sessions: input.item.sessions,\n metadata: input.item.metadata,\n },\n },\n });\n } catch (error) {\n if (error instanceof FactoryDispatchError) throw error;\n if (error instanceof FactorySourceSessionResolutionError) {\n const code = error.reason === 'connection' ? 'source_control_missing' : 'source_repository_missing';\n throw new FactoryDispatchError(code, error.message, { cause: error });\n }\n if (error instanceof SourceControlConnectionNotFoundError) {\n throw new FactoryDispatchError('source_control_missing', error.message, { cause: error });\n }\n if (error instanceof MaterializeError) {\n throw new FactoryDispatchError(MATERIALIZE_FAILURE_CODE[error.code], error.message, { cause: error });\n }\n throw error;\n }\n}\n\n/**\n * Build the {@link IntegrationContext} handed to an integration when the\n * factory collects its capabilities (routes, workers). One shape everywhere:\n * `assembleFactoryApiRoutes` uses it per registration, and `MastraFactory` uses it\n * when collecting integration workers at finalize.\n */\nexport function buildIntegrationContext(\n deps: Pick<\n FactoryApiRoutesDeps,\n | 'controller'\n | 'publicOrigin'\n | 'auth'\n | 'sandbox'\n | 'users'\n | 'factoryStorage'\n | 'integrationStorage'\n | 'sourceControlStorage'\n | 'integrations'\n > & {\n stateSigner: StateSigner;\n emitAudit?: AuditEmitter['emit'];\n onRepositoryPush?: IntegrationHooks['onRepositoryPush'];\n configVersion: string;\n boardRegistry: BoardRegistry | ProjectBoardSource;\n /** Passed for the workers' context only: routes do not sweep. */\n keptCards?: CardSource;\n factoryReady: boolean;\n domains: Pick<\n FactoryApiRoutesDeps['domains'],\n | 'projects'\n | 'intake'\n | 'workItems'\n | 'channelIdentity'\n | 'memorySettings'\n | 'modelDefaults'\n | 'modelCredentials'\n | 'voiceSettings'\n >;\n /**\n * Stable id of the registered source-control-owning integration (today:\n * `'github'` when registered). Every call site must derive and pass it so\n * `routes()`, `channels()`, and `workers()` all see the same context shape.\n */\n sourceControlOwnerId?: string;\n },\n integrationId: string,\n): IntegrationContext {\n return {\n auth: deps.auth,\n sandbox: deps.sandbox,\n ...(deps.users ? { users: deps.users } : {}),\n factoryStorage: deps.factoryStorage,\n baseUrl: deps.publicOrigin,\n controller: deps.controller,\n stateSigner: deps.stateSigner,\n storage: {\n generic: deps.integrationStorage.forIntegration(integrationId),\n sourceControl: deps.sourceControlStorage.forIntegration(integrationId),\n ...(deps.sourceControlOwnerId\n ? { sourceControlOwner: deps.sourceControlStorage.forIntegration(deps.sourceControlOwnerId) }\n : {}),\n sourceControls: (deps.integrations ?? [])\n .filter(({ integration }) => integration.versionControl)\n .map(({ integration }) => deps.sourceControlStorage.forIntegration(integration.id)),\n projects: deps.domains.projects,\n intake: deps.domains.intake,\n channelIdentity: deps.domains.channelIdentity,\n memorySettings: deps.domains.memorySettings,\n modelDefaults: deps.domains.modelDefaults,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n },\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.factoryReady\n ? {\n runtime: {\n configVersion: deps.configVersion,\n workItems: deps.domains.workItems,\n boards: deps.boardRegistry,\n ...(deps.keptCards ? { keptCards: deps.keptCards } : {}),\n },\n }\n : {}),\n ...(deps.emitAudit || deps.onRepositoryPush\n ? {\n hooks: {\n ...(deps.emitAudit ? { emitAudit: deps.emitAudit } : {}),\n ...(deps.onRepositoryPush ? { onRepositoryPush: deps.onRepositoryPush } : {}),\n },\n }\n : {}),\n };\n}\n\n/**\n * Disabled-status stub for the well-known integration ids. The SPA polls\n * `/web/github/status`, `/web/linear/status`, and `/web/jira/status`\n * unconditionally, so when an integration is absent (or not ready) the status\n * contract must still hold. Unknown custom ids get no stub — the SPA doesn't\n * poll them.\n */\nfunction disabledIntegrationStatusRoutes(deps: FactoryApiRoutesDeps, id: string, configured = false): ApiRoute[] {\n if (id === 'github') {\n return [\n registerApiRoute('/web/github/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n installations: [],\n reason: 'missing_config',\n diagnostics: getGithubFeatureDiagnostics({\n github: undefined,\n auth: deps.auth,\n appDbConfigured: deps.factoryStorage !== undefined,\n stateSigner: deps.stateSigner,\n sandbox: deps.sandbox,\n }),\n }),\n }),\n ];\n }\n if (id === 'linear') {\n return [\n registerApiRoute('/web/linear/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n connected: false,\n workspace: null,\n reason: 'missing_config',\n diagnostics: {\n linearAppConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: true,\n },\n }),\n }),\n ];\n }\n if (id === 'jira') {\n return [\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c =>\n c.json({\n enabled: false,\n configured,\n site: null,\n reason: 'missing_config',\n diagnostics: {\n jiraConfigured: configured,\n factoryAuthEnabled: deps.auth.enabled(),\n appDbConfigured: deps.factoryStorage !== undefined,\n },\n }),\n }),\n ];\n }\n return [];\n}\n\n/**\n * Stub for `GET /web/channel-accounts` when NO Slack integration is\n * registered. The SPA's Connections section polls the path unconditionally;\n * without a stub the SPA fallback serves HTML, which the UI can only read as\n * \"old server / unknown\". The machine-readable reason lets it say the truth:\n * the integration isn't registered.\n *\n * Mounted only for ABSENT slack — a registered integration owns the path via\n * its connect routes (or, when the state signer is unstable, gets no routes\n * at all and the UI falls back to the generic copy). Static payload, leaks\n * nothing → no auth needed, same posture as the github/linear stubs.\n */\nfunction absentSlackChannelAccountsRoutes(): ApiRoute[] {\n return [\n registerApiRoute('/web/channel-accounts', {\n method: 'GET',\n requiresAuth: false,\n handler: c => c.json({ accounts: [], canConnect: false, reason: 'not_registered' }),\n }),\n ];\n}\n\nexport interface FactoryStatusProblem {\n code: 'secret_key_mismatch';\n title: string;\n message: string;\n /** The one step that fixes it. Env var names are wrapped in backticks. */\n fix: string;\n /** Where an operator reads more, such as how to rotate keys. */\n docsUrl: string;\n}\n\n/** Domains that hold encrypted secrets; Factory can't run if they can't be read. */\nconst SECRET_DOMAINS = ['integrations', 'model-credentials', 'custom-providers'];\n\n/**\n * `GET /web/status`: problems that stop the whole Factory from working, so the\n * UI shows one alert banner instead of every page failing on its own. Only a\n * key problem counts, since only a redeploy with the right key clears it. Read\n * from the latest storage init result, so a key failure found by a later init\n * retry shows up too. Only client-safe copy goes out.\n */\nfunction factoryStatusRoutes(storage: FactoryStorage | undefined): ApiRoute[] {\n return [\n registerApiRoute('/web/status', {\n method: 'GET',\n requiresAuth: false,\n handler: c => {\n const problem = SECRET_DOMAINS.map(domain => secretKeyProblem(storage?.domainInitError(domain))).find(Boolean);\n const problems: FactoryStatusProblem[] = problem\n ? [\n {\n code: 'secret_key_mismatch',\n ...problem,\n docsUrl: 'https://factory.mastra.ai/troubleshooting#stored-credentials-stop-working',\n },\n ]\n : [];\n return c.json({ problems });\n },\n }),\n ];\n}\n\n/**\n * Assemble the custom `/web/*` API routes as Mastra `server.apiRoutes`:\n * - fs browser routes (project picker), confined to `fsRoot`\n * - config routes (provider/API-key/default-model/OM management)\n * - every registered integration's `routes()` surface (full set when ready,\n * disabled-status stub otherwise), plus stubs for absent known ids\n */\nexport function assembleFactoryApiRoutes(deps: FactoryApiRoutesDeps): ApiRoute[] {\n const emitAudit: AuditEmitter['emit'] = args => deps.audit.emit(args);\n const registrations = deps.integrations ?? [];\n const githubRegistration = registrations.find(({ integration }) => integration.id === 'github');\n const githubStorage = githubRegistration ? deps.sourceControlStorage.forIntegration('github') : undefined;\n const githubIntegration = githubRegistration?.integration as GithubIntegration | undefined;\n const sourceControlRegistrations = registrations.filter(({ integration }) => integration.versionControl);\n const sourceControlIntegrationIds = [\n ...new Set(['github', ...sourceControlRegistrations.map(({ integration }) => integration.id)]),\n ];\n const sourceControls = sourceControlIntegrationIds.map(id => deps.sourceControlStorage.forIntegration(id));\n const sourceControlSessions = createSourceControlSessionLookup(sourceControls);\n\n const integrationRoutes = registrations.flatMap(registration => {\n const { integration } = registration;\n if (!deps.stateSigner) return disabledIntegrationStatusRoutes(deps, integration.id, true);\n const context = buildIntegrationContext(\n {\n ...deps,\n // Integrations evaluate code behaviors and place new cards with the code boards.\n boardRegistry: toBoardSource(deps.boardRegistry).codeRegistry,\n stateSigner: deps.stateSigner,\n emitAudit,\n ...(githubRegistration ? { sourceControlOwnerId: 'github' } : {}),\n },\n integration.id,\n );\n return guardIntegrationRoutes({ ...registration, routes: integration.routes(context) });\n });\n // Session persistence belongs to the linked source-control provider, not to\n // GitHub. Replace legacy GitHub-owned handlers with one resolver spanning\n // the legacy GitHub partition and every registered source-control partition.\n const sharedSessionRouteKeys = new Set([\n 'GET /web/github/projects/:id/sessions',\n 'POST /web/github/projects/:id/sessions',\n 'GET /web/user-sessions/:sessionId',\n 'DELETE /web/user-sessions/:sessionId',\n 'POST /web/user-sessions/:sessionId/owner',\n 'POST /web/user-sessions/:sessionId/title',\n ]);\n const providerRoutes = integrationRoutes.filter(\n route => !sharedSessionRouteKeys.has(route.method + ' ' + route.path),\n );\n const sourceControlSessionRoutes =\n sourceControls.length === 0\n ? []\n : buildSourceControlSessionRoutes({\n auth: deps.auth,\n sourceControls,\n projects: deps.domains.projects,\n ...(deps.users ? { users: deps.users } : {}),\n controller: deps.controller,\n audit: deps.audit,\n memorySettings: deps.domains.memorySettings,\n sessionRetirement: deps.sessionRetirement,\n // A local sandbox's destroy keeps the session directory, so recreate\n // couldn't deliver the fresh checkout it promises there.\n sandboxRecreateSupported: deps.sandbox !== undefined && deps.sandbox.provider !== 'local',\n filesystem: deps.domains.filesystem,\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n ...(deps.moveThread ? { moveThread: deps.moveThread } : {}),\n ...(githubStorage ? { githubRepositories: githubStorage.repositories } : {}),\n });\n // Absent known integrations still get their disabled-status stub.\n const absentStubs = ['github', 'linear', 'jira']\n .filter(id => !registrations.some(({ integration }) => integration.id === id))\n .flatMap(id => disabledIntegrationStatusRoutes(deps, id));\n // Absent slack gets the channel-accounts not-registered stub (registered\n // slack owns the path via its own connect routes).\n const slackAbsentStubs = registrations.some(({ integration }) => integration.id === 'slack')\n ? []\n : absentSlackChannelAccountsRoutes();\n\n const transitionService = deps.factoryReady\n ? (deps.factoryTransitionService ??\n new FactoryTransitionService({\n configVersion: deps.configVersion,\n boards: deps.boardRegistry,\n storage: deps.domains.workItems,\n audit: deps.audit,\n }))\n : undefined;\n const startCoordinator = transitionService\n ? new FactoryStartCoordinator(\n deps.controller,\n deps.domains.workItems,\n transitionService,\n request =>\n resolveFactorySourceControl({\n sourceControls,\n orgId: request.orgId,\n factoryProjectId: request.factoryProjectId,\n sessionId: request.sessionId,\n }),\n deps.domains.intake,\n { projects: deps.domains.projects, modelDefaults: deps.domains.modelDefaults },\n deps.boardRegistry,\n )\n : undefined;\n if (transitionService && startCoordinator) {\n deps.onFactoryRuntime?.({\n transitionService,\n startCoordinator,\n ...(sourceControlRegistrations.length > 0\n ? {\n prepareBinding: async (input: FactoryBindingPreparationInput) => {\n const sourceControl = await resolveFactorySourceControl({\n sourceControls,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n });\n if (!sourceControl) {\n throw new FactoryDispatchError(\n 'source_control_missing',\n 'Factory project has no linked source-control repository.',\n );\n }\n return prepareFactoryRuleBinding(\n sourceControl,\n startCoordinator,\n deps.domains.projects,\n deps.boardRegistry,\n input,\n deps.domains.intake,\n {\n workItems: deps.domains.workItems,\n modelCredentials: deps.domains.modelCredentials,\n customProviders: deps.domains.customProviders,\n deploymentModelProviders: deps.deploymentModelProviders,\n },\n );\n },\n }\n : {}),\n });\n }\n\n return [\n ...factoryStatusRoutes(deps.factoryStorage),\n ...buildFsRoutes({\n root: deps.fsRoot,\n sessionFs: {\n auth: deps.auth,\n sessions: sourceControlSessions,\n controller: deps.controller,\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n },\n }),\n ...new ConfigRoutes({\n auth: deps.auth,\n controller: deps.controller,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n modelDefaults: deps.domains.modelDefaults,\n sourceControlSessions,\n sourceControls,\n workItems: deps.domains.workItems,\n memorySettings: deps.domains.memorySettings,\n factoryProjects: deps.domains.projects,\n customProviders: deps.domains.customProviders,\n features: { knowledge: deps.knowledgeEnabled, mcp: deps.mcpEnabled },\n deploymentProviders: deps.deploymentModelProviders,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n onCustomProvidersChanged: invalidateCustomProvidersSnapshots,\n }).routes(),\n ...new OAuthRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n onCredentialsChanged: invalidateTenantCredentialSnapshots,\n }).routes(),\n ...new VoiceRoutes({\n auth: deps.auth,\n authStorage: deps.authStorage,\n modelCredentials: deps.domains.modelCredentials,\n voiceSettings: deps.domains.voiceSettings,\n factoryProjects: deps.domains.projects,\n }).routes(),\n ...new SkillRoutes({\n auth: deps.auth,\n controllerId: deps.controllerId,\n controller: deps.controller,\n sourceControlStorage: githubStorage,\n ensureSourceControlReady: githubRegistration?.ensureReady,\n ...(deps.skills ? { skills: deps.skills } : {}),\n overrides: { projects: deps.domains.projects, storage: deps.domains.skillOverrides, audit: deps.audit },\n }).routes(),\n ...sourceControlSessionRoutes,\n ...(sourceControls.length === 0\n ? []\n : buildSourceControlSettingsRoutes({\n auth: deps.auth,\n sourceControls,\n ...(deps.onEnvironmentSaved ? { onEnvironmentSaved: deps.onEnvironmentSaved } : {}),\n })),\n ...providerRoutes,\n ...absentStubs,\n ...slackAbsentStubs,\n ...(deps.intakeReady\n ? new IntakeRoutes({\n auth: deps.auth,\n audit: deps.audit,\n intake: deps.domains.intake,\n projects: deps.domains.projects,\n integrations: (deps.integrations ?? []).flatMap(({ integration }) => [\n ...(integration.intake ? [{ id: integration.id, intake: integration.intake }] : []),\n ...(integration.additionalIntakes ?? []),\n ]),\n }).routes()\n : []),\n ...(deps.factoryReady && deps.knowledgeEnabled\n ? new KnowledgeRoutes({\n auth: deps.auth,\n projects: deps.domains.projects,\n knowledge: async key => deps.controller.getMastra()?.getKnowledge(key),\n defaultKnowledgeKey: deps.knowledgeKey,\n }).routes()\n : []),\n ...(deps.factoryReady\n ? new WorkItemRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n boardRegistry: deps.boardRegistry,\n intakeRoutes: deps.storedBoards?.storage,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: deps.liveSessions,\n runSlots: deps.runSlots,\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new BoardRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n }).routes()\n : []),\n ...(deps.factoryReady && deps.storedBoards\n ? new IntakeRouteRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n storage: deps.storedBoards.storage,\n boards: deps.storedBoards.cache,\n }).routes()\n : []),\n ...(deps.factoryReady\n ? buildAutomationRunRoutes({\n auth: deps.auth,\n audit: deps.audit,\n projects: deps.domains.projects,\n workItems: deps.domains.workItems,\n configVersion: deps.configVersion,\n boards: deps.boardRegistry,\n })\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,MAAM,2BAA2B;CAC/B,eAAe;CACf,wBAAwB;CACxB,kBAAkB;CAClB,gBAAgB;CAChB,eAAe;CACf,e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vB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,eAAe,KAAK;GACpB,QAAQ,KAAK;EACf,CAAC,IACD,CAAC;CACP;AACF"}
@@ -7,7 +7,10 @@ export declare function unstartedCards(board: readonly Card[], query: string, li
7
7
  cards: Card[];
8
8
  total: number;
9
9
  };
10
- /** The cards filed from one of `sources`, each a source id or a URL, in board order. */
10
+ /**
11
+ * The cards filed from one of `sources`, each a source id or a URL, in board order. A pull request
12
+ * attached to an issue card counts as filed on that card.
13
+ */
11
14
  export declare function cardsFiledFrom(board: readonly Card[], sources: readonly string[]): Card[];
12
15
  /** The cards whose id is one of `ids`, in board order. An id no card has is left out. */
13
16
  export declare function cardsWithIds(board: readonly Card[], ids: readonly string[]): Card[];
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-selection.d.ts","sourceRoot":"","sources":["../../src/routes/work-item-selection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AA0BlE;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAIrH;AAED,wFAAwF;AACxF,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,EAAE,CAOzF;AAED,yFAAyF;AACzF,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,EAAE,CAGnF"}
1
+ {"version":3,"file":"work-item-selection.d.ts","sourceRoot":"","sources":["../../src/routes/work-item-selection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AA2BlE;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,IAAI,EAAE,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAIrH;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,OAAO,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,EAAE,CAUzF;AAED,yFAAyF;AACzF,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,EAAE,GAAG,EAAE,SAAS,MAAM,EAAE,GAAG,IAAI,EAAE,CAGnF"}
@@ -1,5 +1,6 @@
1
1
  import { cardSearchText } from "../work-items/card-search-text.js";
2
2
  import { hasEveryWord, searchWords } from "../work-items/search-words.js";
3
+ import { sourceExternalId } from "../work-items/source-external-id.js";
3
4
  // src/routes/work-item-selection.ts
4
5
  const unstartedByBoard = /* @__PURE__ */ new WeakMap();
5
6
  function unstarted(board) {
@@ -25,13 +26,17 @@ function unstartedCards(board, query, limit) {
25
26
  total: matches.length
26
27
  };
27
28
  }
28
- /** The cards filed from one of `sources`, each a source id or a URL, in board order. */
29
+ /**
30
+ * The cards filed from one of `sources`, each a source id or a URL, in board order. A pull request
31
+ * attached to an issue card counts as filed on that card.
32
+ */
29
33
  function cardsFiledFrom(board, sources) {
30
34
  const wanted = new Set(sources);
31
35
  return board.filter((card) => [
32
36
  card.externalSource?.externalId,
33
37
  card.externalSource?.url,
34
- card.workItem.url
38
+ card.workItem.url,
39
+ ...card.workItem.sources.flatMap((source) => [sourceExternalId(source), source.url])
35
40
  ].some((key) => typeof key === "string" && wanted.has(key)));
36
41
  }
37
42
  /** The cards whose id is one of `ids`, in board order. An id no card has is left out. */
@@ -1 +1 @@
1
- {"version":3,"file":"work-item-selection.js","names":[],"sources":["../../src/routes/work-item-selection.ts"],"sourcesContent":["import type { Card } from '../storage/domains/work-items/base.js';\nimport { cardSearchText } from '../work-items/card-search-text.js';\nimport { hasEveryWord, searchWords } from '../work-items/search-words.js';\n\ninterface UnstartedCard {\n card: Card;\n /** Lowercased, so a search lowercases only its own words. */\n text: string;\n}\n\n// One list per board version: `listShared` returns the same array until a card changes.\nconst unstartedByBoard = new WeakMap<readonly Card[], UnstartedCard[]>();\n\nfunction unstarted(board: readonly Card[]): UnstartedCard[] {\n let cards = unstartedByBoard.get(board);\n if (!cards) {\n cards = board\n .filter(card => Object.keys(card.sessions).length === 0)\n // Cards updated at the same instant keep the board's order, newest created first.\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())\n .map(card => ({ card, text: cardSearchText(card) }));\n unstartedByBoard.set(board, cards);\n }\n return cards;\n}\n\n/**\n * The cards holding no session whose text has every word of `query`, most recently updated first:\n * the first `limit` of them, and how many there are in all.\n */\nexport function unstartedCards(board: readonly Card[], query: string, limit: number): { cards: Card[]; total: number } {\n const words = searchWords(query);\n const matches = unstarted(board).filter(({ text }) => hasEveryWord(text, words));\n return { cards: matches.slice(0, limit).map(({ card }) => card), total: matches.length };\n}\n\n/** The cards filed from one of `sources`, each a source id or a URL, in board order. */\nexport function cardsFiledFrom(board: readonly Card[], sources: readonly string[]): Card[] {\n const wanted = new Set(sources);\n return board.filter(card =>\n [card.externalSource?.externalId, card.externalSource?.url, card.workItem.url].some(\n key => typeof key === 'string' && wanted.has(key),\n ),\n );\n}\n\n/** The cards whose id is one of `ids`, in board order. An id no card has is left out. */\nexport function cardsWithIds(board: readonly Card[], ids: readonly string[]): Card[] {\n const wanted = new Set(ids);\n return board.filter(card => wanted.has(card.id));\n}\n"],"mappings":";;;AAWA,MAAM,mCAAmB,IAAI,QAA0C;AAEvE,SAAS,UAAU,OAAyC;CAC1D,IAAI,QAAQ,iBAAiB,IAAI,KAAK;CACtC,IAAI,CAAC,OAAO;EACV,QAAQ,MACL,QAAO,SAAQ,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,WAAW,CAAC,CAAC,CAEvD,MAAM,GAAG,MAAM,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,CAAC,CAAC,CAC7D,KAAI,UAAS;GAAE;GAAM,MAAM,eAAe,IAAI;EAAE,EAAE;EACrD,iBAAiB,IAAI,OAAO,KAAK;CACnC;CACA,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,OAAwB,OAAe,OAAiD;CACrH,MAAM,QAAQ,YAAY,KAAK;CAC/B,MAAM,UAAU,UAAU,KAAK,CAAC,CAAC,QAAQ,EAAE,WAAW,aAAa,MAAM,KAAK,CAAC;CAC/E,OAAO;EAAE,OAAO,QAAQ,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,WAAW,IAAI;EAAG,OAAO,QAAQ;CAAO;AACzF;;AAGA,SAAgB,eAAe,OAAwB,SAAoC;CACzF,MAAM,SAAS,IAAI,IAAI,OAAO;CAC9B,OAAO,MAAM,QAAO,SAClB;EAAC,KAAK,gBAAgB;EAAY,KAAK,gBAAgB;EAAK,KAAK,SAAS;CAAG,CAAC,CAAC,MAC7E,QAAO,OAAO,QAAQ,YAAY,OAAO,IAAI,GAAG,CAClD,CACF;AACF;;AAGA,SAAgB,aAAa,OAAwB,KAAgC;CACnF,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,MAAM,QAAO,SAAQ,OAAO,IAAI,KAAK,EAAE,CAAC;AACjD"}
1
+ {"version":3,"file":"work-item-selection.js","names":[],"sources":["../../src/routes/work-item-selection.ts"],"sourcesContent":["import type { Card } from '../storage/domains/work-items/base.js';\nimport { cardSearchText } from '../work-items/card-search-text.js';\nimport { hasEveryWord, searchWords } from '../work-items/search-words.js';\nimport { sourceExternalId } from '../work-items/source-external-id.js';\n\ninterface UnstartedCard {\n card: Card;\n /** Lowercased, so a search lowercases only its own words. */\n text: string;\n}\n\n// One list per board version: `listShared` returns the same array until a card changes.\nconst unstartedByBoard = new WeakMap<readonly Card[], UnstartedCard[]>();\n\nfunction unstarted(board: readonly Card[]): UnstartedCard[] {\n let cards = unstartedByBoard.get(board);\n if (!cards) {\n cards = board\n .filter(card => Object.keys(card.sessions).length === 0)\n // Cards updated at the same instant keep the board's order, newest created first.\n .sort((a, b) => b.updatedAt.getTime() - a.updatedAt.getTime())\n .map(card => ({ card, text: cardSearchText(card) }));\n unstartedByBoard.set(board, cards);\n }\n return cards;\n}\n\n/**\n * The cards holding no session whose text has every word of `query`, most recently updated first:\n * the first `limit` of them, and how many there are in all.\n */\nexport function unstartedCards(board: readonly Card[], query: string, limit: number): { cards: Card[]; total: number } {\n const words = searchWords(query);\n const matches = unstarted(board).filter(({ text }) => hasEveryWord(text, words));\n return { cards: matches.slice(0, limit).map(({ card }) => card), total: matches.length };\n}\n\n/**\n * The cards filed from one of `sources`, each a source id or a URL, in board order. A pull request\n * attached to an issue card counts as filed on that card.\n */\nexport function cardsFiledFrom(board: readonly Card[], sources: readonly string[]): Card[] {\n const wanted = new Set(sources);\n return board.filter(card =>\n [\n card.externalSource?.externalId,\n card.externalSource?.url,\n card.workItem.url,\n ...card.workItem.sources.flatMap(source => [sourceExternalId(source), source.url]),\n ].some(key => typeof key === 'string' && wanted.has(key)),\n );\n}\n\n/** The cards whose id is one of `ids`, in board order. An id no card has is left out. */\nexport function cardsWithIds(board: readonly Card[], ids: readonly string[]): Card[] {\n const wanted = new Set(ids);\n return board.filter(card => wanted.has(card.id));\n}\n"],"mappings":";;;;AAYA,MAAM,mCAAmB,IAAI,QAA0C;AAEvE,SAAS,UAAU,OAAyC;CAC1D,IAAI,QAAQ,iBAAiB,IAAI,KAAK;CACtC,IAAI,CAAC,OAAO;EACV,QAAQ,MACL,QAAO,SAAQ,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,WAAW,CAAC,CAAC,CAEvD,MAAM,GAAG,MAAM,EAAE,UAAU,QAAQ,IAAI,EAAE,UAAU,QAAQ,CAAC,CAAC,CAC7D,KAAI,UAAS;GAAE;GAAM,MAAM,eAAe,IAAI;EAAE,EAAE;EACrD,iBAAiB,IAAI,OAAO,KAAK;CACnC;CACA,OAAO;AACT;;;;;AAMA,SAAgB,eAAe,OAAwB,OAAe,OAAiD;CACrH,MAAM,QAAQ,YAAY,KAAK;CAC/B,MAAM,UAAU,UAAU,KAAK,CAAC,CAAC,QAAQ,EAAE,WAAW,aAAa,MAAM,KAAK,CAAC;CAC/E,OAAO;EAAE,OAAO,QAAQ,MAAM,GAAG,KAAK,CAAC,CAAC,KAAK,EAAE,WAAW,IAAI;EAAG,OAAO,QAAQ;CAAO;AACzF;;;;;AAMA,SAAgB,eAAe,OAAwB,SAAoC;CACzF,MAAM,SAAS,IAAI,IAAI,OAAO;CAC9B,OAAO,MAAM,QAAO,SAClB;EACE,KAAK,gBAAgB;EACrB,KAAK,gBAAgB;EACrB,KAAK,SAAS;EACd,GAAG,KAAK,SAAS,QAAQ,SAAQ,WAAU,CAAC,iBAAiB,MAAM,GAAG,OAAO,GAAG,CAAC;CACnF,CAAC,CAAC,MAAK,QAAO,OAAO,QAAQ,YAAY,OAAO,IAAI,GAAG,CAAC,CAC1D;AACF;;AAGA,SAAgB,aAAa,OAAwB,KAAgC;CACnF,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,MAAM,QAAO,SAAQ,OAAO,IAAI,KAAK,EAAE,CAAC;AACjD"}
@@ -38,6 +38,11 @@ export interface WorkItemRoutesDeps extends RouteDependencies {
38
38
  startCoordinator?: Pick<FactoryStartCoordinator, 'prepare'>;
39
39
  /** Materialized sessions, read to report which of the listed cards are being worked or wait on someone. */
40
40
  liveSessions: Pick<LiveSessions, 'isRunning' | 'parked' | 'parkedIn'>;
41
+ /** This process's dispatcher run slots; absent or `undefined` while it runs no dispatcher. */
42
+ runSlots?: () => {
43
+ inUse: number;
44
+ cap: number;
45
+ } | undefined;
41
46
  }
42
47
  /** Validate an untrusted create body. Unknown keys are dropped. */
43
48
  export declare function parseCreateWorkItem(body: unknown): CreateWorkItemInput | null;
@@ -1 +1 @@
1
- {"version":3,"file":"work-items.d.ts","sourceRoot":"","sources":["../../src/routes/work-items.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAKpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACxD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEtE,OAAO,KAAK,EAAE,kBAAkB,EAAsB,MAAM,6BAA6B,CAAC;AAG1F,OAAO,KAAK,EACV,uBAAuB,EAGxB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,KAAK,EAA4B,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAEzG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAEvE,OAAO,KAAK,EAAuB,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AACvG,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,yCAAyC,CAAC;AAElF,OAAO,KAAK,EACV,mBAAmB,EAEnB,mBAAmB,EAEnB,gBAAgB,EACjB,MAAM,uCAAuC,CAAC;AA0B/C,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AACpD,OAAO,EAAS,KAAK,EAAE,MAAM,YAAY,CAAC;AAU1C,MAAM,WAAW,kBAAmB,SAAQ,iBAAiB;IAC3D,KAAK,EAAE,YAAY,CAAC;IACpB,yFAAyF;IACzF,QAAQ,EAAE,sBAAsB,CAAC;IACjC,kDAAkD;IAClD,SAAS,EAAE,gBAAgB,CAAC;IAC5B,kDAAkD;IAClD,oFAAoF;IACpF,aAAa,CAAC,EAAE,aAAa,GAAG,kBAAkB,CAAC;IACnD,6EAA6E;IAC7E,YAAY,CAAC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AC,IAAI,EAAE,OAAO,GAAG,mBAAmB,GAAG,IAAI,CAG7E;AAyFD,qBAAa,cAAe,SAAQ,KAAK,CAAC,kBAAkB,CAAC;;IAoH3D,gEAAgE;IAChE,MAAM,IAAI,QAAQ,EAAE,CA0mBnB;CACF"}
@@ -20,6 +20,7 @@ import { buildAttentionRoutes } from "./attention.js";
20
20
  import { boardSnapshot, hashedBody, listCheck, matchesEtag, movedBody, namedBody, scopedSnapshot, sha1 } from "./board-snapshot.js";
21
21
  import { FACTORY_ROUTE_CONTRACTS } from "./contracts.js";
22
22
  import { Route, loose } from "./route.js";
23
+ import { readRunQueue } from "./run-queue.js";
23
24
  import { workItemActivity } from "./work-item-activity.js";
24
25
  import { cardsFiledFrom, cardsWithIds, unstartedCards } from "./work-item-selection.js";
25
26
  import { CARD_DECISION_STATUSES, cardsWithFailedRun, workItemStarters } from "./work-item-starters.js";
@@ -593,6 +594,22 @@ var WorkItemRoutes = class extends Route {
593
594
  });
594
595
  }
595
596
  }),
597
+ registerApiRoute(FACTORY_ROUTE_CONTRACTS.runQueue.path, {
598
+ method: FACTORY_ROUTE_CONTRACTS.runQueue.method,
599
+ requiresAuth: false,
600
+ handler: async (c) => {
601
+ const resolved = await this.#resolveProject(loose(c));
602
+ if ("response" in resolved) return resolved.response;
603
+ await workItems.ensureReady();
604
+ return c.json(await readRunQueue({
605
+ workItems,
606
+ orgId: resolved.orgId,
607
+ factoryProjectId: resolved.factoryProjectId,
608
+ slots: this.deps.runSlots?.(),
609
+ now: /* @__PURE__ */ new Date()
610
+ }));
611
+ }
612
+ }),
596
613
  ...buildAttentionRoutes({
597
614
  workItems,
598
615
  boards: this.#boards,