@mastra/factory 0.28.0 → 0.29.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -8
- package/dist/board-changes.d.ts +16 -0
- package/dist/board-changes.d.ts.map +1 -0
- package/dist/board-changes.js +40 -0
- package/dist/board-changes.js.map +1 -0
- package/dist/boards/index.js +2 -1
- package/dist/boards/reroute.d.ts +31 -0
- package/dist/boards/reroute.d.ts.map +1 -0
- package/dist/boards/reroute.js +71 -0
- package/dist/boards/reroute.js.map +1 -0
- package/dist/boards/semantics.d.ts +1 -3
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +1 -5
- package/dist/boards/semantics.js.map +1 -1
- package/dist/environment/repository-access.d.ts +2 -0
- package/dist/environment/repository-access.d.ts.map +1 -1
- package/dist/environment/repository-access.js +9 -4
- package/dist/environment/repository-access.js.map +1 -1
- package/dist/factory.d.ts +4 -0
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +60 -9
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +17 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/dependabot/default-rules.d.ts +38 -0
- package/dist/integrations/dependabot/default-rules.d.ts.map +1 -0
- package/dist/integrations/dependabot/default-rules.js +63 -0
- package/dist/integrations/dependabot/default-rules.js.map +1 -0
- package/dist/integrations/dependabot/rules.d.ts +42 -0
- package/dist/integrations/dependabot/rules.d.ts.map +1 -0
- package/dist/integrations/dependabot/rules.js +187 -0
- package/dist/integrations/dependabot/rules.js.map +1 -0
- package/dist/integrations/dependabot/sync.d.ts +76 -0
- package/dist/integrations/dependabot/sync.d.ts.map +1 -0
- package/dist/integrations/dependabot/sync.js +111 -0
- package/dist/integrations/dependabot/sync.js.map +1 -0
- package/dist/integrations/github/pull-request-source.js +2 -1
- package/dist/integrations/github/pull-request-source.js.map +1 -1
- package/dist/integrations/github/reconcile-worker.js +1 -1
- package/dist/integrations/github/reconcile-worker.js.map +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +7 -2
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +5 -2
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +16 -13
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts +12 -0
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +24 -3
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +2 -1
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/discovery.d.ts +16 -0
- package/dist/integrations/gitlab/discovery.d.ts.map +1 -0
- package/dist/integrations/gitlab/discovery.js +107 -0
- package/dist/integrations/gitlab/discovery.js.map +1 -0
- package/dist/integrations/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/gitlab/integration.js +1 -2
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/issue-reconciler.js +1 -0
- package/dist/integrations/gitlab/issue-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/merge-request-reconciler.js +26 -10
- package/dist/integrations/gitlab/merge-request-reconciler.js.map +1 -1
- package/dist/integrations/gitlab/reconciler.d.ts.map +1 -1
- package/dist/integrations/gitlab/reconciler.js +4 -2
- package/dist/integrations/gitlab/reconciler.js.map +1 -1
- package/dist/integrations/gitlab/reconciliation-config.d.ts +0 -1
- package/dist/integrations/gitlab/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/gitlab/reconciliation-config.js +2 -8
- package/dist/integrations/gitlab/reconciliation-config.js.map +1 -1
- package/dist/integrations/gitlab/routes.d.ts +17 -0
- package/dist/integrations/gitlab/routes.d.ts.map +1 -1
- package/dist/integrations/gitlab/routes.js +28 -22
- package/dist/integrations/gitlab/routes.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +10 -4
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +32 -8
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/integration.d.ts +2 -1
- package/dist/integrations/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/incidentio/integration.js +7 -7
- package/dist/integrations/incidentio/integration.js.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.d.ts +7 -0
- package/dist/integrations/incidentio/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/incidentio/issue-reconciler.js +36 -1
- package/dist/integrations/incidentio/issue-reconciler.js.map +1 -1
- package/dist/integrations/incidentio/reconciliation-config.d.ts +0 -1
- package/dist/integrations/incidentio/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/incidentio/reconciliation-config.js +2 -5
- package/dist/integrations/incidentio/reconciliation-config.js.map +1 -1
- package/dist/integrations/incidentio/routes.d.ts +24 -8
- package/dist/integrations/incidentio/routes.d.ts.map +1 -1
- package/dist/integrations/incidentio/routes.js +33 -35
- package/dist/integrations/incidentio/routes.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts +0 -4
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +17 -14
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/intake-discovery.d.ts +44 -0
- package/dist/integrations/intake-discovery.d.ts.map +1 -0
- package/dist/integrations/intake-discovery.js +60 -0
- package/dist/integrations/intake-discovery.js.map +1 -0
- package/dist/integrations/issue-reconcile-worker.js +1 -1
- package/dist/integrations/issue-reconcile-worker.js.map +1 -1
- package/dist/integrations/issue-reconciler.d.ts +7 -0
- package/dist/integrations/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/issue-reconciler.js +47 -12
- package/dist/integrations/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/integration.d.ts +3 -2
- package/dist/integrations/jira/integration.d.ts.map +1 -1
- package/dist/integrations/jira/integration.js +5 -7
- package/dist/integrations/jira/integration.js.map +1 -1
- package/dist/integrations/jira/issue-reconciler.d.ts +17 -1
- package/dist/integrations/jira/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/jira/issue-reconciler.js +34 -1
- package/dist/integrations/jira/issue-reconciler.js.map +1 -1
- package/dist/integrations/jira/reconciliation-config.d.ts +0 -1
- package/dist/integrations/jira/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/jira/reconciliation-config.js +2 -5
- package/dist/integrations/jira/reconciliation-config.js.map +1 -1
- package/dist/integrations/jira/routes.d.ts +0 -7
- package/dist/integrations/jira/routes.d.ts.map +1 -1
- package/dist/integrations/jira/routes.js +2 -12
- package/dist/integrations/jira/routes.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts +0 -4
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +3 -13
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/kept-cards.d.ts +49 -0
- package/dist/integrations/kept-cards.d.ts.map +1 -0
- package/dist/integrations/kept-cards.js +97 -0
- package/dist/integrations/kept-cards.js.map +1 -0
- package/dist/integrations/linear/intake-discovery.d.ts +34 -0
- package/dist/integrations/linear/intake-discovery.d.ts.map +1 -0
- package/dist/integrations/linear/intake-discovery.js +112 -0
- package/dist/integrations/linear/intake-discovery.js.map +1 -0
- package/dist/integrations/linear/integration.d.ts.map +1 -1
- package/dist/integrations/linear/integration.js +1 -4
- package/dist/integrations/linear/integration.js.map +1 -1
- package/dist/integrations/linear/issue-reconciler.d.ts +13 -4
- package/dist/integrations/linear/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/linear/issue-reconciler.js +24 -20
- package/dist/integrations/linear/issue-reconciler.js.map +1 -1
- package/dist/integrations/linear/reconciliation-config.d.ts +0 -1
- package/dist/integrations/linear/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/linear/reconciliation-config.js +2 -8
- package/dist/integrations/linear/reconciliation-config.js.map +1 -1
- package/dist/integrations/linear/routes.d.ts +0 -2
- package/dist/integrations/linear/routes.d.ts.map +1 -1
- package/dist/integrations/linear/routes.js +3 -9
- package/dist/integrations/linear/routes.js.map +1 -1
- package/dist/integrations/platform/api-client.d.ts +2 -0
- package/dist/integrations/platform/api-client.d.ts.map +1 -1
- package/dist/integrations/platform/api-client.js +6 -1
- package/dist/integrations/platform/api-client.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +8 -1
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.d.ts +17 -0
- package/dist/integrations/platform/github/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +89 -7
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +20 -1
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +54 -3
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js +1 -1
- package/dist/integrations/platform/gitlab/event-worker.js.map +1 -1
- package/dist/integrations/platform/incidentio/integration.d.ts +3 -2
- package/dist/integrations/platform/incidentio/integration.d.ts.map +1 -1
- package/dist/integrations/platform/incidentio/integration.js +7 -7
- package/dist/integrations/platform/incidentio/integration.js.map +1 -1
- package/dist/integrations/platform/jira/integration.d.ts.map +1 -1
- package/dist/integrations/platform/jira/integration.js +4 -7
- package/dist/integrations/platform/jira/integration.js.map +1 -1
- package/dist/integrations/platform/jira/routes.d.ts +0 -7
- package/dist/integrations/platform/jira/routes.d.ts.map +1 -1
- package/dist/integrations/platform/jira/routes.js +2 -12
- package/dist/integrations/platform/jira/routes.js.map +1 -1
- package/dist/integrations/platform/linear/event-worker.d.ts +2 -2
- package/dist/integrations/platform/linear/event-worker.d.ts.map +1 -1
- package/dist/integrations/platform/linear/event-worker.js +1 -1
- package/dist/integrations/platform/linear/event-worker.js.map +1 -1
- package/dist/integrations/platform/linear/integration.d.ts +1 -0
- package/dist/integrations/platform/linear/integration.d.ts.map +1 -1
- package/dist/integrations/platform/linear/integration.js +7 -7
- package/dist/integrations/platform/linear/integration.js.map +1 -1
- package/dist/integrations/platform/vanta/integration.d.ts +38 -0
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -0
- package/dist/integrations/platform/vanta/integration.js +149 -0
- package/dist/integrations/platform/vanta/integration.js.map +1 -0
- package/dist/integrations/reconciliation-config.d.ts +0 -1
- package/dist/integrations/reconciliation-config.d.ts.map +1 -1
- package/dist/integrations/reconciliation-config.js +1 -8
- package/dist/integrations/reconciliation-config.js.map +1 -1
- package/dist/integrations/slack/channel-reply-processor.js +1 -1
- package/dist/integrations/slack/channel-reply-processor.js.map +1 -1
- package/dist/integrations/startup-summary.d.ts +8 -0
- package/dist/integrations/startup-summary.d.ts.map +1 -0
- package/dist/integrations/startup-summary.js +36 -0
- package/dist/integrations/startup-summary.js.map +1 -0
- package/dist/integrations/vanta/default-rules.d.ts +34 -0
- package/dist/integrations/vanta/default-rules.d.ts.map +1 -0
- package/dist/integrations/vanta/default-rules.js +61 -0
- package/dist/integrations/vanta/default-rules.js.map +1 -0
- package/dist/integrations/vanta/rules.d.ts +40 -0
- package/dist/integrations/vanta/rules.d.ts.map +1 -0
- package/dist/integrations/vanta/rules.js +208 -0
- package/dist/integrations/vanta/rules.js.map +1 -0
- package/dist/integrations/vanta/sync.d.ts +40 -0
- package/dist/integrations/vanta/sync.d.ts.map +1 -0
- package/dist/integrations/vanta/sync.js +81 -0
- package/dist/integrations/vanta/sync.js.map +1 -0
- package/dist/linked-repositories-changed.d.ts +14 -0
- package/dist/linked-repositories-changed.d.ts.map +1 -0
- package/dist/linked-repositories-changed.js +48 -0
- package/dist/linked-repositories-changed.js.map +1 -0
- package/dist/mcp/routes.d.ts.map +1 -1
- package/dist/mcp/routes.js +1 -1
- package/dist/mcp/routes.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 +23 -2
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/contracts.d.ts +322 -0
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +202 -5
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/intake-routes.d.ts +3 -0
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +44 -0
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/knowledge.d.ts.map +1 -1
- package/dist/routes/knowledge.js +3 -2
- package/dist/routes/knowledge.js.map +1 -1
- package/dist/routes/run-queue.d.ts +17 -0
- package/dist/routes/run-queue.d.ts.map +1 -0
- package/dist/routes/run-queue.js +69 -0
- package/dist/routes/run-queue.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +1 -1
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +109 -3
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +14 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +76 -11
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/work-item-selection.d.ts +4 -5
- package/dist/routes/work-item-selection.d.ts.map +1 -1
- package/dist/routes/work-item-selection.js +11 -23
- package/dist/routes/work-item-selection.js.map +1 -1
- package/dist/routes/work-item-starters.d.ts.map +1 -1
- package/dist/routes/work-item-starters.js +4 -21
- package/dist/routes/work-item-starters.js.map +1 -1
- package/dist/routes/work-items.d.ts +5 -0
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +129 -36
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/dispatch-errors.d.ts +3 -0
- package/dist/rules/dispatch-errors.d.ts.map +1 -1
- package/dist/rules/dispatch-errors.js +5 -0
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +15 -1
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +48 -20
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/index.d.ts +2 -2
- package/dist/rules/index.d.ts.map +1 -1
- package/dist/rules/index.js +2 -2
- package/dist/rules/review-source-tool.js +2 -1
- package/dist/rules/review-source-tool.js.map +1 -1
- package/dist/rules/start-coordinator.d.ts +6 -1
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +6 -2
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +3 -2
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +71 -3
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +10 -2
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +5 -0
- package/dist/rules/validation.js.map +1 -1
- package/dist/session/factory-session.d.ts +20 -5
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +20 -6
- package/dist/session/factory-session.js.map +1 -1
- package/dist/storage/domains/audit/actions.d.ts +1 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +2 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/audit/actors.d.ts.map +1 -1
- package/dist/storage/domains/audit/actors.js +1 -1
- package/dist/storage/domains/audit/actors.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +1 -1
- package/dist/storage/domains/intake/base.js +2 -2
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts +10 -0
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +24 -2
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +32 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +54 -4
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +3 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +17 -0
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +16 -4
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +28 -1
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/timing.d.ts +8 -1
- package/dist/timing.d.ts.map +1 -1
- package/dist/timing.js +10 -2
- package/dist/timing.js.map +1 -1
- package/dist/tools/approval-tools.d.ts +20 -0
- package/dist/tools/approval-tools.d.ts.map +1 -1
- package/dist/tools/approval-tools.js +79 -30
- package/dist/tools/approval-tools.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +1 -1
- package/dist/tools/messaging-tools.d.ts.map +1 -1
- package/dist/tools/messaging-tools.js +1 -1
- package/dist/tools/messaging-tools.js.map +1 -1
- package/dist/tools/read-tools.d.ts +0 -2
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +2 -7
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/reports.d.ts +3 -0
- package/dist/tools/reports.d.ts.map +1 -1
- package/dist/tools/reports.js +3 -3
- package/dist/tools/reports.js.map +1 -1
- package/dist/tools/run-watch.d.ts +14 -2
- package/dist/tools/run-watch.d.ts.map +1 -1
- package/dist/tools/run-watch.js +24 -4
- package/dist/tools/run-watch.js.map +1 -1
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +17 -6
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/side-sessions.d.ts.map +1 -1
- package/dist/tools/side-sessions.js +1 -1
- package/dist/tools/side-sessions.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +12 -2
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-item-branch.d.ts +1 -1
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +2 -0
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/board-filter-options.d.ts +5 -0
- package/dist/work-items/board-filter-options.d.ts.map +1 -0
- package/dist/work-items/board-filter-options.js +27 -0
- package/dist/work-items/board-filter-options.js.map +1 -0
- package/dist/work-items/board-phases.d.ts +28 -0
- package/dist/work-items/board-phases.d.ts.map +1 -0
- package/dist/work-items/board-phases.js +165 -0
- package/dist/work-items/board-phases.js.map +1 -0
- package/dist/work-items/card-facts.d.ts +24 -0
- package/dist/work-items/card-facts.d.ts.map +1 -0
- package/dist/work-items/card-facts.js +75 -0
- package/dist/work-items/card-facts.js.map +1 -0
- package/dist/work-items/card-labels.d.ts +5 -0
- package/dist/work-items/card-labels.d.ts.map +1 -0
- package/dist/work-items/card-labels.js +13 -0
- package/dist/work-items/card-labels.js.map +1 -0
- package/dist/work-items/card-number.d.ts +10 -0
- package/dist/work-items/card-number.d.ts.map +1 -0
- package/dist/work-items/card-number.js +15 -0
- package/dist/work-items/card-number.js.map +1 -0
- package/dist/work-items/card-people.d.ts +25 -0
- package/dist/work-items/card-people.d.ts.map +1 -0
- package/dist/work-items/card-people.js +100 -0
- package/dist/work-items/card-people.js.map +1 -0
- package/dist/work-items/card-search-text.d.ts +4 -0
- package/dist/work-items/card-search-text.d.ts.map +1 -0
- package/dist/work-items/card-search-text.js +15 -0
- package/dist/work-items/card-search-text.js.map +1 -0
- package/dist/work-items/card-source-filters.d.ts +23 -0
- package/dist/work-items/card-source-filters.d.ts.map +1 -0
- package/dist/work-items/card-source-filters.js +25 -0
- package/dist/work-items/card-source-filters.js.map +1 -0
- package/dist/work-items/create-work-item.d.ts +0 -6
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +2 -7
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/list-related-cards.d.ts +4 -0
- package/dist/work-items/list-related-cards.d.ts.map +1 -0
- package/dist/work-items/list-related-cards.js +24 -0
- package/dist/work-items/list-related-cards.js.map +1 -0
- package/dist/work-items/search-words.d.ts +5 -0
- package/dist/work-items/search-words.d.ts.map +1 -0
- package/dist/work-items/search-words.js +12 -0
- package/dist/work-items/search-words.js.map +1 -0
- package/dist/work-items/source-external-id.d.ts +4 -0
- package/dist/work-items/source-external-id.d.ts.map +1 -0
- package/dist/work-items/source-external-id.js +9 -0
- package/dist/work-items/source-external-id.js.map +1 -0
- package/dist/workspace.d.ts.map +1 -1
- package/dist/workspace.js +92 -47
- package/dist/workspace.js.map +1 -1
- package/package.json +9 -8
|
@@ -136,13 +136,12 @@ function buildJiraRoutes(options) {
|
|
|
136
136
|
message: "Jira intake is turned off in Settings."
|
|
137
137
|
}, 404);
|
|
138
138
|
const selectedIds = selection.sourceIds ?? [];
|
|
139
|
-
const
|
|
139
|
+
const scopes = (factoryProjectId ? await scopeJiraSourcesToProject({
|
|
140
140
|
intake,
|
|
141
141
|
orgId: resolved.tenant.orgId,
|
|
142
142
|
factoryProjectId,
|
|
143
143
|
selectedIds
|
|
144
|
-
}) : null;
|
|
145
|
-
const scopes = projectScope?.scopes ?? unfilteredJiraScopes(selectedIds);
|
|
144
|
+
}) : null)?.scopes ?? unfilteredJiraScopes(selectedIds);
|
|
146
145
|
if (scopes.length === 0) return c.json({
|
|
147
146
|
issues: [],
|
|
148
147
|
nextCursor: null
|
|
@@ -165,15 +164,6 @@ function buildJiraRoutes(options) {
|
|
|
165
164
|
updatedAt: issue.updatedAt,
|
|
166
165
|
sourceId: issue.sourceId || null
|
|
167
166
|
}));
|
|
168
|
-
if (factoryProjectId && projectScope && options.ingestFactoryIssues) await options.ingestFactoryIssues({
|
|
169
|
-
orgId: resolved.tenant.orgId,
|
|
170
|
-
userId: resolved.tenant.userId,
|
|
171
|
-
factoryProjectId,
|
|
172
|
-
issues: issuePayload.map((issue) => ({
|
|
173
|
-
...issue,
|
|
174
|
-
site: null
|
|
175
|
-
}))
|
|
176
|
-
});
|
|
177
167
|
return c.json({
|
|
178
168
|
issues: issuePayload,
|
|
179
169
|
nextCursor
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/jira/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Jira intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Mirrors the Linear module minus everything OAuth: there is no\n * connect/callback flow, no state signer, and no per-org connection storage —\n * Jira credentials are deployment-global constructor config on the\n * integration instance. Every route still re-resolves the authenticated user\n * from the request and scopes intake selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildJiraRoutes` returns only `GET /web/jira/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Jira UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { JiraApiError } from './api.js';\nimport { scopeJiraSourcesToProject } from './binding-scope.js';\nimport { unfilteredJiraScopes } from './intake-jql.js';\nimport { DEPLOYMENT_CONNECTION } from './integration.js';\nimport type { JiraIntegration } from './integration.js';\nimport type { JiraRulesIngress } from './rules.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\n/**\n * Non-secret diagnostic snapshot of every Jira feature gate, mirroring the\n * Linear diagnostics shape. Only booleans — never values.\n */\nexport interface JiraFeatureDiagnostics {\n jiraConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountJiraRoutesOptions {\n /**\n * The integration instance providing REST access. Required for everything\n * beyond the disabled `status` route.\n */\n jira?: JiraIntegration;\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /**\n * Factory rules ingress for observed issues. When present, a board-scoped\n * issue listing also materializes new cards through the Jira event rules —\n * the same automatic intake Linear has.\n */\n ingestFactoryIssues?: (input: JiraRulesIngress) => Promise<unknown>;\n /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource'>;\n}\n\n/**\n * Resolve the org-scoped tenant for a Jira request. Intake selections are\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the Linear routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Jira intake requires an organization. Personal accounts cannot use Jira intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Jira pagination cursor from the query string. Cursors are\n * server-issued (`nextPageToken`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Jira.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Jira read failure to the API response for the SPA. */\nfunction jiraFetchError(c: RouteContext, err: unknown) {\n if (err instanceof JiraApiError && err.code === 'jira_auth_failed') {\n return c.json(\n {\n error: 'jira_auth_failed',\n message: 'Jira rejected the configured credentials. Check JIRA_EMAIL and JIRA_API_TOKEN.',\n },\n 409,\n );\n }\n return c.json({ error: 'jira_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Jira routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildJiraRoutes(options: MountJiraRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { jira, auth, intake, workItems } = options;\n const enabled = Boolean(jira) && auth.enabled();\n const diagnostics = (): JiraFeatureDiagnostics => ({\n jiraConfigured: Boolean(jira),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: true,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !jira || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(jira),\n mode: 'direct',\n site: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n const site = new URL(jira.baseUrl).host;\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n organizationRequired: true,\n site,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n // Deployment-global credentials: configured means ready — there is no\n // per-org connection step like Linear's OAuth.\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n site,\n reason: 'ready',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !jira || !intake) {\n return routes;\n }\n\n // ── List the site's projects (Settings intake-source picker) ────────────\n routes.push(\n registerApiRoute('/web/jira/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n try {\n const sources = await jira.intake.listSources(resolved.tenant);\n return c.json({\n projects: sources.map(source => ({\n id: source.id,\n name: source.name,\n key: typeof source.metadata?.key === 'string' ? source.metadata.key : null,\n })),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the site's active issues (cursor-paged) ────────────────────────\n // Respects the caller's intake config: disabled Jira intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/jira/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Jira.\n const selectedIds = selection.sourceIds ?? [];\n // A board request only ever sees the projects routed to a board of\n // that Factory project; unscoped listing stays available to callers\n // that don't view a specific board.\n const projectScope = factoryProjectId\n ? await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const scopes = projectScope?.scopes ?? unfilteredJiraScopes(selectedIds);\n if (scopes.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);\n const issuePayload = issues.map(issue => ({\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n project: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId || null,\n }));\n if (factoryProjectId && projectScope && options.ingestFactoryIssues) {\n await options.ingestFactoryIssues({\n orgId: resolved.tenant.orgId,\n userId: resolved.tenant.userId,\n factoryProjectId,\n issues: issuePayload.map(issue => ({ ...issue, site: null })),\n });\n }\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/jira/issues/:identifier', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const identifier = c.req.param('identifier');\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!ISSUE_KEY_RE.test(identifier)) return c.json({ error: 'invalid_issue_identifier' }, 400);\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048) return c.json({ error: 'invalid_issue_ref' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (projectScope.scopes.length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n const issue = await jira.intake.getIssue({ connection: DEPLOYMENT_CONNECTION, issueId: issueRef });\n // An unbound project's issue, or one in another Factory's slice that this\n // Factory never filed, reads like one that doesn't exist (as on Linear).\n const routed =\n issue?.sourceId != null &&\n projectScope.sourceIds.includes(issue.sourceId) &&\n (projectScope.takes(issue.sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issue.id },\n })));\n if (!issue || issue.identifier.toUpperCase() !== identifier.toUpperCase() || !routed) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n return c.json({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description,\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\n"],"mappings":";;;;;;;AAgCA,MAAM,UAAU;AAChB,MAAM,eAAe;;;;;;AAwCrB,eAAe,iBACb,GACA,MACiF;CACjF,MAAM,KAAK,WAAW,CAAC;CACvB,MAAM,SAAS,KAAK,OAAO,CAAC;CAC5B,IAAI,CAAC,QAAQ,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,OAAO,eAAe,GAAG,GAAG,EAAE;CACvE,IAAI,CAAC,OAAO,OACV,OAAO,EACL,UAAU,EAAE,KACV;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF,EACF;CAEF,OAAO,EAAE,QAAQ;EAAE,OAAO,OAAO;EAAO,QAAQ,OAAO;CAAO,EAAE;AAClE;;;;;;AAOA,SAAS,iBAAiB,KAAoD;CAC5E,IAAI,QAAQ,KAAA,KAAa,QAAQ,IAAI,OAAO,KAAA;CAC5C,IAAI,IAAI,SAAS,OAAO,CAAC,gBAAgB,KAAK,GAAG,GAAG,OAAO;CAC3D,OAAO;AACT;;AAGA,SAAS,eAAe,GAAiB,KAAc;CACrD,IAAI,eAAe,gBAAgB,IAAI,SAAS,oBAC9C,OAAO,EAAE,KACP;EACE,OAAO;EACP,SAAS;CACX,GACA,GACF;CAEF,OAAO,EAAE,KAAK;EAAE,OAAO;EAAqB,SAAS,eAAe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C;GACH,SAAS,KAAK;IACZ,OAAO,eAAe,MAAM,CAAC,GAAG,GAAG;GACrC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"routes.js","names":[],"sources":["../../../src/integrations/jira/routes.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for the Jira intake feature.\n *\n * Registered alongside the other `/web/*` routes, behind the host auth gate.\n * Mirrors the Linear module minus everything OAuth: there is no\n * connect/callback flow, no state signer, and no per-org connection storage —\n * Jira credentials are deployment-global constructor config on the\n * integration instance. Every route still re-resolves the authenticated user\n * from the request and scopes intake selections by the caller's org.\n *\n * When the feature is disabled (no auth, or no intake storage),\n * `buildJiraRoutes` returns only `GET /web/jira/status`, which reports\n * `enabled:false` so the SPA can cleanly hide all Jira UI.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { loose } from '../../routes/route.js';\nimport type { RouteAuth } from '../../routes/route.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport { JiraApiError } from './api.js';\nimport { scopeJiraSourcesToProject } from './binding-scope.js';\nimport { unfilteredJiraScopes } from './intake-jql.js';\nimport { DEPLOYMENT_CONNECTION } from './integration.js';\nimport type { JiraIntegration } from './integration.js';\n\ntype RouteContext = Context;\n\nconst UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\nconst ISSUE_KEY_RE = /^[A-Za-z][A-Za-z0-9_]*-\\d+$/;\n\n/**\n * Non-secret diagnostic snapshot of every Jira feature gate, mirroring the\n * Linear diagnostics shape. Only booleans — never values.\n */\nexport interface JiraFeatureDiagnostics {\n jiraConfigured: boolean;\n factoryAuthEnabled: boolean;\n appDbConfigured: boolean;\n}\n\nexport interface MountJiraRoutesOptions {\n /**\n * The integration instance providing REST access. Required for everything\n * beyond the disabled `status` route.\n */\n jira?: JiraIntegration;\n /** Host auth seam. Intake selections are org-owned, so the feature is inert without it. */\n auth: RouteAuth;\n /**\n * Cross-integration intake selection domain. Required for the issues route's\n * project filter; when absent, only the disabled `status` route is served.\n */\n intake?: IntakeStorage;\n /** Filed cards, so a Factory keeps reading issues it filed after a label filter moves them to another slice. */\n workItems?: Pick<WorkItemsStorage, 'getByProjectSource'>;\n}\n\n/**\n * Resolve the org-scoped tenant for a Jira request. Intake selections are\n * org-owned, so it requires both a signed-in user and an organization — same\n * tenancy rules as the Linear routes.\n */\nasync function resolveOrgTenant(\n c: RouteContext,\n auth: RouteAuth,\n): Promise<{ tenant: { orgId: string; userId: string } } | { response: Response }> {\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) return { response: c.json({ error: 'unauthorized' }, 401) };\n if (!tenant.orgId) {\n return {\n response: c.json(\n {\n error: 'organization_required',\n message: 'Jira intake requires an organization. Personal accounts cannot use Jira intake.',\n },\n 403,\n ),\n };\n }\n return { tenant: { orgId: tenant.orgId, userId: tenant.userId } };\n}\n\n/**\n * Validate an opaque Jira pagination cursor from the query string. Cursors are\n * server-issued (`nextPageToken`), so anything outside a conservative\n * charset/length is rejected rather than forwarded to Jira.\n */\nfunction parseAfterCursor(raw: string | undefined): string | undefined | null {\n if (raw === undefined || raw === '') return undefined;\n if (raw.length > 512 || !/^[\\w+/=.:-]+$/.test(raw)) return null;\n return raw;\n}\n\n/** Map a Jira read failure to the API response for the SPA. */\nfunction jiraFetchError(c: RouteContext, err: unknown) {\n if (err instanceof JiraApiError && err.code === 'jira_auth_failed') {\n return c.json(\n {\n error: 'jira_auth_failed',\n message: 'Jira rejected the configured credentials. Check JIRA_EMAIL and JIRA_API_TOKEN.',\n },\n 409,\n );\n }\n return c.json({ error: 'jira_fetch_failed', message: err instanceof Error ? err.message : String(err) }, 502);\n}\n\n/**\n * Build the Jira routes as Mastra `apiRoutes`. When the feature is disabled,\n * returns only the `status` route so the SPA can detect the disabled state.\n */\nexport function buildJiraRoutes(options: MountJiraRoutesOptions): ApiRoute[] {\n const routes: ApiRoute[] = [];\n const { jira, auth, intake, workItems } = options;\n const enabled = Boolean(jira) && auth.enabled();\n const diagnostics = (): JiraFeatureDiagnostics => ({\n jiraConfigured: Boolean(jira),\n factoryAuthEnabled: auth.enabled(),\n appDbConfigured: true,\n });\n\n // The status route is always registered so the SPA can detect the disabled state.\n routes.push(\n registerApiRoute('/web/jira/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!enabled || !jira || !intake) {\n return c.json({\n enabled: false,\n configured: Boolean(jira),\n mode: 'direct',\n site: null,\n reason: 'missing_config',\n diagnostics: diagnostics(),\n });\n }\n await auth.ensureUser(loose(c));\n const tenant = auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n\n const site = new URL(jira.baseUrl).host;\n if (!tenant.orgId) {\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n organizationRequired: true,\n site,\n reason: 'organization_required',\n diagnostics: diagnostics(),\n });\n }\n\n // Deployment-global credentials: configured means ready — there is no\n // per-org connection step like Linear's OAuth.\n return c.json({\n enabled: true,\n configured: true,\n mode: 'direct',\n site,\n reason: 'ready',\n diagnostics: diagnostics(),\n });\n },\n }),\n );\n\n // Without the integration instance or the intake domain the feature can't\n // serve org-scoped data — serve only the disabled `status` route.\n if (!enabled || !jira || !intake) {\n return routes;\n }\n\n // ── List the site's projects (Settings intake-source picker) ────────────\n routes.push(\n registerApiRoute('/web/jira/projects', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n try {\n const sources = await jira.intake.listSources(resolved.tenant);\n return c.json({\n projects: sources.map(source => ({\n id: source.id,\n name: source.name,\n key: typeof source.metadata?.key === 'string' ? source.metadata.key : null,\n })),\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n // ── List the site's active issues (cursor-paged) ────────────────────────\n // Respects the caller's intake config: disabled Jira intake 404s the\n // source, and an explicit project selection narrows the issue filter.\n routes.push(\n registerApiRoute('/web/jira/issues', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const after = parseAfterCursor(c.req.query('after'));\n if (after === null) return c.json({ error: 'invalid_cursor' }, 400);\n const factoryProjectId = c.req.query('factoryProjectId');\n if (factoryProjectId && !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n\n // No projects selected means nothing is synced — don't fan out to Jira.\n const selectedIds = selection.sourceIds ?? [];\n // A board request only ever sees the projects routed to a board of\n // that Factory project; unscoped listing stays available to callers\n // that don't view a specific board.\n const projectScope = factoryProjectId\n ? await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds,\n })\n : null;\n const scopes = projectScope?.scopes ?? unfilteredJiraScopes(selectedIds);\n if (scopes.length === 0) {\n return c.json({ issues: [], nextCursor: null });\n }\n\n try {\n const { issues, nextCursor } = await jira.listActiveIssues(after, scopes);\n const issuePayload = issues.map(issue => ({\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n author: issue.author,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee,\n project: issue.source,\n labels: issue.labels,\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId || null,\n }));\n return c.json({ issues: issuePayload, nextCursor });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n routes.push(\n registerApiRoute('/web/jira/issues/:identifier', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n const resolved = await resolveOrgTenant(loose(c), auth);\n if ('response' in resolved) return resolved.response;\n\n const identifier = c.req.param('identifier');\n const factoryProjectId = c.req.query('factoryProjectId');\n const issueRef = c.req.query('issueRef');\n if (!ISSUE_KEY_RE.test(identifier)) return c.json({ error: 'invalid_issue_identifier' }, 400);\n if (!factoryProjectId || !UUID_RE.test(factoryProjectId)) {\n return c.json({ error: 'invalid_factory_project_id' }, 400);\n }\n if (!issueRef || issueRef.length > 2_048) return c.json({ error: 'invalid_issue_ref' }, 400);\n\n await intake.ensureReady();\n const config = await intake.getConfig({ orgId: resolved.tenant.orgId, integrationIds: ['jira'] });\n const selection = config.jira!;\n if (!selection.enabled) {\n return c.json({ error: 'jira_intake_disabled', message: 'Jira intake is turned off in Settings.' }, 404);\n }\n const projectScope = await scopeJiraSourcesToProject({\n intake,\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n selectedIds: selection.sourceIds ?? [],\n });\n if (projectScope.scopes.length === 0) return c.json({ error: 'issue_not_found' }, 404);\n\n try {\n const issue = await jira.intake.getIssue({ connection: DEPLOYMENT_CONNECTION, issueId: issueRef });\n // An unbound project's issue, or one in another Factory's slice that this\n // Factory never filed, reads like one that doesn't exist (as on Linear).\n const routed =\n issue?.sourceId != null &&\n projectScope.sourceIds.includes(issue.sourceId) &&\n (projectScope.takes(issue.sourceId, issue.labels) ||\n !!(await workItems?.getByProjectSource({\n orgId: resolved.tenant.orgId,\n factoryProjectId,\n source: { integrationId: 'jira', type: 'issue', externalId: issue.id },\n })));\n if (!issue || issue.identifier.toUpperCase() !== identifier.toUpperCase() || !routed) {\n return c.json({ error: 'issue_not_found' }, 404);\n }\n return c.json({\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n description: issue.description,\n });\n } catch (err) {\n return jiraFetchError(loose(c), err);\n }\n },\n }),\n );\n\n return routes;\n}\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;GAErF,IAAI;IACF,MAAM,QAAQ,MAAM,KAAK,OAAO,SAAS;KAAE,YAAY;KAAuB,SAAS;IAAS,CAAC;IAGjG,MAAM,SACJ,OAAO,YAAY,QACnB,aAAa,UAAU,SAAS,MAAM,QAAQ,MAC7C,aAAa,MAAM,MAAM,UAAU,MAAM,MAAM,KAC9C,CAAC,CAAE,MAAM,WAAW,mBAAmB;KACrC,OAAO,SAAS,OAAO;KACvB;KACA,QAAQ;MAAE,eAAe;MAAQ,MAAM;MAAS,YAAY,MAAM;KAAG;IACvE,CAAC;IACL,IAAI,CAAC,SAAS,MAAM,WAAW,YAAY,MAAM,WAAW,YAAY,KAAK,CAAC,QAC5E,OAAO,EAAE,KAAK,EAAE,OAAO,kBAAkB,GAAG,GAAG;IAEjD,OAAO,EAAE,KAAK;KACZ,YAAY,MAAM;KAClB,OAAO,MAAM;KACb,KAAK,MAAM;KACX,aAAa,MAAM;IACrB,CAAC;GACH,SAAS,KAAK;IACZ,OAAO,eAAe,MAAM,CAAC,GAAG,GAAG;GACrC;EACF;CACF,CAAC,CACH;CAEA,OAAO;AACT"}
|
|
@@ -4,7 +4,6 @@ import type { ProjectBoardSource } from '../../boards/project-boards.js';
|
|
|
4
4
|
import type { FactoryJiraRuleContext } from '../../rules/types.js';
|
|
5
5
|
import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
|
|
6
6
|
import type { WorkItemsStorage } from '../../storage/domains/work-items/base.js';
|
|
7
|
-
import type { IntegrationContext } from '../base.js';
|
|
8
7
|
import type { JiraEventRules } from './default-rules.js';
|
|
9
8
|
export interface JiraIssueIngress {
|
|
10
9
|
/** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */
|
|
@@ -57,8 +56,5 @@ export declare class JiraRules {
|
|
|
57
56
|
ingested: number;
|
|
58
57
|
}>;
|
|
59
58
|
}
|
|
60
|
-
export declare function attachJiraRules(jira: {
|
|
61
|
-
readonly rules: JiraEventRules;
|
|
62
|
-
}, context: IntegrationContext): ((input: JiraRulesIngress) => Promise<unknown>) | undefined;
|
|
63
59
|
export {};
|
|
64
60
|
//# sourceMappingURL=rules.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AASpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,KAAK,EAAE,sBAAsB,EAAuB,MAAM,sBAAsB,CAAC;AAGxF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAQ,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,KAAK,EAAE,
|
|
1
|
+
{"version":3,"file":"rules.d.ts","sourceRoot":"","sources":["../../../src/integrations/jira/rules.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AASpE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAC;AAEzE,OAAO,KAAK,EAAE,sBAAsB,EAAuB,MAAM,sBAAsB,CAAC;AAGxF,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAQ,gBAAgB,EAAE,MAAM,0CAA0C,CAAC;AACvF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAoBzD,MAAM,WAAW,gBAAgB;IAC/B,uFAAuF;IACvF,EAAE,EAAE,MAAM,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;IACnB,KAAK,EAAE,MAAM,CAAC;IACd,GAAG,EAAE,MAAM,CAAC;I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G,OAAO,CAAC;QAAE,MAAM,EAAE,aAAa,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CA4B1F;CA4HF"}
|
|
@@ -60,9 +60,10 @@ var JiraRules = class {
|
|
|
60
60
|
factoryProjectId: input.factoryProjectId
|
|
61
61
|
});
|
|
62
62
|
const itemsBySourceKey = new Map(items.map((item) => [item.externalSource?.externalId, item]));
|
|
63
|
+
const itemsByUrl = new Map(items.flatMap((item) => item.externalSource?.url ? [[item.externalSource.url, item]] : []));
|
|
63
64
|
const statuses = [];
|
|
64
65
|
for (const issue of input.issues) {
|
|
65
|
-
const relatedItem = itemsBySourceKey.get(issue.id);
|
|
66
|
+
const relatedItem = itemsBySourceKey.get(issue.id) ?? itemsByUrl.get(issue.url);
|
|
66
67
|
statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));
|
|
67
68
|
}
|
|
68
69
|
if (statuses.some((status) => status === "committed")) return {
|
|
@@ -184,17 +185,6 @@ var JiraRules = class {
|
|
|
184
185
|
return committed.status;
|
|
185
186
|
}
|
|
186
187
|
};
|
|
187
|
-
|
|
188
|
-
if (!context.runtime) return void 0;
|
|
189
|
-
const rules = new JiraRules({
|
|
190
|
-
projects: context.storage.projects,
|
|
191
|
-
storage: context.runtime.workItems,
|
|
192
|
-
configVersion: context.runtime.configVersion,
|
|
193
|
-
boards: context.runtime.boards,
|
|
194
|
-
jiraRules: jira.rules
|
|
195
|
-
});
|
|
196
|
-
return (input) => rules.ingest(input);
|
|
197
|
-
}
|
|
198
|
-
export { JiraRules, attachJiraRules, boardEventFor };
|
|
188
|
+
export { JiraRules, boardEventFor };
|
|
199
189
|
|
|
200
190
|
//# sourceMappingURL=rules.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryJiraRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport type { JiraEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: JiraRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'jira', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Jira issue per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Jira rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: 'jira.issueObserved' },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Jira rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachJiraRules(\n jira: { readonly rules: JiraEventRules },\n context: IntegrationContext,\n): ((input: JiraRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new JiraRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n jiraRules: jira.rules,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA+ChC,SAAgB,cAAc,SAAgG;CAC5H,IAAI,QAAQ,UAAU,eACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,cAAc,UAAU;CAAE;CAEjG,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;AAEA,IAAa,YAAb,MAAuB;CACQ;CAA7B,YAAY,SAA4C;EAA3B,KAAA,UAAA;CAA4B;;CAGzD,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,OAAO,OAA+E;EAE1F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EACtD,MAAM,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,KAAK,KAAK;EAGnD,MAAM,KAAK,QAAQ,QAAQ,gBAAgB;GACzC,OAAO,MAAM;GACb,kBAAkB,MAAM;GACxB,SAAS,MAAM,OAAO,KAAI,W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;EAC/B,QAAQ,QAAQ,QAAQ;EACxB,WAAW,KAAK;CAClB,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
|
|
1
|
+
{"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/jira/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport {\n boardEventHandlers,\n boardForWorkItem,\n eventBoardId,\n rulePhaseField,\n withBoardClosure,\n withIntakeTarget,\n} from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { deploymentOwnsEvent, routeEventDecision, selectEventRule, withoutRouteEvent } from '../../rules/event-rules.js';\nimport type { FactoryJiraRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { JiraEventRules } from './default-rules.js';\n\nconst RULE_TIMEOUT_MS = 5_000;\n\nasync function withRuleTimeout<T>(promise: Promise<T>): Promise<T> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timeout = setTimeout(() => reject(new Error('FACTORY_RULE_TIMEOUT')), RULE_TIMEOUT_MS);\n }),\n ]);\n } finally {\n if (timeout) clearTimeout(timeout);\n }\n}\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\nexport interface JiraIssueIngress {\n /** Stable issue reference — direct Jira id or the Platform-encoded issue reference. */\n id: string;\n identifier: string;\n title: string;\n url: string;\n state: string;\n stateType: string;\n priorityLabel: string;\n assignee: string | null;\n /** Display name of the Jira reporter, when available. */\n author: string | null;\n /** Jira project key the issue belongs to, when available. */\n project: string | null;\n /** Jira site host the issue was read from, when available. */\n site: string | null;\n labels: string[];\n createdAt: string;\n updatedAt: string;\n /** Jira source the issue was read from. */\n sourceId?: string | null;\n}\n\nexport interface JiraRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n /** The code boards, or the per-project source so a project's stored boards run its cards. */\n boards: BoardRegistry | ProjectBoardSource;\n jiraRules: JiraEventRules;\n}\n\nexport interface JiraRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n issues: JiraIssueIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/**\n * The status change a Jira sync reports: a issue seen for the first time is created, and a\n * completed or canceled one is closed for that reason. Later sightings of an open issue report none.\n */\nexport function boardEventFor(context: Pick<FactoryJiraRuleContext, 'event' | 'issue' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'issueClosed') {\n return { type: 'work_item.closed', reason: closeReason(context.issue.stateType === 'canceled') };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\nexport class JiraRules {\n constructor(private readonly options: JiraRulesOptions) {}\n\n /** The project's boards, loaded at the start of {@link ingest}. */\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: JiraRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n // A finished card may still be only in the legacy table; copy it so the issue finds it.\n await this.options.storage.copyLegacyCards({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n sources: input.issues.map(issue => ({ integrationId: 'jira', type: 'issue', externalId: issue.id })),\n });\n // The shared list is the cache itself: only the card handed on to rules is cloned.\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(items.map(item => [item.externalSource?.externalId, item]));\n // A card filed by hand from Settings › Intake holds the issue key, while the\n // sweep names the issue by its id. Its browse URL names both the site and the key.\n const itemsByUrl = new Map(\n items.flatMap(item => (item.externalSource?.url ? [[item.externalSource.url, item] as const] : [])),\n );\n const statuses: IngressStatus[] = [];\n for (const issue of input.issues) {\n // One card per Jira issue per project; other projects may file their own.\n const relatedItem = itemsBySourceKey.get(issue.id) ?? itemsByUrl.get(issue.url);\n statuses.push(await this.#ingestIssue(input, issue, relatedItem && structuredClone(relatedItem)));\n }\n if (statuses.some(status => status === 'committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.some(status => status === 'replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestIssue(\n input: JiraRulesIngress,\n issue: JiraIssueIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const ingressId = `jira:${issue.id}:${issue.updatedAt}`;\n const actor = { type: 'human' as const, id: input.userId };\n\n // Closed issues without existing work items should not create new ones.\n const isClosed = issue.stateType === 'completed' || issue.stateType === 'canceled';\n if (isClosed && !relatedItem) {\n return 'missing';\n }\n\n const event = isClosed ? 'issueClosed' : 'issueObserved';\n const context: FactoryJiraRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'jira', id: ingressId },\n cause: `jira.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'jira-issue',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(this.#boards(input), relatedItem),\n ...rulePhaseField(this.#boards(input), relatedItem),\n }\n : {}),\n ...withIntakeTarget(this.#boards(input)),\n event,\n issue,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const ownedByDeployment = deploymentOwnsEvent(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n const rule = selectEventRule(\n this.options.jiraRules,\n boardEventHandlers(this.#boards(input), eventBoardId(context), 'jira'),\n context.event,\n );\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await withRuleTimeout(Promise.resolve(rule(Object.freeze(context)))) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(\n entry,\n this.#boards(input),\n relatedItem ? boardForWorkItem(relatedItem) : undefined,\n );\n return { ...entry };\n });\n }\n } catch (error) {\n const timedOut = error instanceof Error && error.message === 'FACTORY_RULE_TIMEOUT';\n outcome = {\n status: 'rejected',\n code: timedOut ? 'timeout' : 'rule_error',\n reason: timedOut\n ? 'Factory rule evaluation timed out.'\n : error instanceof Error\n ? error.message.slice(0, 2_000)\n : 'Factory Jira rule failed.',\n };\n }\n if (ownedByDeployment) decisions = decisions.map(withoutRouteEvent);\n if (!decision && !ownedByDeployment && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId, triggerType: 'jira.issueObserved' },\n configVersion: this.options.configVersion,\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n // Nothing was persisted: re-read the item and evaluate again at its fresh revision.\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Jira rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestIssue(input, issue, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n"],"mappings":";;;;;;;AAqBA,MAAM,kBAAkB;AAExB,eAAe,gBAAmB,SAAiC;CACjE,IAAI;CACJ,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,SACA,IAAI,SAAgB,GAAG,WAAW;GAChC,UAAU,iBAAiB,uBAAO,IAAI,MAAM,sBAAsB,CAAC,GAAG,eAAe;EACvF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,SAAS,aAAa,OAAO;CACnC;AACF;AAEA,MAAM,0BAA0B;;;;;AA+ChC,SAAgB,cAAc,SAAgG;CAC5H,IAAI,QAAQ,UAAU,eACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,QAAQ,MAAM,cAAc,UAAU;CAAE;CAEjG,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;AAEA,IAAa,YAAb,MAAuB;CACQ;CAA7B,YAAY,SAA4C;EAA3B,KAAA,UAAA;CAA4B;;CAGzD,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,OAAO,OAA+E;EAE1F,IAAI,CAAC,MADiB,KAAK,QAAQ,SAAS,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAiB,CAAC,GACpF,OAAO;GAAE,QAAQ;GAAW,UAAU;EAAE;EACtD,MAAM,cAAc,KAAK,QAAQ,MAA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AC,OAAO,OAAO;GAClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';
|
|
2
|
+
import type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';
|
|
3
|
+
interface BoardScope {
|
|
4
|
+
orgId: string;
|
|
5
|
+
factoryProjectId: string;
|
|
6
|
+
}
|
|
7
|
+
/** What a background sweep reads: the projects, and each project's cards. */
|
|
8
|
+
export interface CardSource {
|
|
9
|
+
projects(): Promise<readonly FactoryProject[]>;
|
|
10
|
+
/** Shared between readers: do not mutate. */
|
|
11
|
+
cards(scope: BoardScope): Promise<readonly Card[]>;
|
|
12
|
+
}
|
|
13
|
+
/** Reads storage on every call: what a sweep uses when no {@link KeptCards} is wired. */
|
|
14
|
+
export declare function storageCards(options: {
|
|
15
|
+
projects: Pick<FactoryProjectsStorage, 'listAll'>;
|
|
16
|
+
workItems: Pick<WorkItemsStorage, 'listShared'>;
|
|
17
|
+
}): CardSource;
|
|
18
|
+
/**
|
|
19
|
+
* Keeps the cards sweeps look at in memory, so a sweep that finds nothing to
|
|
20
|
+
* change at a provider reads nothing from storage. A board is read again only
|
|
21
|
+
* after a change to it was announced through {@link changed}. There is no timed
|
|
22
|
+
* re-read, since that would wake the database; an announcement lost between
|
|
23
|
+
* replicas stays unseen until that board changes again or the process restarts.
|
|
24
|
+
*
|
|
25
|
+
* The kept cards decide what a sweep looks at, not what it writes: a sweep
|
|
26
|
+
* about to write a card reads that card first.
|
|
27
|
+
*/
|
|
28
|
+
export declare class KeptCards implements CardSource {
|
|
29
|
+
#private;
|
|
30
|
+
constructor(options: {
|
|
31
|
+
projects: Pick<FactoryProjectsStorage, 'listAll'>;
|
|
32
|
+
workItems: Pick<WorkItemsStorage, 'listShared'>;
|
|
33
|
+
});
|
|
34
|
+
/**
|
|
35
|
+
* Call once every replica's board changes reach {@link changed}. Until then
|
|
36
|
+
* nothing is kept and every read goes to storage.
|
|
37
|
+
*/
|
|
38
|
+
trustAnnouncements(): void;
|
|
39
|
+
/**
|
|
40
|
+
* A committed write changed this project's board, or deleted the project, on
|
|
41
|
+
* this replica or another. The project list is read again too: one query,
|
|
42
|
+
* only after activity, and it is how a new or deleted project shows up.
|
|
43
|
+
*/
|
|
44
|
+
changed(scope: BoardScope): void;
|
|
45
|
+
projects(): Promise<readonly FactoryProject[]>;
|
|
46
|
+
cards(scope: BoardScope): Promise<readonly Card[]>;
|
|
47
|
+
}
|
|
48
|
+
export {};
|
|
49
|
+
//# sourceMappingURL=kept-cards.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kept-cards.d.ts","sourceRoot":"","sources":["../../src/integrations/kept-cards.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAClG,OAAO,KAAK,EAAE,IAAI,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAEpF,UAAU,UAAU;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,gBAAgB,EAAE,MAAM,CAAC;CAC1B;AAED,6EAA6E;AAC7E,MAAM,WAAW,UAAU;IACzB,QAAQ,IAAI,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAAC;IAC/C,6CAA6C;IAC7C,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,IAAI,EAAE,CAAC,CAAC;CACpD;AAED,yFAAyF;AACzF,wBAAgB,YAAY,CAAC,OAAO,EAAE;IACpC,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAClD,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC;CACjD,GAAG,UAAU,CAKb;AAMD;;;;;;;;;GASG;AACH,qBAAa,SAAU,YAAW,UAAU;;IAa1C,YAAY,OAAO,EAAE;QACnB,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;QAClD,SAAS,EAAE,IAAI,CAAC,gBAAgB,EAAE,YAAY,CAAC,CAAC;KACjD,EAEA;IAED;;;OAGG;IACH,kBAAkB,IAAI,IAAI,CAEzB;IAED;;;;OAIG;IACH,OAAO,CAAC,KAAK,EAAE,UAAU,GAAG,IAAI,CAM/B;IAED,QAAQ,IAAI,OAAO,CAAC,SAAS,cAAc,EAAE,CAAC,CAO7C;IAEK,KAAK,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,IAAI,EAAE,CAAC,CAYvD;CAyBF"}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// src/integrations/kept-cards.ts
|
|
2
|
+
/** Reads storage on every call: what a sweep uses when no {@link KeptCards} is wired. */
|
|
3
|
+
function storageCards(options) {
|
|
4
|
+
return {
|
|
5
|
+
projects: () => options.projects.listAll(),
|
|
6
|
+
cards: (scope) => options.workItems.listShared(scope)
|
|
7
|
+
};
|
|
8
|
+
}
|
|
9
|
+
function scopeKey(scope) {
|
|
10
|
+
return `${scope.orgId}\u0000${scope.factoryProjectId}`;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Keeps the cards sweeps look at in memory, so a sweep that finds nothing to
|
|
14
|
+
* change at a provider reads nothing from storage. A board is read again only
|
|
15
|
+
* after a change to it was announced through {@link changed}. There is no timed
|
|
16
|
+
* re-read, since that would wake the database; an announcement lost between
|
|
17
|
+
* replicas stays unseen until that board changes again or the process restarts.
|
|
18
|
+
*
|
|
19
|
+
* The kept cards decide what a sweep looks at, not what it writes: a sweep
|
|
20
|
+
* about to write a card reads that card first.
|
|
21
|
+
*/
|
|
22
|
+
var KeptCards = class {
|
|
23
|
+
#storage;
|
|
24
|
+
#trusted = false;
|
|
25
|
+
#projects;
|
|
26
|
+
#known = /* @__PURE__ */ new Set();
|
|
27
|
+
/** Bumped by every change, since a change can mean a project was created or deleted. */
|
|
28
|
+
#projectChanges = 0;
|
|
29
|
+
#projectsLoading;
|
|
30
|
+
#cards = /* @__PURE__ */ new Map();
|
|
31
|
+
#boardChanges = /* @__PURE__ */ new Map();
|
|
32
|
+
#cardsLoading = /* @__PURE__ */ new Map();
|
|
33
|
+
constructor(options) {
|
|
34
|
+
this.#storage = storageCards(options);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Call once every replica's board changes reach {@link changed}. Until then
|
|
38
|
+
* nothing is kept and every read goes to storage.
|
|
39
|
+
*/
|
|
40
|
+
trustAnnouncements() {
|
|
41
|
+
this.#trusted = true;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A committed write changed this project's board, or deleted the project, on
|
|
45
|
+
* this replica or another. The project list is read again too: one query,
|
|
46
|
+
* only after activity, and it is how a new or deleted project shows up.
|
|
47
|
+
*/
|
|
48
|
+
changed(scope) {
|
|
49
|
+
const key = scopeKey(scope);
|
|
50
|
+
this.#cards.delete(key);
|
|
51
|
+
this.#boardChanges.set(key, (this.#boardChanges.get(key) ?? 0) + 1);
|
|
52
|
+
this.#projects = void 0;
|
|
53
|
+
this.#projectChanges += 1;
|
|
54
|
+
}
|
|
55
|
+
projects() {
|
|
56
|
+
if (this.#projects) return Promise.resolve(this.#projects);
|
|
57
|
+
this.#projectsLoading ??= this.#readProjects().finally(() => {
|
|
58
|
+
this.#projectsLoading = void 0;
|
|
59
|
+
});
|
|
60
|
+
return this.#projectsLoading;
|
|
61
|
+
}
|
|
62
|
+
async cards(scope) {
|
|
63
|
+
await this.projects();
|
|
64
|
+
const key = scopeKey(scope);
|
|
65
|
+
const kept = this.#cards.get(key);
|
|
66
|
+
if (kept) return kept;
|
|
67
|
+
let loading = this.#cardsLoading.get(key);
|
|
68
|
+
if (!loading) {
|
|
69
|
+
loading = this.#readCards(scope, key).finally(() => this.#cardsLoading.delete(key));
|
|
70
|
+
this.#cardsLoading.set(key, loading);
|
|
71
|
+
}
|
|
72
|
+
return loading;
|
|
73
|
+
}
|
|
74
|
+
async #readProjects() {
|
|
75
|
+
const changes = this.#projectChanges;
|
|
76
|
+
const projects = await this.#storage.projects();
|
|
77
|
+
if (this.#trusted && changes === this.#projectChanges) {
|
|
78
|
+
this.#projects = projects;
|
|
79
|
+
this.#known = new Set(projects.map((project) => scopeKey({
|
|
80
|
+
orgId: project.orgId,
|
|
81
|
+
factoryProjectId: project.id
|
|
82
|
+
})));
|
|
83
|
+
for (const key of this.#cards.keys()) if (!this.#known.has(key)) this.#cards.delete(key);
|
|
84
|
+
for (const key of this.#boardChanges.keys()) if (!this.#known.has(key)) this.#boardChanges.delete(key);
|
|
85
|
+
}
|
|
86
|
+
return projects;
|
|
87
|
+
}
|
|
88
|
+
async #readCards(scope, key) {
|
|
89
|
+
const changes = this.#boardChanges.get(key) ?? 0;
|
|
90
|
+
const cards = await this.#storage.cards(scope);
|
|
91
|
+
if (this.#trusted && this.#known.has(key) && changes === (this.#boardChanges.get(key) ?? 0)) this.#cards.set(key, cards);
|
|
92
|
+
return cards;
|
|
93
|
+
}
|
|
94
|
+
};
|
|
95
|
+
export { KeptCards, storageCards };
|
|
96
|
+
|
|
97
|
+
//# sourceMappingURL=kept-cards.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kept-cards.js","names":[],"sources":["../../src/integrations/kept-cards.ts"],"sourcesContent":["import type { FactoryProject, FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\ninterface BoardScope {\n orgId: string;\n factoryProjectId: string;\n}\n\n/** What a background sweep reads: the projects, and each project's cards. */\nexport interface CardSource {\n projects(): Promise<readonly FactoryProject[]>;\n /** Shared between readers: do not mutate. */\n cards(scope: BoardScope): Promise<readonly Card[]>;\n}\n\n/** Reads storage on every call: what a sweep uses when no {@link KeptCards} is wired. */\nexport function storageCards(options: {\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n workItems: Pick<WorkItemsStorage, 'listShared'>;\n}): CardSource {\n return {\n projects: () => options.projects.listAll(),\n cards: scope => options.workItems.listShared(scope),\n };\n}\n\nfunction scopeKey(scope: BoardScope): string {\n return `${scope.orgId}\\u0000${scope.factoryProjectId}`;\n}\n\n/**\n * Keeps the cards sweeps look at in memory, so a sweep that finds nothing to\n * change at a provider reads nothing from storage. A board is read again only\n * after a change to it was announced through {@link changed}. There is no timed\n * re-read, since that would wake the database; an announcement lost between\n * replicas stays unseen until that board changes again or the process restarts.\n *\n * The kept cards decide what a sweep looks at, not what it writes: a sweep\n * about to write a card reads that card first.\n */\nexport class KeptCards implements CardSource {\n readonly #storage: CardSource;\n\n #trusted = false;\n #projects: readonly FactoryProject[] | undefined;\n #known = new Set<string>();\n /** Bumped by every change, since a change can mean a project was created or deleted. */\n #projectChanges = 0;\n #projectsLoading: Promise<readonly FactoryProject[]> | undefined;\n readonly #cards = new Map<string, readonly Card[]>();\n readonly #boardChanges = new Map<string, number>();\n readonly #cardsLoading = new Map<string, Promise<readonly Card[]>>();\n\n constructor(options: {\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n workItems: Pick<WorkItemsStorage, 'listShared'>;\n }) {\n this.#storage = storageCards(options);\n }\n\n /**\n * Call once every replica's board changes reach {@link changed}. Until then\n * nothing is kept and every read goes to storage.\n */\n trustAnnouncements(): void {\n this.#trusted = true;\n }\n\n /**\n * A committed write changed this project's board, or deleted the project, on\n * this replica or another. The project list is read again too: one query,\n * only after activity, and it is how a new or deleted project shows up.\n */\n changed(scope: BoardScope): void {\n const key = scopeKey(scope);\n this.#cards.delete(key);\n this.#boardChanges.set(key, (this.#boardChanges.get(key) ?? 0) + 1);\n this.#projects = undefined;\n this.#projectChanges += 1;\n }\n\n projects(): Promise<readonly FactoryProject[]> {\n if (this.#projects) return Promise.resolve(this.#projects);\n // Sweeps of several integrations start together; they share one read.\n this.#projectsLoading ??= this.#readProjects().finally(() => {\n this.#projectsLoading = undefined;\n });\n return this.#projectsLoading;\n }\n\n async cards(scope: BoardScope): Promise<readonly Card[]> {\n // Only a listed project's cards are kept; the list is usually kept too.\n await this.projects();\n const key = scopeKey(scope);\n const kept = this.#cards.get(key);\n if (kept) return kept;\n let loading = this.#cardsLoading.get(key);\n if (!loading) {\n loading = this.#readCards(scope, key).finally(() => this.#cardsLoading.delete(key));\n this.#cardsLoading.set(key, loading);\n }\n return loading;\n }\n\n async #readProjects(): Promise<readonly FactoryProject[]> {\n const changes = this.#projectChanges;\n const projects = await this.#storage.projects();\n // A project announced during the read may be missing from it, so that read\n // is used for this pass only.\n if (this.#trusted && changes === this.#projectChanges) {\n this.#projects = projects;\n this.#known = new Set(projects.map(project => scopeKey({ orgId: project.orgId, factoryProjectId: project.id })));\n for (const key of this.#cards.keys()) if (!this.#known.has(key)) this.#cards.delete(key);\n for (const key of this.#boardChanges.keys()) if (!this.#known.has(key)) this.#boardChanges.delete(key);\n }\n return projects;\n }\n\n async #readCards(scope: BoardScope, key: string): Promise<readonly Card[]> {\n const changes = this.#boardChanges.get(key) ?? 0;\n const cards = await this.#storage.cards(scope);\n // Kept only for a listed project, so a deleted project's cards are not.\n if (this.#trusted && this.#known.has(key) && changes === (this.#boardChanges.get(key) ?? 0)) {\n this.#cards.set(key, cards);\n }\n return cards;\n }\n}\n"],"mappings":";;AAgBA,SAAgB,aAAa,SAGd;CACb,OAAO;EACL,gBAAgB,QAAQ,SAAS,QAAQ;EACzC,QAAO,UAAS,QAAQ,UAAU,WAAW,KAAK;CACpD;AACF;AAEA,SAAS,SAAS,OAA2B;CAC3C,OAAO,GAAG,MAAM,MAAM,QAAQ,MAAM;AACtC;;;;;;;;;;;AAYA,IAAa,YAAb,MAA6C;CAC3C;CAEA,WAAW;CACX;CACA,yBAAS,IAAI,IAAY;;CAEzB,kBAAkB;CAClB;CACA,yBAAkB,IAAI,IAA6B;CACnD,gCAAyB,IAAI,IAAoB;CACjD,gCAAyB,IAAI,I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AAO,GAAG;GACvF,KAAK,MAAM,OAAO,KAAK,cAAc,KAAK,GAAG,IAAI,CAAC,KAAK,OAAO,IAAI,GAAG,GAAG,KAAK,cAAc,OAAO,GAAG;EACvG;EACA,OAAO;CACT;CAEA,MAAM,WAAW,OAAmB,KAAuC;EACzE,MAAM,UAAU,KAAK,cAAc,IAAI,GAAG,KAAK;EAC/C,MAAM,QAAQ,MAAM,KAAK,SAAS,MAAM,KAAK;EAE7C,IAAI,KAAK,YAAY,KAAK,OAAO,IAAI,GAAG,KAAK,aAAa,KAAK,cAAc,IAAI,GAAG,KAAK,IACvF,KAAK,OAAO,IAAI,KAAK,KAAK;EAE5B,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { IntakeIssue } from '../../capabilities/intake.js';
|
|
2
|
+
import type { IntakeStorage } from '../../storage/domains/intake/base.js';
|
|
3
|
+
import type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';
|
|
4
|
+
import type { LinearIntegration } from './integration.js';
|
|
5
|
+
import type { LinearIssueIngress, LinearRules } from './rules.js';
|
|
6
|
+
/**
|
|
7
|
+
* Listing calls made per project each run. A call answers up to 30 of the most
|
|
8
|
+
* recently updated active issues per stream: one stream for the bound Linear
|
|
9
|
+
* projects and one for the bound teams, or one per bound source on Platform.
|
|
10
|
+
*/
|
|
11
|
+
export declare const LINEAR_INTAKE_DISCOVERY_MAX_PAGES = 5;
|
|
12
|
+
export interface LinearIntakeDiscoverySummary {
|
|
13
|
+
/** Issues handed to the Linear rules (new and already carded). */
|
|
14
|
+
observed: number;
|
|
15
|
+
failed: number;
|
|
16
|
+
errors: Array<{
|
|
17
|
+
projectId: string;
|
|
18
|
+
error: string;
|
|
19
|
+
}>;
|
|
20
|
+
}
|
|
21
|
+
export interface LinearIntakeDiscoveryOptions {
|
|
22
|
+
linear: Pick<LinearIntegration, 'intake' | 'loadConnection' | 'getFreshAccessToken'>;
|
|
23
|
+
intake: Pick<IntakeStorage, 'ensureReady' | 'getConfig' | 'listBindings'>;
|
|
24
|
+
projects: Pick<FactoryProjectsStorage, 'listAll'>;
|
|
25
|
+
rules: Pick<LinearRules, 'ingest'>;
|
|
26
|
+
}
|
|
27
|
+
export declare function issueToIngress(issue: IntakeIssue): LinearIssueIngress;
|
|
28
|
+
/**
|
|
29
|
+
* Feeds every project's bound Linear sources through the Linear rules, so a new
|
|
30
|
+
* issue gets its card (and custom `issueObserved` rules see updates) without a
|
|
31
|
+
* board open. Lists exactly what the board's issue list shows for the project.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createLinearIntakeDiscovery(options: LinearIntakeDiscoveryOptions): () => Promise<LinearIntakeDiscoverySummary>;
|
|
34
|
+
//# sourceMappingURL=intake-discovery.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake-discovery.d.ts","sourceRoot":"","sources":["../../../src/integrations/linear/intake-discovery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sCAAsC,CAAC;AAC1E,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAElE;;;;GAIG;AACH,eAAO,MAAM,iCAAiC,IAAI,CAAC;AAEnD,MAAM,WAAW,4BAA4B;IAC3C,kEAAkE;IAClE,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,KAAK,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACrD;AAED,MAAM,WAAW,4BAA4B;IAC3C,MAAM,EAAE,IAAI,CAAC,iBAAiB,EAAE,QAAQ,GAAG,gBAAgB,GAAG,qBAAqB,CAAC,CAAC;IACrF,MAAM,EAAE,IAAI,CAAC,aAAa,EAAE,aAAa,GAAG,WAAW,GAAG,cAAc,CAAC,CAAC;IAC1E,QAAQ,EAAE,IAAI,CAAC,sBAAsB,EAAE,SAAS,CAAC,CAAC;IAClD,KAAK,EAAE,IAAI,CAAC,WAAW,EAAE,QAAQ,CAAC,CAAC;CACpC;AAED,wBAAgB,cAAc,CAAC,KAAK,EAAE,WAAW,GAAG,kBAAkB,CAkBrE;AAMD;;;;GAIG;AACH,wBAAgB,2BAA2B,CAAC,OAAO,EAAE,4BAA4B,SAG7C,OAAO,CAAC,4BAA4B,CAAC,CAiExE"}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// src/integrations/linear/intake-discovery.ts
|
|
2
|
+
/**
|
|
3
|
+
* Listing calls made per project each run. A call answers up to 30 of the most
|
|
4
|
+
* recently updated active issues per stream: one stream for the bound Linear
|
|
5
|
+
* projects and one for the bound teams, or one per bound source on Platform.
|
|
6
|
+
*/
|
|
7
|
+
const LINEAR_INTAKE_DISCOVERY_MAX_PAGES = 5;
|
|
8
|
+
function issueToIngress(issue) {
|
|
9
|
+
return {
|
|
10
|
+
id: issue.id,
|
|
11
|
+
identifier: issue.identifier,
|
|
12
|
+
title: issue.title,
|
|
13
|
+
url: issue.url,
|
|
14
|
+
state: issue.state ?? "",
|
|
15
|
+
stateType: issue.stateType ?? "",
|
|
16
|
+
priorityLabel: issue.priority ?? "",
|
|
17
|
+
assignee: issue.assignee ?? null,
|
|
18
|
+
creator: issue.author ?? null,
|
|
19
|
+
team: issue.source ?? null,
|
|
20
|
+
labels: [...issue.labels ?? []],
|
|
21
|
+
createdAt: issue.createdAt,
|
|
22
|
+
updatedAt: issue.updatedAt,
|
|
23
|
+
sourceId: issue.sourceId ?? null,
|
|
24
|
+
projectId: issue.projectId ?? null
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
function errorMessage(error) {
|
|
28
|
+
return error instanceof Error ? error.message : String(error);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Feeds every project's bound Linear sources through the Linear rules, so a new
|
|
32
|
+
* issue gets its card (and custom `issueObserved` rules see updates) without a
|
|
33
|
+
* board open. Lists exactly what the board's issue list shows for the project.
|
|
34
|
+
*/
|
|
35
|
+
function createLinearIntakeDiscovery(options) {
|
|
36
|
+
const { linear, intake, rules } = options;
|
|
37
|
+
return async function discover() {
|
|
38
|
+
const summary = {
|
|
39
|
+
observed: 0,
|
|
40
|
+
failed: 0,
|
|
41
|
+
errors: []
|
|
42
|
+
};
|
|
43
|
+
const projectsByOrg = /* @__PURE__ */ new Map();
|
|
44
|
+
for (const project of await options.projects.listAll()) projectsByOrg.set(project.orgId, [...projectsByOrg.get(project.orgId) ?? [], project.id]);
|
|
45
|
+
for (const [orgId, projectIds] of projectsByOrg) {
|
|
46
|
+
let bound;
|
|
47
|
+
let selectedIds;
|
|
48
|
+
let accessToken;
|
|
49
|
+
try {
|
|
50
|
+
await intake.ensureReady();
|
|
51
|
+
const selection = (await intake.getConfig({
|
|
52
|
+
orgId,
|
|
53
|
+
integrationIds: ["linear"]
|
|
54
|
+
})).linear;
|
|
55
|
+
selectedIds = selection?.enabled ? selection.sourceIds ?? [] : [];
|
|
56
|
+
if (selectedIds.length === 0) continue;
|
|
57
|
+
const bindings = await intake.listBindings({
|
|
58
|
+
orgId,
|
|
59
|
+
integrationId: "linear"
|
|
60
|
+
});
|
|
61
|
+
bound = projectIds.map((id) => [id, bindings.filter((binding) => binding.factoryProjectId === id && selectedIds.includes(binding.sourceId)).map((binding) => binding.sourceId)]).filter(([, sourceIds]) => sourceIds.length > 0);
|
|
62
|
+
if (bound.length === 0) continue;
|
|
63
|
+
const connection = await linear.loadConnection(orgId);
|
|
64
|
+
if (!connection) continue;
|
|
65
|
+
accessToken = await linear.getFreshAccessToken(connection);
|
|
66
|
+
} catch (error) {
|
|
67
|
+
summary.failed += 1;
|
|
68
|
+
summary.errors.push({
|
|
69
|
+
projectId: `org:${orgId}`,
|
|
70
|
+
error: errorMessage(error)
|
|
71
|
+
});
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
for (const [factoryProjectId, sourceIds] of bound) try {
|
|
75
|
+
const issues = [];
|
|
76
|
+
let cursor;
|
|
77
|
+
for (let page = 0; page < 5; page += 1) {
|
|
78
|
+
const result = await linear.intake.listIssues({
|
|
79
|
+
connection: {
|
|
80
|
+
type: "oauth",
|
|
81
|
+
accessToken
|
|
82
|
+
},
|
|
83
|
+
sourceIds,
|
|
84
|
+
attributionSourceIds: selectedIds,
|
|
85
|
+
cursor
|
|
86
|
+
});
|
|
87
|
+
for (const issue of result.issues) if (issue.sourceId != null && sourceIds.includes(issue.sourceId)) issues.push(issueToIngress(issue));
|
|
88
|
+
if (!result.nextCursor) break;
|
|
89
|
+
cursor = result.nextCursor;
|
|
90
|
+
}
|
|
91
|
+
if (issues.length === 0) continue;
|
|
92
|
+
await rules.ingest({
|
|
93
|
+
orgId,
|
|
94
|
+
userId: "factory-rule-dispatcher",
|
|
95
|
+
factoryProjectId,
|
|
96
|
+
issues
|
|
97
|
+
});
|
|
98
|
+
summary.observed += issues.length;
|
|
99
|
+
} catch (error) {
|
|
100
|
+
summary.failed += 1;
|
|
101
|
+
summary.errors.push({
|
|
102
|
+
projectId: factoryProjectId,
|
|
103
|
+
error: errorMessage(error)
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return summary;
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
export { LINEAR_INTAKE_DISCOVERY_MAX_PAGES, createLinearIntakeDiscovery, issueToIngress };
|
|
111
|
+
|
|
112
|
+
//# sourceMappingURL=intake-discovery.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"intake-discovery.js","names":[],"sources":["../../../src/integrations/linear/intake-discovery.ts"],"sourcesContent":["import type { IntakeIssue } from '../../capabilities/intake.js';\nimport type { IntakeStorage } from '../../storage/domains/intake/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { LinearIntegration } from './integration.js';\nimport type { LinearIssueIngress, LinearRules } from './rules.js';\n\n/**\n * Listing calls made per project each run. A call answers up to 30 of the most\n * recently updated active issues per stream: one stream for the bound Linear\n * projects and one for the bound teams, or one per bound source on Platform.\n */\nexport const LINEAR_INTAKE_DISCOVERY_MAX_PAGES = 5;\n\nexport interface LinearIntakeDiscoverySummary {\n /** Issues handed to the Linear rules (new and already carded). */\n observed: number;\n failed: number;\n errors: Array<{ projectId: string; error: string }>;\n}\n\nexport interface LinearIntakeDiscoveryOptions {\n linear: Pick<LinearIntegration, 'intake' | 'loadConnection' | 'getFreshAccessToken'>;\n intake: Pick<IntakeStorage, 'ensureReady' | 'getConfig' | 'listBindings'>;\n projects: Pick<FactoryProjectsStorage, 'listAll'>;\n rules: Pick<LinearRules, 'ingest'>;\n}\n\nexport function issueToIngress(issue: IntakeIssue): LinearIssueIngress {\n return {\n id: issue.id,\n identifier: issue.identifier,\n title: issue.title,\n url: issue.url,\n state: issue.state ?? '',\n stateType: issue.stateType ?? '',\n priorityLabel: issue.priority ?? '',\n assignee: issue.assignee ?? null,\n creator: issue.author ?? null,\n team: issue.source ?? null,\n labels: [...(issue.labels ?? [])],\n createdAt: issue.createdAt,\n updatedAt: issue.updatedAt,\n sourceId: issue.sourceId ?? null,\n projectId: issue.projectId ?? null,\n };\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Feeds every project's bound Linear sources through the Linear rules, so a new\n * issue gets its card (and custom `issueObserved` rules see updates) without a\n * board open. Lists exactly what the board's issue list shows for the project.\n */\nexport function createLinearIntakeDiscovery(options: LinearIntakeDiscoveryOptions) {\n const { linear, intake, rules } = options;\n\n return async function discover(): Promise<LinearIntakeDiscoverySummary> {\n const summary: LinearIntakeDiscoverySummary = { observed: 0, failed: 0, errors: [] };\n const projectsByOrg = new Map<string, string[]>();\n for (const project of await options.projects.listAll()) {\n projectsByOrg.set(project.orgId, [...(projectsByOrg.get(project.orgId) ?? []), project.id]);\n }\n\n for (const [orgId, projectIds] of projectsByOrg) {\n let bound: Array<[string, string[]]>;\n let selectedIds: string[];\n let accessToken: string;\n try {\n await intake.ensureReady();\n const selection = (await intake.getConfig({ orgId, integrationIds: ['linear'] })).linear;\n selectedIds = selection?.enabled ? (selection.sourceIds ?? []) : [];\n if (selectedIds.length === 0) continue;\n const bindings = await intake.listBindings({ orgId, integrationId: 'linear' });\n bound = projectIds\n .map((id): [string, string[]] => [\n id,\n bindings\n .filter(binding => binding.factoryProjectId === id && selectedIds.includes(binding.sourceId))\n .map(binding => binding.sourceId),\n ])\n .filter(([, sourceIds]) => sourceIds.length > 0);\n if (bound.length === 0) continue;\n const connection = await linear.loadConnection(orgId);\n if (!connection) continue;\n accessToken = await linear.getFreshAccessToken(connection);\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({ projectId: `org:${orgId}`, error: errorMessage(error) });\n continue;\n }\n\n for (const [factoryProjectId, sourceIds] of bound) {\n try {\n const issues: LinearIssueIngress[] = [];\n let cursor: string | undefined;\n for (let page = 0; page < LINEAR_INTAKE_DISCOVERY_MAX_PAGES; page += 1) {\n const result = await linear.intake.listIssues({\n connection: { type: 'oauth', accessToken },\n sourceIds,\n // Precedence (project beats team) is resolved against the whole selection.\n attributionSourceIds: selectedIds,\n cursor,\n });\n for (const issue of result.issues) {\n if (issue.sourceId != null && sourceIds.includes(issue.sourceId)) issues.push(issueToIngress(issue));\n }\n if (!result.nextCursor) break;\n cursor = result.nextCursor;\n }\n if (issues.length === 0) continue;\n await rules.ingest({ orgId, userId: 'factory-rule-dispatcher', factoryProjectId, issues });\n summary.observed += issues.length;\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({ projectId: factoryProjectId, error: errorMessage(error) });\n }\n }\n }\n\n return summary;\n };\n}\n"],"mappings":";;;;;;AAWA,MAAa,oCAAoC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