@mastra/factory 0.29.0-alpha.3 → 0.29.0-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +123 -64
- package/dist/boards/board-events.d.ts +89 -9
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +176 -13
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +14 -1
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/busy-card.d.ts +11 -0
- package/dist/boards/busy-card.d.ts.map +1 -0
- package/dist/boards/busy-card.js +15 -0
- package/dist/boards/busy-card.js.map +1 -0
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +18 -4
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/index.d.ts +2 -1
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +3 -2
- package/dist/boards/intake-dry-run.d.ts +109 -0
- package/dist/boards/intake-dry-run.d.ts.map +1 -0
- package/dist/boards/intake-dry-run.js +158 -0
- package/dist/boards/intake-dry-run.js.map +1 -0
- package/dist/boards/intake-lookup.d.ts +32 -0
- package/dist/boards/intake-lookup.d.ts.map +1 -0
- package/dist/boards/intake-lookup.js +12 -0
- package/dist/boards/intake-lookup.js.map +1 -0
- package/dist/boards/intake-order.d.ts +32 -0
- package/dist/boards/intake-order.d.ts.map +1 -0
- package/dist/boards/intake-order.js +60 -0
- package/dist/boards/intake-order.js.map +1 -0
- package/dist/boards/intake-routing.d.ts +246 -35
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +437 -52
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/reroute.d.ts +7 -3
- package/dist/boards/reroute.d.ts.map +1 -1
- package/dist/boards/reroute.js +21 -4
- package/dist/boards/reroute.js.map +1 -1
- package/dist/boards/semantics.d.ts +8 -28
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +7 -39
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/work-routes.d.ts +31 -11
- package/dist/boards/work-routes.d.ts.map +1 -1
- package/dist/boards/work-routes.js +104 -20
- package/dist/boards/work-routes.js.map +1 -1
- package/dist/factory.d.ts +27 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +32 -18
- package/dist/factory.js.map +1 -1
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -2
- package/dist/integrations/base.d.ts +9 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/dependabot/rules.d.ts.map +1 -1
- package/dist/integrations/dependabot/rules.js +2 -6
- package/dist/integrations/dependabot/rules.js.map +1 -1
- package/dist/integrations/github/commits.d.ts +0 -21
- package/dist/integrations/github/commits.d.ts.map +1 -1
- package/dist/integrations/github/commits.js +1 -24
- package/dist/integrations/github/commits.js.map +1 -1
- package/dist/integrations/github/default-rules.d.ts +22 -1
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +23 -5
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/intake-lookup.d.ts +16 -0
- package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
- package/dist/integrations/github/intake-lookup.js +76 -0
- package/dist/integrations/github/intake-lookup.js.map +1 -0
- package/dist/integrations/github/integration.d.ts +20 -6
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +23 -12
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/review-status-reporter.js +1 -1
- package/dist/integrations/github/routes.d.ts +1 -11
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +20 -517
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +12 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +275 -38
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +30 -4
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +19 -3
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/discovery.d.ts +1 -1
- package/dist/integrations/gitlab/discovery.js +1 -1
- package/dist/integrations/gitlab/discovery.js.map +1 -1
- package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
- package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
- package/dist/integrations/gitlab/intake-lookup.js +85 -0
- package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
- package/dist/integrations/gitlab/integration.d.ts +5 -0
- package/dist/integrations/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/gitlab/integration.js +21 -2
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts +0 -2
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +49 -165
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +20 -0
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +128 -19
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +5 -5
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +3 -59
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +15 -9
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/jira/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts +2 -2
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +0 -68
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +13 -7
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +2 -2
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +0 -83
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +14 -7
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +9 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +6 -6
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +23 -6
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/jira/routes.d.ts +2 -2
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +0 -69
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/integrations/pull-request-head.d.ts +1 -1
- package/dist/integrations/pull-request-head.d.ts.map +1 -1
- package/dist/integrations/pull-request-head.js +5 -0
- package/dist/integrations/pull-request-head.js.map +1 -1
- package/dist/integrations/vanta/rules.d.ts.map +1 -1
- package/dist/integrations/vanta/rules.js +2 -6
- package/dist/integrations/vanta/rules.js.map +1 -1
- package/dist/packages/_internals/workspace/dist/index.js.map +1 -1
- package/dist/routes/automation-runs.d.ts +0 -2
- package/dist/routes/automation-runs.d.ts.map +1 -1
- package/dist/routes/automation-runs.js +2 -6
- package/dist/routes/automation-runs.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +8 -1
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +33 -7
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/config.d.ts +6 -0
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +5 -2
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +1258 -5
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +588 -17
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/fs.d.ts +10 -0
- package/dist/routes/fs.d.ts.map +1 -1
- package/dist/routes/fs.js +184 -11
- package/dist/routes/fs.js.map +1 -1
- package/dist/routes/intake-check.d.ts +92 -0
- package/dist/routes/intake-check.d.ts.map +1 -0
- package/dist/routes/intake-check.js +322 -0
- package/dist/routes/intake-check.js.map +1 -0
- package/dist/routes/intake-routes.d.ts +10 -2
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +292 -11
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/mastra-gateway.d.ts.map +1 -1
- package/dist/routes/mastra-gateway.js +3 -2
- package/dist/routes/mastra-gateway.js.map +1 -1
- package/dist/routes/project-sessions.d.ts +49 -0
- package/dist/routes/project-sessions.d.ts.map +1 -0
- package/dist/routes/project-sessions.js +93 -0
- package/dist/routes/project-sessions.js.map +1 -0
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +4 -17
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/run-queue.d.ts +6 -6
- package/dist/routes/run-queue.d.ts.map +1 -1
- package/dist/routes/run-queue.js +28 -8
- package/dist/routes/run-queue.js.map +1 -1
- package/dist/routes/session-rows.d.ts +30 -0
- package/dist/routes/session-rows.d.ts.map +1 -0
- package/dist/routes/session-rows.js +98 -0
- package/dist/routes/session-rows.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +4 -8
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +8 -106
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +13 -3
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +25 -38
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-starters.d.ts +1 -0
- package/dist/routes/work-item-starters.d.ts.map +1 -1
- package/dist/routes/work-item-starters.js +14 -2
- package/dist/routes/work-item-starters.js.map +1 -1
- package/dist/routes/work-items.d.ts +13 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +87 -34
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatch-errors.js +1 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +39 -7
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +362 -127
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +69 -1
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +151 -5
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/processor.d.ts.map +1 -1
- package/dist/rules/processor.js +1 -6
- package/dist/rules/processor.js.map +1 -1
- package/dist/rules/review-source-tool.js +1 -1
- package/dist/rules/rule-group.d.ts +18 -1
- package/dist/rules/rule-group.d.ts.map +1 -1
- package/dist/rules/rule-group.js +52 -8
- package/dist/rules/rule-group.js.map +1 -1
- package/dist/rules/run-bearing.d.ts +8 -0
- package/dist/rules/run-bearing.d.ts.map +1 -0
- package/dist/rules/run-bearing.js +11 -0
- package/dist/rules/run-bearing.js.map +1 -0
- package/dist/rules/start-coordinator.d.ts +2 -3
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +27 -35
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +2 -1
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +16 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +34 -12
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +18 -5
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +2 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/update-fold.d.ts +32 -0
- package/dist/rules/update-fold.d.ts.map +1 -0
- package/dist/rules/update-fold.js +60 -0
- package/dist/rules/update-fold.js.map +1 -0
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +54 -6
- package/dist/rules/validation.js.map +1 -1
- package/dist/session/resource-migration.d.ts.map +1 -1
- package/dist/session/resource-migration.js +2 -3
- package/dist/session/resource-migration.js.map +1 -1
- package/dist/session/run-audit.d.ts +9 -0
- package/dist/session/run-audit.d.ts.map +1 -1
- package/dist/session/run-audit.js +9 -1
- package/dist/session/run-audit.js.map +1 -1
- package/dist/session/self-review-gate.d.ts +26 -2
- package/dist/session/self-review-gate.d.ts.map +1 -1
- package/dist/session/self-review-gate.js +60 -10
- package/dist/session/self-review-gate.js.map +1 -1
- package/dist/session/session-row-query.d.ts +25 -0
- package/dist/session/session-row-query.d.ts.map +1 -0
- package/dist/session/session-row-query.js +47 -0
- package/dist/session/session-row-query.js.map +1 -0
- package/dist/session/session-row-status.d.ts +16 -0
- package/dist/session/session-row-status.d.ts.map +1 -0
- package/dist/session/session-row-status.js +14 -0
- package/dist/session/session-row-status.js.map +1 -0
- package/dist/session/session-row-view.d.ts +14 -0
- package/dist/session/session-row-view.d.ts.map +1 -0
- package/dist/session/session-row-view.js +125 -0
- package/dist/session/session-row-view.js.map +1 -0
- package/dist/session/session-rows.d.ts +46 -0
- package/dist/session/session-rows.d.ts.map +1 -0
- package/dist/session/session-rows.js +232 -0
- package/dist/session/session-rows.js.map +1 -0
- package/dist/session/session-threads.d.ts.map +1 -1
- package/dist/session/session-threads.js +1 -0
- package/dist/session/session-threads.js.map +1 -1
- package/dist/session/source-control-tools.d.ts +14 -7
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +10 -2
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/work-item-repository.d.ts +44 -0
- package/dist/session/work-item-repository.d.ts.map +1 -1
- package/dist/session/work-item-repository.js +80 -1
- package/dist/session/work-item-repository.js.map +1 -1
- package/dist/session/work-item-state-processor.d.ts.map +1 -1
- package/dist/session/work-item-state-processor.js +44 -8
- package/dist/session/work-item-state-processor.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +2 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +3 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +162 -14
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +415 -41
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts +6 -0
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +93 -3
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +11 -10
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +30 -65
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/integrations/base.d.ts +0 -2
- package/dist/storage/domains/integrations/base.d.ts.map +1 -1
- package/dist/storage/domains/integrations/base.js +0 -6
- package/dist/storage/domains/integrations/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +19 -22
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +0 -10
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +6 -21
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +1 -6
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +49 -53
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +152 -156
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +3 -2
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +4 -2
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.d.ts +12 -3
- package/dist/storage/domains/work-items/work-item-schema.d.ts.map +1 -1
- package/dist/storage/domains/work-items/work-item-schema.js +12 -3
- package/dist/storage/domains/work-items/work-item-schema.js.map +1 -1
- package/dist/storage/legacy-collections.d.ts +9 -0
- package/dist/storage/legacy-collections.d.ts.map +1 -0
- package/dist/storage/legacy-collections.js +17 -0
- package/dist/storage/legacy-collections.js.map +1 -0
- package/dist/storage/probed-list.d.ts +11 -0
- package/dist/storage/probed-list.d.ts.map +1 -0
- package/dist/storage/probed-list.js +52 -0
- package/dist/storage/probed-list.js.map +1 -0
- package/dist/tools/audit-events-tool.d.ts +2 -2
- package/dist/tools/read-tools.d.ts +0 -3
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +4 -42
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +5 -9
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +3 -0
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +8 -4
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-item-branch.d.ts +4 -0
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +7 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-context-sessions.d.ts +50 -0
- package/dist/work-items/card-context-sessions.d.ts.map +1 -0
- package/dist/work-items/card-context-sessions.js +84 -0
- package/dist/work-items/card-context-sessions.js.map +1 -0
- package/dist/work-items/change-requests.d.ts +87 -0
- package/dist/work-items/change-requests.d.ts.map +1 -0
- package/dist/work-items/change-requests.js +134 -0
- package/dist/work-items/change-requests.js.map +1 -0
- package/dist/work-items/create-work-item.d.ts +7 -2
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +44 -13
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/list-related-cards.d.ts.map +1 -1
- package/dist/work-items/list-related-cards.js +1 -1
- package/dist/work-items/list-related-cards.js.map +1 -1
- package/dist/work-items/providers/github.d.ts.map +1 -1
- package/dist/work-items/providers/github.js +1 -0
- package/dist/work-items/providers/github.js.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +1 -3
- package/dist/workspace.js.map +1 -1
- package/factory-skills/configure-factory-rules/SKILL.md +2 -2
- package/factory-skills/factory-build/SKILL.md +1 -1
- package/factory-skills/factory-plan/SKILL.md +5 -3
- package/factory-skills/factory-self-review/SKILL.md +2 -0
- package/factory-skills/factory-triage/SKILL.md +1 -1
- package/package.json +10 -10
- package/dist/session/filesystem-capture.d.ts +0 -50
- package/dist/session/filesystem-capture.d.ts.map +0 -1
- package/dist/session/filesystem-capture.js +0 -229
- package/dist/session/filesystem-capture.js.map +0 -1
- package/dist/storage/domains/filesystem/base.d.ts +0 -30
- package/dist/storage/domains/filesystem/base.d.ts.map +0 -1
- package/dist/storage/domains/filesystem/base.js +0 -78
- package/dist/storage/domains/filesystem/base.js.map +0 -1
|
@@ -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 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 expectedBindingId: input.expectedBindingId,\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,eAAe;CACf,iBAAiB;CACjB,cAAc;CACd,aAAa;AACf;AA4EA,MAAM,4BAA4B;AAElC,SAAS,uBAAuB,EAC9B,aACA,OACA,aACA,UAC+D;CAC/D,IAAI,OAAO,OAAO;CAElB,IAAI;CACJ,MAAM,aAAa,YAAY;EAC7B,IAAI;GACF,MAAM,YAAY;GAClB;EACF,SAAS,OAAO;GAEd,MAAM,UAAU,OAAO,KAAK;GAC5B,MAAM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KAAK,gBAAgB,KAAK,mBAC1B,IAAI,gBAAgB;GAClB,MAAM,KAAK;GACX,UAAU,KAAK,QAAQ;GACvB,WAAW,OAAM,QAAO,KAAK,WAAW,UAAU,CAAC,EAAE,aAAa,GAAG;GACrE,qBAAqB,KAAK;EAC5B,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,IAAI,eAAe;GACjB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,eAAe,KAAK;GACpB,cAAc,KAAK,cAAc;GACjC,aAAa,KAAK,QAAQ;GAC1B;GACA;GACA,cAAc,KAAK;GACnB,UAAU,KAAK;EACjB,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,gBAAgB,KAAK,eAC1B,IAAI,YAAY;GACd,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,SAAS,KAAK,aAAa;GAC3B,QAAQ,KAAK,aAAa;EAC5B,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,gBAAgB,KAAK,eAC1B,IAAI,kBAAkB;GACpB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,SAAS,KAAK,aAAa;GAC3B,QAAQ,KAAK,aAAa;EAC5B,CAAC,CAAC,CAAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,yBAAyB;GACvB,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"}
|
|
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 type { ForcedIntakeEvaluator } from '../boards/intake-routing.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 type { NotRoutedLookup } from '../rules/event-rules.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 { repositoryChosenByRun, resolveRunRepository } 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 { IntakeEvaluator, 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 { 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 { createProjectSessionsReader } from './project-sessions.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 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 /** Forces an evaluator on every project; without it each project uses its own setting. */\n intakeEvaluator?: IntakeEvaluator;\n /** What forced `intakeEvaluator`. */\n intakeEvaluatorSource?: ForcedIntakeEvaluator['source'];\n /** Stored boards and their cache; mounts the board management routes when present. */\n storedBoards?: {\n storage: StoredBoardsStorage;\n cache: ProjectBoardCache;\n };\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; interactive: { 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; a card that names no repository stays in it.\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 // A card that names no repository keeps a retry in its role session's\n // repository, else starts in the environment's first one; its agent\n // determines which repository the card belongs to. An explicit signal is\n // never overridden.\n const repository = await resolveRunRepository({\n sourceControl,\n orgId: input.record.orgId,\n factoryProjectId: input.record.factoryProjectId,\n item: input.item,\n linearRepositoryMap: intakeConfig?.linear?.repositoryByLinearProject,\n ...(boundSession ? { boundProjectRepositoryId: boundSession.projectRepositoryId } : {}),\n });\n if (repository.status !== 'resolved') {\n throw new FactoryDispatchError('source_repository_ambiguous', repository.hint);\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. A session may work on a card outside its own repository\n // only when a run recorded that repository on a card that named none.\n const approver = input.record.approvedBy ?? undefined;\n if (\n boundSession &&\n boundSession.projectRepositoryId !== repository.projectRepositoryId &&\n !repositoryChosenByRun(input.item, repository.slug)\n ) {\n throw new FactoryDispatchError(\n 'source_repository_ambiguous',\n `The existing session is bound to a different repository than ${repository.slug}. Set the card's repository back, or end that session and retry.`,\n );\n }\n // The session is filed under the card's repository, or the environment's\n // first one when the card names none: the sandbox holds every environment\n // repository, but the coordinator, the PR tools and the subscriptions\n // follow the session's link.\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 expectedBindingId: input.expectedBindingId,\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 /** Which items intake turned away, so integrations run intake again when one changes. */\n notRouted?: NotRoutedLookup;\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 ...(deps.notRouted ? { notRouted: deps.notRouted } : {}),\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 const projectSessions = createProjectSessionsReader({\n sourceControls,\n ...(deps.users ? { users: deps.users } : {}),\n ...(deps.factoryReady ? { workItems: deps.domains.workItems } : {}),\n });\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 ...(deps.storedBoards ? { notRouted: deps.storedBoards.storage } : {}),\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 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 projectSessions,\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 ...(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 ...integrationRoutes,\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 intakeEvaluator: deps.intakeEvaluator,\n queueHealth: deps.domains.queueHealth,\n transitionService,\n startCoordinator,\n liveSessions: deps.liveSessions,\n runSlots: deps.runSlots,\n projectSessions,\n activeRuns: () => deps.controller.listActiveThreadRuns(),\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 intakeEvaluator: deps.intakeEvaluator,\n intakeEvaluatorSource: deps.intakeEvaluatorSource,\n intakeLookups: (deps.integrations ?? []).flatMap(({ integration, ready }) =>\n ready && integration.intakeLookup ? [integration.intakeLookup] : [],\n ),\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 boards: deps.boardRegistry,\n })\n : []),\n ];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAM,2BAA2B;CAC/B,eAAe;CACf,wBAAwB;C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AAC,OAAO,IACV,CAAC;EACL,GAAI,KAAK,eACL,yBAAyB;GACvB,MAAM,KAAK;GACX,OAAO,KAAK;GACZ,UAAU,KAAK,QAAQ;GACvB,WAAW,KAAK,QAAQ;GACxB,QAAQ,KAAK;EACf,CAAC,IACD,CAAC;CACP;AACF"}
|
|
@@ -16,6 +16,7 @@ export declare const CARD_DECISION_STATUSES: readonly ['pending', 'proposed', 'l
|
|
|
16
16
|
export declare const CARD_DECISION_PAGE_SIZE = 50;
|
|
17
17
|
/** The cards whose newest decision past proposal failed: a proposal waits on a person, it is not the run's state. */
|
|
18
18
|
export declare function cardsWithFailedRun(decisions: readonly Pick<FactoryDeferredDecisionRecord, 'workItemId' | 'status'>[]): Set<string>;
|
|
19
|
+
export declare function cardsAwaitingPerson(decisions: readonly Pick<FactoryDeferredDecisionRecord, 'workItemId' | 'status'>[]): Set<string>;
|
|
19
20
|
/**
|
|
20
21
|
* Count the cards behind each starter. `cards` are the project's cards as storage holds them,
|
|
21
22
|
* `failedCardIds` the cards whose run failed ({@link cardsWithFailedRun}).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"work-item-starters.d.ts","sourceRoot":"","sources":["../../src/routes/work-item-starters.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,KAAK,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAE7B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAGzD,OAAO,KAAK,EAAE,IAAI,EAAE,6BAA6B,EAAE,MAAM,uCAAuC,CAAC;AAIjG,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAErE,MAAM,MAAM,gBAAgB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,8BAA8B,CAAC,CAAC;AAE9E;;;GAGG;AACH,eAAO,MAAM,sBAAsB,YAAI,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAU,CAAC;A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ED,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,SAAS,IAAI,CAAC,6BAA6B,EAAE,YAAY,GAAG,QAAQ,CAAC,EAAE,GACjF,GAAG,CAAC,MAAM,CAAC,CAUb;AAyED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,EAC/B,KAAK,EACL,KAAK,EACL,aAAa,EACb,GAAG,GACJ,EAAE;IACD,KAAK,EAAE,cAAc,GAAG,SAAS,CAAC;IAClC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;IACvB,aAAa,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACnC,GAAG,EAAE,MAAM,CAAC;CACb,GAAG,gBAAgB,CAiFnB"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import "../boards/index.js";
|
|
2
|
-
import {
|
|
2
|
+
import { isPullRequestCard } from "../work-items/change-requests.js";
|
|
3
|
+
import { boardFlow, boardForWorkItem } from "../boards/semantics.js";
|
|
3
4
|
import { workItemBranchSource } from "../work-item-branch.js";
|
|
4
5
|
import { sourceMetadata } from "../work-items/card-facts.js";
|
|
5
6
|
import { metadataLabels } from "../work-items/card-labels.js";
|
|
@@ -41,6 +42,17 @@ function cardsWithFailedRun(decisions) {
|
|
|
41
42
|
}
|
|
42
43
|
return failed;
|
|
43
44
|
}
|
|
45
|
+
function cardsAwaitingPerson(decisions) {
|
|
46
|
+
const proposed = /* @__PURE__ */ new Set();
|
|
47
|
+
const withEffect = /* @__PURE__ */ new Set();
|
|
48
|
+
for (const { workItemId, status } of decisions) {
|
|
49
|
+
if (workItemId === null) continue;
|
|
50
|
+
(status === "proposed" ? proposed : withEffect).add(workItemId);
|
|
51
|
+
}
|
|
52
|
+
const awaiting = cardsWithFailedRun(decisions);
|
|
53
|
+
for (const workItemId of proposed) if (!withEffect.has(workItemId)) awaiting.add(workItemId);
|
|
54
|
+
return awaiting;
|
|
55
|
+
}
|
|
44
56
|
function isPullRequest(card) {
|
|
45
57
|
return isPullRequestCard({ source: workItemBranchSource(card.externalSource) });
|
|
46
58
|
}
|
|
@@ -147,6 +159,6 @@ function workItemStarters({ board, cards, failedCardIds, now }) {
|
|
|
147
159
|
};
|
|
148
160
|
return starters;
|
|
149
161
|
}
|
|
150
|
-
export { CARD_DECISION_PAGE_SIZE, CARD_DECISION_STATUSES, cardsWithFailedRun, workItemStarters };
|
|
162
|
+
export { CARD_DECISION_PAGE_SIZE, CARD_DECISION_STATUSES, cardsAwaitingPerson, cardsWithFailedRun, workItemStarters };
|
|
151
163
|
|
|
152
164
|
//# sourceMappingURL=work-item-starters.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"work-item-starters.js","names":[],"sources":["../../src/routes/work-item-starters.ts"],"sourcesContent":["/**\n * What the draft page's starter buttons count: each number is the cards one button would act on,\n * read off the project's default board. The page words the buttons; the rules for which cards\n * count live here, so the page never downloads the board to count them.\n */\n\nimport type { z } from 'zod';\n\nimport type { InstalledBoard } from '../boards/index.js';\nimport { boardFlow, boardForWorkItem, isPullRequestCard } from '../boards/index.js';\nimport type { FactoryRuleBoardFlow } from '../rules/types.js';\nimport type { Card, FactoryDeferredDecisionRecord } from '../storage/domains/work-items/base.js';\nimport { workItemBranchSource } from '../work-item-branch.js';\nimport { sourceMetadata } from '../work-items/card-facts.js';\nimport { metadataLabels } from '../work-items/card-labels.js';\nimport type { workItemStartersResponseSchema } from './contracts.js';\n\nexport type WorkItemStarters = z.infer<typeof workItemStartersResponseSchema>;\n\n/**\n * The decisions a board's cards show their run state from: one page of these statuses, newest\n * first. Failures older than that page are not counted, on the cards or here.\n */\nexport const CARD_DECISION_STATUSES = ['pending', 'proposed', 'leased', 'retry', 'failed'] as const;\nexport const CARD_DECISION_PAGE_SIZE = 50;\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** A pull request waiting longer than this is stale rather than waiting for review. */\nconst REVIEW_HORIZON_MS = 30 * DAY_MS;\n\n/** Labels GitHub ships with every repository: they say what kind of issue it is, not which area. */\nconst GITHUB_TYPE_LABELS = [\n 'bug',\n 'documentation',\n 'duplicate',\n 'enhancement',\n 'good first issue',\n 'help wanted',\n 'invalid',\n 'question',\n 'wontfix',\n];\n\n/** The cards whose newest decision past proposal failed: a proposal waits on a person, it is not the run's state. */\nexport function cardsWithFailedRun(\n decisions: readonly Pick<FactoryDeferredDecisionRecord, 'workItemId' | 'status'>[],\n): Set<string> {\n const settled = new Set<string>();\n const failed = new Set<string>();\n for (const { workItemId, status } of decisions) {\n // A decision about no card says nothing of a card's run.\n if (workItemId === null || status === 'proposed' || settled.has(workItemId)) continue;\n settled.add(workItemId);\n if (status === 'failed') failed.add(workItemId);\n }\n return failed;\n}\n\nfunction isPullRequest(card: Card): boolean {\n return isPullRequestCard({ source: workItemBranchSource(card.externalSource) });\n}\n\n/** An open pull request that is not a draft. A source that reports no state is read off the card: `finished` says it sits in a terminal phase. */\nfunction isOpenPullRequest(facts: Record<string, unknown>, finished: boolean): boolean {\n if (facts.state === 'merged' || facts.merged === true || facts.state === 'closed') return false;\n if (facts.state !== 'open' && finished) return false;\n return facts.draft !== true;\n}\n\nfunction openedAt(card: Card, { sourceCreatedAt }: Record<string, unknown>): number {\n const opened = typeof sourceCreatedAt === 'string' ? Date.parse(sourceCreatedAt) : Number.NaN;\n return Number.isNaN(opened) ? card.createdAt.getTime() : opened;\n}\n\n/** A review verdict given on an earlier head no longer speaks for the pull request. */\nfunction verdictOutdated({ reviewedHeadSha, pullRequestHeadSha }: Record<string, unknown>): boolean {\n return (\n typeof reviewedHeadSha === 'string' &&\n typeof pullRequestHeadSha === 'string' &&\n reviewedHeadSha.toLowerCase() !== pullRequestHeadSha.toLowerCase()\n );\n}\n\n/** The seats of a board's loop the starters ask about. */\ninterface StarterSeats {\n /** The phase that triages a card and the context its session is kept under. */\n triage?: { phase: string; context: string };\n /** The context that plans and builds. */\n planner?: string;\n /** The phase that plans before the build, when the board has one. */\n planPhase?: string;\n /** The working phases, in declaration order. */\n working: string[];\n}\n\nfunction starterSeats(board: InstalledBoard, flow: FactoryRuleBoardFlow): StarterSeats {\n const working = Object.keys(board.phases).filter(phase => board.phaseKind(phase) === 'working');\n const triageContext = flow.triage === undefined ? undefined : board.roleForPhase(flow.triage);\n const build = flow.build;\n return {\n working,\n ...(flow.triage !== undefined && triageContext !== undefined\n ? { triage: { phase: flow.triage, context: triageContext } }\n : {}),\n ...(flow.buildRole !== undefined ? { planner: flow.buildRole } : {}),\n ...(build !== undefined\n ? {\n planPhase: working.find(\n phase =>\n phase !== build && board.roleForPhase(phase) === flow.buildRole && board.allowsTransition(phase, build),\n ),\n }\n : {}),\n };\n}\n\n/**\n * Whether a triaged card resting in the first phase waits on a person's decision: its next move\n * is still triage, because no later working phase has held it.\n */\nfunction awaitsTriageDecision(board: InstalledBoard, seats: StarterSeats, card: Card): boolean {\n const { triage } = seats;\n if (!triage || card.sessions[triage.context] === undefined) return false;\n const deepest = seats.working.findLast(phase => card.stageHistory.some(entry => entry.stage === phase));\n if (deepest === undefined) return true;\n const resume = board.allowsTransition(board.initialPhase, deepest) ? deepest : (seats.planPhase ?? deepest);\n return resume === triage.phase;\n}\n\n/**\n * Count the cards behind each starter. `cards` are the project's cards as storage holds them,\n * `failedCardIds` the cards whose run failed ({@link cardsWithFailedRun}).\n */\nexport function workItemStarters({\n board,\n cards,\n failedCardIds,\n now,\n}: {\n board: InstalledBoard | undefined;\n cards: readonly Card[];\n failedCardIds: ReadonlySet<string>;\n now: number;\n}): WorkItemStarters {\n const starters: WorkItemStarters = {\n failed: 0,\n changesRequested: 0,\n review: { count: 0 },\n undecided: 0,\n untriaged: 0,\n unplannedBugs: 0,\n stale: 0,\n };\n if (!board) return starters;\n\n const flow = boardFlow(board);\n const seats = starterSeats(board, flow);\n const firstPhase = Object.keys(board.phases)[0];\n const triagePhase = flow.triage;\n const horizon = now - REVIEW_HORIZON_MS;\n const areas = new Map<string, number>();\n let oldestOpenedAt = Number.POSITIVE_INFINITY;\n\n for (const card of cards) {\n // Finished is judged by the default board's terminal phases for every card, as the buttons always have.\n const finished = card.stages.some(stage => board.isTerminal(stage));\n if (failedCardIds.has(card.id) && !finished) starters.failed += 1;\n if (boardForWorkItem(card) !== board.id) continue;\n\n // A card in none of the board's phases rests in the first one when that is where cards start.\n const resting =\n card.stages.includes(board.initialPhase) ||\n (board.initialPhase === firstPhase && !card.stages.some(stage => Object.hasOwn(board.phases, stage)));\n\n if (isPullRequest(card)) {\n const facts = sourceMetadata(card);\n if (!isOpenPullRequest(facts, finished)) continue;\n // Factory's verdict sits on the card, over what the source reports.\n const verdict = { ...card.workItem.metadata, ...card.metadata };\n if (\n verdict.factoryAuthored === true &&\n verdict.reviewVerdict === 'request changes' &&\n !verdictOutdated(verdict)\n ) {\n starters.changesRequested += 1;\n }\n if (!resting) continue;\n const opened = openedAt(card, facts);\n if (opened < horizon) {\n starters.stale += 1;\n } else {\n starters.review.count += 1;\n oldestOpenedAt = Math.min(oldestOpenedAt, opened);\n }\n continue;\n }\n\n if (resting && seats.triage) {\n if (card.sessions[seats.triage.context] === undefined) starters.untriaged += 1;\n else if (awaitsTriageDecision(board, seats, card)) starters.undecided += 1;\n }\n\n const notStarted = resting || (triagePhase !== undefined && card.stages.includes(triagePhase));\n if (!notStarted) continue;\n const labels = metadataLabels(sourceMetadata(card));\n if (\n seats.planner !== undefined &&\n labels.some(label => label.toLowerCase() === 'bug') &&\n card.sessions[seats.planner] === undefined &&\n // Cards planned before planning moved into the build context hold their planner under `plan`.\n card.sessions.plan === undefined\n ) {\n starters.unplannedBugs += 1;\n }\n for (const label of labels) {\n if (label.includes(':') || GITHUB_TYPE_LABELS.includes(label.toLowerCase())) continue;\n areas.set(label, (areas.get(label) ?? 0) + 1);\n }\n }\n\n if (starters.review.count > 0) starters.review.oldestOpenedAt = new Date(oldestOpenedAt).toISOString();\n const [largest] = [...areas].sort(([a, x], [b, y]) => y - x || a.localeCompare(b));\n if (largest) starters.sweep = { area: largest[0], count: largest[1] };\n return starters;\n}\n"],"mappings":";;;;;;;;;;A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,SAAS,iBAAiB;EAE5B,KAAK,MAAM,SAAS,QAAQ;GAC1B,IAAI,MAAM,SAAS,GAAG,KAAK,mBAAmB,SAAS,MAAM,YAAY,CAAC,GAAG;GAC7E,MAAM,IAAI,QAAQ,MAAM,IAAI,KAAK,KAAK,KAAK,CAAC;EAC9C;CACF;CAEA,IAAI,SAAS,OAAO,QAAQ,GAAG,SAAS,OAAO,iBAAiB,IAAI,KAAK,cAAc,CAAC,CAAC,YAAY;CACrG,MAAM,CAAC,WAAW,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,OAAO,IAAI,KAAK,EAAE,cAAc,CAAC,CAAC;CACjF,IAAI,SAAS,SAAS,QAAQ;EAAE,MAAM,QAAQ;EAAI,OAAO,QAAQ;CAAG;CACpE,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"work-item-starters.js","names":[],"sources":["../../src/routes/work-item-starters.ts"],"sourcesContent":["/**\n * What the draft page's starter buttons count: each number is the cards one button would act on,\n * read off the project's default board. The page words the buttons; the rules for which cards\n * count live here, so the page never downloads the board to count them.\n */\n\nimport type { z } from 'zod';\n\nimport type { InstalledBoard } from '../boards/index.js';\nimport { boardFlow, boardForWorkItem, isPullRequestCard } from '../boards/index.js';\nimport type { FactoryRuleBoardFlow } from '../rules/types.js';\nimport type { Card, FactoryDeferredDecisionRecord } from '../storage/domains/work-items/base.js';\nimport { workItemBranchSource } from '../work-item-branch.js';\nimport { sourceMetadata } from '../work-items/card-facts.js';\nimport { metadataLabels } from '../work-items/card-labels.js';\nimport type { workItemStartersResponseSchema } from './contracts.js';\n\nexport type WorkItemStarters = z.infer<typeof workItemStartersResponseSchema>;\n\n/**\n * The decisions a board's cards show their run state from: one page of these statuses, newest\n * first. Failures older than that page are not counted, on the cards or here.\n */\nexport const CARD_DECISION_STATUSES = ['pending', 'proposed', 'leased', 'retry', 'failed'] as const;\nexport const CARD_DECISION_PAGE_SIZE = 50;\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n/** A pull request waiting longer than this is stale rather than waiting for review. */\nconst REVIEW_HORIZON_MS = 30 * DAY_MS;\n\n/** Labels GitHub ships with every repository: they say what kind of issue it is, not which area. */\nconst GITHUB_TYPE_LABELS = [\n 'bug',\n 'documentation',\n 'duplicate',\n 'enhancement',\n 'good first issue',\n 'help wanted',\n 'invalid',\n 'question',\n 'wontfix',\n];\n\n/** The cards whose newest decision past proposal failed: a proposal waits on a person, it is not the run's state. */\nexport function cardsWithFailedRun(\n decisions: readonly Pick<FactoryDeferredDecisionRecord, 'workItemId' | 'status'>[],\n): Set<string> {\n const settled = new Set<string>();\n const failed = new Set<string>();\n for (const { workItemId, status } of decisions) {\n // A decision about no card says nothing of a card's run.\n if (workItemId === null || status === 'proposed' || settled.has(workItemId)) continue;\n settled.add(workItemId);\n if (status === 'failed') failed.add(workItemId);\n }\n return failed;\n}\n\nexport function cardsAwaitingPerson(\n decisions: readonly Pick<FactoryDeferredDecisionRecord, 'workItemId' | 'status'>[],\n): Set<string> {\n const proposed = new Set<string>();\n const withEffect = new Set<string>();\n for (const { workItemId, status } of decisions) {\n if (workItemId === null) continue;\n (status === 'proposed' ? proposed : withEffect).add(workItemId);\n }\n const awaiting = cardsWithFailedRun(decisions);\n for (const workItemId of proposed) if (!withEffect.has(workItemId)) awaiting.add(workItemId);\n return awaiting;\n}\n\nfunction isPullRequest(card: Card): boolean {\n return isPullRequestCard({ source: workItemBranchSource(card.externalSource) });\n}\n\n/** An open pull request that is not a draft. A source that reports no state is read off the card: `finished` says it sits in a terminal phase. */\nfunction isOpenPullRequest(facts: Record<string, unknown>, finished: boolean): boolean {\n if (facts.state === 'merged' || facts.merged === true || facts.state === 'closed') return false;\n if (facts.state !== 'open' && finished) return false;\n return facts.draft !== true;\n}\n\nfunction openedAt(card: Card, { sourceCreatedAt }: Record<string, unknown>): number {\n const opened = typeof sourceCreatedAt === 'string' ? Date.parse(sourceCreatedAt) : Number.NaN;\n return Number.isNaN(opened) ? card.createdAt.getTime() : opened;\n}\n\n/** A review verdict given on an earlier head no longer speaks for the pull request. */\nfunction verdictOutdated({ reviewedHeadSha, pullRequestHeadSha }: Record<string, unknown>): boolean {\n return (\n typeof reviewedHeadSha === 'string' &&\n typeof pullRequestHeadSha === 'string' &&\n reviewedHeadSha.toLowerCase() !== pullRequestHeadSha.toLowerCase()\n );\n}\n\n/** The seats of a board's loop the starters ask about. */\ninterface StarterSeats {\n /** The phase that triages a card and the context its session is kept under. */\n triage?: { phase: string; context: string };\n /** The context that plans and builds. */\n planner?: string;\n /** The phase that plans before the build, when the board has one. */\n planPhase?: string;\n /** The working phases, in declaration order. */\n working: string[];\n}\n\nfunction starterSeats(board: InstalledBoard, flow: FactoryRuleBoardFlow): StarterSeats {\n const working = Object.keys(board.phases).filter(phase => board.phaseKind(phase) === 'working');\n const triageContext = flow.triage === undefined ? undefined : board.roleForPhase(flow.triage);\n const build = flow.build;\n return {\n working,\n ...(flow.triage !== undefined && triageContext !== undefined\n ? { triage: { phase: flow.triage, context: triageContext } }\n : {}),\n ...(flow.buildRole !== undefined ? { planner: flow.buildRole } : {}),\n ...(build !== undefined\n ? {\n planPhase: working.find(\n phase =>\n phase !== build && board.roleForPhase(phase) === flow.buildRole && board.allowsTransition(phase, build),\n ),\n }\n : {}),\n };\n}\n\n/**\n * Whether a triaged card resting in the first phase waits on a person's decision: its next move\n * is still triage, because no later working phase has held it.\n */\nfunction awaitsTriageDecision(board: InstalledBoard, seats: StarterSeats, card: Card): boolean {\n const { triage } = seats;\n if (!triage || card.sessions[triage.context] === undefined) return false;\n const deepest = seats.working.findLast(phase => card.stageHistory.some(entry => entry.stage === phase));\n if (deepest === undefined) return true;\n const resume = board.allowsTransition(board.initialPhase, deepest) ? deepest : (seats.planPhase ?? deepest);\n return resume === triage.phase;\n}\n\n/**\n * Count the cards behind each starter. `cards` are the project's cards as storage holds them,\n * `failedCardIds` the cards whose run failed ({@link cardsWithFailedRun}).\n */\nexport function workItemStarters({\n board,\n cards,\n failedCardIds,\n now,\n}: {\n board: InstalledBoard | undefined;\n cards: readonly Card[];\n failedCardIds: ReadonlySet<string>;\n now: number;\n}): WorkItemStarters {\n const starters: WorkItemStarters = {\n failed: 0,\n changesRequested: 0,\n review: { count: 0 },\n undecided: 0,\n untriaged: 0,\n unplannedBugs: 0,\n stale: 0,\n };\n if (!board) return starters;\n\n const flow = boardFlow(board);\n const seats = starterSeats(board, flow);\n const firstPhase = Object.keys(board.phases)[0];\n const triagePhase = flow.triage;\n const horizon = now - REVIEW_HORIZON_MS;\n const areas = new Map<string, number>();\n let oldestOpenedAt = Number.POSITIVE_INFINITY;\n\n for (const card of cards) {\n // Finished is judged by the default board's terminal phases for every card, as the buttons always have.\n const finished = card.stages.some(stage => board.isTerminal(stage));\n if (failedCardIds.has(card.id) && !finished) starters.failed += 1;\n if (boardForWorkItem(card) !== board.id) continue;\n\n // A card in none of the board's phases rests in the first one when that is where cards start.\n const resting =\n card.stages.includes(board.initialPhase) ||\n (board.initialPhase === firstPhase && !card.stages.some(stage => Object.hasOwn(board.phases, stage)));\n\n if (isPullRequest(card)) {\n const facts = sourceMetadata(card);\n if (!isOpenPullRequest(facts, finished)) continue;\n // Factory's verdict sits on the card, over what the source reports.\n const verdict = { ...card.workItem.metadata, ...card.metadata };\n if (\n verdict.factoryAuthored === true &&\n verdict.reviewVerdict === 'request changes' &&\n !verdictOutdated(verdict)\n ) {\n starters.changesRequested += 1;\n }\n if (!resting) continue;\n const opened = openedAt(card, facts);\n if (opened < horizon) {\n starters.stale += 1;\n } else {\n starters.review.count += 1;\n oldestOpenedAt = Math.min(oldestOpenedAt, opened);\n }\n continue;\n }\n\n if (resting && seats.triage) {\n if (card.sessions[seats.triage.context] === undefined) starters.untriaged += 1;\n else if (awaitsTriageDecision(board, seats, card)) starters.undecided += 1;\n }\n\n const notStarted = resting || (triagePhase !== undefined && card.stages.includes(triagePhase));\n if (!notStarted) continue;\n const labels = metadataLabels(sourceMetadata(card));\n if (\n seats.planner !== undefined &&\n labels.some(label => label.toLowerCase() === 'bug') &&\n card.sessions[seats.planner] === undefined &&\n // Cards planned before planning moved into the build context hold their planner under `plan`.\n card.sessions.plan === undefined\n ) {\n starters.unplannedBugs += 1;\n }\n for (const label of labels) {\n if (label.includes(':') || GITHUB_TYPE_LABELS.includes(label.toLowerCase())) continue;\n areas.set(label, (areas.get(label) ?? 0) + 1);\n }\n }\n\n if (starters.review.count > 0) starters.review.oldestOpenedAt = new Date(oldestOpenedAt).toISOString();\n const [largest] = [...areas].sort(([a, x], [b, y]) => y - x || a.localeCompare(b));\n if (largest) starters.sweep = { area: largest[0], count: largest[1] };\n return starters;\n}\n"],"mappings":";;;;;;;;;;;AAuBA,MAAa,yBAAyB;CAAC;CAAW;CAAY;CAAU;CAAS;AAAQ;AACzF,MAAa,0BAA0B;;AAIvC,MAAM,oBAAoB;;AAG1B,MAAM,qBAAqB;CACzB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAgB,mBACd,WACa;CACb,MAAM,0BAAU,IAAI,IAAY;CAChC,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,EAAE,YAAY,YAAY,WAAW;EAE9C,IAAI,eAAe,QAAQ,WAAW,cAAc,QAAQ,IAAI,UAAU,GAAG;EAC7E,QAAQ,IAAI,UAAU;EACtB,IAAI,WAAW,UAAU,OAAO,IAAI,UAAU;CAChD;CACA,OAAO;AACT;AAEA,SAAgB,oBACd,WACa;CACb,MAAM,2BAAW,IAAI,IAAY;CACjC,MAAM,6BAAa,IAAI,IAAY;CACnC,KAAK,MAAM,EAAE,YAAY,YAAY,WAAW;EAC9C,IAAI,eAAe,MAAM;EACzB,CAAC,WAAW,aAAa,WAAW,WAAA,CAAY,IAAI,UAAU;CAChE;CACA,MAAM,WAAW,mBAAmB,SAAS;CAC7C,KAAK,MAAM,cAAc,UAAU,IAAI,CAAC,WAAW,IAAI,UAAU,GAAG,SAAS,IAAI,UAAU;CAC3F,OAA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AAQ;EAAE,MAAM,QAAQ;EAAI,OAAO,QAAQ;CAAG;CACpE,OAAO;AACT"}
|
|
@@ -14,9 +14,11 @@ import type { FactoryStartCoordinator } from '../rules/start-coordinator.js';
|
|
|
14
14
|
import type { FactoryTransitionService } from '../rules/transition-service.js';
|
|
15
15
|
import type { LiveSessions } from '../session/live-sessions.js';
|
|
16
16
|
import type { AuditEmitter } from '../storage/domains/audit/domain.js';
|
|
17
|
+
import type { IntakeEvaluator } from '../storage/domains/boards/base.js';
|
|
17
18
|
import type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
18
19
|
import type { QueueHealthStorage } from '../storage/domains/queue-health/base.js';
|
|
19
20
|
import type { CreateWorkItemInput, UpdateWorkItemInput, WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
21
|
+
import type { ProjectSessionsReader } from './project-sessions.js';
|
|
20
22
|
import type { RouteDependencies } from './route.js';
|
|
21
23
|
import { Route } from './route.js';
|
|
22
24
|
export interface WorkItemRoutesDeps extends RouteDependencies {
|
|
@@ -30,6 +32,8 @@ export interface WorkItemRoutesDeps extends RouteDependencies {
|
|
|
30
32
|
boardRegistry?: BoardRegistry | ProjectBoardSource;
|
|
31
33
|
/** The project's intake routes, which place a card filed without a board. */
|
|
32
34
|
intakeRoutes?: IntakeRoutesReader;
|
|
35
|
+
/** Which evaluator places a filed card; the old `route-list` by default. */
|
|
36
|
+
intakeEvaluator?: IntakeEvaluator;
|
|
33
37
|
/** Per-project queue-health threshold config. */
|
|
34
38
|
queueHealth: QueueHealthStorage;
|
|
35
39
|
/** Governed stage-transition service. Stage moves 503 when absent. */
|
|
@@ -42,7 +46,16 @@ export interface WorkItemRoutesDeps extends RouteDependencies {
|
|
|
42
46
|
runSlots?: () => {
|
|
43
47
|
inUse: number;
|
|
44
48
|
cap: number;
|
|
49
|
+
interactive: {
|
|
50
|
+
inUse: number;
|
|
51
|
+
cap: number;
|
|
52
|
+
};
|
|
45
53
|
} | undefined;
|
|
54
|
+
projectSessions?: ProjectSessionsReader;
|
|
55
|
+
activeRuns?: () => readonly {
|
|
56
|
+
threadId: string;
|
|
57
|
+
resourceId?: string;
|
|
58
|
+
}[];
|
|
46
59
|
}
|
|
47
60
|
/** Validate an untrusted create body. Unknown keys are dropped. */
|
|
48
61
|
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;
|
|
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;AAapD,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;AAGzG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AAEzE,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,uC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